@tscircuit/eval 0.0.470 → 0.0.471

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- var Ipt=Object.create;var Px=Object.defineProperty;var Npt=Object.getOwnPropertyDescriptor;var Apt=Object.getOwnPropertyNames;var Rpt=Object.getPrototypeOf,Opt=Object.prototype.hasOwnProperty;var Lpt=(n,e,t)=>e in n?Px(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var Zy=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var qt=(n,e)=>()=>(n&&(e=n(n=0)),e);var ue=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),xh=(n,e)=>{for(var t in e)Px(n,t,{get:e[t],enumerable:!0})},Fpt=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Apt(e))!Opt.call(n,r)&&r!==t&&Px(n,r,{get:()=>e[r],enumerable:!(i=Npt(e,r))||i.enumerable});return n};var Ht=(n,e,t)=>(t=n!=null?Ipt(Rpt(n)):{},Fpt(e||!n||!n.__esModule?Px(t,"default",{value:n,enumerable:!0}):t,n));var d=(n,e,t)=>Lpt(n,typeof e!="symbol"?e+"":e,t);var gD=ue(Me=>{"use strict";var I3=Symbol.for("react.transitional.element"),Kpt=Symbol.for("react.portal"),Jpt=Symbol.for("react.fragment"),Qpt=Symbol.for("react.strict_mode"),tht=Symbol.for("react.profiler"),eht=Symbol.for("react.consumer"),nht=Symbol.for("react.context"),iht=Symbol.for("react.forward_ref"),rht=Symbol.for("react.suspense"),sht=Symbol.for("react.memo"),hD=Symbol.for("react.lazy"),oht=Symbol.for("react.activity"),cD=Symbol.iterator;function aht(n){return n===null||typeof n!="object"?null:(n=cD&&n[cD]||n["@@iterator"],typeof n=="function"?n:null)}var dD={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},fD=Object.assign,mD={};function xm(n,e,t){this.props=n,this.context=e,this.refs=mD,this.updater=t||dD}xm.prototype.isReactComponent={};xm.prototype.setState=function(n,e){if(typeof n!="object"&&typeof n!="function"&&n!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,n,e,"setState")};xm.prototype.forceUpdate=function(n){this.updater.enqueueForceUpdate(this,n,"forceUpdate")};function _D(){}_D.prototype=xm.prototype;function N3(n,e,t){this.props=n,this.context=e,this.refs=mD,this.updater=t||dD}var A3=N3.prototype=new _D;A3.constructor=N3;fD(A3,xm.prototype);A3.isPureReactComponent=!0;var lD=Array.isArray;function C3(){}var zn={H:null,A:null,T:null,S:null},yD=Object.prototype.hasOwnProperty;function R3(n,e,t){var i=t.ref;return{$$typeof:I3,type:n,key:e,ref:i!==void 0?i:null,props:t}}function cht(n,e){return R3(n.type,e,n.props)}function O3(n){return typeof n=="object"&&n!==null&&n.$$typeof===I3}function lht(n){var e={"=":"=0",":":"=2"};return"$"+n.replace(/[=:]/g,function(t){return e[t]})}var uD=/\/+/g;function M3(n,e){return typeof n=="object"&&n!==null&&n.key!=null?lht(""+n.key):e.toString(36)}function uht(n){switch(n.status){case"fulfilled":return n.value;case"rejected":throw n.reason;default:switch(typeof n.status=="string"?n.then(C3,C3):(n.status="pending",n.then(function(e){n.status==="pending"&&(n.status="fulfilled",n.value=e)},function(e){n.status==="pending"&&(n.status="rejected",n.reason=e)})),n.status){case"fulfilled":return n.value;case"rejected":throw n.reason}}throw n}function gm(n,e,t,i,r){var s=typeof n;(s==="undefined"||s==="boolean")&&(n=null);var o=!1;if(n===null)o=!0;else switch(s){case"bigint":case"string":case"number":o=!0;break;case"object":switch(n.$$typeof){case I3:case Kpt:o=!0;break;case hD:return o=n._init,gm(o(n._payload),e,t,i,r)}}if(o)return r=r(n),o=i===""?"."+M3(n,0):i,lD(r)?(t="",o!=null&&(t=o.replace(uD,"$&/")+"/"),gm(r,e,t,"",function(l){return l})):r!=null&&(O3(r)&&(r=cht(r,t+(r.key==null||n&&n.key===r.key?"":(""+r.key).replace(uD,"$&/")+"/")+o)),e.push(r)),1;o=0;var a=i===""?".":i+":";if(lD(n))for(var c=0;c<n.length;c++)i=n[c],s=a+M3(i,c),o+=gm(i,e,t,s,r);else if(c=aht(n),typeof c=="function")for(n=c.call(n),c=0;!(i=n.next()).done;)i=i.value,s=a+M3(i,c++),o+=gm(i,e,t,s,r);else if(s==="object"){if(typeof n.then=="function")return gm(uht(n),e,t,i,r);throw e=String(n),Error("Objects are not valid as a React child (found: "+(e==="[object Object]"?"object with keys {"+Object.keys(n).join(", ")+"}":e)+"). If you meant to render a collection of children, use an array instead.")}return o}function Nx(n,e,t){if(n==null)return n;var i=[],r=0;return gm(n,i,"","",function(s){return e.call(t,s,r++)}),i}function pht(n){if(n._status===-1){var e=n._result;e=e(),e.then(function(t){(n._status===0||n._status===-1)&&(n._status=1,n._result=t)},function(t){(n._status===0||n._status===-1)&&(n._status=2,n._result=t)}),n._status===-1&&(n._status=0,n._result=e)}if(n._status===1)return n._result.default;throw n._result}var pD=typeof reportError=="function"?reportError:function(n){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var e=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof n=="object"&&n!==null&&typeof n.message=="string"?String(n.message):String(n),error:n});if(!window.dispatchEvent(e))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",n);return}console.error(n)},hht={map:Nx,forEach:function(n,e,t){Nx(n,function(){e.apply(this,arguments)},t)},count:function(n){var e=0;return Nx(n,function(){e++}),e},toArray:function(n){return Nx(n,function(e){return e})||[]},only:function(n){if(!O3(n))throw Error("React.Children.only expected to receive a single React element child.");return n}};Me.Activity=oht;Me.Children=hht;Me.Component=xm;Me.Fragment=Jpt;Me.Profiler=tht;Me.PureComponent=N3;Me.StrictMode=Qpt;Me.Suspense=rht;Me.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=zn;Me.__COMPILER_RUNTIME={__proto__:null,c:function(n){return zn.H.useMemoCache(n)}};Me.cache=function(n){return function(){return n.apply(null,arguments)}};Me.cacheSignal=function(){return null};Me.cloneElement=function(n,e,t){if(n==null)throw Error("The argument must be a React element, but you passed "+n+".");var i=fD({},n.props),r=n.key;if(e!=null)for(s in e.key!==void 0&&(r=""+e.key),e)!yD.call(e,s)||s==="key"||s==="__self"||s==="__source"||s==="ref"&&e.ref===void 0||(i[s]=e[s]);var s=arguments.length-2;if(s===1)i.children=t;else if(1<s){for(var o=Array(s),a=0;a<s;a++)o[a]=arguments[a+2];i.children=o}return R3(n.type,r,i)};Me.createContext=function(n){return n={$$typeof:nht,_currentValue:n,_currentValue2:n,_threadCount:0,Provider:null,Consumer:null},n.Provider=n,n.Consumer={$$typeof:eht,_context:n},n};Me.createElement=function(n,e,t){var i,r={},s=null;if(e!=null)for(i in e.key!==void 0&&(s=""+e.key),e)yD.call(e,i)&&i!=="key"&&i!=="__self"&&i!=="__source"&&(r[i]=e[i]);var o=arguments.length-2;if(o===1)r.children=t;else if(1<o){for(var a=Array(o),c=0;c<o;c++)a[c]=arguments[c+2];r.children=a}if(n&&n.defaultProps)for(i in o=n.defaultProps,o)r[i]===void 0&&(r[i]=o[i]);return R3(n,s,r)};Me.createRef=function(){return{current:null}};Me.forwardRef=function(n){return{$$typeof:iht,render:n}};Me.isValidElement=O3;Me.lazy=function(n){return{$$typeof:hD,_payload:{_status:-1,_result:n},_init:pht}};Me.memo=function(n,e){return{$$typeof:sht,type:n,compare:e===void 0?null:e}};Me.startTransition=function(n){var e=zn.T,t={};zn.T=t;try{var i=n(),r=zn.S;r!==null&&r(t,i),typeof i=="object"&&i!==null&&typeof i.then=="function"&&i.then(C3,pD)}catch(s){pD(s)}finally{e!==null&&t.types!==null&&(e.types=t.types),zn.T=e}};Me.unstable_useCacheRefresh=function(){return zn.H.useCacheRefresh()};Me.use=function(n){return zn.H.use(n)};Me.useActionState=function(n,e,t){return zn.H.useActionState(n,e,t)};Me.useCallback=function(n,e){return zn.H.useCallback(n,e)};Me.useContext=function(n){return zn.H.useContext(n)};Me.useDebugValue=function(){};Me.useDeferredValue=function(n,e){return zn.H.useDeferredValue(n,e)};Me.useEffect=function(n,e){return zn.H.useEffect(n,e)};Me.useEffectEvent=function(n){return zn.H.useEffectEvent(n)};Me.useId=function(){return zn.H.useId()};Me.useImperativeHandle=function(n,e,t){return zn.H.useImperativeHandle(n,e,t)};Me.useInsertionEffect=function(n,e){return zn.H.useInsertionEffect(n,e)};Me.useLayoutEffect=function(n,e){return zn.H.useLayoutEffect(n,e)};Me.useMemo=function(n,e){return zn.H.useMemo(n,e)};Me.useOptimistic=function(n,e){return zn.H.useOptimistic(n,e)};Me.useReducer=function(n,e,t){return zn.H.useReducer(n,e,t)};Me.useRef=function(n){return zn.H.useRef(n)};Me.useState=function(n){return zn.H.useState(n)};Me.useSyncExternalStore=function(n,e,t){return zn.H.useSyncExternalStore(n,e,t)};Me.useTransition=function(){return zn.H.useTransition()};Me.version="19.2.0"});var Hs=ue((EYt,xD)=>{"use strict";xD.exports=gD()});var Ve,L3,Gt,Eo,Ky=qt(()=>{"use strict";(function(n){n.assertEqual=r=>{};function e(r){}n.assertIs=e;function t(r){throw new Error}n.assertNever=t,n.arrayToEnum=r=>{let s={};for(let o of r)s[o]=o;return s},n.getValidEnumValues=r=>{let s=n.objectKeys(r).filter(a=>typeof r[r[a]]!="number"),o={};for(let a of s)o[a]=r[a];return n.objectValues(o)},n.objectValues=r=>n.objectKeys(r).map(function(s){return r[s]}),n.objectKeys=typeof Object.keys=="function"?r=>Object.keys(r):r=>{let s=[];for(let o in r)Object.prototype.hasOwnProperty.call(r,o)&&s.push(o);return s},n.find=(r,s)=>{for(let o of r)if(s(o))return o},n.isInteger=typeof Number.isInteger=="function"?r=>Number.isInteger(r):r=>typeof r=="number"&&Number.isFinite(r)&&Math.floor(r)===r;function i(r,s=" | "){return r.map(o=>typeof o=="string"?`'${o}'`:o).join(s)}n.joinValues=i,n.jsonStringifyReplacer=(r,s)=>typeof s=="bigint"?s.toString():s})(Ve||(Ve={}));(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(L3||(L3={}));Gt=Ve.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Eo=n=>{switch(typeof n){case"undefined":return Gt.undefined;case"string":return Gt.string;case"number":return Number.isNaN(n)?Gt.nan:Gt.number;case"boolean":return Gt.boolean;case"function":return Gt.function;case"bigint":return Gt.bigint;case"symbol":return Gt.symbol;case"object":return Array.isArray(n)?Gt.array:n===null?Gt.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?Gt.promise:typeof Map<"u"&&n instanceof Map?Gt.map:typeof Set<"u"&&n instanceof Set?Gt.set:typeof Date<"u"&&n instanceof Date?Gt.date:Gt.object;default:return Gt.unknown}}});var Nt,dht,Lr,Ax=qt(()=>{"use strict";Ky();Nt=Ve.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"]),dht=n=>JSON.stringify(n,null,2).replace(/"([^"]+)":/g,"$1:"),Lr=class n extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=i=>{this.issues=[...this.issues,i]},this.addIssues=(i=[])=>{this.issues=[...this.issues,...i]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(s){return s.message},i={_errors:[]},r=s=>{for(let o of s.issues)if(o.code==="invalid_union")o.unionErrors.map(r);else if(o.code==="invalid_return_type")r(o.returnTypeError);else if(o.code==="invalid_arguments")r(o.argumentsError);else if(o.path.length===0)i._errors.push(t(o));else{let a=i,c=0;for(;c<o.path.length;){let l=o.path[c];c===o.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(t(o))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return r(this),i}static assert(e){if(!(e instanceof n))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Ve.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},i=[];for(let r of this.issues)if(r.path.length>0){let s=r.path[0];t[s]=t[s]||[],t[s].push(e(r))}else i.push(e(r));return{formErrors:i,fieldErrors:t}}get formErrors(){return this.flatten()}};Lr.create=n=>new Lr(n)});var fht,ma,F3=qt(()=>{"use strict";Ax();Ky();fht=(n,e)=>{let t;switch(n.code){case Nt.invalid_type:n.received===Gt.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case Nt.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,Ve.jsonStringifyReplacer)}`;break;case Nt.unrecognized_keys:t=`Unrecognized key(s) in object: ${Ve.joinValues(n.keys,", ")}`;break;case Nt.invalid_union:t="Invalid input";break;case Nt.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${Ve.joinValues(n.options)}`;break;case Nt.invalid_enum_value:t=`Invalid enum value. Expected ${Ve.joinValues(n.options)}, received '${n.received}'`;break;case Nt.invalid_arguments:t="Invalid function arguments";break;case Nt.invalid_return_type:t="Invalid function return type";break;case Nt.invalid_date:t="Invalid date";break;case Nt.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:Ve.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case Nt.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case Nt.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case Nt.custom:t="Invalid input";break;case Nt.invalid_intersection_types:t="Intersection results could not be merged";break;case Nt.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case Nt.not_finite:t="Number must be finite";break;default:t=e.defaultError,Ve.assertNever(n)}return{message:t}},ma=fht});function mht(n){bD=n}function bm(){return bD}var bD,Rx=qt(()=>{"use strict";F3();bD=ma});function Bt(n,e){let t=bm(),i=Jy({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===ma?void 0:ma].filter(r=>!!r)});n.common.issues.push(i)}var Jy,_ht,Ki,ye,vh,lr,Ox,Lx,Ac,vm,z3=qt(()=>{"use strict";Rx();F3();Jy=n=>{let{data:e,path:t,errorMaps:i,issueData:r}=n,s=[...t,...r.path||[]],o={...r,path:s};if(r.message!==void 0)return{...r,path:s,message:r.message};let a="",c=i.filter(l=>!!l).slice().reverse();for(let l of c)a=l(o,{data:e,defaultError:a}).message;return{...r,path:s,message:a}},_ht=[];Ki=class n{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let i=[];for(let r of t){if(r.status==="aborted")return ye;r.status==="dirty"&&e.dirty(),i.push(r.value)}return{status:e.value,value:i}}static async mergeObjectAsync(e,t){let i=[];for(let r of t){let s=await r.key,o=await r.value;i.push({key:s,value:o})}return n.mergeObjectSync(e,i)}static mergeObjectSync(e,t){let i={};for(let r of t){let{key:s,value:o}=r;if(s.status==="aborted"||o.status==="aborted")return ye;s.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof o.value<"u"||r.alwaysSet)&&(i[s.value]=o.value)}return{status:e.value,value:i}}},ye=Object.freeze({status:"aborted"}),vh=n=>({status:"dirty",value:n}),lr=n=>({status:"valid",value:n}),Ox=n=>n.status==="aborted",Lx=n=>n.status==="dirty",Ac=n=>n.status==="valid",vm=n=>typeof Promise<"u"&&n instanceof Promise});var vD=qt(()=>{"use strict"});var se,wD=qt(()=>{"use strict";(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e?.message})(se||(se={}))});function Ie(n){if(!n)return{};let{errorMap:e,invalid_type_error:t,required_error:i,description:r}=n;if(e&&(t||i))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:r}:{errorMap:(o,a)=>{let{message:c}=n;return o.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??i??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:c??t??a.defaultError}},description:r}}function TD(n){let e="[0-5]\\d";n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`);let t=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function Rht(n){return new RegExp(`^${TD(n)}$`)}function ED(n){let e=`${kD}T${TD(n)}`,t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Oht(n,e){return!!((e==="v4"||!e)&&Tht.test(n)||(e==="v6"||!e)&&Mht.test(n))}function Lht(n,e){if(!wht.test(n))return!1;try{let[t]=n.split(".");if(!t)return!1;let i=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),r=JSON.parse(atob(i));return!(typeof r!="object"||r===null||"typ"in r&&r?.typ!=="JWT"||!r.alg||e&&r.alg!==e)}catch{return!1}}function Fht(n,e){return!!((e==="v4"||!e)&&Eht.test(n)||(e==="v6"||!e)&&Cht.test(n))}function zht(n,e){let t=(n.toString().split(".")[1]||"").length,i=(e.toString().split(".")[1]||"").length,r=t>i?t:i,s=Number.parseInt(n.toFixed(r).replace(".","")),o=Number.parseInt(e.toFixed(r).replace(".",""));return s%o/10**r}function wm(n){if(n instanceof Fr){let e={};for(let t in n.shape){let i=n.shape[t];e[t]=ws.create(wm(i))}return new Fr({...n._def,shape:()=>e})}else return n instanceof ga?new ga({...n._def,type:wm(n.element)}):n instanceof ws?ws.create(wm(n.unwrap())):n instanceof Co?Co.create(wm(n.unwrap())):n instanceof Mo?Mo.create(n.items.map(e=>wm(e))):n}function $3(n,e){let t=Eo(n),i=Eo(e);if(n===e)return{valid:!0,data:n};if(t===Gt.object&&i===Gt.object){let r=Ve.objectKeys(e),s=Ve.objectKeys(n).filter(a=>r.indexOf(a)!==-1),o={...n,...e};for(let a of s){let c=$3(n[a],e[a]);if(!c.valid)return{valid:!1};o[a]=c.data}return{valid:!0,data:o}}else if(t===Gt.array&&i===Gt.array){if(n.length!==e.length)return{valid:!1};let r=[];for(let s=0;s<n.length;s++){let o=n[s],a=e[s],c=$3(o,a);if(!c.valid)return{valid:!1};r.push(c.data)}return{valid:!0,data:r}}else return t===Gt.date&&i===Gt.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}function MD(n,e){return new Ah({values:n,typeName:we.ZodEnum,...Ie(e)})}function PD(n,e){let t=typeof n=="function"?n(e):typeof n=="string"?{message:n}:n;return typeof t=="string"?{message:t}:t}function CD(n,e={},t){return n?Oc.create().superRefine((i,r)=>{let s=n(i);if(s instanceof Promise)return s.then(o=>{if(!o){let a=PD(e,i),c=a.fatal??t??!0;r.addIssue({code:"custom",...a,fatal:c})}});if(!s){let o=PD(e,i),a=o.fatal??t??!0;r.addIssue({code:"custom",...o,fatal:a})}}):Oc.create()}var Ss,SD,Fe,yht,ght,xht,bht,vht,wht,Sht,Pht,kht,D3,Tht,Eht,Mht,Cht,Iht,Nht,kD,Aht,Rc,wh,Sh,Ph,kh,Sm,Th,Eh,Oc,ya,Ws,Pm,ga,Fr,Mh,_a,Fx,Ch,Mo,zx,km,Tm,Dx,Ih,Nh,Ah,Rh,Lc,Ps,ws,Co,Oh,Lh,Em,Dht,Qy,tg,Fh,$ht,we,jht,ID,ND,Bht,Yht,AD,Xht,Uht,Vht,Ght,Hht,Wht,qht,Zht,Kht,Jht,Qht,tdt,edt,ndt,idt,rdt,sdt,odt,adt,cdt,ldt,udt,pdt,hdt,ddt,fdt,mdt,_dt,ydt,gdt,xdt,bdt,vdt,wdt,RD=qt(()=>{"use strict";Ax();Rx();wD();z3();Ky();Ss=class{constructor(e,t,i,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=i,this._key=r}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}},SD=(n,e)=>{if(Ac(e))return{success:!0,data:e.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new Lr(n.common.issues);return this._error=t,this._error}}};Fe=class{get description(){return this._def.description}_getType(e){return Eo(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Eo(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ki,ctx:{common:e.parent.common,data:e.data,parsedType:Eo(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(vm(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let i=this.safeParse(e,t);if(i.success)return i.data;throw i.error}safeParse(e,t){let i={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Eo(e)},r=this._parseSync({data:e,path:i.path,parent:i});return SD(i,r)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Eo(e)};if(!this["~standard"].async)try{let i=this._parseSync({data:e,path:[],parent:t});return Ac(i)?{value:i.value}:{issues:t.common.issues}}catch(i){i?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(i=>Ac(i)?{value:i.value}:{issues:t.common.issues})}async parseAsync(e,t){let i=await this.safeParseAsync(e,t);if(i.success)return i.data;throw i.error}async safeParseAsync(e,t){let i={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Eo(e)},r=this._parse({data:e,path:i.path,parent:i}),s=await(vm(r)?r:Promise.resolve(r));return SD(i,s)}refine(e,t){let i=r=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(r):t;return this._refinement((r,s)=>{let o=e(r),a=()=>s.addIssue({code:Nt.custom,...i(r)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,t){return this._refinement((i,r)=>e(i)?!0:(r.addIssue(typeof t=="function"?t(i,r):t),!1))}_refinement(e){return new Ps({schema:this,typeName:we.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,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:t=>this["~validate"](t)}}optional(){return ws.create(this,this._def)}nullable(){return Co.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ga.create(this)}promise(){return Lc.create(this,this._def)}or(e){return Mh.create([this,e],this._def)}and(e){return Ch.create(this,e,this._def)}transform(e){return new Ps({...Ie(this._def),schema:this,typeName:we.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Oh({...Ie(this._def),innerType:this,defaultValue:t,typeName:we.ZodDefault})}brand(){return new Qy({typeName:we.ZodBranded,type:this,...Ie(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new Lh({...Ie(this._def),innerType:this,catchValue:t,typeName:we.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return tg.create(this,e)}readonly(){return Fh.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},yht=/^c[^\s-]{8,}$/i,ght=/^[0-9a-z]+$/,xht=/^[0-9A-HJKMNP-TV-Z]{26}$/i,bht=/^[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,vht=/^[a-z0-9_-]{21}$/i,wht=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Sht=/^[-+]?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)?)??$/,Pht=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,kht="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Tht=/^(?:(?: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])$/,Eht=/^(?:(?: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])$/,Mht=/^(([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]))$/,Cht=/^(([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])$/,Iht=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Nht=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,kD="((\\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])))",Aht=new RegExp(`^${kD}$`);Rc=class n extends Fe{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==Gt.string){let s=this._getOrReturnCtx(e);return Bt(s,{code:Nt.invalid_type,expected:Gt.string,received:s.parsedType}),ye}let i=new Ki,r;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(r=this._getOrReturnCtx(e,r),Bt(r,{code:Nt.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),i.dirty());else if(s.kind==="max")e.data.length>s.value&&(r=this._getOrReturnCtx(e,r),Bt(r,{code:Nt.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),i.dirty());else if(s.kind==="length"){let o=e.data.length>s.value,a=e.data.length<s.value;(o||a)&&(r=this._getOrReturnCtx(e,r),o?Bt(r,{code:Nt.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&Bt(r,{code:Nt.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),i.dirty())}else if(s.kind==="email")Pht.test(e.data)||(r=this._getOrReturnCtx(e,r),Bt(r,{validation:"email",code:Nt.invalid_string,message:s.message}),i.dirty());else if(s.kind==="emoji")D3||(D3=new RegExp(kht,"u")),D3.test(e.data)||(r=this._getOrReturnCtx(e,r),Bt(r,{validation:"emoji",code:Nt.invalid_string,message:s.message}),i.dirty());else if(s.kind==="uuid")bht.test(e.data)||(r=this._getOrReturnCtx(e,r),Bt(r,{validation:"uuid",code:Nt.invalid_string,message:s.message}),i.dirty());else if(s.kind==="nanoid")vht.test(e.data)||(r=this._getOrReturnCtx(e,r),Bt(r,{validation:"nanoid",code:Nt.invalid_string,message:s.message}),i.dirty());else if(s.kind==="cuid")yht.test(e.data)||(r=this._getOrReturnCtx(e,r),Bt(r,{validation:"cuid",code:Nt.invalid_string,message:s.message}),i.dirty());else if(s.kind==="cuid2")ght.test(e.data)||(r=this._getOrReturnCtx(e,r),Bt(r,{validation:"cuid2",code:Nt.invalid_string,message:s.message}),i.dirty());else if(s.kind==="ulid")xht.test(e.data)||(r=this._getOrReturnCtx(e,r),Bt(r,{validation:"ulid",code:Nt.invalid_string,message:s.message}),i.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),Bt(r,{validation:"url",code:Nt.invalid_string,message:s.message}),i.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),Bt(r,{validation:"regex",code:Nt.invalid_string,message:s.message}),i.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(r=this._getOrReturnCtx(e,r),Bt(r,{code:Nt.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),i.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(r=this._getOrReturnCtx(e,r),Bt(r,{code:Nt.invalid_string,validation:{startsWith:s.value},message:s.message}),i.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(r=this._getOrReturnCtx(e,r),Bt(r,{code:Nt.invalid_string,validation:{endsWith:s.value},message:s.message}),i.dirty()):s.kind==="datetime"?ED(s).test(e.data)||(r=this._getOrReturnCtx(e,r),Bt(r,{code:Nt.invalid_string,validation:"datetime",message:s.message}),i.dirty()):s.kind==="date"?Aht.test(e.data)||(r=this._getOrReturnCtx(e,r),Bt(r,{code:Nt.invalid_string,validation:"date",message:s.message}),i.dirty()):s.kind==="time"?Rht(s).test(e.data)||(r=this._getOrReturnCtx(e,r),Bt(r,{code:Nt.invalid_string,validation:"time",message:s.message}),i.dirty()):s.kind==="duration"?Sht.test(e.data)||(r=this._getOrReturnCtx(e,r),Bt(r,{validation:"duration",code:Nt.invalid_string,message:s.message}),i.dirty()):s.kind==="ip"?Oht(e.data,s.version)||(r=this._getOrReturnCtx(e,r),Bt(r,{validation:"ip",code:Nt.invalid_string,message:s.message}),i.dirty()):s.kind==="jwt"?Lht(e.data,s.alg)||(r=this._getOrReturnCtx(e,r),Bt(r,{validation:"jwt",code:Nt.invalid_string,message:s.message}),i.dirty()):s.kind==="cidr"?Fht(e.data,s.version)||(r=this._getOrReturnCtx(e,r),Bt(r,{validation:"cidr",code:Nt.invalid_string,message:s.message}),i.dirty()):s.kind==="base64"?Iht.test(e.data)||(r=this._getOrReturnCtx(e,r),Bt(r,{validation:"base64",code:Nt.invalid_string,message:s.message}),i.dirty()):s.kind==="base64url"?Nht.test(e.data)||(r=this._getOrReturnCtx(e,r),Bt(r,{validation:"base64url",code:Nt.invalid_string,message:s.message}),i.dirty()):Ve.assertNever(s);return{status:i.value,value:e.data}}_regex(e,t,i){return this.refinement(r=>e.test(r),{validation:t,code:Nt.invalid_string,...se.errToObj(i)})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...se.errToObj(e)})}url(e){return this._addCheck({kind:"url",...se.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...se.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...se.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...se.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...se.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...se.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...se.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...se.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...se.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...se.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...se.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...se.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...se.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...se.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...se.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...se.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...se.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...se.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...se.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...se.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...se.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...se.errToObj(t)})}nonempty(e){return this.min(1,se.errToObj(e))}trim(){return new n({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new n({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new n({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};Rc.create=n=>new Rc({checks:[],typeName:we.ZodString,coerce:n?.coerce??!1,...Ie(n)});wh=class n extends Fe{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==Gt.number){let s=this._getOrReturnCtx(e);return Bt(s,{code:Nt.invalid_type,expected:Gt.number,received:s.parsedType}),ye}let i,r=new Ki;for(let s of this._def.checks)s.kind==="int"?Ve.isInteger(e.data)||(i=this._getOrReturnCtx(e,i),Bt(i,{code:Nt.invalid_type,expected:"integer",received:"float",message:s.message}),r.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(i=this._getOrReturnCtx(e,i),Bt(i,{code:Nt.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(i=this._getOrReturnCtx(e,i),Bt(i,{code:Nt.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty()):s.kind==="multipleOf"?zht(e.data,s.value)!==0&&(i=this._getOrReturnCtx(e,i),Bt(i,{code:Nt.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(i=this._getOrReturnCtx(e,i),Bt(i,{code:Nt.not_finite,message:s.message}),r.dirty()):Ve.assertNever(s);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,se.toString(t))}gt(e,t){return this.setLimit("min",e,!1,se.toString(t))}lte(e,t){return this.setLimit("max",e,!0,se.toString(t))}lt(e,t){return this.setLimit("max",e,!1,se.toString(t))}setLimit(e,t,i,r){return new n({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:se.toString(r)}]})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:se.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:se.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:se.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:se.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:se.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:se.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:se.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:se.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:se.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Ve.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let i of this._def.checks){if(i.kind==="finite"||i.kind==="int"||i.kind==="multipleOf")return!0;i.kind==="min"?(t===null||i.value>t)&&(t=i.value):i.kind==="max"&&(e===null||i.value<e)&&(e=i.value)}return Number.isFinite(t)&&Number.isFinite(e)}};wh.create=n=>new wh({checks:[],typeName:we.ZodNumber,coerce:n?.coerce||!1,...Ie(n)});Sh=class n extends Fe{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==Gt.bigint)return this._getInvalidInput(e);let i,r=new Ki;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(i=this._getOrReturnCtx(e,i),Bt(i,{code:Nt.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(i=this._getOrReturnCtx(e,i),Bt(i,{code:Nt.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(i=this._getOrReturnCtx(e,i),Bt(i,{code:Nt.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):Ve.assertNever(s);return{status:r.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return Bt(t,{code:Nt.invalid_type,expected:Gt.bigint,received:t.parsedType}),ye}gte(e,t){return this.setLimit("min",e,!0,se.toString(t))}gt(e,t){return this.setLimit("min",e,!1,se.toString(t))}lte(e,t){return this.setLimit("max",e,!0,se.toString(t))}lt(e,t){return this.setLimit("max",e,!1,se.toString(t))}setLimit(e,t,i,r){return new n({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:se.toString(r)}]})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:se.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:se.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:se.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:se.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:se.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};Sh.create=n=>new Sh({checks:[],typeName:we.ZodBigInt,coerce:n?.coerce??!1,...Ie(n)});Ph=class extends Fe{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==Gt.boolean){let i=this._getOrReturnCtx(e);return Bt(i,{code:Nt.invalid_type,expected:Gt.boolean,received:i.parsedType}),ye}return lr(e.data)}};Ph.create=n=>new Ph({typeName:we.ZodBoolean,coerce:n?.coerce||!1,...Ie(n)});kh=class n extends Fe{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==Gt.date){let s=this._getOrReturnCtx(e);return Bt(s,{code:Nt.invalid_type,expected:Gt.date,received:s.parsedType}),ye}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return Bt(s,{code:Nt.invalid_date}),ye}let i=new Ki,r;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(r=this._getOrReturnCtx(e,r),Bt(r,{code:Nt.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),i.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(r=this._getOrReturnCtx(e,r),Bt(r,{code:Nt.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),i.dirty()):Ve.assertNever(s);return{status:i.value,value:new Date(e.data.getTime())}}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:se.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:se.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};kh.create=n=>new kh({checks:[],coerce:n?.coerce||!1,typeName:we.ZodDate,...Ie(n)});Sm=class extends Fe{_parse(e){if(this._getType(e)!==Gt.symbol){let i=this._getOrReturnCtx(e);return Bt(i,{code:Nt.invalid_type,expected:Gt.symbol,received:i.parsedType}),ye}return lr(e.data)}};Sm.create=n=>new Sm({typeName:we.ZodSymbol,...Ie(n)});Th=class extends Fe{_parse(e){if(this._getType(e)!==Gt.undefined){let i=this._getOrReturnCtx(e);return Bt(i,{code:Nt.invalid_type,expected:Gt.undefined,received:i.parsedType}),ye}return lr(e.data)}};Th.create=n=>new Th({typeName:we.ZodUndefined,...Ie(n)});Eh=class extends Fe{_parse(e){if(this._getType(e)!==Gt.null){let i=this._getOrReturnCtx(e);return Bt(i,{code:Nt.invalid_type,expected:Gt.null,received:i.parsedType}),ye}return lr(e.data)}};Eh.create=n=>new Eh({typeName:we.ZodNull,...Ie(n)});Oc=class extends Fe{constructor(){super(...arguments),this._any=!0}_parse(e){return lr(e.data)}};Oc.create=n=>new Oc({typeName:we.ZodAny,...Ie(n)});ya=class extends Fe{constructor(){super(...arguments),this._unknown=!0}_parse(e){return lr(e.data)}};ya.create=n=>new ya({typeName:we.ZodUnknown,...Ie(n)});Ws=class extends Fe{_parse(e){let t=this._getOrReturnCtx(e);return Bt(t,{code:Nt.invalid_type,expected:Gt.never,received:t.parsedType}),ye}};Ws.create=n=>new Ws({typeName:we.ZodNever,...Ie(n)});Pm=class extends Fe{_parse(e){if(this._getType(e)!==Gt.undefined){let i=this._getOrReturnCtx(e);return Bt(i,{code:Nt.invalid_type,expected:Gt.void,received:i.parsedType}),ye}return lr(e.data)}};Pm.create=n=>new Pm({typeName:we.ZodVoid,...Ie(n)});ga=class n extends Fe{_parse(e){let{ctx:t,status:i}=this._processInputParams(e),r=this._def;if(t.parsedType!==Gt.array)return Bt(t,{code:Nt.invalid_type,expected:Gt.array,received:t.parsedType}),ye;if(r.exactLength!==null){let o=t.data.length>r.exactLength.value,a=t.data.length<r.exactLength.value;(o||a)&&(Bt(t,{code:o?Nt.too_big:Nt.too_small,minimum:a?r.exactLength.value:void 0,maximum:o?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),i.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(Bt(t,{code:Nt.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),i.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(Bt(t,{code:Nt.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),i.dirty()),t.common.async)return Promise.all([...t.data].map((o,a)=>r.type._parseAsync(new Ss(t,o,t.path,a)))).then(o=>Ki.mergeArray(i,o));let s=[...t.data].map((o,a)=>r.type._parseSync(new Ss(t,o,t.path,a)));return Ki.mergeArray(i,s)}get element(){return this._def.type}min(e,t){return new n({...this._def,minLength:{value:e,message:se.toString(t)}})}max(e,t){return new n({...this._def,maxLength:{value:e,message:se.toString(t)}})}length(e,t){return new n({...this._def,exactLength:{value:e,message:se.toString(t)}})}nonempty(e){return this.min(1,e)}};ga.create=(n,e)=>new ga({type:n,minLength:null,maxLength:null,exactLength:null,typeName:we.ZodArray,...Ie(e)});Fr=class n extends Fe{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=Ve.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==Gt.object){let l=this._getOrReturnCtx(e);return Bt(l,{code:Nt.invalid_type,expected:Gt.object,received:l.parsedType}),ye}let{status:i,ctx:r}=this._processInputParams(e),{shape:s,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof Ws&&this._def.unknownKeys==="strip"))for(let l in r.data)o.includes(l)||a.push(l);let c=[];for(let l of o){let u=s[l],p=r.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Ss(r,p,r.path,l)),alwaysSet:l in r.data})}if(this._def.catchall instanceof Ws){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of a)c.push({key:{status:"valid",value:u},value:{status:"valid",value:r.data[u]}});else if(l==="strict")a.length>0&&(Bt(r,{code:Nt.unrecognized_keys,keys:a}),i.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of a){let p=r.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new Ss(r,p,r.path,u)),alwaysSet:u in r.data})}}return r.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let p=await u.key,f=await u.value;l.push({key:p,value:f,alwaysSet:u.alwaysSet})}return l}).then(l=>Ki.mergeObjectSync(i,l)):Ki.mergeObjectSync(i,c)}get shape(){return this._def.shape()}strict(e){return se.errToObj,new n({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,i)=>{let r=this._def.errorMap?.(t,i).message??i.defaultError;return t.code==="unrecognized_keys"?{message:se.errToObj(e).message??r}:{message:r}}}:{}})}strip(){return new n({...this._def,unknownKeys:"strip"})}passthrough(){return new n({...this._def,unknownKeys:"passthrough"})}extend(e){return new n({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new n({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:we.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new n({...this._def,catchall:e})}pick(e){let t={};for(let i of Ve.objectKeys(e))e[i]&&this.shape[i]&&(t[i]=this.shape[i]);return new n({...this._def,shape:()=>t})}omit(e){let t={};for(let i of Ve.objectKeys(this.shape))e[i]||(t[i]=this.shape[i]);return new n({...this._def,shape:()=>t})}deepPartial(){return wm(this)}partial(e){let t={};for(let i of Ve.objectKeys(this.shape)){let r=this.shape[i];e&&!e[i]?t[i]=r:t[i]=r.optional()}return new n({...this._def,shape:()=>t})}required(e){let t={};for(let i of Ve.objectKeys(this.shape))if(e&&!e[i])t[i]=this.shape[i];else{let s=this.shape[i];for(;s instanceof ws;)s=s._def.innerType;t[i]=s}return new n({...this._def,shape:()=>t})}keyof(){return MD(Ve.objectKeys(this.shape))}};Fr.create=(n,e)=>new Fr({shape:()=>n,unknownKeys:"strip",catchall:Ws.create(),typeName:we.ZodObject,...Ie(e)});Fr.strictCreate=(n,e)=>new Fr({shape:()=>n,unknownKeys:"strict",catchall:Ws.create(),typeName:we.ZodObject,...Ie(e)});Fr.lazycreate=(n,e)=>new Fr({shape:n,unknownKeys:"strip",catchall:Ws.create(),typeName:we.ZodObject,...Ie(e)});Mh=class extends Fe{_parse(e){let{ctx:t}=this._processInputParams(e),i=this._def.options;function r(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return t.common.issues.push(...a.ctx.common.issues),a.result;let o=s.map(a=>new Lr(a.ctx.common.issues));return Bt(t,{code:Nt.invalid_union,unionErrors:o}),ye}if(t.common.async)return Promise.all(i.map(async s=>{let o={...t,common:{...t.common,issues:[]},parent:null};return{result:await s._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(r);{let s,o=[];for(let c of i){let l={...t,common:{...t.common,issues:[]},parent:null},u=c._parseSync({data:t.data,path:t.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:l}),l.common.issues.length&&o.push(l.common.issues)}if(s)return t.common.issues.push(...s.ctx.common.issues),s.result;let a=o.map(c=>new Lr(c));return Bt(t,{code:Nt.invalid_union,unionErrors:a}),ye}}get options(){return this._def.options}};Mh.create=(n,e)=>new Mh({options:n,typeName:we.ZodUnion,...Ie(e)});_a=n=>n instanceof Ih?_a(n.schema):n instanceof Ps?_a(n.innerType()):n instanceof Nh?[n.value]:n instanceof Ah?n.options:n instanceof Rh?Ve.objectValues(n.enum):n instanceof Oh?_a(n._def.innerType):n instanceof Th?[void 0]:n instanceof Eh?[null]:n instanceof ws?[void 0,..._a(n.unwrap())]:n instanceof Co?[null,..._a(n.unwrap())]:n instanceof Qy||n instanceof Fh?_a(n.unwrap()):n instanceof Lh?_a(n._def.innerType):[],Fx=class n extends Fe{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==Gt.object)return Bt(t,{code:Nt.invalid_type,expected:Gt.object,received:t.parsedType}),ye;let i=this.discriminator,r=t.data[i],s=this.optionsMap.get(r);return s?t.common.async?s._parseAsync({data:t.data,path:t.path,parent:t}):s._parseSync({data:t.data,path:t.path,parent:t}):(Bt(t,{code:Nt.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[i]}),ye)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,i){let r=new Map;for(let s of t){let o=_a(s.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of o){if(r.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);r.set(a,s)}}return new n({typeName:we.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:r,...Ie(i)})}};Ch=class extends Fe{_parse(e){let{status:t,ctx:i}=this._processInputParams(e),r=(s,o)=>{if(Ox(s)||Ox(o))return ye;let a=$3(s.value,o.value);return a.valid?((Lx(s)||Lx(o))&&t.dirty(),{status:t.value,value:a.data}):(Bt(i,{code:Nt.invalid_intersection_types}),ye)};return i.common.async?Promise.all([this._def.left._parseAsync({data:i.data,path:i.path,parent:i}),this._def.right._parseAsync({data:i.data,path:i.path,parent:i})]).then(([s,o])=>r(s,o)):r(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}};Ch.create=(n,e,t)=>new Ch({left:n,right:e,typeName:we.ZodIntersection,...Ie(t)});Mo=class n extends Fe{_parse(e){let{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==Gt.array)return Bt(i,{code:Nt.invalid_type,expected:Gt.array,received:i.parsedType}),ye;if(i.data.length<this._def.items.length)return Bt(i,{code:Nt.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ye;!this._def.rest&&i.data.length>this._def.items.length&&(Bt(i,{code:Nt.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let s=[...i.data].map((o,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Ss(i,o,i.path,a)):null}).filter(o=>!!o);return i.common.async?Promise.all(s).then(o=>Ki.mergeArray(t,o)):Ki.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new n({...this._def,rest:e})}};Mo.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Mo({items:n,typeName:we.ZodTuple,rest:null,...Ie(e)})};zx=class n extends Fe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==Gt.object)return Bt(i,{code:Nt.invalid_type,expected:Gt.object,received:i.parsedType}),ye;let r=[],s=this._def.keyType,o=this._def.valueType;for(let a in i.data)r.push({key:s._parse(new Ss(i,a,i.path,a)),value:o._parse(new Ss(i,i.data[a],i.path,a)),alwaysSet:a in i.data});return i.common.async?Ki.mergeObjectAsync(t,r):Ki.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(e,t,i){return t instanceof Fe?new n({keyType:e,valueType:t,typeName:we.ZodRecord,...Ie(i)}):new n({keyType:Rc.create(),valueType:e,typeName:we.ZodRecord,...Ie(t)})}},km=class extends Fe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==Gt.map)return Bt(i,{code:Nt.invalid_type,expected:Gt.map,received:i.parsedType}),ye;let r=this._def.keyType,s=this._def.valueType,o=[...i.data.entries()].map(([a,c],l)=>({key:r._parse(new Ss(i,a,i.path,[l,"key"])),value:s._parse(new Ss(i,c,i.path,[l,"value"]))}));if(i.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of o){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return ye;(l.status==="dirty"||u.status==="dirty")&&t.dirty(),a.set(l.value,u.value)}return{status:t.value,value:a}})}else{let a=new Map;for(let c of o){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return ye;(l.status==="dirty"||u.status==="dirty")&&t.dirty(),a.set(l.value,u.value)}return{status:t.value,value:a}}}};km.create=(n,e,t)=>new km({valueType:e,keyType:n,typeName:we.ZodMap,...Ie(t)});Tm=class n extends Fe{_parse(e){let{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==Gt.set)return Bt(i,{code:Nt.invalid_type,expected:Gt.set,received:i.parsedType}),ye;let r=this._def;r.minSize!==null&&i.data.size<r.minSize.value&&(Bt(i,{code:Nt.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&i.data.size>r.maxSize.value&&(Bt(i,{code:Nt.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let s=this._def.valueType;function o(c){let l=new Set;for(let u of c){if(u.status==="aborted")return ye;u.status==="dirty"&&t.dirty(),l.add(u.value)}return{status:t.value,value:l}}let a=[...i.data.values()].map((c,l)=>s._parse(new Ss(i,c,i.path,l)));return i.common.async?Promise.all(a).then(c=>o(c)):o(a)}min(e,t){return new n({...this._def,minSize:{value:e,message:se.toString(t)}})}max(e,t){return new n({...this._def,maxSize:{value:e,message:se.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Tm.create=(n,e)=>new Tm({valueType:n,minSize:null,maxSize:null,typeName:we.ZodSet,...Ie(e)});Dx=class n extends Fe{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==Gt.function)return Bt(t,{code:Nt.invalid_type,expected:Gt.function,received:t.parsedType}),ye;function i(a,c){return Jy({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,bm(),ma].filter(l=>!!l),issueData:{code:Nt.invalid_arguments,argumentsError:c}})}function r(a,c){return Jy({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,bm(),ma].filter(l=>!!l),issueData:{code:Nt.invalid_return_type,returnTypeError:c}})}let s={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof Lc){let a=this;return lr(async function(...c){let l=new Lr([]),u=await a._def.args.parseAsync(c,s).catch(y=>{throw l.addIssue(i(c,y)),l}),p=await Reflect.apply(o,this,u);return await a._def.returns._def.type.parseAsync(p,s).catch(y=>{throw l.addIssue(r(p,y)),l})})}else{let a=this;return lr(function(...c){let l=a._def.args.safeParse(c,s);if(!l.success)throw new Lr([i(c,l.error)]);let u=Reflect.apply(o,this,l.data),p=a._def.returns.safeParse(u,s);if(!p.success)throw new Lr([r(u,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new n({...this._def,args:Mo.create(e).rest(ya.create())})}returns(e){return new n({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,i){return new n({args:e||Mo.create([]).rest(ya.create()),returns:t||ya.create(),typeName:we.ZodFunction,...Ie(i)})}},Ih=class extends Fe{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};Ih.create=(n,e)=>new Ih({getter:n,typeName:we.ZodLazy,...Ie(e)});Nh=class extends Fe{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return Bt(t,{received:t.data,code:Nt.invalid_literal,expected:this._def.value}),ye}return{status:"valid",value:e.data}}get value(){return this._def.value}};Nh.create=(n,e)=>new Nh({value:n,typeName:we.ZodLiteral,...Ie(e)});Ah=class n extends Fe{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),i=this._def.values;return Bt(t,{expected:Ve.joinValues(i),received:t.parsedType,code:Nt.invalid_type}),ye}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),i=this._def.values;return Bt(t,{received:t.data,code:Nt.invalid_enum_value,options:i}),ye}return lr(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return n.create(e,{...this._def,...t})}exclude(e,t=this._def){return n.create(this.options.filter(i=>!e.includes(i)),{...this._def,...t})}};Ah.create=MD;Rh=class extends Fe{_parse(e){let t=Ve.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(e);if(i.parsedType!==Gt.string&&i.parsedType!==Gt.number){let r=Ve.objectValues(t);return Bt(i,{expected:Ve.joinValues(r),received:i.parsedType,code:Nt.invalid_type}),ye}if(this._cache||(this._cache=new Set(Ve.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let r=Ve.objectValues(t);return Bt(i,{received:i.data,code:Nt.invalid_enum_value,options:r}),ye}return lr(e.data)}get enum(){return this._def.values}};Rh.create=(n,e)=>new Rh({values:n,typeName:we.ZodNativeEnum,...Ie(e)});Lc=class extends Fe{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==Gt.promise&&t.common.async===!1)return Bt(t,{code:Nt.invalid_type,expected:Gt.promise,received:t.parsedType}),ye;let i=t.parsedType===Gt.promise?t.data:Promise.resolve(t.data);return lr(i.then(r=>this._def.type.parseAsync(r,{path:t.path,errorMap:t.common.contextualErrorMap})))}};Lc.create=(n,e)=>new Lc({type:n,typeName:we.ZodPromise,...Ie(e)});Ps=class extends Fe{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===we.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:i}=this._processInputParams(e),r=this._def.effect||null,s={addIssue:o=>{Bt(i,o),o.fatal?t.abort():t.dirty()},get path(){return i.path}};if(s.addIssue=s.addIssue.bind(s),r.type==="preprocess"){let o=r.transform(i.data,s);if(i.common.async)return Promise.resolve(o).then(async a=>{if(t.value==="aborted")return ye;let c=await this._def.schema._parseAsync({data:a,path:i.path,parent:i});return c.status==="aborted"?ye:c.status==="dirty"?vh(c.value):t.value==="dirty"?vh(c.value):c});{if(t.value==="aborted")return ye;let a=this._def.schema._parseSync({data:o,path:i.path,parent:i});return a.status==="aborted"?ye:a.status==="dirty"?vh(a.value):t.value==="dirty"?vh(a.value):a}}if(r.type==="refinement"){let o=a=>{let c=r.refinement(a,s);if(i.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(i.common.async===!1){let a=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});return a.status==="aborted"?ye:(a.status==="dirty"&&t.dirty(),o(a.value),{status:t.value,value:a.value})}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(a=>a.status==="aborted"?ye:(a.status==="dirty"&&t.dirty(),o(a.value).then(()=>({status:t.value,value:a.value}))))}if(r.type==="transform")if(i.common.async===!1){let o=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(!Ac(o))return ye;let a=r.transform(o.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(o=>Ac(o)?Promise.resolve(r.transform(o.value,s)).then(a=>({status:t.value,value:a})):ye);Ve.assertNever(r)}};Ps.create=(n,e,t)=>new Ps({schema:n,typeName:we.ZodEffects,effect:e,...Ie(t)});Ps.createWithPreprocess=(n,e,t)=>new Ps({schema:e,effect:{type:"preprocess",transform:n},typeName:we.ZodEffects,...Ie(t)});ws=class extends Fe{_parse(e){return this._getType(e)===Gt.undefined?lr(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ws.create=(n,e)=>new ws({innerType:n,typeName:we.ZodOptional,...Ie(e)});Co=class extends Fe{_parse(e){return this._getType(e)===Gt.null?lr(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Co.create=(n,e)=>new Co({innerType:n,typeName:we.ZodNullable,...Ie(e)});Oh=class extends Fe{_parse(e){let{ctx:t}=this._processInputParams(e),i=t.data;return t.parsedType===Gt.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Oh.create=(n,e)=>new Oh({innerType:n,typeName:we.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Ie(e)});Lh=class extends Fe{_parse(e){let{ctx:t}=this._processInputParams(e),i={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return vm(r)?r.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Lr(i.common.issues)},input:i.data})})):{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new Lr(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}};Lh.create=(n,e)=>new Lh({innerType:n,typeName:we.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Ie(e)});Em=class extends Fe{_parse(e){if(this._getType(e)!==Gt.nan){let i=this._getOrReturnCtx(e);return Bt(i,{code:Nt.invalid_type,expected:Gt.nan,received:i.parsedType}),ye}return{status:"valid",value:e.data}}};Em.create=n=>new Em({typeName:we.ZodNaN,...Ie(n)});Dht=Symbol("zod_brand"),Qy=class extends Fe{_parse(e){let{ctx:t}=this._processInputParams(e),i=t.data;return this._def.type._parse({data:i,path:t.path,parent:t})}unwrap(){return this._def.type}},tg=class n extends Fe{_parse(e){let{status:t,ctx:i}=this._processInputParams(e);if(i.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});return s.status==="aborted"?ye:s.status==="dirty"?(t.dirty(),vh(s.value)):this._def.out._parseAsync({data:s.value,path:i.path,parent:i})})();{let r=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return r.status==="aborted"?ye:r.status==="dirty"?(t.dirty(),{status:"dirty",value:r.value}):this._def.out._parseSync({data:r.value,path:i.path,parent:i})}}static create(e,t){return new n({in:e,out:t,typeName:we.ZodPipeline})}},Fh=class extends Fe{_parse(e){let t=this._def.innerType._parse(e),i=r=>(Ac(r)&&(r.value=Object.freeze(r.value)),r);return vm(t)?t.then(r=>i(r)):i(t)}unwrap(){return this._def.innerType}};Fh.create=(n,e)=>new Fh({innerType:n,typeName:we.ZodReadonly,...Ie(e)});$ht={object:Fr.lazycreate};(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(we||(we={}));jht=(n,e={message:`Input not instance of ${n.name}`})=>CD(t=>t instanceof n,e),ID=Rc.create,ND=wh.create,Bht=Em.create,Yht=Sh.create,AD=Ph.create,Xht=kh.create,Uht=Sm.create,Vht=Th.create,Ght=Eh.create,Hht=Oc.create,Wht=ya.create,qht=Ws.create,Zht=Pm.create,Kht=ga.create,Jht=Fr.create,Qht=Fr.strictCreate,tdt=Mh.create,edt=Fx.create,ndt=Ch.create,idt=Mo.create,rdt=zx.create,sdt=km.create,odt=Tm.create,adt=Dx.create,cdt=Ih.create,ldt=Nh.create,udt=Ah.create,pdt=Rh.create,hdt=Lc.create,ddt=Ps.create,fdt=ws.create,mdt=Co.create,_dt=Ps.createWithPreprocess,ydt=tg.create,gdt=()=>ID().optional(),xdt=()=>ND().optional(),bdt=()=>AD().optional(),vdt={string:(n=>Rc.create({...n,coerce:!0})),number:(n=>wh.create({...n,coerce:!0})),boolean:(n=>Ph.create({...n,coerce:!0})),bigint:(n=>Sh.create({...n,coerce:!0})),date:(n=>kh.create({...n,coerce:!0}))},wdt=ye});var h={};xh(h,{BRAND:()=>Dht,DIRTY:()=>vh,EMPTY_PATH:()=>_ht,INVALID:()=>ye,NEVER:()=>wdt,OK:()=>lr,ParseStatus:()=>Ki,Schema:()=>Fe,ZodAny:()=>Oc,ZodArray:()=>ga,ZodBigInt:()=>Sh,ZodBoolean:()=>Ph,ZodBranded:()=>Qy,ZodCatch:()=>Lh,ZodDate:()=>kh,ZodDefault:()=>Oh,ZodDiscriminatedUnion:()=>Fx,ZodEffects:()=>Ps,ZodEnum:()=>Ah,ZodError:()=>Lr,ZodFirstPartyTypeKind:()=>we,ZodFunction:()=>Dx,ZodIntersection:()=>Ch,ZodIssueCode:()=>Nt,ZodLazy:()=>Ih,ZodLiteral:()=>Nh,ZodMap:()=>km,ZodNaN:()=>Em,ZodNativeEnum:()=>Rh,ZodNever:()=>Ws,ZodNull:()=>Eh,ZodNullable:()=>Co,ZodNumber:()=>wh,ZodObject:()=>Fr,ZodOptional:()=>ws,ZodParsedType:()=>Gt,ZodPipeline:()=>tg,ZodPromise:()=>Lc,ZodReadonly:()=>Fh,ZodRecord:()=>zx,ZodSchema:()=>Fe,ZodSet:()=>Tm,ZodString:()=>Rc,ZodSymbol:()=>Sm,ZodTransformer:()=>Ps,ZodTuple:()=>Mo,ZodType:()=>Fe,ZodUndefined:()=>Th,ZodUnion:()=>Mh,ZodUnknown:()=>ya,ZodVoid:()=>Pm,addIssueToContext:()=>Bt,any:()=>Hht,array:()=>Kht,bigint:()=>Yht,boolean:()=>AD,coerce:()=>vdt,custom:()=>CD,date:()=>Xht,datetimeRegex:()=>ED,defaultErrorMap:()=>ma,discriminatedUnion:()=>edt,effect:()=>ddt,enum:()=>udt,function:()=>adt,getErrorMap:()=>bm,getParsedType:()=>Eo,instanceof:()=>jht,intersection:()=>ndt,isAborted:()=>Ox,isAsync:()=>vm,isDirty:()=>Lx,isValid:()=>Ac,late:()=>$ht,lazy:()=>cdt,literal:()=>ldt,makeIssue:()=>Jy,map:()=>sdt,nan:()=>Bht,nativeEnum:()=>pdt,never:()=>qht,null:()=>Ght,nullable:()=>mdt,number:()=>ND,object:()=>Jht,objectUtil:()=>L3,oboolean:()=>bdt,onumber:()=>xdt,optional:()=>fdt,ostring:()=>gdt,pipeline:()=>ydt,preprocess:()=>_dt,promise:()=>hdt,quotelessJson:()=>dht,record:()=>rdt,set:()=>odt,setErrorMap:()=>mht,strictObject:()=>Qht,string:()=>ID,symbol:()=>Uht,transformer:()=>ddt,tuple:()=>idt,undefined:()=>Vht,union:()=>tdt,unknown:()=>Wht,util:()=>Ve,void:()=>Zht});var j3=qt(()=>{"use strict";Rx();z3();vD();Ky();RD();Ax()});var J=qt(()=>{"use strict";j3();j3()});var jh={};xh(jh,{all_layers:()=>Im,any_circuit_element:()=>qj,any_soup_element:()=>$h,any_source_component:()=>UD,battery_capacity:()=>DD,brep_shape:()=>k$,cad_component:()=>Dj,capacitance:()=>xa,circuit_json_footprint_load_error:()=>Vx,current:()=>Pdt,distance:()=>X,duration_ms:()=>eg,experiment_type:()=>Xj,external_footprint_load_error:()=>Nm,frequency:()=>pr,getZodPrefixedIdWithDefault:()=>At,inductance:()=>$x,layer_ref:()=>he,layer_string:()=>Y3,length:()=>$,ms:()=>ur,ninePointAnchor:()=>ng,pcb_autorouting_error:()=>Pj,pcb_board:()=>Z$,pcb_breakout_point:()=>kj,pcb_component:()=>E$,pcb_component_invalid_layer_error:()=>Am,pcb_component_outside_board_error:()=>Rj,pcb_copper_pour:()=>Aj,pcb_copper_pour_brep:()=>Ij,pcb_copper_pour_polygon:()=>Nj,pcb_copper_pour_rect:()=>Cj,pcb_copper_text:()=>ij,pcb_courtyard_outline:()=>Fj,pcb_courtyard_polygon:()=>zj,pcb_courtyard_rect:()=>Lj,pcb_cutout:()=>vj,pcb_cutout_circle:()=>xj,pcb_cutout_polygon:()=>bj,pcb_cutout_rect:()=>gj,pcb_fabrication_note_dimension:()=>uj,pcb_fabrication_note_path:()=>cj,pcb_fabrication_note_rect:()=>lj,pcb_fabrication_note_text:()=>aj,pcb_footprint_overlap_error:()=>_j,pcb_ground_plane:()=>Tj,pcb_ground_plane_region:()=>Ej,pcb_group:()=>Sj,pcb_hole:()=>O$,pcb_hole_circle_or_square_shape:()=>Odt,pcb_hole_circle_shape:()=>Adt,pcb_hole_oval_shape:()=>Ldt,pcb_hole_pill_shape:()=>Fdt,pcb_hole_rect_shape:()=>Rdt,pcb_hole_rotated_pill_shape:()=>zdt,pcb_keepout:()=>yj,pcb_manual_edit_conflict_warning:()=>Gx,pcb_missing_footprint_error:()=>wj,pcb_net:()=>W$,pcb_note_dimension:()=>mj,pcb_note_line:()=>fj,pcb_note_path:()=>dj,pcb_note_rect:()=>hj,pcb_note_text:()=>pj,pcb_panel:()=>K$,pcb_placement_error:()=>J$,pcb_plated_hole:()=>L$,pcb_port:()=>F$,pcb_port_not_connected_error:()=>H$,pcb_port_not_matched_error:()=>G$,pcb_route_hint:()=>T$,pcb_route_hints:()=>Ndt,pcb_silkscreen_circle:()=>sj,pcb_silkscreen_line:()=>tj,pcb_silkscreen_oval:()=>oj,pcb_silkscreen_path:()=>ej,pcb_silkscreen_rect:()=>rj,pcb_silkscreen_text:()=>nj,pcb_smtpad:()=>D$,pcb_smtpad_pill:()=>z$,pcb_solder_paste:()=>$$,pcb_text:()=>j$,pcb_thermal_spoke:()=>Mj,pcb_trace:()=>X$,pcb_trace_error:()=>U$,pcb_trace_hint:()=>Q$,pcb_trace_missing_error:()=>V$,pcb_trace_route_point:()=>Ux,pcb_trace_route_point_via:()=>Y$,pcb_trace_route_point_wire:()=>B$,pcb_via:()=>q$,pcb_via_clearance_error:()=>Oj,point:()=>Jt,point3:()=>zh,point_with_bulge:()=>P$,port_arrangement:()=>i$,position:()=>Tdt,position3:()=>Edt,resistance:()=>Fc,ring:()=>X3,rotation:()=>He,route_hint_point:()=>Ji,schematic_arc:()=>c$,schematic_box:()=>JD,schematic_circle:()=>a$,schematic_component:()=>r$,schematic_component_port_arrangement_by_sides:()=>n$,schematic_component_port_arrangement_by_size:()=>e$,schematic_debug_line:()=>_$,schematic_debug_object:()=>g$,schematic_debug_object_base:()=>Yx,schematic_debug_point:()=>y$,schematic_debug_rect:()=>m$,schematic_error:()=>d$,schematic_group:()=>b$,schematic_layout_error:()=>f$,schematic_line:()=>s$,schematic_manual_edit_conflict_warning:()=>Xx,schematic_net_label:()=>h$,schematic_path:()=>QD,schematic_pin_styles:()=>t$,schematic_port:()=>p$,schematic_rect:()=>o$,schematic_sheet:()=>S$,schematic_table:()=>v$,schematic_table_cell:()=>w$,schematic_text:()=>u$,schematic_trace:()=>l$,schematic_voltage_probe:()=>x$,simulation_ac_voltage_source:()=>Bj,simulation_dc_voltage_source:()=>jj,simulation_experiment:()=>Uj,simulation_switch:()=>Gj,simulation_transient_voltage_graph:()=>Vj,simulation_unknown_experiment_error:()=>Wj,simulation_voltage_probe:()=>Hj,simulation_voltage_source:()=>Yj,size:()=>U3,source_board:()=>qD,source_component_base:()=>fi,source_failed_to_create_component_error:()=>YD,source_group:()=>HD,source_manually_placed_via:()=>KD,source_missing_property_error:()=>BD,source_net:()=>WD,source_pcb_ground_plane:()=>ZD,source_pin_missing_trace_warning:()=>lE,source_port:()=>VD,source_project_metadata:()=>aE,source_property_ignored_warning:()=>XD,source_simple_battery:()=>Z3,source_simple_capacitor:()=>V3,source_simple_chip:()=>W3,source_simple_crystal:()=>jD,source_simple_diode:()=>jx,source_simple_ground:()=>$D,source_simple_inductor:()=>K3,source_simple_led:()=>H3,source_simple_mosfet:()=>sE,source_simple_pin_header:()=>tE,source_simple_pinout:()=>eE,source_simple_potentiometer:()=>Q3,source_simple_power_source:()=>q3,source_simple_push_button:()=>J3,source_simple_resistor:()=>G3,source_simple_resonator:()=>nE,source_simple_switch:()=>oE,source_simple_test_point:()=>rE,source_simple_transistor:()=>iE,source_trace:()=>GD,source_trace_not_connected_error:()=>cE,supplier_name:()=>Cm,time:()=>kdt,timestamp:()=>zD,unknown_error_finding_part:()=>Bx,visible_layer:()=>Zs,voltage:()=>Si,wave_shape:()=>$j});function Sdt(n){for(let[e,t]of Object.entries(FD))if(n in t.variants)return{baseUnit:t.baseUnit,conversionFactor:t.variants[n]};return{baseUnit:n,conversionFactor:1}}function qs(n){if(n==null)return{parsedUnit:null,unitOfValue:null,value:null};if(typeof n=="string"&&n.match(/^-?[\d\.]+$/))return{value:Number.parseFloat(n),parsedUnit:null,unitOfValue:null};if(typeof n=="number")return{value:n,parsedUnit:null,unitOfValue:null};if(typeof n=="object"&&"x"in n&&"y"in n){let{parsedUnit:a,unitOfValue:c}=qs(n.x),l=qs(n.x),u=qs(n.y);return l.value===null||u.value===null?{parsedUnit:null,unitOfValue:null,value:null}:{parsedUnit:a,unitOfValue:c,value:{x:l.value,y:u.value}}}let t=n.toString().split("").reverse().join("").match(/[^\d\s]+/)?.[0];if(!t)throw new Error(`Could not determine unit: "${n}"`);let i=t.split("").reverse().join(""),r=n.slice(0,-i.length);if(i in LD&&!B3.has(i)){let a=LD[i];return{parsedUnit:null,unitOfValue:null,value:Number.parseFloat(r)*a}}let{baseUnit:s,conversionFactor:o}=Sdt(i);return{parsedUnit:i,unitOfValue:s,value:o*Number.parseFloat(r)}}var FD,B3,LD,Fc,xa,$x,Si,$,pr,X,Pdt,eg,kdt,ur,zD,He,DD,_t,Dh,Jt,Tdt,zh,Edt,U3,Mdt,At,ng,Cm,fi,V3,G3,jx,H3,$D,W3,q3,Cdt,Z3,K3,J3,Q3,jD,tE,eE,nE,iE,rE,sE,oE,aE,BD,YD,cE,XD,lE,UD,VD,GD,HD,WD,qD,ZD,Im,Y3,he,Zs,KD,Bx,JD,QD,t$,e$,n$,i$,r$,s$,o$,a$,c$,l$,Idt,u$,p$,h$,d$,f$,Yx,m$,_$,y$,g$,x$,Xx,b$,v$,w$,S$,P$,X3,k$,T$,Ndt,Ji,E$,M$,Adt,C$,Rdt,I$,Odt,N$,Ldt,A$,Fdt,R$,zdt,O$,Ddt,$dt,jdt,Bdt,Ydt,L$,F$,Xdt,Udt,Vdt,z$,Gdt,Hdt,D$,Wdt,qdt,Zdt,Kdt,Jdt,$$,j$,B$,Y$,Ux,X$,U$,V$,G$,H$,W$,q$,Z$,K$,J$,Q$,tj,ej,nj,ij,rj,sj,oj,aj,cj,lj,uj,pj,hj,dj,fj,mj,_j,yj,uE,gj,xj,bj,vj,wj,Nm,Vx,Sj,Pj,Gx,kj,Tj,Ej,Mj,pE,Cj,Ij,Nj,Aj,Rj,Am,Oj,Lj,Fj,zj,Dj,$j,Qdt,jj,Bj,Yj,Xj,Uj,Vj,Gj,Hj,Wj,qj,$h,wt=qt(()=>{"use strict";J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();FD={Hz:{baseUnit:"Hz",variants:{MHz:1e6,kHz:1e3,Hz:1}},g:{baseUnit:"g",variants:{kg:1e3,g:1}},\u03A9:{baseUnit:"\u03A9",variants:{m\u03A9:.001,\u03A9:1,k\u03A9:1e3,K\u03A9:1e3,kohm:1e3,M\u03A9:1e6,G\u03A9:1e9,T\u03A9:1e12}},V:{baseUnit:"V",variants:{mV:.001,V:1,kV:1e3,KV:1e3,MV:1e6,GV:1e9,TV:1e12}},A:{baseUnit:"A",variants:{\u00B5A:1e-6,mA:.001,ma:.001,A:1,kA:1e3,MA:1e6}},F:{baseUnit:"F",variants:{pF:1e-12,nF:1e-9,\u00B5F:1e-6,uF:1e-6,mF:.001,F:1}},ml:{baseUnit:"ml",variants:{ml:1,mL:1,l:1e3,L:1e3}},deg:{baseUnit:"deg",variants:{rad:180/Math.PI}},ms:{baseUnit:"ms",variants:{fs:1e-12,ps:1e-9,ns:1e-6,us:.001,\u00B5s:.001,ms:1,s:1e3}},mm:{baseUnit:"mm",variants:{nm:1e-6,\u00B5m:.001,um:.001,mm:1,cm:10,dm:100,m:1e3,km:1e6,in:25.4,ft:304.8,IN:25.4,FT:304.8,yd:914.4,mi:1609344,mil:.0254}}},B3=new Set;for(let[n,e]of Object.entries(FD)){B3.add(n);for(let t of Object.keys(e.variants))B3.add(t)}LD={tera:1e12,T:1e12,giga:1e9,G:1e9,mega:1e6,M:1e6,kilo:1e3,k:1e3,deci:.1,d:.1,centi:.01,c:.01,milli:.001,m:.001,micro:1e-6,u:1e-6,\u00B5:1e-6,nano:1e-9,n:1e-9,pico:1e-12,p:1e-12};Fc=h.string().or(h.number()).transform(n=>qs(n).value),xa=h.string().or(h.number()).transform(n=>qs(n).value).transform(n=>Number.parseFloat(n.toPrecision(12))),$x=h.string().or(h.number()).transform(n=>qs(n).value),Si=h.string().or(h.number()).transform(n=>qs(n).value),$=h.string().or(h.number()).transform(n=>qs(n).value),pr=h.string().or(h.number()).transform(n=>qs(n).value),X=$,Pdt=h.string().or(h.number()).transform(n=>qs(n).value),eg=h.string().or(h.number()).transform(n=>qs(n).value),kdt=eg,ur=eg,zD=h.string().datetime(),He=h.string().or(h.number()).transform(n=>typeof n=="number"?n:n.endsWith("deg")?Number.parseFloat(n.split("deg")[0]):n.endsWith("rad")?Number.parseFloat(n.split("rad")[0])*180/Math.PI:Number.parseFloat(n)),DD=h.number().or(h.string().endsWith("mAh")).transform(n=>{if(typeof n=="string"){let e=n.replace("mAh",""),t=Number.parseFloat(e);if(Number.isNaN(t))throw new Error("Invalid capacity");return t}return n}).describe("Battery capacity in mAh"),_t=n=>{};_t("extra props b");_t("missing props b");_t(!0);_t("mismatched prop types: a");Dh=n=>{};Dh(!0);Dh('T1 has extra: "c", T2 has extra: "d"');Dh('T1 has extra: "c"');Dh('T2 has extra: "c"');Dh('T1 has extra: "d", T2 has extra: "c"');Dh(!0);Jt=h.object({x:X,y:X}),Tdt=Jt;_t(!0);_t(!0);zh=h.object({x:X,y:X,z:X}),Edt=zh;_t(!0);U3=h.object({width:h.number(),height:h.number()});_t(!0);Mdt=n=>{let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";return Array.from({length:n},()=>e[Math.floor(Math.random()*e.length)]).join("")},At=n=>h.string().optional().default(()=>`${n}_${Mdt(10)}`),ng=h.enum(["top_left","top_center","top_right","center_left","center","center_right","bottom_left","bottom_center","bottom_right"]);_t(!0);Cm=h.enum(["jlcpcb","macrofab","pcbway","digikey","mouser","lcsc"]);_t(!0);fi=h.object({type:h.literal("source_component"),ftype:h.string().optional(),source_component_id:h.string(),name:h.string(),manufacturer_part_number:h.string().optional(),supplier_part_numbers:h.record(Cm,h.array(h.string())).optional(),display_value:h.string().optional(),are_pins_interchangeable:h.boolean().optional(),internally_connected_source_port_ids:h.array(h.array(h.string())).optional(),source_group_id:h.string().optional(),subcircuit_id:h.string().optional()});_t(!0);V3=fi.extend({ftype:h.literal("simple_capacitor"),capacitance:xa,max_voltage_rating:Si.optional(),display_capacitance:h.string().optional(),max_decoupling_trace_length:X.optional()});_t(!0);G3=fi.extend({ftype:h.literal("simple_resistor"),resistance:Fc,display_resistance:h.string().optional()});_t(!0);jx=fi.extend({ftype:h.literal("simple_diode")});_t(!0);H3=jx.extend({ftype:h.literal("simple_led"),color:h.string().optional(),wavelength:h.string().optional()});_t(!0);$D=fi.extend({ftype:h.literal("simple_ground")});_t(!0);W3=fi.extend({ftype:h.literal("simple_chip")});_t(!0);q3=fi.extend({ftype:h.literal("simple_power_source"),voltage:Si});_t(!0);Cdt=fi.extend({ftype:h.literal("simple_fuse"),current_rating_amps:h.number().describe("Nominal current in amps the fuse is rated for"),voltage_rating_volts:h.number().describe("Voltage rating in volts, e.g. \xB15V would be 5")});_t(!0);Z3=fi.extend({ftype:h.literal("simple_battery"),capacity:DD});_t(!0);K3=fi.extend({ftype:h.literal("simple_inductor"),inductance:$x,max_current_rating:h.number().optional()});_t(!0);J3=fi.extend({ftype:h.literal("simple_push_button")});_t(!0);Q3=fi.extend({ftype:h.literal("simple_potentiometer"),max_resistance:Fc});_t(!0);jD=fi.extend({ftype:h.literal("simple_crystal"),frequency:h.number().describe("Frequency in Hz"),load_capacitance:h.number().optional().describe("Load capacitance in pF")});_t(!0);tE=fi.extend({ftype:h.literal("simple_pin_header"),pin_count:h.number(),gender:h.enum(["male","female"]).optional().default("male")});_t(!0);eE=fi.extend({ftype:h.literal("simple_pinout")});_t(!0);nE=fi.extend({ftype:h.literal("simple_resonator"),load_capacitance:xa,equivalent_series_resistance:Fc.optional(),frequency:pr});_t(!0);iE=fi.extend({ftype:h.literal("simple_transistor"),transistor_type:h.enum(["npn","pnp"])});_t(!0);rE=fi.extend({ftype:h.literal("simple_test_point"),footprint_variant:h.enum(["pad","through_hole"]).optional(),pad_shape:h.enum(["rect","circle"]).optional(),pad_diameter:h.union([h.number(),h.string()]).optional(),hole_diameter:h.union([h.number(),h.string()]).optional(),width:h.union([h.number(),h.string()]).optional(),height:h.union([h.number(),h.string()]).optional()});_t(!0);sE=fi.extend({ftype:h.literal("simple_mosfet"),channel_type:h.enum(["n","p"]),mosfet_mode:h.enum(["enhancement","depletion"])});_t(!0);oE=fi.extend({ftype:h.literal("simple_switch")});_t(!0);aE=h.object({type:h.literal("source_project_metadata"),name:h.string().optional(),software_used_string:h.string().optional(),project_url:h.string().optional(),created_at:zD.optional()});_t(!0);BD=h.object({type:h.literal("source_missing_property_error"),source_missing_property_error_id:At("source_missing_property_error"),source_component_id:h.string(),property_name:h.string(),subcircuit_id:h.string().optional(),error_type:h.literal("source_missing_property_error").default("source_missing_property_error"),message:h.string()}).describe("The source code is missing a property");_t(!0);YD=h.object({type:h.literal("source_failed_to_create_component_error"),source_failed_to_create_component_error_id:At("source_failed_to_create_component_error"),error_type:h.literal("source_failed_to_create_component_error").default("source_failed_to_create_component_error"),component_name:h.string().optional(),subcircuit_id:h.string().optional(),parent_source_component_id:h.string().optional(),message:h.string(),pcb_center:h.object({x:h.number().optional(),y:h.number().optional()}).optional(),schematic_center:h.object({x:h.number().optional(),y:h.number().optional()}).optional()}).describe("Error emitted when a component fails to be constructed");_t(!0);cE=h.object({type:h.literal("source_trace_not_connected_error"),source_trace_not_connected_error_id:At("source_trace_not_connected_error"),error_type:h.literal("source_trace_not_connected_error").default("source_trace_not_connected_error"),message:h.string(),subcircuit_id:h.string().optional(),source_group_id:h.string().optional(),source_trace_id:h.string().optional(),connected_source_port_ids:h.array(h.string()).optional(),selectors_not_found:h.array(h.string()).optional()}).describe("Occurs when a source trace selector does not match any ports");_t(!0);XD=h.object({type:h.literal("source_property_ignored_warning"),source_property_ignored_warning_id:At("source_property_ignored_warning"),source_component_id:h.string(),property_name:h.string(),subcircuit_id:h.string().optional(),error_type:h.literal("source_property_ignored_warning").default("source_property_ignored_warning"),message:h.string()}).describe("The source property was ignored");_t(!0);lE=h.object({type:h.literal("source_pin_missing_trace_warning"),source_pin_missing_trace_warning_id:At("source_pin_missing_trace_warning"),warning_type:h.literal("source_pin_missing_trace_warning").default("source_pin_missing_trace_warning"),message:h.string(),source_component_id:h.string(),source_port_id:h.string(),subcircuit_id:h.string().optional()}).describe("Warning emitted when a source component pin is missing a trace connection");_t(!0);UD=h.union([G3,V3,jx,H3,$D,W3,q3,Z3,K3,J3,Q3,jD,tE,eE,nE,oE,iE,rE,sE,Cdt,aE,BD,YD,cE,XD,lE]);_t(!0);VD=h.object({type:h.literal("source_port"),pin_number:h.number().optional(),port_hints:h.array(h.string()).optional(),name:h.string(),source_port_id:h.string(),source_component_id:h.string().optional(),source_group_id:h.string().optional(),subcircuit_id:h.string().optional(),subcircuit_connectivity_map_key:h.string().optional()});_t(!0);GD=h.object({type:h.literal("source_trace"),source_trace_id:h.string(),connected_source_port_ids:h.array(h.string()),connected_source_net_ids:h.array(h.string()),subcircuit_id:h.string().optional(),subcircuit_connectivity_map_key:h.string().optional(),max_length:h.number().optional(),min_trace_thickness:h.number().optional(),display_name:h.string().optional()});_t(!0);HD=h.object({type:h.literal("source_group"),source_group_id:h.string(),subcircuit_id:h.string().optional(),parent_subcircuit_id:h.string().optional(),parent_source_group_id:h.string().optional(),is_subcircuit:h.boolean().optional(),show_as_schematic_box:h.boolean().optional(),name:h.string().optional(),was_automatically_named:h.boolean().optional()});_t(!0);WD=h.object({type:h.literal("source_net"),source_net_id:h.string(),name:h.string(),member_source_group_ids:h.array(h.string()),is_power:h.boolean().optional(),is_ground:h.boolean().optional(),is_digital_signal:h.boolean().optional(),is_analog_signal:h.boolean().optional(),is_positive_voltage_source:h.boolean().optional(),trace_width:h.number().optional(),subcircuit_id:h.string().optional(),subcircuit_connectivity_map_key:h.string().optional()});_t(!0);qD=h.object({type:h.literal("source_board"),source_board_id:h.string(),source_group_id:h.string(),title:h.string().optional()}).describe("Defines a board in the source domain");_t(!0);ZD=h.object({type:h.literal("source_pcb_ground_plane"),source_pcb_ground_plane_id:h.string(),source_group_id:h.string(),source_net_id:h.string(),subcircuit_id:h.string().optional()}).describe("Defines a ground plane in the source domain");_t(!0);Im=["top","bottom","inner1","inner2","inner3","inner4","inner5","inner6"],Y3=h.enum(Im),he=Y3.or(h.object({name:Y3})).transform(n=>typeof n=="string"?n:n.name);_t(!0);Zs=h.enum(["top","bottom"]),KD=h.object({type:h.literal("source_manually_placed_via"),source_manually_placed_via_id:h.string(),source_group_id:h.string(),source_net_id:h.string(),subcircuit_id:h.string().optional(),source_trace_id:h.string().optional()}).describe("Defines a via that is manually placed in the source domain");_t(!0);Bx=h.object({type:h.literal("unknown_error_finding_part"),unknown_error_finding_part_id:At("unknown_error_finding_part"),error_type:h.literal("unknown_error_finding_part").default("unknown_error_finding_part"),message:h.string(),source_component_id:h.string().optional(),subcircuit_id:h.string().optional()}).describe("Error emitted when an unexpected error occurs while finding a part");_t(!0);JD=h.object({type:h.literal("schematic_box"),schematic_component_id:h.string().optional(),width:X,height:X,is_dashed:h.boolean().default(!1),x:X,y:X,subcircuit_id:h.string().optional()}).describe("Draws a box on the schematic");_t(!0);QD=h.object({type:h.literal("schematic_path"),schematic_component_id:h.string(),fill_color:h.enum(["red","blue"]).optional(),is_filled:h.boolean().optional(),points:h.array(Jt),subcircuit_id:h.string().optional()});_t(!0);t$=h.record(h.object({left_margin:$.optional(),right_margin:$.optional(),top_margin:$.optional(),bottom_margin:$.optional()})),e$=h.object({left_size:h.number(),right_size:h.number(),top_size:h.number().optional(),bottom_size:h.number().optional()});_t(!0);n$=h.object({left_side:h.object({pins:h.array(h.number()),direction:h.enum(["top-to-bottom","bottom-to-top"]).optional()}).optional(),right_side:h.object({pins:h.array(h.number()),direction:h.enum(["top-to-bottom","bottom-to-top"]).optional()}).optional(),top_side:h.object({pins:h.array(h.number()),direction:h.enum(["left-to-right","right-to-left"]).optional()}).optional(),bottom_side:h.object({pins:h.array(h.number()),direction:h.enum(["left-to-right","right-to-left"]).optional()}).optional()});_t(!0);i$=h.union([e$,n$]),r$=h.object({type:h.literal("schematic_component"),size:U3,center:Jt,source_component_id:h.string().optional(),schematic_component_id:h.string(),pin_spacing:$.optional(),pin_styles:t$.optional(),box_width:$.optional(),symbol_name:h.string().optional(),port_arrangement:i$.optional(),port_labels:h.record(h.string()).optional(),symbol_display_value:h.string().optional(),subcircuit_id:h.string().optional(),schematic_group_id:h.string().optional(),is_schematic_group:h.boolean().optional(),source_group_id:h.string().optional(),is_box_with_pins:h.boolean().optional().default(!0)});_t(!0);s$=h.object({type:h.literal("schematic_line"),schematic_line_id:At("schematic_line"),schematic_component_id:h.string(),x1:X,y1:X,x2:X,y2:X,stroke_width:X.nullable().optional(),color:h.string().default("#000000"),is_dashed:h.boolean().default(!1),subcircuit_id:h.string().optional()}).describe("Draws a styled line on the schematic");_t(!0);o$=h.object({type:h.literal("schematic_rect"),schematic_rect_id:At("schematic_rect"),schematic_component_id:h.string(),center:Jt,width:X,height:X,rotation:He.default(0),stroke_width:X.nullable().optional(),color:h.string().default("#000000"),is_filled:h.boolean().default(!1),fill_color:h.string().optional(),is_dashed:h.boolean().default(!1),subcircuit_id:h.string().optional()}).describe("Draws a styled rectangle on the schematic");_t(!0);a$=h.object({type:h.literal("schematic_circle"),schematic_circle_id:At("schematic_circle"),schematic_component_id:h.string(),center:Jt,radius:X,stroke_width:X.nullable().optional(),color:h.string().default("#000000"),is_filled:h.boolean().default(!1),fill_color:h.string().optional(),is_dashed:h.boolean().default(!1),subcircuit_id:h.string().optional()}).describe("Draws a styled circle on the schematic");_t(!0);c$=h.object({type:h.literal("schematic_arc"),schematic_arc_id:At("schematic_arc"),schematic_component_id:h.string(),center:Jt,radius:X,start_angle_degrees:He,end_angle_degrees:He,direction:h.enum(["clockwise","counterclockwise"]).default("counterclockwise"),stroke_width:X.nullable().optional(),color:h.string().default("#000000"),is_dashed:h.boolean().default(!1),subcircuit_id:h.string().optional()}).describe("Draws a styled arc on the schematic");_t(!0);l$=h.object({type:h.literal("schematic_trace"),schematic_trace_id:h.string(),source_trace_id:h.string().optional(),junctions:h.array(h.object({x:h.number(),y:h.number()})),edges:h.array(h.object({from:h.object({x:h.number(),y:h.number()}),to:h.object({x:h.number(),y:h.number()}),is_crossing:h.boolean().optional(),from_schematic_port_id:h.string().optional(),to_schematic_port_id:h.string().optional()})),subcircuit_id:h.string().optional(),subcircuit_connectivity_map_key:h.string().optional()});_t(!0);Idt=h.enum(["center","left","right","top","bottom"]);_t(!0);u$=h.object({type:h.literal("schematic_text"),schematic_component_id:h.string().optional(),schematic_text_id:h.string(),text:h.string(),font_size:h.number().default(.18),position:h.object({x:X,y:X}),rotation:h.number().default(0),anchor:h.union([Idt.describe("legacy"),ng]).default("center"),color:h.string().default("#000000"),subcircuit_id:h.string().optional()});_t(!0);p$=h.object({type:h.literal("schematic_port"),schematic_port_id:h.string(),source_port_id:h.string(),schematic_component_id:h.string().optional(),center:Jt,facing_direction:h.enum(["up","down","left","right"]).optional(),distance_from_component_edge:h.number().optional(),side_of_component:h.enum(["top","bottom","left","right"]).optional(),true_ccw_index:h.number().optional(),pin_number:h.number().optional(),display_pin_label:h.string().optional(),subcircuit_id:h.string().optional(),is_connected:h.boolean().optional(),has_input_arrow:h.boolean().optional(),has_output_arrow:h.boolean().optional()}).describe("Defines a port on a schematic component");_t(!0);h$=h.object({type:h.literal("schematic_net_label"),schematic_net_label_id:At("schematic_net_label"),schematic_trace_id:h.string().optional(),source_trace_id:h.string().optional(),source_net_id:h.string(),center:Jt,anchor_position:Jt.optional(),anchor_side:h.enum(["top","bottom","left","right"]),text:h.string(),symbol_name:h.string().optional(),is_movable:h.boolean().optional(),subcircuit_id:h.string().optional()});_t(!0);d$=h.object({type:h.literal("schematic_error"),schematic_error_id:h.string(),error_type:h.literal("schematic_port_not_found").default("schematic_port_not_found"),message:h.string(),subcircuit_id:h.string().optional()}).describe("Defines a schematic error on the schematic");_t(!0);f$=h.object({type:h.literal("schematic_layout_error"),schematic_layout_error_id:At("schematic_layout_error"),error_type:h.literal("schematic_layout_error").default("schematic_layout_error"),message:h.string(),source_group_id:h.string(),schematic_group_id:h.string(),subcircuit_id:h.string().optional()}).describe("Error emitted when schematic layout fails for a group");_t(!0);Yx=h.object({type:h.literal("schematic_debug_object"),label:h.string().optional(),subcircuit_id:h.string().optional()}),m$=Yx.extend({shape:h.literal("rect"),center:Jt,size:U3}),_$=Yx.extend({shape:h.literal("line"),start:Jt,end:Jt}),y$=Yx.extend({shape:h.literal("point"),center:Jt}),g$=h.discriminatedUnion("shape",[m$,_$,y$]);_t(!0);x$=h.object({type:h.literal("schematic_voltage_probe"),schematic_voltage_probe_id:h.string(),position:Jt,schematic_trace_id:h.string(),voltage:Si.optional(),subcircuit_id:h.string().optional()}).describe("Defines a voltage probe measurement point on a schematic trace");_t(!0);Xx=h.object({type:h.literal("schematic_manual_edit_conflict_warning"),schematic_manual_edit_conflict_warning_id:At("schematic_manual_edit_conflict_warning"),warning_type:h.literal("schematic_manual_edit_conflict_warning").default("schematic_manual_edit_conflict_warning"),message:h.string(),schematic_component_id:h.string(),schematic_group_id:h.string().optional(),subcircuit_id:h.string().optional(),source_component_id:h.string()}).describe("Warning emitted when a component has both manual placement and explicit schX/schY coordinates");_t(!0);b$=h.object({type:h.literal("schematic_group"),schematic_group_id:At("schematic_group"),source_group_id:h.string(),is_subcircuit:h.boolean().optional(),subcircuit_id:h.string().optional(),width:$,height:$,center:Jt,schematic_component_ids:h.array(h.string()),show_as_schematic_box:h.boolean().optional(),name:h.string().optional(),description:h.string().optional()}).describe("Defines a group of components on the schematic");_t(!0);v$=h.object({type:h.literal("schematic_table"),schematic_table_id:At("schematic_table"),anchor_position:Jt,column_widths:h.array(X),row_heights:h.array(X),cell_padding:X.optional(),border_width:X.optional(),subcircuit_id:h.string().optional(),schematic_component_id:h.string().optional(),anchor:ng.optional()}).describe("Defines a table on the schematic");_t(!0);w$=h.object({type:h.literal("schematic_table_cell"),schematic_table_cell_id:At("schematic_table_cell"),schematic_table_id:h.string(),start_row_index:h.number(),end_row_index:h.number(),start_column_index:h.number(),end_column_index:h.number(),text:h.string().optional(),center:Jt,width:X,height:X,horizontal_align:h.enum(["left","center","right"]).optional(),vertical_align:h.enum(["top","middle","bottom"]).optional(),font_size:X.optional(),subcircuit_id:h.string().optional()}).describe("Defines a cell within a schematic_table");_t(!0);S$=h.object({type:h.literal("schematic_sheet"),schematic_sheet_id:At("schematic_sheet"),name:h.string().optional(),subcircuit_id:h.string().optional()}).describe("Defines a schematic sheet or page that components can be placed on");_t(!0);P$=h.object({x:X,y:X,bulge:h.number().optional()});_t(!0);X3=h.object({vertices:h.array(P$)});_t(!0);k$=h.object({outer_ring:X3,inner_rings:h.array(X3).default([])});_t(!0);T$=h.object({x:X,y:X,via:h.boolean().optional(),via_to_layer:he.optional()}),Ndt=h.array(T$);_t(!0);_t(!0);Ji=h.object({x:X,y:X,via:h.boolean().optional(),to_layer:he.optional(),trace_width:X.optional()});_t(!0);E$=h.object({type:h.literal("pcb_component"),pcb_component_id:At("pcb_component"),source_component_id:h.string(),center:Jt,layer:he,rotation:He,width:$,height:$,do_not_place:h.boolean().optional(),subcircuit_id:h.string().optional(),pcb_group_id:h.string().optional(),position_mode:h.enum(["packed","relative_to_group_anchor","none"]).optional(),positioned_relative_to_pcb_group_id:h.string().optional(),obstructs_within_bounds:h.boolean().default(!0).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");_t(!0);M$=h.object({type:h.literal("pcb_hole"),pcb_hole_id:At("pcb_hole"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),hole_shape:h.literal("circle"),hole_diameter:h.number(),x:X,y:X}),Adt=M$.describe("Defines a circular hole on the PCB");_t(!0);C$=h.object({type:h.literal("pcb_hole"),pcb_hole_id:At("pcb_hole"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),hole_shape:h.literal("rect"),hole_width:h.number(),hole_height:h.number(),x:X,y:X}),Rdt=C$.describe("Defines a rectangular (square-capable) hole on the PCB. Use equal width/height for square.");_t(!0);I$=h.object({type:h.literal("pcb_hole"),pcb_hole_id:At("pcb_hole"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),hole_shape:h.enum(["circle","square"]),hole_diameter:h.number(),x:X,y:X}),Odt=I$.describe("Defines a circular or square hole on the PCB");_t(!0);N$=h.object({type:h.literal("pcb_hole"),pcb_hole_id:At("pcb_hole"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),hole_shape:h.literal("oval"),hole_width:h.number(),hole_height:h.number(),x:X,y:X}),Ldt=N$.describe("Defines an oval hole on the PCB");_t(!0);A$=h.object({type:h.literal("pcb_hole"),pcb_hole_id:At("pcb_hole"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),hole_shape:h.literal("pill"),hole_width:h.number(),hole_height:h.number(),x:X,y:X}),Fdt=A$.describe("Defines a pill-shaped hole on the PCB");_t(!0);R$=h.object({type:h.literal("pcb_hole"),pcb_hole_id:At("pcb_hole"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),hole_shape:h.literal("rotated_pill"),hole_width:h.number(),hole_height:h.number(),x:X,y:X,ccw_rotation:He}),zdt=R$.describe("Defines a rotated pill-shaped hole on the PCB");_t(!0);O$=I$.or(N$).or(A$).or(R$).or(M$).or(C$),Ddt=h.object({type:h.literal("pcb_plated_hole"),shape:h.literal("circle"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),outer_diameter:h.number(),hole_diameter:h.number(),x:X,y:X,layers:h.array(he),port_hints:h.array(h.string()).optional(),pcb_component_id:h.string().optional(),pcb_port_id:h.string().optional(),pcb_plated_hole_id:At("pcb_plated_hole")}),$dt=h.object({type:h.literal("pcb_plated_hole"),shape:h.enum(["oval","pill"]),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),outer_width:h.number(),outer_height:h.number(),hole_width:h.number(),hole_height:h.number(),x:X,y:X,ccw_rotation:He,layers:h.array(he),port_hints:h.array(h.string()).optional(),pcb_component_id:h.string().optional(),pcb_port_id:h.string().optional(),pcb_plated_hole_id:At("pcb_plated_hole")}),jdt=h.object({type:h.literal("pcb_plated_hole"),shape:h.literal("circular_hole_with_rect_pad"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),hole_shape:h.literal("circle"),pad_shape:h.literal("rect"),hole_diameter:h.number(),rect_pad_width:h.number(),rect_pad_height:h.number(),rect_border_radius:h.number().optional(),hole_offset_x:X.default(0),hole_offset_y:X.default(0),x:X,y:X,layers:h.array(he),port_hints:h.array(h.string()).optional(),pcb_component_id:h.string().optional(),pcb_port_id:h.string().optional(),pcb_plated_hole_id:At("pcb_plated_hole")}),Bdt=h.object({type:h.literal("pcb_plated_hole"),shape:h.literal("pill_hole_with_rect_pad"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),hole_shape:h.literal("pill"),pad_shape:h.literal("rect"),hole_width:h.number(),hole_height:h.number(),rect_pad_width:h.number(),rect_pad_height:h.number(),rect_border_radius:h.number().optional(),hole_offset_x:X.default(0),hole_offset_y:X.default(0),x:X,y:X,layers:h.array(he),port_hints:h.array(h.string()).optional(),pcb_component_id:h.string().optional(),pcb_port_id:h.string().optional(),pcb_plated_hole_id:At("pcb_plated_hole")}),Ydt=h.object({type:h.literal("pcb_plated_hole"),shape:h.literal("rotated_pill_hole_with_rect_pad"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),hole_shape:h.literal("rotated_pill"),pad_shape:h.literal("rect"),hole_width:h.number(),hole_height:h.number(),hole_ccw_rotation:He,rect_pad_width:h.number(),rect_pad_height:h.number(),rect_border_radius:h.number().optional(),rect_ccw_rotation:He,hole_offset_x:X.default(0),hole_offset_y:X.default(0),x:X,y:X,layers:h.array(he),port_hints:h.array(h.string()).optional(),pcb_component_id:h.string().optional(),pcb_port_id:h.string().optional(),pcb_plated_hole_id:At("pcb_plated_hole")}),L$=h.union([Ddt,$dt,jdt,Bdt,Ydt]);_t(!0);_t(!0);_t(!0);_t(!0);_t(!0);F$=h.object({type:h.literal("pcb_port"),pcb_port_id:At("pcb_port"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),source_port_id:h.string(),pcb_component_id:h.string().optional(),x:X,y:X,layers:h.array(he),is_board_pinout:h.boolean().optional()}).describe("Defines a port on the PCB");_t(!0);Xdt=h.object({type:h.literal("pcb_smtpad"),shape:h.literal("circle"),pcb_smtpad_id:At("pcb_smtpad"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),x:X,y:X,radius:h.number(),layer:he,port_hints:h.array(h.string()).optional(),pcb_component_id:h.string().optional(),pcb_port_id:h.string().optional(),is_covered_with_solder_mask:h.boolean().optional()}),Udt=h.object({type:h.literal("pcb_smtpad"),shape:h.literal("rect"),pcb_smtpad_id:At("pcb_smtpad"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),x:X,y:X,width:h.number(),height:h.number(),rect_border_radius:h.number().optional(),corner_radius:h.number().optional(),layer:he,port_hints:h.array(h.string()).optional(),pcb_component_id:h.string().optional(),pcb_port_id:h.string().optional(),is_covered_with_solder_mask:h.boolean().optional()}),Vdt=h.object({type:h.literal("pcb_smtpad"),shape:h.literal("rotated_rect"),pcb_smtpad_id:At("pcb_smtpad"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),x:X,y:X,width:h.number(),height:h.number(),rect_border_radius:h.number().optional(),corner_radius:h.number().optional(),ccw_rotation:He,layer:he,port_hints:h.array(h.string()).optional(),pcb_component_id:h.string().optional(),pcb_port_id:h.string().optional(),is_covered_with_solder_mask:h.boolean().optional()}),z$=h.object({type:h.literal("pcb_smtpad"),shape:h.literal("pill"),pcb_smtpad_id:At("pcb_smtpad"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),x:X,y:X,width:h.number(),height:h.number(),radius:h.number(),layer:he,port_hints:h.array(h.string()).optional(),pcb_component_id:h.string().optional(),pcb_port_id:h.string().optional(),is_covered_with_solder_mask:h.boolean().optional()}),Gdt=h.object({type:h.literal("pcb_smtpad"),shape:h.literal("rotated_pill"),pcb_smtpad_id:At("pcb_smtpad"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),x:X,y:X,width:h.number(),height:h.number(),radius:h.number(),ccw_rotation:He,layer:he,port_hints:h.array(h.string()).optional(),pcb_component_id:h.string().optional(),pcb_port_id:h.string().optional(),is_covered_with_solder_mask:h.boolean().optional()}),Hdt=h.object({type:h.literal("pcb_smtpad"),shape:h.literal("polygon"),pcb_smtpad_id:At("pcb_smtpad"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),points:h.array(Jt),layer:he,port_hints:h.array(h.string()).optional(),pcb_component_id:h.string().optional(),pcb_port_id:h.string().optional(),is_covered_with_solder_mask:h.boolean().optional()}),D$=h.discriminatedUnion("shape",[Xdt,Udt,Vdt,Gdt,z$,Hdt]).describe("Defines an SMT pad on the PCB");_t(!0);_t(!0);_t(!0);_t(!0);_t(!0);_t(!0);Wdt=h.object({type:h.literal("pcb_solder_paste"),shape:h.literal("circle"),pcb_solder_paste_id:At("pcb_solder_paste"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),x:X,y:X,radius:h.number(),layer:he,pcb_component_id:h.string().optional(),pcb_smtpad_id:h.string().optional()}),qdt=h.object({type:h.literal("pcb_solder_paste"),shape:h.literal("rect"),pcb_solder_paste_id:At("pcb_solder_paste"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),x:X,y:X,width:h.number(),height:h.number(),layer:he,pcb_component_id:h.string().optional(),pcb_smtpad_id:h.string().optional()}),Zdt=h.object({type:h.literal("pcb_solder_paste"),shape:h.literal("pill"),pcb_solder_paste_id:At("pcb_solder_paste"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),x:X,y:X,width:h.number(),height:h.number(),radius:h.number(),layer:he,pcb_component_id:h.string().optional(),pcb_smtpad_id:h.string().optional()}),Kdt=h.object({type:h.literal("pcb_solder_paste"),shape:h.literal("rotated_rect"),pcb_solder_paste_id:At("pcb_solder_paste"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),x:X,y:X,width:h.number(),height:h.number(),ccw_rotation:X,layer:he,pcb_component_id:h.string().optional(),pcb_smtpad_id:h.string().optional()}),Jdt=h.object({type:h.literal("pcb_solder_paste"),shape:h.literal("oval"),pcb_solder_paste_id:At("pcb_solder_paste"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),x:X,y:X,width:h.number(),height:h.number(),layer:he,pcb_component_id:h.string().optional(),pcb_smtpad_id:h.string().optional()}),$$=h.union([Wdt,qdt,Zdt,Kdt,Jdt]).describe("Defines solderpaste on the PCB");_t(!0);_t(!0);_t(!0);_t(!0);_t(!0);j$=h.object({type:h.literal("pcb_text"),pcb_text_id:At("pcb_text"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),text:h.string(),center:Jt,layer:he,width:$,height:$,lines:h.number(),align:h.enum(["bottom-left"])}).describe("Defines text on the PCB");_t(!0);B$=h.object({route_type:h.literal("wire"),x:X,y:X,width:X,start_pcb_port_id:h.string().optional(),end_pcb_port_id:h.string().optional(),layer:he}),Y$=h.object({route_type:h.literal("via"),x:X,y:X,hole_diameter:X.optional(),outer_diameter:X.optional(),from_layer:h.string(),to_layer:h.string()}),Ux=h.union([B$,Y$]),X$=h.object({type:h.literal("pcb_trace"),source_trace_id:h.string().optional(),pcb_component_id:h.string().optional(),pcb_trace_id:At("pcb_trace"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),route_thickness_mode:h.enum(["constant","interpolated"]).default("constant").optional(),route_order_index:h.number().optional(),should_round_corners:h.boolean().optional(),trace_length:h.number().optional(),highlight_color:h.string().optional(),route:h.array(Ux)}).describe("Defines a trace on the PCB");_t(!0);_t(!0);U$=h.object({type:h.literal("pcb_trace_error"),pcb_trace_error_id:At("pcb_trace_error"),error_type:h.literal("pcb_trace_error").default("pcb_trace_error"),message:h.string(),center:Jt.optional(),pcb_trace_id:h.string(),source_trace_id:h.string(),pcb_component_ids:h.array(h.string()),pcb_port_ids:h.array(h.string()),subcircuit_id:h.string().optional()}).describe("Defines a trace error on the PCB");_t(!0);V$=h.object({type:h.literal("pcb_trace_missing_error"),pcb_trace_missing_error_id:At("pcb_trace_missing_error"),error_type:h.literal("pcb_trace_missing_error").default("pcb_trace_missing_error"),message:h.string(),center:Jt.optional(),source_trace_id:h.string(),pcb_component_ids:h.array(h.string()),pcb_port_ids:h.array(h.string()),subcircuit_id:h.string().optional()}).describe("Defines an error when a source trace has no corresponding PCB trace");_t(!0);G$=h.object({type:h.literal("pcb_port_not_matched_error"),pcb_error_id:At("pcb_error"),error_type:h.literal("pcb_port_not_matched_error").default("pcb_port_not_matched_error"),message:h.string(),pcb_component_ids:h.array(h.string()),subcircuit_id:h.string().optional()}).describe("Defines a trace error on the PCB where a port is not matched");_t(!0);H$=h.object({type:h.literal("pcb_port_not_connected_error"),pcb_port_not_connected_error_id:At("pcb_port_not_connected_error"),error_type:h.literal("pcb_port_not_connected_error").default("pcb_port_not_connected_error"),message:h.string(),pcb_port_ids:h.array(h.string()),pcb_component_ids:h.array(h.string()),subcircuit_id:h.string().optional()}).describe("Defines an error when a pcb port is not connected to any trace");_t(!0);W$=h.object({type:h.literal("pcb_net"),pcb_net_id:At("pcb_net"),source_net_id:h.string().optional(),highlight_color:h.string().optional()}).describe("Defines a net on the PCB");_t(!0);q$=h.object({type:h.literal("pcb_via"),pcb_via_id:At("pcb_via"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),subcircuit_connectivity_map_key:h.string().optional(),x:X,y:X,outer_diameter:X.default("0.6mm"),hole_diameter:X.default("0.25mm"),from_layer:he.optional(),to_layer:he.optional(),layers:h.array(he),pcb_trace_id:h.string().optional(),net_is_assignable:h.boolean().optional(),net_assigned:h.boolean().optional()}).describe("Defines a via on the PCB");_t(!0);Z$=h.object({type:h.literal("pcb_board"),pcb_board_id:At("pcb_board"),pcb_panel_id:h.string().optional(),is_subcircuit:h.boolean().optional(),subcircuit_id:h.string().optional(),width:$.optional(),height:$.optional(),center:Jt,thickness:$.optional().default(1.4),num_layers:h.number().optional().default(4),outline:h.array(Jt).optional(),shape:h.enum(["rect","polygon"]).optional(),material:h.enum(["fr4","fr1"]).default("fr4")}).describe("Defines the board outline of the PCB");_t(!0);K$=h.object({type:h.literal("pcb_panel"),pcb_panel_id:At("pcb_panel"),width:$,height:$,covered_with_solder_mask:h.boolean().optional().default(!0)}).describe("Defines a PCB panel that can contain multiple boards");_t(!0);J$=h.object({type:h.literal("pcb_placement_error"),pcb_placement_error_id:At("pcb_placement_error"),error_type:h.literal("pcb_placement_error").default("pcb_placement_error"),message:h.string(),subcircuit_id:h.string().optional()}).describe("Defines a placement error on the PCB");_t(!0);Q$=h.object({type:h.literal("pcb_trace_hint"),pcb_trace_hint_id:At("pcb_trace_hint"),pcb_port_id:h.string(),pcb_component_id:h.string(),route:h.array(Ji),subcircuit_id:h.string().optional()}).describe("A hint that can be used during generation of a PCB trace");_t(!0);tj=h.object({type:h.literal("pcb_silkscreen_line"),pcb_silkscreen_line_id:At("pcb_silkscreen_line"),pcb_component_id:h.string(),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),stroke_width:X.default("0.1mm"),x1:X,y1:X,x2:X,y2:X,layer:Zs}).describe("Defines a silkscreen line on the PCB");_t(!0);ej=h.object({type:h.literal("pcb_silkscreen_path"),pcb_silkscreen_path_id:At("pcb_silkscreen_path"),pcb_component_id:h.string(),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),layer:Zs,route:h.array(Jt),stroke_width:$}).describe("Defines a silkscreen path on the PCB");_t(!0);nj=h.object({type:h.literal("pcb_silkscreen_text"),pcb_silkscreen_text_id:At("pcb_silkscreen_text"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),font:h.literal("tscircuit2024").default("tscircuit2024"),font_size:X.default("0.2mm"),pcb_component_id:h.string(),text:h.string(),is_knockout:h.boolean().default(!1).optional(),knockout_padding:h.object({left:$,top:$,bottom:$,right:$}).default({left:"0.2mm",top:"0.2mm",bottom:"0.2mm",right:"0.2mm"}).optional(),ccw_rotation:h.number().optional(),layer:he,is_mirrored:h.boolean().default(!1).optional(),anchor_position:Jt.default({x:0,y:0}),anchor_alignment:ng.default("center")}).describe("Defines silkscreen text on the PCB");_t(!0);ij=h.object({type:h.literal("pcb_copper_text"),pcb_copper_text_id:At("pcb_copper_text"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),font:h.literal("tscircuit2024").default("tscircuit2024"),font_size:X.default("0.2mm"),pcb_component_id:h.string(),text:h.string(),is_knockout:h.boolean().default(!1).optional(),knockout_padding:h.object({left:$,top:$,bottom:$,right:$}).default({left:"0.2mm",top:"0.2mm",bottom:"0.2mm",right:"0.2mm"}).optional(),ccw_rotation:h.number().optional(),layer:he,is_mirrored:h.boolean().default(!1).optional(),anchor_position:Jt.default({x:0,y:0}),anchor_alignment:ng.default("center")}).describe("Defines copper text on the PCB");_t(!0);rj=h.object({type:h.literal("pcb_silkscreen_rect"),pcb_silkscreen_rect_id:At("pcb_silkscreen_rect"),pcb_component_id:h.string(),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),center:Jt,width:$,height:$,layer:he,stroke_width:$.default("1mm"),corner_radius:$.optional(),is_filled:h.boolean().default(!0).optional(),has_stroke:h.boolean().optional(),is_stroke_dashed:h.boolean().optional()}).describe("Defines a silkscreen rect on the PCB");_t(!0);sj=h.object({type:h.literal("pcb_silkscreen_circle"),pcb_silkscreen_circle_id:At("pcb_silkscreen_circle"),pcb_component_id:h.string(),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),center:Jt,radius:$,layer:Zs,stroke_width:$.default("1mm")}).describe("Defines a silkscreen circle on the PCB");_t(!0);oj=h.object({type:h.literal("pcb_silkscreen_oval"),pcb_silkscreen_oval_id:At("pcb_silkscreen_oval"),pcb_component_id:h.string(),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),center:Jt,radius_x:X,radius_y:X,layer:Zs}).describe("Defines a silkscreen oval on the PCB");_t(!0);aj=h.object({type:h.literal("pcb_fabrication_note_text"),pcb_fabrication_note_text_id:At("pcb_fabrication_note_text"),subcircuit_id:h.string().optional(),pcb_group_id:h.string().optional(),font:h.literal("tscircuit2024").default("tscircuit2024"),font_size:X.default("1mm"),pcb_component_id:h.string(),text:h.string(),layer:Zs,anchor_position:Jt.default({x:0,y:0}),anchor_alignment:h.enum(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),color:h.string().optional()}).describe("Defines a fabrication note in text on the PCB, useful for leaving notes for assemblers or fabricators");_t(!0);cj=h.object({type:h.literal("pcb_fabrication_note_path"),pcb_fabrication_note_path_id:At("pcb_fabrication_note_path"),pcb_component_id:h.string(),subcircuit_id:h.string().optional(),layer:he,route:h.array(Jt),stroke_width:$,color:h.string().optional()}).describe("Defines a fabrication path on the PCB for fabricators or assemblers");_t(!0);lj=h.object({type:h.literal("pcb_fabrication_note_rect"),pcb_fabrication_note_rect_id:At("pcb_fabrication_note_rect"),pcb_component_id:h.string(),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),center:Jt,width:$,height:$,layer:Zs,stroke_width:$.default("0.1mm"),corner_radius:$.optional(),is_filled:h.boolean().optional(),has_stroke:h.boolean().optional(),is_stroke_dashed:h.boolean().optional(),color:h.string().optional()}).describe("Defines a fabrication note rectangle on the PCB");_t(!0);uj=h.object({type:h.literal("pcb_fabrication_note_dimension"),pcb_fabrication_note_dimension_id:At("pcb_fabrication_note_dimension"),pcb_component_id:h.string(),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),layer:Zs,from:Jt,to:Jt,text:h.string().optional(),text_ccw_rotation:h.number().optional(),offset:$.optional(),offset_distance:$.optional(),offset_direction:h.object({x:h.number(),y:h.number()}).optional(),font:h.literal("tscircuit2024").default("tscircuit2024"),font_size:$.default("1mm"),color:h.string().optional(),arrow_size:$.default("1mm")}).describe("Defines a measurement annotation within PCB fabrication notes");_t(!0);pj=h.object({type:h.literal("pcb_note_text"),pcb_note_text_id:At("pcb_note_text"),pcb_component_id:h.string().optional(),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),name:h.string().optional(),font:h.literal("tscircuit2024").default("tscircuit2024"),font_size:X.default("1mm"),text:h.string().optional(),anchor_position:Jt.default({x:0,y:0}),anchor_alignment:h.enum(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),color:h.string().optional()}).describe("Defines a documentation note in text on the PCB");_t(!0);hj=h.object({type:h.literal("pcb_note_rect"),pcb_note_rect_id:At("pcb_note_rect"),pcb_component_id:h.string().optional(),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),name:h.string().optional(),text:h.string().optional(),center:Jt,width:$,height:$,stroke_width:$.default("0.1mm"),corner_radius:$.optional(),is_filled:h.boolean().optional(),has_stroke:h.boolean().optional(),is_stroke_dashed:h.boolean().optional(),color:h.string().optional()}).describe("Defines a rectangular documentation note on the PCB");_t(!0);dj=h.object({type:h.literal("pcb_note_path"),pcb_note_path_id:At("pcb_note_path"),pcb_component_id:h.string().optional(),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),name:h.string().optional(),text:h.string().optional(),route:h.array(Jt),stroke_width:$.default("0.1mm"),color:h.string().optional()}).describe("Defines a polyline documentation note on the PCB");_t(!0);fj=h.object({type:h.literal("pcb_note_line"),pcb_note_line_id:At("pcb_note_line"),pcb_component_id:h.string().optional(),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),name:h.string().optional(),text:h.string().optional(),x1:X,y1:X,x2:X,y2:X,stroke_width:X.default("0.1mm"),color:h.string().optional(),is_dashed:h.boolean().optional()}).describe("Defines a straight documentation note line on the PCB");_t(!0);mj=h.object({type:h.literal("pcb_note_dimension"),pcb_note_dimension_id:At("pcb_note_dimension"),pcb_component_id:h.string().optional(),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),name:h.string().optional(),from:Jt,to:Jt,text:h.string().optional(),text_ccw_rotation:h.number().optional(),offset_distance:$.optional(),offset_direction:h.object({x:h.number(),y:h.number()}).optional(),font:h.literal("tscircuit2024").default("tscircuit2024"),font_size:$.default("1mm"),color:h.string().optional(),arrow_size:$.default("1mm")}).describe("Defines a measurement annotation within PCB documentation notes");_t(!0);_j=h.object({type:h.literal("pcb_footprint_overlap_error"),pcb_error_id:At("pcb_error"),error_type:h.literal("pcb_footprint_overlap_error").default("pcb_footprint_overlap_error"),message:h.string(),pcb_smtpad_ids:h.array(h.string()).optional(),pcb_plated_hole_ids:h.array(h.string()).optional(),pcb_hole_ids:h.array(h.string()).optional(),pcb_keepout_ids:h.array(h.string()).optional()}).describe("Error emitted when a pcb footprint overlaps with another element");_t(!0);yj=h.object({type:h.literal("pcb_keepout"),shape:h.literal("rect"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),center:Jt,width:X,height:X,pcb_keepout_id:h.string(),layers:h.array(h.string()),description:h.string().optional()}).or(h.object({type:h.literal("pcb_keepout"),shape:h.literal("circle"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),center:Jt,radius:X,pcb_keepout_id:h.string(),layers:h.array(h.string()),description:h.string().optional()}));_t(!0);uE=h.object({type:h.literal("pcb_cutout"),pcb_cutout_id:At("pcb_cutout"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional()}),gj=uE.extend({shape:h.literal("rect"),center:Jt,width:$,height:$,rotation:He.optional()});_t(!0);xj=uE.extend({shape:h.literal("circle"),center:Jt,radius:$});_t(!0);bj=uE.extend({shape:h.literal("polygon"),points:h.array(Jt)});_t(!0);vj=h.discriminatedUnion("shape",[gj,xj,bj]).describe("Defines a cutout on the PCB, removing board material.");_t(!0);wj=h.object({type:h.literal("pcb_missing_footprint_error"),pcb_missing_footprint_error_id:At("pcb_missing_footprint_error"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),error_type:h.literal("pcb_missing_footprint_error").default("pcb_missing_footprint_error"),source_component_id:h.string(),message:h.string()}).describe("Defines a missing footprint error on the PCB");_t(!0);Nm=h.object({type:h.literal("external_footprint_load_error"),external_footprint_load_error_id:At("external_footprint_load_error"),pcb_component_id:h.string(),source_component_id:h.string(),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),footprinter_string:h.string().optional(),error_type:h.literal("external_footprint_load_error").default("external_footprint_load_error"),message:h.string()}).describe("Defines an error when an external footprint fails to load");_t(!0);Vx=h.object({type:h.literal("circuit_json_footprint_load_error"),circuit_json_footprint_load_error_id:At("circuit_json_footprint_load_error"),pcb_component_id:h.string(),source_component_id:h.string(),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),error_type:h.literal("circuit_json_footprint_load_error").default("circuit_json_footprint_load_error"),message:h.string(),circuit_json:h.array(h.any()).optional()}).describe("Defines an error when a circuit JSON footprint fails to load");_t(!0);Sj=h.object({type:h.literal("pcb_group"),pcb_group_id:At("pcb_group"),source_group_id:h.string(),is_subcircuit:h.boolean().optional(),subcircuit_id:h.string().optional(),width:$.optional(),height:$.optional(),center:Jt,outline:h.array(Jt).optional(),anchor_position:Jt.optional(),anchor_alignment:h.enum(["center","top_left","top_right","bottom_left","bottom_right"]).optional(),pcb_component_ids:h.array(h.string()),child_layout_mode:h.enum(["packed","none"]).optional(),name:h.string().optional(),description:h.string().optional(),layout_mode:h.string().optional(),autorouter_configuration:h.object({trace_clearance:$}).optional(),autorouter_used_string:h.string().optional()}).describe("Defines a group of components on the PCB");_t(!0);Pj=h.object({type:h.literal("pcb_autorouting_error"),pcb_error_id:At("pcb_autorouting_error"),error_type:h.literal("pcb_autorouting_error").default("pcb_autorouting_error"),message:h.string(),subcircuit_id:h.string().optional()}).describe("The autorouting has failed to route a portion of the board");_t(!0);Gx=h.object({type:h.literal("pcb_manual_edit_conflict_warning"),pcb_manual_edit_conflict_warning_id:At("pcb_manual_edit_conflict_warning"),warning_type:h.literal("pcb_manual_edit_conflict_warning").default("pcb_manual_edit_conflict_warning"),message:h.string(),pcb_component_id:h.string(),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),source_component_id:h.string()}).describe("Warning emitted when a component has both manual placement and explicit pcbX/pcbY coordinates");_t(!0);kj=h.object({type:h.literal("pcb_breakout_point"),pcb_breakout_point_id:At("pcb_breakout_point"),pcb_group_id:h.string(),subcircuit_id:h.string().optional(),source_trace_id:h.string().optional(),source_port_id:h.string().optional(),source_net_id:h.string().optional(),x:X,y:X}).describe("Defines a routing target within a pcb_group for a source_trace or source_net");_t(!0);Tj=h.object({type:h.literal("pcb_ground_plane"),pcb_ground_plane_id:At("pcb_ground_plane"),source_pcb_ground_plane_id:h.string(),source_net_id:h.string(),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional()}).describe("Defines a ground plane on the PCB");_t(!0);Ej=h.object({type:h.literal("pcb_ground_plane_region"),pcb_ground_plane_region_id:At("pcb_ground_plane_region"),pcb_ground_plane_id:h.string(),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),layer:he,points:h.array(Jt)}).describe("Defines a polygon region of a ground plane");_t(!0);Mj=h.object({type:h.literal("pcb_thermal_spoke"),pcb_thermal_spoke_id:At("pcb_thermal_spoke"),pcb_ground_plane_id:h.string(),shape:h.string(),spoke_count:h.number(),spoke_thickness:X,spoke_inner_diameter:X,spoke_outer_diameter:X,pcb_plated_hole_id:h.string().optional(),subcircuit_id:h.string().optional()}).describe("Pattern for connecting a ground plane to a plated hole");_t(!0);pE=h.object({type:h.literal("pcb_copper_pour"),pcb_copper_pour_id:At("pcb_copper_pour"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),layer:he,source_net_id:h.string().optional(),covered_with_solder_mask:h.boolean().optional().default(!0)}),Cj=pE.extend({shape:h.literal("rect"),center:Jt,width:$,height:$,rotation:He.optional()});_t(!0);Ij=pE.extend({shape:h.literal("brep"),brep_shape:k$});_t(!0);Nj=pE.extend({shape:h.literal("polygon"),points:h.array(Jt)});_t(!0);Aj=h.discriminatedUnion("shape",[Cj,Ij,Nj]).describe("Defines a copper pour on the PCB.");_t(!0);Rj=h.object({type:h.literal("pcb_component_outside_board_error"),pcb_component_outside_board_error_id:At("pcb_component_outside_board_error"),error_type:h.literal("pcb_component_outside_board_error").default("pcb_component_outside_board_error"),message:h.string(),pcb_component_id:h.string(),pcb_board_id:h.string(),component_center:Jt,component_bounds:h.object({min_x:h.number(),max_x:h.number(),min_y:h.number(),max_y:h.number()}),subcircuit_id:h.string().optional(),source_component_id:h.string().optional()}).describe("Error emitted when a PCB component is placed outside the board boundaries");_t(!0);Am=h.object({type:h.literal("pcb_component_invalid_layer_error"),pcb_component_invalid_layer_error_id:At("pcb_component_invalid_layer_error"),error_type:h.literal("pcb_component_invalid_layer_error").default("pcb_component_invalid_layer_error"),message:h.string(),pcb_component_id:h.string().optional(),source_component_id:h.string(),layer:he,subcircuit_id:h.string().optional()}).describe("Error emitted when a component is placed on an invalid layer (components can only be on 'top' or 'bottom' layers)");_t(!0);Oj=h.object({type:h.literal("pcb_via_clearance_error"),pcb_error_id:At("pcb_error"),error_type:h.literal("pcb_via_clearance_error").default("pcb_via_clearance_error"),message:h.string(),pcb_via_ids:h.array(h.string()).min(2),minimum_clearance:X.optional(),actual_clearance:X.optional(),pcb_center:h.object({x:h.number().optional(),y:h.number().optional()}).optional(),subcircuit_id:h.string().optional()}).describe("Error emitted when vias are closer than the allowed clearance");_t(!0);Lj=h.object({type:h.literal("pcb_courtyard_rect"),pcb_courtyard_rect_id:At("pcb_courtyard_rect"),pcb_component_id:h.string(),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),center:Jt,width:$,height:$,layer:Zs,color:h.string().optional()}).describe("Defines a courtyard rectangle on the PCB");_t(!0);Fj=h.object({type:h.literal("pcb_courtyard_outline"),pcb_courtyard_outline_id:At("pcb_courtyard_outline"),pcb_component_id:h.string(),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),layer:Zs,outline:h.array(Jt).min(2),stroke_width:$.default("0.1mm"),is_closed:h.boolean().optional(),is_stroke_dashed:h.boolean().optional(),color:h.string().optional()}).describe("Defines a courtyard outline on the PCB");_t(!0);zj=h.object({type:h.literal("pcb_courtyard_polygon"),pcb_courtyard_polygon_id:At("pcb_courtyard_polygon"),pcb_component_id:h.string(),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),layer:Zs,points:h.array(Jt).min(3),color:h.string().optional()}).describe("Defines a courtyard polygon on the PCB");_t(!0);Dj=h.object({type:h.literal("cad_component"),cad_component_id:h.string(),pcb_component_id:h.string(),source_component_id:h.string(),position:zh,rotation:zh.optional(),size:zh.optional(),layer:he.optional(),subcircuit_id:h.string().optional(),footprinter_string:h.string().optional(),model_obj_url:h.string().optional(),model_stl_url:h.string().optional(),model_3mf_url:h.string().optional(),model_gltf_url:h.string().optional(),model_glb_url:h.string().optional(),model_step_url:h.string().optional(),model_wrl_url:h.string().optional(),model_unit_to_mm_scale_factor:h.number().optional(),model_jscad:h.any().optional()}).describe("Defines a component on the PCB");_t(!0);$j=h.enum(["sinewave","square","triangle","sawtooth"]),Qdt=h.union([h.string(),h.number()]).transform(n=>typeof n=="string"?n.endsWith("%")?parseFloat(n.slice(0,-1))/100:parseFloat(n):n).pipe(h.number().min(0,"Duty cycle must be non-negative").max(1,"Duty cycle cannot be greater than 100%")),jj=h.object({type:h.literal("simulation_voltage_source"),simulation_voltage_source_id:At("simulation_voltage_source"),is_dc_source:h.literal(!0).optional().default(!0),positive_source_port_id:h.string().optional(),negative_source_port_id:h.string().optional(),positive_source_net_id:h.string().optional(),negative_source_net_id:h.string().optional(),voltage:Si}).describe("Defines a DC voltage source for simulation"),Bj=h.object({type:h.literal("simulation_voltage_source"),simulation_voltage_source_id:At("simulation_voltage_source"),is_dc_source:h.literal(!1),terminal1_source_port_id:h.string().optional(),terminal2_source_port_id:h.string().optional(),terminal1_source_net_id:h.string().optional(),terminal2_source_net_id:h.string().optional(),voltage:Si.optional(),frequency:pr.optional(),peak_to_peak_voltage:Si.optional(),wave_shape:$j.optional(),phase:He.optional(),duty_cycle:Qdt.optional()}).describe("Defines an AC voltage source for simulation"),Yj=h.union([jj,Bj]).describe("Defines a voltage source for simulation");_t(!0);_t(!0);_t(!0);Xj=h.union([h.literal("spice_dc_sweep"),h.literal("spice_dc_operating_point"),h.literal("spice_transient_analysis"),h.literal("spice_ac_analysis")]),Uj=h.object({type:h.literal("simulation_experiment"),simulation_experiment_id:At("simulation_experiment"),name:h.string(),experiment_type:Xj,time_per_step:eg.optional(),start_time_ms:ur.optional(),end_time_ms:ur.optional()}).describe("Defines a simulation experiment configuration");_t(!0);Vj=h.object({type:h.literal("simulation_transient_voltage_graph"),simulation_transient_voltage_graph_id:At("simulation_transient_voltage_graph"),simulation_experiment_id:h.string(),timestamps_ms:h.array(h.number()).optional(),voltage_levels:h.array(h.number()),schematic_voltage_probe_id:h.string().optional(),simulation_voltage_probe_id:h.string().optional(),subcircuit_connectivity_map_key:h.string().optional(),time_per_step:eg,start_time_ms:ur,end_time_ms:ur,name:h.string().optional()}).describe("Stores voltage measurements over time for a simulation");_t(!0);Gj=h.object({type:h.literal("simulation_switch"),simulation_switch_id:At("simulation_switch"),source_component_id:h.string().optional(),closes_at:ur.optional(),opens_at:ur.optional(),starts_closed:h.boolean().optional(),switching_frequency:pr.optional()}).describe("Defines a switch for simulation timing control");_t(!0);Hj=h.object({type:h.literal("simulation_voltage_probe"),simulation_voltage_probe_id:At("simulation_voltage_probe"),source_port_id:h.string().optional(),source_net_id:h.string().optional(),name:h.string().optional(),subcircuit_id:h.string().optional()}).describe("Defines a voltage probe for simulation, connected to a port or a net").refine(n=>!!n.source_port_id!=!!n.source_net_id,{message:"Exactly one of source_port_id or source_net_id must be provided to simulation_voltage_probe"});_t(!0);Wj=h.object({type:h.literal("simulation_unknown_experiment_error"),simulation_unknown_experiment_error_id:At("simulation_unknown_experiment_error"),error_type:h.literal("simulation_unknown_experiment_error").default("simulation_unknown_experiment_error"),message:h.string(),simulation_experiment_id:h.string().optional(),subcircuit_id:h.string().optional()}).describe("An unknown error occurred during the simulation experiment.");_t(!0);qj=h.union([GD,VD,UD,WD,HD,W3,V3,jx,H3,G3,q3,Z3,K3,tE,eE,nE,oE,iE,rE,sE,Q3,J3,ZD,KD,qD,aE,cE,lE,Bx,E$,O$,wj,Nm,Vx,Gx,L$,yj,F$,W$,j$,X$,q$,D$,$$,Z$,K$,Sj,Q$,tj,ej,nj,ij,rj,sj,oj,U$,V$,J$,G$,H$,Oj,cj,aj,lj,uj,pj,hj,dj,fj,mj,Pj,_j,kj,vj,Tj,Ej,Mj,Aj,Rj,Am,Lj,Fj,zj,JD,u$,s$,o$,a$,c$,r$,p$,l$,QD,d$,f$,h$,g$,x$,Xx,b$,S$,v$,w$,Dj,Yj,Uj,Vj,Gj,Hj,Wj]),$h=qj;_t(!0);Dh(!0)});var bB=ue((rqt,xB)=>{"use strict";var Om=1e3,Lm=Om*60,Fm=Lm*60,Xh=Fm*24,ggt=Xh*7,xgt=Xh*365.25;xB.exports=function(n,e){e=e||{};var t=typeof n;if(t==="string"&&n.length>0)return bgt(n);if(t==="number"&&isFinite(n))return e.long?wgt(n):vgt(n);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(n))};function bgt(n){if(n=String(n),!(n.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(n);if(e){var t=parseFloat(e[1]),i=(e[2]||"ms").toLowerCase();switch(i){case"years":case"year":case"yrs":case"yr":case"y":return t*xgt;case"weeks":case"week":case"w":return t*ggt;case"days":case"day":case"d":return t*Xh;case"hours":case"hour":case"hrs":case"hr":case"h":return t*Fm;case"minutes":case"minute":case"mins":case"min":case"m":return t*Lm;case"seconds":case"second":case"secs":case"sec":case"s":return t*Om;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function vgt(n){var e=Math.abs(n);return e>=Xh?Math.round(n/Xh)+"d":e>=Fm?Math.round(n/Fm)+"h":e>=Lm?Math.round(n/Lm)+"m":e>=Om?Math.round(n/Om)+"s":n+"ms"}function wgt(n){var e=Math.abs(n);return e>=Xh?nb(n,e,Xh,"day"):e>=Fm?nb(n,e,Fm,"hour"):e>=Lm?nb(n,e,Lm,"minute"):e>=Om?nb(n,e,Om,"second"):n+" ms"}function nb(n,e,t,i){var r=e>=t*1.5;return Math.round(n/t)+" "+i+(r?"s":"")}});var wB=ue((sqt,vB)=>{"use strict";function Sgt(n){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=r,t.enabled=a,t.humanize=bB(),t.destroy=l,Object.keys(n).forEach(u=>{t[u]=n[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let p=0;for(let f=0;f<u.length;f++)p=(p<<5)-p+u.charCodeAt(f),p|=0;return t.colors[Math.abs(p)%t.colors.length]}t.selectColor=e;function t(u){let p,f=null,y,g;function x(...v){if(!x.enabled)return;let S=x,P=Number(new Date),T=P-(p||P);S.diff=T,S.prev=p,S.curr=P,p=P,v[0]=t.coerce(v[0]),typeof v[0]!="string"&&v.unshift("%O");let k=0;v[0]=v[0].replace(/%([a-zA-Z%])/g,(E,N)=>{if(E==="%%")return"%";k++;let I=t.formatters[N];if(typeof I=="function"){let A=v[k];E=I.call(S,A),v.splice(k,1),k--}return E}),t.formatArgs.call(S,v),(S.log||t.log).apply(S,v)}return x.namespace=u,x.useColors=t.useColors(),x.color=t.selectColor(u),x.extend=i,x.destroy=t.destroy,Object.defineProperty(x,"enabled",{enumerable:!0,configurable:!1,get:()=>f!==null?f:(y!==t.namespaces&&(y=t.namespaces,g=t.enabled(u)),g),set:v=>{f=v}}),typeof t.init=="function"&&t.init(x),x}function i(u,p){let f=t(this.namespace+(typeof p>"u"?":":p)+u);return f.log=this.log,f}function r(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let p=(typeof u=="string"?u:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let f of p)f[0]==="-"?t.skips.push(f.slice(1)):t.names.push(f)}function s(u,p){let f=0,y=0,g=-1,x=0;for(;f<u.length;)if(y<p.length&&(p[y]===u[f]||p[y]==="*"))p[y]==="*"?(g=y,x=f,y++):(f++,y++);else if(g!==-1)y=g+1,x++,f=x;else return!1;for(;y<p.length&&p[y]==="*";)y++;return y===p.length}function o(){let u=[...t.names,...t.skips.map(p=>"-"+p)].join(",");return t.enable(""),u}function a(u){for(let p of t.skips)if(s(u,p))return!1;for(let p of t.names)if(s(u,p))return!0;return!1}function c(u){return u instanceof Error?u.stack||u.message:u}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}vB.exports=Sgt});var An=ue((zr,ib)=>{"use strict";zr.formatArgs=kgt;zr.save=Tgt;zr.load=Egt;zr.useColors=Pgt;zr.storage=Mgt();zr.destroy=(()=>{let n=!1;return()=>{n||(n=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();zr.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function Pgt(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let n;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(n=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(n[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function kgt(n){if(n[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+n[0]+(this.useColors?"%c ":" ")+"+"+ib.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;n.splice(1,0,e,"color: inherit");let t=0,i=0;n[0].replace(/%[a-zA-Z%]/g,r=>{r!=="%%"&&(t++,r==="%c"&&(i=t))}),n.splice(i,0,e)}zr.log=console.debug||console.log||(()=>{});function Tgt(n){try{n?zr.storage.setItem("debug",n):zr.storage.removeItem("debug")}catch{}}function Egt(){let n;try{n=zr.storage.getItem("debug")||zr.storage.getItem("DEBUG")}catch{}return!n&&typeof process<"u"&&"env"in process&&(n=process.env.DEBUG),n}function Mgt(){try{return localStorage}catch{}}ib.exports=wB()(zr);var{formatters:Cgt}=ib.exports;Cgt.j=function(n){try{return JSON.stringify(n)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var AB=ue(Un=>{"use strict";function vE(n,e){var t=n.length;n.push(e);t:for(;0<t;){var i=t-1>>>1,r=n[i];if(0<rb(r,e))n[i]=e,n[t]=r,t=i;else break t}}function Io(n){return n.length===0?null:n[0]}function ob(n){if(n.length===0)return null;var e=n[0],t=n.pop();if(t!==e){n[0]=t;t:for(var i=0,r=n.length,s=r>>>1;i<s;){var o=2*(i+1)-1,a=n[o],c=o+1,l=n[c];if(0>rb(a,t))c<r&&0>rb(l,a)?(n[i]=l,n[c]=t,i=c):(n[i]=a,n[o]=t,i=o);else if(c<r&&0>rb(l,t))n[i]=l,n[c]=t,i=c;else break t}}return e}function rb(n,e){var t=n.sortIndex-e.sortIndex;return t!==0?t:n.id-e.id}Un.unstable_now=void 0;typeof performance=="object"&&typeof performance.now=="function"?(SB=performance,Un.unstable_now=function(){return SB.now()}):(gE=Date,PB=gE.now(),Un.unstable_now=function(){return gE.now()-PB});var SB,gE,PB,Sa=[],$c=[],Igt=1,ks=null,hr=3,wE=!1,rg=!1,sg=!1,SE=!1,EB=typeof setTimeout=="function"?setTimeout:null,MB=typeof clearTimeout=="function"?clearTimeout:null,kB=typeof setImmediate<"u"?setImmediate:null;function sb(n){for(var e=Io($c);e!==null;){if(e.callback===null)ob($c);else if(e.startTime<=n)ob($c),e.sortIndex=e.expirationTime,vE(Sa,e);else break;e=Io($c)}}function PE(n){if(sg=!1,sb(n),!rg)if(Io(Sa)!==null)rg=!0,Dm||(Dm=!0,zm());else{var e=Io($c);e!==null&&kE(PE,e.startTime-n)}}var Dm=!1,og=-1,CB=5,IB=-1;function NB(){return SE?!0:!(Un.unstable_now()-IB<CB)}function xE(){if(SE=!1,Dm){var n=Un.unstable_now();IB=n;var e=!0;try{t:{rg=!1,sg&&(sg=!1,MB(og),og=-1),wE=!0;var t=hr;try{e:{for(sb(n),ks=Io(Sa);ks!==null&&!(ks.expirationTime>n&&NB());){var i=ks.callback;if(typeof i=="function"){ks.callback=null,hr=ks.priorityLevel;var r=i(ks.expirationTime<=n);if(n=Un.unstable_now(),typeof r=="function"){ks.callback=r,sb(n),e=!0;break e}ks===Io(Sa)&&ob(Sa),sb(n)}else ob(Sa);ks=Io(Sa)}if(ks!==null)e=!0;else{var s=Io($c);s!==null&&kE(PE,s.startTime-n),e=!1}}break t}finally{ks=null,hr=t,wE=!1}e=void 0}}finally{e?zm():Dm=!1}}}var zm;typeof kB=="function"?zm=function(){kB(xE)}:typeof MessageChannel<"u"?(bE=new MessageChannel,TB=bE.port2,bE.port1.onmessage=xE,zm=function(){TB.postMessage(null)}):zm=function(){EB(xE,0)};var bE,TB;function kE(n,e){og=EB(function(){n(Un.unstable_now())},e)}Un.unstable_IdlePriority=5;Un.unstable_ImmediatePriority=1;Un.unstable_LowPriority=4;Un.unstable_NormalPriority=3;Un.unstable_Profiling=null;Un.unstable_UserBlockingPriority=2;Un.unstable_cancelCallback=function(n){n.callback=null};Un.unstable_forceFrameRate=function(n){0>n||125<n?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):CB=0<n?Math.floor(1e3/n):5};Un.unstable_getCurrentPriorityLevel=function(){return hr};Un.unstable_next=function(n){switch(hr){case 1:case 2:case 3:var e=3;break;default:e=hr}var t=hr;hr=e;try{return n()}finally{hr=t}};Un.unstable_requestPaint=function(){SE=!0};Un.unstable_runWithPriority=function(n,e){switch(n){case 1:case 2:case 3:case 4:case 5:break;default:n=3}var t=hr;hr=n;try{return e()}finally{hr=t}};Un.unstable_scheduleCallback=function(n,e,t){var i=Un.unstable_now();switch(typeof t=="object"&&t!==null?(t=t.delay,t=typeof t=="number"&&0<t?i+t:i):t=i,n){case 1:var r=-1;break;case 2:r=250;break;case 5:r=1073741823;break;case 4:r=1e4;break;default:r=5e3}return r=t+r,n={id:Igt++,callback:e,priorityLevel:n,startTime:t,expirationTime:r,sortIndex:-1},t>i?(n.sortIndex=t,vE($c,n),Io(Sa)===null&&n===Io($c)&&(sg?(MB(og),og=-1):sg=!0,kE(PE,t-i))):(n.sortIndex=r,vE(Sa,n),rg||wE||(rg=!0,Dm||(Dm=!0,zm()))),n};Un.unstable_shouldYield=NB;Un.unstable_wrapCallback=function(n){var e=hr;return function(){var t=hr;hr=e;try{return n.apply(this,arguments)}finally{hr=t}}}});var OB=ue((aqt,RB)=>{"use strict";RB.exports=AB()});var LB=ue((cqt,ag)=>{"use strict";ag.exports=function(n){function e(m,_,w,M){return new Ult(m,_,w,M)}function t(){}function i(m){var _="https://react.dev/errors/"+m;if(1<arguments.length){_+="?args[]="+encodeURIComponent(arguments[1]);for(var w=2;w<arguments.length;w++)_+="&args[]="+encodeURIComponent(arguments[w])}return"Minified React error #"+m+"; visit "+_+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function r(m){var _=m,w=m;if(m.alternate)for(;_.return;)_=_.return;else{m=_;do _=m,(_.flags&4098)!==0&&(w=_.return),m=_.return;while(m)}return _.tag===3?w:null}function s(m){if(r(m)!==m)throw Error(i(188))}function o(m){var _=m.alternate;if(!_){if(_=r(m),_===null)throw Error(i(188));return _!==m?null:m}for(var w=m,M=_;;){var O=w.return;if(O===null)break;var D=O.alternate;if(D===null){if(M=O.return,M!==null){w=M;continue}break}if(O.child===D.child){for(D=O.child;D;){if(D===w)return s(O),m;if(D===M)return s(O),_;D=D.sibling}throw Error(i(188))}if(w.return!==M.return)w=O,M=D;else{for(var K=!1,at=O.child;at;){if(at===w){K=!0,w=O,M=D;break}if(at===M){K=!0,M=O,w=D;break}at=at.sibling}if(!K){for(at=D.child;at;){if(at===w){K=!0,w=D,M=O;break}if(at===M){K=!0,M=D,w=O;break}at=at.sibling}if(!K)throw Error(i(189))}}if(w.alternate!==M)throw Error(i(190))}if(w.tag!==3)throw Error(i(188));return w.stateNode.current===w?m:_}function a(m){var _=m.tag;if(_===5||_===26||_===27||_===6)return m;for(m=m.child;m!==null;){if(_=a(m),_!==null)return _;m=m.sibling}return null}function c(m){var _=m.tag;if(_===5||_===26||_===27||_===6)return m;for(m=m.child;m!==null;){if(m.tag!==4&&(_=c(m),_!==null))return _;m=m.sibling}return null}function l(m){return m===null||typeof m!="object"?null:(m=bz&&m[bz]||m["@@iterator"],typeof m=="function"?m:null)}function u(m){if(m==null)return null;if(typeof m=="function")return m.$$typeof===Zlt?null:m.displayName||m.name||null;if(typeof m=="string")return m;switch(m){case Wf:return"Fragment";case WT:return"Profiler";case gz:return"StrictMode";case ZT:return"Suspense";case KT:return"SuspenseList";case QT:return"Activity"}if(typeof m=="object")switch(m.$$typeof){case Hf:return"Portal";case vc:return(m.displayName||"Context")+".Provider";case xz:return(m._context.displayName||"Context")+".Consumer";case qT:var _=m.render;return m=m.displayName,m||(m=_.displayName||_.name||"",m=m!==""?"ForwardRef("+m+")":"ForwardRef"),m;case JT:return _=m.displayName||null,_!==null?_:u(m.type)||"Memo";case wc:_=m._payload,m=m._init;try{return u(m(_))}catch{}}return null}function p(m){return{current:m}}function f(m){0>Kf||(m.current=r3[Kf],r3[Kf]=null,Kf--)}function y(m,_){Kf++,r3[Kf]=m.current,m.current=_}function g(m){return m>>>=0,m===0?32:31-(dpt(m)/fpt|0)|0}function x(m){var _=m&42;if(_!==0)return _;switch(m&-m){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return m&4194048;case 4194304:case 8388608:case 16777216:case 33554432:return m&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return m}}function v(m,_,w){var M=m.pendingLanes;if(M===0)return 0;var O=0,D=m.suspendedLanes,K=m.pingedLanes;m=m.warmLanes;var at=M&134217727;return at!==0?(M=at&~D,M!==0?O=x(M):(K&=at,K!==0?O=x(K):w||(w=at&~m,w!==0&&(O=x(w))))):(at=M&~D,at!==0?O=x(at):K!==0?O=x(K):w||(w=M&~m,w!==0&&(O=x(w)))),O===0?0:_!==0&&_!==O&&(_&D)===0&&(D=O&-O,w=_&-_,D>=w||D===32&&(w&4194048)!==0)?_:O}function S(m,_){return(m.pendingLanes&~(m.suspendedLanes&~m.pingedLanes)&_)===0}function P(m,_){switch(m){case 1:case 2:case 4:case 8:case 64:return _+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return _+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function T(){var m=ix;return ix<<=1,(ix&4194048)===0&&(ix=256),m}function k(){var m=rx;return rx<<=1,(rx&62914560)===0&&(rx=4194304),m}function C(m){for(var _=[],w=0;31>w;w++)_.push(m);return _}function E(m,_){m.pendingLanes|=_,_!==268435456&&(m.suspendedLanes=0,m.pingedLanes=0,m.warmLanes=0)}function N(m,_,w,M,O,D){var K=m.pendingLanes;m.pendingLanes=w,m.suspendedLanes=0,m.pingedLanes=0,m.warmLanes=0,m.expiredLanes&=w,m.entangledLanes&=w,m.errorRecoveryDisabledLanes&=w,m.shellSuspendCounter=0;var at=m.entanglements,xt=m.expirationTimes,It=m.hiddenUpdates;for(w=K&~w;0<w;){var Dt=31-ts(w),Xt=1<<Dt;at[Dt]=0,xt[Dt]=-1;var Wt=It[Dt];if(Wt!==null)for(It[Dt]=null,Dt=0;Dt<Wt.length;Dt++){var Re=Wt[Dt];Re!==null&&(Re.lane&=-536870913)}w&=~Xt}M!==0&&I(m,M,0),D!==0&&O===0&&m.tag!==0&&(m.suspendedLanes|=D&~(K&~_))}function I(m,_,w){m.pendingLanes|=_,m.suspendedLanes&=~_;var M=31-ts(_);m.entangledLanes|=_,m.entanglements[M]=m.entanglements[M]|1073741824|w&4194090}function A(m,_){var w=m.entangledLanes|=_;for(m=m.entanglements;w;){var M=31-ts(w),O=1<<M;O&_|m[M]&_&&(m[M]|=_),w&=~O}}function R(m){switch(m){case 2:m=1;break;case 8:m=4;break;case 32:m=16;break;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:m=128;break;case 268435456:m=134217728;break;default:m=0}return m}function j(m){return m&=-m,2<m?8<m?(m&134217727)!==0?32:268435456:8:2}function B(m){if(typeof xpt=="function"&&bpt(m),es&&typeof es.setStrictMode=="function")try{es.setStrictMode($y,m)}catch{}}function G(m){if(a3===void 0)try{throw Error()}catch(w){var _=w.stack.trim().match(/\n( *(at )?)/);a3=_&&_[1]||"",Vz=-1<w.stack.indexOf(`
1
+ var Ipt=Object.create;var Px=Object.defineProperty;var Npt=Object.getOwnPropertyDescriptor;var Apt=Object.getOwnPropertyNames;var Rpt=Object.getPrototypeOf,Opt=Object.prototype.hasOwnProperty;var Lpt=(n,e,t)=>e in n?Px(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var Zy=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var qt=(n,e)=>()=>(n&&(e=n(n=0)),e);var ue=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),xh=(n,e)=>{for(var t in e)Px(n,t,{get:e[t],enumerable:!0})},Fpt=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Apt(e))!Opt.call(n,r)&&r!==t&&Px(n,r,{get:()=>e[r],enumerable:!(i=Npt(e,r))||i.enumerable});return n};var Ht=(n,e,t)=>(t=n!=null?Ipt(Rpt(n)):{},Fpt(e||!n||!n.__esModule?Px(t,"default",{value:n,enumerable:!0}):t,n));var d=(n,e,t)=>Lpt(n,typeof e!="symbol"?e+"":e,t);var gD=ue(Me=>{"use strict";var I3=Symbol.for("react.transitional.element"),Kpt=Symbol.for("react.portal"),Jpt=Symbol.for("react.fragment"),Qpt=Symbol.for("react.strict_mode"),tht=Symbol.for("react.profiler"),eht=Symbol.for("react.consumer"),nht=Symbol.for("react.context"),iht=Symbol.for("react.forward_ref"),rht=Symbol.for("react.suspense"),sht=Symbol.for("react.memo"),hD=Symbol.for("react.lazy"),oht=Symbol.for("react.activity"),cD=Symbol.iterator;function aht(n){return n===null||typeof n!="object"?null:(n=cD&&n[cD]||n["@@iterator"],typeof n=="function"?n:null)}var dD={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},fD=Object.assign,mD={};function xm(n,e,t){this.props=n,this.context=e,this.refs=mD,this.updater=t||dD}xm.prototype.isReactComponent={};xm.prototype.setState=function(n,e){if(typeof n!="object"&&typeof n!="function"&&n!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,n,e,"setState")};xm.prototype.forceUpdate=function(n){this.updater.enqueueForceUpdate(this,n,"forceUpdate")};function _D(){}_D.prototype=xm.prototype;function N3(n,e,t){this.props=n,this.context=e,this.refs=mD,this.updater=t||dD}var A3=N3.prototype=new _D;A3.constructor=N3;fD(A3,xm.prototype);A3.isPureReactComponent=!0;var lD=Array.isArray;function C3(){}var zn={H:null,A:null,T:null,S:null},yD=Object.prototype.hasOwnProperty;function R3(n,e,t){var i=t.ref;return{$$typeof:I3,type:n,key:e,ref:i!==void 0?i:null,props:t}}function cht(n,e){return R3(n.type,e,n.props)}function O3(n){return typeof n=="object"&&n!==null&&n.$$typeof===I3}function lht(n){var e={"=":"=0",":":"=2"};return"$"+n.replace(/[=:]/g,function(t){return e[t]})}var uD=/\/+/g;function M3(n,e){return typeof n=="object"&&n!==null&&n.key!=null?lht(""+n.key):e.toString(36)}function uht(n){switch(n.status){case"fulfilled":return n.value;case"rejected":throw n.reason;default:switch(typeof n.status=="string"?n.then(C3,C3):(n.status="pending",n.then(function(e){n.status==="pending"&&(n.status="fulfilled",n.value=e)},function(e){n.status==="pending"&&(n.status="rejected",n.reason=e)})),n.status){case"fulfilled":return n.value;case"rejected":throw n.reason}}throw n}function gm(n,e,t,i,r){var s=typeof n;(s==="undefined"||s==="boolean")&&(n=null);var o=!1;if(n===null)o=!0;else switch(s){case"bigint":case"string":case"number":o=!0;break;case"object":switch(n.$$typeof){case I3:case Kpt:o=!0;break;case hD:return o=n._init,gm(o(n._payload),e,t,i,r)}}if(o)return r=r(n),o=i===""?"."+M3(n,0):i,lD(r)?(t="",o!=null&&(t=o.replace(uD,"$&/")+"/"),gm(r,e,t,"",function(l){return l})):r!=null&&(O3(r)&&(r=cht(r,t+(r.key==null||n&&n.key===r.key?"":(""+r.key).replace(uD,"$&/")+"/")+o)),e.push(r)),1;o=0;var a=i===""?".":i+":";if(lD(n))for(var c=0;c<n.length;c++)i=n[c],s=a+M3(i,c),o+=gm(i,e,t,s,r);else if(c=aht(n),typeof c=="function")for(n=c.call(n),c=0;!(i=n.next()).done;)i=i.value,s=a+M3(i,c++),o+=gm(i,e,t,s,r);else if(s==="object"){if(typeof n.then=="function")return gm(uht(n),e,t,i,r);throw e=String(n),Error("Objects are not valid as a React child (found: "+(e==="[object Object]"?"object with keys {"+Object.keys(n).join(", ")+"}":e)+"). If you meant to render a collection of children, use an array instead.")}return o}function Nx(n,e,t){if(n==null)return n;var i=[],r=0;return gm(n,i,"","",function(s){return e.call(t,s,r++)}),i}function pht(n){if(n._status===-1){var e=n._result;e=e(),e.then(function(t){(n._status===0||n._status===-1)&&(n._status=1,n._result=t)},function(t){(n._status===0||n._status===-1)&&(n._status=2,n._result=t)}),n._status===-1&&(n._status=0,n._result=e)}if(n._status===1)return n._result.default;throw n._result}var pD=typeof reportError=="function"?reportError:function(n){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var e=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof n=="object"&&n!==null&&typeof n.message=="string"?String(n.message):String(n),error:n});if(!window.dispatchEvent(e))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",n);return}console.error(n)},hht={map:Nx,forEach:function(n,e,t){Nx(n,function(){e.apply(this,arguments)},t)},count:function(n){var e=0;return Nx(n,function(){e++}),e},toArray:function(n){return Nx(n,function(e){return e})||[]},only:function(n){if(!O3(n))throw Error("React.Children.only expected to receive a single React element child.");return n}};Me.Activity=oht;Me.Children=hht;Me.Component=xm;Me.Fragment=Jpt;Me.Profiler=tht;Me.PureComponent=N3;Me.StrictMode=Qpt;Me.Suspense=rht;Me.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=zn;Me.__COMPILER_RUNTIME={__proto__:null,c:function(n){return zn.H.useMemoCache(n)}};Me.cache=function(n){return function(){return n.apply(null,arguments)}};Me.cacheSignal=function(){return null};Me.cloneElement=function(n,e,t){if(n==null)throw Error("The argument must be a React element, but you passed "+n+".");var i=fD({},n.props),r=n.key;if(e!=null)for(s in e.key!==void 0&&(r=""+e.key),e)!yD.call(e,s)||s==="key"||s==="__self"||s==="__source"||s==="ref"&&e.ref===void 0||(i[s]=e[s]);var s=arguments.length-2;if(s===1)i.children=t;else if(1<s){for(var o=Array(s),a=0;a<s;a++)o[a]=arguments[a+2];i.children=o}return R3(n.type,r,i)};Me.createContext=function(n){return n={$$typeof:nht,_currentValue:n,_currentValue2:n,_threadCount:0,Provider:null,Consumer:null},n.Provider=n,n.Consumer={$$typeof:eht,_context:n},n};Me.createElement=function(n,e,t){var i,r={},s=null;if(e!=null)for(i in e.key!==void 0&&(s=""+e.key),e)yD.call(e,i)&&i!=="key"&&i!=="__self"&&i!=="__source"&&(r[i]=e[i]);var o=arguments.length-2;if(o===1)r.children=t;else if(1<o){for(var a=Array(o),c=0;c<o;c++)a[c]=arguments[c+2];r.children=a}if(n&&n.defaultProps)for(i in o=n.defaultProps,o)r[i]===void 0&&(r[i]=o[i]);return R3(n,s,r)};Me.createRef=function(){return{current:null}};Me.forwardRef=function(n){return{$$typeof:iht,render:n}};Me.isValidElement=O3;Me.lazy=function(n){return{$$typeof:hD,_payload:{_status:-1,_result:n},_init:pht}};Me.memo=function(n,e){return{$$typeof:sht,type:n,compare:e===void 0?null:e}};Me.startTransition=function(n){var e=zn.T,t={};zn.T=t;try{var i=n(),r=zn.S;r!==null&&r(t,i),typeof i=="object"&&i!==null&&typeof i.then=="function"&&i.then(C3,pD)}catch(s){pD(s)}finally{e!==null&&t.types!==null&&(e.types=t.types),zn.T=e}};Me.unstable_useCacheRefresh=function(){return zn.H.useCacheRefresh()};Me.use=function(n){return zn.H.use(n)};Me.useActionState=function(n,e,t){return zn.H.useActionState(n,e,t)};Me.useCallback=function(n,e){return zn.H.useCallback(n,e)};Me.useContext=function(n){return zn.H.useContext(n)};Me.useDebugValue=function(){};Me.useDeferredValue=function(n,e){return zn.H.useDeferredValue(n,e)};Me.useEffect=function(n,e){return zn.H.useEffect(n,e)};Me.useEffectEvent=function(n){return zn.H.useEffectEvent(n)};Me.useId=function(){return zn.H.useId()};Me.useImperativeHandle=function(n,e,t){return zn.H.useImperativeHandle(n,e,t)};Me.useInsertionEffect=function(n,e){return zn.H.useInsertionEffect(n,e)};Me.useLayoutEffect=function(n,e){return zn.H.useLayoutEffect(n,e)};Me.useMemo=function(n,e){return zn.H.useMemo(n,e)};Me.useOptimistic=function(n,e){return zn.H.useOptimistic(n,e)};Me.useReducer=function(n,e,t){return zn.H.useReducer(n,e,t)};Me.useRef=function(n){return zn.H.useRef(n)};Me.useState=function(n){return zn.H.useState(n)};Me.useSyncExternalStore=function(n,e,t){return zn.H.useSyncExternalStore(n,e,t)};Me.useTransition=function(){return zn.H.useTransition()};Me.version="19.2.0"});var Hs=ue((EYt,xD)=>{"use strict";xD.exports=gD()});var Ve,L3,Gt,Eo,Ky=qt(()=>{"use strict";(function(n){n.assertEqual=r=>{};function e(r){}n.assertIs=e;function t(r){throw new Error}n.assertNever=t,n.arrayToEnum=r=>{let s={};for(let o of r)s[o]=o;return s},n.getValidEnumValues=r=>{let s=n.objectKeys(r).filter(a=>typeof r[r[a]]!="number"),o={};for(let a of s)o[a]=r[a];return n.objectValues(o)},n.objectValues=r=>n.objectKeys(r).map(function(s){return r[s]}),n.objectKeys=typeof Object.keys=="function"?r=>Object.keys(r):r=>{let s=[];for(let o in r)Object.prototype.hasOwnProperty.call(r,o)&&s.push(o);return s},n.find=(r,s)=>{for(let o of r)if(s(o))return o},n.isInteger=typeof Number.isInteger=="function"?r=>Number.isInteger(r):r=>typeof r=="number"&&Number.isFinite(r)&&Math.floor(r)===r;function i(r,s=" | "){return r.map(o=>typeof o=="string"?`'${o}'`:o).join(s)}n.joinValues=i,n.jsonStringifyReplacer=(r,s)=>typeof s=="bigint"?s.toString():s})(Ve||(Ve={}));(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(L3||(L3={}));Gt=Ve.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Eo=n=>{switch(typeof n){case"undefined":return Gt.undefined;case"string":return Gt.string;case"number":return Number.isNaN(n)?Gt.nan:Gt.number;case"boolean":return Gt.boolean;case"function":return Gt.function;case"bigint":return Gt.bigint;case"symbol":return Gt.symbol;case"object":return Array.isArray(n)?Gt.array:n===null?Gt.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?Gt.promise:typeof Map<"u"&&n instanceof Map?Gt.map:typeof Set<"u"&&n instanceof Set?Gt.set:typeof Date<"u"&&n instanceof Date?Gt.date:Gt.object;default:return Gt.unknown}}});var Nt,dht,Lr,Ax=qt(()=>{"use strict";Ky();Nt=Ve.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"]),dht=n=>JSON.stringify(n,null,2).replace(/"([^"]+)":/g,"$1:"),Lr=class n extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=i=>{this.issues=[...this.issues,i]},this.addIssues=(i=[])=>{this.issues=[...this.issues,...i]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(s){return s.message},i={_errors:[]},r=s=>{for(let o of s.issues)if(o.code==="invalid_union")o.unionErrors.map(r);else if(o.code==="invalid_return_type")r(o.returnTypeError);else if(o.code==="invalid_arguments")r(o.argumentsError);else if(o.path.length===0)i._errors.push(t(o));else{let a=i,c=0;for(;c<o.path.length;){let l=o.path[c];c===o.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(t(o))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return r(this),i}static assert(e){if(!(e instanceof n))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Ve.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},i=[];for(let r of this.issues)if(r.path.length>0){let s=r.path[0];t[s]=t[s]||[],t[s].push(e(r))}else i.push(e(r));return{formErrors:i,fieldErrors:t}}get formErrors(){return this.flatten()}};Lr.create=n=>new Lr(n)});var fht,ma,F3=qt(()=>{"use strict";Ax();Ky();fht=(n,e)=>{let t;switch(n.code){case Nt.invalid_type:n.received===Gt.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case Nt.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,Ve.jsonStringifyReplacer)}`;break;case Nt.unrecognized_keys:t=`Unrecognized key(s) in object: ${Ve.joinValues(n.keys,", ")}`;break;case Nt.invalid_union:t="Invalid input";break;case Nt.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${Ve.joinValues(n.options)}`;break;case Nt.invalid_enum_value:t=`Invalid enum value. Expected ${Ve.joinValues(n.options)}, received '${n.received}'`;break;case Nt.invalid_arguments:t="Invalid function arguments";break;case Nt.invalid_return_type:t="Invalid function return type";break;case Nt.invalid_date:t="Invalid date";break;case Nt.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:Ve.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case Nt.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case Nt.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case Nt.custom:t="Invalid input";break;case Nt.invalid_intersection_types:t="Intersection results could not be merged";break;case Nt.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case Nt.not_finite:t="Number must be finite";break;default:t=e.defaultError,Ve.assertNever(n)}return{message:t}},ma=fht});function mht(n){bD=n}function bm(){return bD}var bD,Rx=qt(()=>{"use strict";F3();bD=ma});function Bt(n,e){let t=bm(),i=Jy({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===ma?void 0:ma].filter(r=>!!r)});n.common.issues.push(i)}var Jy,_ht,Ki,ye,vh,lr,Ox,Lx,Ac,vm,z3=qt(()=>{"use strict";Rx();F3();Jy=n=>{let{data:e,path:t,errorMaps:i,issueData:r}=n,s=[...t,...r.path||[]],o={...r,path:s};if(r.message!==void 0)return{...r,path:s,message:r.message};let a="",c=i.filter(l=>!!l).slice().reverse();for(let l of c)a=l(o,{data:e,defaultError:a}).message;return{...r,path:s,message:a}},_ht=[];Ki=class n{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let i=[];for(let r of t){if(r.status==="aborted")return ye;r.status==="dirty"&&e.dirty(),i.push(r.value)}return{status:e.value,value:i}}static async mergeObjectAsync(e,t){let i=[];for(let r of t){let s=await r.key,o=await r.value;i.push({key:s,value:o})}return n.mergeObjectSync(e,i)}static mergeObjectSync(e,t){let i={};for(let r of t){let{key:s,value:o}=r;if(s.status==="aborted"||o.status==="aborted")return ye;s.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof o.value<"u"||r.alwaysSet)&&(i[s.value]=o.value)}return{status:e.value,value:i}}},ye=Object.freeze({status:"aborted"}),vh=n=>({status:"dirty",value:n}),lr=n=>({status:"valid",value:n}),Ox=n=>n.status==="aborted",Lx=n=>n.status==="dirty",Ac=n=>n.status==="valid",vm=n=>typeof Promise<"u"&&n instanceof Promise});var vD=qt(()=>{"use strict"});var se,wD=qt(()=>{"use strict";(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e?.message})(se||(se={}))});function Ie(n){if(!n)return{};let{errorMap:e,invalid_type_error:t,required_error:i,description:r}=n;if(e&&(t||i))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:r}:{errorMap:(o,a)=>{let{message:c}=n;return o.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??i??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:c??t??a.defaultError}},description:r}}function TD(n){let e="[0-5]\\d";n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`);let t=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function Rht(n){return new RegExp(`^${TD(n)}$`)}function ED(n){let e=`${kD}T${TD(n)}`,t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Oht(n,e){return!!((e==="v4"||!e)&&Tht.test(n)||(e==="v6"||!e)&&Mht.test(n))}function Lht(n,e){if(!wht.test(n))return!1;try{let[t]=n.split(".");if(!t)return!1;let i=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),r=JSON.parse(atob(i));return!(typeof r!="object"||r===null||"typ"in r&&r?.typ!=="JWT"||!r.alg||e&&r.alg!==e)}catch{return!1}}function Fht(n,e){return!!((e==="v4"||!e)&&Eht.test(n)||(e==="v6"||!e)&&Cht.test(n))}function zht(n,e){let t=(n.toString().split(".")[1]||"").length,i=(e.toString().split(".")[1]||"").length,r=t>i?t:i,s=Number.parseInt(n.toFixed(r).replace(".","")),o=Number.parseInt(e.toFixed(r).replace(".",""));return s%o/10**r}function wm(n){if(n instanceof Fr){let e={};for(let t in n.shape){let i=n.shape[t];e[t]=ws.create(wm(i))}return new Fr({...n._def,shape:()=>e})}else return n instanceof ga?new ga({...n._def,type:wm(n.element)}):n instanceof ws?ws.create(wm(n.unwrap())):n instanceof Co?Co.create(wm(n.unwrap())):n instanceof Mo?Mo.create(n.items.map(e=>wm(e))):n}function $3(n,e){let t=Eo(n),i=Eo(e);if(n===e)return{valid:!0,data:n};if(t===Gt.object&&i===Gt.object){let r=Ve.objectKeys(e),s=Ve.objectKeys(n).filter(a=>r.indexOf(a)!==-1),o={...n,...e};for(let a of s){let c=$3(n[a],e[a]);if(!c.valid)return{valid:!1};o[a]=c.data}return{valid:!0,data:o}}else if(t===Gt.array&&i===Gt.array){if(n.length!==e.length)return{valid:!1};let r=[];for(let s=0;s<n.length;s++){let o=n[s],a=e[s],c=$3(o,a);if(!c.valid)return{valid:!1};r.push(c.data)}return{valid:!0,data:r}}else return t===Gt.date&&i===Gt.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}function MD(n,e){return new Ah({values:n,typeName:we.ZodEnum,...Ie(e)})}function PD(n,e){let t=typeof n=="function"?n(e):typeof n=="string"?{message:n}:n;return typeof t=="string"?{message:t}:t}function CD(n,e={},t){return n?Oc.create().superRefine((i,r)=>{let s=n(i);if(s instanceof Promise)return s.then(o=>{if(!o){let a=PD(e,i),c=a.fatal??t??!0;r.addIssue({code:"custom",...a,fatal:c})}});if(!s){let o=PD(e,i),a=o.fatal??t??!0;r.addIssue({code:"custom",...o,fatal:a})}}):Oc.create()}var Ss,SD,Fe,yht,ght,xht,bht,vht,wht,Sht,Pht,kht,D3,Tht,Eht,Mht,Cht,Iht,Nht,kD,Aht,Rc,wh,Sh,Ph,kh,Sm,Th,Eh,Oc,ya,Ws,Pm,ga,Fr,Mh,_a,Fx,Ch,Mo,zx,km,Tm,Dx,Ih,Nh,Ah,Rh,Lc,Ps,ws,Co,Oh,Lh,Em,Dht,Qy,tg,Fh,$ht,we,jht,ID,ND,Bht,Yht,AD,Xht,Uht,Vht,Ght,Hht,Wht,qht,Zht,Kht,Jht,Qht,tdt,edt,ndt,idt,rdt,sdt,odt,adt,cdt,ldt,udt,pdt,hdt,ddt,fdt,mdt,_dt,ydt,gdt,xdt,bdt,vdt,wdt,RD=qt(()=>{"use strict";Ax();Rx();wD();z3();Ky();Ss=class{constructor(e,t,i,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=i,this._key=r}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}},SD=(n,e)=>{if(Ac(e))return{success:!0,data:e.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new Lr(n.common.issues);return this._error=t,this._error}}};Fe=class{get description(){return this._def.description}_getType(e){return Eo(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Eo(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ki,ctx:{common:e.parent.common,data:e.data,parsedType:Eo(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(vm(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let i=this.safeParse(e,t);if(i.success)return i.data;throw i.error}safeParse(e,t){let i={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Eo(e)},r=this._parseSync({data:e,path:i.path,parent:i});return SD(i,r)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Eo(e)};if(!this["~standard"].async)try{let i=this._parseSync({data:e,path:[],parent:t});return Ac(i)?{value:i.value}:{issues:t.common.issues}}catch(i){i?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(i=>Ac(i)?{value:i.value}:{issues:t.common.issues})}async parseAsync(e,t){let i=await this.safeParseAsync(e,t);if(i.success)return i.data;throw i.error}async safeParseAsync(e,t){let i={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Eo(e)},r=this._parse({data:e,path:i.path,parent:i}),s=await(vm(r)?r:Promise.resolve(r));return SD(i,s)}refine(e,t){let i=r=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(r):t;return this._refinement((r,s)=>{let o=e(r),a=()=>s.addIssue({code:Nt.custom,...i(r)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,t){return this._refinement((i,r)=>e(i)?!0:(r.addIssue(typeof t=="function"?t(i,r):t),!1))}_refinement(e){return new Ps({schema:this,typeName:we.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,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:t=>this["~validate"](t)}}optional(){return ws.create(this,this._def)}nullable(){return Co.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ga.create(this)}promise(){return Lc.create(this,this._def)}or(e){return Mh.create([this,e],this._def)}and(e){return Ch.create(this,e,this._def)}transform(e){return new Ps({...Ie(this._def),schema:this,typeName:we.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Oh({...Ie(this._def),innerType:this,defaultValue:t,typeName:we.ZodDefault})}brand(){return new Qy({typeName:we.ZodBranded,type:this,...Ie(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new Lh({...Ie(this._def),innerType:this,catchValue:t,typeName:we.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return tg.create(this,e)}readonly(){return Fh.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},yht=/^c[^\s-]{8,}$/i,ght=/^[0-9a-z]+$/,xht=/^[0-9A-HJKMNP-TV-Z]{26}$/i,bht=/^[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,vht=/^[a-z0-9_-]{21}$/i,wht=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Sht=/^[-+]?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)?)??$/,Pht=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,kht="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Tht=/^(?:(?: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])$/,Eht=/^(?:(?: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])$/,Mht=/^(([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]))$/,Cht=/^(([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])$/,Iht=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Nht=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,kD="((\\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])))",Aht=new RegExp(`^${kD}$`);Rc=class n extends Fe{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==Gt.string){let s=this._getOrReturnCtx(e);return Bt(s,{code:Nt.invalid_type,expected:Gt.string,received:s.parsedType}),ye}let i=new Ki,r;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(r=this._getOrReturnCtx(e,r),Bt(r,{code:Nt.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),i.dirty());else if(s.kind==="max")e.data.length>s.value&&(r=this._getOrReturnCtx(e,r),Bt(r,{code:Nt.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),i.dirty());else if(s.kind==="length"){let o=e.data.length>s.value,a=e.data.length<s.value;(o||a)&&(r=this._getOrReturnCtx(e,r),o?Bt(r,{code:Nt.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&Bt(r,{code:Nt.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),i.dirty())}else if(s.kind==="email")Pht.test(e.data)||(r=this._getOrReturnCtx(e,r),Bt(r,{validation:"email",code:Nt.invalid_string,message:s.message}),i.dirty());else if(s.kind==="emoji")D3||(D3=new RegExp(kht,"u")),D3.test(e.data)||(r=this._getOrReturnCtx(e,r),Bt(r,{validation:"emoji",code:Nt.invalid_string,message:s.message}),i.dirty());else if(s.kind==="uuid")bht.test(e.data)||(r=this._getOrReturnCtx(e,r),Bt(r,{validation:"uuid",code:Nt.invalid_string,message:s.message}),i.dirty());else if(s.kind==="nanoid")vht.test(e.data)||(r=this._getOrReturnCtx(e,r),Bt(r,{validation:"nanoid",code:Nt.invalid_string,message:s.message}),i.dirty());else if(s.kind==="cuid")yht.test(e.data)||(r=this._getOrReturnCtx(e,r),Bt(r,{validation:"cuid",code:Nt.invalid_string,message:s.message}),i.dirty());else if(s.kind==="cuid2")ght.test(e.data)||(r=this._getOrReturnCtx(e,r),Bt(r,{validation:"cuid2",code:Nt.invalid_string,message:s.message}),i.dirty());else if(s.kind==="ulid")xht.test(e.data)||(r=this._getOrReturnCtx(e,r),Bt(r,{validation:"ulid",code:Nt.invalid_string,message:s.message}),i.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),Bt(r,{validation:"url",code:Nt.invalid_string,message:s.message}),i.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),Bt(r,{validation:"regex",code:Nt.invalid_string,message:s.message}),i.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(r=this._getOrReturnCtx(e,r),Bt(r,{code:Nt.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),i.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(r=this._getOrReturnCtx(e,r),Bt(r,{code:Nt.invalid_string,validation:{startsWith:s.value},message:s.message}),i.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(r=this._getOrReturnCtx(e,r),Bt(r,{code:Nt.invalid_string,validation:{endsWith:s.value},message:s.message}),i.dirty()):s.kind==="datetime"?ED(s).test(e.data)||(r=this._getOrReturnCtx(e,r),Bt(r,{code:Nt.invalid_string,validation:"datetime",message:s.message}),i.dirty()):s.kind==="date"?Aht.test(e.data)||(r=this._getOrReturnCtx(e,r),Bt(r,{code:Nt.invalid_string,validation:"date",message:s.message}),i.dirty()):s.kind==="time"?Rht(s).test(e.data)||(r=this._getOrReturnCtx(e,r),Bt(r,{code:Nt.invalid_string,validation:"time",message:s.message}),i.dirty()):s.kind==="duration"?Sht.test(e.data)||(r=this._getOrReturnCtx(e,r),Bt(r,{validation:"duration",code:Nt.invalid_string,message:s.message}),i.dirty()):s.kind==="ip"?Oht(e.data,s.version)||(r=this._getOrReturnCtx(e,r),Bt(r,{validation:"ip",code:Nt.invalid_string,message:s.message}),i.dirty()):s.kind==="jwt"?Lht(e.data,s.alg)||(r=this._getOrReturnCtx(e,r),Bt(r,{validation:"jwt",code:Nt.invalid_string,message:s.message}),i.dirty()):s.kind==="cidr"?Fht(e.data,s.version)||(r=this._getOrReturnCtx(e,r),Bt(r,{validation:"cidr",code:Nt.invalid_string,message:s.message}),i.dirty()):s.kind==="base64"?Iht.test(e.data)||(r=this._getOrReturnCtx(e,r),Bt(r,{validation:"base64",code:Nt.invalid_string,message:s.message}),i.dirty()):s.kind==="base64url"?Nht.test(e.data)||(r=this._getOrReturnCtx(e,r),Bt(r,{validation:"base64url",code:Nt.invalid_string,message:s.message}),i.dirty()):Ve.assertNever(s);return{status:i.value,value:e.data}}_regex(e,t,i){return this.refinement(r=>e.test(r),{validation:t,code:Nt.invalid_string,...se.errToObj(i)})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...se.errToObj(e)})}url(e){return this._addCheck({kind:"url",...se.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...se.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...se.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...se.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...se.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...se.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...se.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...se.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...se.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...se.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...se.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...se.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...se.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...se.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...se.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...se.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...se.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...se.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...se.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...se.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...se.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...se.errToObj(t)})}nonempty(e){return this.min(1,se.errToObj(e))}trim(){return new n({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new n({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new n({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};Rc.create=n=>new Rc({checks:[],typeName:we.ZodString,coerce:n?.coerce??!1,...Ie(n)});wh=class n extends Fe{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==Gt.number){let s=this._getOrReturnCtx(e);return Bt(s,{code:Nt.invalid_type,expected:Gt.number,received:s.parsedType}),ye}let i,r=new Ki;for(let s of this._def.checks)s.kind==="int"?Ve.isInteger(e.data)||(i=this._getOrReturnCtx(e,i),Bt(i,{code:Nt.invalid_type,expected:"integer",received:"float",message:s.message}),r.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(i=this._getOrReturnCtx(e,i),Bt(i,{code:Nt.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(i=this._getOrReturnCtx(e,i),Bt(i,{code:Nt.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty()):s.kind==="multipleOf"?zht(e.data,s.value)!==0&&(i=this._getOrReturnCtx(e,i),Bt(i,{code:Nt.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(i=this._getOrReturnCtx(e,i),Bt(i,{code:Nt.not_finite,message:s.message}),r.dirty()):Ve.assertNever(s);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,se.toString(t))}gt(e,t){return this.setLimit("min",e,!1,se.toString(t))}lte(e,t){return this.setLimit("max",e,!0,se.toString(t))}lt(e,t){return this.setLimit("max",e,!1,se.toString(t))}setLimit(e,t,i,r){return new n({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:se.toString(r)}]})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:se.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:se.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:se.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:se.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:se.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:se.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:se.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:se.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:se.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Ve.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let i of this._def.checks){if(i.kind==="finite"||i.kind==="int"||i.kind==="multipleOf")return!0;i.kind==="min"?(t===null||i.value>t)&&(t=i.value):i.kind==="max"&&(e===null||i.value<e)&&(e=i.value)}return Number.isFinite(t)&&Number.isFinite(e)}};wh.create=n=>new wh({checks:[],typeName:we.ZodNumber,coerce:n?.coerce||!1,...Ie(n)});Sh=class n extends Fe{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==Gt.bigint)return this._getInvalidInput(e);let i,r=new Ki;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(i=this._getOrReturnCtx(e,i),Bt(i,{code:Nt.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(i=this._getOrReturnCtx(e,i),Bt(i,{code:Nt.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(i=this._getOrReturnCtx(e,i),Bt(i,{code:Nt.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):Ve.assertNever(s);return{status:r.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return Bt(t,{code:Nt.invalid_type,expected:Gt.bigint,received:t.parsedType}),ye}gte(e,t){return this.setLimit("min",e,!0,se.toString(t))}gt(e,t){return this.setLimit("min",e,!1,se.toString(t))}lte(e,t){return this.setLimit("max",e,!0,se.toString(t))}lt(e,t){return this.setLimit("max",e,!1,se.toString(t))}setLimit(e,t,i,r){return new n({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:se.toString(r)}]})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:se.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:se.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:se.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:se.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:se.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};Sh.create=n=>new Sh({checks:[],typeName:we.ZodBigInt,coerce:n?.coerce??!1,...Ie(n)});Ph=class extends Fe{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==Gt.boolean){let i=this._getOrReturnCtx(e);return Bt(i,{code:Nt.invalid_type,expected:Gt.boolean,received:i.parsedType}),ye}return lr(e.data)}};Ph.create=n=>new Ph({typeName:we.ZodBoolean,coerce:n?.coerce||!1,...Ie(n)});kh=class n extends Fe{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==Gt.date){let s=this._getOrReturnCtx(e);return Bt(s,{code:Nt.invalid_type,expected:Gt.date,received:s.parsedType}),ye}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return Bt(s,{code:Nt.invalid_date}),ye}let i=new Ki,r;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(r=this._getOrReturnCtx(e,r),Bt(r,{code:Nt.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),i.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(r=this._getOrReturnCtx(e,r),Bt(r,{code:Nt.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),i.dirty()):Ve.assertNever(s);return{status:i.value,value:new Date(e.data.getTime())}}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:se.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:se.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};kh.create=n=>new kh({checks:[],coerce:n?.coerce||!1,typeName:we.ZodDate,...Ie(n)});Sm=class extends Fe{_parse(e){if(this._getType(e)!==Gt.symbol){let i=this._getOrReturnCtx(e);return Bt(i,{code:Nt.invalid_type,expected:Gt.symbol,received:i.parsedType}),ye}return lr(e.data)}};Sm.create=n=>new Sm({typeName:we.ZodSymbol,...Ie(n)});Th=class extends Fe{_parse(e){if(this._getType(e)!==Gt.undefined){let i=this._getOrReturnCtx(e);return Bt(i,{code:Nt.invalid_type,expected:Gt.undefined,received:i.parsedType}),ye}return lr(e.data)}};Th.create=n=>new Th({typeName:we.ZodUndefined,...Ie(n)});Eh=class extends Fe{_parse(e){if(this._getType(e)!==Gt.null){let i=this._getOrReturnCtx(e);return Bt(i,{code:Nt.invalid_type,expected:Gt.null,received:i.parsedType}),ye}return lr(e.data)}};Eh.create=n=>new Eh({typeName:we.ZodNull,...Ie(n)});Oc=class extends Fe{constructor(){super(...arguments),this._any=!0}_parse(e){return lr(e.data)}};Oc.create=n=>new Oc({typeName:we.ZodAny,...Ie(n)});ya=class extends Fe{constructor(){super(...arguments),this._unknown=!0}_parse(e){return lr(e.data)}};ya.create=n=>new ya({typeName:we.ZodUnknown,...Ie(n)});Ws=class extends Fe{_parse(e){let t=this._getOrReturnCtx(e);return Bt(t,{code:Nt.invalid_type,expected:Gt.never,received:t.parsedType}),ye}};Ws.create=n=>new Ws({typeName:we.ZodNever,...Ie(n)});Pm=class extends Fe{_parse(e){if(this._getType(e)!==Gt.undefined){let i=this._getOrReturnCtx(e);return Bt(i,{code:Nt.invalid_type,expected:Gt.void,received:i.parsedType}),ye}return lr(e.data)}};Pm.create=n=>new Pm({typeName:we.ZodVoid,...Ie(n)});ga=class n extends Fe{_parse(e){let{ctx:t,status:i}=this._processInputParams(e),r=this._def;if(t.parsedType!==Gt.array)return Bt(t,{code:Nt.invalid_type,expected:Gt.array,received:t.parsedType}),ye;if(r.exactLength!==null){let o=t.data.length>r.exactLength.value,a=t.data.length<r.exactLength.value;(o||a)&&(Bt(t,{code:o?Nt.too_big:Nt.too_small,minimum:a?r.exactLength.value:void 0,maximum:o?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),i.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(Bt(t,{code:Nt.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),i.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(Bt(t,{code:Nt.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),i.dirty()),t.common.async)return Promise.all([...t.data].map((o,a)=>r.type._parseAsync(new Ss(t,o,t.path,a)))).then(o=>Ki.mergeArray(i,o));let s=[...t.data].map((o,a)=>r.type._parseSync(new Ss(t,o,t.path,a)));return Ki.mergeArray(i,s)}get element(){return this._def.type}min(e,t){return new n({...this._def,minLength:{value:e,message:se.toString(t)}})}max(e,t){return new n({...this._def,maxLength:{value:e,message:se.toString(t)}})}length(e,t){return new n({...this._def,exactLength:{value:e,message:se.toString(t)}})}nonempty(e){return this.min(1,e)}};ga.create=(n,e)=>new ga({type:n,minLength:null,maxLength:null,exactLength:null,typeName:we.ZodArray,...Ie(e)});Fr=class n extends Fe{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=Ve.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==Gt.object){let l=this._getOrReturnCtx(e);return Bt(l,{code:Nt.invalid_type,expected:Gt.object,received:l.parsedType}),ye}let{status:i,ctx:r}=this._processInputParams(e),{shape:s,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof Ws&&this._def.unknownKeys==="strip"))for(let l in r.data)o.includes(l)||a.push(l);let c=[];for(let l of o){let u=s[l],p=r.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Ss(r,p,r.path,l)),alwaysSet:l in r.data})}if(this._def.catchall instanceof Ws){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of a)c.push({key:{status:"valid",value:u},value:{status:"valid",value:r.data[u]}});else if(l==="strict")a.length>0&&(Bt(r,{code:Nt.unrecognized_keys,keys:a}),i.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of a){let p=r.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new Ss(r,p,r.path,u)),alwaysSet:u in r.data})}}return r.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let p=await u.key,f=await u.value;l.push({key:p,value:f,alwaysSet:u.alwaysSet})}return l}).then(l=>Ki.mergeObjectSync(i,l)):Ki.mergeObjectSync(i,c)}get shape(){return this._def.shape()}strict(e){return se.errToObj,new n({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,i)=>{let r=this._def.errorMap?.(t,i).message??i.defaultError;return t.code==="unrecognized_keys"?{message:se.errToObj(e).message??r}:{message:r}}}:{}})}strip(){return new n({...this._def,unknownKeys:"strip"})}passthrough(){return new n({...this._def,unknownKeys:"passthrough"})}extend(e){return new n({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new n({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:we.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new n({...this._def,catchall:e})}pick(e){let t={};for(let i of Ve.objectKeys(e))e[i]&&this.shape[i]&&(t[i]=this.shape[i]);return new n({...this._def,shape:()=>t})}omit(e){let t={};for(let i of Ve.objectKeys(this.shape))e[i]||(t[i]=this.shape[i]);return new n({...this._def,shape:()=>t})}deepPartial(){return wm(this)}partial(e){let t={};for(let i of Ve.objectKeys(this.shape)){let r=this.shape[i];e&&!e[i]?t[i]=r:t[i]=r.optional()}return new n({...this._def,shape:()=>t})}required(e){let t={};for(let i of Ve.objectKeys(this.shape))if(e&&!e[i])t[i]=this.shape[i];else{let s=this.shape[i];for(;s instanceof ws;)s=s._def.innerType;t[i]=s}return new n({...this._def,shape:()=>t})}keyof(){return MD(Ve.objectKeys(this.shape))}};Fr.create=(n,e)=>new Fr({shape:()=>n,unknownKeys:"strip",catchall:Ws.create(),typeName:we.ZodObject,...Ie(e)});Fr.strictCreate=(n,e)=>new Fr({shape:()=>n,unknownKeys:"strict",catchall:Ws.create(),typeName:we.ZodObject,...Ie(e)});Fr.lazycreate=(n,e)=>new Fr({shape:n,unknownKeys:"strip",catchall:Ws.create(),typeName:we.ZodObject,...Ie(e)});Mh=class extends Fe{_parse(e){let{ctx:t}=this._processInputParams(e),i=this._def.options;function r(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return t.common.issues.push(...a.ctx.common.issues),a.result;let o=s.map(a=>new Lr(a.ctx.common.issues));return Bt(t,{code:Nt.invalid_union,unionErrors:o}),ye}if(t.common.async)return Promise.all(i.map(async s=>{let o={...t,common:{...t.common,issues:[]},parent:null};return{result:await s._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(r);{let s,o=[];for(let c of i){let l={...t,common:{...t.common,issues:[]},parent:null},u=c._parseSync({data:t.data,path:t.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:l}),l.common.issues.length&&o.push(l.common.issues)}if(s)return t.common.issues.push(...s.ctx.common.issues),s.result;let a=o.map(c=>new Lr(c));return Bt(t,{code:Nt.invalid_union,unionErrors:a}),ye}}get options(){return this._def.options}};Mh.create=(n,e)=>new Mh({options:n,typeName:we.ZodUnion,...Ie(e)});_a=n=>n instanceof Ih?_a(n.schema):n instanceof Ps?_a(n.innerType()):n instanceof Nh?[n.value]:n instanceof Ah?n.options:n instanceof Rh?Ve.objectValues(n.enum):n instanceof Oh?_a(n._def.innerType):n instanceof Th?[void 0]:n instanceof Eh?[null]:n instanceof ws?[void 0,..._a(n.unwrap())]:n instanceof Co?[null,..._a(n.unwrap())]:n instanceof Qy||n instanceof Fh?_a(n.unwrap()):n instanceof Lh?_a(n._def.innerType):[],Fx=class n extends Fe{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==Gt.object)return Bt(t,{code:Nt.invalid_type,expected:Gt.object,received:t.parsedType}),ye;let i=this.discriminator,r=t.data[i],s=this.optionsMap.get(r);return s?t.common.async?s._parseAsync({data:t.data,path:t.path,parent:t}):s._parseSync({data:t.data,path:t.path,parent:t}):(Bt(t,{code:Nt.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[i]}),ye)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,i){let r=new Map;for(let s of t){let o=_a(s.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of o){if(r.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);r.set(a,s)}}return new n({typeName:we.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:r,...Ie(i)})}};Ch=class extends Fe{_parse(e){let{status:t,ctx:i}=this._processInputParams(e),r=(s,o)=>{if(Ox(s)||Ox(o))return ye;let a=$3(s.value,o.value);return a.valid?((Lx(s)||Lx(o))&&t.dirty(),{status:t.value,value:a.data}):(Bt(i,{code:Nt.invalid_intersection_types}),ye)};return i.common.async?Promise.all([this._def.left._parseAsync({data:i.data,path:i.path,parent:i}),this._def.right._parseAsync({data:i.data,path:i.path,parent:i})]).then(([s,o])=>r(s,o)):r(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}};Ch.create=(n,e,t)=>new Ch({left:n,right:e,typeName:we.ZodIntersection,...Ie(t)});Mo=class n extends Fe{_parse(e){let{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==Gt.array)return Bt(i,{code:Nt.invalid_type,expected:Gt.array,received:i.parsedType}),ye;if(i.data.length<this._def.items.length)return Bt(i,{code:Nt.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ye;!this._def.rest&&i.data.length>this._def.items.length&&(Bt(i,{code:Nt.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let s=[...i.data].map((o,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Ss(i,o,i.path,a)):null}).filter(o=>!!o);return i.common.async?Promise.all(s).then(o=>Ki.mergeArray(t,o)):Ki.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new n({...this._def,rest:e})}};Mo.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Mo({items:n,typeName:we.ZodTuple,rest:null,...Ie(e)})};zx=class n extends Fe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==Gt.object)return Bt(i,{code:Nt.invalid_type,expected:Gt.object,received:i.parsedType}),ye;let r=[],s=this._def.keyType,o=this._def.valueType;for(let a in i.data)r.push({key:s._parse(new Ss(i,a,i.path,a)),value:o._parse(new Ss(i,i.data[a],i.path,a)),alwaysSet:a in i.data});return i.common.async?Ki.mergeObjectAsync(t,r):Ki.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(e,t,i){return t instanceof Fe?new n({keyType:e,valueType:t,typeName:we.ZodRecord,...Ie(i)}):new n({keyType:Rc.create(),valueType:e,typeName:we.ZodRecord,...Ie(t)})}},km=class extends Fe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==Gt.map)return Bt(i,{code:Nt.invalid_type,expected:Gt.map,received:i.parsedType}),ye;let r=this._def.keyType,s=this._def.valueType,o=[...i.data.entries()].map(([a,c],l)=>({key:r._parse(new Ss(i,a,i.path,[l,"key"])),value:s._parse(new Ss(i,c,i.path,[l,"value"]))}));if(i.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of o){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return ye;(l.status==="dirty"||u.status==="dirty")&&t.dirty(),a.set(l.value,u.value)}return{status:t.value,value:a}})}else{let a=new Map;for(let c of o){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return ye;(l.status==="dirty"||u.status==="dirty")&&t.dirty(),a.set(l.value,u.value)}return{status:t.value,value:a}}}};km.create=(n,e,t)=>new km({valueType:e,keyType:n,typeName:we.ZodMap,...Ie(t)});Tm=class n extends Fe{_parse(e){let{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==Gt.set)return Bt(i,{code:Nt.invalid_type,expected:Gt.set,received:i.parsedType}),ye;let r=this._def;r.minSize!==null&&i.data.size<r.minSize.value&&(Bt(i,{code:Nt.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&i.data.size>r.maxSize.value&&(Bt(i,{code:Nt.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let s=this._def.valueType;function o(c){let l=new Set;for(let u of c){if(u.status==="aborted")return ye;u.status==="dirty"&&t.dirty(),l.add(u.value)}return{status:t.value,value:l}}let a=[...i.data.values()].map((c,l)=>s._parse(new Ss(i,c,i.path,l)));return i.common.async?Promise.all(a).then(c=>o(c)):o(a)}min(e,t){return new n({...this._def,minSize:{value:e,message:se.toString(t)}})}max(e,t){return new n({...this._def,maxSize:{value:e,message:se.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Tm.create=(n,e)=>new Tm({valueType:n,minSize:null,maxSize:null,typeName:we.ZodSet,...Ie(e)});Dx=class n extends Fe{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==Gt.function)return Bt(t,{code:Nt.invalid_type,expected:Gt.function,received:t.parsedType}),ye;function i(a,c){return Jy({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,bm(),ma].filter(l=>!!l),issueData:{code:Nt.invalid_arguments,argumentsError:c}})}function r(a,c){return Jy({data:a,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,bm(),ma].filter(l=>!!l),issueData:{code:Nt.invalid_return_type,returnTypeError:c}})}let s={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof Lc){let a=this;return lr(async function(...c){let l=new Lr([]),u=await a._def.args.parseAsync(c,s).catch(y=>{throw l.addIssue(i(c,y)),l}),p=await Reflect.apply(o,this,u);return await a._def.returns._def.type.parseAsync(p,s).catch(y=>{throw l.addIssue(r(p,y)),l})})}else{let a=this;return lr(function(...c){let l=a._def.args.safeParse(c,s);if(!l.success)throw new Lr([i(c,l.error)]);let u=Reflect.apply(o,this,l.data),p=a._def.returns.safeParse(u,s);if(!p.success)throw new Lr([r(u,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new n({...this._def,args:Mo.create(e).rest(ya.create())})}returns(e){return new n({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,i){return new n({args:e||Mo.create([]).rest(ya.create()),returns:t||ya.create(),typeName:we.ZodFunction,...Ie(i)})}},Ih=class extends Fe{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};Ih.create=(n,e)=>new Ih({getter:n,typeName:we.ZodLazy,...Ie(e)});Nh=class extends Fe{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return Bt(t,{received:t.data,code:Nt.invalid_literal,expected:this._def.value}),ye}return{status:"valid",value:e.data}}get value(){return this._def.value}};Nh.create=(n,e)=>new Nh({value:n,typeName:we.ZodLiteral,...Ie(e)});Ah=class n extends Fe{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),i=this._def.values;return Bt(t,{expected:Ve.joinValues(i),received:t.parsedType,code:Nt.invalid_type}),ye}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),i=this._def.values;return Bt(t,{received:t.data,code:Nt.invalid_enum_value,options:i}),ye}return lr(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return n.create(e,{...this._def,...t})}exclude(e,t=this._def){return n.create(this.options.filter(i=>!e.includes(i)),{...this._def,...t})}};Ah.create=MD;Rh=class extends Fe{_parse(e){let t=Ve.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(e);if(i.parsedType!==Gt.string&&i.parsedType!==Gt.number){let r=Ve.objectValues(t);return Bt(i,{expected:Ve.joinValues(r),received:i.parsedType,code:Nt.invalid_type}),ye}if(this._cache||(this._cache=new Set(Ve.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let r=Ve.objectValues(t);return Bt(i,{received:i.data,code:Nt.invalid_enum_value,options:r}),ye}return lr(e.data)}get enum(){return this._def.values}};Rh.create=(n,e)=>new Rh({values:n,typeName:we.ZodNativeEnum,...Ie(e)});Lc=class extends Fe{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==Gt.promise&&t.common.async===!1)return Bt(t,{code:Nt.invalid_type,expected:Gt.promise,received:t.parsedType}),ye;let i=t.parsedType===Gt.promise?t.data:Promise.resolve(t.data);return lr(i.then(r=>this._def.type.parseAsync(r,{path:t.path,errorMap:t.common.contextualErrorMap})))}};Lc.create=(n,e)=>new Lc({type:n,typeName:we.ZodPromise,...Ie(e)});Ps=class extends Fe{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===we.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:i}=this._processInputParams(e),r=this._def.effect||null,s={addIssue:o=>{Bt(i,o),o.fatal?t.abort():t.dirty()},get path(){return i.path}};if(s.addIssue=s.addIssue.bind(s),r.type==="preprocess"){let o=r.transform(i.data,s);if(i.common.async)return Promise.resolve(o).then(async a=>{if(t.value==="aborted")return ye;let c=await this._def.schema._parseAsync({data:a,path:i.path,parent:i});return c.status==="aborted"?ye:c.status==="dirty"?vh(c.value):t.value==="dirty"?vh(c.value):c});{if(t.value==="aborted")return ye;let a=this._def.schema._parseSync({data:o,path:i.path,parent:i});return a.status==="aborted"?ye:a.status==="dirty"?vh(a.value):t.value==="dirty"?vh(a.value):a}}if(r.type==="refinement"){let o=a=>{let c=r.refinement(a,s);if(i.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(i.common.async===!1){let a=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});return a.status==="aborted"?ye:(a.status==="dirty"&&t.dirty(),o(a.value),{status:t.value,value:a.value})}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(a=>a.status==="aborted"?ye:(a.status==="dirty"&&t.dirty(),o(a.value).then(()=>({status:t.value,value:a.value}))))}if(r.type==="transform")if(i.common.async===!1){let o=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(!Ac(o))return ye;let a=r.transform(o.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(o=>Ac(o)?Promise.resolve(r.transform(o.value,s)).then(a=>({status:t.value,value:a})):ye);Ve.assertNever(r)}};Ps.create=(n,e,t)=>new Ps({schema:n,typeName:we.ZodEffects,effect:e,...Ie(t)});Ps.createWithPreprocess=(n,e,t)=>new Ps({schema:e,effect:{type:"preprocess",transform:n},typeName:we.ZodEffects,...Ie(t)});ws=class extends Fe{_parse(e){return this._getType(e)===Gt.undefined?lr(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ws.create=(n,e)=>new ws({innerType:n,typeName:we.ZodOptional,...Ie(e)});Co=class extends Fe{_parse(e){return this._getType(e)===Gt.null?lr(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Co.create=(n,e)=>new Co({innerType:n,typeName:we.ZodNullable,...Ie(e)});Oh=class extends Fe{_parse(e){let{ctx:t}=this._processInputParams(e),i=t.data;return t.parsedType===Gt.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Oh.create=(n,e)=>new Oh({innerType:n,typeName:we.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Ie(e)});Lh=class extends Fe{_parse(e){let{ctx:t}=this._processInputParams(e),i={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return vm(r)?r.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Lr(i.common.issues)},input:i.data})})):{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new Lr(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}};Lh.create=(n,e)=>new Lh({innerType:n,typeName:we.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Ie(e)});Em=class extends Fe{_parse(e){if(this._getType(e)!==Gt.nan){let i=this._getOrReturnCtx(e);return Bt(i,{code:Nt.invalid_type,expected:Gt.nan,received:i.parsedType}),ye}return{status:"valid",value:e.data}}};Em.create=n=>new Em({typeName:we.ZodNaN,...Ie(n)});Dht=Symbol("zod_brand"),Qy=class extends Fe{_parse(e){let{ctx:t}=this._processInputParams(e),i=t.data;return this._def.type._parse({data:i,path:t.path,parent:t})}unwrap(){return this._def.type}},tg=class n extends Fe{_parse(e){let{status:t,ctx:i}=this._processInputParams(e);if(i.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});return s.status==="aborted"?ye:s.status==="dirty"?(t.dirty(),vh(s.value)):this._def.out._parseAsync({data:s.value,path:i.path,parent:i})})();{let r=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return r.status==="aborted"?ye:r.status==="dirty"?(t.dirty(),{status:"dirty",value:r.value}):this._def.out._parseSync({data:r.value,path:i.path,parent:i})}}static create(e,t){return new n({in:e,out:t,typeName:we.ZodPipeline})}},Fh=class extends Fe{_parse(e){let t=this._def.innerType._parse(e),i=r=>(Ac(r)&&(r.value=Object.freeze(r.value)),r);return vm(t)?t.then(r=>i(r)):i(t)}unwrap(){return this._def.innerType}};Fh.create=(n,e)=>new Fh({innerType:n,typeName:we.ZodReadonly,...Ie(e)});$ht={object:Fr.lazycreate};(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(we||(we={}));jht=(n,e={message:`Input not instance of ${n.name}`})=>CD(t=>t instanceof n,e),ID=Rc.create,ND=wh.create,Bht=Em.create,Yht=Sh.create,AD=Ph.create,Xht=kh.create,Uht=Sm.create,Vht=Th.create,Ght=Eh.create,Hht=Oc.create,Wht=ya.create,qht=Ws.create,Zht=Pm.create,Kht=ga.create,Jht=Fr.create,Qht=Fr.strictCreate,tdt=Mh.create,edt=Fx.create,ndt=Ch.create,idt=Mo.create,rdt=zx.create,sdt=km.create,odt=Tm.create,adt=Dx.create,cdt=Ih.create,ldt=Nh.create,udt=Ah.create,pdt=Rh.create,hdt=Lc.create,ddt=Ps.create,fdt=ws.create,mdt=Co.create,_dt=Ps.createWithPreprocess,ydt=tg.create,gdt=()=>ID().optional(),xdt=()=>ND().optional(),bdt=()=>AD().optional(),vdt={string:(n=>Rc.create({...n,coerce:!0})),number:(n=>wh.create({...n,coerce:!0})),boolean:(n=>Ph.create({...n,coerce:!0})),bigint:(n=>Sh.create({...n,coerce:!0})),date:(n=>kh.create({...n,coerce:!0}))},wdt=ye});var h={};xh(h,{BRAND:()=>Dht,DIRTY:()=>vh,EMPTY_PATH:()=>_ht,INVALID:()=>ye,NEVER:()=>wdt,OK:()=>lr,ParseStatus:()=>Ki,Schema:()=>Fe,ZodAny:()=>Oc,ZodArray:()=>ga,ZodBigInt:()=>Sh,ZodBoolean:()=>Ph,ZodBranded:()=>Qy,ZodCatch:()=>Lh,ZodDate:()=>kh,ZodDefault:()=>Oh,ZodDiscriminatedUnion:()=>Fx,ZodEffects:()=>Ps,ZodEnum:()=>Ah,ZodError:()=>Lr,ZodFirstPartyTypeKind:()=>we,ZodFunction:()=>Dx,ZodIntersection:()=>Ch,ZodIssueCode:()=>Nt,ZodLazy:()=>Ih,ZodLiteral:()=>Nh,ZodMap:()=>km,ZodNaN:()=>Em,ZodNativeEnum:()=>Rh,ZodNever:()=>Ws,ZodNull:()=>Eh,ZodNullable:()=>Co,ZodNumber:()=>wh,ZodObject:()=>Fr,ZodOptional:()=>ws,ZodParsedType:()=>Gt,ZodPipeline:()=>tg,ZodPromise:()=>Lc,ZodReadonly:()=>Fh,ZodRecord:()=>zx,ZodSchema:()=>Fe,ZodSet:()=>Tm,ZodString:()=>Rc,ZodSymbol:()=>Sm,ZodTransformer:()=>Ps,ZodTuple:()=>Mo,ZodType:()=>Fe,ZodUndefined:()=>Th,ZodUnion:()=>Mh,ZodUnknown:()=>ya,ZodVoid:()=>Pm,addIssueToContext:()=>Bt,any:()=>Hht,array:()=>Kht,bigint:()=>Yht,boolean:()=>AD,coerce:()=>vdt,custom:()=>CD,date:()=>Xht,datetimeRegex:()=>ED,defaultErrorMap:()=>ma,discriminatedUnion:()=>edt,effect:()=>ddt,enum:()=>udt,function:()=>adt,getErrorMap:()=>bm,getParsedType:()=>Eo,instanceof:()=>jht,intersection:()=>ndt,isAborted:()=>Ox,isAsync:()=>vm,isDirty:()=>Lx,isValid:()=>Ac,late:()=>$ht,lazy:()=>cdt,literal:()=>ldt,makeIssue:()=>Jy,map:()=>sdt,nan:()=>Bht,nativeEnum:()=>pdt,never:()=>qht,null:()=>Ght,nullable:()=>mdt,number:()=>ND,object:()=>Jht,objectUtil:()=>L3,oboolean:()=>bdt,onumber:()=>xdt,optional:()=>fdt,ostring:()=>gdt,pipeline:()=>ydt,preprocess:()=>_dt,promise:()=>hdt,quotelessJson:()=>dht,record:()=>rdt,set:()=>odt,setErrorMap:()=>mht,strictObject:()=>Qht,string:()=>ID,symbol:()=>Uht,transformer:()=>ddt,tuple:()=>idt,undefined:()=>Vht,union:()=>tdt,unknown:()=>Wht,util:()=>Ve,void:()=>Zht});var j3=qt(()=>{"use strict";Rx();z3();vD();Ky();RD();Ax()});var J=qt(()=>{"use strict";j3();j3()});var jh={};xh(jh,{all_layers:()=>Im,any_circuit_element:()=>qj,any_soup_element:()=>$h,any_source_component:()=>UD,battery_capacity:()=>DD,brep_shape:()=>k$,cad_component:()=>Dj,capacitance:()=>xa,circuit_json_footprint_load_error:()=>Vx,current:()=>Pdt,distance:()=>X,duration_ms:()=>eg,experiment_type:()=>Xj,external_footprint_load_error:()=>Nm,frequency:()=>pr,getZodPrefixedIdWithDefault:()=>At,inductance:()=>$x,layer_ref:()=>he,layer_string:()=>Y3,length:()=>$,ms:()=>ur,ninePointAnchor:()=>ng,pcb_autorouting_error:()=>Pj,pcb_board:()=>Z$,pcb_breakout_point:()=>kj,pcb_component:()=>E$,pcb_component_invalid_layer_error:()=>Am,pcb_component_outside_board_error:()=>Rj,pcb_copper_pour:()=>Aj,pcb_copper_pour_brep:()=>Ij,pcb_copper_pour_polygon:()=>Nj,pcb_copper_pour_rect:()=>Cj,pcb_copper_text:()=>ij,pcb_courtyard_outline:()=>Fj,pcb_courtyard_polygon:()=>zj,pcb_courtyard_rect:()=>Lj,pcb_cutout:()=>vj,pcb_cutout_circle:()=>xj,pcb_cutout_polygon:()=>bj,pcb_cutout_rect:()=>gj,pcb_fabrication_note_dimension:()=>uj,pcb_fabrication_note_path:()=>cj,pcb_fabrication_note_rect:()=>lj,pcb_fabrication_note_text:()=>aj,pcb_footprint_overlap_error:()=>_j,pcb_ground_plane:()=>Tj,pcb_ground_plane_region:()=>Ej,pcb_group:()=>Sj,pcb_hole:()=>O$,pcb_hole_circle_or_square_shape:()=>Odt,pcb_hole_circle_shape:()=>Adt,pcb_hole_oval_shape:()=>Ldt,pcb_hole_pill_shape:()=>Fdt,pcb_hole_rect_shape:()=>Rdt,pcb_hole_rotated_pill_shape:()=>zdt,pcb_keepout:()=>yj,pcb_manual_edit_conflict_warning:()=>Gx,pcb_missing_footprint_error:()=>wj,pcb_net:()=>W$,pcb_note_dimension:()=>mj,pcb_note_line:()=>fj,pcb_note_path:()=>dj,pcb_note_rect:()=>hj,pcb_note_text:()=>pj,pcb_panel:()=>K$,pcb_placement_error:()=>J$,pcb_plated_hole:()=>L$,pcb_port:()=>F$,pcb_port_not_connected_error:()=>H$,pcb_port_not_matched_error:()=>G$,pcb_route_hint:()=>T$,pcb_route_hints:()=>Ndt,pcb_silkscreen_circle:()=>sj,pcb_silkscreen_line:()=>tj,pcb_silkscreen_oval:()=>oj,pcb_silkscreen_path:()=>ej,pcb_silkscreen_rect:()=>rj,pcb_silkscreen_text:()=>nj,pcb_smtpad:()=>D$,pcb_smtpad_pill:()=>z$,pcb_solder_paste:()=>$$,pcb_text:()=>j$,pcb_thermal_spoke:()=>Mj,pcb_trace:()=>X$,pcb_trace_error:()=>U$,pcb_trace_hint:()=>Q$,pcb_trace_missing_error:()=>V$,pcb_trace_route_point:()=>Ux,pcb_trace_route_point_via:()=>Y$,pcb_trace_route_point_wire:()=>B$,pcb_via:()=>q$,pcb_via_clearance_error:()=>Oj,point:()=>Jt,point3:()=>zh,point_with_bulge:()=>P$,port_arrangement:()=>i$,position:()=>Tdt,position3:()=>Edt,resistance:()=>Fc,ring:()=>X3,rotation:()=>He,route_hint_point:()=>Ji,schematic_arc:()=>c$,schematic_box:()=>JD,schematic_circle:()=>a$,schematic_component:()=>r$,schematic_component_port_arrangement_by_sides:()=>n$,schematic_component_port_arrangement_by_size:()=>e$,schematic_debug_line:()=>_$,schematic_debug_object:()=>g$,schematic_debug_object_base:()=>Yx,schematic_debug_point:()=>y$,schematic_debug_rect:()=>m$,schematic_error:()=>d$,schematic_group:()=>b$,schematic_layout_error:()=>f$,schematic_line:()=>s$,schematic_manual_edit_conflict_warning:()=>Xx,schematic_net_label:()=>h$,schematic_path:()=>QD,schematic_pin_styles:()=>t$,schematic_port:()=>p$,schematic_rect:()=>o$,schematic_sheet:()=>S$,schematic_table:()=>v$,schematic_table_cell:()=>w$,schematic_text:()=>u$,schematic_trace:()=>l$,schematic_voltage_probe:()=>x$,simulation_ac_voltage_source:()=>Bj,simulation_dc_voltage_source:()=>jj,simulation_experiment:()=>Uj,simulation_switch:()=>Gj,simulation_transient_voltage_graph:()=>Vj,simulation_unknown_experiment_error:()=>Wj,simulation_voltage_probe:()=>Hj,simulation_voltage_source:()=>Yj,size:()=>U3,source_board:()=>qD,source_component_base:()=>fi,source_failed_to_create_component_error:()=>YD,source_group:()=>HD,source_manually_placed_via:()=>KD,source_missing_property_error:()=>BD,source_net:()=>WD,source_pcb_ground_plane:()=>ZD,source_pin_missing_trace_warning:()=>lE,source_port:()=>VD,source_project_metadata:()=>aE,source_property_ignored_warning:()=>XD,source_simple_battery:()=>Z3,source_simple_capacitor:()=>V3,source_simple_chip:()=>W3,source_simple_crystal:()=>jD,source_simple_diode:()=>jx,source_simple_ground:()=>$D,source_simple_inductor:()=>K3,source_simple_led:()=>H3,source_simple_mosfet:()=>sE,source_simple_pin_header:()=>tE,source_simple_pinout:()=>eE,source_simple_potentiometer:()=>Q3,source_simple_power_source:()=>q3,source_simple_push_button:()=>J3,source_simple_resistor:()=>G3,source_simple_resonator:()=>nE,source_simple_switch:()=>oE,source_simple_test_point:()=>rE,source_simple_transistor:()=>iE,source_trace:()=>GD,source_trace_not_connected_error:()=>cE,supplier_name:()=>Cm,time:()=>kdt,timestamp:()=>zD,unknown_error_finding_part:()=>Bx,visible_layer:()=>Zs,voltage:()=>Si,wave_shape:()=>$j});function Sdt(n){for(let[e,t]of Object.entries(FD))if(n in t.variants)return{baseUnit:t.baseUnit,conversionFactor:t.variants[n]};return{baseUnit:n,conversionFactor:1}}function qs(n){if(n==null)return{parsedUnit:null,unitOfValue:null,value:null};if(typeof n=="string"&&n.match(/^-?[\d\.]+$/))return{value:Number.parseFloat(n),parsedUnit:null,unitOfValue:null};if(typeof n=="number")return{value:n,parsedUnit:null,unitOfValue:null};if(typeof n=="object"&&"x"in n&&"y"in n){let{parsedUnit:a,unitOfValue:c}=qs(n.x),l=qs(n.x),u=qs(n.y);return l.value===null||u.value===null?{parsedUnit:null,unitOfValue:null,value:null}:{parsedUnit:a,unitOfValue:c,value:{x:l.value,y:u.value}}}let t=n.toString().split("").reverse().join("").match(/[^\d\s]+/)?.[0];if(!t)throw new Error(`Could not determine unit: "${n}"`);let i=t.split("").reverse().join(""),r=n.slice(0,-i.length);if(i in LD&&!B3.has(i)){let a=LD[i];return{parsedUnit:null,unitOfValue:null,value:Number.parseFloat(r)*a}}let{baseUnit:s,conversionFactor:o}=Sdt(i);return{parsedUnit:i,unitOfValue:s,value:o*Number.parseFloat(r)}}var FD,B3,LD,Fc,xa,$x,Si,$,pr,X,Pdt,eg,kdt,ur,zD,He,DD,_t,Dh,Jt,Tdt,zh,Edt,U3,Mdt,At,ng,Cm,fi,V3,G3,jx,H3,$D,W3,q3,Cdt,Z3,K3,J3,Q3,jD,tE,eE,nE,iE,rE,sE,oE,aE,BD,YD,cE,XD,lE,UD,VD,GD,HD,WD,qD,ZD,Im,Y3,he,Zs,KD,Bx,JD,QD,t$,e$,n$,i$,r$,s$,o$,a$,c$,l$,Idt,u$,p$,h$,d$,f$,Yx,m$,_$,y$,g$,x$,Xx,b$,v$,w$,S$,P$,X3,k$,T$,Ndt,Ji,E$,M$,Adt,C$,Rdt,I$,Odt,N$,Ldt,A$,Fdt,R$,zdt,O$,Ddt,$dt,jdt,Bdt,Ydt,L$,F$,Xdt,Udt,Vdt,z$,Gdt,Hdt,D$,Wdt,qdt,Zdt,Kdt,Jdt,$$,j$,B$,Y$,Ux,X$,U$,V$,G$,H$,W$,q$,Z$,K$,J$,Q$,tj,ej,nj,ij,rj,sj,oj,aj,cj,lj,uj,pj,hj,dj,fj,mj,_j,yj,uE,gj,xj,bj,vj,wj,Nm,Vx,Sj,Pj,Gx,kj,Tj,Ej,Mj,pE,Cj,Ij,Nj,Aj,Rj,Am,Oj,Lj,Fj,zj,Dj,$j,Qdt,jj,Bj,Yj,Xj,Uj,Vj,Gj,Hj,Wj,qj,$h,wt=qt(()=>{"use strict";J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();J();FD={Hz:{baseUnit:"Hz",variants:{MHz:1e6,kHz:1e3,Hz:1}},g:{baseUnit:"g",variants:{kg:1e3,g:1}},\u03A9:{baseUnit:"\u03A9",variants:{m\u03A9:.001,\u03A9:1,k\u03A9:1e3,K\u03A9:1e3,kohm:1e3,M\u03A9:1e6,G\u03A9:1e9,T\u03A9:1e12}},V:{baseUnit:"V",variants:{mV:.001,V:1,kV:1e3,KV:1e3,MV:1e6,GV:1e9,TV:1e12}},A:{baseUnit:"A",variants:{\u00B5A:1e-6,mA:.001,ma:.001,A:1,kA:1e3,MA:1e6}},F:{baseUnit:"F",variants:{pF:1e-12,nF:1e-9,\u00B5F:1e-6,uF:1e-6,mF:.001,F:1}},ml:{baseUnit:"ml",variants:{ml:1,mL:1,l:1e3,L:1e3}},deg:{baseUnit:"deg",variants:{rad:180/Math.PI}},ms:{baseUnit:"ms",variants:{fs:1e-12,ps:1e-9,ns:1e-6,us:.001,\u00B5s:.001,ms:1,s:1e3}},mm:{baseUnit:"mm",variants:{nm:1e-6,\u00B5m:.001,um:.001,mm:1,cm:10,dm:100,m:1e3,km:1e6,in:25.4,ft:304.8,IN:25.4,FT:304.8,yd:914.4,mi:1609344,mil:.0254}}},B3=new Set;for(let[n,e]of Object.entries(FD)){B3.add(n);for(let t of Object.keys(e.variants))B3.add(t)}LD={tera:1e12,T:1e12,giga:1e9,G:1e9,mega:1e6,M:1e6,kilo:1e3,k:1e3,deci:.1,d:.1,centi:.01,c:.01,milli:.001,m:.001,micro:1e-6,u:1e-6,\u00B5:1e-6,nano:1e-9,n:1e-9,pico:1e-12,p:1e-12};Fc=h.string().or(h.number()).transform(n=>qs(n).value),xa=h.string().or(h.number()).transform(n=>qs(n).value).transform(n=>Number.parseFloat(n.toPrecision(12))),$x=h.string().or(h.number()).transform(n=>qs(n).value),Si=h.string().or(h.number()).transform(n=>qs(n).value),$=h.string().or(h.number()).transform(n=>qs(n).value),pr=h.string().or(h.number()).transform(n=>qs(n).value),X=$,Pdt=h.string().or(h.number()).transform(n=>qs(n).value),eg=h.string().or(h.number()).transform(n=>qs(n).value),kdt=eg,ur=eg,zD=h.string().datetime(),He=h.string().or(h.number()).transform(n=>typeof n=="number"?n:n.endsWith("deg")?Number.parseFloat(n.split("deg")[0]):n.endsWith("rad")?Number.parseFloat(n.split("rad")[0])*180/Math.PI:Number.parseFloat(n)),DD=h.number().or(h.string().endsWith("mAh")).transform(n=>{if(typeof n=="string"){let e=n.replace("mAh",""),t=Number.parseFloat(e);if(Number.isNaN(t))throw new Error("Invalid capacity");return t}return n}).describe("Battery capacity in mAh"),_t=n=>{};_t("extra props b");_t("missing props b");_t(!0);_t("mismatched prop types: a");Dh=n=>{};Dh(!0);Dh('T1 has extra: "c", T2 has extra: "d"');Dh('T1 has extra: "c"');Dh('T2 has extra: "c"');Dh('T1 has extra: "d", T2 has extra: "c"');Dh(!0);Jt=h.object({x:X,y:X}),Tdt=Jt;_t(!0);_t(!0);zh=h.object({x:X,y:X,z:X}),Edt=zh;_t(!0);U3=h.object({width:h.number(),height:h.number()});_t(!0);Mdt=n=>{let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";return Array.from({length:n},()=>e[Math.floor(Math.random()*e.length)]).join("")},At=n=>h.string().optional().default(()=>`${n}_${Mdt(10)}`),ng=h.enum(["top_left","top_center","top_right","center_left","center","center_right","bottom_left","bottom_center","bottom_right"]);_t(!0);Cm=h.enum(["jlcpcb","macrofab","pcbway","digikey","mouser","lcsc"]);_t(!0);fi=h.object({type:h.literal("source_component"),ftype:h.string().optional(),source_component_id:h.string(),name:h.string(),manufacturer_part_number:h.string().optional(),supplier_part_numbers:h.record(Cm,h.array(h.string())).optional(),display_value:h.string().optional(),are_pins_interchangeable:h.boolean().optional(),internally_connected_source_port_ids:h.array(h.array(h.string())).optional(),source_group_id:h.string().optional(),subcircuit_id:h.string().optional()});_t(!0);V3=fi.extend({ftype:h.literal("simple_capacitor"),capacitance:xa,max_voltage_rating:Si.optional(),display_capacitance:h.string().optional(),max_decoupling_trace_length:X.optional()});_t(!0);G3=fi.extend({ftype:h.literal("simple_resistor"),resistance:Fc,display_resistance:h.string().optional()});_t(!0);jx=fi.extend({ftype:h.literal("simple_diode")});_t(!0);H3=jx.extend({ftype:h.literal("simple_led"),color:h.string().optional(),wavelength:h.string().optional()});_t(!0);$D=fi.extend({ftype:h.literal("simple_ground")});_t(!0);W3=fi.extend({ftype:h.literal("simple_chip")});_t(!0);q3=fi.extend({ftype:h.literal("simple_power_source"),voltage:Si});_t(!0);Cdt=fi.extend({ftype:h.literal("simple_fuse"),current_rating_amps:h.number().describe("Nominal current in amps the fuse is rated for"),voltage_rating_volts:h.number().describe("Voltage rating in volts, e.g. \xB15V would be 5")});_t(!0);Z3=fi.extend({ftype:h.literal("simple_battery"),capacity:DD});_t(!0);K3=fi.extend({ftype:h.literal("simple_inductor"),inductance:$x,max_current_rating:h.number().optional()});_t(!0);J3=fi.extend({ftype:h.literal("simple_push_button")});_t(!0);Q3=fi.extend({ftype:h.literal("simple_potentiometer"),max_resistance:Fc});_t(!0);jD=fi.extend({ftype:h.literal("simple_crystal"),frequency:h.number().describe("Frequency in Hz"),load_capacitance:h.number().optional().describe("Load capacitance in pF")});_t(!0);tE=fi.extend({ftype:h.literal("simple_pin_header"),pin_count:h.number(),gender:h.enum(["male","female"]).optional().default("male")});_t(!0);eE=fi.extend({ftype:h.literal("simple_pinout")});_t(!0);nE=fi.extend({ftype:h.literal("simple_resonator"),load_capacitance:xa,equivalent_series_resistance:Fc.optional(),frequency:pr});_t(!0);iE=fi.extend({ftype:h.literal("simple_transistor"),transistor_type:h.enum(["npn","pnp"])});_t(!0);rE=fi.extend({ftype:h.literal("simple_test_point"),footprint_variant:h.enum(["pad","through_hole"]).optional(),pad_shape:h.enum(["rect","circle"]).optional(),pad_diameter:h.union([h.number(),h.string()]).optional(),hole_diameter:h.union([h.number(),h.string()]).optional(),width:h.union([h.number(),h.string()]).optional(),height:h.union([h.number(),h.string()]).optional()});_t(!0);sE=fi.extend({ftype:h.literal("simple_mosfet"),channel_type:h.enum(["n","p"]),mosfet_mode:h.enum(["enhancement","depletion"])});_t(!0);oE=fi.extend({ftype:h.literal("simple_switch")});_t(!0);aE=h.object({type:h.literal("source_project_metadata"),name:h.string().optional(),software_used_string:h.string().optional(),project_url:h.string().optional(),created_at:zD.optional()});_t(!0);BD=h.object({type:h.literal("source_missing_property_error"),source_missing_property_error_id:At("source_missing_property_error"),source_component_id:h.string(),property_name:h.string(),subcircuit_id:h.string().optional(),error_type:h.literal("source_missing_property_error").default("source_missing_property_error"),message:h.string()}).describe("The source code is missing a property");_t(!0);YD=h.object({type:h.literal("source_failed_to_create_component_error"),source_failed_to_create_component_error_id:At("source_failed_to_create_component_error"),error_type:h.literal("source_failed_to_create_component_error").default("source_failed_to_create_component_error"),component_name:h.string().optional(),subcircuit_id:h.string().optional(),parent_source_component_id:h.string().optional(),message:h.string(),pcb_center:h.object({x:h.number().optional(),y:h.number().optional()}).optional(),schematic_center:h.object({x:h.number().optional(),y:h.number().optional()}).optional()}).describe("Error emitted when a component fails to be constructed");_t(!0);cE=h.object({type:h.literal("source_trace_not_connected_error"),source_trace_not_connected_error_id:At("source_trace_not_connected_error"),error_type:h.literal("source_trace_not_connected_error").default("source_trace_not_connected_error"),message:h.string(),subcircuit_id:h.string().optional(),source_group_id:h.string().optional(),source_trace_id:h.string().optional(),connected_source_port_ids:h.array(h.string()).optional(),selectors_not_found:h.array(h.string()).optional()}).describe("Occurs when a source trace selector does not match any ports");_t(!0);XD=h.object({type:h.literal("source_property_ignored_warning"),source_property_ignored_warning_id:At("source_property_ignored_warning"),source_component_id:h.string(),property_name:h.string(),subcircuit_id:h.string().optional(),error_type:h.literal("source_property_ignored_warning").default("source_property_ignored_warning"),message:h.string()}).describe("The source property was ignored");_t(!0);lE=h.object({type:h.literal("source_pin_missing_trace_warning"),source_pin_missing_trace_warning_id:At("source_pin_missing_trace_warning"),warning_type:h.literal("source_pin_missing_trace_warning").default("source_pin_missing_trace_warning"),message:h.string(),source_component_id:h.string(),source_port_id:h.string(),subcircuit_id:h.string().optional()}).describe("Warning emitted when a source component pin is missing a trace connection");_t(!0);UD=h.union([G3,V3,jx,H3,$D,W3,q3,Z3,K3,J3,Q3,jD,tE,eE,nE,oE,iE,rE,sE,Cdt,aE,BD,YD,cE,XD,lE]);_t(!0);VD=h.object({type:h.literal("source_port"),pin_number:h.number().optional(),port_hints:h.array(h.string()).optional(),name:h.string(),source_port_id:h.string(),source_component_id:h.string().optional(),source_group_id:h.string().optional(),subcircuit_id:h.string().optional(),subcircuit_connectivity_map_key:h.string().optional()});_t(!0);GD=h.object({type:h.literal("source_trace"),source_trace_id:h.string(),connected_source_port_ids:h.array(h.string()),connected_source_net_ids:h.array(h.string()),subcircuit_id:h.string().optional(),subcircuit_connectivity_map_key:h.string().optional(),max_length:h.number().optional(),min_trace_thickness:h.number().optional(),display_name:h.string().optional()});_t(!0);HD=h.object({type:h.literal("source_group"),source_group_id:h.string(),subcircuit_id:h.string().optional(),parent_subcircuit_id:h.string().optional(),parent_source_group_id:h.string().optional(),is_subcircuit:h.boolean().optional(),show_as_schematic_box:h.boolean().optional(),name:h.string().optional(),was_automatically_named:h.boolean().optional()});_t(!0);WD=h.object({type:h.literal("source_net"),source_net_id:h.string(),name:h.string(),member_source_group_ids:h.array(h.string()),is_power:h.boolean().optional(),is_ground:h.boolean().optional(),is_digital_signal:h.boolean().optional(),is_analog_signal:h.boolean().optional(),is_positive_voltage_source:h.boolean().optional(),trace_width:h.number().optional(),subcircuit_id:h.string().optional(),subcircuit_connectivity_map_key:h.string().optional()});_t(!0);qD=h.object({type:h.literal("source_board"),source_board_id:h.string(),source_group_id:h.string(),title:h.string().optional()}).describe("Defines a board in the source domain");_t(!0);ZD=h.object({type:h.literal("source_pcb_ground_plane"),source_pcb_ground_plane_id:h.string(),source_group_id:h.string(),source_net_id:h.string(),subcircuit_id:h.string().optional()}).describe("Defines a ground plane in the source domain");_t(!0);Im=["top","bottom","inner1","inner2","inner3","inner4","inner5","inner6"],Y3=h.enum(Im),he=Y3.or(h.object({name:Y3})).transform(n=>typeof n=="string"?n:n.name);_t(!0);Zs=h.enum(["top","bottom"]),KD=h.object({type:h.literal("source_manually_placed_via"),source_manually_placed_via_id:h.string(),source_group_id:h.string(),source_net_id:h.string(),subcircuit_id:h.string().optional(),source_trace_id:h.string().optional()}).describe("Defines a via that is manually placed in the source domain");_t(!0);Bx=h.object({type:h.literal("unknown_error_finding_part"),unknown_error_finding_part_id:At("unknown_error_finding_part"),error_type:h.literal("unknown_error_finding_part").default("unknown_error_finding_part"),message:h.string(),source_component_id:h.string().optional(),subcircuit_id:h.string().optional()}).describe("Error emitted when an unexpected error occurs while finding a part");_t(!0);JD=h.object({type:h.literal("schematic_box"),schematic_component_id:h.string().optional(),width:X,height:X,is_dashed:h.boolean().default(!1),x:X,y:X,subcircuit_id:h.string().optional()}).describe("Draws a box on the schematic");_t(!0);QD=h.object({type:h.literal("schematic_path"),schematic_component_id:h.string(),fill_color:h.enum(["red","blue"]).optional(),is_filled:h.boolean().optional(),points:h.array(Jt),subcircuit_id:h.string().optional()});_t(!0);t$=h.record(h.object({left_margin:$.optional(),right_margin:$.optional(),top_margin:$.optional(),bottom_margin:$.optional()})),e$=h.object({left_size:h.number(),right_size:h.number(),top_size:h.number().optional(),bottom_size:h.number().optional()});_t(!0);n$=h.object({left_side:h.object({pins:h.array(h.number()),direction:h.enum(["top-to-bottom","bottom-to-top"]).optional()}).optional(),right_side:h.object({pins:h.array(h.number()),direction:h.enum(["top-to-bottom","bottom-to-top"]).optional()}).optional(),top_side:h.object({pins:h.array(h.number()),direction:h.enum(["left-to-right","right-to-left"]).optional()}).optional(),bottom_side:h.object({pins:h.array(h.number()),direction:h.enum(["left-to-right","right-to-left"]).optional()}).optional()});_t(!0);i$=h.union([e$,n$]),r$=h.object({type:h.literal("schematic_component"),size:U3,center:Jt,source_component_id:h.string().optional(),schematic_component_id:h.string(),pin_spacing:$.optional(),pin_styles:t$.optional(),box_width:$.optional(),symbol_name:h.string().optional(),port_arrangement:i$.optional(),port_labels:h.record(h.string()).optional(),symbol_display_value:h.string().optional(),subcircuit_id:h.string().optional(),schematic_group_id:h.string().optional(),is_schematic_group:h.boolean().optional(),source_group_id:h.string().optional(),is_box_with_pins:h.boolean().optional().default(!0)});_t(!0);s$=h.object({type:h.literal("schematic_line"),schematic_line_id:At("schematic_line"),schematic_component_id:h.string(),x1:X,y1:X,x2:X,y2:X,stroke_width:X.nullable().optional(),color:h.string().default("#000000"),is_dashed:h.boolean().default(!1),subcircuit_id:h.string().optional()}).describe("Draws a styled line on the schematic");_t(!0);o$=h.object({type:h.literal("schematic_rect"),schematic_rect_id:At("schematic_rect"),schematic_component_id:h.string(),center:Jt,width:X,height:X,rotation:He.default(0),stroke_width:X.nullable().optional(),color:h.string().default("#000000"),is_filled:h.boolean().default(!1),fill_color:h.string().optional(),is_dashed:h.boolean().default(!1),subcircuit_id:h.string().optional()}).describe("Draws a styled rectangle on the schematic");_t(!0);a$=h.object({type:h.literal("schematic_circle"),schematic_circle_id:At("schematic_circle"),schematic_component_id:h.string(),center:Jt,radius:X,stroke_width:X.nullable().optional(),color:h.string().default("#000000"),is_filled:h.boolean().default(!1),fill_color:h.string().optional(),is_dashed:h.boolean().default(!1),subcircuit_id:h.string().optional()}).describe("Draws a styled circle on the schematic");_t(!0);c$=h.object({type:h.literal("schematic_arc"),schematic_arc_id:At("schematic_arc"),schematic_component_id:h.string(),center:Jt,radius:X,start_angle_degrees:He,end_angle_degrees:He,direction:h.enum(["clockwise","counterclockwise"]).default("counterclockwise"),stroke_width:X.nullable().optional(),color:h.string().default("#000000"),is_dashed:h.boolean().default(!1),subcircuit_id:h.string().optional()}).describe("Draws a styled arc on the schematic");_t(!0);l$=h.object({type:h.literal("schematic_trace"),schematic_trace_id:h.string(),source_trace_id:h.string().optional(),junctions:h.array(h.object({x:h.number(),y:h.number()})),edges:h.array(h.object({from:h.object({x:h.number(),y:h.number()}),to:h.object({x:h.number(),y:h.number()}),is_crossing:h.boolean().optional(),from_schematic_port_id:h.string().optional(),to_schematic_port_id:h.string().optional()})),subcircuit_id:h.string().optional(),subcircuit_connectivity_map_key:h.string().optional()});_t(!0);Idt=h.enum(["center","left","right","top","bottom"]);_t(!0);u$=h.object({type:h.literal("schematic_text"),schematic_component_id:h.string().optional(),schematic_text_id:h.string(),text:h.string(),font_size:h.number().default(.18),position:h.object({x:X,y:X}),rotation:h.number().default(0),anchor:h.union([Idt.describe("legacy"),ng]).default("center"),color:h.string().default("#000000"),subcircuit_id:h.string().optional()});_t(!0);p$=h.object({type:h.literal("schematic_port"),schematic_port_id:h.string(),source_port_id:h.string(),schematic_component_id:h.string().optional(),center:Jt,facing_direction:h.enum(["up","down","left","right"]).optional(),distance_from_component_edge:h.number().optional(),side_of_component:h.enum(["top","bottom","left","right"]).optional(),true_ccw_index:h.number().optional(),pin_number:h.number().optional(),display_pin_label:h.string().optional(),subcircuit_id:h.string().optional(),is_connected:h.boolean().optional(),has_input_arrow:h.boolean().optional(),has_output_arrow:h.boolean().optional()}).describe("Defines a port on a schematic component");_t(!0);h$=h.object({type:h.literal("schematic_net_label"),schematic_net_label_id:At("schematic_net_label"),schematic_trace_id:h.string().optional(),source_trace_id:h.string().optional(),source_net_id:h.string(),center:Jt,anchor_position:Jt.optional(),anchor_side:h.enum(["top","bottom","left","right"]),text:h.string(),symbol_name:h.string().optional(),is_movable:h.boolean().optional(),subcircuit_id:h.string().optional()});_t(!0);d$=h.object({type:h.literal("schematic_error"),schematic_error_id:h.string(),error_type:h.literal("schematic_port_not_found").default("schematic_port_not_found"),message:h.string(),subcircuit_id:h.string().optional()}).describe("Defines a schematic error on the schematic");_t(!0);f$=h.object({type:h.literal("schematic_layout_error"),schematic_layout_error_id:At("schematic_layout_error"),error_type:h.literal("schematic_layout_error").default("schematic_layout_error"),message:h.string(),source_group_id:h.string(),schematic_group_id:h.string(),subcircuit_id:h.string().optional()}).describe("Error emitted when schematic layout fails for a group");_t(!0);Yx=h.object({type:h.literal("schematic_debug_object"),label:h.string().optional(),subcircuit_id:h.string().optional()}),m$=Yx.extend({shape:h.literal("rect"),center:Jt,size:U3}),_$=Yx.extend({shape:h.literal("line"),start:Jt,end:Jt}),y$=Yx.extend({shape:h.literal("point"),center:Jt}),g$=h.discriminatedUnion("shape",[m$,_$,y$]);_t(!0);x$=h.object({type:h.literal("schematic_voltage_probe"),schematic_voltage_probe_id:h.string(),position:Jt,schematic_trace_id:h.string(),voltage:Si.optional(),subcircuit_id:h.string().optional()}).describe("Defines a voltage probe measurement point on a schematic trace");_t(!0);Xx=h.object({type:h.literal("schematic_manual_edit_conflict_warning"),schematic_manual_edit_conflict_warning_id:At("schematic_manual_edit_conflict_warning"),warning_type:h.literal("schematic_manual_edit_conflict_warning").default("schematic_manual_edit_conflict_warning"),message:h.string(),schematic_component_id:h.string(),schematic_group_id:h.string().optional(),subcircuit_id:h.string().optional(),source_component_id:h.string()}).describe("Warning emitted when a component has both manual placement and explicit schX/schY coordinates");_t(!0);b$=h.object({type:h.literal("schematic_group"),schematic_group_id:At("schematic_group"),source_group_id:h.string(),is_subcircuit:h.boolean().optional(),subcircuit_id:h.string().optional(),width:$,height:$,center:Jt,schematic_component_ids:h.array(h.string()),show_as_schematic_box:h.boolean().optional(),name:h.string().optional(),description:h.string().optional()}).describe("Defines a group of components on the schematic");_t(!0);v$=h.object({type:h.literal("schematic_table"),schematic_table_id:At("schematic_table"),anchor_position:Jt,column_widths:h.array(X),row_heights:h.array(X),cell_padding:X.optional(),border_width:X.optional(),subcircuit_id:h.string().optional(),schematic_component_id:h.string().optional(),anchor:ng.optional()}).describe("Defines a table on the schematic");_t(!0);w$=h.object({type:h.literal("schematic_table_cell"),schematic_table_cell_id:At("schematic_table_cell"),schematic_table_id:h.string(),start_row_index:h.number(),end_row_index:h.number(),start_column_index:h.number(),end_column_index:h.number(),text:h.string().optional(),center:Jt,width:X,height:X,horizontal_align:h.enum(["left","center","right"]).optional(),vertical_align:h.enum(["top","middle","bottom"]).optional(),font_size:X.optional(),subcircuit_id:h.string().optional()}).describe("Defines a cell within a schematic_table");_t(!0);S$=h.object({type:h.literal("schematic_sheet"),schematic_sheet_id:At("schematic_sheet"),name:h.string().optional(),subcircuit_id:h.string().optional()}).describe("Defines a schematic sheet or page that components can be placed on");_t(!0);P$=h.object({x:X,y:X,bulge:h.number().optional()});_t(!0);X3=h.object({vertices:h.array(P$)});_t(!0);k$=h.object({outer_ring:X3,inner_rings:h.array(X3).default([])});_t(!0);T$=h.object({x:X,y:X,via:h.boolean().optional(),via_to_layer:he.optional()}),Ndt=h.array(T$);_t(!0);_t(!0);Ji=h.object({x:X,y:X,via:h.boolean().optional(),to_layer:he.optional(),trace_width:X.optional()});_t(!0);E$=h.object({type:h.literal("pcb_component"),pcb_component_id:At("pcb_component"),source_component_id:h.string(),center:Jt,layer:he,rotation:He,width:$,height:$,do_not_place:h.boolean().optional(),subcircuit_id:h.string().optional(),pcb_group_id:h.string().optional(),position_mode:h.enum(["packed","relative_to_group_anchor","none"]).optional(),positioned_relative_to_pcb_group_id:h.string().optional(),obstructs_within_bounds:h.boolean().default(!0).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");_t(!0);M$=h.object({type:h.literal("pcb_hole"),pcb_hole_id:At("pcb_hole"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),hole_shape:h.literal("circle"),hole_diameter:h.number(),x:X,y:X}),Adt=M$.describe("Defines a circular hole on the PCB");_t(!0);C$=h.object({type:h.literal("pcb_hole"),pcb_hole_id:At("pcb_hole"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),hole_shape:h.literal("rect"),hole_width:h.number(),hole_height:h.number(),x:X,y:X}),Rdt=C$.describe("Defines a rectangular (square-capable) hole on the PCB. Use equal width/height for square.");_t(!0);I$=h.object({type:h.literal("pcb_hole"),pcb_hole_id:At("pcb_hole"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),hole_shape:h.enum(["circle","square"]),hole_diameter:h.number(),x:X,y:X}),Odt=I$.describe("Defines a circular or square hole on the PCB");_t(!0);N$=h.object({type:h.literal("pcb_hole"),pcb_hole_id:At("pcb_hole"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),hole_shape:h.literal("oval"),hole_width:h.number(),hole_height:h.number(),x:X,y:X}),Ldt=N$.describe("Defines an oval hole on the PCB");_t(!0);A$=h.object({type:h.literal("pcb_hole"),pcb_hole_id:At("pcb_hole"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),hole_shape:h.literal("pill"),hole_width:h.number(),hole_height:h.number(),x:X,y:X}),Fdt=A$.describe("Defines a pill-shaped hole on the PCB");_t(!0);R$=h.object({type:h.literal("pcb_hole"),pcb_hole_id:At("pcb_hole"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),hole_shape:h.literal("rotated_pill"),hole_width:h.number(),hole_height:h.number(),x:X,y:X,ccw_rotation:He}),zdt=R$.describe("Defines a rotated pill-shaped hole on the PCB");_t(!0);O$=I$.or(N$).or(A$).or(R$).or(M$).or(C$),Ddt=h.object({type:h.literal("pcb_plated_hole"),shape:h.literal("circle"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),outer_diameter:h.number(),hole_diameter:h.number(),x:X,y:X,layers:h.array(he),port_hints:h.array(h.string()).optional(),pcb_component_id:h.string().optional(),pcb_port_id:h.string().optional(),pcb_plated_hole_id:At("pcb_plated_hole")}),$dt=h.object({type:h.literal("pcb_plated_hole"),shape:h.enum(["oval","pill"]),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),outer_width:h.number(),outer_height:h.number(),hole_width:h.number(),hole_height:h.number(),x:X,y:X,ccw_rotation:He,layers:h.array(he),port_hints:h.array(h.string()).optional(),pcb_component_id:h.string().optional(),pcb_port_id:h.string().optional(),pcb_plated_hole_id:At("pcb_plated_hole")}),jdt=h.object({type:h.literal("pcb_plated_hole"),shape:h.literal("circular_hole_with_rect_pad"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),hole_shape:h.literal("circle"),pad_shape:h.literal("rect"),hole_diameter:h.number(),rect_pad_width:h.number(),rect_pad_height:h.number(),rect_border_radius:h.number().optional(),hole_offset_x:X.default(0),hole_offset_y:X.default(0),x:X,y:X,layers:h.array(he),port_hints:h.array(h.string()).optional(),pcb_component_id:h.string().optional(),pcb_port_id:h.string().optional(),pcb_plated_hole_id:At("pcb_plated_hole")}),Bdt=h.object({type:h.literal("pcb_plated_hole"),shape:h.literal("pill_hole_with_rect_pad"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),hole_shape:h.literal("pill"),pad_shape:h.literal("rect"),hole_width:h.number(),hole_height:h.number(),rect_pad_width:h.number(),rect_pad_height:h.number(),rect_border_radius:h.number().optional(),hole_offset_x:X.default(0),hole_offset_y:X.default(0),x:X,y:X,layers:h.array(he),port_hints:h.array(h.string()).optional(),pcb_component_id:h.string().optional(),pcb_port_id:h.string().optional(),pcb_plated_hole_id:At("pcb_plated_hole")}),Ydt=h.object({type:h.literal("pcb_plated_hole"),shape:h.literal("rotated_pill_hole_with_rect_pad"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),hole_shape:h.literal("rotated_pill"),pad_shape:h.literal("rect"),hole_width:h.number(),hole_height:h.number(),hole_ccw_rotation:He,rect_pad_width:h.number(),rect_pad_height:h.number(),rect_border_radius:h.number().optional(),rect_ccw_rotation:He,hole_offset_x:X.default(0),hole_offset_y:X.default(0),x:X,y:X,layers:h.array(he),port_hints:h.array(h.string()).optional(),pcb_component_id:h.string().optional(),pcb_port_id:h.string().optional(),pcb_plated_hole_id:At("pcb_plated_hole")}),L$=h.union([Ddt,$dt,jdt,Bdt,Ydt]);_t(!0);_t(!0);_t(!0);_t(!0);_t(!0);F$=h.object({type:h.literal("pcb_port"),pcb_port_id:At("pcb_port"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),source_port_id:h.string(),pcb_component_id:h.string().optional(),x:X,y:X,layers:h.array(he),is_board_pinout:h.boolean().optional()}).describe("Defines a port on the PCB");_t(!0);Xdt=h.object({type:h.literal("pcb_smtpad"),shape:h.literal("circle"),pcb_smtpad_id:At("pcb_smtpad"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),x:X,y:X,radius:h.number(),layer:he,port_hints:h.array(h.string()).optional(),pcb_component_id:h.string().optional(),pcb_port_id:h.string().optional(),is_covered_with_solder_mask:h.boolean().optional()}),Udt=h.object({type:h.literal("pcb_smtpad"),shape:h.literal("rect"),pcb_smtpad_id:At("pcb_smtpad"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),x:X,y:X,width:h.number(),height:h.number(),rect_border_radius:h.number().optional(),corner_radius:h.number().optional(),layer:he,port_hints:h.array(h.string()).optional(),pcb_component_id:h.string().optional(),pcb_port_id:h.string().optional(),is_covered_with_solder_mask:h.boolean().optional()}),Vdt=h.object({type:h.literal("pcb_smtpad"),shape:h.literal("rotated_rect"),pcb_smtpad_id:At("pcb_smtpad"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),x:X,y:X,width:h.number(),height:h.number(),rect_border_radius:h.number().optional(),corner_radius:h.number().optional(),ccw_rotation:He,layer:he,port_hints:h.array(h.string()).optional(),pcb_component_id:h.string().optional(),pcb_port_id:h.string().optional(),is_covered_with_solder_mask:h.boolean().optional()}),z$=h.object({type:h.literal("pcb_smtpad"),shape:h.literal("pill"),pcb_smtpad_id:At("pcb_smtpad"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),x:X,y:X,width:h.number(),height:h.number(),radius:h.number(),layer:he,port_hints:h.array(h.string()).optional(),pcb_component_id:h.string().optional(),pcb_port_id:h.string().optional(),is_covered_with_solder_mask:h.boolean().optional()}),Gdt=h.object({type:h.literal("pcb_smtpad"),shape:h.literal("rotated_pill"),pcb_smtpad_id:At("pcb_smtpad"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),x:X,y:X,width:h.number(),height:h.number(),radius:h.number(),ccw_rotation:He,layer:he,port_hints:h.array(h.string()).optional(),pcb_component_id:h.string().optional(),pcb_port_id:h.string().optional(),is_covered_with_solder_mask:h.boolean().optional()}),Hdt=h.object({type:h.literal("pcb_smtpad"),shape:h.literal("polygon"),pcb_smtpad_id:At("pcb_smtpad"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),points:h.array(Jt),layer:he,port_hints:h.array(h.string()).optional(),pcb_component_id:h.string().optional(),pcb_port_id:h.string().optional(),is_covered_with_solder_mask:h.boolean().optional()}),D$=h.discriminatedUnion("shape",[Xdt,Udt,Vdt,Gdt,z$,Hdt]).describe("Defines an SMT pad on the PCB");_t(!0);_t(!0);_t(!0);_t(!0);_t(!0);_t(!0);Wdt=h.object({type:h.literal("pcb_solder_paste"),shape:h.literal("circle"),pcb_solder_paste_id:At("pcb_solder_paste"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),x:X,y:X,radius:h.number(),layer:he,pcb_component_id:h.string().optional(),pcb_smtpad_id:h.string().optional()}),qdt=h.object({type:h.literal("pcb_solder_paste"),shape:h.literal("rect"),pcb_solder_paste_id:At("pcb_solder_paste"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),x:X,y:X,width:h.number(),height:h.number(),layer:he,pcb_component_id:h.string().optional(),pcb_smtpad_id:h.string().optional()}),Zdt=h.object({type:h.literal("pcb_solder_paste"),shape:h.literal("pill"),pcb_solder_paste_id:At("pcb_solder_paste"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),x:X,y:X,width:h.number(),height:h.number(),radius:h.number(),layer:he,pcb_component_id:h.string().optional(),pcb_smtpad_id:h.string().optional()}),Kdt=h.object({type:h.literal("pcb_solder_paste"),shape:h.literal("rotated_rect"),pcb_solder_paste_id:At("pcb_solder_paste"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),x:X,y:X,width:h.number(),height:h.number(),ccw_rotation:X,layer:he,pcb_component_id:h.string().optional(),pcb_smtpad_id:h.string().optional()}),Jdt=h.object({type:h.literal("pcb_solder_paste"),shape:h.literal("oval"),pcb_solder_paste_id:At("pcb_solder_paste"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),x:X,y:X,width:h.number(),height:h.number(),layer:he,pcb_component_id:h.string().optional(),pcb_smtpad_id:h.string().optional()}),$$=h.union([Wdt,qdt,Zdt,Kdt,Jdt]).describe("Defines solderpaste on the PCB");_t(!0);_t(!0);_t(!0);_t(!0);_t(!0);j$=h.object({type:h.literal("pcb_text"),pcb_text_id:At("pcb_text"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),text:h.string(),center:Jt,layer:he,width:$,height:$,lines:h.number(),align:h.enum(["bottom-left"])}).describe("Defines text on the PCB");_t(!0);B$=h.object({route_type:h.literal("wire"),x:X,y:X,width:X,start_pcb_port_id:h.string().optional(),end_pcb_port_id:h.string().optional(),layer:he}),Y$=h.object({route_type:h.literal("via"),x:X,y:X,hole_diameter:X.optional(),outer_diameter:X.optional(),from_layer:h.string(),to_layer:h.string()}),Ux=h.union([B$,Y$]),X$=h.object({type:h.literal("pcb_trace"),source_trace_id:h.string().optional(),pcb_component_id:h.string().optional(),pcb_trace_id:At("pcb_trace"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),route_thickness_mode:h.enum(["constant","interpolated"]).default("constant").optional(),route_order_index:h.number().optional(),should_round_corners:h.boolean().optional(),trace_length:h.number().optional(),highlight_color:h.string().optional(),route:h.array(Ux)}).describe("Defines a trace on the PCB");_t(!0);_t(!0);U$=h.object({type:h.literal("pcb_trace_error"),pcb_trace_error_id:At("pcb_trace_error"),error_type:h.literal("pcb_trace_error").default("pcb_trace_error"),message:h.string(),center:Jt.optional(),pcb_trace_id:h.string(),source_trace_id:h.string(),pcb_component_ids:h.array(h.string()),pcb_port_ids:h.array(h.string()),subcircuit_id:h.string().optional()}).describe("Defines a trace error on the PCB");_t(!0);V$=h.object({type:h.literal("pcb_trace_missing_error"),pcb_trace_missing_error_id:At("pcb_trace_missing_error"),error_type:h.literal("pcb_trace_missing_error").default("pcb_trace_missing_error"),message:h.string(),center:Jt.optional(),source_trace_id:h.string(),pcb_component_ids:h.array(h.string()),pcb_port_ids:h.array(h.string()),subcircuit_id:h.string().optional()}).describe("Defines an error when a source trace has no corresponding PCB trace");_t(!0);G$=h.object({type:h.literal("pcb_port_not_matched_error"),pcb_error_id:At("pcb_error"),error_type:h.literal("pcb_port_not_matched_error").default("pcb_port_not_matched_error"),message:h.string(),pcb_component_ids:h.array(h.string()),subcircuit_id:h.string().optional()}).describe("Defines a trace error on the PCB where a port is not matched");_t(!0);H$=h.object({type:h.literal("pcb_port_not_connected_error"),pcb_port_not_connected_error_id:At("pcb_port_not_connected_error"),error_type:h.literal("pcb_port_not_connected_error").default("pcb_port_not_connected_error"),message:h.string(),pcb_port_ids:h.array(h.string()),pcb_component_ids:h.array(h.string()),subcircuit_id:h.string().optional()}).describe("Defines an error when a pcb port is not connected to any trace");_t(!0);W$=h.object({type:h.literal("pcb_net"),pcb_net_id:At("pcb_net"),source_net_id:h.string().optional(),highlight_color:h.string().optional()}).describe("Defines a net on the PCB");_t(!0);q$=h.object({type:h.literal("pcb_via"),pcb_via_id:At("pcb_via"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),subcircuit_connectivity_map_key:h.string().optional(),x:X,y:X,outer_diameter:X.default("0.6mm"),hole_diameter:X.default("0.25mm"),from_layer:he.optional(),to_layer:he.optional(),layers:h.array(he),pcb_trace_id:h.string().optional(),net_is_assignable:h.boolean().optional(),net_assigned:h.boolean().optional()}).describe("Defines a via on the PCB");_t(!0);Z$=h.object({type:h.literal("pcb_board"),pcb_board_id:At("pcb_board"),pcb_panel_id:h.string().optional(),is_subcircuit:h.boolean().optional(),subcircuit_id:h.string().optional(),width:$.optional(),height:$.optional(),center:Jt,thickness:$.optional().default(1.4),num_layers:h.number().optional().default(4),outline:h.array(Jt).optional(),shape:h.enum(["rect","polygon"]).optional(),material:h.enum(["fr4","fr1"]).default("fr4")}).describe("Defines the board outline of the PCB");_t(!0);K$=h.object({type:h.literal("pcb_panel"),pcb_panel_id:At("pcb_panel"),width:$,height:$,center:Jt,covered_with_solder_mask:h.boolean().optional().default(!0)}).describe("Defines a PCB panel that can contain multiple boards");_t(!0);J$=h.object({type:h.literal("pcb_placement_error"),pcb_placement_error_id:At("pcb_placement_error"),error_type:h.literal("pcb_placement_error").default("pcb_placement_error"),message:h.string(),subcircuit_id:h.string().optional()}).describe("Defines a placement error on the PCB");_t(!0);Q$=h.object({type:h.literal("pcb_trace_hint"),pcb_trace_hint_id:At("pcb_trace_hint"),pcb_port_id:h.string(),pcb_component_id:h.string(),route:h.array(Ji),subcircuit_id:h.string().optional()}).describe("A hint that can be used during generation of a PCB trace");_t(!0);tj=h.object({type:h.literal("pcb_silkscreen_line"),pcb_silkscreen_line_id:At("pcb_silkscreen_line"),pcb_component_id:h.string(),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),stroke_width:X.default("0.1mm"),x1:X,y1:X,x2:X,y2:X,layer:Zs}).describe("Defines a silkscreen line on the PCB");_t(!0);ej=h.object({type:h.literal("pcb_silkscreen_path"),pcb_silkscreen_path_id:At("pcb_silkscreen_path"),pcb_component_id:h.string(),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),layer:Zs,route:h.array(Jt),stroke_width:$}).describe("Defines a silkscreen path on the PCB");_t(!0);nj=h.object({type:h.literal("pcb_silkscreen_text"),pcb_silkscreen_text_id:At("pcb_silkscreen_text"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),font:h.literal("tscircuit2024").default("tscircuit2024"),font_size:X.default("0.2mm"),pcb_component_id:h.string(),text:h.string(),is_knockout:h.boolean().default(!1).optional(),knockout_padding:h.object({left:$,top:$,bottom:$,right:$}).default({left:"0.2mm",top:"0.2mm",bottom:"0.2mm",right:"0.2mm"}).optional(),ccw_rotation:h.number().optional(),layer:he,is_mirrored:h.boolean().default(!1).optional(),anchor_position:Jt.default({x:0,y:0}),anchor_alignment:ng.default("center")}).describe("Defines silkscreen text on the PCB");_t(!0);ij=h.object({type:h.literal("pcb_copper_text"),pcb_copper_text_id:At("pcb_copper_text"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),font:h.literal("tscircuit2024").default("tscircuit2024"),font_size:X.default("0.2mm"),pcb_component_id:h.string(),text:h.string(),is_knockout:h.boolean().default(!1).optional(),knockout_padding:h.object({left:$,top:$,bottom:$,right:$}).default({left:"0.2mm",top:"0.2mm",bottom:"0.2mm",right:"0.2mm"}).optional(),ccw_rotation:h.number().optional(),layer:he,is_mirrored:h.boolean().default(!1).optional(),anchor_position:Jt.default({x:0,y:0}),anchor_alignment:ng.default("center")}).describe("Defines copper text on the PCB");_t(!0);rj=h.object({type:h.literal("pcb_silkscreen_rect"),pcb_silkscreen_rect_id:At("pcb_silkscreen_rect"),pcb_component_id:h.string(),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),center:Jt,width:$,height:$,layer:he,stroke_width:$.default("1mm"),corner_radius:$.optional(),is_filled:h.boolean().default(!0).optional(),has_stroke:h.boolean().optional(),is_stroke_dashed:h.boolean().optional()}).describe("Defines a silkscreen rect on the PCB");_t(!0);sj=h.object({type:h.literal("pcb_silkscreen_circle"),pcb_silkscreen_circle_id:At("pcb_silkscreen_circle"),pcb_component_id:h.string(),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),center:Jt,radius:$,layer:Zs,stroke_width:$.default("1mm")}).describe("Defines a silkscreen circle on the PCB");_t(!0);oj=h.object({type:h.literal("pcb_silkscreen_oval"),pcb_silkscreen_oval_id:At("pcb_silkscreen_oval"),pcb_component_id:h.string(),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),center:Jt,radius_x:X,radius_y:X,layer:Zs}).describe("Defines a silkscreen oval on the PCB");_t(!0);aj=h.object({type:h.literal("pcb_fabrication_note_text"),pcb_fabrication_note_text_id:At("pcb_fabrication_note_text"),subcircuit_id:h.string().optional(),pcb_group_id:h.string().optional(),font:h.literal("tscircuit2024").default("tscircuit2024"),font_size:X.default("1mm"),pcb_component_id:h.string(),text:h.string(),layer:Zs,anchor_position:Jt.default({x:0,y:0}),anchor_alignment:h.enum(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),color:h.string().optional()}).describe("Defines a fabrication note in text on the PCB, useful for leaving notes for assemblers or fabricators");_t(!0);cj=h.object({type:h.literal("pcb_fabrication_note_path"),pcb_fabrication_note_path_id:At("pcb_fabrication_note_path"),pcb_component_id:h.string(),subcircuit_id:h.string().optional(),layer:he,route:h.array(Jt),stroke_width:$,color:h.string().optional()}).describe("Defines a fabrication path on the PCB for fabricators or assemblers");_t(!0);lj=h.object({type:h.literal("pcb_fabrication_note_rect"),pcb_fabrication_note_rect_id:At("pcb_fabrication_note_rect"),pcb_component_id:h.string(),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),center:Jt,width:$,height:$,layer:Zs,stroke_width:$.default("0.1mm"),corner_radius:$.optional(),is_filled:h.boolean().optional(),has_stroke:h.boolean().optional(),is_stroke_dashed:h.boolean().optional(),color:h.string().optional()}).describe("Defines a fabrication note rectangle on the PCB");_t(!0);uj=h.object({type:h.literal("pcb_fabrication_note_dimension"),pcb_fabrication_note_dimension_id:At("pcb_fabrication_note_dimension"),pcb_component_id:h.string(),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),layer:Zs,from:Jt,to:Jt,text:h.string().optional(),text_ccw_rotation:h.number().optional(),offset:$.optional(),offset_distance:$.optional(),offset_direction:h.object({x:h.number(),y:h.number()}).optional(),font:h.literal("tscircuit2024").default("tscircuit2024"),font_size:$.default("1mm"),color:h.string().optional(),arrow_size:$.default("1mm")}).describe("Defines a measurement annotation within PCB fabrication notes");_t(!0);pj=h.object({type:h.literal("pcb_note_text"),pcb_note_text_id:At("pcb_note_text"),pcb_component_id:h.string().optional(),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),name:h.string().optional(),font:h.literal("tscircuit2024").default("tscircuit2024"),font_size:X.default("1mm"),text:h.string().optional(),anchor_position:Jt.default({x:0,y:0}),anchor_alignment:h.enum(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),color:h.string().optional()}).describe("Defines a documentation note in text on the PCB");_t(!0);hj=h.object({type:h.literal("pcb_note_rect"),pcb_note_rect_id:At("pcb_note_rect"),pcb_component_id:h.string().optional(),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),name:h.string().optional(),text:h.string().optional(),center:Jt,width:$,height:$,stroke_width:$.default("0.1mm"),corner_radius:$.optional(),is_filled:h.boolean().optional(),has_stroke:h.boolean().optional(),is_stroke_dashed:h.boolean().optional(),color:h.string().optional()}).describe("Defines a rectangular documentation note on the PCB");_t(!0);dj=h.object({type:h.literal("pcb_note_path"),pcb_note_path_id:At("pcb_note_path"),pcb_component_id:h.string().optional(),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),name:h.string().optional(),text:h.string().optional(),route:h.array(Jt),stroke_width:$.default("0.1mm"),color:h.string().optional()}).describe("Defines a polyline documentation note on the PCB");_t(!0);fj=h.object({type:h.literal("pcb_note_line"),pcb_note_line_id:At("pcb_note_line"),pcb_component_id:h.string().optional(),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),name:h.string().optional(),text:h.string().optional(),x1:X,y1:X,x2:X,y2:X,stroke_width:X.default("0.1mm"),color:h.string().optional(),is_dashed:h.boolean().optional()}).describe("Defines a straight documentation note line on the PCB");_t(!0);mj=h.object({type:h.literal("pcb_note_dimension"),pcb_note_dimension_id:At("pcb_note_dimension"),pcb_component_id:h.string().optional(),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),name:h.string().optional(),from:Jt,to:Jt,text:h.string().optional(),text_ccw_rotation:h.number().optional(),offset_distance:$.optional(),offset_direction:h.object({x:h.number(),y:h.number()}).optional(),font:h.literal("tscircuit2024").default("tscircuit2024"),font_size:$.default("1mm"),color:h.string().optional(),arrow_size:$.default("1mm")}).describe("Defines a measurement annotation within PCB documentation notes");_t(!0);_j=h.object({type:h.literal("pcb_footprint_overlap_error"),pcb_error_id:At("pcb_error"),error_type:h.literal("pcb_footprint_overlap_error").default("pcb_footprint_overlap_error"),message:h.string(),pcb_smtpad_ids:h.array(h.string()).optional(),pcb_plated_hole_ids:h.array(h.string()).optional(),pcb_hole_ids:h.array(h.string()).optional(),pcb_keepout_ids:h.array(h.string()).optional()}).describe("Error emitted when a pcb footprint overlaps with another element");_t(!0);yj=h.object({type:h.literal("pcb_keepout"),shape:h.literal("rect"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),center:Jt,width:X,height:X,pcb_keepout_id:h.string(),layers:h.array(h.string()),description:h.string().optional()}).or(h.object({type:h.literal("pcb_keepout"),shape:h.literal("circle"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),center:Jt,radius:X,pcb_keepout_id:h.string(),layers:h.array(h.string()),description:h.string().optional()}));_t(!0);uE=h.object({type:h.literal("pcb_cutout"),pcb_cutout_id:At("pcb_cutout"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional()}),gj=uE.extend({shape:h.literal("rect"),center:Jt,width:$,height:$,rotation:He.optional()});_t(!0);xj=uE.extend({shape:h.literal("circle"),center:Jt,radius:$});_t(!0);bj=uE.extend({shape:h.literal("polygon"),points:h.array(Jt)});_t(!0);vj=h.discriminatedUnion("shape",[gj,xj,bj]).describe("Defines a cutout on the PCB, removing board material.");_t(!0);wj=h.object({type:h.literal("pcb_missing_footprint_error"),pcb_missing_footprint_error_id:At("pcb_missing_footprint_error"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),error_type:h.literal("pcb_missing_footprint_error").default("pcb_missing_footprint_error"),source_component_id:h.string(),message:h.string()}).describe("Defines a missing footprint error on the PCB");_t(!0);Nm=h.object({type:h.literal("external_footprint_load_error"),external_footprint_load_error_id:At("external_footprint_load_error"),pcb_component_id:h.string(),source_component_id:h.string(),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),footprinter_string:h.string().optional(),error_type:h.literal("external_footprint_load_error").default("external_footprint_load_error"),message:h.string()}).describe("Defines an error when an external footprint fails to load");_t(!0);Vx=h.object({type:h.literal("circuit_json_footprint_load_error"),circuit_json_footprint_load_error_id:At("circuit_json_footprint_load_error"),pcb_component_id:h.string(),source_component_id:h.string(),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),error_type:h.literal("circuit_json_footprint_load_error").default("circuit_json_footprint_load_error"),message:h.string(),circuit_json:h.array(h.any()).optional()}).describe("Defines an error when a circuit JSON footprint fails to load");_t(!0);Sj=h.object({type:h.literal("pcb_group"),pcb_group_id:At("pcb_group"),source_group_id:h.string(),is_subcircuit:h.boolean().optional(),subcircuit_id:h.string().optional(),width:$.optional(),height:$.optional(),center:Jt,outline:h.array(Jt).optional(),anchor_position:Jt.optional(),anchor_alignment:h.enum(["center","top_left","top_right","bottom_left","bottom_right"]).optional(),pcb_component_ids:h.array(h.string()),child_layout_mode:h.enum(["packed","none"]).optional(),name:h.string().optional(),description:h.string().optional(),layout_mode:h.string().optional(),autorouter_configuration:h.object({trace_clearance:$}).optional(),autorouter_used_string:h.string().optional()}).describe("Defines a group of components on the PCB");_t(!0);Pj=h.object({type:h.literal("pcb_autorouting_error"),pcb_error_id:At("pcb_autorouting_error"),error_type:h.literal("pcb_autorouting_error").default("pcb_autorouting_error"),message:h.string(),subcircuit_id:h.string().optional()}).describe("The autorouting has failed to route a portion of the board");_t(!0);Gx=h.object({type:h.literal("pcb_manual_edit_conflict_warning"),pcb_manual_edit_conflict_warning_id:At("pcb_manual_edit_conflict_warning"),warning_type:h.literal("pcb_manual_edit_conflict_warning").default("pcb_manual_edit_conflict_warning"),message:h.string(),pcb_component_id:h.string(),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),source_component_id:h.string()}).describe("Warning emitted when a component has both manual placement and explicit pcbX/pcbY coordinates");_t(!0);kj=h.object({type:h.literal("pcb_breakout_point"),pcb_breakout_point_id:At("pcb_breakout_point"),pcb_group_id:h.string(),subcircuit_id:h.string().optional(),source_trace_id:h.string().optional(),source_port_id:h.string().optional(),source_net_id:h.string().optional(),x:X,y:X}).describe("Defines a routing target within a pcb_group for a source_trace or source_net");_t(!0);Tj=h.object({type:h.literal("pcb_ground_plane"),pcb_ground_plane_id:At("pcb_ground_plane"),source_pcb_ground_plane_id:h.string(),source_net_id:h.string(),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional()}).describe("Defines a ground plane on the PCB");_t(!0);Ej=h.object({type:h.literal("pcb_ground_plane_region"),pcb_ground_plane_region_id:At("pcb_ground_plane_region"),pcb_ground_plane_id:h.string(),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),layer:he,points:h.array(Jt)}).describe("Defines a polygon region of a ground plane");_t(!0);Mj=h.object({type:h.literal("pcb_thermal_spoke"),pcb_thermal_spoke_id:At("pcb_thermal_spoke"),pcb_ground_plane_id:h.string(),shape:h.string(),spoke_count:h.number(),spoke_thickness:X,spoke_inner_diameter:X,spoke_outer_diameter:X,pcb_plated_hole_id:h.string().optional(),subcircuit_id:h.string().optional()}).describe("Pattern for connecting a ground plane to a plated hole");_t(!0);pE=h.object({type:h.literal("pcb_copper_pour"),pcb_copper_pour_id:At("pcb_copper_pour"),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),layer:he,source_net_id:h.string().optional(),covered_with_solder_mask:h.boolean().optional().default(!0)}),Cj=pE.extend({shape:h.literal("rect"),center:Jt,width:$,height:$,rotation:He.optional()});_t(!0);Ij=pE.extend({shape:h.literal("brep"),brep_shape:k$});_t(!0);Nj=pE.extend({shape:h.literal("polygon"),points:h.array(Jt)});_t(!0);Aj=h.discriminatedUnion("shape",[Cj,Ij,Nj]).describe("Defines a copper pour on the PCB.");_t(!0);Rj=h.object({type:h.literal("pcb_component_outside_board_error"),pcb_component_outside_board_error_id:At("pcb_component_outside_board_error"),error_type:h.literal("pcb_component_outside_board_error").default("pcb_component_outside_board_error"),message:h.string(),pcb_component_id:h.string(),pcb_board_id:h.string(),component_center:Jt,component_bounds:h.object({min_x:h.number(),max_x:h.number(),min_y:h.number(),max_y:h.number()}),subcircuit_id:h.string().optional(),source_component_id:h.string().optional()}).describe("Error emitted when a PCB component is placed outside the board boundaries");_t(!0);Am=h.object({type:h.literal("pcb_component_invalid_layer_error"),pcb_component_invalid_layer_error_id:At("pcb_component_invalid_layer_error"),error_type:h.literal("pcb_component_invalid_layer_error").default("pcb_component_invalid_layer_error"),message:h.string(),pcb_component_id:h.string().optional(),source_component_id:h.string(),layer:he,subcircuit_id:h.string().optional()}).describe("Error emitted when a component is placed on an invalid layer (components can only be on 'top' or 'bottom' layers)");_t(!0);Oj=h.object({type:h.literal("pcb_via_clearance_error"),pcb_error_id:At("pcb_error"),error_type:h.literal("pcb_via_clearance_error").default("pcb_via_clearance_error"),message:h.string(),pcb_via_ids:h.array(h.string()).min(2),minimum_clearance:X.optional(),actual_clearance:X.optional(),pcb_center:h.object({x:h.number().optional(),y:h.number().optional()}).optional(),subcircuit_id:h.string().optional()}).describe("Error emitted when vias are closer than the allowed clearance");_t(!0);Lj=h.object({type:h.literal("pcb_courtyard_rect"),pcb_courtyard_rect_id:At("pcb_courtyard_rect"),pcb_component_id:h.string(),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),center:Jt,width:$,height:$,layer:Zs,color:h.string().optional()}).describe("Defines a courtyard rectangle on the PCB");_t(!0);Fj=h.object({type:h.literal("pcb_courtyard_outline"),pcb_courtyard_outline_id:At("pcb_courtyard_outline"),pcb_component_id:h.string(),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),layer:Zs,outline:h.array(Jt).min(2),stroke_width:$.default("0.1mm"),is_closed:h.boolean().optional(),is_stroke_dashed:h.boolean().optional(),color:h.string().optional()}).describe("Defines a courtyard outline on the PCB");_t(!0);zj=h.object({type:h.literal("pcb_courtyard_polygon"),pcb_courtyard_polygon_id:At("pcb_courtyard_polygon"),pcb_component_id:h.string(),pcb_group_id:h.string().optional(),subcircuit_id:h.string().optional(),layer:Zs,points:h.array(Jt).min(3),color:h.string().optional()}).describe("Defines a courtyard polygon on the PCB");_t(!0);Dj=h.object({type:h.literal("cad_component"),cad_component_id:h.string(),pcb_component_id:h.string(),source_component_id:h.string(),position:zh,rotation:zh.optional(),size:zh.optional(),layer:he.optional(),subcircuit_id:h.string().optional(),footprinter_string:h.string().optional(),model_obj_url:h.string().optional(),model_stl_url:h.string().optional(),model_3mf_url:h.string().optional(),model_gltf_url:h.string().optional(),model_glb_url:h.string().optional(),model_step_url:h.string().optional(),model_wrl_url:h.string().optional(),model_unit_to_mm_scale_factor:h.number().optional(),model_jscad:h.any().optional()}).describe("Defines a component on the PCB");_t(!0);$j=h.enum(["sinewave","square","triangle","sawtooth"]),Qdt=h.union([h.string(),h.number()]).transform(n=>typeof n=="string"?n.endsWith("%")?parseFloat(n.slice(0,-1))/100:parseFloat(n):n).pipe(h.number().min(0,"Duty cycle must be non-negative").max(1,"Duty cycle cannot be greater than 100%")),jj=h.object({type:h.literal("simulation_voltage_source"),simulation_voltage_source_id:At("simulation_voltage_source"),is_dc_source:h.literal(!0).optional().default(!0),positive_source_port_id:h.string().optional(),negative_source_port_id:h.string().optional(),positive_source_net_id:h.string().optional(),negative_source_net_id:h.string().optional(),voltage:Si}).describe("Defines a DC voltage source for simulation"),Bj=h.object({type:h.literal("simulation_voltage_source"),simulation_voltage_source_id:At("simulation_voltage_source"),is_dc_source:h.literal(!1),terminal1_source_port_id:h.string().optional(),terminal2_source_port_id:h.string().optional(),terminal1_source_net_id:h.string().optional(),terminal2_source_net_id:h.string().optional(),voltage:Si.optional(),frequency:pr.optional(),peak_to_peak_voltage:Si.optional(),wave_shape:$j.optional(),phase:He.optional(),duty_cycle:Qdt.optional()}).describe("Defines an AC voltage source for simulation"),Yj=h.union([jj,Bj]).describe("Defines a voltage source for simulation");_t(!0);_t(!0);_t(!0);Xj=h.union([h.literal("spice_dc_sweep"),h.literal("spice_dc_operating_point"),h.literal("spice_transient_analysis"),h.literal("spice_ac_analysis")]),Uj=h.object({type:h.literal("simulation_experiment"),simulation_experiment_id:At("simulation_experiment"),name:h.string(),experiment_type:Xj,time_per_step:eg.optional(),start_time_ms:ur.optional(),end_time_ms:ur.optional()}).describe("Defines a simulation experiment configuration");_t(!0);Vj=h.object({type:h.literal("simulation_transient_voltage_graph"),simulation_transient_voltage_graph_id:At("simulation_transient_voltage_graph"),simulation_experiment_id:h.string(),timestamps_ms:h.array(h.number()).optional(),voltage_levels:h.array(h.number()),schematic_voltage_probe_id:h.string().optional(),simulation_voltage_probe_id:h.string().optional(),subcircuit_connectivity_map_key:h.string().optional(),time_per_step:eg,start_time_ms:ur,end_time_ms:ur,name:h.string().optional()}).describe("Stores voltage measurements over time for a simulation");_t(!0);Gj=h.object({type:h.literal("simulation_switch"),simulation_switch_id:At("simulation_switch"),source_component_id:h.string().optional(),closes_at:ur.optional(),opens_at:ur.optional(),starts_closed:h.boolean().optional(),switching_frequency:pr.optional()}).describe("Defines a switch for simulation timing control");_t(!0);Hj=h.object({type:h.literal("simulation_voltage_probe"),simulation_voltage_probe_id:At("simulation_voltage_probe"),source_port_id:h.string().optional(),source_net_id:h.string().optional(),name:h.string().optional(),subcircuit_id:h.string().optional()}).describe("Defines a voltage probe for simulation, connected to a port or a net").refine(n=>!!n.source_port_id!=!!n.source_net_id,{message:"Exactly one of source_port_id or source_net_id must be provided to simulation_voltage_probe"});_t(!0);Wj=h.object({type:h.literal("simulation_unknown_experiment_error"),simulation_unknown_experiment_error_id:At("simulation_unknown_experiment_error"),error_type:h.literal("simulation_unknown_experiment_error").default("simulation_unknown_experiment_error"),message:h.string(),simulation_experiment_id:h.string().optional(),subcircuit_id:h.string().optional()}).describe("An unknown error occurred during the simulation experiment.");_t(!0);qj=h.union([GD,VD,UD,WD,HD,W3,V3,jx,H3,G3,q3,Z3,K3,tE,eE,nE,oE,iE,rE,sE,Q3,J3,ZD,KD,qD,aE,cE,lE,Bx,E$,O$,wj,Nm,Vx,Gx,L$,yj,F$,W$,j$,X$,q$,D$,$$,Z$,K$,Sj,Q$,tj,ej,nj,ij,rj,sj,oj,U$,V$,J$,G$,H$,Oj,cj,aj,lj,uj,pj,hj,dj,fj,mj,Pj,_j,kj,vj,Tj,Ej,Mj,Aj,Rj,Am,Lj,Fj,zj,JD,u$,s$,o$,a$,c$,r$,p$,l$,QD,d$,f$,h$,g$,x$,Xx,b$,S$,v$,w$,Dj,Yj,Uj,Vj,Gj,Hj,Wj]),$h=qj;_t(!0);Dh(!0)});var bB=ue((rqt,xB)=>{"use strict";var Om=1e3,Lm=Om*60,Fm=Lm*60,Xh=Fm*24,ggt=Xh*7,xgt=Xh*365.25;xB.exports=function(n,e){e=e||{};var t=typeof n;if(t==="string"&&n.length>0)return bgt(n);if(t==="number"&&isFinite(n))return e.long?wgt(n):vgt(n);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(n))};function bgt(n){if(n=String(n),!(n.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(n);if(e){var t=parseFloat(e[1]),i=(e[2]||"ms").toLowerCase();switch(i){case"years":case"year":case"yrs":case"yr":case"y":return t*xgt;case"weeks":case"week":case"w":return t*ggt;case"days":case"day":case"d":return t*Xh;case"hours":case"hour":case"hrs":case"hr":case"h":return t*Fm;case"minutes":case"minute":case"mins":case"min":case"m":return t*Lm;case"seconds":case"second":case"secs":case"sec":case"s":return t*Om;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function vgt(n){var e=Math.abs(n);return e>=Xh?Math.round(n/Xh)+"d":e>=Fm?Math.round(n/Fm)+"h":e>=Lm?Math.round(n/Lm)+"m":e>=Om?Math.round(n/Om)+"s":n+"ms"}function wgt(n){var e=Math.abs(n);return e>=Xh?nb(n,e,Xh,"day"):e>=Fm?nb(n,e,Fm,"hour"):e>=Lm?nb(n,e,Lm,"minute"):e>=Om?nb(n,e,Om,"second"):n+" ms"}function nb(n,e,t,i){var r=e>=t*1.5;return Math.round(n/t)+" "+i+(r?"s":"")}});var wB=ue((sqt,vB)=>{"use strict";function Sgt(n){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=r,t.enabled=a,t.humanize=bB(),t.destroy=l,Object.keys(n).forEach(u=>{t[u]=n[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let p=0;for(let f=0;f<u.length;f++)p=(p<<5)-p+u.charCodeAt(f),p|=0;return t.colors[Math.abs(p)%t.colors.length]}t.selectColor=e;function t(u){let p,f=null,y,g;function x(...v){if(!x.enabled)return;let S=x,P=Number(new Date),T=P-(p||P);S.diff=T,S.prev=p,S.curr=P,p=P,v[0]=t.coerce(v[0]),typeof v[0]!="string"&&v.unshift("%O");let k=0;v[0]=v[0].replace(/%([a-zA-Z%])/g,(E,N)=>{if(E==="%%")return"%";k++;let I=t.formatters[N];if(typeof I=="function"){let A=v[k];E=I.call(S,A),v.splice(k,1),k--}return E}),t.formatArgs.call(S,v),(S.log||t.log).apply(S,v)}return x.namespace=u,x.useColors=t.useColors(),x.color=t.selectColor(u),x.extend=i,x.destroy=t.destroy,Object.defineProperty(x,"enabled",{enumerable:!0,configurable:!1,get:()=>f!==null?f:(y!==t.namespaces&&(y=t.namespaces,g=t.enabled(u)),g),set:v=>{f=v}}),typeof t.init=="function"&&t.init(x),x}function i(u,p){let f=t(this.namespace+(typeof p>"u"?":":p)+u);return f.log=this.log,f}function r(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let p=(typeof u=="string"?u:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let f of p)f[0]==="-"?t.skips.push(f.slice(1)):t.names.push(f)}function s(u,p){let f=0,y=0,g=-1,x=0;for(;f<u.length;)if(y<p.length&&(p[y]===u[f]||p[y]==="*"))p[y]==="*"?(g=y,x=f,y++):(f++,y++);else if(g!==-1)y=g+1,x++,f=x;else return!1;for(;y<p.length&&p[y]==="*";)y++;return y===p.length}function o(){let u=[...t.names,...t.skips.map(p=>"-"+p)].join(",");return t.enable(""),u}function a(u){for(let p of t.skips)if(s(u,p))return!1;for(let p of t.names)if(s(u,p))return!0;return!1}function c(u){return u instanceof Error?u.stack||u.message:u}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}vB.exports=Sgt});var An=ue((zr,ib)=>{"use strict";zr.formatArgs=kgt;zr.save=Tgt;zr.load=Egt;zr.useColors=Pgt;zr.storage=Mgt();zr.destroy=(()=>{let n=!1;return()=>{n||(n=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();zr.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function Pgt(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let n;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(n=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(n[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function kgt(n){if(n[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+n[0]+(this.useColors?"%c ":" ")+"+"+ib.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;n.splice(1,0,e,"color: inherit");let t=0,i=0;n[0].replace(/%[a-zA-Z%]/g,r=>{r!=="%%"&&(t++,r==="%c"&&(i=t))}),n.splice(i,0,e)}zr.log=console.debug||console.log||(()=>{});function Tgt(n){try{n?zr.storage.setItem("debug",n):zr.storage.removeItem("debug")}catch{}}function Egt(){let n;try{n=zr.storage.getItem("debug")||zr.storage.getItem("DEBUG")}catch{}return!n&&typeof process<"u"&&"env"in process&&(n=process.env.DEBUG),n}function Mgt(){try{return localStorage}catch{}}ib.exports=wB()(zr);var{formatters:Cgt}=ib.exports;Cgt.j=function(n){try{return JSON.stringify(n)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var AB=ue(Un=>{"use strict";function vE(n,e){var t=n.length;n.push(e);t:for(;0<t;){var i=t-1>>>1,r=n[i];if(0<rb(r,e))n[i]=e,n[t]=r,t=i;else break t}}function Io(n){return n.length===0?null:n[0]}function ob(n){if(n.length===0)return null;var e=n[0],t=n.pop();if(t!==e){n[0]=t;t:for(var i=0,r=n.length,s=r>>>1;i<s;){var o=2*(i+1)-1,a=n[o],c=o+1,l=n[c];if(0>rb(a,t))c<r&&0>rb(l,a)?(n[i]=l,n[c]=t,i=c):(n[i]=a,n[o]=t,i=o);else if(c<r&&0>rb(l,t))n[i]=l,n[c]=t,i=c;else break t}}return e}function rb(n,e){var t=n.sortIndex-e.sortIndex;return t!==0?t:n.id-e.id}Un.unstable_now=void 0;typeof performance=="object"&&typeof performance.now=="function"?(SB=performance,Un.unstable_now=function(){return SB.now()}):(gE=Date,PB=gE.now(),Un.unstable_now=function(){return gE.now()-PB});var SB,gE,PB,Sa=[],$c=[],Igt=1,ks=null,hr=3,wE=!1,rg=!1,sg=!1,SE=!1,EB=typeof setTimeout=="function"?setTimeout:null,MB=typeof clearTimeout=="function"?clearTimeout:null,kB=typeof setImmediate<"u"?setImmediate:null;function sb(n){for(var e=Io($c);e!==null;){if(e.callback===null)ob($c);else if(e.startTime<=n)ob($c),e.sortIndex=e.expirationTime,vE(Sa,e);else break;e=Io($c)}}function PE(n){if(sg=!1,sb(n),!rg)if(Io(Sa)!==null)rg=!0,Dm||(Dm=!0,zm());else{var e=Io($c);e!==null&&kE(PE,e.startTime-n)}}var Dm=!1,og=-1,CB=5,IB=-1;function NB(){return SE?!0:!(Un.unstable_now()-IB<CB)}function xE(){if(SE=!1,Dm){var n=Un.unstable_now();IB=n;var e=!0;try{t:{rg=!1,sg&&(sg=!1,MB(og),og=-1),wE=!0;var t=hr;try{e:{for(sb(n),ks=Io(Sa);ks!==null&&!(ks.expirationTime>n&&NB());){var i=ks.callback;if(typeof i=="function"){ks.callback=null,hr=ks.priorityLevel;var r=i(ks.expirationTime<=n);if(n=Un.unstable_now(),typeof r=="function"){ks.callback=r,sb(n),e=!0;break e}ks===Io(Sa)&&ob(Sa),sb(n)}else ob(Sa);ks=Io(Sa)}if(ks!==null)e=!0;else{var s=Io($c);s!==null&&kE(PE,s.startTime-n),e=!1}}break t}finally{ks=null,hr=t,wE=!1}e=void 0}}finally{e?zm():Dm=!1}}}var zm;typeof kB=="function"?zm=function(){kB(xE)}:typeof MessageChannel<"u"?(bE=new MessageChannel,TB=bE.port2,bE.port1.onmessage=xE,zm=function(){TB.postMessage(null)}):zm=function(){EB(xE,0)};var bE,TB;function kE(n,e){og=EB(function(){n(Un.unstable_now())},e)}Un.unstable_IdlePriority=5;Un.unstable_ImmediatePriority=1;Un.unstable_LowPriority=4;Un.unstable_NormalPriority=3;Un.unstable_Profiling=null;Un.unstable_UserBlockingPriority=2;Un.unstable_cancelCallback=function(n){n.callback=null};Un.unstable_forceFrameRate=function(n){0>n||125<n?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):CB=0<n?Math.floor(1e3/n):5};Un.unstable_getCurrentPriorityLevel=function(){return hr};Un.unstable_next=function(n){switch(hr){case 1:case 2:case 3:var e=3;break;default:e=hr}var t=hr;hr=e;try{return n()}finally{hr=t}};Un.unstable_requestPaint=function(){SE=!0};Un.unstable_runWithPriority=function(n,e){switch(n){case 1:case 2:case 3:case 4:case 5:break;default:n=3}var t=hr;hr=n;try{return e()}finally{hr=t}};Un.unstable_scheduleCallback=function(n,e,t){var i=Un.unstable_now();switch(typeof t=="object"&&t!==null?(t=t.delay,t=typeof t=="number"&&0<t?i+t:i):t=i,n){case 1:var r=-1;break;case 2:r=250;break;case 5:r=1073741823;break;case 4:r=1e4;break;default:r=5e3}return r=t+r,n={id:Igt++,callback:e,priorityLevel:n,startTime:t,expirationTime:r,sortIndex:-1},t>i?(n.sortIndex=t,vE($c,n),Io(Sa)===null&&n===Io($c)&&(sg?(MB(og),og=-1):sg=!0,kE(PE,t-i))):(n.sortIndex=r,vE(Sa,n),rg||wE||(rg=!0,Dm||(Dm=!0,zm()))),n};Un.unstable_shouldYield=NB;Un.unstable_wrapCallback=function(n){var e=hr;return function(){var t=hr;hr=e;try{return n.apply(this,arguments)}finally{hr=t}}}});var OB=ue((aqt,RB)=>{"use strict";RB.exports=AB()});var LB=ue((cqt,ag)=>{"use strict";ag.exports=function(n){function e(m,_,w,M){return new Ult(m,_,w,M)}function t(){}function i(m){var _="https://react.dev/errors/"+m;if(1<arguments.length){_+="?args[]="+encodeURIComponent(arguments[1]);for(var w=2;w<arguments.length;w++)_+="&args[]="+encodeURIComponent(arguments[w])}return"Minified React error #"+m+"; visit "+_+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function r(m){var _=m,w=m;if(m.alternate)for(;_.return;)_=_.return;else{m=_;do _=m,(_.flags&4098)!==0&&(w=_.return),m=_.return;while(m)}return _.tag===3?w:null}function s(m){if(r(m)!==m)throw Error(i(188))}function o(m){var _=m.alternate;if(!_){if(_=r(m),_===null)throw Error(i(188));return _!==m?null:m}for(var w=m,M=_;;){var O=w.return;if(O===null)break;var D=O.alternate;if(D===null){if(M=O.return,M!==null){w=M;continue}break}if(O.child===D.child){for(D=O.child;D;){if(D===w)return s(O),m;if(D===M)return s(O),_;D=D.sibling}throw Error(i(188))}if(w.return!==M.return)w=O,M=D;else{for(var K=!1,at=O.child;at;){if(at===w){K=!0,w=O,M=D;break}if(at===M){K=!0,M=O,w=D;break}at=at.sibling}if(!K){for(at=D.child;at;){if(at===w){K=!0,w=D,M=O;break}if(at===M){K=!0,M=D,w=O;break}at=at.sibling}if(!K)throw Error(i(189))}}if(w.alternate!==M)throw Error(i(190))}if(w.tag!==3)throw Error(i(188));return w.stateNode.current===w?m:_}function a(m){var _=m.tag;if(_===5||_===26||_===27||_===6)return m;for(m=m.child;m!==null;){if(_=a(m),_!==null)return _;m=m.sibling}return null}function c(m){var _=m.tag;if(_===5||_===26||_===27||_===6)return m;for(m=m.child;m!==null;){if(m.tag!==4&&(_=c(m),_!==null))return _;m=m.sibling}return null}function l(m){return m===null||typeof m!="object"?null:(m=bz&&m[bz]||m["@@iterator"],typeof m=="function"?m:null)}function u(m){if(m==null)return null;if(typeof m=="function")return m.$$typeof===Zlt?null:m.displayName||m.name||null;if(typeof m=="string")return m;switch(m){case Wf:return"Fragment";case WT:return"Profiler";case gz:return"StrictMode";case ZT:return"Suspense";case KT:return"SuspenseList";case QT:return"Activity"}if(typeof m=="object")switch(m.$$typeof){case Hf:return"Portal";case vc:return(m.displayName||"Context")+".Provider";case xz:return(m._context.displayName||"Context")+".Consumer";case qT:var _=m.render;return m=m.displayName,m||(m=_.displayName||_.name||"",m=m!==""?"ForwardRef("+m+")":"ForwardRef"),m;case JT:return _=m.displayName||null,_!==null?_:u(m.type)||"Memo";case wc:_=m._payload,m=m._init;try{return u(m(_))}catch{}}return null}function p(m){return{current:m}}function f(m){0>Kf||(m.current=r3[Kf],r3[Kf]=null,Kf--)}function y(m,_){Kf++,r3[Kf]=m.current,m.current=_}function g(m){return m>>>=0,m===0?32:31-(dpt(m)/fpt|0)|0}function x(m){var _=m&42;if(_!==0)return _;switch(m&-m){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return m&4194048;case 4194304:case 8388608:case 16777216:case 33554432:return m&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return m}}function v(m,_,w){var M=m.pendingLanes;if(M===0)return 0;var O=0,D=m.suspendedLanes,K=m.pingedLanes;m=m.warmLanes;var at=M&134217727;return at!==0?(M=at&~D,M!==0?O=x(M):(K&=at,K!==0?O=x(K):w||(w=at&~m,w!==0&&(O=x(w))))):(at=M&~D,at!==0?O=x(at):K!==0?O=x(K):w||(w=M&~m,w!==0&&(O=x(w)))),O===0?0:_!==0&&_!==O&&(_&D)===0&&(D=O&-O,w=_&-_,D>=w||D===32&&(w&4194048)!==0)?_:O}function S(m,_){return(m.pendingLanes&~(m.suspendedLanes&~m.pingedLanes)&_)===0}function P(m,_){switch(m){case 1:case 2:case 4:case 8:case 64:return _+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return _+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function T(){var m=ix;return ix<<=1,(ix&4194048)===0&&(ix=256),m}function k(){var m=rx;return rx<<=1,(rx&62914560)===0&&(rx=4194304),m}function C(m){for(var _=[],w=0;31>w;w++)_.push(m);return _}function E(m,_){m.pendingLanes|=_,_!==268435456&&(m.suspendedLanes=0,m.pingedLanes=0,m.warmLanes=0)}function N(m,_,w,M,O,D){var K=m.pendingLanes;m.pendingLanes=w,m.suspendedLanes=0,m.pingedLanes=0,m.warmLanes=0,m.expiredLanes&=w,m.entangledLanes&=w,m.errorRecoveryDisabledLanes&=w,m.shellSuspendCounter=0;var at=m.entanglements,xt=m.expirationTimes,It=m.hiddenUpdates;for(w=K&~w;0<w;){var Dt=31-ts(w),Xt=1<<Dt;at[Dt]=0,xt[Dt]=-1;var Wt=It[Dt];if(Wt!==null)for(It[Dt]=null,Dt=0;Dt<Wt.length;Dt++){var Re=Wt[Dt];Re!==null&&(Re.lane&=-536870913)}w&=~Xt}M!==0&&I(m,M,0),D!==0&&O===0&&m.tag!==0&&(m.suspendedLanes|=D&~(K&~_))}function I(m,_,w){m.pendingLanes|=_,m.suspendedLanes&=~_;var M=31-ts(_);m.entangledLanes|=_,m.entanglements[M]=m.entanglements[M]|1073741824|w&4194090}function A(m,_){var w=m.entangledLanes|=_;for(m=m.entanglements;w;){var M=31-ts(w),O=1<<M;O&_|m[M]&_&&(m[M]|=_),w&=~O}}function R(m){switch(m){case 2:m=1;break;case 8:m=4;break;case 32:m=16;break;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:m=128;break;case 268435456:m=134217728;break;default:m=0}return m}function j(m){return m&=-m,2<m?8<m?(m&134217727)!==0?32:268435456:8:2}function B(m){if(typeof xpt=="function"&&bpt(m),es&&typeof es.setStrictMode=="function")try{es.setStrictMode($y,m)}catch{}}function G(m){if(a3===void 0)try{throw Error()}catch(w){var _=w.stack.trim().match(/\n( *(at )?)/);a3=_&&_[1]||"",Vz=-1<w.stack.indexOf(`
2
2
  at`)?" (<anonymous>)":-1<w.stack.indexOf("@")?"@unknown:0:0":""}return`
3
3
  `+a3+m+Vz}function U(m,_){if(!m||c3)return"";c3=!0;var w=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var M={DetermineComponentFrameRoot:function(){try{if(_){var Xt=function(){throw Error()};if(Object.defineProperty(Xt.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Xt,[])}catch(Re){var Wt=Re}Reflect.construct(m,[],Xt)}else{try{Xt.call()}catch(Re){Wt=Re}m.call(Xt.prototype)}}else{try{throw Error()}catch(Re){Wt=Re}(Xt=m())&&typeof Xt.catch=="function"&&Xt.catch(function(){})}}catch(Re){if(Re&&Wt&&typeof Re.stack=="string")return[Re.stack,Wt.stack]}return[null,null]}};M.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var O=Object.getOwnPropertyDescriptor(M.DetermineComponentFrameRoot,"name");O&&O.configurable&&Object.defineProperty(M.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var D=M.DetermineComponentFrameRoot(),K=D[0],at=D[1];if(K&&at){var xt=K.split(`
4
4
  `),It=at.split(`
@@ -141,7 +141,7 @@ svg { font-family: 'Inter', 'Helvetica Neue', Arial, sans-serif; }
141
141
  L ${x[3].x},${x[3].y}
142
142
  L ${x[4].x},${x[4].y}
143
143
  Z
144
- `;r.push({name:"path",type:"element",attributes:{class:"net-label",d:v,fill:t.schematic.label_background,stroke:t.schematic.label_global,"stroke-width":`${Ui(e)}px`},value:"",children:[]});let S={x:f.x+u.x*s*.5,y:f.y+u.y*s*.5},P={left:"start",top:"start",bottom:"start",right:"end"}[n.anchor_side],T={left:"",right:"",top:`rotate(90 ${S.x} ${S.y})`,bottom:`rotate(-90 ${S.x} ${S.y})`}[n.anchor_side];return r.push({name:"text",type:"element",attributes:{class:"net-label-text",x:S.x.toString(),y:S.y.toString(),fill:t.schematic.label_global,"text-anchor":P,"dominant-baseline":"central","font-family":"sans-serif","font-variant-numeric":"tabular-nums","font-size":`${s}px`,transform:T},children:[{type:"text",value:i||"",name:"",attributes:{},children:[]}],value:""}),r},V8t=({schematicBox:n,transform:e,colorMap:t})=>{let i=st(e,{x:n.x,y:n.y}),r=st(e,{x:n.x+n.width,y:n.y+n.height}),s=Math.min(i.y,r.y),o=Math.max(i.y,r.y),a=Math.min(i.x,r.x),c=Math.max(i.x,r.x),l=Ui(e),u={class:"schematic-box",x:a.toString(),y:s.toString(),width:(c-a).toString(),height:(o-s).toString(),"stroke-width":`${l}px`,stroke:t.schematic.component_outline||"black",fill:"transparent"};if(n.is_dashed){let p=8*l,f=4*l;u["stroke-dasharray"]=`${p} ${f}`}return[{name:"rect",type:"element",value:"",attributes:u,children:[]}]},G8t=({schematicTable:n,transform:e,colorMap:t,circuitJson:i})=>{let{anchor_position:r,border_width:s=.05,anchor:o="center"}=n,{column_widths:a,row_heights:c}=$tt(n,i),l=a.reduce((N,I)=>N+I,0),u=c.reduce((N,I)=>N+I,0),p=r.x,f=r.y;o.includes("center")?p-=l/2:o.includes("right")&&(p-=l),o.includes("center")?f+=u/2:o.includes("bottom")&&(f+=u);let y=[],g=s*Math.abs(e.a),x=Ui(e),[v,S]=st(e,[p,f]),[P,T]=st(e,[p+l,f-u]);y.push({name:"rect",type:"element",attributes:{x:v.toString(),y:S.toString(),width:(P-v).toString(),height:(T-S).toString(),fill:"none",stroke:t.schematic.table,"stroke-width":g.toString()},children:[],value:""});let k=i.filter(N=>N.type==="schematic_table_cell"&&N.schematic_table_id===n.schematic_table_id),C=p;for(let N=0;N<a.length-1;N++){C+=a[N];let I=f;for(let A=0;A<c.length;A++){let R=I-c[A];if(!k.some(B=>B.start_column_index<=N&&B.end_column_index>N&&B.start_row_index<=A&&B.end_row_index>=A)){let B=st(e,{x:C,y:I}),G=st(e,{x:C,y:R});y.push({name:"line",type:"element",attributes:{x1:B.x.toString(),y1:B.y.toString(),x2:G.x.toString(),y2:G.y.toString(),stroke:t.schematic.table,"stroke-width":x.toString()},children:[],value:""})}I=R}}let E=f;for(let N=0;N<c.length-1;N++){E-=c[N];let I=p;for(let A=0;A<a.length;A++){let R=I+a[A];if(!k.some(B=>B.start_row_index<=N&&B.end_row_index>N&&B.start_column_index<=A&&B.end_column_index>=A)){let B=st(e,{x:I,y:E}),G=st(e,{x:R,y:E});y.push({name:"line",type:"element",attributes:{x1:B.x.toString(),y1:B.y.toString(),x2:G.x.toString(),y2:G.y.toString(),stroke:t.schematic.table,"stroke-width":x.toString()},children:[],value:""})}I=R}}for(let N of k)if(N.text){let I=a.slice(N.start_column_index,N.end_column_index+1).reduce((nt,et)=>nt+et,0),A=c.slice(N.start_row_index,N.end_row_index+1).reduce((nt,et)=>nt+et,0),R=p+a.slice(0,N.start_column_index).reduce((nt,et)=>nt+et,0),j=f-c.slice(0,N.start_row_index).reduce((nt,et)=>nt+et,0),{cell_padding:B=.2}=n,G=N.horizontal_align??"center",U=N.vertical_align??"middle",H={x:R+I/2,y:j-A/2};G==="left"?H.x=R+B:G==="right"&&(H.x=R+I-B),U==="top"?H.y=j-B:U==="bottom"&&(H.y=j-A+B);let Q=st(e,H),tt=ja(e,"reference_designator",N.font_size),V={left:"start",center:"middle",right:"end"},ot={top:"hanging",middle:"middle",bottom:"ideographic"};y.push({name:"text",type:"element",attributes:{x:Q.x.toString(),y:Q.y.toString(),"font-size":`${tt}px`,"text-anchor":V[G],"dominant-baseline":ot[U],fill:t.schematic.table,"font-family":"sans-serif"},children:[{type:"text",value:N.text,name:"",attributes:{},children:[]}],value:""})}return[{name:"g",type:"element",attributes:{"data-schematic-table-id":n.schematic_table_id},children:y,value:""}]},H8t=.02,W8t=({schPort:n,transform:e})=>{let t=st(e,n.center),i=Math.abs(e.a)*H8t*2;return[{name:"g",type:"element",value:"",attributes:{class:"schematic-port-hover","data-schematic-port-id":n.source_port_id},children:[{name:"circle",type:"element",value:"",attributes:{cx:t.x.toString(),cy:t.y.toString(),r:i.toString(),fill:"red",opacity:"0"},children:[]}]}]},Ytt=({component:n,transform:e,circuitJson:t})=>{let i=Be(t).schematic_port.list({schematic_component_id:n.schematic_component_id}),r=[];for(let s of i)r.push(...W8t({schPort:s,transform:e}));return r};tRt=jA;eRt=1200,nRt=600,$n={top:64,right:100,bottom:80,left:100},vtt="#1f77b4";fRt=15,Gtt=16,mRt=24;wRt=1200,SRt=1200,Htt=.55;Ett=["pcb_board","pcb_solder_paste"]});var cit=ue((g0e,iP)=>{"use strict";function xr(n){this._line=this._col=this._pos=0,this._stream=n}xr.not_whitespace_or_end=/^(\S|$)/;xr.space_quote_paren_escaped_or_end=/^(\s|\\|"|'|`|,|\(|\)|$)/;xr.string_or_escaped_or_end=/^(\\|"|$)/;xr.string_delimiters=/["]/;xr.quotes=/['`,]/;xr.quotes_map={"'":"quote","`":"quasiquote",",":"unquote"};xr.prototype={peek:p7t,consume:h7t,until:d7t,error:u7t,string:f7t,atom:m7t,quoted:_7t,expr:y7t,list:g7t};iP.exports=function n(e){var t=new n.Parser(e),i=t.expr();return i instanceof Error?i:t.peek()!=""?t.error("Superfluous characters after expression: `"+t.peek()+"`"):i};iP.exports.Parser=xr;iP.exports.SyntaxError=Error;function u7t(n){var e=new Error("Syntax error: "+n);return e.line=this._line+1,e.col=this._col+1,e}function p7t(){return this._stream.length==this._pos?"":this._stream[this._pos]}function h7t(){if(this._stream.length==this._pos)return"";var n=this._stream[this._pos];return this._pos+=1,n=="\r"?(this.peek()==`
144
+ `;r.push({name:"path",type:"element",attributes:{class:"net-label",d:v,fill:t.schematic.label_background,stroke:t.schematic.label_global,"stroke-width":`${Ui(e)}px`},value:"",children:[]});let S={x:f.x+u.x*s*.5,y:f.y+u.y*s*.5},P={left:"start",top:"start",bottom:"start",right:"end"}[n.anchor_side],T={left:"",right:"",top:`rotate(90 ${S.x} ${S.y})`,bottom:`rotate(-90 ${S.x} ${S.y})`}[n.anchor_side];return r.push({name:"text",type:"element",attributes:{class:"net-label-text",x:S.x.toString(),y:S.y.toString(),fill:t.schematic.label_global,"text-anchor":P,"dominant-baseline":"central","font-family":"sans-serif","font-variant-numeric":"tabular-nums","font-size":`${s}px`,transform:T},children:[{type:"text",value:i||"",name:"",attributes:{},children:[]}],value:""}),r},V8t=({schematicBox:n,transform:e,colorMap:t})=>{let i=st(e,{x:n.x,y:n.y}),r=st(e,{x:n.x+n.width,y:n.y+n.height}),s=Math.min(i.y,r.y),o=Math.max(i.y,r.y),a=Math.min(i.x,r.x),c=Math.max(i.x,r.x),l=Ui(e),u={class:"schematic-box",x:a.toString(),y:s.toString(),width:(c-a).toString(),height:(o-s).toString(),"stroke-width":`${l}px`,stroke:t.schematic.component_outline||"black",fill:"transparent"};if(n.is_dashed){let p=8*l,f=4*l;u["stroke-dasharray"]=`${p} ${f}`}return[{name:"rect",type:"element",value:"",attributes:u,children:[]}]},G8t=({schematicTable:n,transform:e,colorMap:t,circuitJson:i})=>{let{anchor_position:r,border_width:s=.05,anchor:o="center"}=n,{column_widths:a,row_heights:c}=$tt(n,i),l=a.reduce((N,I)=>N+I,0),u=c.reduce((N,I)=>N+I,0),p=r.x,f=r.y;o.includes("center")?p-=l/2:o.includes("right")&&(p-=l),o.includes("center")?f+=u/2:o.includes("bottom")&&(f+=u);let y=[],g=s*Math.abs(e.a),x=Ui(e),[v,S]=st(e,[p,f]),[P,T]=st(e,[p+l,f-u]);y.push({name:"rect",type:"element",attributes:{x:v.toString(),y:S.toString(),width:(P-v).toString(),height:(T-S).toString(),fill:"none",stroke:t.schematic.table,"stroke-width":g.toString()},children:[],value:""});let k=i.filter(N=>N.type==="schematic_table_cell"&&N.schematic_table_id===n.schematic_table_id),C=p;for(let N=0;N<a.length-1;N++){C+=a[N];let I=f;for(let A=0;A<c.length;A++){let R=I-c[A];if(!k.some(B=>B.start_column_index<=N&&B.end_column_index>N&&B.start_row_index<=A&&B.end_row_index>=A)){let B=st(e,{x:C,y:I}),G=st(e,{x:C,y:R});y.push({name:"line",type:"element",attributes:{x1:B.x.toString(),y1:B.y.toString(),x2:G.x.toString(),y2:G.y.toString(),stroke:t.schematic.table,"stroke-width":x.toString()},children:[],value:""})}I=R}}let E=f;for(let N=0;N<c.length-1;N++){E-=c[N];let I=p;for(let A=0;A<a.length;A++){let R=I+a[A];if(!k.some(B=>B.start_row_index<=N&&B.end_row_index>N&&B.start_column_index<=A&&B.end_column_index>=A)){let B=st(e,{x:I,y:E}),G=st(e,{x:R,y:E});y.push({name:"line",type:"element",attributes:{x1:B.x.toString(),y1:B.y.toString(),x2:G.x.toString(),y2:G.y.toString(),stroke:t.schematic.table,"stroke-width":x.toString()},children:[],value:""})}I=R}}for(let N of k)if(N.text){let I=a.slice(N.start_column_index,N.end_column_index+1).reduce((nt,et)=>nt+et,0),A=c.slice(N.start_row_index,N.end_row_index+1).reduce((nt,et)=>nt+et,0),R=p+a.slice(0,N.start_column_index).reduce((nt,et)=>nt+et,0),j=f-c.slice(0,N.start_row_index).reduce((nt,et)=>nt+et,0),{cell_padding:B=.2}=n,G=N.horizontal_align??"center",U=N.vertical_align??"middle",H={x:R+I/2,y:j-A/2};G==="left"?H.x=R+B:G==="right"&&(H.x=R+I-B),U==="top"?H.y=j-B:U==="bottom"&&(H.y=j-A+B);let Q=st(e,H),tt=ja(e,"reference_designator",N.font_size),V={left:"start",center:"middle",right:"end"},ot={top:"hanging",middle:"middle",bottom:"ideographic"};y.push({name:"text",type:"element",attributes:{x:Q.x.toString(),y:Q.y.toString(),"font-size":`${tt}px`,"text-anchor":V[G],"dominant-baseline":ot[U],fill:t.schematic.table,"font-family":"sans-serif"},children:[{type:"text",value:N.text,name:"",attributes:{},children:[]}],value:""})}return[{name:"g",type:"element",attributes:{"data-schematic-table-id":n.schematic_table_id},children:y,value:""}]},H8t=.02,W8t=({schPort:n,transform:e})=>{let t=st(e,n.center),i=Math.abs(e.a)*H8t*2;return[{name:"g",type:"element",value:"",attributes:{class:"schematic-port-hover","data-schematic-port-id":n.source_port_id},children:[{name:"circle",type:"element",value:"",attributes:{cx:t.x.toString(),cy:t.y.toString(),r:i.toString(),fill:"red",opacity:"0"},children:[]}]}]},Ytt=({component:n,transform:e,circuitJson:t})=>{let i=Be(t).schematic_port.list({schematic_component_id:n.schematic_component_id}),r=[];for(let s of i)r.push(...W8t({schPort:s,transform:e}));return r};tRt=jA;eRt=1200,nRt=600,$n={top:64,right:100,bottom:80,left:100},vtt="#1f77b4";fRt=15,Gtt=16,mRt=24;wRt=1200,SRt=1200,Htt=.55;Ett=["pcb_board","pcb_solder_paste"]});var cit=ue((x0e,iP)=>{"use strict";function xr(n){this._line=this._col=this._pos=0,this._stream=n}xr.not_whitespace_or_end=/^(\S|$)/;xr.space_quote_paren_escaped_or_end=/^(\s|\\|"|'|`|,|\(|\)|$)/;xr.string_or_escaped_or_end=/^(\\|"|$)/;xr.string_delimiters=/["]/;xr.quotes=/['`,]/;xr.quotes_map={"'":"quote","`":"quasiquote",",":"unquote"};xr.prototype={peek:p7t,consume:h7t,until:d7t,error:u7t,string:f7t,atom:m7t,quoted:_7t,expr:y7t,list:g7t};iP.exports=function n(e){var t=new n.Parser(e),i=t.expr();return i instanceof Error?i:t.peek()!=""?t.error("Superfluous characters after expression: `"+t.peek()+"`"):i};iP.exports.Parser=xr;iP.exports.SyntaxError=Error;function u7t(n){var e=new Error("Syntax error: "+n);return e.line=this._line+1,e.col=this._col+1,e}function p7t(){return this._stream.length==this._pos?"":this._stream[this._pos]}function h7t(){if(this._stream.length==this._pos)return"";var n=this._stream[this._pos];return this._pos+=1,n=="\r"?(this.peek()==`
145
145
  `&&(this._pos+=1,n+=`
146
146
  `),this._line++,this._col=0):n==`
147
147
  `?(this._line++,this._col=0):this._col++,n}function d7t(n){for(var e="";!n.test(this.peek());)e+=this.consume();return e}function f7t(){for(var n=this.consume(),e="";;){e+=this.until(xr.string_or_escaped_or_end);var t=this.peek();if(t=="")return this.error("Unterminated string literal");if(t==n){this.consume();break}if(t=="\\"){this.consume(),t=this.peek(),t=="r"?(this.consume(),e+="\r"):t=="t"?(this.consume(),e+=" "):t=="n"?(this.consume(),e+=`
@@ -245,12 +245,12 @@ ${y.join(`
245
245
  </div>`},LNt=n=>{let e=n.layout(),t={title:"CssGrid",coordinateSystem:"screen",lines:[],circles:[],points:[],rects:[],texts:[]},{cells:i}=e;for(let r of i){let{x:s,y:o,width:a,height:c,key:l}=r;t.rects.push({center:{x:s+a/2,y:o+c/2},width:a,height:c,fill:eQ(l),label:l})}return t};function MS(n){return n.replace(/repeat\((\d+),\s*([^)]+)\)/g,(e,t,i)=>Array(Number(t)).fill(i.trim()).join(" "))}function CS(n){return n.trim().split(/\s+/).filter(Boolean)}function JJ(n){return n?CS(MS(n)).length:0}function QJ(n,e){if(n==="auto")return{fr:1};if(n.endsWith("%")){let i=parseFloat(n);return e!=null?e*i/100:0}if(n.endsWith("px"))return parseFloat(n);if(n.endsWith("em"))return parseFloat(n)*16;if(n.endsWith("fr"))return{fr:parseFloat(n)};let t=parseFloat(n);return Number.isNaN(t)?0:t}function tQ(n,e){return n>0?n:e+2+n}var FNt=n=>{let e=n.opts,t=e.children,i,r;if("gridTemplate"in e&&typeof e.gridTemplate=="string"){let[E,N]=e.gridTemplate.split("/");i=E?.trim(),r=N?.trim()}else i=typeof e.gridTemplateRows=="string"?e.gridTemplateRows:void 0,r=typeof e.gridTemplateColumns=="string"?e.gridTemplateColumns:void 0;let s=JJ(r),o=JJ(i);function a(E,N,I,A){if(!E)return 0;let R=MS(E),j=CS(R),B=j.length,G=0,U=!1;for(let Q=0;Q<j.length;Q++){let tt=j[Q];if(tt.endsWith("px"))G+=parseFloat(tt);else if(tt.endsWith("em"))G+=parseFloat(tt)*16;else if(tt.endsWith("fr")||tt==="auto"){U=!0;let V=0;for(let ot of N){let nt=I?ot.columnStart||ot.column:ot.rowStart||ot.row,et=I?ot.columnSpan||1:ot.rowSpan||1,ht=I?ot.contentWidth:ot.contentHeight,dt=(typeof nt=="number"?nt:parseInt(nt||"1"))-1,St=typeof et=="number"?et:parseInt(et.toString());if(dt<=Q&&Q<dt+St&&ht){let Pt=typeof ht=="string"&&ht.endsWith("px")?parseFloat(ht):typeof ht=="number"?ht:0;V=Math.max(V,Pt/St)}}G+=V}}let H=A*(B-1);return G+H}function c(E,N,I,A=!0,R=1){if(!E)return[];if(N==null){let et=MS(E),ht=CS(et),dt=ht.length,St=Y=>Y===void 0?0:typeof Y=="number"?Y:(Y.endsWith("px"),parseFloat(Y)),Pt=new Array(dt).fill(0),ut=0;for(let Y of t){let q=A?typeof Y.columnSpan=="number"?Y.columnSpan:Y.columnSpan?parseInt(Y.columnSpan.toString()):1:typeof Y.rowSpan=="number"?Y.rowSpan:Y.rowSpan?parseInt(Y.rowSpan.toString()):1,rt=A?Y.contentWidth:Y.contentHeight,pt=St(rt)/q,yt;A?(Y.columnStart!==void 0||Y.column!==void 0)&&(yt=parseInt(Y.columnStart??Y.column)-1):(Y.rowStart!==void 0||Y.row!==void 0)&&(yt=parseInt(Y.rowStart??Y.row)-1),(yt===void 0||Number.isNaN(yt))&&(A?yt=ut%dt:yt=Math.floor(ut/R),ut+=q);for(let Z=0;Z<q&&yt+Z<dt;Z++)Pt[yt+Z]=Math.max(Pt[yt+Z],pt)}return ht.forEach((Y,q)=>{let rt=QJ(Y,void 0);typeof rt=="number"&&(Pt[q]=rt)}),Pt}let j=MS(E),B=CS(j),G=B.length,U=N;U==null&&(U=a(E,t,A,I));let H=U-I*(G-1),Q=0,tt=0,V=[],ot=[];B.forEach((et,ht)=>{let dt=QJ(et,H);typeof dt=="number"?(ot.push(dt),Q+=dt):dt&&typeof dt=="object"&&"fr"in dt?(ot.push(dt),tt+=dt.fr,V.push({idx:ht,fr:dt.fr})):(ot.push(0),Q+=0)});let nt=Math.max(H-Q,0);return ot.map(et=>typeof et=="number"?et:tt>0?nt/tt*et.fr:0)}let l=typeof e.gap=="number"?e.gap:Array.isArray(e.gap)?e.gap[0]:0,u=typeof e.gap=="number"?e.gap:Array.isArray(e.gap)?e.gap[1]:0,p=c(i,e.containerHeight,l,!1,s||1),f=c(r,e.containerWidth,u,!0,o||1),y=p.length,g=f.length;g===0&&t.length>0&&(g=1);let x=[],v=0;for(let E of t){let N=E.rowStart!==void 0?E.rowStart:E.row,I=E.columnStart!==void 0?E.columnStart:E.column,A=E.rowSpan!==void 0?typeof E.rowSpan=="string"?parseInt(E.rowSpan):E.rowSpan:1,R=E.columnSpan!==void 0?typeof E.columnSpan=="string"?parseInt(E.columnSpan):E.columnSpan:1;if(E.rowEnd!==void 0){let G=typeof E.rowEnd=="string"?parseInt(E.rowEnd):E.rowEnd;N!==void 0?A=G-(typeof N=="string"?parseInt(N):N):N=G-A}if(E.columnEnd!==void 0){let G=typeof E.columnEnd=="string"?parseInt(E.columnEnd):E.columnEnd;I!==void 0?R=G-(typeof I=="string"?parseInt(I):I):I=G-R}if(typeof N=="string"&&(N=parseInt(N)),typeof I=="string"&&(I=parseInt(I)),typeof N=="number"&&N<0&&(N=tQ(N,y)),typeof I=="number"&&I<0&&(I=tQ(I,g)),N===void 0&&I!==void 0)N=1;else if(I===void 0&&N!==void 0)I=1;else if(N===void 0&&I===void 0){let G=v;N=Math.floor(G/g)+1,I=G%g+1}let j=N-1,B=I-1;A=Math.max(1,A),R=Math.max(1,R),x.push({key:E.key,row:j,column:B,rowSpan:A,columnSpan:R,x:0,y:0,width:0,height:0}),v+=R}let S=p.length,P=f.length;for(let E of x)E.row+E.rowSpan>S&&(S=E.row+E.rowSpan),E.column+E.columnSpan>P&&(P=E.column+E.columnSpan);if(p.length===0&&S>0&&e.containerHeight){let E=S,I=(e.containerHeight-l*(E-1))/E;for(let A=0;A<E;A++)p.push(I)}else for(;p.length<S;)p.push(0);if(f.length===0&&P>0&&e.containerWidth){let E=P,I=(e.containerWidth-u*(E-1))/E;for(let A=0;A<E;A++)f.push(I)}else if(f.length===0&&t.length>0&&e.containerWidth)f.push(e.containerWidth);else for(;f.length<P;)f.push(0);let T=(E,N,I)=>{let A=0;for(let R=0;R<E;R++)A+=N[R]||0,A+=I;return A},k=(E,N,I,A)=>{let R=0;for(let j=E;j<E+N;j++)R+=I[j]||0,j>E&&(R+=A);return R},C={};for(let E of x){let N=t.find(ot=>ot.key===E.key),I=T(E.column,f,u),A=T(E.row,p,l),R=k(E.column,E.columnSpan,f,u),j=k(E.row,E.rowSpan,p,l),B=ot=>ot===void 0?0:typeof ot=="string"?ot.endsWith("px")?parseFloat(ot):ot.endsWith("%")?0:parseFloat(ot):ot,G=B(N?.contentWidth),U=B(N?.contentHeight),H=R,Q=j,tt=I,V=A;if(G>0)switch(H=G,e.justifyItems||"stretch"){case"start":tt=I;break;case"end":tt=I+R-H;break;case"center":tt=I+(R-H)/2;break;case"stretch":H=R,tt=I;break}if(U>0)switch(Q=U,e.alignItems||"stretch"){case"start":V=A;break;case"end":V=A+j-Q;break;case"center":V=A+(j-Q)/2;break;case"stretch":Q=j,V=A;break}E.x=tt,E.y=V,E.width=H,E.height=Q,C[E.key]={x:tt,y:V,width:H,height:Q}}return{cells:x,rowSizes:p,columnSizes:f,rowGap:l,columnGap:u,itemCoordinates:C}},nQ=class{constructor(n){d(this,"opts");this.opts=n}layout(){return FNt(this)}convertToHtml(){return ONt(this)}visualize(){return LNt(this)}};wt();var Ket=Ht(An(),1);Oe();Oe();wt();var sA=class{constructor(n){d(this,"netMap");d(this,"idToNetMap");this.netMap=n,this.idToNetMap={};for(let[e,t]of Object.entries(n))for(let i of t)this.idToNetMap[i]=e}addConnections(n){for(let e of n){let t=new Set;for(let r of e){let s=this.idToNetMap[r];s&&t.add(s)}let i;if(t.size===0)i=`connectivity_net${Object.keys(this.netMap).length}`,this.netMap[i]=[];else if(t.size===1)i=t.values().next().value??`connectivity_net${Object.keys(this.netMap).length}`;else{i=t.values().next().value??`connectivity_net${Object.keys(this.netMap).length}`;for(let r of t)if(r!==i){let s=this.netMap[i],o=this.netMap[r];if(s&&o){s.push(...o),this.netMap[r]=s;for(let a of s)this.idToNetMap[a]=i}}}for(let r of e){let s=this.netMap[i];s&&!s.includes(r)&&s.push(r),this.idToNetMap[r]=i}}}getIdsConnectedToNet(n){return this.netMap[n]||[]}getNetConnectedToId(n){return this.idToNetMap[n]}areIdsConnected(n,e){if(n===e)return!0;let t=this.getNetConnectedToId(n);if(!t)return!1;let i=this.getNetConnectedToId(e);return i?t===i||i===n||i===n:!1}areAllIdsConnected(n){if(n.length===0)return!0;let e=this.getNetConnectedToId(n[0]);if(!e)return!1;for(let t of n){let i=this.getNetConnectedToId(t);if(i===void 0||i!==e)return!1}return!0}};Ig();var y1=class{constructor(){this.ids=[],this.values=[],this.length=0}clear(){this.length=0}push(e,t){let i=this.length++;for(;i>0;){let r=i-1>>1,s=this.values[r];if(t>=s)break;this.ids[i]=this.ids[r],this.values[i]=s,i=r}this.ids[i]=e,this.values[i]=t}pop(){if(this.length===0)return;let e=this.ids,t=this.values,i=e[0],r=--this.length;if(r>0){let s=e[r],o=t[r],a=0,c=r>>1;for(;a<c;){let l=(a<<1)+1,u=l+1,p=l+(+(u<r)&+(t[u]<t[l]));if(t[p]>=o)break;e[a]=e[p],t[a]=t[p],a=p}e[a]=s,t[a]=o}return i}peek(){return this.length>0?this.ids[0]:void 0}peekValue(){return this.length>0?this.values[0]:void 0}shrink(){this.ids.length=this.values.length=this.length}};var iQ=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],oA=3,g1=class n{static from(e,t=0){if(t%8!==0)throw new Error("byteOffset must be 8-byte aligned.");if(!e||e.byteLength===void 0||e.buffer)throw new Error("Data must be an instance of ArrayBuffer or SharedArrayBuffer.");let[i,r]=new Uint8Array(e,t+0,2);if(i!==251)throw new Error("Data does not appear to be in a Flatbush format.");let s=r>>4;if(s!==oA)throw new Error(`Got v${s} data when expected v${oA}.`);let o=iQ[r&15];if(!o)throw new Error("Unrecognized array type.");let[a]=new Uint16Array(e,t+2,1),[c]=new Uint32Array(e,t+4,1);return new n(c,a,o,void 0,e,t)}constructor(e,t=16,i=Float64Array,r=ArrayBuffer,s,o=0){if(e===void 0)throw new Error("Missing required argument: numItems.");if(isNaN(e)||e<=0)throw new Error(`Unexpected numItems value: ${e}.`);this.numItems=+e,this.nodeSize=Math.min(Math.max(+t,2),65535),this.byteOffset=o;let a=e,c=a;this._levelBounds=[a*4];do a=Math.ceil(a/this.nodeSize),c+=a,this._levelBounds.push(c*4);while(a!==1);this.ArrayType=i,this.IndexArrayType=c<16384?Uint16Array:Uint32Array;let l=iQ.indexOf(i),u=c*4*i.BYTES_PER_ELEMENT;if(l<0)throw new Error(`Unexpected typed array class: ${i}.`);if(s)this.data=s,this._boxes=new i(s,o+8,c*4),this._indices=new this.IndexArrayType(s,o+8+u,c),this._pos=c*4,this.minX=this._boxes[this._pos-4],this.minY=this._boxes[this._pos-3],this.maxX=this._boxes[this._pos-2],this.maxY=this._boxes[this._pos-1];else{let p=this.data=new r(8+u+c*this.IndexArrayType.BYTES_PER_ELEMENT);this._boxes=new i(p,8,c*4),this._indices=new this.IndexArrayType(p,8+u,c),this._pos=0,this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,new Uint8Array(p,0,2).set([251,(oA<<4)+l]),new Uint16Array(p,2,1)[0]=t,new Uint32Array(p,4,1)[0]=e}this._queue=new y1}add(e,t,i=e,r=t){let s=this._pos>>2,o=this._boxes;return this._indices[s]=s,o[this._pos++]=e,o[this._pos++]=t,o[this._pos++]=i,o[this._pos++]=r,e<this.minX&&(this.minX=e),t<this.minY&&(this.minY=t),i>this.maxX&&(this.maxX=i),r>this.maxY&&(this.maxY=r),s}finish(){if(this._pos>>2!==this.numItems)throw new Error(`Added ${this._pos>>2} items when expected ${this.numItems}.`);let e=this._boxes;if(this.numItems<=this.nodeSize){e[this._pos++]=this.minX,e[this._pos++]=this.minY,e[this._pos++]=this.maxX,e[this._pos++]=this.maxY;return}let t=this.maxX-this.minX||1,i=this.maxY-this.minY||1,r=new Uint32Array(this.numItems),s=65535;for(let o=0,a=0;o<this.numItems;o++){let c=e[a++],l=e[a++],u=e[a++],p=e[a++],f=Math.floor(s*((c+u)/2-this.minX)/t),y=Math.floor(s*((l+p)/2-this.minY)/i);r[o]=DNt(f,y)}aA(r,e,this._indices,0,this.numItems-1,this.nodeSize);for(let o=0,a=0;o<this._levelBounds.length-1;o++){let c=this._levelBounds[o];for(;a<c;){let l=a,u=e[a++],p=e[a++],f=e[a++],y=e[a++];for(let g=1;g<this.nodeSize&&a<c;g++)u=Math.min(u,e[a++]),p=Math.min(p,e[a++]),f=Math.max(f,e[a++]),y=Math.max(y,e[a++]);this._indices[this._pos>>2]=l,e[this._pos++]=u,e[this._pos++]=p,e[this._pos++]=f,e[this._pos++]=y}}}search(e,t,i,r,s){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");let o=this._boxes.length-4,a=[],c=[];for(;o!==void 0;){let l=Math.min(o+this.nodeSize*4,rQ(o,this._levelBounds));for(let u=o;u<l;u+=4){let p=this._boxes[u];if(i<p)continue;let f=this._boxes[u+1];if(r<f)continue;let y=this._boxes[u+2];if(e>y)continue;let g=this._boxes[u+3];if(t>g)continue;let x=this._indices[u>>2]|0;o>=this.numItems*4?a.push(x):(s===void 0||s(x,p,f,y,g))&&c.push(x)}o=a.pop()}return c}neighbors(e,t,i=1/0,r=1/0,s){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");let o=this._boxes.length-4,a=this._queue,c=[],l=r*r;t:for(;o!==void 0;){let u=Math.min(o+this.nodeSize*4,rQ(o,this._levelBounds));for(let p=o;p<u;p+=4){let f=this._indices[p>>2]|0,y=this._boxes[p],g=this._boxes[p+1],x=this._boxes[p+2],v=this._boxes[p+3],S=e<y?y-e:e>x?e-x:0,P=t<g?g-t:t>v?t-v:0,T=S*S+P*P;T>l||(o>=this.numItems*4?a.push(f<<1,T):(s===void 0||s(f))&&a.push((f<<1)+1,T))}for(;a.length&&a.peek()&1;)if(a.peekValue()>l||(c.push(a.pop()>>1),c.length===i))break t;o=a.length?a.pop()>>1:void 0}return a.clear(),c}};function rQ(n,e){let t=0,i=e.length-1;for(;t<i;){let r=t+i>>1;e[r]>n?i=r:t=r+1}return e[t]}function aA(n,e,t,i,r,s){if(Math.floor(i/s)>=Math.floor(r/s))return;let o=n[i],a=n[i+r>>1],c=n[r],l=c,u=Math.max(o,a);c>u?l=u:u===o?l=Math.max(a,c):u===a&&(l=Math.max(o,c));let p=i-1,f=r+1;for(;;){do p++;while(n[p]<l);do f--;while(n[f]>l);if(p>=f)break;zNt(n,e,t,p,f)}aA(n,e,t,i,f,s),aA(n,e,t,f+1,r,s)}function zNt(n,e,t,i,r){let s=n[i];n[i]=n[r],n[r]=s;let o=4*i,a=4*r,c=e[o],l=e[o+1],u=e[o+2],p=e[o+3];e[o]=e[a],e[o+1]=e[a+1],e[o+2]=e[a+2],e[o+3]=e[a+3],e[a]=c,e[a+1]=l,e[a+2]=u,e[a+3]=p;let f=t[i];t[i]=t[r],t[r]=f}function DNt(n,e){let t=n^e,i=65535^t,r=65535^(n|e),s=n&(e^65535),o=t|i>>1,a=t>>1^t,c=r>>1^i&s>>1^r,l=t&r>>1^s>>1^s;t=o,i=a,r=c,s=l,o=t&t>>2^i&i>>2,a=t&i>>2^i&(t^i)>>2,c^=t&r>>2^i&s>>2,l^=i&r>>2^(t^i)&s>>2,t=o,i=a,r=c,s=l,o=t&t>>4^i&i>>4,a=t&i>>4^i&(t^i)>>4,c^=t&r>>4^i&s>>4,l^=i&r>>4^(t^i)&s>>4,t=o,i=a,r=c,s=l,c^=t&r>>8^i&s>>8,l^=i&r>>8^(t^i)&s>>8,t=c^c>>1,i=l^l>>1;let u=n^e,p=i|65535^(u|t);return u=(u|u<<8)&16711935,u=(u|u<<4)&252645135,u=(u|u<<2)&858993459,u=(u|u<<1)&1431655765,p=(p|p<<8)&16711935,p=(p|p<<4)&252645135,p=(p|p<<2)&858993459,p=(p|p<<1)&1431655765,(p<<1|u)>>>0}var kr=class{constructor(){d(this,"MAX_ITERATIONS",1e5);d(this,"solved",!1);d(this,"failed",!1);d(this,"iterations",0);d(this,"progress",0);d(this,"error",null);d(this,"activeSubSolver");d(this,"failedSubSolvers");d(this,"timeToSolve");d(this,"stats",{})}step(){if(!this.solved&&!this.failed){this.iterations++;try{this._step()}catch(n){throw this.error=`${this.constructor.name} error: ${n}`,this.failed=!0,n}!this.solved&&this.iterations>this.MAX_ITERATIONS&&this.tryFinalAcceptance(),!this.solved&&this.iterations>this.MAX_ITERATIONS&&(this.error=`${this.constructor.name} ran out of iterations`,this.failed=!0),"computeProgress"in this&&(this.progress=this.computeProgress())}}_step(){}getConstructorParams(){throw new Error("getConstructorParams not implemented")}solve(){let n=Date.now();for(;!this.solved&&!this.failed;)this.step();let e=Date.now();this.timeToSolve=e-n}visualize(){return{lines:[],points:[],rects:[],circles:[]}}tryFinalAcceptance(){}preview(){return{lines:[],points:[],rects:[],circles:[]}}},mA=n=>{let e=new sA({});for(let i of n.directConnections)e.addConnections([i.netId?[i.netId,...i.pinIds]:i.pinIds]);let t=new sA(e.netMap);for(let i of n.netConnections)t.addConnections([[i.netId,...i.pinIds]]);return{directConnMap:e,netConnMap:t}};function $Nt(n,e={}){let t=n.length,i=e?.maxDistance??Number.POSITIVE_INFINITY;if(t<=1)return[];{let u=new Set;for(let p of n){if(u.has(p.pinId))throw new Error(`Duplicate pinId detected: "${p.pinId}"`);u.add(p.pinId)}}let r=(u,p)=>Math.abs(u.x-p.x)+Math.abs(u.y-p.y),s=new Array(t).fill(!1),o=new Array(t).fill(Number.POSITIVE_INFINITY),a=new Array(t).fill(-1),c=0;for(let u=1;u<t;u++)n[u].pinId<n[c].pinId&&(c=u);o[c]=0;let l=[];for(let u=0;u<t;u++){let p=-1,f=Number.POSITIVE_INFINITY,y="";for(let g=0;g<t;g++)if(!s[g]){let x=o[g];(x<f||x===f&&(y===""||n[g].pinId<y))&&(f=x,y=n[g].pinId,p=g)}s[p]=!0,a[p]!==-1&&l.push([n[p].pinId,n[a[p]].pinId]);for(let g=0;g<t;g++)if(!s[g]){let x=r(n[p],n[g]),v=e?.forbidEdge?.(n[p],n[g])??!1,S=x>i||v?Number.POSITIVE_INFINITY:x;(S<o[g]||S===o[g]&&n[p].pinId<n[a[g]]?.pinId)&&(o[g]=S,a[g]=p)}}return l}var x1=(n,e)=>{let{x:t,y:i}=n,{center:r,width:s,height:o}=e,a=r.y+o/2,c=r.y-o/2,l=r.x+s/2,u=r.x-s/2,p=a-i,f=i-c,y=l-t,g=t-u,x=Math.min(p,f,y,g);return x===p?"y+":x===f?"y-":x===y?"x+":"x-"},jNt=n=>{let{pins:e,inputProblem:t,pinIdMap:i,chipMap:r}=n,s=f=>{let y=new Set,g=[f];y.add(f);let x=t.directConnections||[];for(;g.length;){let v=g.shift();for(let S of x)if(S.pinIds.includes(v))for(let P of S.pinIds)y.has(P)||(y.add(P),g.push(P))}return y},o=e[0].pinId,a=e[1].pinId,c=new Set([...s(o),...s(a)]),l=new Map,u=new Map,p=new Set(e.map(f=>f.chipId));for(let f of c){let y=i.get(f);if(!y)continue;let g=r[y.chipId];if(!g)continue;let x=y._facingDirection??x1(y,g),v=u.get(g.chipId);if(!v){v={center:g.center};let S={xPos:0,xNeg:0,yPos:0,yNeg:0};for(let P of g.pins){let T=P._facingDirection??x1(P,g);T==="x+"&&S.xPos++,T==="x-"&&S.xNeg++,T==="y+"&&S.yPos++,T==="y-"&&S.yNeg++}v.counts=S,u.set(g.chipId,v)}x==="x+"&&(v.hasXPos=!0),x==="x-"&&(v.hasXNeg=!0),x==="y+"&&(v.hasYPos=!0),x==="y-"&&(v.hasYNeg=!0)}for(let[f,y]of u){let g=new Set,x={axes:g},v=y.counts;!!!(v&&(v.xPos>1||v.xNeg>1||v.yPos>1||v.yNeg>1))&&p.has(f)||(y.hasXPos&&y.hasXNeg&&(x.x=y.center.x,g.add("x")),y.hasYPos&&y.hasYNeg&&(x.y=y.center.y,g.add("y"))),g.size>0&&l.set(f,x)}return l},cA=n=>{let{inputProblem:e,chipMap:t,pinIdMap:i,p1:r,p2:s}=n,o=jNt({pins:[r,s],inputProblem:e,pinIdMap:i,chipMap:t});if(o.size===0)return!1;let a=1e-9,c=(y,g)=>{for(let[,x]of o)if(x.axes.has("x")&&typeof x.x=="number"&&(y.x-x.x)*(g.x-x.x)<-a||x.axes.has("y")&&typeof x.y=="number"&&(y.y-x.y)*(g.y-x.y)<-a)return!0;return!1};if(Math.abs(r.x-s.x)<a||Math.abs(r.y-s.y)<a)return c({x:r.x,y:r.y},{x:s.x,y:s.y});let l={x:s.x,y:r.y},u={x:r.x,y:s.y},p=c({x:r.x,y:r.y},l)||c(l,{x:s.x,y:s.y}),f=c({x:r.x,y:r.y},u)||c(u,{x:s.x,y:s.y});return p&&f},Rs=(n,e=1)=>`hsl(${n.split("").reduce((i,r)=>i*31+r.charCodeAt(0),0)%360}, 100%, 50%, ${e})`,cs=(n,e={})=>{let{connectionAlpha:t=.8,chipAlpha:i=.8}=e,r={lines:[],points:[],rects:[]},s=new Map;for(let o of n.chips)for(let a of o.pins)s.set(a.pinId,a);for(let o of n.chips){r.rects.push({label:o.chipId,center:o.center,width:o.width,height:o.height,fill:Rs(o.chipId,i)});for(let a of o.pins)r.points.push({label:`${a.pinId}
246
246
  ${a._facingDirection??x1(a,o)}`,x:a.x,y:a.y,color:Rs(a.pinId,.8)})}for(let o of n.directConnections){let[a,c]=o.pinIds,l=s.get(a),u=s.get(c);r.lines.push({points:[{x:l.x,y:l.y},{x:u.x,y:u.y}],strokeColor:Rs(o.netId??`${a}-${c}`,t)})}for(let o of n.netConnections){let a=o.pinIds.map(c=>s.get(c));for(let c=0;c<a.length-1;c++)for(let l=c+1;l<a.length;l++){let u=a[c],p=a[l];r.lines.push({points:[{x:u.x,y:u.y},{x:p.x,y:p.y}],strokeColor:Rs(o.netId,t),strokeDash:"4 2"})}}return r},BNt=class extends kr{constructor({inputProblem:e}){super();d(this,"inputProblem");d(this,"mspConnectionPairs",[]);d(this,"dcConnMap");d(this,"globalConnMap");d(this,"queuedDcNetIds");d(this,"chipMap");d(this,"maxMspPairDistance");d(this,"pinMap");d(this,"userNetIdByPinId");this.inputProblem=e,this.maxMspPairDistance=e.maxMspPairDistance??1;let{directConnMap:t,netConnMap:i}=mA(e);this.dcConnMap=t,this.globalConnMap=i,this.pinMap={};for(let r of e.chips)for(let s of r.pins)this.pinMap[s.pinId]={...s,chipId:r.chipId};this.chipMap={};for(let r of e.chips)this.chipMap[r.chipId]=r;this.userNetIdByPinId={};for(let r of e.directConnections)if(r.netId){let[s,o]=r.pinIds;this.userNetIdByPinId[s]=r.netId,this.userNetIdByPinId[o]=r.netId}for(let r of e.netConnections)for(let s of r.pinIds)this.userNetIdByPinId[s]=r.netId;this.queuedDcNetIds=Object.keys(i.netMap)}getConstructorParams(){return{inputProblem:this.inputProblem}}_step(){if(this.queuedDcNetIds.length===0){this.solved=!0;return}let e=this.queuedDcNetIds.shift(),i=this.globalConnMap.getIdsConnectedToNet(e).filter(o=>!!this.pinMap[o]);if(i.length<=1)return;if(i.length===2){let[o,a]=i,c=this.pinMap[o],l=this.pinMap[a];if(Math.abs(c.x-l.x)+Math.abs(c.y-l.y)>this.maxMspPairDistance)return;let p=new Map(Object.entries(this.pinMap));if(cA({inputProblem:this.inputProblem,chipMap:this.chipMap,pinIdMap:p,p1:c,p2:l}))return;let f=this.globalConnMap.getNetConnectedToId(o),y=this.userNetIdByPinId[o]??this.userNetIdByPinId[a];this.mspConnectionPairs.push({mspPairId:`${o}-${a}`,dcConnNetId:e,globalConnNetId:f,userNetId:y,pins:[c,l]});return}let r=new Map(Object.entries(this.pinMap)),s=$Nt(i.map(o=>this.pinMap[o]).filter(Boolean),{maxDistance:this.maxMspPairDistance,forbidEdge:(o,a)=>cA({inputProblem:this.inputProblem,chipMap:this.chipMap,pinIdMap:r,p1:o,p2:a})});for(let[o,a]of s){let c=this.pinMap[o],l=this.pinMap[a];if(cA({inputProblem:this.inputProblem,chipMap:this.chipMap,pinIdMap:r,p1:c,p2:l}))continue;let u=this.globalConnMap.getNetConnectedToId(o),p=this.userNetIdByPinId[o]??this.userNetIdByPinId[a];this.mspConnectionPairs.push({mspPairId:`${o}-${a}`,dcConnNetId:e,globalConnNetId:u,userNetId:p,pins:[c,l]})}}visualize(){let e=cs(this.inputProblem,{chipAlpha:.1,connectionAlpha:.1});for(let t of this.mspConnectionPairs)e.lines.push({points:[{x:t.pins[0].x,y:t.pins[0].y},{x:t.pins[1].x,y:t.pins[1].y}],strokeColor:Rs(t.mspPairId,.75)});return e}};function _A(n){let e=n.width/2,t=n.height/2;return{minX:n.center.x-e,maxX:n.center.x+e,minY:n.center.y-t,maxY:n.center.y+t}}var YNt=n=>{let e=_A(n);return{chipId:n.chipId,...e}},NS=n=>n.chips.map(YNt),yA=1e-9,Fa=(n,e,t=yA)=>Math.abs(n.x-e.x)<t,ll=(n,e,t=yA)=>Math.abs(n.y-e.y)<t,v1=(n,e,t,i=yA)=>{let r=Fa(n,e,i),s=ll(n,e,i);if(!r&&!s)return!1;if(r){let o=n.x;if(o<t.minX-i||o>t.maxX+i)return!1;let a=Math.min(n.y,e.y),c=Math.max(n.y,e.y);return Math.min(c,t.maxY)-Math.max(a,t.minY)>i}else{let o=n.y;if(o<t.minY-i||o>t.maxY+i)return!1;let a=Math.min(n.x,e.x),c=Math.max(n.x,e.x);return Math.min(c,t.maxX)-Math.max(a,t.minX)>i}},XNt=(n,e,t={})=>{for(let i=0;i<n.length-1;i++){let r=n[i],s=n[i+1],o=t.excludeRectIdsForSegment?.(i)??new Set;for(let a of e)if(!o.has(a.chipId)&&v1(r,s,a))return{segIndex:i,rect:a}}return null},UNt=(n,e)=>{for(let t=0;t<n.length-1;t++)for(let i of e)if(v1(n[t],n[t+1],i))return!0;return!1},mQ=1e-9,VNt=(n,e)=>({minX:Math.min(n.x,e.x),maxX:Math.max(n.x,e.x),minY:Math.min(n.y,e.y),maxY:Math.max(n.y,e.y)}),sQ=(n,e,t,i=mQ)=>n==="x"?e.x<t.minX-i?[(e.x+t.minX)/2]:e.x>t.maxX+i?[(e.x+t.maxX)/2]:[t.minX-.2,t.maxX+.2]:e.y<t.minY-i?[(e.y+t.minY)/2]:e.y>t.maxY+i?[(e.y+t.maxY)/2]:[t.minY-.2,t.maxY+.2],GNt=(n,e,t,i,r,s=mQ)=>{let o=[...i].map(a=>t.get(a)).filter(a=>!!a);if(n==="x"){let a=[r.minX,...o.map(f=>f.maxX)].filter(f=>f<e.minX-s),c=[r.maxX,...o.map(f=>f.minX)].filter(f=>f>e.maxX+s),l=a.length>0?Math.max(...a):void 0,u=c.length>0?Math.min(...c):void 0,p=[];return l!==void 0&&p.push((l+e.minX)/2),u!==void 0&&p.push((e.maxX+u)/2),p}else{let a=[r.minY,...o.map(f=>f.maxY)].filter(f=>f<e.minY-s),c=[r.maxY,...o.map(f=>f.minY)].filter(f=>f>e.maxY+s),l=a.length>0?Math.max(...a):void 0,u=c.length>0?Math.min(...c):void 0,p=[];return l!==void 0&&p.push((l+e.minY)/2),u!==void 0&&p.push((e.maxY+u)/2),p}},HNt=1e-9,WNt=(n,e,t,i,r=HNt)=>{if(e<0||e>=n.length-1)return null;let s=n[e],o=n[e+1],a=Fa(s,o,r),c=ll(s,o,r);if(!a&&!c||a&&t!=="x"||c&&t!=="y")return null;let l=n.map(u=>({...u}));if(t==="x"){if(Math.abs(s.x-i)<r&&Math.abs(o.x-i)<r)return null;l[e]={...l[e],x:i},l[e+1]={...l[e+1],x:i}}else{if(Math.abs(s.y-i)<r&&Math.abs(o.y-i)<r)return null;l[e]={...l[e],y:i},l[e+1]={...l[e+1],y:i}}if(e-1>=0){let u=l[e-1],p=l[e];if(Math.abs(u.x-p.x)+Math.abs(u.y-p.y)<r)return null}if(e+2<=l.length-1){let u=l[e+1],p=l[e+2];if(Math.abs(u.x-p.x)+Math.abs(u.y-p.y)<r)return null}for(let u=0;u<l.length-1;u++){let p=l[u],f=l[u+1];if(!ll(p,f,r)&&!Fa(p,f,r))return null}return l},oQ=(n,e=6)=>n.map(i=>`${i.x.toFixed(e)},${i.y.toFixed(e)}`).join("|"),_Q=class extends kr{constructor(e){super();d(this,"pins");d(this,"inputProblem");d(this,"chipMap");d(this,"obstacles");d(this,"rectById");d(this,"aabb");d(this,"baseElbow");d(this,"solvedTracePath",null);d(this,"queue",[]);d(this,"visited",new Set);this.pins=e.pins,this.inputProblem=e.inputProblem,this.chipMap=e.chipMap;for(let r of this.pins)if(!r._facingDirection){let s=this.chipMap[r.chipId];r._facingDirection=x1(r,s)}this.obstacles=NS(this.inputProblem),this.rectById=new Map(this.obstacles.map(r=>[r.chipId,r]));let[t,i]=this.pins;this.baseElbow=Wc({x:t.x,y:t.y,facingDirection:t._facingDirection},{x:i.x,y:i.y,facingDirection:i._facingDirection},{overshoot:.2}),this.aabb=VNt({x:t.x,y:t.y},{x:i.x,y:i.y}),this.queue.push({path:this.baseElbow,collisionChipIds:new Set}),this.visited.add(oQ(this.baseElbow))}getConstructorParams(){return{chipMap:this.chipMap,pins:this.pins,inputProblem:this.inputProblem}}axisOfSegment(e,t){return Fa(e,t)?"x":ll(e,t)?"y":null}pathLength(e){let t=0;for(let i=0;i<e.length-1;i++)t+=Math.abs(e[i+1].x-e[i].x)+Math.abs(e[i+1].y-e[i].y);return t}_step(){if(this.solvedTracePath){this.solved=!0;return}let e=this.queue.shift();if(!e){this.failed=!0,this.error="No collision-free path found";return}let{path:t,collisionChipIds:i}=e,[r,s]=this.pins,o=XNt(t,this.obstacles);if(!o){let v=t[0],S=t[t.length-1],P=1e-9,T=(k,C)=>Math.abs(k.x-C.x)<P&&Math.abs(k.y-C.y)<P;T(v,{x:r.x,y:r.y})&&T(S,{x:s.x,y:s.y})&&(this.solvedTracePath=t,this.solved=!0);return}let{segIndex:a,rect:c}=o,l=a===0,u=a===t.length-2;if(l){if(t.length<3)return;a=1}else if(u){if(t.length<3)return;a=t.length-3}let p=t[a],f=t[a+1],y=this.axisOfSegment(p,f);if(!y)return;let g=[];if(i.size===0){let v=sQ(y,{x:r.x,y:r.y},c),S=sQ(y,{x:s.x,y:s.y},c),P=[...v,...S],T=[...new Set(P)];g.push(...T)}else{let v=GNt(y,c,this.rectById,i,this.aabb);g.push(...v)}let x=[];for(let v of g){let S=WNt(t,a,y,v);if(!S)continue;let P=oQ(S);if(this.visited.has(P))continue;this.visited.add(P);let T=new Set(i);T.add(c.chipId);let k=this.pathLength(S);x.push({path:S,collisionRectIds:T,len:k})}x.sort((v,S)=>v.len-S.len);for(let v of x)this.queue.push({path:v.path,collisionChipIds:v.collisionRectIds})}visualize(){let e=cs(this.inputProblem,{chipAlpha:.1,connectionAlpha:.1});e.lines.push({points:this.baseElbow,strokeColor:"red",strokeDash:"4 4"});let[t,i]=this.pins;e.lines.push({points:[{x:t.x,y:t.y},{x:i.x,y:i.y}],strokeColor:"blue",strokeDash:"5 5"});for(let{path:r,collisionChipIds:s}of this.queue)e.lines.push({points:r,strokeColor:"teal",strokeDash:"2 2"});return this.solvedTracePath?e.lines.push({points:this.solvedTracePath,strokeColor:"green"}):this.queue.length>0&&e.lines.push({points:this.queue[0].path,strokeColor:"orange"}),e}},qNt=class extends kr{constructor(e){super();d(this,"inputProblem");d(this,"mspConnectionPairs");d(this,"dcConnMap");d(this,"globalConnMap");d(this,"queuedConnectionPairs");d(this,"chipMap");d(this,"currentConnectionPair",null);d(this,"solvedTracePaths",[]);d(this,"failedConnectionPairs",[]);this.inputProblem=e.inputProblem,this.mspConnectionPairs=e.mspConnectionPairs,this.dcConnMap=e.dcConnMap,this.globalConnMap=e.globalConnMap,this.chipMap=e.chipMap,this.queuedConnectionPairs=[...this.mspConnectionPairs]}getConstructorParams(){return{inputProblem:this.inputProblem,chipMap:this.chipMap,mspConnectionPairs:this.mspConnectionPairs,dcConnMap:this.dcConnMap,globalConnMap:this.globalConnMap}}_step(){if(this.activeSubSolver?.solved&&(this.solvedTracePaths.push({...this.currentConnectionPair,tracePath:this.activeSubSolver.solvedTracePath,mspConnectionPairIds:[this.currentConnectionPair.mspPairId],pinIds:[this.currentConnectionPair.pins[0].pinId,this.currentConnectionPair.pins[1].pinId]}),this.activeSubSolver=null,this.currentConnectionPair=null),this.activeSubSolver?.failed&&(this.currentConnectionPair&&this.failedConnectionPairs.push({...this.currentConnectionPair,error:this.activeSubSolver.error||void 0}),this.activeSubSolver=null,this.currentConnectionPair=null),this.activeSubSolver){this.activeSubSolver.step();return}let e=this.queuedConnectionPairs.shift();if(!e){this.solved=!0;return}this.currentConnectionPair=e;let{pins:t}=e;this.activeSubSolver=new _Q({inputProblem:this.inputProblem,pins:t,chipMap:this.chipMap})}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let e=cs(this.inputProblem,{chipAlpha:.1,connectionAlpha:.1});for(let{mspPairId:t,tracePath:i}of this.solvedTracePaths)e.lines.push({points:i,strokeColor:"green"});for(let t of this.failedConnectionPairs)e.lines.push({points:[{x:t.pins[0].x,y:t.pins[0].y},{x:t.pins[1].x,y:t.pins[1].y}],strokeColor:"red",strokeDash:"4 2"});return e}},ZNt=({pts:n,segmentIndex:e,offset:t,JOG_SIZE:i,EPS:r=1e-6})=>{if(e!==0&&e!==n.length-2)return;let s=n[e],o=n[e+1],a=Math.abs(s.x-o.x)<r,c=Math.abs(s.y-o.y)<r;if(!a&&!c)return;let l=a?o.y>s.y?1:-1:o.x>s.x?1:-1;if(e===0)if(a){let u=s.y+l*i;n.splice(1,1,{x:s.x,y:u},{x:s.x+t,y:u},{x:o.x+t,y:o.y})}else{let u=s.x+l*i;n.splice(1,1,{x:u,y:s.y},{x:u,y:s.y+t},{x:o.x,y:o.y+t})}else if(a){let u=o.y-l*i;n.splice(e,1,{x:s.x+t,y:s.y},{x:o.x+t,y:u},{x:o.x,y:u})}else{let u=o.x-l*i;n.splice(e,1,{x:s.x,y:s.y+t},{x:u,y:o.y+t},{x:u,y:o.y})}},KNt=class extends kr{constructor(e){super();d(this,"overlappingTraceSegments");d(this,"traceNetIslands");d(this,"SHIFT_DISTANCE",.1);d(this,"correctedTraceMap",{});this.overlappingTraceSegments=e.overlappingTraceSegments,this.traceNetIslands=e.traceNetIslands;for(let{connNetId:t,pathsWithOverlap:i}of this.overlappingTraceSegments)for(let{solvedTracePathIndex:r,traceSegmentIndex:s}of i){let o=this.traceNetIslands[t][r].mspPairId;this.correctedTraceMap[o]=this.traceNetIslands[t][r]}}_step(){let t=this.overlappingTraceSegments.map((s,o)=>{let a=Math.floor(o/2)+1;return(o%2===0?-a:a)*this.SHIFT_DISTANCE}),i=(s,o)=>Math.abs(s-o)<1e-6,r=(s,o)=>!!s&&!!o&&i(s.x,o.x)&&i(s.y,o.y);this.overlappingTraceSegments.forEach((s,o)=>{let a=t[o],c=new Map;for(let l of s.pathsWithOverlap)c.has(l.solvedTracePathIndex)||c.set(l.solvedTracePathIndex,new Set),c.get(l.solvedTracePathIndex).add(l.traceSegmentIndex);for(let[l,u]of c){let p=this.traceNetIslands[s.connNetId][l],f=this.correctedTraceMap[p.mspPairId]??p,y=f.tracePath.map(P=>({...P})),g=Array.from(u).sort((P,T)=>P-T),x=Array.from(u).sort((P,T)=>P-T).reverse(),v=this.SHIFT_DISTANCE;for(let P of x)if(!(P<0||P>=y.length-1))if(P===0||P===y.length-2)ZNt({pts:y,segmentIndex:P,offset:a,JOG_SIZE:v,EPS:1e-6});else{let T=y[P],k=y[P+1],C=Math.abs(T.x-k.x)<1e-6,E=Math.abs(T.y-k.y)<1e-6;if(!C&&!E)continue;C?(T.x+=a,k.x+=a):(T.y+=a,k.y+=a)}let S=[];for(let P of y)(S.length===0||!r(S[S.length-1],P))&&S.push(P);this.correctedTraceMap[p.mspPairId]={...f,tracePath:S}}}),this.solved=!0}visualize(){let e={lines:[],points:[],rects:[],circles:[]};for(let t of this.overlappingTraceSegments)for(let{solvedTracePathIndex:i,traceSegmentIndex:r}of t.pathsWithOverlap){let s=this.traceNetIslands[t.connNetId][i],o=s.tracePath[r],a=s.tracePath[r+1];e.lines.push({points:[o,a],strokeColor:"red"})}for(let t of Object.values(this.correctedTraceMap))e.lines.push({points:t.tracePath,strokeColor:"blue",strokeDash:"4 2"});return e}},JNt=class extends kr{constructor(e){super();d(this,"inputProblem");d(this,"inputTracePaths");d(this,"globalConnMap");d(this,"traceNetIslands",{});d(this,"correctedTraceMap",{});d(this,"cleanupPhase",null);this.inputProblem=e.inputProblem,this.inputTracePaths=e.inputTracePaths,this.globalConnMap=e.globalConnMap;for(let t of this.inputTracePaths){let{mspPairId:i}=t;this.correctedTraceMap[i]=t}this.traceNetIslands=this.computeTraceNetIslands()}getConstructorParams(){return{inputProblem:this.inputProblem,inputTracePaths:this.inputTracePaths,globalConnMap:this.globalConnMap}}computeTraceNetIslands(){let e={};for(let t of this.inputTracePaths){let i=this.correctedTraceMap[t.mspPairId]??t,r=i.globalConnNetId;e[r]||(e[r]=[]),e[r].push(i)}return e}findNextOverlapIssue(){let t=Object.keys(this.traceNetIslands);for(let i=0;i<t.length;i++)for(let r=i+1;r<t.length;r++){let s=t[i],o=t[r],a=this.traceNetIslands[s]||[],c=this.traceNetIslands[o]||[],l=[],u=[],p=new Set,f=new Set,y=(g,x,v,S)=>{let P=Math.min(g,x),T=Math.max(g,x),k=Math.min(v,S),C=Math.max(v,S);return Math.min(T,C)-Math.max(P,k)>.002};for(let g=0;g<a.length;g++){let v=a[g].tracePath;for(let S=0;S<v.length-1;S++){let P=v[S],T=v[S+1],k=Math.abs(P.x-T.x)<.002,C=Math.abs(P.y-T.y)<.002;if(!(!k&&!C))for(let E=0;E<c.length;E++){let I=c[E].tracePath;for(let A=0;A<I.length-1;A++){let R=I[A],j=I[A+1],B=Math.abs(R.x-j.x)<.002,G=Math.abs(R.y-j.y)<.002;if(!(!B&&!G)){if(k&&B){if(Math.abs(P.x-R.x)<.002&&y(P.y,T.y,R.y,j.y)){let U=`${g}:${S}`,H=`${E}:${A}`;p.has(U)||(l.push({solvedTracePathIndex:g,traceSegmentIndex:S}),p.add(U)),f.has(H)||(u.push({solvedTracePathIndex:E,traceSegmentIndex:A}),f.add(H))}}else if(C&&G&&Math.abs(P.y-R.y)<.002&&y(P.x,T.x,R.x,j.x)){let U=`${g}:${S}`,H=`${E}:${A}`;p.has(U)||(l.push({solvedTracePathIndex:g,traceSegmentIndex:S}),p.add(U)),f.has(H)||(u.push({solvedTracePathIndex:E,traceSegmentIndex:A}),f.add(H))}}}}}}if(l.length>0&&u.length>0)return{overlappingTraceSegments:[{connNetId:s,pathsWithOverlap:l},{connNetId:o,pathsWithOverlap:u}]}}return null}findNextDiagonalSegment(){for(let t in this.correctedTraceMap){let i=this.correctedTraceMap[t].tracePath;for(let r=0;r<i.length-1;r++){let s=i[r],o=i[r+1],a=Math.abs(s.y-o.y)<.002,c=Math.abs(s.x-o.x)<.002;if(!a&&!c)return{mspPairId:t,tracePath:i,i:r,p1:s,p2:o}}}return null}findAndFixNextDiagonalSegment(){let e=this.findNextDiagonalSegment();if(!e)return!1;let{mspPairId:t,tracePath:i,i:r,p1:s,p2:o}=e,a=.002,c=r>0?i[r-1]:null,l=r+2<i.length?i[r+2]:null,u=c?Math.abs(c.x-s.x)<a:!1,p=c?Math.abs(c.y-s.y)<a:!1,f=l?Math.abs(o.x-l.x)<a:!1,y=l?Math.abs(o.y-l.y)<a:!1,g={x:s.x,y:o.y},x={x:o.x,y:s.y},v=0;u&&v++,y&&v++;let S=0;p&&S++,f&&S++;let P=v<S?g:x;return i.splice(r+1,0,P),!0}_step(){if(this.activeSubSolver?.solved){for(let[i,r]of Object.entries(this.activeSubSolver.correctedTraceMap))this.correctedTraceMap[i]=r;this.activeSubSolver=null,this.traceNetIslands=this.computeTraceNetIslands()}if(this.activeSubSolver){this.activeSubSolver.step();return}let e=this.findNextOverlapIssue();if(e===null){if(this.cleanupPhase===null&&(this.cleanupPhase="diagonals"),this.cleanupPhase==="diagonals"){this.findAndFixNextDiagonalSegment()||(this.cleanupPhase="done",this.solved=!0);return}this.solved=!0;return}let{overlappingTraceSegments:t}=e;this.activeSubSolver=new KNt({overlappingTraceSegments:t,traceNetIslands:this.traceNetIslands})}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let e=cs(this.inputProblem);e.circles=e.circles||[];for(let t of Object.values(this.correctedTraceMap))e.lines.push({points:t.tracePath,strokeColor:"purple"});if(this.cleanupPhase==="diagonals"){let t=this.findNextDiagonalSegment();t&&e.lines.push({points:[t.p1,t.p2],strokeColor:"red",strokeWidth:.05})}return e}},QNt=class{constructor(n){d(this,"chips");d(this,"spatialIndex");d(this,"spatialIndexIdToChip");this.chips=n.map(e=>({...e,bounds:_A(e),spatialIndexId:null})),this.spatialIndexIdToChip=new Map,this.spatialIndex=new g1(n.length);for(let e of this.chips)e.spatialIndexId=this.spatialIndex.add(e.bounds.minX,e.bounds.minY,e.bounds.maxX,e.bounds.maxY),this.spatialIndexIdToChip.set(e.spatialIndexId,e);this.spatialIndex.finish()}getChipsInBounds(n){return this.spatialIndex.search(n.minX,n.minY,n.maxX,n.maxY).map(t=>this.spatialIndexIdToChip.get(t))}doesOrthogonalLineIntersectChip(n,e={}){let t=e.excludeChipIds??[],[i,r]=n,{x:s,y:o}=i,{x:a,y:c}=r;return this.getChipsInBounds({minX:Math.min(s,a),minY:Math.min(o,c),maxX:Math.max(s,a),maxY:Math.max(o,c)}).filter(u=>!t.includes(u.chipId)).length>0}},tAt=.45,aQ=.2;function dA(n){let{orientation:e,netLabelWidth:t}=n,i=typeof t=="number"?t:tAt;return e==="y+"||e==="y-"?{width:aQ,height:i}:{width:i,height:aQ}}function fA(n,e,t,i){switch(e){case"x+":return{x:n.x+t/2,y:n.y};case"x-":return{x:n.x-t/2,y:n.y};case"y+":return{x:n.x,y:n.y+i/2};case"y-":return{x:n.x,y:n.y-i/2}}}function Pd(n,e,t){return{minX:n.x-e/2,minY:n.y-t/2,maxX:n.x+e/2,maxY:n.y+t/2}}function yQ(n,e,t,i=1e-9){let r=Math.abs(n.x-e.x)<i,s=Math.abs(n.y-e.y)<i;if(!r&&!s)return!1;if(r){let o=n.x;if(o<t.minX-i||o>t.maxX+i)return!1;let a=Math.min(n.y,e.y),c=Math.max(n.y,e.y);return Math.min(c,t.maxY)-Math.max(a,t.minY)>i}else{let o=n.y;if(o<t.minY-i||o>t.maxY+i)return!1;let a=Math.min(n.x,e.x),c=Math.max(n.x,e.x);return Math.min(c,t.maxX)-Math.max(a,t.minX)>i}}function gQ(n,e,t,i){for(let[r,s]of Object.entries(e)){let o=s.tracePath;for(let a=0;a<o.length-1;a++)if(!(r===t&&a===i)&&yQ(o[a],o[a+1],n))return{hasIntersection:!0,mspPairId:r,segIndex:a}}return{hasIntersection:!1}}function cQ(n){let e=0,t=n.tracePath;for(let i=0;i<t.length-1;i++)e+=Math.abs(t[i+1].x-t[i].x)+Math.abs(t[i+1].y-t[i].y);return e}function xQ(n){let{inputProblem:e,inputTraceMap:t,globalConnNetId:i,fallbackTrace:r,mspConnectionPairIds:s}=n,o=Object.fromEntries(e.chips.map(f=>[f.chipId,f])),a=Object.values(t).filter(f=>f.globalConnNetId===i);if(s&&s.length>0){let f=new Set(s);a=a.filter(y=>y.mspConnectionPairIds.some(g=>f.has(g)))}let c=new Set;for(let f of a)c.add(f.pins[0].chipId),c.add(f.pins[1].chipId);let l=null,u=-1;for(let f of c){let g=o[f]?.pins?.length??0;g>u&&(u=g,l=f)}let p=l==null?[]:a.filter(f=>f.pins[0].chipId===l||f.pins[1].chipId===l);return p.length>0?p.reduce((f,y)=>cQ(f)>=cQ(y)?f:y):r}function eAt(n,e){return[{x:n.x,y:n.y},{x:(n.x+e.x)/2,y:(n.y+e.y)/2},{x:e.x,y:e.y}]}function nAt(n){let{inputProblem:e,inputTraceMap:t,chipObstacleSpatialIndex:i,overlappingSameNetTraceGroup:r,availableOrientations:s,netLabelWidth:o}=n,a=r.portOnlyPinId;if(!a)return{placement:null,testedCandidates:[],error:"No portOnlyPinId provided"};let c=null,l=null;for(let E of e.chips){let N=E.pins.find(I=>I.pinId===a);if(N){c={x:N.x,y:N.y},l=N._facingDirection||x1(N,E);break}}if(!c||!l)return{placement:null,testedCandidates:[],error:`Port-only pin not found: ${a}`};let u=s.length>0?s:["x+","x-","y+","y-"],p={x:c.x,y:c.y},f=E=>E==="x+"?{x:1,y:0}:E==="x-"?{x:-1,y:0}:E==="y+"?{x:0,y:1}:{x:0,y:-1},y=[];for(let E of u){let{width:N,height:I}=dA({orientation:E,netLabelWidth:o}),A=fA(p,E,N,I),R=f(E),j=.001,B={x:A.x+R.x*j,y:A.y+R.y*j},G=Pd(B,N,I);if(i.getChipsInBounds(G).length>0){y.push({center:B,width:N,height:I,bounds:G,anchor:p,orientation:E,status:"chip-collision",hostSegIndex:-1});continue}if(gQ(G,t,"",-1).hasIntersection){y.push({center:B,width:N,height:I,bounds:G,anchor:p,orientation:E,status:"trace-collision",hostSegIndex:-1});continue}return y.push({center:B,width:N,height:I,bounds:G,anchor:p,orientation:E,status:"ok",hostSegIndex:-1}),{placement:{globalConnNetId:r.globalConnNetId,dcConnNetId:void 0,netId:r.netId,mspConnectionPairIds:[],pinIds:[a],orientation:E,anchorPoint:p,width:N,height:I,center:B},testedCandidates:y}}let g=l,{width:x,height:v}=dA({orientation:g,netLabelWidth:o}),S=fA(p,g,x,v),P=f(g),T=.001,k={x:S.x+P.x*T,y:S.y+P.y*T};return{placement:{globalConnNetId:r.globalConnNetId,dcConnNetId:void 0,netId:r.netId,mspConnectionPairIds:[],pinIds:[a],orientation:g,anchorPoint:p,width:x,height:v,center:k},testedCandidates:y}}function iAt(n){let e=cs(n.inputProblem),t=n.overlappingSameNetTraceGroup.globalConnNetId,i=xQ({inputProblem:n.inputProblem,inputTraceMap:n.inputTraceMap,globalConnNetId:t,fallbackTrace:n.overlappingSameNetTraceGroup.overlappingTraces}),r=Rs(t,.9),s=Rs(t,.5);for(let o of Object.values(n.inputTraceMap)){let a=i?o.mspPairId===i.mspPairId:!1;e.lines.push({points:o.tracePath})}for(let o of n.testedCandidates){let a=o.status==="ok"?"rgba(0, 180, 0, 0.25)":o.status==="chip-collision"?"rgba(220, 0, 0, 0.25)":o.status==="trace-collision"?"rgba(220, 140, 0, 0.25)":"rgba(120, 120, 120, 0.15)",c=o.status==="ok"?"green":o.status==="chip-collision"?"red":o.status==="trace-collision"?"orange":"gray";e.rects.push({center:{x:(o.bounds.minX+o.bounds.maxX)/2,y:(o.bounds.minY+o.bounds.maxY)/2},width:o.width,height:o.height,fill:a,strokeColor:c}),e.points.push({x:o.anchor.x,y:o.anchor.y,color:c})}if(n.netLabelPlacement){let o=n.netLabelPlacement;e.rects.push({center:o.center,width:o.width,height:o.height,fill:"rgba(0, 128, 255, 0.35)",strokeColor:"blue"}),e.points.push({x:o.anchorPoint.x,y:o.anchorPoint.y,color:"blue"})}return e}var lQ=class extends kr{constructor(e){super();d(this,"inputProblem");d(this,"inputTraceMap");d(this,"overlappingSameNetTraceGroup");d(this,"availableOrientations");d(this,"chipObstacleSpatialIndex");d(this,"netLabelWidth");d(this,"netLabelPlacement",null);d(this,"testedCandidates",[]);this.inputProblem=e.inputProblem,this.inputTraceMap=e.inputTraceMap,this.overlappingSameNetTraceGroup=e.overlappingSameNetTraceGroup,this.availableOrientations=e.availableOrientations,this.netLabelWidth=e.netLabelWidth,this.chipObstacleSpatialIndex=e.inputProblem._chipObstacleSpatialIndex??new QNt(e.inputProblem.chips)}getConstructorParams(){return{inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,overlappingSameNetTraceGroup:this.overlappingSameNetTraceGroup,availableOrientations:this.availableOrientations,netLabelWidth:this.netLabelWidth}}_step(){if(this.netLabelPlacement){this.solved=!0;return}if(this.overlappingSameNetTraceGroup.portOnlyPinId){let f=nAt({inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,chipObstacleSpatialIndex:this.chipObstacleSpatialIndex,overlappingSameNetTraceGroup:this.overlappingSameNetTraceGroup,availableOrientations:this.availableOrientations,netLabelWidth:this.netLabelWidth});if(this.testedCandidates.push(...f.testedCandidates),f.placement){this.netLabelPlacement=f.placement,this.solved=!0;return}this.failed=!0,this.error=f.error??"Could not place net label at port without collisions";return}let e=this.overlappingSameNetTraceGroup.globalConnNetId,t=xQ({inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,globalConnNetId:e,fallbackTrace:this.overlappingSameNetTraceGroup.overlappingTraces,mspConnectionPairIds:this.overlappingSameNetTraceGroup.mspConnectionPairIds});if(!t){this.failed=!0,this.error="No host trace found for net label placement";return}let i=new Set(this.overlappingSameNetTraceGroup.mspConnectionPairIds??[]),r=Object.values(this.inputTraceMap).filter(f=>f.globalConnNetId===e&&(i.size===0||f.mspConnectionPairIds.some(y=>i.has(y)))),s=this.availableOrientations.length===1?[t,...r.filter(f=>f.mspPairId!==t.mspPairId)]:[t],o=this.availableOrientations.length>0?this.availableOrientations:["x+","x-","y+","y-"],a=this.availableOrientations.length===1,c=(f,y)=>{switch(f){case"y+":return y.y;case"y-":return-y.y;case"x+":return y.x;case"x-":return-y.x}},l=null,u=-1/0,p=1e-6;for(let f of s){let y=f.tracePath.slice();for(let g=0;g<y.length-1;g++){let x=y[g],v=y[g+1],S=Math.abs(x.y-v.y)<p,P=Math.abs(x.x-v.x)<p;if(!S&&!P)continue;let T=S?["y+","y-"]:["x+","x-"],k=o.filter(E=>T.includes(E));if(k.length===0)continue;let C=eAt(x,v);for(let E of C)for(let N of k){let{width:I,height:A}=dA({orientation:N,netLabelWidth:this.netLabelWidth}),R=fA(E,N,I,A),j=N==="x+"?{x:1,y:0}:N==="x-"?{x:-1,y:0}:N==="y+"?{x:0,y:1}:{x:0,y:-1},B=1e-4,G={x:R.x+j.x*B,y:R.y+j.y*B},U=Pd(G,I,A);if(this.chipObstacleSpatialIndex.getChipsInBounds(U).length>0){this.testedCandidates.push({center:G,width:I,height:A,bounds:U,anchor:E,orientation:N,status:"chip-collision",hostSegIndex:g});continue}if(gQ(U,this.inputTraceMap,f.mspPairId,g).hasIntersection){this.testedCandidates.push({center:G,width:I,height:A,bounds:U,anchor:E,orientation:N,status:"trace-collision",hostSegIndex:g});continue}if(this.testedCandidates.push({center:G,width:I,height:A,bounds:U,anchor:E,orientation:N,status:"ok",hostSegIndex:g}),a){let tt=c(N,E);tt>u+1e-9&&(u=tt,l={anchor:E,orientation:N,width:I,height:A,center:R,hostSegIndex:g,dcConnNetId:f.dcConnNetId,mspPairId:f.mspPairId,pinIds:[f.pins[0].pinId,f.pins[1].pinId]});continue}this.netLabelPlacement={globalConnNetId:this.overlappingSameNetTraceGroup.globalConnNetId,dcConnNetId:f.dcConnNetId,netId:this.overlappingSameNetTraceGroup.netId,mspConnectionPairIds:[f.mspPairId],pinIds:[f.pins[0].pinId,f.pins[1].pinId],orientation:N,anchorPoint:E,width:I,height:A,center:R},this.solved=!0;return}}}if(a&&l){this.netLabelPlacement={globalConnNetId:this.overlappingSameNetTraceGroup.globalConnNetId,dcConnNetId:l.dcConnNetId,netId:this.overlappingSameNetTraceGroup.netId,mspConnectionPairIds:[l.mspPairId],pinIds:l.pinIds,orientation:l.orientation,anchorPoint:l.anchor,width:l.width,height:l.height,center:l.center},this.solved=!0;return}this.failed=!0,this.error="Could not place net label without collisions"}visualize(){return iAt(this)}},uQ=class extends kr{constructor(e){super();d(this,"inputProblem");d(this,"inputTraceMap");d(this,"overlappingSameNetTraceGroups");d(this,"queuedOverlappingSameNetTraceGroups");d(this,"netLabelPlacements",[]);d(this,"currentGroup",null);d(this,"triedAnyOrientationFallbackForCurrentGroup",!1);this.inputProblem=e.inputProblem,this.inputTraceMap=e.inputTraceMap,this.overlappingSameNetTraceGroups=this.computeOverlappingSameNetTraceGroups(),this.queuedOverlappingSameNetTraceGroups=[...this.overlappingSameNetTraceGroups]}computeOverlappingSameNetTraceGroups(){let e={};for(let c of Object.values(this.inputTraceMap)){let l=c.globalConnNetId;e[l]||(e[l]=[]),e[l].push(c)}let{netConnMap:t}=mA(this.inputProblem),i=new Map;for(let c of this.inputProblem.chips)for(let l of c.pins)i.set(l.pinId,l);let r={};for(let c of this.inputProblem.directConnections)if(c.netId){let[l,u]=c.pinIds;r[l]=c.netId,r[u]=c.netId}for(let c of this.inputProblem.netConnections)for(let l of c.pinIds)r[l]=c.netId;let s=[],o=this.inputProblem.chips.flatMap(c=>c.pins.map(l=>l.pinId)),a=new Set;for(let c of o){let l=t.getNetConnectedToId(c);l&&a.add(l)}for(let c of a){let u=t.getIdsConnectedToNet(c).filter(y=>i.has(y)),p={};for(let y of u)p[y]=new Set;for(let y of e[c]??[]){let g=y.pins[0].pinId,x=y.pins[1].pinId;p[g]&&p[x]&&(p[g].add(x),p[x].add(g))}let f=new Set;for(let y of u){if(f.has(y))continue;let g=[y],x=new Set;for(f.add(y);g.length>0;){let S=g.pop();x.add(S);for(let P of p[S]??[])f.has(P)||(f.add(P),g.push(P))}let v=(e[c]??[]).filter(S=>x.has(S.pins[0].pinId)&&x.has(S.pins[1].pinId));if(v.length>0){let S=N=>{let I=0,A=N.tracePath;for(let R=0;R<A.length-1;R++)I+=Math.abs(A[R+1].x-A[R].x)+Math.abs(A[R+1].y-A[R].y);return I},P=v[0],T=S(P);for(let N=1;N<v.length;N++){let I=S(v[N]);I>T&&(P=v[N],T=I)}let k=v.find(N=>N.userNetId!=null)?.userNetId;if(!k){for(let N of x)if(r[N]){k=r[N];break}}let C=Array.from(new Set(v.flatMap(N=>N.mspConnectionPairIds??[N.mspPairId]))),E={globalConnNetId:c,netId:k,overlappingTraces:P,mspConnectionPairIds:C};s.push(E)}else for(let S of x){let P=r[S];P&&s.push({globalConnNetId:c,netId:P,portOnlyPinId:S})}}}return s}_step(){if(this.activeSubSolver?.solved){this.netLabelPlacements.push(this.activeSubSolver.netLabelPlacement),this.activeSubSolver=null,this.currentGroup=null,this.triedAnyOrientationFallbackForCurrentGroup=!1;return}if(this.activeSubSolver?.failed){let r=["x+","x-","y+","y-"],s=this.activeSubSolver.availableOrientations,o=s.length===4&&r.every(a=>s.includes(a));if(!this.triedAnyOrientationFallbackForCurrentGroup&&!o&&this.currentGroup){this.triedAnyOrientationFallbackForCurrentGroup=!0;let a=this.currentGroup.netId?this.inputProblem.netConnections.find(c=>c.netId===this.currentGroup.netId)?.netLabelWidth:void 0;this.activeSubSolver=new lQ({inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,overlappingSameNetTraceGroup:this.currentGroup,availableOrientations:r,netLabelWidth:a});return}this.failed=!0,this.error=this.activeSubSolver.error;return}if(this.activeSubSolver){this.activeSubSolver.step();return}let e=this.queuedOverlappingSameNetTraceGroups.shift();if(!e){this.solved=!0;return}let t=e.netId??e.globalConnNetId;this.currentGroup=e,this.triedAnyOrientationFallbackForCurrentGroup=!1;let i=this.currentGroup.netId?this.inputProblem.netConnections.find(r=>r.netId===this.currentGroup.netId)?.netLabelWidth:void 0;this.activeSubSolver=new lQ({inputProblem:this.inputProblem,inputTraceMap:this.inputTraceMap,overlappingSameNetTraceGroup:e,availableOrientations:this.inputProblem.availableNetLabelOrientations[t]??["x+","x-","y+","y-"],netLabelWidth:i})}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let e=cs(this.inputProblem);for(let t of Object.values(this.inputTraceMap))e.lines.push({points:t.tracePath,strokeColor:"purple"});for(let t of this.netLabelPlacements)e.rects.push({center:t.center,width:t.width,height:t.height,fill:Rs(t.globalConnNetId,.35),strokeColor:Rs(t.globalConnNetId,.9)}),e.points.push({x:t.anchorPoint.x,y:t.anchorPoint.y,color:Rs(t.globalConnNetId,.9)});return e}},rAt=class extends kr{constructor(e){super();d(this,"input");d(this,"output");d(this,"inputProblem");d(this,"traces");this.input=e,this.inputProblem=e.inputProblem,this.traces=e.traces,this.output={netLabelPlacements:e.netLabelPlacements,mergedLabelNetIdMap:{}}}_step(){let e=this.input.netLabelPlacements,t={};if(!e||e.length===0){this.output={netLabelPlacements:[],mergedLabelNetIdMap:{}},this.solved=!0;return}let i={};for(let s of e){if(s.pinIds.length===0)continue;let o=s.pinIds[0].split(".")[0];if(!o)continue;let a=`${o}-${s.orientation}`;a in i||(i[a]=[]),i[a].push(s)}let r=[];for(let[s,o]of Object.entries(i)){if(o.length<=1){r.push(...o);continue}let a=1/0,c=1/0,l=-1/0,u=-1/0;for(let v of o){let S=Pd(v.center,v.width,v.height);a=Math.min(a,S.minX),c=Math.min(c,S.minY),l=Math.max(l,S.maxX),u=Math.max(u,S.maxY)}let p=l-a,f=u-c,y=o[0],g=`merged-group-${s}`,x=new Set(o.map(v=>v.globalConnNetId));t[g]=x,r.push({...y,globalConnNetId:g,width:p,height:f,center:{x:a+p/2,y:c+f/2},pinIds:[...new Set(o.flatMap(v=>v.pinIds))],mspConnectionPairIds:[...new Set(o.flatMap(v=>v.mspConnectionPairIds))]})}this.output={netLabelPlacements:r,mergedLabelNetIdMap:t},this.solved=!0}getOutput(){return this.output}visualize(){let e=cs(this.inputProblem,{chipAlpha:.1,connectionAlpha:.1});e.rects||(e.rects=[]),e.lines||(e.lines=[]),e.points||(e.points=[]),e.texts||(e.texts=[]);let t=new Map;for(let i of this.input.netLabelPlacements)t.set(i.globalConnNetId,i);for(let i of this.traces){let r={points:i.tracePath.map(s=>({x:s.x,y:s.y})),strokeColor:"blue"};e.lines.push(r)}for(let i of this.output.netLabelPlacements){let r=i.globalConnNetId.startsWith("merged-group-"),s=Rs(i.globalConnNetId);if(r){e.rects.push({center:i.center,width:i.width,height:i.height,fill:s.replace(/, 1\)/,", 0.2)"),stroke:s,label:i.globalConnNetId});let o=this.output.mergedLabelNetIdMap[i.globalConnNetId];if(o)for(let a of o){let c=t.get(a);if(c){let l=Pd(c.center,c.width,c.height),u={x:l.minX,y:l.minY},p={x:l.maxX,y:l.minY},f={x:l.maxX,y:l.maxY},y={x:l.minX,y:l.maxY};e.lines.push({points:[u,p,f,y,u],strokeColor:s,strokeDash:"4 4"}),e.lines.push({points:[c.center,i.center],strokeColor:s,strokeDash:"2 2"})}}}else e.rects.push({center:i.center,width:i.width,height:i.height,stroke:s,label:i.globalConnNetId})}return e}},sAt=(n,e)=>{let t=[];for(let i of n)for(let r of e){let s=Pd(r.center,r.width,r.height);for(let o=0;o<i.tracePath.length-1;o++){let a=i.tracePath[o],c=i.tracePath[o+1];if(yQ(a,c,s)){if(i.globalConnNetId===r.globalConnNetId)break;t.push({trace:i,label:r});break}}}return t},oAt=(n,e)=>{let t=s=>s.x>e.minX&&s.x<e.maxX&&s.y>e.minY&&s.y<e.maxY,i=-1,r=-1;for(let s=0;s<n.length;s++)t(n[s])&&(i===-1&&(i=s),r=s);return{firstInsideIndex:i,lastInsideIndex:r}},aAt=({initialTrace:n,firstInsideIndex:e,lastInsideIndex:t,labelBounds:i,paddingBuffer:r,detourCount:s})=>{if(e<=0||t>=n.tracePath.length-1)return[];let o=n.tracePath[e-1],a=n.tracePath[t+1],c=n.tracePath.slice(0,e),l=n.tracePath.slice(t+1),u=[];o.x!==a.x&&o.y!==a.y?(u.push([{x:a.x,y:o.y}]),u.push([{x:o.x,y:a.y}])):(o.x===a.x||o.y===a.y)&&u.push([]);let p=r+s*r,f=i.minX-p,y=i.maxX+p,g=i.maxY+p,x=i.minY-p;return(o.x<=i.minX||a.x<=i.minX)&&o.x<i.maxX&&a.x<i.maxX&&u.push([{x:f,y:o.y},{x:f,y:a.y}]),(o.x>=i.maxX||a.x>=i.maxX)&&o.x>i.minX&&a.x>i.minX&&u.push([{x:y,y:o.y},{x:y,y:a.y}]),(o.y>=i.maxY||a.y>=i.maxY)&&o.y>i.minY&&a.y>i.minY&&u.push([{x:o.x,y:g},{x:a.x,y:g}]),(o.y<=i.minY||a.y<=i.minY)&&o.y<i.maxY&&a.y<i.maxY&&u.push([{x:o.x,y:x},{x:a.x,y:x}]),u.map(v=>[...c,...v,...l])},cAt=({initialTrace:n,label:e,labelBounds:t,paddingBuffer:i,detourCount:r})=>{let s=-1;for(let p=0;p<n.tracePath.length-1;p++)if(v1(n.tracePath[p],n.tracePath[p+1],t)){s=p;break}if(s===-1)return[];let o=n.tracePath[s],a=n.tracePath[s+1];if(!o||!a)return[];let c=[],l=Pd(e.center,e.width,e.height),u=i+r*i;if(Fa(o,a)){let p=[l.maxX+u,l.minX-u];for(let f of p)c.push(a.y>o.y?[{x:o.x,y:l.minY-u},{x:f,y:l.minY-u},{x:f,y:l.maxY+u},{x:a.x,y:l.maxY+u}]:[{x:o.x,y:l.maxY+u},{x:f,y:l.maxY+u},{x:f,y:l.minY-u},{x:a.x,y:l.minY-u}])}else{let p=[l.maxY+u,l.minY-u];for(let f of p)c.push(a.x>o.x?[{x:l.minX-u,y:o.y},{x:l.minX-u,y:f},{x:l.maxX+u,y:f},{x:l.maxX+u,y:a.y}]:[{x:l.maxX+u,y:o.y},{x:l.maxX+u,y:f},{x:l.minX-u,y:f},{x:l.minX-u,y:a.y}])}return c.map(p=>[...n.tracePath.slice(0,s+1),...p,...n.tracePath.slice(s+1)])},b1=n=>{if(n.length<3)return n;let e=[n[0]];for(let i=1;i<n.length-1;i++){let r=e[e.length-1],s=n[i],o=n[i+1];Fa(r,s)&&Fa(s,o)||ll(r,s)&&ll(s,o)||e.push(s)}if(e.push(n[n.length-1]),e.length<3)return e;let t=[e[0]];for(let i=1;i<e.length-1;i++){let r=t[t.length-1],s=e[i],o=e[i+1];Fa(r,s)&&Fa(s,o)||ll(r,s)&&ll(s,o)||t.push(s)}return t.push(e[e.length-1]),t},lAt=({trace:n,label:e,paddingBuffer:t,detourCount:i})=>{let r={...n,tracePath:b1(n.tracePath)};if(n.globalConnNetId===e.globalConnNetId)return[r.tracePath];let s=t,o=Pd(e.center,e.width,e.height),a={minX:o.minX-s,minY:o.minY-s,maxX:o.maxX+s,maxY:o.maxY+s,chipId:`netlabel-${e.netId}`},c=cAt({initialTrace:r,label:e,labelBounds:a,paddingBuffer:t,detourCount:i}),{firstInsideIndex:l,lastInsideIndex:u}=oAt(r.tracePath,a),p=aAt({initialTrace:r,firstInsideIndex:l,lastInsideIndex:u,labelBounds:a,paddingBuffer:t,detourCount:i});return[...c,...p]},uAt=class extends kr{constructor(e){super();d(this,"queuedCandidatePaths");d(this,"solvedTracePath",null);d(this,"initialTrace");d(this,"problem");d(this,"obstacles");d(this,"label");this.initialTrace=e.trace,this.problem=e.problem,this.label=e.label;let t=lAt({...e}),i=r=>{let s=0;for(let o=0;o<r.length-1;o++){let a=r[o+1].x-r[o].x,c=r[o+1].y-r[o].y;s+=Math.sqrt(a*a+c*c)}return s};this.queuedCandidatePaths=t.sort((r,s)=>i(r)-i(s)),this.obstacles=NS(this.problem)}_step(){if(this.queuedCandidatePaths.length===0){this.failed=!0;return}let e=this.queuedCandidatePaths.shift(),t=b1(e);UNt(t,this.obstacles)||(this.solvedTracePath=t,this.solved=!0)}visualize(){let e=cs(this.problem,{chipAlpha:.1,connectionAlpha:.1});return e.lines||(e.lines=[]),e.rects||(e.rects=[]),e.lines.push({points:this.initialTrace.tracePath,strokeColor:"red",strokeDash:"4 4"}),e.rects.push({center:this.label.center,width:this.label.width,height:this.label.height,fill:"rgba(255, 0, 0, 0.2)"}),this.queuedCandidatePaths.length>0&&e.lines.push({points:this.queuedCandidatePaths[0],strokeColor:"orange"}),this.solvedTracePath&&e.lines.push({points:this.solvedTracePath,strokeColor:"green"}),e}},pAt=class extends kr{constructor(e){super();d(this,"inputProblem");d(this,"netLabelPlacements");d(this,"mergedLabelNetIdMap");d(this,"allTraces");d(this,"modifiedTraces",[]);d(this,"detourCountByLabel",{});d(this,"PADDING_BUFFER",.1);d(this,"activeSubSolver",null);d(this,"overlapQueue",[]);d(this,"recentlyFailed",new Set);this.inputProblem=e.inputProblem,this.netLabelPlacements=e.netLabelPlacements,this.mergedLabelNetIdMap=e.mergedLabelNetIdMap,this.allTraces=[...e.traces]}_step(){if(this.activeSubSolver){if(this.activeSubSolver.step(),this.activeSubSolver.solved){let r=this.activeSubSolver.solvedTracePath;if(r){let s=this.allTraces.findIndex(o=>o.mspPairId===this.activeSubSolver.initialTrace.mspPairId);s!==-1&&(this.allTraces[s].tracePath=r,this.modifiedTraces.push(this.allTraces[s]))}this.activeSubSolver=null,this.recentlyFailed.clear()}else if(this.activeSubSolver.failed){let r=`${this.activeSubSolver.initialTrace.mspPairId}-${this.activeSubSolver.label.globalConnNetId}`;this.recentlyFailed.add(r),this.activeSubSolver=null}return}let e=sAt(this.allTraces,this.netLabelPlacements).filter(r=>{let s=this.mergedLabelNetIdMap[r.label.globalConnNetId];return s?!s.has(r.trace.globalConnNetId):r.trace.globalConnNetId!==r.label.globalConnNetId});if(e.length===0){this.solved=!0;return}let t=e.filter(r=>{let s=`${r.trace.mspPairId}-${r.label.globalConnNetId}`;return!this.recentlyFailed.has(s)});if(t.length===0){this.solved=!0;return}this.overlapQueue=t;let i=this.overlapQueue.shift();if(i){let r=this.allTraces.find(s=>s.mspPairId===i.trace.mspPairId);if(r){let s=i.label.globalConnNetId,o=this.detourCountByLabel[s]||0;this.detourCountByLabel[s]=o+1,this.activeSubSolver=new uAt({trace:r,label:i.label,problem:this.inputProblem,paddingBuffer:this.PADDING_BUFFER,detourCount:o})}}}getOutput(){return{allTraces:this.allTraces,modifiedTraces:this.modifiedTraces}}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let e=cs(this.inputProblem);e.lines||(e.lines=[]);for(let t of this.allTraces)e.lines.push({points:t.tracePath,strokeColor:"purple"});return e}},hAt=class extends kr{constructor(e){super();d(this,"inputProblem");d(this,"traces");d(this,"netLabelPlacements");d(this,"labelMergingSolver");d(this,"overlapAvoidanceSolver");d(this,"pipelineStepIndex",0);this.inputProblem=e.inputProblem,this.traces=e.traces,this.netLabelPlacements=e.netLabelPlacements}_step(){if(this.activeSubSolver){this.activeSubSolver.step(),this.activeSubSolver.solved?(this.activeSubSolver=null,this.pipelineStepIndex++):this.activeSubSolver.failed&&(this.failed=!0,this.activeSubSolver=null);return}switch(this.pipelineStepIndex){case 0:this.labelMergingSolver=new rAt({netLabelPlacements:this.netLabelPlacements,inputProblem:this.inputProblem,traces:this.traces}),this.activeSubSolver=this.labelMergingSolver;break;case 1:this.overlapAvoidanceSolver=new pAt({inputProblem:this.inputProblem,traces:this.traces,netLabelPlacements:this.labelMergingSolver.getOutput().netLabelPlacements,mergedLabelNetIdMap:this.labelMergingSolver.getOutput().mergedLabelNetIdMap}),this.activeSubSolver=this.overlapAvoidanceSolver;break;default:this.solved=!0;break}}getOutput(){return{traces:this.overlapAvoidanceSolver?.getOutput().allTraces??this.traces,netLabelPlacements:this.labelMergingSolver?.getOutput().netLabelPlacements??this.netLabelPlacements}}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let e=cs(this.inputProblem);e.lines||(e.lines=[]),e.rects||(e.rects=[]);let t=this.getOutput();for(let i of t.traces)e.lines.push({points:i.tracePath,strokeColor:"purple"});for(let i of t.netLabelPlacements){let r=Rs(i.globalConnNetId,.3);e.rects.push({center:i.center,width:i.width,height:i.height,fill:r,stroke:r.replace("0.3","1"),label:i.globalConnNetId})}return e}},dAt=n=>{for(let e of n.chips){let t=_A(e);for(let i of e.pins){if(!(i.x>t.minX&&i.x<t.maxX&&i.y>t.minY&&i.y<t.maxY))continue;let s=i.x-t.minX,o=t.maxX-i.x,a=i.y-t.minY,c=t.maxY-i.y,l=Math.min(s,o,a,c);l===s?i.x=t.minX:l===o?i.x=t.maxX:l===a?i.y=t.minY:i.y=t.maxY,i._facingDirection=void 0}}},fAt=n=>{for(let e of n.chips){let t=e.width/2,i=e.height/2,r=0,s=0;for(let c of e.pins){let l=Math.abs(c.x-e.center.x),u=Math.abs(c.y-e.center.y);l>r&&(r=l),u>s&&(s=u)}let o=Math.max(t,r),a=Math.max(i,s);if(o>t||a>i){e.width=o*2,e.height=a*2;for(let c of e.pins)c._facingDirection=void 0}}};function mAt(n,e){for(let t=0;t<n.length-1;t++){let i=n[t],r=n[t+1];for(let s of e)for(let o=0;o<s.tracePath.length-1;o++){let a=s.tracePath[o],c=s.tracePath[o+1];if(ki(i,r,a,c))return!0}}return!1}var _At=3,yAt=(n,e)=>Math.sqrt(Math.pow(n.x-e.x,2)+Math.pow(n.y-e.y,2)),gAt=class extends kr{constructor(e){super();d(this,"solvedLongDistanceTraces",[]);d(this,"queuedCandidatePairs",[]);d(this,"currentCandidatePair",null);d(this,"subSolver",null);d(this,"chipMap",{});d(this,"inputProblem");d(this,"netConnMap");d(this,"newlyConnectedPinIds",new Set);d(this,"allSolvedTraces",[]);this.params=e;let{inputProblem:t,primaryMspConnectionPairs:i,alreadySolvedTraces:r}=this.params;this.inputProblem=t,this.allSolvedTraces=[...r];let s=new Set;for(let u of i)s.add(u.pins[0].pinId),s.add(u.pins[1].pinId);let{netConnMap:o}=mA(t);this.netConnMap=o;let a=new Map;for(let u of t.chips){this.chipMap[u.chipId]=u;for(let p of u.pins)a.set(p.pinId,{...p,chipId:u.chipId})}let c=[],l=new Set;for(let u of Object.keys(o.netMap)){let p=o.getIdsConnectedToNet(u);if(p.length<2)continue;let f=p.filter(y=>!s.has(y));for(let y of f){let g=a.get(y);if(!g)continue;let x=p.filter(v=>v!==y).flatMap(v=>{let S=a.get(v);return S?[{pin:S,distance:yAt(g,S)}]:[]}).sort((v,S)=>v.distance-S.distance).slice(0,_At);for(let v of x){let S=[g,v.pin],P=S.map(T=>T.pinId).sort().join("--");l.has(P)||(c.push(S),l.add(P))}}}this.queuedCandidatePairs=c}getConstructorParams(){return this.params}_step(){if(this.subSolver?.solved){let e=this.subSolver.solvedTracePath;if(e&&this.currentCandidatePair&&!mAt(e,this.allSolvedTraces)){let[i,r]=this.currentCandidatePair,s=this.netConnMap.getNetConnectedToId(i.pinId),o=`${i.pinId}-${r.pinId}`,a={mspPairId:o,dcConnNetId:s,globalConnNetId:s,pins:[i,r],tracePath:e,mspConnectionPairIds:[o],pinIds:[i.pinId,r.pinId]};this.solvedLongDistanceTraces.push(a),this.allSolvedTraces.push(a),this.newlyConnectedPinIds.add(i.pinId),this.newlyConnectedPinIds.add(r.pinId)}this.subSolver=null,this.currentCandidatePair=null}else this.subSolver?.failed&&(this.subSolver=null,this.currentCandidatePair=null);if(this.subSolver){this.subSolver.step();return}for(;this.queuedCandidatePairs.length>0;){let e=this.queuedCandidatePairs.shift(),[t,i]=e;if(!(this.newlyConnectedPinIds.has(t.pinId)||this.newlyConnectedPinIds.has(i.pinId))){this.currentCandidatePair=e,this.subSolver=new _Q({inputProblem:this.params.inputProblem,pins:this.currentCandidatePair,chipMap:this.chipMap});return}}this.solved=!0}visualize(){if(this.subSolver)return this.subSolver.visualize();let e=cs(this.inputProblem);for(let t of this.solvedLongDistanceTraces)e.lines.push({points:t.tracePath,strokeColor:"purple"});for(let[t,i]of this.queuedCandidatePairs)e.lines.push({points:[t,i],strokeColor:"gray",strokeDash:"4 4"});return e}getOutput(){return this.solved?{newTraces:this.solvedLongDistanceTraces,allTracesMerged:[...this.params.alreadySolvedTraces,...this.solvedLongDistanceTraces]}:{newTraces:[],allTracesMerged:this.params.alreadySolvedTraces}}},lA=(n,e)=>{for(let t=0;t<n.length-1;t++){let i=n[t],r=n[t+1];for(let s of e){let o={center:{x:s.minX+(s.maxX-s.minX)/2,y:s.minY+(s.maxY-s.minY)/2},width:s.maxX-s.minX,height:s.maxY-s.minY};if(yw(i,r,o)<=0)return!0}}return!1},uA=n=>{let e=0;for(let t=1;t<n.length-1;t++){let i=n[t-1],r=n[t],s=n[t+1],o=i.x===r.x,a=r.x===s.x;o!==a&&e++}return e},pQ=(n,e)=>{let t=[];return n.x===e.x||n.y===e.y?t.push([n,e]):(t.push([n,{x:e.x,y:n.y},e]),t.push([n,{x:n.x,y:e.y},e])),t},pA=(n,e)=>{for(let t=0;t<n.length-1;t++){let i=n[t],r=n[t+1];for(let s of e)if(v1(i,r,s))return!0}return!1},xAt=(n,e)=>{if(e>=n.length-3)return-1;let t=e,i=!0;for(let r=e;r<n.length-2&&r<e+10&&!(r+2>=n.length);r++){let s=n[r],o=n[r+1],a=n[r+2],c=s.x===o.x,l=o.x===a.x;if(c===l)break;let u=Math.sign(c?o.y-s.y:o.x-s.x);if(r>e){let p=n[r-1],f=p.x===s.x,y=Math.sign(f?s.y-p.y:s.x-p.x);if(c&&f&&u!==y||!c&&!f&&u!==y){i=!1;break}}t=r+2}return i&&t-e>=3?t:-1},N_=(n,e,t)=>{if(t.length<2)return!1;let i=t[0],r=t[t.length-1];return n.x===i.x&&n.y===i.y&&e.x===t[1].x&&e.y===t[1].y||n.x===t[t.length-2].x&&n.y===t[t.length-2].y&&e.x===r.x&&e.y===r.y},bAt=({path:n,obstacles:e,labelBounds:t,originalPath:i})=>{if(n.length<=2)return n;let r=[...n],s=uA(r),o=!0;for(;o;){o=!1;for(let c=0;c<r.length-3;c++){let l=xAt(r,c);if(l>0){if(N_(r[c],r[c+1],i)||N_(r[l-1],r[l],i))continue;let u=r[c],p=r[l],f=pQ(u,p);for(let y of f){let g=[...r.slice(0,c+1),...y.slice(1,-1),...r.slice(l)],x=lA(y,e),v=pA(y,t);if(!x&&!v){let S=uA(g);r=g,s=S,o=!0;break}}if(o)break}}if(!o)for(let c=0;c<r.length-2;c++){let l=Math.min(r.length-c-2,r.length-2);for(let u=1;u<=l;u++){let p=c+u+1;if(p>=r.length||N_(r[c],r[c+1],i)||N_(r[p-1],r[p],i))continue;let f=r[c],y=r[p],g=pQ(f,y);for(let x of g){let v=[...r.slice(0,c+1),...x.slice(1,-1),...r.slice(p)],S=x,P=lA(S,e),T=pA(S,t);if(!P&&!T){let k=uA(v);if(k<s||k===s&&v.length<r.length){r=v,s=k,o=!0;break}}}if(o)break}if(o)break}if(!o)for(let c=0;c<r.length-2;c++){let l=r[c],u=r[c+1],p=r[c+2];if(N_(l,u,i)||N_(u,p,i))continue;let f=l.x===u.x&&u.x===p.x,y=l.y===u.y&&u.y===p.y;if(f||y){let g=[...r.slice(0,c+1),...r.slice(c+2)],x=lA([l,p],e),v=pA([l,p],t);if(!x&&!v){r=g,o=!0;break}}}}return b1(r)},vAt=({targetMspConnectionPairId:n,traces:e,inputProblem:t,allLabelPlacements:i,mergedLabelNetIdMap:r,paddingBuffer:s})=>{let o=e.find(P=>P.mspPairId===n);if(!o)throw new Error(`Target trace ${n} not found`);let a=e.filter(P=>P.mspPairId!==n),c=.01,l=a.flatMap((P,T)=>P.tracePath.slice(0,-1).map((k,C)=>{let E=P.tracePath[C+1];return{chipId:`trace-obstacle-${T}-${C}`,minX:Math.min(k.x,E.x)-c/2,minY:Math.min(k.y,E.y)-c/2,maxX:Math.max(k.x,E.x)+c/2,maxY:Math.max(k.y,E.y)+c/2}})),u=NS(t),p=.01,y=[...u.map(P=>({...P,minX:P.minX-p,minY:P.minY-p,maxX:P.maxX+p,maxY:P.maxY+p})),...l],g=o.tracePath,v=i.filter(P=>{let T=r[P.globalConnNetId];return T?!T.has(o.globalConnNetId):P.globalConnNetId!==o.globalConnNetId}).map(P=>({minX:P.center.x-P.width/2-s,maxX:P.center.x+P.width/2+s,minY:P.center.y-P.height/2-s,maxY:P.center.y+P.height/2+s})),S=bAt({path:g,obstacles:y,labelBounds:v,originalPath:g});return{...o,tracePath:S}},wAt=({targetMspConnectionPairId:n,traces:e,inputProblem:t,allLabelPlacements:i,mergedLabelNetIdMap:r,paddingBuffer:s})=>{let o=e.find(P=>P.mspPairId===n);if(!o)throw new Error(`Target trace ${n} not found`);let a=1e-5,c=e.filter(P=>P.mspPairId!==n),l=.01,u=c.flatMap((P,T)=>P.tracePath.slice(0,-1).map((k,C)=>{let E=P.tracePath[C+1];return{chipId:`trace-obstacle-${T}-${C}`,minX:Math.min(k.x,E.x)-l/2,minY:Math.min(k.y,E.y)-l/2,maxX:Math.max(k.x,E.x)+l/2,maxY:Math.max(k.y,E.y)+l/2}})),f=[...NS(t).map(P=>({...P,minX:P.minX+a,maxX:P.maxX-a,minY:P.minY+a,maxY:P.maxY-a})),...u],y=(P,T,k)=>{for(let C of k)if(v1(P,T,C))return!0;return!1},x=i.filter(P=>{let T=r[P.globalConnNetId];return T?!T.has(o.globalConnNetId):P.globalConnNetId!==o.globalConnNetId}).map(P=>({minX:P.center.x-P.width/2+a,maxX:P.center.x+P.width/2-a,minY:P.center.y-P.height/2+a,maxY:P.center.y+P.height/2-a})),v=[...o.tracePath];if(v.length<4)return{...o};if(v.length===4){let[P,T,k,C]=v,E,N;if(P.y===T.y&&T.x===k.x&&k.y===C.y){let R=(P.x+C.x)/2;E={x:R,y:T.y},N={x:R,y:k.y}}else{let R=(P.y+C.y)/2;E={x:T.x,y:R},N={x:k.x,y:R}}return y(P,E,f)||y(E,N,f)||y(N,C,f)||y(P,E,x)||y(E,N,x)||y(N,C,x)||(v[1]=E,v[2]=N),{...o,tracePath:b1(v)}}for(let P=1;P<v.length-4;P++){let T=v[P],k=v[P+1],C=v[P+2],E=v[P+3],N=T.y===k.y&&k.x===C.x&&C.y===E.y,I=T.x===k.x&&k.y===C.y&&C.x===E.x,A=T.y===k.y&&k.y===C.y&&C.y===E.y,R=T.x===k.x&&k.x===C.x&&C.x===E.x,j=A||R,B=!1;if(N?B=Math.sign(k.x-T.x)===Math.sign(E.x-C.x):I&&(B=Math.sign(k.y-T.y)===Math.sign(E.y-C.y)),!((N||I)&&!j&&B))continue;let U,H,Q=Math.abs(N?T.x-k.x:T.y-k.y),tt=Math.abs(N?C.x-E.x:C.y-E.y);if(Math.abs(Q-tt)<.001)continue;if(N){let ot=(T.x+E.x)/2;U={x:ot,y:k.y},H={x:ot,y:C.y}}else{let ot=(T.y+E.y)/2;U={x:k.x,y:ot},H={x:C.x,y:ot}}y(T,U,f)||y(U,H,f)||y(H,E,f)||y(T,U,x)||y(U,H,x)||y(H,E,x)||(v[P+1]=U,v[P+2]=H,P=0)}let S=b1(v);return{...o,tracePath:S}},SAt=n=>{let e=[];if(n.length<3)return e;for(let t=0;t<n.length-2;t++){let i=n[t],r=n[t+1],s=n[t+2],o=r.x-i.x,a=r.y-i.y,c=s.x-r.x,l=s.y-r.y;(o===0&&l===0&&a!==0&&c!==0||a===0&&c===0&&o!==0&&l!==0)&&o*o+a*a>=.25&&c*c+l*l>=.25&&e.push({p1:i,p2:r,p3:s})}return e},PAt=(n,e)=>{let t=[];for(let i of n)i.mspPairId!==e&&t.push({points:i.tracePath});return t},hQ=(n,e,t)=>{let i=[];for(let r of t){let s=r.points;for(let o=0;o<s.length-1;o++){let a=s[o],c=s[o+1];if(!a||!c)continue;let l=rd(n,e,a,c);l&&i.push(l)}}return i},La=1e-6,al=(n,e,t=La)=>Math.abs(n.x-e.x)<t,kAt=({lShape:n,rectangle:e,padding:t=.5,interactionPoint1:i,interactionPoint2:r})=>{let{p1:s,p2:o,p3:a}=n,{x:c,y:l,width:u,height:p}=e,f,y=i,g=r;if(Math.abs(o.x-c)<La&&Math.abs(o.y-(l+p))<La)f={x:c+u+t,y:l-t},al(s,o)?y={x:i.x,y:i.y-t}:y={x:i.x+t,y:i.y},al(o,a)?g={x:r.x,y:r.y-t}:g={x:r.x+t,y:r.y};else if(Math.abs(o.x-(c+u))<La&&Math.abs(o.y-(l+p))<La)f={x:c-t,y:l-t},al(s,o)?y={x:i.x,y:i.y-t}:y={x:i.x-t,y:i.y},al(o,a)?g={x:r.x,y:r.y-t}:g={x:r.x-t,y:r.y};else if(Math.abs(o.x-c)<La&&Math.abs(o.y-l)<La)f={x:c+u+t,y:l+p+t},al(s,o)?y={x:i.x,y:i.y+t}:y={x:i.x+t,y:i.y},al(o,a)?g={x:r.x,y:r.y+t}:g={x:r.x+t,y:r.y};else if(Math.abs(o.x-(c+u))<La&&Math.abs(o.y-l)<La)f={x:c-t,y:l+p+t},al(s,o)?y={x:i.x,y:i.y+t}:y={x:i.x-t,y:i.y},al(o,a)?g={x:r.x,y:r.y+t}:g={x:r.x-t,y:r.y};else return[];return[[y,f,g]]},TAt=(n,e,t)=>{if(n.length<2)return{isColliding:!1};for(let i=0;i<n.length-1;i++){let r=n[i],s=n[i+1];for(let o of e)if(o.mspPairId!==t)for(let a=0;a<o.tracePath.length-1;a++){let c=o.tracePath[a],l=o.tracePath[a+1],u=rd(r,s,c,l);if(u)return{isColliding:!0,collidingTraceId:o.mspPairId,collisionPoint:u}}}return{isColliding:!1}},EAt=(n,e)=>{let t=[];for(let i of n)for(let r of e){let s=Math.min(i.x,r.x),o=Math.min(i.y,r.y),a=Math.max(i.x,r.x),c=Math.max(i.y,r.y),l=a-s,u=c-o;l>1e-6&&u>1e-6&&t.push({rect:{x:s,y:o,width:l,height:u},i1:i,i2:r})}return t},IS=n=>{let e={circles:[],lines:[]},t=Array.isArray(n)?n:[n];for(let i of t)e.circles.push({center:{x:i.p2.x,y:i.p2.y},radius:.01,fill:"blue"}),e.lines.push({points:[i.p1,i.p2,i.p3],strokeColor:"lightblue"});return e},dQ=(n,e="red")=>{let t={circles:[]};for(let i of n)t.circles.push({center:{x:i.x,y:i.y},radius:.01,fill:e});return t},fQ=n=>{let e={rects:[]};return e.rects.push({center:{x:n.x+n.width/2,y:n.y+n.height/2},width:n.width,height:n.height,stroke:"green"}),e},MAt=(n,e="gray",t=[])=>{let i={lines:[],circles:[]};for(let r of n)i.lines.push({points:r,strokeColor:e});for(let r of t)i.circles.push({center:r,radius:.01,fill:"green"});return i},hA=n=>{let e={lines:[],points:[],rects:[],circles:[],texts:[]};for(let t of n)t&&(t.lines&&e.lines.push(...t.lines),t.points&&e.points.push(...t.points),t.rects&&e.rects.push(...t.rects),t.circles&&e.circles.push(...t.circles),t.texts&&e.texts.push(...t.texts));return e},CAt=n=>{let e={circles:[]};return n?.isColliding&&n.collisionPoint&&e.circles.push({center:n.collisionPoint,radius:.01,fill:"red"}),e},IAt=class extends kr{constructor(e){super();d(this,"input");d(this,"lShapesToProcess",[]);d(this,"visualizationMode","l_shapes");d(this,"currentLShape",null);d(this,"intersectionPoints",[]);d(this,"tightRectangle",null);d(this,"candidates",[]);d(this,"bestRoute",null);d(this,"lastCollision",null);d(this,"collidingCandidate",null);d(this,"rectangleCandidates",[]);d(this,"currentRectangleIndex",0);d(this,"isInitialStep",!0);d(this,"currentCandidateIndex",0);d(this,"lShapeProcessingStep","idle");d(this,"lShapeJustProcessed",!1);d(this,"bestRouteFound",null);this.input=e,this.visualizationMode="l_shapes";for(let t of this.input.allTraces){let i=SAt(t.tracePath);this.lShapesToProcess.push(...i.map(r=>({...r,traceId:t.mspPairId})))}}_step(){if(this.isInitialStep){this.isInitialStep=!1;return}if(this.lShapeJustProcessed){this._resetAfterLShapProcessing();return}if(this.lShapesToProcess.length===0&&this.currentLShape===null){this.solved=!0;return}switch(this.lShapeProcessingStep){case"idle":this._handleIdleStep();break;case"intersections":this._handleIntersectionsStep();break;case"rectangle_selection":this._handleRectangleSelectionStep();break;case"candidate_evaluation":this._handleCandidateEvaluationStep();break}}_resetAfterLShapProcessing(){this.lShapeProcessingStep="idle",this.currentLShape=null,this.currentCandidateIndex=0,this.lShapeJustProcessed=!1,this.visualizationMode="l_shapes",this.intersectionPoints=[],this.tightRectangle=null,this.candidates=[],this.bestRoute=null,this.lastCollision=null,this.collidingCandidate=null}_handleIdleStep(){if(this.currentLShape=this.lShapesToProcess.shift(),!this.currentLShape){this.solved=!0;return}this.lShapeProcessingStep="intersections",this.visualizationMode="l_shapes"}_handleIntersectionsStep(){if(!this.currentLShape.traceId){this.lShapeProcessingStep="idle";return}let e=PAt(this.input.allTraces,this.currentLShape.traceId),t=hQ(this.currentLShape.p1,this.currentLShape.p2,e),i=hQ(this.currentLShape.p2,this.currentLShape.p3,e);if(this.intersectionPoints=[...t,...i],t.length===0||i.length===0){this.lShapeProcessingStep="idle";return}this.rectangleCandidates=EAt(t,i),this.currentRectangleIndex=0,this.lShapeProcessingStep="rectangle_selection"}_handleRectangleSelectionStep(){if(this.currentRectangleIndex>=this.rectangleCandidates.length){this.lShapeProcessingStep="idle";return}let{rect:e,i1:t,i2:i}=this.rectangleCandidates[this.currentRectangleIndex];this.tightRectangle=e,this.candidates=kAt({lShape:this.currentLShape,rectangle:this.tightRectangle,padding:2*this.input.paddingBuffer,interactionPoint1:t,interactionPoint2:i}),this.currentCandidateIndex=0,this.lastCollision=null,this.collidingCandidate=null,this.visualizationMode="candidates",this.lShapeProcessingStep="candidate_evaluation"}_handleCandidateEvaluationStep(){if(this.visualizationMode="candidates",this.bestRouteFound){this._applyBestRoute(this.bestRouteFound),this.bestRouteFound=null;return}if(this.currentCandidateIndex>=this.candidates.length){this.currentRectangleIndex++,this.lShapeProcessingStep="rectangle_selection";return}let e=this.candidates[this.currentCandidateIndex],t=TAt(e,this.input.allTraces,this.currentLShape.traceId);t?.isColliding?(this.lastCollision=t,this.collidingCandidate=e,this.currentCandidateIndex++):(this.bestRouteFound=e,this.lastCollision=null,this.collidingCandidate=null)}_applyBestRoute(e){this.bestRoute=e,this.collidingCandidate=null,this.lastCollision=null;let t=this.input.allTraces.findIndex(i=>i.mspPairId===this.currentLShape.traceId);if(t!==-1){let i=this.input.allTraces[t],r=i.tracePath.findIndex(s=>s.x===this.currentLShape.p2.x&&s.y===this.currentLShape.p2.y);if(r!==-1){let s=[...i.tracePath.slice(0,r),...e,...i.tracePath.slice(r+1)];this.input.allTraces[t]={...i,tracePath:s},this.lShapesToProcess=this.lShapesToProcess.filter(o=>o.traceId!==this.currentLShape.traceId)}}this.lShapeJustProcessed=!0}getOutput(){return{traces:this.input.allTraces}}visualize(){switch(this.visualizationMode){case"l_shapes":return IS(this.lShapesToProcess);case"intersection_points":return hA([this.currentLShape?IS(this.currentLShape):void 0,dQ(this.intersectionPoints)]);case"tight_rectangle":return hA([this.currentLShape?IS(this.currentLShape):void 0,dQ(this.intersectionPoints),this.tightRectangle?fQ(this.tightRectangle):void 0]);case"candidates":{if(this.lShapeJustProcessed){let i={lines:[]};for(let r of this.input.allTraces){let s=r.mspPairId===this.currentLShape?.traceId;for(let o=0;o<r.tracePath.length-1;o++)i.lines.push({points:[r.tracePath[o],r.tracePath[o+1]],strokeColor:s?"green":"#ccc"})}return i}let e={lines:[]};for(let i of this.input.allTraces)for(let r=0;r<i.tracePath.length-1;r++)e.lines.push({points:[i.tracePath[r],i.tracePath[r+1]],strokeColor:"#ccc"});let t;return this.bestRouteFound?t=this.bestRouteFound:this.lastCollision?.isColliding?t=this.collidingCandidate??void 0:this.currentCandidateIndex<this.candidates.length&&(t=this.candidates[this.currentCandidateIndex]),hA([e,this.currentLShape?IS(this.currentLShape):void 0,this.tightRectangle?fQ(this.tightRectangle):void 0,t?MAt([t],this.bestRouteFound?"green":"blue",this.intersectionPoints):void 0,this.lastCollision?CAt(this.lastCollision):void 0])}default:return{}}}},NAt=n=>{if(n.length!==4)return!1;let[e,t,i,r]=n,s=e.y===t.y&&t.x===i.x&&i.y===r.y&&e.x===r.x,o=e.x===t.x&&t.y===i.y&&i.x===r.x&&e.y===r.y;return s||o},AAt=class extends kr{constructor(e){super();d(this,"input");d(this,"outputTraces");d(this,"traceIdQueue");d(this,"tracesMap");d(this,"pipelineStep","untangling_traces");d(this,"activeTraceId",null);d(this,"activeSubSolver",null);this.input=e,this.outputTraces=[...e.allTraces],this.tracesMap=new Map(this.outputTraces.map(t=>[t.mspPairId,t])),this.traceIdQueue=Array.from(e.allTraces.map(t=>t.mspPairId))}_step(){if(this.activeSubSolver){if(this.activeSubSolver.step(),this.activeSubSolver.solved){let e=this.activeSubSolver.getOutput();this.outputTraces=e.traces,this.tracesMap=new Map(this.outputTraces.map(t=>[t.mspPairId,t])),this.activeSubSolver=null,this.pipelineStep="minimizing_turns"}else this.activeSubSolver.failed&&(this.activeSubSolver=null,this.pipelineStep="minimizing_turns");return}switch(this.pipelineStep){case"untangling_traces":this._runUntangleTracesStep();break;case"minimizing_turns":this._runMinimizeTurnsStep();break;case"balancing_l_shapes":this._runBalanceLShapesStep();break}}_runUntangleTracesStep(){this.activeSubSolver=new IAt({...this.input,allTraces:Array.from(this.tracesMap.values())})}_runMinimizeTurnsStep(){if(this.traceIdQueue.length===0){this.pipelineStep="balancing_l_shapes",this.traceIdQueue=Array.from(this.input.allTraces.map(e=>e.mspPairId));return}this._processTrace("minimizing_turns")}_runBalanceLShapesStep(){if(this.traceIdQueue.length===0){this.solved=!0;return}this._processTrace("balancing_l_shapes")}_processTrace(e){let t=this.traceIdQueue.shift();this.activeTraceId=t;let i=this.tracesMap.get(t);if(NAt(i.tracePath))return;let r=Array.from(this.tracesMap.values()),s;e==="minimizing_turns"?s=vAt({...this.input,targetMspConnectionPairId:t,traces:r}):s=wAt({...this.input,targetMspConnectionPairId:t,traces:r}),this.tracesMap.set(t,s),this.outputTraces=Array.from(this.tracesMap.values())}getOutput(){return{traces:this.outputTraces}}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();let e=cs(this.input.inputProblem,{chipAlpha:.1,connectionAlpha:.1});e.lines||(e.lines=[]),e.points||(e.points=[]),e.rects||(e.rects=[]),e.circles||(e.circles=[]),e.texts||(e.texts=[]);for(let t of this.outputTraces){let i={points:t.tracePath.map(r=>({x:r.x,y:r.y})),strokeColor:t.mspPairId===this.activeTraceId?"red":"blue"};e.lines.push(i)}return e}};function cl(n,e,t,i={}){return{solverName:n,solverClass:e,getConstructorParams:t,onSolved:i.onSolved,shouldSkip:i.shouldSkip}}var bQ=class extends kr{constructor(e){super();d(this,"mspConnectionPairSolver");d(this,"schematicTraceLinesSolver");d(this,"longDistancePairSolver");d(this,"traceOverlapShiftSolver");d(this,"netLabelPlacementSolver");d(this,"labelMergingSolver");d(this,"traceLabelOverlapAvoidanceSolver");d(this,"traceCleanupSolver");d(this,"startTimeOfPhase");d(this,"endTimeOfPhase");d(this,"timeSpentOnPhase");d(this,"firstIterationOfPhase");d(this,"inputProblem");d(this,"pipelineDef",[cl("mspConnectionPairSolver",BNt,()=>[{inputProblem:this.inputProblem}],{onSolved:e=>{}}),cl("schematicTraceLinesSolver",qNt,()=>[{mspConnectionPairs:this.mspConnectionPairSolver.mspConnectionPairs,dcConnMap:this.mspConnectionPairSolver.dcConnMap,globalConnMap:this.mspConnectionPairSolver.globalConnMap,inputProblem:this.inputProblem,chipMap:this.mspConnectionPairSolver.chipMap}]),cl("longDistancePairSolver",gAt,e=>[{inputProblem:e.inputProblem,primaryMspConnectionPairs:e.mspConnectionPairSolver.mspConnectionPairs,alreadySolvedTraces:e.schematicTraceLinesSolver.solvedTracePaths}],{onSolved:e=>{}}),cl("traceOverlapShiftSolver",JNt,()=>[{inputProblem:this.inputProblem,inputTracePaths:this.longDistancePairSolver?.getOutput().allTracesMerged,globalConnMap:this.mspConnectionPairSolver.globalConnMap}],{onSolved:e=>{}}),cl("netLabelPlacementSolver",uQ,()=>[{inputProblem:this.inputProblem,inputTraceMap:this.traceOverlapShiftSolver?.correctedTraceMap??Object.fromEntries(this.longDistancePairSolver.getOutput().allTracesMerged.map(e=>[e.mspPairId,e]))}],{onSolved:e=>{}}),cl("traceLabelOverlapAvoidanceSolver",hAt,e=>{let t=e.traceOverlapShiftSolver?.correctedTraceMap??Object.fromEntries(e.longDistancePairSolver.getOutput().allTracesMerged.map(s=>[s.mspPairId,s])),i=Object.values(t),r=e.netLabelPlacementSolver.netLabelPlacements;return[{inputProblem:e.inputProblem,traces:i,netLabelPlacements:r}]}),cl("traceCleanupSolver",AAt,e=>{let i=e.traceLabelOverlapAvoidanceSolver.getOutput().traces,r=e.traceLabelOverlapAvoidanceSolver.labelMergingSolver.getOutput();return[{inputProblem:e.inputProblem,allTraces:i,allLabelPlacements:r.netLabelPlacements,mergedLabelNetIdMap:r.mergedLabelNetIdMap,paddingBuffer:.1}]}),cl("netLabelPlacementSolver",uQ,e=>{let t=e.traceCleanupSolver?.getOutput().traces??e.traceLabelOverlapAvoidanceSolver.getOutput().traces;return[{inputProblem:e.inputProblem,inputTraceMap:Object.fromEntries(t.map(i=>[i.mspPairId,i]))}]})]);d(this,"currentPipelineStepIndex",0);this.inputProblem=this.cloneAndCorrectInputProblem(e),this.MAX_ITERATIONS=1e6,this.startTimeOfPhase={},this.endTimeOfPhase={},this.timeSpentOnPhase={},this.firstIterationOfPhase={}}getConstructorParams(){return this.inputProblem}cloneAndCorrectInputProblem(e){let t=structuredClone({...e,_chipObstacleSpatialIndex:void 0});return fAt(t),dAt(t),t}_step(){let e=this.pipelineDef[this.currentPipelineStepIndex];if(!e){this.solved=!0;return}if(this.activeSubSolver){this.activeSubSolver.step(),this.activeSubSolver.solved?(this.endTimeOfPhase[e.solverName]=performance.now(),this.timeSpentOnPhase[e.solverName]=this.endTimeOfPhase[e.solverName]-this.startTimeOfPhase[e.solverName],e.onSolved?.(this),this.activeSubSolver=null,this.currentPipelineStepIndex++):this.activeSubSolver.failed&&(this.error=this.activeSubSolver?.error,this.failed=!0,this.activeSubSolver=null);return}let t=e.getConstructorParams(this);this.activeSubSolver=new e.solverClass(...t),this[e.solverName]=this.activeSubSolver,this.timeSpentOnPhase[e.solverName]=0,this.startTimeOfPhase[e.solverName]=performance.now(),this.firstIterationOfPhase[e.solverName]=this.iterations}solveUntilPhase(e){for(;this.getCurrentPhase().toLowerCase()!==e.toLowerCase();)this.step()}getCurrentPhase(){return this.pipelineDef[this.currentPipelineStepIndex]?.solverName??"none"}visualize(){if(!this.solved&&this.activeSubSolver)return this.activeSubSolver.visualize();let e=[cs(this.inputProblem),...this.pipelineDef.map(i=>this[i.solverName]?.visualize()).filter(Boolean).map((i,r)=>{for(let s of i.rects??[])s.step=r;for(let s of i.points??[])s.step=r;for(let s of i.circles??[])s.step=r;for(let s of i.texts??[])s.step=r;for(let s of i.lines??[])s.step=r;return i})];return e.length===1?e[0]:{points:e.flatMap(i=>i.points||[]),rects:e.flatMap(i=>i.rects||[]),lines:e.flatMap(i=>i.lines||[]),circles:e.flatMap(i=>i.circles||[]),texts:e.flatMap(i=>i.texts||[])}}preview(){return this.activeSubSolver?this.activeSubSolver.preview():super.preview()}};var Jet=Ht(An(),1);var Qet=Ht(An(),1);var tnt=Ht(An(),1);nr();var RAt=n=>{let e=[];e.push(n.title),n.models.size>0&&e.push(...Array.from(n.models.values()));for(let t of n.components)e.push(t.toSpiceString());for(let t of n.subcircuits)e.push(t.toSpiceString());return n.printStatements.length>0&&e.push(...n.printStatements),n.controls.length>0&&(e.push(".control"),e.push(...n.controls),e.push(".endc")),n.tranCommand&&!e.some(t=>t.trim().toLowerCase().startsWith(".tran"))&&e.push(n.tranCommand),e.push(".END"),e.join(`
247
247
  `)},OAt=class{constructor(n="Circuit Netlist"){d(this,"title");d(this,"components");d(this,"nodes");d(this,"controls");d(this,"subcircuits");d(this,"models");d(this,"tranCommand");d(this,"printStatements");this.title=n,this.components=[],this.nodes=new Set,this.controls=[],this.subcircuits=[],this.models=new Map,this.tranCommand=null,this.printStatements=[]}addComponent(n){this.components.push(n);for(let e of n.nodes)this.nodes.add(e)}addSubcircuit(n){this.subcircuits.find(e=>e.name===n.name)||this.subcircuits.push(n)}toSpiceString(){return RAt(this)}},za=class{constructor(n,e,t){d(this,"name");d(this,"command");d(this,"nodes");this.name=n,this.command=e,this.nodes=t}toSpiceString(){return this.command.toSpiceString()}},LAt=class{constructor(n){d(this,"commandName","resistor");d(this,"props");this.props=n}toSpiceString(){let{name:n,positiveNode:e,negativeNode:t,model:i,value:r}=this.props,s=`R${n} ${e} ${t}`;return i&&(s+=` ${i}`),s+=` ${r}`,s}},FAt=class{constructor(n){d(this,"commandName","capacitor");d(this,"props");this.props=n}toSpiceString(){let{name:n,positiveNode:e,negativeNode:t,modelName:i,value:r,initialCondition:s}=this.props,o=`C${n} ${e} ${t}`;return i&&(o+=` ${i}`),o+=` ${r}`,s&&(o+=` IC=${s}`),o}},gA=class{constructor(n){d(this,"commandName","voltage_source");d(this,"props");this.props=n}toSpiceString(){let{name:n,positiveNode:e,negativeNode:t,value:i,acMagnitude:r,acPhase:s}=this.props,o=`V${n} ${e} ${t}`;return i&&(o+=` ${i}`),r&&(o+=` AC ${r}`,s&&(o+=` ${s}`)),o}},zAt=class{constructor(n){d(this,"commandName","diode");d(this,"props");this.props=n}toSpiceString(){let{name:n,positiveNode:e,negativeNode:t,model:i,area:r}=this.props,s=`D${n} ${e} ${t} ${i}`;return r&&(s+=` ${r}`),s}},DAt=class{constructor(n){d(this,"commandName","inductor");d(this,"props");this.props=n}toSpiceString(){let{name:n,positiveNode:e,negativeNode:t,model:i,value:r,initialCondition:s}=this.props,o=`L${n} ${e} ${t}`;return i&&(o+=` ${i}`),o+=` ${r}`,s&&(o+=` IC=${s}`),o}},vQ=class{constructor(n){d(this,"commandName","voltage_controlled_switch");d(this,"props");this.props=n}toSpiceString(){let{name:n,positiveNode:e,negativeNode:t,positiveControl:i,negativeControl:r,model:s}=this.props;return`S${n} ${e} ${t} ${i} ${r} ${s}`}};function wQ(n){let e=new OAt("* Circuit JSON to SPICE Netlist"),t=to(n).source_component.list(),i=to(n).source_port.list(),r=n.filter(x=>x.type==="simulation_switch").map(x=>x),s=new Map;for(let x of r)x.source_component_id&&s.set(x.source_component_id,x);let o=jG(n),a=new Map,c=new Map,l=1,u=new Set,p=new Set(to(n).source_net.list().filter(x=>x.name?.toLowerCase().includes("gnd")).map(x=>x.source_net_id));if(p.size>0){for(let x of to(n).source_trace.list())if(x.connected_source_port_ids.length>0&&x.connected_source_net_ids.some(S=>p.has(S))){let S=x.connected_source_port_ids[0],P=o.getNetConnectedToId(S);P&&u.add(P)}}let f=i.filter(x=>x.name?.toLowerCase()==="gnd");for(let x of f){let v=o.getNetConnectedToId(x.source_port_id);v&&u.add(v)}for(let x of to(n).simulation_voltage_source.list()){let v=x.negative_source_port_id??x.terminal2_source_port_id;if(v){let S=o.getNetConnectedToId(v);S&&u.add(S)}}for(let x of u)c.set(x,"0");for(let x of i){let v=x.source_port_id,S=o.getNetConnectedToId(v);S&&(c.has(S)||c.set(S,`N${l++}`),a.set(v,c.get(S)))}for(let x of i){let v=x.source_port_id;a.has(v)||a.set(v,`N${l++}`)}for(let x of t){if(x.type!=="source_component")continue;let v=to(n).source_port.list({source_component_id:x.source_component_id}).sort((P,T)=>(P.pin_number??0)-(T.pin_number??0)),S=v.map(P=>a.get(P.source_port_id)||"0");if("ftype"in x){let P=null;switch(x.ftype){case"simple_resistor":{if("resistance"in x&&"name"in x){let T=new LAt({name:x.name,positiveNode:S[0]||"0",negativeNode:S[1]||"0",value:$At(x.resistance)});P=new za(x.name,T,S)}break}case"simple_switch":{let T=YAt(x.name??x.source_component_id,"SW"),k=S[0]||"0",C=S[1]||"0",E=`NCTRL_${T}`,N=`SW_${T}`,I=s.get(x.source_component_id),A=XAt(I),R=new vQ({name:T,positiveNode:k,negativeNode:C,positiveControl:E,negativeControl:"0",model:N});P=new za(T,R,[k,C,E,"0"]),e.models.has(N)||e.models.set(N,`.MODEL ${N} SW(Ron=0.1 Roff=1e9 Vt=2.5 Vh=0.1)`);let j=`CTRL_${T}`,B=new gA({name:j,positiveNode:E,negativeNode:"0",value:A}),G=new za(j,B,[E,"0"]);e.addComponent(G);break}case"simple_capacitor":{if("capacitance"in x&&"name"in x){let T=new FAt({name:x.name,positiveNode:S[0]||"0",negativeNode:S[1]||"0",value:jAt(x.capacitance)});P=new za(x.name,T,S)}break}case"simple_diode":{if("name"in x){let T=v.find(A=>A.name?.toLowerCase()==="anode"||A.port_hints?.includes("anode")),k=v.find(A=>A.name?.toLowerCase()==="cathode"||A.port_hints?.includes("cathode")),C=a.get(T?.source_port_id??"")||"0",E=a.get(k?.source_port_id??"")||"0",N="D",I=new zAt({name:x.name,positiveNode:C,negativeNode:E,model:N});e.models.set(N,`.MODEL ${N} D`),P=new za(x.name,I,[C,E])}break}case"simple_inductor":{if("inductance"in x&&"name"in x){let T=new DAt({name:x.name,positiveNode:S[0]||"0",negativeNode:S[1]||"0",value:BAt(x.inductance)});P=new za(x.name,T,S)}break}case"simple_mosfet":{if("name"in x){let T=v.find(j=>j.name?.toLowerCase()==="drain"||j.port_hints?.includes("drain")),k=v.find(j=>j.name?.toLowerCase()==="gate"||j.port_hints?.includes("gate")),C=v.find(j=>j.name?.toLowerCase()==="source"||j.port_hints?.includes("source")),E=a.get(T?.source_port_id??"")||"0",N=a.get(k?.source_port_id??"")||"0",I=a.get(C?.source_port_id??"")||"0",A="SWMOD",R=new vQ({name:x.name,positiveNode:E,negativeNode:I,positiveControl:N,negativeControl:I,model:A});e.models.set(A,`.MODEL ${A} SW`),P=new za(x.name,R,[E,N,I])}break}}P&&e.addComponent(P)}}let y=to(n).simulation_voltage_source.list();for(let x of y)if(x.type==="simulation_voltage_source")if(x.is_dc_source===!1){if("terminal1_source_port_id"in x&&"terminal2_source_port_id"in x&&x.terminal1_source_port_id&&x.terminal2_source_port_id){let v=a.get(x.terminal1_source_port_id)||"0",S=a.get(x.terminal2_source_port_id)||"0",P="",T=x.wave_shape;if(T==="sinewave"){let C=x.voltage??0,E=x.frequency??0,N=0,I=0,A=x.phase??0;E>0?P=`SIN(0 ${C} ${E} ${N} ${I} ${A})`:P=`DC ${x.voltage??0}`}else if(T==="square"){let C=x.voltage??0,E=x.frequency??0,N=E===0?1/0:1/E,I=x.period??N,A=x.duty_cycle??.5,R=I*A;P=`PULSE(0 ${C} 0 1n 1n ${R} ${I})`}else x.voltage!==void 0&&(P=`DC ${x.voltage}`);if(P){let k=new gA({name:x.simulation_voltage_source_id,positiveNode:v,negativeNode:S,value:P}),C=new za(x.simulation_voltage_source_id,k,[v,S]);e.addComponent(C)}}}else{let v=x.positive_source_port_id??x.terminal1_source_port_id,S=x.negative_source_port_id??x.terminal2_source_port_id;if(v&&S&&"voltage"in x&&x.voltage!==void 0){let P=a.get(v)||"0",T=a.get(S)||"0",k=new gA({name:x.simulation_voltage_source_id,positiveNode:P,negativeNode:T,value:`DC ${x.voltage}`}),C=new za(x.simulation_voltage_source_id,k,[P,T]);e.addComponent(C)}}let g=n.find(x=>x.type==="simulation_experiment");if(g){let x=n.filter(T=>T.type==="simulation_voltage_probe");if(x.length>0){let T=to(n).source_trace.list(),k=new Set;for(let C of x){let E;if(C.source_port_id)E=a.get(C.source_port_id);else if(C.source_net_id){let N=T.find(I=>I.connected_source_net_ids.includes(C.source_net_id));if(N&&N.connected_source_port_ids.length>0){let I=N.connected_source_port_ids[0];E=a.get(I)}}E&&E!=="0"&&k.add(`V(${E.toLowerCase()})`)}k.size>0&&g.experiment_type?.includes("transient")&&e.printStatements.push(`.PRINT TRAN ${[...k].join(" ")}`)}let v=g.time_per_step,S=g.end_time_ms,P=g.start_time_ms;if(v&&S){let T=(P??0)/1e3,k=`.tran ${Xi(v/1e3)} ${Xi(S/1e3)}`;T>0&&(k+=` ${Xi(T)}`),k+=" UIC",e.tranCommand=k}}return e}function $At(n){return n>=1e6?`${n/1e6}MEG`:n>=1e3?`${n/1e3}K`:n.toString()}function jAt(n){return n>=.001?`${n*1e3}M`:n>=1e-6?`${n*1e6}U`:n>=1e-9?`${n*1e9}N`:n>=1e-12?`${n*1e12}P`:n.toString()}function BAt(n){return n>=1?n.toString():n>=.001?`${n*1e3}m`:n>=1e-6?`${n*1e6}u`:n>=1e-9?`${n*1e9}n`:n>=1e-12?`${n*1e12}p`:n.toString()}function YAt(n,e){if(!n)return e;let t=n.replace(/[^A-Za-z0-9_]/g,"_");return t?/^[0-9]/.test(t)?`${e}_${t}`:t:e}function XAt(n){if(!n)return"DC 0";let s=n.starts_closed??!1,o=n.closes_at??0,a=n.opens_at,c=n.switching_frequency,[l,u]=s?[5,0]:[0,5];if(c&&c>0){let p=1/c,f=a&&a>o?Math.min(a-o,p):0,y=f>0?f:Math.max(p/2,1e-9);return`PULSE(${Xi(l)} ${Xi(u)} ${Xi(o)} 1n 1n ${Xi(y)} ${Xi(p)})`}if(a!==void 0&&a>o){let p=Math.max(a-o,1e-9),f=o+p*2;return`PULSE(${Xi(l)} ${Xi(u)} ${Xi(o)} 1n 1n ${Xi(p)} ${Xi(f)})`}if(o>0){let p=o*2,f=Math.max(p/2,1e-9);return`PULSE(${Xi(l)} ${Xi(u)} ${Xi(o)} 1n 1n ${Xi(f)} ${Xi(p)})`}return`DC ${s?5:0}`}function Xi(n){if(!Number.isFinite(n))return`${n}`;if(n===0)return"0";let e=Math.abs(n);return e>=1e3||e<=.001?Number(n.toExponential(6)).toString():Number(n.toPrecision(6)).toString()}var ent=Ht(An(),1);var oi=1e-15,UAt=class{constructor(){d(this,"map");d(this,"rev");this.map=new Map([["0",0]]),this.rev=["0"]}getOrCreate(n){let e=String(n),t=e.toUpperCase();if(this.map.has(t))return this.map.get(t);let i=this.rev.length;return this.map.set(t,i),this.rev.push(e),i}get(n){return this.map.get(String(n).toUpperCase())}count(){return this.rev.length}matrixIndexOfNode(n){return n===0?-1:n-1}};function _r(n){if(n==null)return NaN;let e=String(n).trim();if(e==="")return NaN;if(/^[+-]?\d*\.?\d+(?:[eE][+-]?\d+)?$/.test(e))return parseFloat(e);let t={t:1e12,g:1e9,meg:1e6,k:1e3,m:.001,u:1e-6,n:1e-9,p:1e-12,f:1e-15},i=e.match(/^([+-]?\d*\.?\d+(?:[eE][+-]?\d+)?)([a-zA-Z]+)$/);if(!i)return parseFloat(e);let[,r,s]=i;if(r==null)return parseFloat(e);let o=parseFloat(r),a=(s??"").toLowerCase();return a=a.replace(/(ohm|v|a|s|h|f)$/g,""),a==="meg"?o*t.meg:a.length===1&&a in t?o*t[a]:o}function VAt(n){let e=/"[^"]*"|\w+\s*\([^)]*\)|\([^()]*\)|\S+/g,t=[],i;for(;(i=e.exec(n))!==null;)t.push(i[0]);return t}function pn(n,e,t){let i=n[e];if(i==null)throw new Error(t);return i}function GAt(n){let i=n.trim().replace(/^pulse\s*\(/i,"(").replace(/^\(/,"").replace(/\)$/,"").trim().split(/[\s,]+/).filter(s=>s.length);if(i.length<7)throw new Error("PULSE(...) requires 7 or 8 args");let r=i.map(s=>_r(s));if(r.some(s=>Number.isNaN(s)))throw new Error("Invalid PULSE() numeric value");return{v1:r[0],v2:r[1],td:r[2],tr:r[3],tf:r[4],ton:r[5],period:r[6],ncycles:i[7]!=null?r[7]:1/0}}function HAt(n){let i=n.trim().replace(/^pwl\s*\(/i,"(").replace(/^\(/,"").replace(/\)$/,"").trim().split(/[\s,]+/).filter(s=>s.length);if(i.length===0||i.length%2!==0)throw new Error("PWL(...) requires an even number of time/value pairs");let r=[];for(let s=0;s<i.length;s+=2){let o=_r(i[s]),a=_r(i[s+1]);if(Number.isNaN(o)||Number.isNaN(a))throw new Error("Invalid PWL() numeric value");r.push({t:o,v:a})}return r}function WAt(n,e){if(n.length===0)return 0;if(e<=n[0].t)return n[0].v;for(let t=1;t<n.length;t++){let i=n[t-1],r=n[t];if(e<=r.t){let s=Math.max(r.t-i.t,oi),o=(e-i.t)/s;return i.v+(r.v-i.v)*o}}return n[n.length-1].v}function qAt(n,e){if(e<n.td)return n.v1;let t=e-n.td,i=Math.floor(t/n.period);if(i>=n.ncycles)return n.v1;let r=t-i*n.period;if(r<n.tr){let s=r/Math.max(n.tr,oi);return n.v1+(n.v2-n.v1)*s}if(r<n.tr+n.ton)return n.v2;if(r<n.tr+n.ton+n.tf){let s=(r-(n.tr+n.ton))/Math.max(n.tf,oi);return n.v2+(n.v1-n.v2)*s}return n.v1}function ZAt(n){let e=new Map,t=new Map,i={nodes:new UAt,R:[],C:[],L:[],V:[],S:[],D:[],analyses:{ac:null,tran:null},probes:{tran:[]},skipped:[],models:{vswitch:e,diode:t}},r=n.split(/\r?\n/),s=!1;for(let a of r){let c=a.trim();if(!c||/^\*/.test(c))continue;if(/^\s*\.end\b/i.test(c))break;c=c.replace(/\/\/.*$/,""),c=c.replace(/;.*$/,"");let l=VAt(c);if(l.length===0)continue;let u=l[0];if(u.length===0)continue;if(!s&&!/^[rclvgsmiqd]\w*$/i.test(u)&&!/^\./.test(u)){s=!0;continue}if(/^\./.test(u)){let y=u.toLowerCase();if(y===".ac"){let g=pn(l,1,".ac missing mode").toLowerCase();if(g!=="dec"&&g!=="lin")throw new Error(".ac supports 'dec' or 'lin'");let x=parseInt(pn(l,2,".ac missing point count"),10),v=_r(pn(l,3,".ac missing start frequency")),S=_r(pn(l,4,".ac missing stop frequency"));i.analyses.ac={mode:g,N:x,f1:v,f2:S}}else if(y===".tran"){let g=_r(pn(l,1,".tran missing timestep")),x=_r(pn(l,2,".tran missing stop time"));i.analyses.tran={dt:g,tstop:x}}else if(y===".print")if(pn(l,1,".print missing analysis type").toLowerCase()==="tran"){let x=l.slice(2);for(let v of x){let S=v.match(/^v\(([^)]+)\)$/i);if(S&&S[1]){let P=S[1];i.probes.tran.some(T=>T.toUpperCase()===P.toUpperCase())||i.probes.tran.push(P)}}}else i.skipped.push(c);else if(y===".model"){let g=pn(l,1,".model missing name"),v=pn(l,2,".model missing type"),S="";if(v.includes("(")){let T=v.indexOf("(");S=v.slice(T+1),v=v.slice(0,T)}if(!S)S=l.slice(3).join(" ").replace(/^\(/,"").replace(/\)$/,"");else{let T=l.slice(3).join(" ").replace(/\)$/,"");S=`${S} ${T}`.trim()}S=S.replace(/^\(/,"").replace(/\)$/,"").trim();let P=v.toLowerCase();if(P==="vswitch"||P==="sw"){let T={name:g,Ron:1,Roff:1e12,Von:0,Voff:0},k,C;if(S.length>0){let E=S.split(/[\s,]+/).filter(Boolean);for(let N of E){let[I,A]=N.split("=");if(!I||A==null)continue;let R=I.toLowerCase(),j=_r(A);Number.isNaN(j)||(R==="ron"?T.Ron=j:R==="roff"?T.Roff=j:R==="von"?T.Von=j:R==="voff"?T.Voff=j:R==="vt"?k=j:R==="vh"&&(C=j))}}if(k!==void 0){let E=C??0;T.Von=k+E/2,T.Voff=k-E/2}e.set(g.toLowerCase(),T)}else if(P==="d"){let T={name:g,Is:1e-14,N:1};if(S.length>0){let k=S.split(/[\s,]+/).filter(Boolean);for(let C of k){let[E,N]=C.split("=");if(!E||N==null)continue;let I=E.toLowerCase(),A=_r(N);Number.isNaN(A)||(I==="is"?T.Is=A:I==="n"&&(T.N=A))}}t.set(g.toLowerCase(),T)}else i.skipped.push(c)}else i.skipped.push(c);continue}let p=u.charAt(0).toLowerCase(),f=u;try{if(p==="r"){let y=i.nodes.getOrCreate(pn(l,1,"Resistor missing node")),g=i.nodes.getOrCreate(pn(l,2,"Resistor missing node")),x=_r(pn(l,3,"Resistor missing value"));i.R.push({name:f,n1:y,n2:g,R:x})}else if(p==="c"){let y=i.nodes.getOrCreate(pn(l,1,"Capacitor missing node")),g=i.nodes.getOrCreate(pn(l,2,"Capacitor missing node")),x=_r(pn(l,3,"Capacitor missing value"));i.C.push({name:f,n1:y,n2:g,C:x,vPrev:0})}else if(p==="l"){let y=i.nodes.getOrCreate(pn(l,1,"Inductor missing node")),g=i.nodes.getOrCreate(pn(l,2,"Inductor missing node")),x=_r(pn(l,3,"Inductor missing value"));i.L.push({name:f,n1:y,n2:g,L:x,iPrev:0})}else if(p==="v"){let y=i.nodes.getOrCreate(pn(l,1,"Voltage source missing node")),g=i.nodes.getOrCreate(pn(l,2,"Voltage source missing node")),x={dc:0,acMag:0,acPhaseDeg:0,waveform:null,index:-1},v=3;for(v<l.length&&!/^[a-zA-Z]/.test(l[v])&&(x.dc=_r(l[v]),v++);v<l.length;){let S=l[v].toLowerCase();if(S==="dc"){let P=pn(l,v+1,"DC value missing");x.dc=_r(P),v+=2}else if(S==="ac"){let P=pn(l,v+1,"AC magnitude missing");x.acMag=_r(P);let T=l[v+2];T!=null&&/^[+-]?\d/.test(T)?(x.acPhaseDeg=_r(T),v+=3):v+=2}else if(S.startsWith("pulse")){let P=S.includes("(")?S:pn(l,v+1,"PULSE() missing arguments");if(!P||!/\(.*\)/.test(P))throw new Error("Malformed PULSE() specification");let T=GAt(P);x.waveform=k=>qAt(T,k),v+=S.includes("(")?1:2}else if(S.startsWith("pwl")){let P=S.includes("(")?S:pn(l,v+1,"PWL() missing arguments");if(!P||!/\(.*\)/.test(P))throw new Error("Malformed PWL() specification");let T=HAt(P);x.waveform=k=>WAt(T,k),v+=S.includes("(")?1:2}else/^\(.*\)$/.test(S),v++}i.V.push({name:f,n1:y,n2:g,dc:x.dc,acMag:x.acMag,acPhaseDeg:x.acPhaseDeg,waveform:x.waveform,index:x.index??-1})}else if(p==="s"){let y=i.nodes.getOrCreate(pn(l,1,"Switch missing node")),g=i.nodes.getOrCreate(pn(l,2,"Switch missing node")),x=i.nodes.getOrCreate(pn(l,3,"Switch missing control node")),v=i.nodes.getOrCreate(pn(l,4,"Switch missing control node")),S=pn(l,5,"Switch missing model");i.S.push({name:f,n1:y,n2:g,ncPos:x,ncNeg:v,modelName:S.toLowerCase(),model:null,isOn:!1})}else if(p==="d")if(l.length===4){let y=i.nodes.getOrCreate(pn(l,1,"Diode missing node")),g=i.nodes.getOrCreate(pn(l,2,"Diode missing node")),x=pn(l,3,"Diode missing model");i.D.push({name:f,nPlus:y,nMinus:g,modelName:x.toLowerCase(),model:null,vdPrev:0})}else i.skipped.push(c);else i.skipped.push(c)}catch(y){throw y instanceof Error?new Error(`Parse error on line: "${c}"
248
- ${y.message}`):y}}let o=i.nodes.count()-1;for(let a=0;a<i.V.length;a++){let c=i.V[a];c&&(c.index=o+a)}for(let a of i.S){let c=e.get(a.modelName);if(!c)throw new Error(`Unknown .model ${a.modelName} referenced by switch ${a.name}`);a.model=c,a.isOn=!1}for(let a of i.D){let c=t.get(a.modelName);if(!c)throw new Error(`Unknown .model ${a.modelName} referenced by diode ${a.name}`);a.model=c}return i}var rn=class Da{constructor(e=0,t=0){d(this,"re");d(this,"im");this.re=e,this.im=t}static from(e,t=0){return new Da(e,t)}static fromPolar(e,t=0){let i=t*Math.PI/180;return new Da(e*Math.cos(i),e*Math.sin(i))}clone(){return new Da(this.re,this.im)}add(e){return new Da(this.re+e.re,this.im+e.im)}sub(e){return new Da(this.re-e.re,this.im-e.im)}mul(e){return new Da(this.re*e.re-this.im*e.im,this.re*e.im+this.im*e.re)}div(e){let t=e.re*e.re+e.im*e.im;if(t<oi)throw new Error("Complex divide by ~0");return new Da((this.re*e.re+this.im*e.im)/t,(this.im*e.re-this.re*e.im)/t)}inv(){let e=this.re*this.re+this.im*this.im;if(e<oi)throw new Error("Complex invert by ~0");return new Da(this.re/e,-this.im/e)}abs(){return Math.hypot(this.re,this.im)}phaseDeg(){return Math.atan2(this.im,this.re)*180/Math.PI}};function KAt(n,e){let t=n.length;for(let r=0;r<t;r++){let s=n[r],o=e[r];if(!s||!o)throw new Error("Matrix dimensions mismatch");let a=s.map(c=>c.clone());a.push(o.clone()),n[r]=a}for(let r=0;r<t;r++){let s=r,o=n[r];if(!o)throw new Error("Matrix row missing");let a=o[r]?.abs()??0;for(let u=r+1;u<t;u++){let p=n[u];if(!p)throw new Error("Matrix row missing");let f=p[r]?.abs()??0;f>a&&(a=f,s=u)}if(a<oi)throw new Error("Singular matrix (complex)");if(s!==r){let u=n[r];n[r]=n[s],n[s]=u}let c=n[r];if(!c)throw new Error("Pivot row missing");let l=c[r];if(!l)throw new Error("Zero pivot encountered");for(let u=r+1;u<t;u++){let p=n[u];if(!p)throw new Error("Matrix row missing");let f=p[r];if(!f)continue;let y=f.div(l);if(!(y.abs()<oi))for(let g=r;g<=t;g++){let x=p[g],v=c[g];!x||!v||(p[g]=x.sub(y.mul(v)))}}}let i=new Array(t);for(let r=t-1;r>=0;r--){let s=n[r];if(!s)throw new Error("Matrix row missing");let o=s[t];if(!o)throw new Error("Augmented column missing");for(let c=r+1;c<t;c++){let l=s[c],u=i[c];!l||!u||(o=o.sub(l.mul(u)))}let a=s[r];if(!a)throw new Error("Zero pivot on back-substitution");i[r]=o.div(a)}return i}function JAt(n,e,t){if(n<=0||e<=0)throw new Error(".ac frequencies must be > 0");e<n&&([n,e]=[e,n]);let i=Math.log10(e/n),r=Math.max(1,Math.ceil(i*t)),s=[];for(let a=0;a<=r;a++)s.push(n*Math.pow(10,a/t));let o=s[s.length-1];return(o==null||o<e*(1-oi))&&s.push(e),s}function xA(n,e,t,i,r){let s=e.matrixIndexOfNode(t),o=e.matrixIndexOfNode(i);if(s>=0){let a=n[s];if(!a)throw new Error("Matrix row missing while stamping");a[s]=a[s]?.add(r)??r}if(o>=0){let a=n[o];if(!a)throw new Error("Matrix row missing while stamping");a[o]=a[o]?.add(r)??r}if(s>=0&&o>=0){let a=n[s],c=n[o];if(!a||!c)throw new Error("Matrix row missing while stamping");a[o]=a[o]?.sub(r)??rn.from(0,0).sub(r),c[s]=c[s]?.sub(r)??rn.from(0,0).sub(r)}}function QAt(n,e,t,i,r){let s=t.matrixIndexOfNode(i.n1),o=t.matrixIndexOfNode(i.n2),a=i.index,c=rn.from(1,0);if(s>=0){let u=n[s];if(!u)throw new Error("Matrix row missing while stamping voltage source");u[a]=u[a]?.add(c)??c}if(o>=0){let u=n[o];if(!u)throw new Error("Matrix row missing while stamping voltage source");u[a]=u[a]?.sub(c)??rn.from(0,0).sub(c)}let l=n[a];if(!l)throw new Error("Branch row missing while stamping voltage source");s>=0&&(l[s]=l[s]?.add(c)??c),o>=0&&(l[o]=l[o]?.sub(c)??rn.from(0,0).sub(c)),e[a]=(e[a]??rn.from(0,0)).add(r)}function t9t(n){var f,y,g,x;if(!n.analyses.ac)return null;let{mode:e,N:t,f1:i,f2:r}=n.analyses.ac,s=n.nodes.count()-1,o=n.V.length,a=s+o,c=e==="dec"?JAt(i,r,t):(()=>{let v=[],S=Math.max(2,t),P=(r-i)/(S-1);for(let T=0;T<S;T++)v.push(i+T*P);return v})(),l={};n.nodes.rev.forEach((v,S)=>{S!==0&&(l[v]=[])});let u={},p=2*Math.PI;for(let v of c){let S=Array.from({length:a},()=>Array.from({length:a},()=>rn.from(0,0))),P=Array.from({length:a},()=>rn.from(0,0));for(let k of n.R){if(k.R<=0)throw new Error(`R ${k.name} must be > 0`);let C=rn.from(1/k.R,0);xA(S,n.nodes,k.n1,k.n2,C)}for(let k of n.C){let C=rn.from(0,p*v*k.C);xA(S,n.nodes,k.n1,k.n2,C)}for(let k of n.L){let C=rn.from(0,p*v*k.L),E=C.abs()<oi?rn.from(0,0):rn.from(1,0).div(C);xA(S,n.nodes,k.n1,k.n2,E)}for(let k of n.V){let C=rn.fromPolar(k.acMag||0,k.acPhaseDeg||0);QAt(S,P,n.nodes,k,C)}let T=KAt(S,P);for(let k=1;k<n.nodes.count();k++){let C=k-1,E=n.nodes.rev[k];if(!E)continue;let N=l[E];N&&N.push(T[C]??rn.from(0,0))}for(let k of n.R){let C=k.n1===0?rn.from(0,0):T[k.n1-1]??rn.from(0,0),E=k.n2===0?rn.from(0,0):T[k.n2-1]??rn.from(0,0),I=rn.from(1/k.R,0).mul(C.sub(E));(u[f=k.name]||(u[f]=[])).push(I)}for(let k of n.C){let C=k.n1===0?rn.from(0,0):T[k.n1-1]??rn.from(0,0),E=k.n2===0?rn.from(0,0):T[k.n2-1]??rn.from(0,0),I=rn.from(0,p*v*k.C).mul(C.sub(E));(u[y=k.name]||(u[y]=[])).push(I)}for(let k of n.L){let C=k.n1===0?rn.from(0,0):T[k.n1-1]??rn.from(0,0),E=k.n2===0?rn.from(0,0):T[k.n2-1]??rn.from(0,0),N=rn.from(0,p*v*k.L),A=(N.abs()<oi?rn.from(0,0):rn.from(1,0).div(N)).mul(C.sub(E));(u[g=k.name]||(u[g]=[])).push(A)}for(let k of n.V){let C=T[k.index]??rn.from(0,0);(u[x=k.name]||(u[x]=[])).push(C)}}return{freqs:c,nodeVoltages:l,elementCurrents:u}}function e9t(n,e){let t=n.length;for(let r=0;r<t;r++){let s=n[r],o=e[r];if(!s||o==null)throw new Error("Matrix dimensions mismatch");let a=s.slice();a.push(o),n[r]=a}for(let r=0;r<t;r++){let s=r,o=n[r];if(!o)throw new Error("Matrix row missing");let a=Math.abs(o[r]??0);for(let u=r+1;u<t;u++){let p=n[u];if(!p)throw new Error("Matrix row missing");let f=Math.abs(p[r]??0);f>a&&(a=f,s=u)}if(a<oi)throw new Error("Singular matrix (real)");if(s!==r){let u=n[r];n[r]=n[s],n[s]=u}let c=n[r];if(!c)throw new Error("Pivot row missing");let l=c[r];if(l==null)throw new Error("Zero pivot encountered");for(let u=r+1;u<t;u++){let p=n[u];if(!p)throw new Error("Matrix row missing");let f=p[r];if(f==null)continue;let y=f/l;if(!(Math.abs(y)<oi))for(let g=r;g<=t;g++){let x=p[g],v=c[g];x==null||v==null||(p[g]=x-y*v)}}}let i=new Array(t).fill(0);for(let r=t-1;r>=0;r--){let s=n[r];if(!s)throw new Error("Matrix row missing");let o=s[t];if(o==null)throw new Error("Augmented column missing");for(let c=r+1;c<t;c++){let l=s[c],u=i[c];l==null||u==null||(o-=l*u)}let a=s[r];if(a==null)throw new Error("Zero pivot on back-substitution");i[r]=o/a}return i}function w1(n,e,t,i,r){let s=e.matrixIndexOfNode(t),o=e.matrixIndexOfNode(i);if(s>=0){let a=n[s];if(!a)throw new Error("Matrix row missing while stamping");a[s]=(a[s]??0)+r}if(o>=0){let a=n[o];if(!a)throw new Error("Matrix row missing while stamping");a[o]=(a[o]??0)+r}if(s>=0&&o>=0){let a=n[s],c=n[o];if(!a||!c)throw new Error("Matrix row missing while stamping");a[o]=(a[o]??0)-r,c[s]=(c[s]??0)-r}}function bA(n,e,t,i,r){let s=e.matrixIndexOfNode(t),o=e.matrixIndexOfNode(i);s>=0&&(n[s]=(n[s]??0)-r),o>=0&&(n[o]=(n[o]??0)+r)}function n9t(n,e,t,i,r){let s=t.matrixIndexOfNode(i.n1),o=t.matrixIndexOfNode(i.n2),a=i.index;if(s>=0){let l=n[s];if(!l)throw new Error("Matrix row missing while stamping voltage source");l[a]=(l[a]??0)+1}if(o>=0){let l=n[o];if(!l)throw new Error("Matrix row missing while stamping voltage source");l[a]=(l[a]??0)-1}let c=n[a];if(!c)throw new Error("Branch row missing while stamping voltage source");s>=0&&(c[s]=(c[s]??0)+1),o>=0&&(c[o]=(c[o]??0)-1),e[a]=(e[a]??0)+r}function i9t(n){var y,g,x,v,S,P;if(!n.analyses.tran)return null;let{dt:e,tstop:t}=n.analyses.tran,i=e>oi?e:Math.max(t/1e3,oi),r=Math.max(1,Math.ceil(t/Math.max(i,oi))),s=r>0?t/r:t,o=n.nodes.count()-1,a=n.V.length,c=o+a,l=[],u={};n.nodes.rev.forEach((T,k)=>{k!==0&&(u[T]=[])});let p={},f=0;for(let T=0;T<=r;T++,f=T*s){l.push(f);let k=new Array(c).fill(0);for(let C=0;C<20;C++){let E=Array.from({length:c},()=>new Array(c).fill(0)),N=new Array(c).fill(0);for(let R of n.R){let j=1/R.R;w1(E,n.nodes,R.n1,R.n2,j)}for(let R of n.C){let j=R.C/Math.max(s,oi);w1(E,n.nodes,R.n1,R.n2,j);let B=-j*R.vPrev;bA(N,n.nodes,R.n1,R.n2,B)}for(let R of n.L){let j=Math.max(s,oi)/R.L;w1(E,n.nodes,R.n1,R.n2,j),bA(N,n.nodes,R.n1,R.n2,R.iPrev)}for(let R of n.S){let j=R.model;if(!j)continue;let B=R.isOn?j.Ron:j.Roff,U=1/Math.max(Math.abs(B),oi);w1(E,n.nodes,R.n1,R.n2,U)}for(let R of n.V){let j=R.waveform?R.waveform(f):R.dc||0;n9t(E,N,n.nodes,R,j)}let I=.02585;for(let R of n.D){let j=R.model;if(!j)continue;let{nPlus:B,nMinus:G}=R,U=n.nodes.matrixIndexOfNode(B),H=n.nodes.matrixIndexOfNode(G),Q=B===0?0:k[U]??0,tt=G===0?0:k[H]??0,V=Q-tt,ot=C===0?R.vdPrev:V,nt=j.N*I,et=ot;ot>.8&&(et=.8),ot<-1&&(et=-1);let ht=Math.exp(et/nt),dt=j.Is*(ht-1),St=Math.max(j.Is/nt*ht,1e-12),Pt=dt-St*et;w1(E,n.nodes,B,G,St),bA(N,n.nodes,B,G,Pt)}k=e9t(E,N);let A=!1;for(let R of n.S){let j=R.model;if(!j)continue;let B=R.ncPos===0?0:k[R.ncPos-1]??0,G=R.ncNeg===0?0:k[R.ncNeg-1]??0,U=B-G,H=R.isOn;R.isOn?U<j.Voff&&(H=!1):U>j.Von&&(H=!0),H!==R.isOn&&(R.isOn=H,A=!0)}if(!A||C===19)break}for(let C=1;C<n.nodes.count();C++){let E=C-1,N=n.nodes.rev[C];if(!N)continue;let I=u[N];I&&I.push(k[E]??0)}for(let C of n.R){let E=C.n1===0?0:k[C.n1-1]??0,N=C.n2===0?0:k[C.n2-1]??0,I=(E-N)/C.R;(p[y=C.name]||(p[y]=[])).push(I)}for(let C of n.C){let E=C.n1===0?0:k[C.n1-1]??0,N=C.n2===0?0:k[C.n2-1]??0,I=C.C*(E-N-C.vPrev)/Math.max(s,oi);(p[g=C.name]||(p[g]=[])).push(I)}for(let C of n.L){let E=C.n1===0?0:k[C.n1-1]??0,N=C.n2===0?0:k[C.n2-1]??0,A=Math.max(s,oi)/C.L*(E-N)+C.iPrev;(p[x=C.name]||(p[x]=[])).push(A)}for(let C of n.V){let E=k[C.index]??0;(p[v=C.name]||(p[v]=[])).push(E)}for(let C of n.S){let E=C.model;if(!E)continue;let N=C.n1===0?0:k[C.n1-1]??0,I=C.n2===0?0:k[C.n2-1]??0,A=C.isOn?E.Ron:E.Roff,R=Math.max(Math.abs(A),oi),j=(N-I)/R;(p[S=C.name]||(p[S]=[])).push(j)}for(let C of n.D){if(!C.model)continue;let{nPlus:E,nMinus:N,model:I}=C,A=E===0?0:k[E-1]??0,R=N===0?0:k[N-1]??0,j=A-R,G=I.N*.02585,U=Math.exp(j/G),H=I.Is*(U-1);(p[P=C.name]||(p[P]=[])).push(H)}for(let C of n.C){let E=C.n1===0?0:k[C.n1-1]??0,N=C.n2===0?0:k[C.n2-1]??0;C.vPrev=E-N}for(let C of n.L){let E=C.n1===0?0:k[C.n1-1]??0,N=C.n2===0?0:k[C.n2-1]??0,I=Math.max(s,oi)/C.L;C.iPrev=I*(E-N)+C.iPrev}for(let C of n.D){let E=C.nPlus===0?0:k[C.nPlus-1]??0,N=C.nMinus===0?0:k[C.nMinus-1]??0;C.vdPrev=E-N}}if(n.probes.tran.length>0){let T={},k=n.probes.tran.map(C=>C.toUpperCase());for(let C in u)k.includes(C.toUpperCase())&&(T[C]=u[C]);return{times:l,nodeVoltages:T,elementCurrents:p}}return{times:l,nodeVoltages:u,elementCurrents:p}}function SQ(n){let e=ZAt(n),t=t9t(e),i=i9t(e);return{circuit:e,ac:t,tran:i}}function PQ(n,e,t){if(!n||!e.analyses.tran)return[];let{dt:i,tstop:r}=e.analyses.tran,{times:s,nodeVoltages:o}=n,a=[];for(let c in o){let l=o[c];a.push({type:"simulation_transient_voltage_graph",simulation_transient_voltage_graph_id:`stvg_${t}_${c}`,simulation_experiment_id:t,timestamps_ms:s.map(u=>u*1e3),voltage_levels:l,time_per_step:i*1e3,start_time_ms:0,end_time_ms:r*1e3,name:`V(${c})`})}return a}nr();Oe();nr();Oe();Oe();wt();Oe();Oe();ri();Oe();nr();Oe();nr();Oe();Oe();nr();Oe();function kQ(n,e,t,i){return Math.sqrt((t-n)**2+(i-e)**2)}var r9t=n=>{let e=n.filter(s=>s.type==="pcb_port"),t=n.filter(s=>s.type==="pcb_smtpad"),i=n.filter(s=>s.type==="pcb_trace");function r(s,o={}){let a=o.traceWidth||0,c=e.find(l=>kQ(l.x,l.y,s.x,s.y)<.01);if(c)return c.pcb_port_id;if(o.isFirstOrLastPoint){let l=t.find(u=>{if(u.shape==="rect")return Math.abs(s.x-u.x)<u.width/2+a/2&&Math.abs(s.y-u.y)<u.height/2+a/2;if(u.shape==="circle")return kQ(s.x,s.y,u.x,u.y)<u.radius});if(l)return l.pcb_port_id??null}return null}for(let s of i)for(let o=0;o<s.route.length;o++){let a=s.route[o],c=o===0||o===s.route.length-1;if(a.route_type==="wire"){if(!a.start_pcb_port_id&&o===0){let l=r(a,{isFirstOrLastPoint:c,traceWidth:a.width});l&&(a.start_pcb_port_id=l)}if(!a.end_pcb_port_id&&o===s.route.length-1){let l=r(a,{isFirstOrLastPoint:c,traceWidth:a.width});l&&(a.end_pcb_port_id=l)}}}};function EQ(n){r9t(n);let e=n.filter(o=>o.type==="source_trace"),t=n.filter(o=>o.type==="pcb_port"),i=[],r=er(n),s=new Map;for(let o of t)s.set(o.source_port_id,o);for(let o of e){let a=o.connected_source_port_ids;if(a.length<2)continue;let c=[],l=[];for(let g of a){let x=s.get(g);x?c.push(x):l.push(g)}if(c.length<2)continue;let u=c[0],p=r.getNetConnectedToId(u.pcb_port_id);r.getIdsConnectedToNet(p).filter(g=>n.some(x=>x.type==="pcb_trace"&&("pcb_trace_id"in x&&x.pcb_trace_id===g||"route_id"in x&&x.route_id===g))).length===0&&new Set(c.map(x=>x.pcb_component_id)).size>1&&i.push({type:"pcb_port_not_connected_error",message:`pcb_port_not_connected_error: Pcb ports [${c.map(x=>x.pcb_port_id).join(", ")}] are not connected together through the same net.`,error_type:"pcb_port_not_connected_error",pcb_port_ids:c.map(x=>x.pcb_port_id),pcb_component_ids:c.map(x=>x.pcb_component_id),pcb_port_not_connected_error_id:`pcb_port_not_connected_error_trace_${o.source_trace_id}`})}return i}var s9t=class{constructor({objects:n,getBounds:e,getId:t,CELL_SIZE:i}){d(this,"buckets");d(this,"objectsById");d(this,"getBounds");d(this,"getId");d(this,"CELL_SIZE",.4);d(this,"_idCounter",0);this.buckets=new Map,this.objectsById=new Map,this.getBounds=e,this.getId=t??(()=>this._getNextId()),this.CELL_SIZE=i??this.CELL_SIZE;for(let r of n)this.addObject(r)}_getNextId(){return`${this._idCounter++}`}addObject(n){let e=this.getBounds(n),t=this.getId(n),i={...n,spatialIndexId:t};this.objectsById.set(t,i);let r=Math.floor(e.minX/this.CELL_SIZE),s=Math.floor(e.minY/this.CELL_SIZE),o=Math.floor(e.maxX/this.CELL_SIZE),a=Math.floor(e.maxY/this.CELL_SIZE);for(let c=r;c<=o;c++)for(let l=s;l<=a;l++){let u=`${c}x${l}`,p=this.buckets.get(u);p?p.push(i):this.buckets.set(u,[i])}}removeObject(n){let e=this.objectsById.get(n);if(!e)return!1;this.objectsById.delete(n);let t=this.getBounds(e),i=Math.floor(t.minX/this.CELL_SIZE),r=Math.floor(t.minY/this.CELL_SIZE),s=Math.floor(t.maxX/this.CELL_SIZE),o=Math.floor(t.maxY/this.CELL_SIZE);for(let a=i;a<=s;a++)for(let c=r;c<=o;c++){let l=`${a}x${c}`,u=this.buckets.get(l);if(u){let p=u.findIndex(f=>f.spatialIndexId===n);p!==-1&&(u.splice(p,1),u.length===0&&this.buckets.delete(l))}}return!0}getBucketKey(n,e){return`${Math.floor(n/this.CELL_SIZE)}x${Math.floor(e/this.CELL_SIZE)}`}getObjectsInBounds(n,e=0){let t=[],i=new Set,r=Math.floor((n.minX-e)/this.CELL_SIZE),s=Math.floor((n.minY-e)/this.CELL_SIZE),o=Math.floor((n.maxX+e)/this.CELL_SIZE),a=Math.floor((n.maxY+e)/this.CELL_SIZE);for(let c=r;c<=o;c++)for(let l=s;l<=a;l++){let u=`${c}x${l}`,p=this.buckets.get(u)||[];for(let f of p){let y=f.spatialIndexId;i.has(y)||(i.add(y),t.push(f))}}return t}},S1=n=>n.type==="pcb_trace_segment"?{minX:Math.min(n.x1,n.x2),minY:Math.min(n.y1,n.y2),maxX:Math.max(n.x1,n.x2),maxY:Math.max(n.y1,n.y2)}:r_([n]),vA=.1,o9t=.15;var a9t=.2,c9t=.3,P1=.005;function l9t(n){let e=new Set;for(let t of n.route)t.route_type==="wire"&&(t.start_pcb_port_id&&e.add(t.start_pcb_port_id),t.end_pcb_port_id&&e.add(t.end_pcb_port_id));return Array.from(e)}function wA(n){let e=new Set;for(let t of n)for(let i of l9t(t))e.add(i);return Array.from(e)}var u9t=(n,e)=>{let t={x:n.x1,y:n.y1},i={x:n.x2,y:n.y2},r={x:e.x1,y:e.y1},s={x:e.x2,y:e.y2},o={x:i.x-t.x,y:i.y-t.y},a={x:s.x-r.x,y:s.y-r.y},c=o.x*o.x+o.y*o.y,l=a.x*a.x+a.y*a.y;if(c===0||l===0){if(c===0&&l===0)return{x:(t.x+r.x)/2,y:(t.y+r.y)/2};if(c===0){let j=Uo(((t.x-r.x)*a.x+(t.y-r.y)*a.y)/l,0,1),B={x:r.x+j*a.x,y:r.y+j*a.y};return{x:(t.x+B.x)/2,y:(t.y+B.y)/2}}let A=Uo(((r.x-t.x)*o.x+(r.y-t.y)*o.y)/c,0,1),R={x:t.x+A*o.x,y:t.y+A*o.y};return{x:(R.x+r.x)/2,y:(R.y+r.y)/2}}let u={x:t.x-r.x,y:t.y-r.y},p=o.x*o.x+o.y*o.y,f=o.x*a.x+o.y*a.y,y=o.x*u.x+o.y*u.y,g=a.x*a.x+a.y*a.y,x=a.x*u.x+a.y*u.y,v=p*g-f*f;if(v<1e-10)return p9t(t,i,r,s,o,a,c,l);let S=(f*x-g*y)/v,P=(p*x-f*y)/v;S=Uo(S,0,1),P=Uo(P,0,1),P=(S*f+x)/g,P=Uo(P,0,1),S=(P*f-y)/p,S=Uo(S,0,1);let T={x:t.x+S*o.x,y:t.y+S*o.y},k={x:r.x+P*a.x,y:r.y+P*a.y},C=T.x-k.x,E=T.y-k.y,N=Math.sqrt(C*C+E*E);return{x:(T.x+k.x)/2,y:(T.y+k.y)/2}},p9t=(n,e,t,i,r,s,o,a)=>{let c=((t.x-n.x)*r.x+(t.y-n.y)*r.y)/o;c=Uo(c,0,1);let l={x:n.x+c*r.x,y:n.y+c*r.y},u=((i.x-n.x)*r.x+(i.y-n.y)*r.y)/o;u=Uo(u,0,1);let p={x:n.x+u*r.x,y:n.y+u*r.y},f=((n.x-t.x)*s.x+(n.y-t.y)*s.y)/a;f=Uo(f,0,1);let y={x:t.x+f*s.x,y:t.y+f*s.y},g=((e.x-t.x)*s.x+(e.y-t.y)*s.y)/a;g=Uo(g,0,1);let x={x:t.x+g*s.x,y:t.y+g*s.y},S=[{pointA:l,pointB:t,distance:Math.sqrt((l.x-t.x)**2+(l.y-t.y)**2)},{pointA:p,pointB:i,distance:Math.sqrt((p.x-i.x)**2+(p.y-i.y)**2)},{pointA:n,pointB:y,distance:Math.sqrt((n.x-y.x)**2+(n.y-y.y)**2)},{pointA:e,pointB:x,distance:Math.sqrt((e.x-x.x)**2+(e.y-x.y)**2)}].reduce((P,T)=>T.distance<P.distance?T:P);return{x:(S.pointA.x+S.pointB.x)/2,y:(S.pointA.y+S.pointB.y)/2}},Uo=(n,e,t)=>Math.max(e,Math.min(t,n)),h9t=n=>{if(n.type==="pcb_via"||n.type==="pcb_plated_hole"&&n.shape==="circle")return n.outer_diameter/2;if(n.type==="pcb_hole"&&n.hole_shape==="circle")return n.hole_diameter/2;if(n.type==="pcb_smtpad"&&n.shape==="circle")return n.radius;throw new Error(`Could not determine radius of element: ${JSON.stringify(n)}`)},TQ=(n,e)=>{let t={x:n.x1,y:n.y1},i={x:n.x2,y:n.y2},r=e.minX,s=e.minY,o=e.maxX,a=e.maxY;if(t.x===i.x&&t.y===i.y){let I=Math.max(r,Math.min(o,t.x)),A=Math.max(s,Math.min(a,t.y));return I===t.x&&A===t.y?{x:t.x,y:t.y}:{x:I,y:A}}let c=i.x-t.x,l=i.y-t.y,u=c!==0?(r-t.x)/c:Number.NEGATIVE_INFINITY,p=c!==0?(o-t.x)/c:Number.POSITIVE_INFINITY,f=l!==0?(s-t.y)/l:Number.NEGATIVE_INFINITY,y=l!==0?(a-t.y)/l:Number.POSITIVE_INFINITY,g=Math.max(Math.min(u,p),Math.min(f,y)),x=Math.min(Math.max(u,p),Math.max(f,y));if(g<=x&&x>=0&&g<=1){let I=Math.max(0,Math.min(1,g));return{x:t.x+I*c,y:t.y+I*l}}let v={x:Math.max(r,Math.min(o,t.x)),y:Math.max(s,Math.min(a,t.y))},S={x:Math.max(r,Math.min(o,i.x)),y:Math.max(s,Math.min(a,i.y))},P=(v.x-t.x)**2+(v.y-t.y)**2,T=(S.x-i.x)**2+(S.y-i.y)**2,k=[{start:{x:r,y:s},end:{x:o,y:s}},{start:{x:o,y:s},end:{x:o,y:a}},{start:{x:o,y:a},end:{x:r,y:a}},{start:{x:r,y:a},end:{x:r,y:s}}],C=Math.min(P,T),E=P<=T?v:S,N=(I,A,R)=>Math.max(A,Math.min(R,I));for(let I of k){let A={x:i.x-t.x,y:i.y-t.y},R={x:I.end.x-I.start.x,y:I.end.y-I.start.y},j={x:t.x-I.start.x,y:t.y-I.start.y},B=A.x*A.x+A.y*A.y,G=A.x*R.x+A.y*R.y,U=A.x*j.x+A.y*j.y,H=R.x*R.x+R.y*R.y,Q=R.x*j.x+R.y*j.y,tt=B*H-G*G;if(Math.abs(tt)<1e-10)continue;let V=(G*Q-H*U)/tt,ot=(B*Q-G*U)/tt;V=N(V,0,1),ot=N(ot,0,1);let nt={x:t.x+V*A.x,y:t.y+V*A.y},et={x:I.start.x+ot*R.x,y:I.start.y+ot*R.y},ht=nt.x-et.x,dt=nt.y-et.y,St=ht*ht+dt*dt;St<C&&(C=St,E={x:(nt.x+et.x)/2,y:(nt.y+et.y)/2})}return E};function d9t(n){return n.type==="pcb_trace_segment"?[n.layer]:n.type==="pcb_smtpad"?[n.layer]:n.type==="pcb_plated_hole"?Array.isArray(n.layers)?n.layers:[...Im]:n.type==="pcb_hole"?[...Im]:n.type==="pcb_via"?Array.isArray(n.layers)?n.layers:[...Im]:n.type==="pcb_keepout"?Array.isArray(n.layers)?n.layers:[]:[]}function MQ(n,{connMap:e}={}){let t=[];e??(e=er(n));let r=Ke(n).pcb_trace.list().flatMap(g=>{let x=[];for(let v=0;v<g.route.length-1;v++){let S=g.route[v],P=g.route[v+1];S.route_type==="wire"&&P.route_type==="wire"&&S.layer===P.layer&&x.push({type:"pcb_trace_segment",pcb_trace_id:g.pcb_trace_id,_pcbTrace:g,thickness:"width"in S?S.width:"width"in P?P.width:o9t,layer:S.layer,x1:S.x,y1:S.y,x2:P.x,y2:P.y})}return x}),s=Ke(n).pcb_smtpad.list(),o=Ke(n).pcb_plated_hole.list(),a=Ke(n).pcb_hole.list(),c=Ke(n).pcb_via.list(),l=Ke(n).pcb_keepout.list(),u=[...r,...s,...o,...a,...c,...l],p=new s9t({objects:u,getBounds:S1}),f=g=>Is(n,g),y=new Set;for(let g of r){let x=vA,v=S1(g),S=p.getObjectsInBounds(v,x+g.thickness/2);if(!(g.x1===g.x2&&g.y1===g.y2))for(let P of S){if(!d9t(P).includes(g.layer))continue;if(P.type==="pcb_trace_segment"){let E=P;if(g.layer!==E.layer||e.areIdsConnected(g.pcb_trace_id,E.pcb_trace_id))continue;let N=n_({x:g.x1,y:g.y1},{x:g.x2,y:g.y2},{x:E.x1,y:E.y1},{x:E.x2,y:E.y2})-g.thickness/2-E.thickness/2;if(N>vA-P1)continue;let I=`overlap_${g.pcb_trace_id}_${E.pcb_trace_id}`,A=`overlap_${E.pcb_trace_id}_${g.pcb_trace_id}`;if(y.has(I)||y.has(A))continue;y.add(I),t.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${f(g.pcb_trace_id)} overlaps with ${f(E.pcb_trace_id)} ${N<0?"(accidental contact)":`(gap: ${N.toFixed(3)}mm)`}`,pcb_trace_id:g.pcb_trace_id,source_trace_id:"",pcb_trace_error_id:I,pcb_component_ids:[],center:u9t(g,E),pcb_port_ids:wA([g._pcbTrace,E._pcbTrace])});continue}let T=Oo(P);if(e.areIdsConnected(g.pcb_trace_id,"pcb_trace_id"in P?P.pcb_trace_id:T))continue;if(P.type==="pcb_via"||P.type==="pcb_plated_hole"&&P.shape==="circle"||P.type==="pcb_hole"||P.type==="pcb_smtpad"&&P.shape==="circle"){let E=h9t(P),I=gw({x:g.x1,y:g.y1},{x:g.x2,y:g.y2},{x:P.x,y:P.y,radius:E})-g.thickness/2;if(I>vA-P1)continue;let A=`overlap_${g.pcb_trace_id}_${T}`;if(y.has(A))continue;y.add(A),t.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${f(g.pcb_trace_id)} overlaps with ${P.type} "${f(Oo(P))}" ${I<0?"(accidental contact)":`(gap: ${I.toFixed(3)}mm)`}`,pcb_trace_id:g.pcb_trace_id,center:TQ(g,S1(P)),source_trace_id:"",pcb_trace_error_id:A,pcb_component_ids:["pcb_component_id"in P?P.pcb_component_id:void 0].filter(Boolean),pcb_port_ids:[...wA([g._pcbTrace]),"pcb_port_id"in P?P.pcb_port_id:void 0].filter(Boolean)})}let C=Cg({x:g.x1,y:g.y1},{x:g.x2,y:g.y2},S1(P))-g.thickness/2;if(C+P1<x){let E=`overlap_${g.pcb_trace_id}_${T}`;if(y.has(E))continue;y.add(E),t.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${f(g.pcb_trace_id)} overlaps with ${P.type} "${f(Oo(P))}" ${C<0?"(accidental contact)":`(gap: ${C.toFixed(3)}mm)`}`,pcb_trace_id:g.pcb_trace_id,source_trace_id:"",pcb_trace_error_id:E,pcb_component_ids:["pcb_component_id"in P?P.pcb_component_id:void 0].filter(Boolean),center:TQ(g,S1(P)),pcb_port_ids:[...wA([g._pcbTrace]),"pcb_port_id"in P?P.pcb_port_id:void 0].filter(Boolean)})}}}return t}function CQ(n){return n.area()>=0}function IQ({center:n,size:e,rotationDeg:t=0}){let i=n.x,r=n.y,s=e.width/2,o=e.height/2,a=[new Xo(i-s,r-o),new Xo(i+s,r-o),new Xo(i+s,r+o),new Xo(i-s,r+o)],c=new m1(a);if(t){let l=nw(t,i,r),u=a.map(p=>{let f=oe(l,{x:p.x,y:p.y});return new Xo(f.x,f.y)});c=new m1(u)}return CQ(c)||c.reverse(),c}function f9t({board:n}){if(n.outline&&n.outline.length>0){let e=n.outline.map(i=>new Xo(i.x,i.y)),t=new m1(e);return CQ(t)||t.reverse(),t}return n.center&&typeof n.width=="number"&&typeof n.height=="number"?IQ({center:n.center,size:{width:n.width,height:n.height},rotationDeg:0}):null}function m9t({circuitJson:n,component:e}){if(e.source_component_id){let t=n.find(i=>i.type==="source_component"&&i.source_component_id===e.source_component_id);if(t&&"name"in t&&t.name)return t.name}return Is(n,e.pcb_component_id)||"Unknown"}function _9t(n,e,t,i,r,s){let o=new Xo(t.x,t.y);if(!e.contains(o)){let x=e.distanceTo(o);return Array.isArray(x)?x[0]:Number(x)||0}let a=i/2,c=r/2,l=[{x:t.x-a,y:t.y-c},{x:t.x+a,y:t.y-c},{x:t.x+a,y:t.y+c},{x:t.x-a,y:t.y+c}],u=[];for(let x=0;x<4;x++){let v=(x+1)%4;u.push({x:(l[x].x+l[v].x)/2,y:(l[x].y+l[v].y)/2})}let p=nw(s,t.x,t.y),f=x=>{let v=oe(p,x);return new Xo(v.x,v.y)},y=l.concat(u).map(f),g=0;for(let x of y)if(!e.contains(x)){let v=e.distanceTo(x),S=Array.isArray(v)?v[0]:Number(v)||0;S>g&&(g=S)}if(g>0)return g;try{let x=WN.intersect(n,e),v=0;x?Array.isArray(x)?v=x.reduce((P,T)=>P+(typeof T.area=="function"?T.area():0),0):typeof x.area=="function"?v=x.area():v=0:v=0;let S=n.area();if(v>0&&v<S){let P=1-v/S,T=Math.abs(i),k=Math.abs(r);return Math.min(T,k)*P}else return .1}catch{return .1}}function NQ(n){let e=n.find(s=>s.type==="pcb_board");if(!e)return[];let t=f9t({board:e});if(!t)return[];let i=n.filter(s=>s.type==="pcb_component");if(i.length===0)return[];let r=[];for(let s of i){if(!s.center||typeof s.width!="number"||typeof s.height!="number"||s.width<=0||s.height<=0)continue;let o=IQ({center:s.center,size:{width:s.width,height:s.height},rotationDeg:s.rotation||0});if(o.area()===0||t.contains(o))continue;let c=_9t(o,t,s.center,s.width,s.height,s.rotation||0),l=m9t({circuitJson:n,component:s}),u=Math.round(c*100)/100;r.push({type:"pcb_component_outside_board_error",error_type:"pcb_component_outside_board_error",pcb_component_outside_board_error_id:`pcb_component_outside_board_${s.pcb_component_id}`,message:`Component ${l} (${s.pcb_component_id}) extends outside board boundaries by ${u}mm`,pcb_component_id:s.pcb_component_id,pcb_board_id:e.pcb_board_id,component_center:s.center,component_bounds:{min_x:o.box.xmin,max_x:o.box.xmax,min_y:o.box.ymin,max_y:o.box.ymax},subcircuit_id:s.subcircuit_id,source_component_id:s.source_component_id})}return r}function y9t(n,e){return Math.hypot(n.x-e.x,n.y-e.y)}function AQ(n,{connMap:e,minSpacing:t=a9t}={}){let i=n.filter(o=>o.type==="pcb_via");if(i.length<2)return[];e??(e=er(n));let r=[],s=new Set;for(let o=0;o<i.length;o++)for(let a=o+1;a<i.length;a++){let c=i[o],l=i[a];if(!e.areIdsConnected(c.pcb_via_id,l.pcb_via_id))continue;let u=y9t(c,l)-c.outer_diameter/2-l.outer_diameter/2;if(u+P1>=t)continue;let p=[c.pcb_via_id,l.pcb_via_id].sort().join("_");s.has(p)||(s.add(p),r.push({type:"pcb_via_clearance_error",pcb_error_id:`same_net_vias_close_${p}`,message:`Vias ${Is(n,c.pcb_via_id)} and ${Is(n,l.pcb_via_id)} are too close together (gap: ${u.toFixed(3)}mm)`,error_type:"pcb_via_clearance_error",pcb_via_ids:[c.pcb_via_id,l.pcb_via_id],minimum_clearance:t,actual_clearance:u,pcb_center:{x:(c.x+l.x)/2,y:(c.y+l.y)/2}}))}return r}function g9t(n,e){return Math.hypot(n.x-e.x,n.y-e.y)}function RQ(n,{connMap:e,minSpacing:t=c9t}={}){let i=n.filter(o=>o.type==="pcb_via");if(i.length<2)return[];e??(e=er(n));let r=[],s=new Set;for(let o=0;o<i.length;o++)for(let a=o+1;a<i.length;a++){let c=i[o],l=i[a];if(e.areIdsConnected(c.pcb_via_id,l.pcb_via_id))continue;let u=g9t(c,l)-c.outer_diameter/2-l.outer_diameter/2;if(u+P1>=t)continue;let p=[c.pcb_via_id,l.pcb_via_id].sort().join("_");s.has(p)||(s.add(p),r.push({type:"pcb_via_clearance_error",pcb_error_id:`different_net_vias_close_${p}`,message:`Vias ${Is(n,c.pcb_via_id)} and ${Is(n,l.pcb_via_id)} from different nets are too close together (gap: ${u.toFixed(3)}mm)`,error_type:"pcb_via_clearance_error",pcb_via_ids:[c.pcb_via_id,l.pcb_via_id],minimum_clearance:t,actual_clearance:u,pcb_center:{x:(c.x+l.x)/2,y:(c.y+l.y)/2}}))}return r}var x9t=.2;function b9t(n){if(n.outline&&n.outline.length>0)return n.outline.map(e=>({x:e.x,y:e.y}));if(n.center&&typeof n.width=="number"&&typeof n.height=="number"){let e=n.center.x,t=n.center.y,i=n.width/2,r=n.height/2;return[{x:e-i,y:t-r},{x:e+i,y:t-r},{x:e+i,y:t+r},{x:e-i,y:t+r}]}return null}function OQ(n,e={}){let t=[],i=e.margin??x9t,r=n.find(a=>a.type==="pcb_board");if(!r)return t;let s=b9t(r);if(!s)return t;let o=Ke(n).pcb_trace.list();for(let a of o)if(!(a.route.length<2))for(let c=0;c<a.route.length-1;c++){let l=a.route[c],u=a.route[c+1];if(l.route_type!=="wire"||u.route_type!=="wire")continue;let p="width"in l?l.width:"width"in u?u.width:.1,f={x:l.x,y:l.y},y={x:u.x,y:u.y},g=1/0;for(let v=0;v<s.length;v++){let S=s[v],P=s[(v+1)%s.length],T=n_(f,y,S,P);T<g&&(g=T)}let x=p/2+i;if(g<x){let v={type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:`trace_too_close_to_board_${a.pcb_trace_id}_segment_${c}`,message:`Trace too close to board edge (${g.toFixed(3)}mm < ${x.toFixed(3)}mm required, margin: ${i}mm)`,pcb_trace_id:a.pcb_trace_id,source_trace_id:a.source_trace_id||"",center:{x:(f.x+y.x)/2,y:(f.y+y.y)/2},pcb_component_ids:[],pcb_port_ids:[]};t.push(v)}}return t}function v9t(n,e){let t=r_([n]),i=r_([e]);return Hc(t,i)}function LQ(n){let e=[],t=er(n),i=Ke(n).pcb_smtpad.list(),r=Ke(n).pcb_plated_hole.list(),s=Ke(n).pcb_hole.list(),o=new Map;for(let c of i){let l=c.pcb_component_id||`standalone_pad_${Oo(c)}`;o.has(l)||o.set(l,{component_id:l,elements:[],bounds:{minX:0,minY:0,maxX:0,maxY:0}}),o.get(l).elements.push(c)}for(let c of r){let l=c.pcb_component_id||`standalone_plated_hole_${Oo(c)}`;o.has(l)||o.set(l,{component_id:l,elements:[],bounds:{minX:0,minY:0,maxX:0,maxY:0}}),o.get(l).elements.push(c)}for(let c of s){let l=`standalone_hole_${Oo(c)}`;o.set(l,{component_id:l,elements:[c],bounds:{minX:0,minY:0,maxX:0,maxY:0}})}for(let[c,l]of o)l.elements.length>0&&(l.bounds=r_(l.elements));let a=Array.from(o.values());for(let c=0;c<a.length;c++)for(let l=c+1;l<a.length;l++){let u=a[c],p=a[l];if(Hc(u.bounds,p.bounds))for(let f of u.elements)for(let y of p.elements){let g=Oo(f),x=Oo(y);if(!(f.type==="pcb_smtpad"&&y.type==="pcb_smtpad"&&t.areIdsConnected(g,x))&&v9t(f,y)){let v={type:"pcb_footprint_overlap_error",pcb_error_id:`pcb_footprint_overlap_${g}_${x}`,error_type:"pcb_footprint_overlap_error",message:`PCB component ${f.type} "${g}" overlaps with ${y.type} "${x}"`};(f.type==="pcb_smtpad"||y.type==="pcb_smtpad")&&(v.pcb_smtpad_ids=[],f.type==="pcb_smtpad"&&v.pcb_smtpad_ids.push(g),y.type==="pcb_smtpad"&&v.pcb_smtpad_ids.push(x)),(f.type==="pcb_plated_hole"||y.type==="pcb_plated_hole")&&(v.pcb_plated_hole_ids=[],f.type==="pcb_plated_hole"&&v.pcb_plated_hole_ids.push(g),y.type==="pcb_plated_hole"&&v.pcb_plated_hole_ids.push(x)),(f.type==="pcb_hole"||y.type==="pcb_hole")&&(v.pcb_hole_ids=[],f.type==="pcb_hole"&&v.pcb_hole_ids.push(g),y.type==="pcb_hole"&&v.pcb_hole_ids.push(x)),e.push(v)}}}return e}var SA=[{value:1e12,symbol:"T"},{value:1e9,symbol:"G"},{value:1e6,symbol:"M"},{value:1e3,symbol:"k"},{value:1,symbol:""},{value:.001,symbol:"m"},{value:1e-6,symbol:"\xB5"},{value:1e-9,symbol:"n"},{value:1e-12,symbol:"p"}];function gi(n){if(n==null)return"";if(n===0)return"0";let e=Math.abs(n),t=SA.find(s=>{let o=e/s.value;return o>=1&&o<1e3})||SA[SA.length-1],r=(n/t.value).toPrecision(3);return r.includes(".")&&!/\.0+$/.test(r)&&(r=r.replace(/0+$/,"")),r=r.replace(/\.0+$/,""),`${r}${t.symbol}`}wt();wt();J();Oe();Ig();var w9t=class{constructor(){d(this,"MAX_ITERATIONS",1e5);d(this,"solved",!1);d(this,"failed",!1);d(this,"iterations",0);d(this,"progress",0);d(this,"error",null);d(this,"activeSubSolver");d(this,"failedSubSolvers");d(this,"timeToSolve");d(this,"stats",{});d(this,"_setupDone",!1)}setup(){this._setupDone||(this._setup(),this._setupDone=!0)}_setup(){}step(){if(this._setupDone||this.setup(),!this.solved&&!this.failed){this.iterations++;try{this._step()}catch(n){throw this.error=`${this.constructor.name} error: ${n}`,console.error(this.error),this.failed=!0,n}!this.solved&&this.iterations>=this.MAX_ITERATIONS&&this.tryFinalAcceptance(),!this.solved&&this.iterations>=this.MAX_ITERATIONS&&(this.error=`${this.constructor.name} ran out of iterations`,console.error(this.error),this.failed=!0),"computeProgress"in this&&(this.progress=this.computeProgress())}}_step(){}getConstructorParams(){throw new Error("getConstructorParams not implemented")}getOutput(){return null}solve(){let n=Date.now();for(;!this.solved&&!this.failed;)this.step();let e=Date.now();this.timeToSolve=e-n}visualize(){return{lines:[],points:[],rects:[],circles:[]}}tryFinalAcceptance(){}preview(){return{lines:[],points:[],rects:[],circles:[]}}};var FQ=class extends w9t{constructor(e){super();d(this,"startTimeOfPhase",{});d(this,"endTimeOfPhase",{});d(this,"timeSpentOnPhase",{});d(this,"firstIterationOfPhase",{});d(this,"currentPipelineStepIndex",0);d(this,"inputProblem");d(this,"pipelineOutputs",{});this.inputProblem=e,this.MAX_ITERATIONS=1e6}_step(){let e=this.pipelineDef[this.currentPipelineStepIndex];if(!e){this.solved=!0;return}if(this.activeSubSolver){if(this.activeSubSolver.step(),this.activeSubSolver.solved){this.endTimeOfPhase[e.solverName]=performance.now(),this.timeSpentOnPhase[e.solverName]=this.endTimeOfPhase[e.solverName]-this.startTimeOfPhase[e.solverName];let i=this.activeSubSolver.getOutput();i!==null&&(this.pipelineOutputs[e.solverName]=i),e.onSolved?.(this),this.activeSubSolver=null,this.currentPipelineStepIndex++}else this.activeSubSolver.failed&&(this.error=this.activeSubSolver?.error,this.failed=!0,this.activeSubSolver=null);return}let t=e.getConstructorParams(this);this.activeSubSolver=new e.solverClass(...t),this[e.solverName]=this.activeSubSolver,this.timeSpentOnPhase[e.solverName]=0,this.startTimeOfPhase[e.solverName]=performance.now(),this.firstIterationOfPhase[e.solverName]=this.iterations}solveUntilPhase(e){for(;this.getCurrentPhase().toLowerCase()!==e.toLowerCase()&&(this.step(),!(this.failed||this.solved)););}getCurrentPhase(){return this.pipelineDef[this.currentPipelineStepIndex]?.solverName??"none"}getPhaseProgress(){let e=this.pipelineDef.length;if(e===0)return 1;let t=this.activeSubSolver?.progress??0;return(this.currentPipelineStepIndex+t)/e}getPhaseStats(){let e={};for(let t of this.pipelineDef){let i=this.timeSpentOnPhase[t.solverName]||0,r=this.firstIterationOfPhase[t.solverName]||0,s=this.iterations,o=t.solverName===this.getCurrentPhase()?s-r:0,a=this.currentPipelineStepIndex>this.pipelineDef.findIndex(c=>c.solverName===t.solverName);e[t.solverName]={timeSpent:i,iterations:o,completed:a}}return e}visualize(){if(!this.solved&&this.activeSubSolver)return this.activeSubSolver.visualize();let e=this.pipelineDef.map((t,i)=>{let s=this[t.solverName]?.visualize();if(!s)return null;for(let o of s.rects??[])o.step=i;for(let o of s.points??[])o.step=i;for(let o of s.circles??[])o.step=i;for(let o of s.texts??[])o.step=i;for(let o of s.lines??[])o.step=i;return s}).filter(Boolean);return e.length===0?{points:[],rects:[],lines:[],circles:[],texts:[]}:e.length===1?e[0]:{points:e.flatMap(t=>t.points||[]),rects:e.flatMap(t=>t.rects||[]),lines:e.flatMap(t=>t.lines||[]),circles:e.flatMap(t=>t.circles||[]),texts:e.flatMap(t=>t.texts||[])}}preview(){return this.activeSubSolver?this.activeSubSolver.preview():super.preview()}computeProgress(){return this.getPhaseProgress()}getStepOutput(e){return this.pipelineOutputs[e]}getAllOutputs(){return{...this.pipelineOutputs}}hasStepOutput(e){return e in this.pipelineOutputs}getSolver(e){return this[e]}};var S9t=n=>{let e=n.board_edge_margin??0;if(n.outline&&n.outline.length>0){let r=new L.Polygon(n.outline.map(s=>L.point(s.x,s.y)));return r.orientation()===L.ORIENTATION.CW&&r.reverse(),r}let{bounds:t}=n,i={minX:t.minX+e,minY:t.minY+e,maxX:t.maxX-e,maxY:t.maxY-e};return i.minX>=i.maxX||i.minY>=i.maxY?new L.Polygon:new L.Polygon(new L.Box(i.minX,i.minY,i.maxX,i.maxY).toPoints())},PA=(n,e=32)=>{let t=[];for(let i=0;i<e;i++){let r=i/e*2*Math.PI;t.push(new L.Point(n.center.x+n.r*Math.cos(r),n.center.y+n.r*Math.sin(r)))}return new L.Polygon(t)},P9t=n=>n.shape==="rect",k9t=n=>n.shape==="trace",T9t=n=>n.shape==="circle",E9t=n=>n.shape==="polygon",M9t=(n,e,t,i)=>{let r=[],{padMargin:s,traceMargin:o,board_edge_margin:a,cutoutMargin:c}=t;if(i&&i.length>0&&a&&a>0){let l=new L.Polygon(i.map(p=>L.point(p.x,p.y)));l.area()<0&&l.reverse();let u=l.vertices;for(let p=0;p<u.length;p++){let f=u[p===0?u.length-1:p-1],y=u[p],g=u[(p+1)%u.length];if(!f||!y||!g)continue;let x=new L.Vector(f,y),v=new L.Vector(y,g),S=x.cross(v),P=new L.Circle(y,a);if(r.push(PA(P)),S<0){let T=new L.Box(y.x-a,y.y-a,y.x+a,y.y+a);r.push(new L.Polygon(T.toPoints()))}}for(let p=0;p<u.length;p++){let f=u[p],y=u[(p+1)%u.length];if(!f||!y)continue;let g=Math.hypot(f.x-y.x,f.y-y.y);if(g===0)continue;let x=a*2,v=(f.x+y.x)/2,S=(f.y+y.y)/2,P=Math.atan2(y.y-f.y,y.x-f.x)*180/Math.PI,T=g/2,k=x/2,C=P*Math.PI/180,E=Math.cos(C),N=Math.sin(C),A=[{x:-T,y:-k},{x:T,y:-k},{x:T,y:k},{x:-T,y:k}].map(R=>({x:v+R.x*E-R.y*N,y:S+R.x*N+R.y*E}));r.push(new L.Polygon(A.map(R=>L.point(R.x,R.y))))}}for(let l of n){if(l.connectivityKey===e)continue;let p=l.connectivityKey.startsWith("hole:")||l.connectivityKey.startsWith("cutout:");if(T9t(l)){let f=p?c??0:s,y=new L.Circle(new L.Point(l.x,l.y),l.radius+f);r.push(PA(y));continue}if(P9t(l)){let f=p?c??0:s,{bounds:y}=l,g=new L.Box(y.minX-f,y.minY-f,y.maxX+f,y.maxY+f);r.push(new L.Polygon(g.toPoints()));continue}if(E9t(l)){let f=p?c??0:0,y=new Set,g=l.points.filter(T=>{let k=`${T.x},${T.y}`;return y.has(k)?!1:(y.add(k),!0)});if(g.length<3)continue;let x=new L.Polygon(g.map(T=>L.point(T.x,T.y)));if(Math.abs(x.area())<1e-9)continue;if(f<=0){r.push(x);continue}x.area()>0&&x.reverse();let v=[],S=x.vertices;for(let T=0;T<S.length;T++){let k=S[T],C=S[(T+1)%S.length],E=L.segment(k,C);if(E.length===0)continue;let N=L.line(E.start,E.end),I=N.norm,A=N.translate(I.multiply(-f));v.push(A)}let P=[];for(let T=0;T<v.length;T++){let k=v[T],C=v[(T+1)%v.length],E=k.intersect(C);E.length>0&&P.push(E[0])}P.length>=3&&r.push(new L.Polygon(P));continue}if(k9t(l)){for(let f of l.segments){let y=new L.Circle(new L.Point(f.x,f.y),l.width/2+o);r.push(PA(y))}for(let f=0;f<l.segments.length-1;f++){let y=l.segments[f],g=l.segments[f+1];if(!y||!g)continue;let x=Math.hypot(y.x-g.x,y.y-g.y);if(x===0)continue;let v=l.width+o*2,S=(y.x+g.x)/2,P=(y.y+g.y)/2,T=Math.atan2(g.y-y.y,g.x-y.x)*180/Math.PI,k=x/2,C=v/2,E=T*Math.PI/180,N=Math.cos(E),I=Math.sin(E),R=[{x:-k,y:-C},{x:k,y:-C},{x:k,y:C},{x:-k,y:C}].map(j=>({x:S+j.x*N-j.y*I,y:P+j.x*I+j.y*N}));r.push(new L.Polygon(R.map(j=>L.point(j.x,j.y))))}continue}}return{polygonsToSubtract:r}},zQ=n=>n.edges.map(e=>{let t={x:e.start.x,y:e.start.y};if(e.isArc){let i=Math.tan(e.shape.sweep/4);Math.abs(i)>1e-9&&(t.bulge=i)}return t}),C9t=n=>{let e=[],t=Array.isArray(n)?n:[n];for(let i of t){let r=i.splitToIslands();for(let s of r){if(s.isEmpty())continue;let o=[...s.faces],a=o.find(p=>p.orientation()===L.ORIENTATION.CCW),c=o.filter(p=>p.orientation()===L.ORIENTATION.CW);if(!a)continue;a.reverse();let l=zQ(a),u=c.map(p=>(p.reverse(),{vertices:zQ(p)}));e.push({outer_ring:{vertices:l},inner_rings:u})}}return e},DQ=class extends FQ{constructor(e){super(e);d(this,"pipelineDef",[]);this.input=e}getOutput(){let e=[];for(let t of this.input.regionsForPour){let i=S9t(t),r=this.input.pads.filter(c=>c.layer===t.layer),{polygonsToSubtract:s}=M9t(r,t.connectivityKey,{padMargin:t.padMargin,traceMargin:t.traceMargin,board_edge_margin:t.board_edge_margin,cutoutMargin:t.cutout_margin},t.outline),o=i;for(let c of s){let l=Array.isArray(o)?o:[o],u=[];for(let p of l){let f=L.BooleanOperations.subtract(p,c);f&&(Array.isArray(f)?u.push(...f.filter(y=>!y.isEmpty())):f.isEmpty()||u.push(f))}o=u}let a=C9t(o);e.push(...a)}return{brep_shapes:e}}},$Q=(n,e)=>{let t=n.filter(T=>T.type==="source_port"),i=n.filter(T=>T.type==="pcb_port"),r=n.filter(T=>T.type==="source_trace"),s=n.filter(T=>T.type==="pcb_trace"),o=n.filter(T=>T.type==="source_net"),a=n.find(T=>T.type==="pcb_board");if(!a)throw new Error("No pcb_board found in circuit json");let c=Object.fromEntries(t.map(T=>[T.source_port_id,T.subcircuit_connectivity_map_key])),l=Object.fromEntries(i.map(T=>[T.pcb_port_id,c[T.source_port_id]])),u={};for(let T of i)T.pcb_port_id&&(u[T.pcb_port_id]=l[T.pcb_port_id]);let p=Object.fromEntries(r.map(T=>[T.source_trace_id,T.subcircuit_connectivity_map_key])),f=Object.fromEntries(o.map(T=>[T.source_net_id,T.subcircuit_connectivity_map_key])),y={...p,...f},g=Object.fromEntries(s.map(T=>[T.pcb_trace_id,T.source_trace_id?y[T.source_trace_id]:void 0]).filter(T=>!!T[1])),x=[];for(let T of n)if(T.type==="pcb_smtpad"){let k=T;if(k.layer!==e.layer)continue;let C;k.pcb_port_id&&(C=l[k.pcb_port_id]),C||(C=`unconnected:${k.pcb_smtpad_id}`),k.shape==="rect"?x.push({shape:"rect",padId:k.pcb_smtpad_id,layer:k.layer,connectivityKey:C,bounds:{minX:k.x-k.width/2,minY:k.y-k.height/2,maxX:k.x+k.width/2,maxY:k.y+k.height/2}}):k.shape==="circle"&&x.push({shape:"circle",padId:k.pcb_smtpad_id,layer:k.layer,connectivityKey:C,x:k.x,y:k.y,radius:k.radius})}else if(T.type==="pcb_plated_hole"){let k=T;if(k.shape!=="circle"||!k.layers.includes(e.layer))continue;let C=u[k.pcb_plated_hole_id];C||(C=`unconnected-plated-hole:${k.pcb_plated_hole_id}`),x.push({shape:"circle",padId:k.pcb_plated_hole_id,layer:e.layer,connectivityKey:C,x:k.x,y:k.y,radius:k.outer_diameter/2})}else if(T.type==="pcb_hole"){let k=T;if(k.hole_shape!=="circle")continue;x.push({shape:"circle",padId:k.pcb_hole_id,layer:e.layer,connectivityKey:`hole:${k.pcb_hole_id}`,x:k.x,y:k.y,radius:k.hole_diameter/2})}else if(T.type==="pcb_cutout"){let k=T;k.shape==="rect"?x.push({shape:"rect",padId:k.pcb_cutout_id,layer:e.layer,connectivityKey:`cutout:${k.pcb_cutout_id}`,bounds:{minX:k.center.x-k.width/2,minY:k.center.y-k.height/2,maxX:k.center.x+k.width/2,maxY:k.center.y+k.height/2}}):k.shape==="circle"?x.push({shape:"circle",padId:k.pcb_cutout_id,layer:e.layer,connectivityKey:`cutout:${k.pcb_cutout_id}`,x:k.center.x,y:k.center.y,radius:k.radius}):k.shape==="polygon"&&x.push({shape:"polygon",padId:k.pcb_cutout_id,layer:e.layer,connectivityKey:`cutout:${k.pcb_cutout_id}`,points:k.points})}else if(T.type==="pcb_via"){let k=T;if(!k.layers.includes(e.layer))continue;let C=k.subcircuit_connectivity_map_key??g[k.pcb_trace_id??""]??`unconnected-via:${k.pcb_via_id}`;x.push({shape:"circle",padId:k.pcb_via_id,layer:e.layer,connectivityKey:C,x:k.x,y:k.y,radius:k.outer_diameter/2})}else if(T.type==="pcb_trace"){let k=T;if(!k.source_trace_id)continue;let C=y[k.source_trace_id];if(!C)continue;let E=[],N=null,I=()=>{E.length>1&&x.push({shape:"trace",padId:`${k.pcb_trace_id}-${x.length}`,layer:e.layer,connectivityKey:C,segments:E,width:N}),E=[],N=null};for(let A of k.route){let R=A;R.route_type==="wire"&&R.layer===e.layer?(N===null&&(N=R.width),E.push({x:R.x,y:R.y})):I()}I()}let{width:v,height:S}=a,P=[{shape:"rect",layer:e.layer,bounds:{minX:-v/2,minY:-S/2,maxX:v/2,maxY:S/2},outline:a.outline,connectivityKey:e.pour_connectivity_key,padMargin:e.pad_margin,traceMargin:e.trace_margin,board_edge_margin:e.board_edge_margin??0,cutout_margin:e.cutout_margin}];return{pads:x,regionsForPour:P}};Pa();wt();Oe();var Jnt=Ht(Hs(),1);var r9=Ht(An(),1),X_=Ht(Hs(),1),Ige=Ht(Hs(),1);var Id=Ht(kd(),1);var Qnt=Ht(kd(),1),tit=Ht(kd(),1);var eit=Ht(kd(),1);var nit=Ht(kd(),1);var iit=Ht(kd(),1),rit=Ht(Hs(),1);var IRt=Object.defineProperty,NRt=(n,e)=>{for(var t in e)IRt(n,t,{get:e[t],enumerable:!0})},ket={};NRt(ket,{AnalogSimulation:()=>Znt,Battery:()=>Int,Board:()=>nnt,Breakout:()=>wnt,BreakoutPoint:()=>Snt,CadAssembly:()=>Bet,CadModel:()=>jet,Capacitor:()=>d9,Chip:()=>Y1,Constraint:()=>pnt,CopperPour:()=>Cnt,Crystal:()=>Lnt,Cutout:()=>$1,Diode:()=>f9,FabricationNoteDimension:()=>mnt,FabricationNotePath:()=>dnt,FabricationNoteRect:()=>hnt,FabricationNoteText:()=>fnt,Footprint:()=>zet,Fuse:()=>snt,Group:()=>_l,Hole:()=>V_,Inductor:()=>_9,Jumper:()=>ont,Keepout:()=>HS,Led:()=>cnt,Mosfet:()=>znt,Net:()=>a9,NetLabel:()=>Pnt,NormalComponent:()=>Gn,Panel:()=>int,PcbNoteDimension:()=>bnt,PcbNoteLine:()=>_nt,PcbNotePath:()=>xnt,PcbNoteRect:()=>ynt,PcbNoteText:()=>gnt,PcbTrace:()=>l9,PinHeader:()=>Nnt,Pinout:()=>rnt,PlatedHole:()=>U_,Port:()=>Vi,Potentiometer:()=>Rnt,PowerSource:()=>lnt,PrimitiveComponent:()=>Te,PushButton:()=>Ont,Renderable:()=>s9,Resistor:()=>m9,Resonator:()=>Ant,SchematicArc:()=>Xnt,SchematicBox:()=>Vnt,SchematicCell:()=>Wnt,SchematicCircle:()=>Unt,SchematicLine:()=>Bnt,SchematicRect:()=>Ynt,SchematicRow:()=>Hnt,SchematicTable:()=>Gnt,SchematicText:()=>jnt,SilkscreenCircle:()=>knt,SilkscreenLine:()=>Ent,SilkscreenPath:()=>c9,SilkscreenRect:()=>Tnt,SilkscreenText:()=>JS,SmtPad:()=>D1,SolderJumper:()=>ant,Subcircuit:()=>vnt,Switch:()=>Dnt,Symbol:()=>qnt,TestPoint:()=>$nt,Trace:()=>oo,TraceHint:()=>p9,Transistor:()=>Fnt,Via:()=>Mnt,VoltageProbe:()=>Knt,VoltageSource:()=>unt});var ARt=(0,Met.default)("tscircuit:renderable"),Xa=["ReactSubtreesRender","InflateSubcircuitCircuitJson","SourceNameDuplicateComponentRemoval","PcbFootprintStringRender","InitializePortsFromChildren","CreateNetsFromProps","AssignFallbackProps","CreateTracesFromProps","CreateTracesFromNetLabels","CreateTraceHintsFromProps","SourceGroupRender","AssignNameToUnnamedComponents","SourceRender","SourceParentAttachment","PortMatching","OptimizeSelectorCache","SourceTraceRender","SourceAddConnectivityMapKey","SourceDesignRuleChecks","SimulationRender","SchematicComponentRender","SchematicPortRender","SchematicPrimitiveRender","SchematicComponentSizeCalculation","SchematicLayout","SchematicTraceRender","SchematicReplaceNetLabelsWithSymbols","PcbComponentRender","PcbPrimitiveRender","PcbFootprintLayout","PcbPortRender","PcbPortAttachment","PcbComponentSizeCalculation","PcbComponentAnchorAlignment","PcbLayout","PcbBoardAutoSize","PcbTraceHintRender","PcbManualTraceRender","PcbTraceRender","PcbRouteNetIslands","PcbCopperPourRender","PcbDesignRuleChecks","SilkscreenOverlapAdjustment","CadModelRender","PartsEngineRender","SimulationSpiceEngineRender"],RRt={PcbFootprintLayout:["PcbFootprintStringRender"],PcbComponentSizeCalculation:["PcbFootprintStringRender"],PcbLayout:["PcbFootprintStringRender"],PcbBoardAutoSize:["PcbFootprintStringRender"],PcbTraceHintRender:["PcbFootprintStringRender"],PcbManualTraceRender:["PcbFootprintStringRender"],PcbCopperPourRender:["PcbFootprintStringRender","PcbTraceRender","PcbRouteNetIslands"],PcbTraceRender:["PcbFootprintStringRender"],PcbRouteNetIslands:["PcbFootprintStringRender"],PcbDesignRuleChecks:["PcbFootprintStringRender"],SilkscreenOverlapAdjustment:["PcbFootprintStringRender"],CadModelRender:["PcbFootprintStringRender"],PartsEngineRender:["PcbFootprintStringRender"],PcbComponentAnchorAlignment:["PcbFootprintStringRender"]},ORt=0,s9=class Cet{constructor(e){d(this,"renderPhaseStates");d(this,"shouldBeRemoved",!1);d(this,"children");d(this,"isPcbPrimitive",!1);d(this,"isSchematicPrimitive",!1);d(this,"_renderId");d(this,"_currentRenderPhase",null);d(this,"_asyncEffects",[]);d(this,"parent",null);this._renderId=`${ORt++}`,this.children=[],this.renderPhaseStates={};for(let t of Xa)this.renderPhaseStates[t]={initialized:!1,dirty:!1}}_markDirty(e){this.renderPhaseStates[e].dirty=!0;let t=Xa.indexOf(e);for(let i=t+1;i<Xa.length;i++)this.renderPhaseStates[Xa[i]].dirty=!0;this.parent?._markDirty&&this.parent._markDirty(e)}_queueAsyncEffect(e,t){let i={promise:t(),phase:this._currentRenderPhase,effectName:e,complete:!1};this._asyncEffects.push(i),"root"in this&&this.root&&this.root.emit("asyncEffect:start",{effectName:e,componentDisplayName:this.getString(),phase:i.phase}),i.promise.then(()=>{i.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:e,componentDisplayName:this.getString(),phase:i.phase})}).catch(r=>{console.error(`Async effect error in ${i.phase} "${e}":
249
- ${r.stack}`),i.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:e,componentDisplayName:this.getString(),phase:i.phase,error:r.toString()})})}_emitRenderLifecycleEvent(e,t){ARt(`${e}:${t} ${this.getString()}`);let i=`renderable:renderLifecycle:${e}:${t}`,r={renderId:this._renderId,componentDisplayName:this.getString(),type:i};"root"in this&&this.root&&(this.root.emit(i,r),this.root.emit("renderable:renderLifecycle:anyEvent",{...r,type:i}))}getString(){return this.constructor.name}_hasIncompleteAsyncEffects(){return this._asyncEffects.some(e=>!e.complete)}_hasIncompleteAsyncEffectsInSubtreeForPhase(e){for(let t of this._asyncEffects)if(!t.complete&&t.phase===e)return!0;for(let t of this.children)if(t._hasIncompleteAsyncEffectsInSubtreeForPhase(e))return!0;return!1}getCurrentRenderPhase(){return this._currentRenderPhase}getRenderGraph(){return{id:this._renderId,currentPhase:this._currentRenderPhase,renderPhaseStates:this.renderPhaseStates,shouldBeRemoved:this.shouldBeRemoved,children:this.children.map(e=>e.getRenderGraph())}}getTopLevelRenderable(){let e=this;for(;e.parent&&e.parent instanceof Cet;)e=e.parent;return e}runRenderCycle(){for(let e of Xa)this.runRenderPhaseForChildren(e),this.runRenderPhase(e)}runRenderPhase(e){this._currentRenderPhase=e;let t=this.renderPhaseStates[e],i=t.initialized,r=t.dirty;if(!i&&this.shouldBeRemoved)return;if(this.shouldBeRemoved&&i){this._emitRenderLifecycleEvent(e,"start"),this?.[`remove${e}`]?.(),t.initialized=!1,t.dirty=!1,this._emitRenderLifecycleEvent(e,"end");return}let s=Xa.indexOf(e)-1;if(s>=0){let a=Xa[s];if(this._asyncEffects.filter(l=>l.phase===a).some(l=>!l.complete))return}let o=RRt[e]||[];if(o.length>0){let a=this.getTopLevelRenderable();for(let c of o)if(a._hasIncompleteAsyncEffectsInSubtreeForPhase(c))return}if(this._emitRenderLifecycleEvent(e,"start"),i){r&&(this?.[`update${e}`]?.(),t.dirty=!1),this._emitRenderLifecycleEvent(e,"end");return}t.dirty=!1,this?.[`doInitial${e}`]?.(),t.initialized=!0,this._emitRenderLifecycleEvent(e,"end")}runRenderPhaseForChildren(e){for(let t of this.children)t.runRenderPhaseForChildren(e),t.runRenderPhase(e)}renderError(e){throw typeof e=="string"?new Error(e):new Error(JSON.stringify(e,null,2))}},GS={},Iet=n=>{let e=Object.fromEntries(Object.entries(n).map(([t,i])=>[t.toLowerCase(),i]));Object.assign(GS,n),Object.assign(GS,e)},LRt=class extends Error{constructor(n,e,t){let i,r=Object.keys(t).filter(c=>c!=="_errors"),s=[],o=e.pinLabels;if(o)for(let[c,l]of Object.entries(o)){let u=Array.isArray(l)?l:[l];for(let p of u)typeof p=="string"&&(p.startsWith(" ")||p.endsWith(" "))&&s.push(`pinLabels.${c} ("${p}" has leading or trailing spaces)`)}let a=r.map(c=>c==="pinLabels"&&s.length>0?s.join(", "):t[c]._errors[0]?`${c} (${t[c]._errors[0]})`:`${c} (${JSON.stringify(t[c])})`).join(", ");"name"in e?i=`Invalid props for ${n} "${e.name}": ${a}`:"footprint"in e&&typeof e.footprint=="string"?i=`Invalid props for ${n} (unnamed ${e.footprint} component): ${a}`:i=`Invalid props for ${n} (unnamed): ${a}`,super(i),this.componentName=n,this.originalProps=e,this.formattedError=t}};function XA(n,e){let t=e.match(/^#(\w+)/);if(t)return n.props.id===t[1];let i=e.match(/^\.(\w+)/);if(i)return n.isMatchingNameOrAlias(i[1]);let[r,...s]=e.split(/(?=[#.[])/);return r==="pin"&&(r="port"),r&&r!=="*"&&n.lowercaseComponentName!==r.toLowerCase()?!1:s.every(o=>{if(o.startsWith("#"))return n.props.id===o.slice(1);if(o.startsWith("."))return n.isMatchingNameOrAlias(o.slice(1));let a=o.match(/\[(\w+)=['"]?(.+?)['"]?\]/);if(!a)return!0;let[,c,l]=a;return n.props[c].toString()===l})}var o9={isTag:n=>!0,getParent:n=>n.parent,getChildren:n=>n.children,getName:n=>n.lowercaseComponentName,getAttributeValue:(n,e)=>{if(e==="class"&&"getNameAndAliases"in n)return n.getNameAndAliases().join(" ");if(e==="name"&&n._parsedProps?.name)return n._parsedProps.name;if(n._parsedProps&&e in n._parsedProps){let i=n._parsedProps[e];return typeof i=="string"?i:i!=null?String(i):null}if(e in n){let i=n[e];return typeof i=="string"?i:i!=null?String(i):null}let t=n._attributeLowerToCamelNameMap;if(t){let i=t[e];if(i&&i in n){let r=n[i];return typeof r=="string"?r:r!=null?String(r):null}}return null},hasAttrib:(n,e)=>{if(e==="class")return!!n._parsedProps?.name;if(n._parsedProps&&e in n._parsedProps||e in n)return!0;let t=n._attributeLowerToCamelNameMap;if(t){let i=t[e];if(i&&i in n)return!0}return!1},getSiblings:n=>n.parent?n.parent.children:[],prevElementSibling:n=>{if(!n.parent)return null;let e=n.parent.children,t=e.indexOf(n);return t>0?e[t-1]:null},getText:()=>"",removeSubsets:n=>n.filter((e,t)=>!n.some((i,r)=>t!==r&&i!==e&&i.getDescendants().includes(e))),existsOne:(n,e)=>e.some(n),findAll:(n,e)=>{let t=[],i=r=>{n(r)&&t.push(r);for(let s of r.children)i(s)};for(let r of e)i(r);return t},findOne:(n,e)=>{for(let t of e){if(n(t))return t;let i=t.children;if(i.length>0){let r=o9.findOne(n,i);if(r)return r}}return null},equals:(n,e)=>n._renderId===e._renderId,isHovered:n=>!1,isVisited:n=>!1,isActive:n=>!1},FRt={...o9,getChildren:n=>n.children.filter(e=>!e.isSubcircuit)},Jtt={...o9,getChildren:n=>n.children.filter(e=>e.isSubcircuit)},Qtt=n=>{if(/net\.[^\s>]*\./.test(n))throw new Error('Net names cannot contain a period, try using "sel.net..." to autocomplete with conventional net names, e.g. V3_3');if(/net\.[^\s>]*[+-]/.test(n))throw new Error('Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P');if(/net\.[0-9]/.test(n)){let e=n.match(/net\.([^ >]+)/),t=e?e[1]:"";throw new Error(`Net name "${t}" cannot start with a number, try using a prefix like "VBUS1"`)}return n.replace(/ pin(?=[\d.])/g," port").replace(/ subcircuit\./g," group[isSubcircuit=true]").replace(/([^ ])\>([^ ])/g,"$1 > $2").replace(/(^|[ >])(?!pin\.)(?!port\.)(?!net\.)([A-Z][A-Za-z0-9_-]*)\.([A-Za-z0-9_-]+)/g,(e,t,i,r)=>{let s=/^\d+$/.test(r)?`pin${r}`:r;return`${t}.${i} > .${s}`}).trim()},UA={adapter:FRt,cacheResults:!0},Te=class extends s9{constructor(e){super(e);d(this,"parent",null);d(this,"children");d(this,"childrenPendingRemoval");d(this,"props");d(this,"_parsedProps");d(this,"externallyAddedAliases");d(this,"isPrimitiveContainer",!1);d(this,"canHaveTextChildren",!1);d(this,"source_group_id",null);d(this,"source_component_id",null);d(this,"schematic_component_id",null);d(this,"pcb_component_id",null);d(this,"cad_component_id",null);d(this,"fallbackUnassignedName");d(this,"_cachedSelectAllQueries",new Map);d(this,"_cachedSelectOneQueries",new Map);this.children=[],this.childrenPendingRemoval=[],this.props=e??{},this.externallyAddedAliases=[];let i=("partial"in this.config.zodProps?this.config.zodProps.partial({name:!0}):this.config.zodProps).safeParse(e??{});if(i.success)this._parsedProps=i.data;else throw new LRt(this.lowercaseComponentName,this.props,i.error.format())}get config(){return{componentName:"",zodProps:h.object({}).passthrough()}}get componentName(){return this.config.componentName}getInheritedProperty(e){let t=this;for(;t;){if(t._parsedProps&&e in t._parsedProps)return t._parsedProps[e];t=t.parent}if(this.root?.platform&&e in this.root.platform)return this.root.platform[e]}getInheritedMergedProperty(e){let t=this.parent?.getInheritedMergedProperty?.(e),i=this._parsedProps?.[e];return{...t,...i}}get lowercaseComponentName(){return this.componentName.toLowerCase()}get isSubcircuit(){return!!this.props.subcircuit||this.lowercaseComponentName==="group"&&this?.parent?.isRoot}get isGroup(){return this.lowercaseComponentName==="group"}get name(){return this._parsedProps.name??this.fallbackUnassignedName}setProps(e){let t=this.config.zodProps.parse({...this.props,...e}),i=this.props;this.props=t,this._parsedProps=this.config.zodProps.parse(e),this.onPropsChange({oldProps:i,newProps:t,changedProps:Object.keys(e)}),this.parent?.onChildChanged?.(this)}_getPcbRotationBeforeLayout(){let{pcbRotation:e}=this.props;return typeof e=="string"?parseFloat(e):e??null}computePcbPropsTransform(){let{_parsedProps:e}=this,t=this._getPcbRotationBeforeLayout()??0;return mi(Nn(e.pcbX??0,e.pcbY??0),Dc(t*Math.PI/180))}_computePcbGlobalTransformBeforeLayout(){let e=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if(e&&this.props.pcbX===void 0&&this.props.pcbY===void 0){let t=this._getPcbRotationBeforeLayout()??0;return mi(this.parent?._computePcbGlobalTransformBeforeLayout()??Qi(),mi(Nn(e.x,e.y),Dc(t*Math.PI/180)))}if(this.isPcbPrimitive){let t=this.getPrimitiveContainer();if(t&&t._parsedProps.layer==="bottom")return mi(this.parent?._computePcbGlobalTransformBeforeLayout()??Qi(),gB(),this.computePcbPropsTransform())}return mi(this.parent?._computePcbGlobalTransformBeforeLayout()??Qi(),this.computePcbPropsTransform())}getPrimitiveContainer(){return this.isPrimitiveContainer?this:this.parent?.getPrimitiveContainer?.()??null}getParentNormalComponent(){let e=this.parent;for(;e;){if(e.isPrimitiveContainer&&e.doInitialPcbComponentRender)return e;e=e.parent}return null}_getPcbCircuitJsonBounds(){return{center:{x:0,y:0},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getPcbPrimitiveFlippedHelpers(){let e=this.getPrimitiveContainer(),t=e?e._parsedProps.layer==="bottom":!1;return{isFlipped:t,maybeFlipLayer:r=>t?r==="top"?"bottom":"top":r}}_setPositionFromLayout(e){throw new Error(`_setPositionFromLayout not implemented for ${this.componentName}`)}computeSchematicPropsTransform(){let{_parsedProps:e}=this;return mi(Nn(e.schX??0,e.schY??0))}computeSchematicGlobalTransform(){let e=this._getSchematicGlobalManualPlacementTransform(this);return e||mi(this.parent?.computeSchematicGlobalTransform?.()??Qi(),this.computeSchematicPropsTransform())}_getSchematicSymbolName(){let{_parsedProps:e}=this,t=this.config.schematicSymbolName,i={horizontal:0,pos_left:0,neg_right:0,pos_right:180,neg_left:180,pos_top:270,neg_bottom:90,vertical:270,pos_bottom:90,neg_top:90},r=e.schOrientation!==void 0?i[e.schOrientation]:e.schRotation;if(r===void 0&&(r=0),r=r%360,r<0&&(r+=360),e.schRotation!==void 0&&r%90!==0)throw new Error(`Schematic rotation ${e.schRotation} is not supported for ${this.componentName}`);let s=`${t}_horz`,o=`${t}_vert`,a=`${t}_up`,c=`${t}_down`,l=`${t}_left`,u=`${t}_right`;if(u in _i&&r===0)return u;if(a in _i&&r===90)return a;if(l in _i&&r===180)return l;if(c in _i&&r===270)return c;if(s in _i&&(r===0||r===180))return s;if(o in _i&&(r===90||r===270))return o;if(t in _i)return t}_getSchematicSymbolNameOrThrow(){let e=this._getSchematicSymbolName();if(!e)throw new Error(`No schematic symbol found (given: "${this.config.schematicSymbolName}")`);return e}getSchematicSymbol(){let e=this._getSchematicSymbolName();return e?_i[e]??null:null}_getPcbManualPlacementForComponent(e){if(!this.isSubcircuit)return null;let t=this.props.manualEdits;if(!t)return null;let i=t?.pcb_placements;if(!i)return null;for(let r of i)if(XA(e,r.selector)||e.props.name===r.selector)return ze(this._computePcbGlobalTransformBeforeLayout(),r.center);return null}_getSchematicManualPlacementForComponent(e){if(!this.isSubcircuit)return null;let t=this.props.manualEdits;if(!t)return null;let i=t.schematic_placements;if(!i)return null;for(let r of i)if(XA(e,r.selector)||e.props.name===r.selector)return ze(this.computeSchematicGlobalTransform(),r.center);return null}_getSchematicGlobalManualPlacementTransform(e){let t=this.getSubcircuit()?._parsedProps.manualEdits;if(!t)return null;for(let i of t.schematic_placements??[])if((XA(e,i.selector)||e.props.name===i.selector)&&i.relative_to==="group_center")return mi(this.parent?._computePcbGlobalTransformBeforeLayout()??Qi(),Nn(i.center.x,i.center.y));return null}_getGlobalPcbPositionBeforeLayout(){return ze(this._computePcbGlobalTransformBeforeLayout(),{x:0,y:0})}_getGlobalSchematicPositionBeforeLayout(){return ze(this.computeSchematicGlobalTransform(),{x:0,y:0})}get root(){return this.parent?.root??null}onAddToParent(e){this.parent=e}onPropsChange(e){}onChildChanged(e){this.parent?.onChildChanged?.(e)}add(e){let t=e.__text;if(typeof t=="string"){if(this.canHaveTextChildren||t.trim()==="")return;throw new Error(`Invalid JSX Element: Expected a React component but received text "${t}"`)}if(Object.keys(e).length!==0){if(this.lowercaseComponentName==="board"&&e.lowercaseComponentName==="board")throw new Error("Nested boards are not supported");if(e.lowercaseComponentName==="panel")throw new Error("<panel> must be a root-level element");if(!e.onAddToParent)throw new Error(`Invalid JSX Element: Expected a React component but received "${JSON.stringify(e)}"`);e.onAddToParent(this),e.parent=this,this.children.push(e)}}addAll(e){for(let t of e)this.add(t)}remove(e){this.children=this.children.filter(t=>t!==e),this.childrenPendingRemoval.push(e),e.shouldBeRemoved=!0}getSubcircuitSelector(){let e=this.name,t=e?`${this.lowercaseComponentName}.${e}`:this.lowercaseComponentName;return!this.parent||this.parent.isSubcircuit?t:`${this.parent.getSubcircuitSelector()} > ${t}`}getFullPathSelector(){let e=this.name,t=e?`${this.lowercaseComponentName}.${e}`:this.lowercaseComponentName,i=this.parent?.getFullPathSelector?.();return i?`${i} > ${t}`:t}getNameAndAliases(){return[this.name,...this._parsedProps.portHints??[]].filter(Boolean)}isMatchingNameOrAlias(e){return this.getNameAndAliases().includes(e)}isMatchingAnyOf(e){return this.getNameAndAliases().some(t=>e.map(i=>i.toString()).includes(t))}getPcbSize(){throw new Error(`getPcbSize not implemented for ${this.componentName}`)}doesSelectorMatch(e){let t=[this.componentName,this.lowercaseComponentName],i=[this.name].filter(Boolean),r=e.trim().split(/\> /)[0],s=r[0];return r.length>1?!1:!!(e==="*"||e[0]==="#"&&e.slice(1)===this.props.id||e[0]==="."&&i.includes(e.slice(1))||/^[a-zA-Z0-9_]/.test(s)&&t.includes(s))}getSubcircuit(){if(this.isSubcircuit)return this;let e=this.parent?.getSubcircuit?.();if(!e)throw new Error("Component is not inside an opaque group (no board?)");return e}getGroup(){return this.isGroup?this:this.parent?.getGroup?.()??null}doInitialAssignNameToUnnamedComponents(){this._parsedProps.name||(this.fallbackUnassignedName=this.getSubcircuit().getNextAvailableName(this))}doInitialOptimizeSelectorCache(){if(!this.isSubcircuit)return;let e=this.selectAll("port");for(let t of e){let r=(t.getParentNormalComponent?.()??t.parent)?.getNameAndAliases(),s=t.getNameAndAliases();if(r)for(let o of r)for(let a of s){let c=[`.${o} > .${a}`,`.${o} .${a}`];for(let l of c){let u=this._cachedSelectAllQueries.get(l);u?u.push(t):this._cachedSelectAllQueries.set(l,[t])}}}for(let[t,i]of this._cachedSelectAllQueries.entries())i.length===1&&this._cachedSelectOneQueries.set(t,i[0])}selectAll(e){if(this._cachedSelectAllQueries.has(e))return this._cachedSelectAllQueries.get(e);let t=Qtt(e),i=F5(t,this,UA);if(i.length>0)return this._cachedSelectAllQueries.set(e,i),i;let[r,...s]=t.split(" "),o=tw(r,this,{adapter:Jtt});if(!o)return[];let a=o.selectAll(s.join(" "));return this._cachedSelectAllQueries.set(e,a),a}selectOne(e,t){if(this._cachedSelectOneQueries.has(e))return this._cachedSelectOneQueries.get(e);let i=Qtt(e);t?.port&&(t.type="port");let r=null;if(t?.type&&(r=F5(i,this,UA).find(l=>l.lowercaseComponentName===t.type)),r??(r=tw(i,this,UA)),r)return this._cachedSelectOneQueries.set(e,r),r;let[s,...o]=i.split(" "),a=tw(s,this,{adapter:Jtt});return a?(r=a.selectOne(o.join(" "),t),this._cachedSelectOneQueries.set(e,r),r):null}getAvailablePcbLayers(){if(this.isPcbPrimitive){let{maybeFlipLayer:e}=this._getPcbPrimitiveFlippedHelpers();return"layer"in this._parsedProps||this.componentName==="SmtPad"?[e(this._parsedProps.layer??"top")]:"layers"in this._parsedProps?this._parsedProps.layers:this.componentName==="PlatedHole"?this.root?._getBoard()?.allLayers??["top","bottom"]:[]}return[]}getDescendants(){let e=[];for(let t of this.children)e.push(t),e.push(...t.getDescendants());return e}getSelectableDescendants(){let e=[];for(let t of this.children)t.isSubcircuit?e.push(t):(e.push(t),e.push(...t.getSelectableDescendants()));return e}_getPinCount(){return 0}_getSchematicBoxDimensions(){return null}_getSchematicBoxComponentDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;let{_parsedProps:e}=this;return{schWidth:e.schWidth,schHeight:e.schHeight}}renderError(e){if(typeof e=="string")return super.renderError(e);switch(e.type){case"pcb_placement_error":this.root?.db.pcb_placement_error.insert(e);break;case"pcb_via_clearance_error":this.root?.db.pcb_via_clearance_error.insert(e);break;case"pcb_trace_error":this.root?.db.pcb_trace_error.insert(e);break;case"pcb_manual_edit_conflict_warning":this.root?.db.pcb_manual_edit_conflict_warning.insert(e);break;default:this.root?.db.pcb_placement_error.insert(e)}}getString(){let{lowercaseComponentName:e,_parsedProps:t,parent:i}=this;return t?.pinNumber!==void 0&&i?.props?.name&&t?.name?`<${e}#${this._renderId}(pin:${t.pinNumber} .${i?.props.name}>.${t.name}) />`:i?.props?.name&&t?.name?`<${e}#${this._renderId}(.${i?.props.name}>.${t?.name}) />`:t?.from&&t?.to?`<${e}#${this._renderId}(from:${t.from} to:${t?.to}) />`:t?.name?`<${e}#${this._renderId} name=".${t?.name}" />`:t?.portHints?`<${e}#${this._renderId}(${t.portHints.map(r=>`.${r}`).join(", ")}) />`:`<${e}#${this._renderId} />`}get[Symbol.toStringTag](){return this.getString()}[Symbol.for("nodejs.util.inspect.custom")](){return this.getString()}},zRt=class extends Te{constructor(n,e){super(n),this._parsedProps={...n,error:e,type:n.type||"unknown",component_name:n.name,error_type:"source_failed_to_create_component_error",message:e instanceof Error?e.message:String(e),pcbX:n.pcbX,pcbY:n.pcbY,schX:n.schX,schY:n.schY}}get config(){return{componentName:"ErrorPlaceholder",zodProps:h.object({}).passthrough()}}doInitialSourceRender(){if(this.root?.db){let n=this._getGlobalPcbPositionBeforeLayout(),e=this._getGlobalSchematicPositionBeforeLayout();this.root.db.source_failed_to_create_component_error.insert({component_name:this._parsedProps.component_name,error_type:"source_failed_to_create_component_error",message:`Could not create ${this._parsedProps.componentType??"component"}${this._parsedProps.name?` "${this._parsedProps.name}"`:""}. ${this._parsedProps.error?.formattedError?._errors?.join("; ")||this._parsedProps.message}`,pcb_center:n,schematic_center:e})}}};function DRt(n,e){return new zRt(n,e)}function $Rt(n,e){let t=n;return t.__tsci={...e},n}var jRt={supportsMutation:!0,createInstance(n,e){let t=GS[n];if(!t)throw Object.keys(GS).length===0?new Error("No components registered in catalogue, did you forget to import lib/register-catalogue in your test file?"):new Error(`Unsupported component type "${n}". No element with this name is registered in the @tscircuit/core catalogue. Check for typos or see https://docs.tscircuit.com/category/built-in-elements for a list of valid components. To add your own component, see docs/CREATING_NEW_COMPONENTS.md`);try{return $Rt(new t(e),{})}catch(i){return DRt({...e,componentType:n},i)}},createTextInstance(n){return{__text:n}},appendInitialChild(n,e){n.add(e)},appendChild(n,e){n.add(e)},appendChildToContainer(n,e){n.add(e)},finalizeInitialChildren(){return!1},prepareUpdate(){return null},shouldSetTextContent(){return!1},getRootHostContext(){return{}},getChildHostContext(){return{}},prepareForCommit(){return null},resetAfterCommit(){},commitMount(){},commitUpdate(){},removeChild(){},clearContainer(){},supportsPersistence:!1,getPublicInstance(n){return n},preparePortalMount(n){throw new Error("Function not implemented.")},scheduleTimeout(n,e){throw new Error("Function not implemented.")},cancelTimeout(n){throw new Error("Function not implemented.")},noTimeout:void 0,isPrimaryRenderer:!1,getInstanceFromNode(n){throw new Error("Function not implemented.")},beforeActiveInstanceBlur(){throw new Error("Function not implemented.")},afterActiveInstanceBlur(){throw new Error("Function not implemented.")},prepareScopeUpdate:(n,e)=>{throw new Error("Function not implemented.")},getInstanceFromScope:n=>{throw new Error("Function not implemented.")},detachDeletedInstance:n=>{throw new Error("Function not implemented.")},getCurrentEventPriority:()=>US.DefaultEventPriority,getCurrentUpdatePriority:()=>US.DefaultEventPriority,resolveUpdatePriority:()=>US.DefaultEventPriority,setCurrentUpdatePriority:()=>{},maySuspendCommit:()=>!1,supportsHydration:!1},jS=(0,Eet.default)(jRt),Net=n=>{let e={children:[],props:{name:"$root"},add(s){s.parent=this,this.children.push(s)},computePcbGlobalTransform(){return Qi()}},t=[],i=jS.createContainer(e,0,null,!1,null,"tsci",s=>{console.log("Error in createContainer"),console.error(s),t.push(s)},null);if(jS.updateContainerSync(n,i,null,()=>{}),jS.flushSyncWork(),t.length>0)throw t[0];let r=jS.getPublicRootInstance(i);return r||e.children[0]},j1=(n,e)=>{if(typeof n=="number")return n;if(n.startsWith("pin"))return Number(n.slice(3));if(!e)throw new Error(`No pin labels provided and pin number or label is not a number: "${n}"`);for(let t in e)if((Array.isArray(e[t])?e[t]:[e[t]]).includes(n))return Number(t.replace("pin",""));throw new Error(`No pin labels provided and pin number or label is not a number: "${n}"`)},BRt=(n,e)=>{if(!n)return;let t={},i={};for(let[r,s]of Object.entries(n)){let o=j1(r,e);i[o]={...i[o],...s}}for(let[r,s]of Object.entries(i)){let o=`pin${r}`;t[o]={bottom_margin:s.bottomMargin,left_margin:s.leftMargin,right_margin:s.rightMargin,top_margin:s.topMargin}}return t},YRt=n=>{if(n){if("leftSide"in n||"rightSide"in n||"topSide"in n||"bottomSide"in n)return{left_side:n.leftSide,right_side:n.rightSide,top_side:n.topSide,bottom_side:n.bottomSide};if("leftPinCount"in n||"rightPinCount"in n||"topPinCount"in n||"bottomPinCount"in n)return{left_size:n.leftPinCount,right_size:n.rightPinCount,top_size:n.topPinCount,bottom_size:n.bottomPinCount};if("leftSize"in n||"rightSize"in n||"topSize"in n||"bottomSize"in n)return{left_size:n.leftSize,right_size:n.rightSize,top_size:n.topSize,bottom_size:n.bottomSize}}};function Aet(n){let e=[];for(let t=0;t<n.length-1;t++)e.push([n[t],n[t+1]]);return e}var XRt=h.object({name:h.string().refine(n=>!/[+-]/.test(n),'Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P')}),a9=class extends Te{constructor(){super(...arguments);d(this,"source_net_id");d(this,"subcircuit_connectivity_map_key",null)}get config(){return{componentName:"Net",zodProps:XRt}}getPortSelector(){return`net.${this.props.name}`}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=t.name.startsWith("GND"),r=t.name.startsWith("V"),s=e.source_net.insert({name:t.name,member_source_group_ids:[],is_ground:i,is_power:r,is_positive_voltage_source:r});this.source_net_id=s.source_net_id}doInitialSourceParentAttachment(){let e=this.getSubcircuit();if(!e)return;let{db:t}=this.root;t.source_net.update(this.source_net_id,{subcircuit_id:e.subcircuit_id})}getAllConnectedPorts(){let e=this.getSubcircuit().selectAll("port"),t=[];for(let i of e){let r=i._getDirectlyConnectedTraces();for(let s of r)if(s._isExplicitlyConnectedToNet(this)){t.push(i);break}}return t}_getAllDirectlyConnectedTraces(){let e=this.getSubcircuit().selectAll("trace"),t=[];for(let i of e)i._isExplicitlyConnectedToNet(this)&&t.push(i);return t}doInitialPcbRouteNetIslands(){if(this.root?.pcbDisabled||this.getSubcircuit()._parsedProps.routingDisabled||this.getSubcircuit()._getAutorouterConfig().groupMode!=="sequential-trace")return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getAllDirectlyConnectedTraces().filter(o=>(o._portsRoutedOnPcb?.length??0)>0),r=[];for(let o of i){let a=o._portsRoutedOnPcb,c=r.find(l=>a.some(u=>l.ports.includes(u)));if(!c){r.push({ports:[...a],traces:[o]});continue}c.traces.push(o),c.ports.push(...a)}if(r.length===0)return;let s=Aet(r);for(let[o,a]of s){let c=o.ports.map(S=>S._getGlobalPcbPositionBeforeLayout()),l=a.ports.map(S=>S._getGlobalPcbPositionBeforeLayout()),u=1/0,p=[-1,-1];for(let S=0;S<c.length;S++){let P=c[S];for(let T=0;T<l.length;T++){let k=l[T],C=Math.sqrt((P.x-k.x)**2+(P.y-k.y)**2);C<u&&(u=C,p=[S,T])}}let f=o.ports[p[0]],y=a.ports[p[1]],g=e.toArray().filter(S=>S.type==="pcb_smtpad"||S.type==="pcb_trace"||S.type==="pcb_plated_hole"||S.type==="pcb_hole"||S.type==="source_port"||S.type==="pcb_port"),{solution:x}=sH(g.concat([{type:"source_trace",source_trace_id:"__net_trace_tmp",connected_source_port_ids:[f.source_port_id,y.source_port_id]}])),v=x[0];if(!v){this.renderError({pcb_trace_error_id:"",pcb_trace_id:"__net_trace_tmp",pcb_component_ids:[f.pcb_component_id,y.pcb_component_id].filter(Boolean),pcb_port_ids:[f.pcb_port_id,y.pcb_port_id].filter(Boolean),type:"pcb_trace_error",error_type:"pcb_trace_error",message:`Failed to route net islands for "${this.getString()}"`,source_trace_id:"__net_trace_tmp"});return}e.pcb_trace.insert(v)}}renderError(e){if(typeof e=="string")return super.renderError(e);this.root?.db.pcb_trace_error.insert(e)}},KS=(n,e)=>{for(let t of e)if(typeof t=="string"&&t.startsWith("net.")){if(/net\.[^\s>]*\./.test(t))throw new Error('Net names cannot contain a period, try using "sel.net..." to autocomplete with conventional net names, e.g. V3_3');if(/net\.[^\s>]*[+-]/.test(t))throw new Error('Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P');if(/net\.[0-9]/.test(t)){let r=t.split("net.")[1];throw new Error(`Net name "${r}" cannot start with a number, try using a prefix like "VBUS1"`)}let i=n.getSubcircuit();if(!i.selectOne(t)){let r=new a9({name:t.split("net.")[1]});i.add(r)}}},D1=class extends Te{constructor(){super(...arguments);d(this,"pcb_smtpad_id",null);d(this,"matchedPort",null);d(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SmtPad",zodProps:NH}}getPcbSize(){let{_parsedProps:e}=this;if(e.shape==="circle")return{width:e.radius*2,height:e.radius*2};if(e.shape==="rect")return{width:e.width,height:e.height};if(e.shape==="rotated_rect"){let i=(e.ccwRotation??0)*Math.PI/180,r=Math.cos(i),s=Math.sin(i),o=Math.abs(e.width*r)+Math.abs(e.height*s),a=Math.abs(e.width*s)+Math.abs(e.height*r);return{width:o,height:a}}if(e.shape==="polygon"){let t=e.points,i=t.map(l=>l.x),r=t.map(l=>l.y),s=Math.min(...i),o=Math.max(...i),a=Math.min(...r),c=Math.max(...r);return{width:o-s,height:c-a}}if(e.shape==="pill")return{width:e.width,height:e.height};throw new Error(`getPcbSize for shape "${e.shape}" not implemented for ${this.componentName}`)}doInitialPortMatching(){let e=this.getPrimitiveContainer()?.selectAll("port");if(this.props.portHints){for(let t of e)if(t.isMatchingAnyOf(this.props.portHints)){this.matchedPort=t,t.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=t.coveredWithSolderMask??!1,r=!i;if(!t.portHints)return;let s=this.getSubcircuit(),o=this._getGlobalPcbPositionBeforeLayout(),a=this._computePcbGlobalTransformBeforeLayout(),u=(Js(this._computePcbGlobalTransformBeforeLayout()).rotation.angle*180/Math.PI%360+360)%360,p=.01,f=Math.abs(u)<p||Math.abs(u-180)<p||Math.abs(u-360)<p,y=Math.abs(u-90)<p||Math.abs(u-270)<p,g=Math.abs(u-360)<p?0:u,x=g,{maybeFlipLayer:v,isFlipped:S}=this._getPcbPrimitiveFlippedHelpers();S&&(g=(360-g+360)%360);let P=null,T=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id;if(t.shape==="circle")P=e.pcb_smtpad.insert({pcb_component_id:T,pcb_port_id:this.matchedPort?.pcb_port_id,layer:v(t.layer??"top"),shape:"circle",radius:t.radius,port_hints:t.portHints.map(k=>k.toString()),is_covered_with_solder_mask:i,x:o.x,y:o.y,subcircuit_id:s?.subcircuit_id??void 0}),r&&e.pcb_solder_paste.insert({layer:P.layer,shape:"circle",radius:P.radius*.7,x:P.x,y:P.y,pcb_component_id:P.pcb_component_id,pcb_smtpad_id:P.pcb_smtpad_id,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});else if(t.shape==="rect")!f&&!y?P=e.pcb_smtpad.insert({pcb_component_id:T,pcb_port_id:this.matchedPort?.pcb_port_id,layer:v(t.layer??"top"),shape:"rotated_rect",width:t.width,height:t.height,corner_radius:t.cornerRadius??void 0,x:o.x,y:o.y,ccw_rotation:g,port_hints:t.portHints.map(C=>C.toString()),is_covered_with_solder_mask:i,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):P=e.pcb_smtpad.insert({pcb_component_id:T,pcb_port_id:this.matchedPort?.pcb_port_id,layer:v(t.layer??"top"),shape:"rect",width:y?t.height:t.width,height:y?t.width:t.height,corner_radius:t.cornerRadius??void 0,port_hints:t.portHints.map(C=>C.toString()),is_covered_with_solder_mask:i,x:o.x,y:o.y,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),r&&(P.shape==="rect"?e.pcb_solder_paste.insert({layer:v(t.layer??"top"),shape:"rect",width:P.width*.7,height:P.height*.7,x:P.x,y:P.y,pcb_component_id:P.pcb_component_id,pcb_smtpad_id:P.pcb_smtpad_id,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):P.shape==="rotated_rect"&&e.pcb_solder_paste.insert({layer:v(t.layer??"top"),shape:"rotated_rect",width:P.width*.7,height:P.height*.7,x:P.x,y:P.y,ccw_rotation:P.ccw_rotation,pcb_component_id:P.pcb_component_id,pcb_smtpad_id:P.pcb_smtpad_id,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}));else if(t.shape==="rotated_rect"){let k=t.ccwRotation??0,C=(x+k+360)%360,E=S?(360-C+360)%360:C;P=e.pcb_smtpad.insert({pcb_component_id:T,pcb_port_id:this.matchedPort?.pcb_port_id,layer:v(t.layer??"top"),shape:"rotated_rect",width:t.width,height:t.height,corner_radius:t.cornerRadius??void 0,x:o.x,y:o.y,ccw_rotation:E,port_hints:t.portHints.map(N=>N.toString()),is_covered_with_solder_mask:i,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),r&&e.pcb_solder_paste.insert({layer:v(t.layer??"top"),shape:"rotated_rect",width:P.width*.7,height:P.height*.7,x:o.x,y:o.y,ccw_rotation:E,pcb_component_id:T,pcb_smtpad_id:P.pcb_smtpad_id,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(t.shape==="polygon"){let k=t.points.map(C=>{let E=ze(a,{x:X.parse(C.x),y:X.parse(C.y)});return{x:E.x,y:E.y}});P=e.pcb_smtpad.insert({pcb_component_id:T,pcb_port_id:this.matchedPort?.pcb_port_id,layer:v(t.layer??"top"),shape:"polygon",points:k,port_hints:t.portHints.map(C=>C.toString()),is_covered_with_solder_mask:i,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else t.shape==="pill"&&(P=e.pcb_smtpad.insert({pcb_component_id:T,pcb_port_id:this.matchedPort?.pcb_port_id,layer:v(t.layer??"top"),shape:"pill",x:o.x,y:o.y,radius:t.radius,height:t.height,width:t.width,port_hints:t.portHints.map(k=>k.toString()),is_covered_with_solder_mask:i,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}));P&&(this.pcb_smtpad_id=P.pcb_smtpad_id)}doInitialPcbPortAttachment(){if(this.root?.pcbDisabled)return;let{db:e}=this.root;e.pcb_smtpad.update(this.pcb_smtpad_id,{pcb_port_id:this.matchedPort?.pcb_port_id})}_getPcbCircuitJsonBounds(){let{db:e}=this.root,t=e.pcb_smtpad.get(this.pcb_smtpad_id);if(t.shape==="rect")return{center:{x:t.x,y:t.y},bounds:{left:t.x-t.width/2,top:t.y+t.height/2,right:t.x+t.width/2,bottom:t.y-t.height/2},width:t.width,height:t.height};if(t.shape==="rotated_rect"){let i=t.ccw_rotation*Math.PI/180,r=Math.cos(i),s=Math.sin(i),o=t.width/2,a=t.height/2,c=Math.abs(o*r)+Math.abs(a*s),l=Math.abs(o*s)+Math.abs(a*r);return{center:{x:t.x,y:t.y},bounds:{left:t.x-c,right:t.x+c,top:t.y-l,bottom:t.y+l},width:c*2,height:l*2}}if(t.shape==="circle")return{center:{x:t.x,y:t.y},bounds:{left:t.x-t.radius,top:t.y-t.radius,right:t.x+t.radius,bottom:t.y+t.radius},width:t.radius*2,height:t.radius*2};if(t.shape==="polygon"){let i=t.points,r=i.map(u=>u.x),s=i.map(u=>u.y),o=Math.min(...r),a=Math.max(...r),c=Math.min(...s),l=Math.max(...s);return{center:{x:(o+a)/2,y:(c+l)/2},bounds:{left:o,top:l,right:a,bottom:c},width:a-o,height:l-c}}if(t.shape==="pill"){let i=t.width/2,r=t.height/2;return{center:{x:t.x,y:t.y},bounds:{left:t.x-i,top:t.y-r,right:t.x+i,bottom:t.y+r},width:t.width,height:t.height}}throw new Error(`circuitJson bounds calculation not implemented for shape "${t.shape}"`)}_setPositionFromLayout(e){let{db:t}=this.root;t.pcb_smtpad.update(this.pcb_smtpad_id,{x:e.x,y:e.y});let i=t.pcb_solder_paste.list().find(r=>r.pcb_smtpad_id===this.pcb_smtpad_id);i&&t.pcb_solder_paste.update(i.pcb_solder_paste_id,{x:e.x,y:e.y}),this.matchedPort?._setPositionFromLayout(e)}},c9=class extends Te{constructor(){super(...arguments);d(this,"pcb_silkscreen_path_id",null);d(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenPath",zodProps:gW}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(t.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenPath. Must be "top" or "bottom".`);let s=this._computePcbGlobalTransformBeforeLayout(),o=this.getSubcircuit(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,c=e.pcb_silkscreen_path.insert({pcb_component_id:a,layer:r,route:t.route.map(l=>{let u=ze(s,{x:l.x,y:l.y});return{...l,x:u.x,y:u.y}}),stroke_width:t.strokeWidth??.1,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_path_id=c.pcb_silkscreen_path_id}_setPositionFromLayout(e){let{db:t}=this.root,{_parsedProps:i}=this,r=t.pcb_silkscreen_path.get(this.pcb_silkscreen_path_id);if(!r)return;let s=0,o=0;for(let u of r.route)s+=u.x,o+=u.y;s/=r.route.length,o/=r.route.length;let a=e.x-s,c=e.y-o,l=r.route.map(u=>({...u,x:u.x+a,y:u.y+c}));t.pcb_silkscreen_path.update(this.pcb_silkscreen_path_id,{route:l})}getPcbSize(){let{_parsedProps:e}=this;if(!e.route||e.route.length===0)return{width:0,height:0};let t=1/0,i=-1/0,r=1/0,s=-1/0;for(let o of e.route)t=Math.min(t,o.x),i=Math.max(i,o.x),r=Math.min(r,o.y),s=Math.max(s,o.y);return{width:i-t,height:s-r}}},URt=h.object({route:h.array(Ux),source_trace_id:h.string().optional()}),l9=class extends Te{constructor(){super(...arguments);d(this,"pcb_trace_id",null);d(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbTrace",zodProps:URt}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this.getPrimitiveContainer(),r=this.getSubcircuit(),{maybeFlipLayer:s}=this._getPcbPrimitiveFlippedHelpers(),o=this._computePcbGlobalTransformBeforeLayout(),a=t.route.map(l=>{let{x:u,y:p,...f}=l,y=ze(o,{x:u,y:p});return l.route_type==="wire"&&l.layer?{...y,...f,layer:s(l.layer)}:{...y,...f}}),c=e.pcb_trace.insert({pcb_component_id:i.pcb_component_id,source_trace_id:t.source_trace_id,route:a,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_trace_id=c.pcb_trace_id}getPcbSize(){let{_parsedProps:e}=this;if(!e.route||e.route.length===0)return{width:0,height:0};let t=1/0,i=-1/0,r=1/0,s=-1/0;for(let o of e.route)t=Math.min(t,o.x),i=Math.max(i,o.x),r=Math.min(r,o.y),s=Math.max(s,o.y),o.route_type==="wire"&&(t=Math.min(t,o.x-o.width/2),i=Math.max(i,o.x+o.width/2),r=Math.min(r,o.y-o.width/2),s=Math.max(s,o.y+o.width/2));return t===1/0||i===-1/0||r===1/0||s===-1/0?{width:0,height:0}:{width:i-t,height:s-r}}},U_=class extends Te{constructor(){super(...arguments);d(this,"pcb_plated_hole_id",null);d(this,"matchedPort",null);d(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PlatedHole",zodProps:vH}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){let{_parsedProps:e}=this;if(e.shape==="circle")return{width:e.outerDiameter,height:e.outerDiameter};if(e.shape==="oval"||e.shape==="pill")return{width:e.outerWidth,height:e.outerHeight};if(e.shape==="circular_hole_with_rect_pad")return{width:e.rectPadWidth,height:e.rectPadHeight};if(e.shape==="pill_hole_with_rect_pad")return{width:e.rectPadWidth,height:e.rectPadHeight};throw new Error(`getPcbSize for shape "${e.shape}" not implemented for ${this.componentName}`)}_getPcbCircuitJsonBounds(){let{db:e}=this.root,t=e.pcb_plated_hole.get(this.pcb_plated_hole_id),i=this.getPcbSize();return{center:{x:t.x,y:t.y},bounds:{left:t.x-i.width/2,top:t.y+i.height/2,right:t.x+i.width/2,bottom:t.y-i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(e){let{db:t}=this.root;t.pcb_plated_hole.update(this.pcb_plated_hole_id,{x:e.x,y:e.y}),this.matchedPort?._setPositionFromLayout(e)}doInitialPortMatching(){let e=this.getPrimitiveContainer()?.selectAll("port");if(this.props.portHints){for(let t of e)if(t.isMatchingAnyOf(this.props.portHints)){this.matchedPort=t,t.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalPcbPositionBeforeLayout(),r=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,s=this.getSubcircuit();if(t.shape==="circle"){let o=e.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,outer_diameter:t.outerDiameter,hole_diameter:t.holeDiameter,shape:"circle",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=o.pcb_plated_hole_id,e.pcb_solder_paste.insert({layer:"top",shape:"circle",radius:t.outerDiameter/2,x:i.x,y:i.y,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),e.pcb_solder_paste.insert({layer:"bottom",shape:"circle",radius:t.outerDiameter/2,x:i.x,y:i.y,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(t.shape==="pill"&&t.rectPad){let o=e.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:t.outerWidth,outer_height:t.outerHeight,hole_width:t.holeWidth,hole_height:t.holeHeight,shape:"rotated_pill_hole_with_rect_pad",type:"pcb_plated_hole",port_hints:this.getNameAndAliases(),pcb_plated_hole_id:this.pcb_plated_hole_id,x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_shape:"rotated_pill",pad_shape:"rect",hole_ccw_rotation:t.pcbRotation??0,rect_ccw_rotation:t.pcbRotation??0,rect_pad_width:t.outerWidth,rect_pad_height:t.outerHeight,hole_offset_x:t.holeOffsetX,hole_offset_y:t.holeOffsetY});this.pcb_plated_hole_id=o.pcb_plated_hole_id}else if(t.shape==="pill"||t.shape==="oval"){let o=e.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:t.outerWidth,outer_height:t.outerHeight,hole_width:t.holeWidth,hole_height:t.holeHeight,shape:t.shape,port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,ccw_rotation:t.pcbRotation??0});this.pcb_plated_hole_id=o.pcb_plated_hole_id,e.pcb_solder_paste.insert({layer:"top",shape:t.shape,width:t.outerWidth,height:t.outerHeight,x:i.x,y:i.y,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),e.pcb_solder_paste.insert({layer:"bottom",shape:t.shape,width:t.outerWidth,height:t.outerHeight,x:i.x,y:i.y,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(t.shape==="circular_hole_with_rect_pad"){let o=e.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,hole_diameter:t.holeDiameter,rect_pad_width:t.rectPadWidth,rect_pad_height:t.rectPadHeight,shape:"circular_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_offset_x:t.holeOffsetX,hole_offset_y:t.holeOffsetY,rect_border_radius:t.rectBorderRadius??0});this.pcb_plated_hole_id=o.pcb_plated_hole_id}else if(t.shape==="pill_hole_with_rect_pad"){let o=e.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,hole_width:t.holeWidth,hole_height:t.holeHeight,rect_pad_width:t.rectPadWidth,rect_pad_height:t.rectPadHeight,hole_offset_x:t.holeOffsetX,hole_offset_y:t.holeOffsetY,shape:"pill_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=o.pcb_plated_hole_id}}doInitialPcbPortAttachment(){if(this.root?.pcbDisabled)return;let{db:e}=this.root;e.pcb_plated_hole.update(this.pcb_plated_hole_id,{pcb_port_id:this.matchedPort?.pcb_port_id})}},HS=class extends Te{constructor(){super(...arguments);d(this,"pcb_keepout_id",null);d(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Keepout",zodProps:nW}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let e=this.getSubcircuit(),{db:t}=this.root,{_parsedProps:i}=this,r=this._getGlobalPcbPositionBeforeLayout(),s=Js(this._computePcbGlobalTransformBeforeLayout()),o=Math.abs(s.rotation.angle*(180/Math.PI)-90)%180<.01,a=null;i.shape==="circle"?a=t.pcb_keepout.insert({layers:["top"],shape:"circle",radius:i.radius,center:{x:r.x,y:r.y},subcircuit_id:e?.subcircuit_id??void 0,pcb_group_id:e?.getGroup()?.pcb_group_id??void 0}):i.shape==="rect"&&(a=t.pcb_keepout.insert({layers:["top"],shape:"rect",...o?{width:i.height,height:i.width}:{width:i.width,height:i.height},center:{x:r.x,y:r.y},subcircuit_id:e?.subcircuit_id??void 0,pcb_group_id:e?.getGroup()?.pcb_group_id??void 0})),a&&(this.pcb_keepout_id=a.pcb_keepout_id)}},V_=class extends Te{constructor(){super(...arguments);d(this,"pcb_hole_id",null);d(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Hole",zodProps:AH}}getPcbSize(){let{_parsedProps:e}=this,t=e.shape==="pill",i=e.shape==="rect";return t?{width:e.width,height:e.height}:i?{width:e.width,height:e.height}:{width:e.diameter,height:e.diameter}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this.getSubcircuit(),r=this._getGlobalPcbPositionBeforeLayout();if(t.shape==="pill")if(t.pcbRotation&&t.pcbRotation!==0){let s=e.pcb_hole.insert({type:"pcb_hole",hole_shape:"rotated_pill",hole_width:t.width,hole_height:t.height,x:r.x,y:r.y,ccw_rotation:t.pcbRotation,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:i?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=s.pcb_hole_id}else{let s=e.pcb_hole.insert({type:"pcb_hole",hole_shape:"pill",hole_width:t.width,hole_height:t.height,x:r.x,y:r.y,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:i?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=s.pcb_hole_id}else if(t.shape==="rect"){let s=e.pcb_hole.insert({type:"pcb_hole",hole_shape:"rect",hole_width:t.width,hole_height:t.height,x:r.x,y:r.y,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:i?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=s.pcb_hole_id}else{let s=e.pcb_hole.insert({type:"pcb_hole",hole_shape:"circle",hole_diameter:t.diameter,x:r.x,y:r.y,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:i?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=s.pcb_hole_id}}_getPcbCircuitJsonBounds(){let{db:e}=this.root,t=e.pcb_hole.get(this.pcb_hole_id),i=this.getPcbSize();return{center:{x:t.x,y:t.y},bounds:{left:t.x-i.width/2,top:t.y-i.height/2,right:t.x+i.width/2,bottom:t.y+i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(e){let{db:t}=this.root;t.pcb_hole.update(this.pcb_hole_id,{x:e.x,y:e.y})}},JS=class extends Te{constructor(){super(...arguments);d(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenText",zodProps:yW}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this.getPrimitiveContainer(),r=this._getGlobalPcbPositionBeforeLayout(),{maybeFlipLayer:s,isFlipped:o}=this._getPcbPrimitiveFlippedHelpers(),a=this.getSubcircuit(),c=0;if(t.pcbRotation!==void 0&&t.pcbRotation!==0)c=t.pcbRotation;else{let f=this._computePcbGlobalTransformBeforeLayout();c=Js(f).rotation.angle*180/Math.PI}o&&(c=(c+180)%360);let l=new Set(t.layers);t.layer&&l.add(t.layer);let u=l.size>0?Array.from(l):["top"],p=t.fontSize??this.getInheritedProperty("pcbStyle")?.silkscreenFontSize??1;for(let f of u)e.pcb_silkscreen_text.insert({anchor_alignment:t.anchorAlignment,anchor_position:{x:r.x,y:r.y},font:t.font??"tscircuit2024",font_size:p,layer:s(f),text:t.text??"",ccw_rotation:c,pcb_component_id:i.pcb_component_id,subcircuit_id:a?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}getPcbSize(){let{_parsedProps:e}=this,t=e.fontSize??this.getInheritedProperty("pcbStyle")?.silkscreenFontSize??1,r=(e.text??"").length*t,s=t;return{width:r*t,height:s*t}}},$1=class extends Te{constructor(){super(...arguments);d(this,"pcb_cutout_id",null);d(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Cutout",zodProps:IH}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this.getSubcircuit(),r=this.getGroup()?.pcb_group_id??void 0,s=this._getGlobalPcbPositionBeforeLayout(),a=this.getPrimitiveContainer()?._parsedProps.pcbRotation??0,c;if(t.shape==="rect"){let l=typeof a=="string"?parseInt(a.replace("deg",""),10):a,u=Math.abs(l%180)===90,p={shape:"rect",center:s,width:u?t.height:t.width,height:u?t.width:t.height,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r};c=e.pcb_cutout.insert(p)}else if(t.shape==="circle"){let l={shape:"circle",center:s,radius:t.radius,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r};c=e.pcb_cutout.insert(l)}else if(t.shape==="polygon"){let l=this._computePcbGlobalTransformBeforeLayout(),p={shape:"polygon",points:t.points.map(f=>ze(l,f)),subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r};c=e.pcb_cutout.insert(p)}c&&(this.pcb_cutout_id=c.pcb_cutout_id)}getPcbSize(){let{_parsedProps:e}=this;if(e.shape==="rect")return{width:e.width,height:e.height};if(e.shape==="circle")return{width:e.radius*2,height:e.radius*2};if(e.shape==="polygon"){if(e.points.length===0)return{width:0,height:0};let t=1/0,i=-1/0,r=1/0,s=-1/0;for(let o of e.points)t=Math.min(t,o.x),i=Math.max(i,o.x),r=Math.min(r,o.y),s=Math.max(s,o.y);return{width:i-t,height:s-r}}return{width:0,height:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_cutout_id)return super._getPcbCircuitJsonBounds();let{db:e}=this.root,t=e.pcb_cutout.get(this.pcb_cutout_id);if(!t)return super._getPcbCircuitJsonBounds();if(t.shape==="rect")return{center:t.center,bounds:{left:t.center.x-t.width/2,top:t.center.y+t.height/2,right:t.center.x+t.width/2,bottom:t.center.y-t.height/2},width:t.width,height:t.height};if(t.shape==="circle")return{center:t.center,bounds:{left:t.center.x-t.radius,top:t.center.y+t.radius,right:t.center.x+t.radius,bottom:t.center.y-t.radius},width:t.radius*2,height:t.radius*2};if(t.shape==="polygon"){if(t.points.length===0)return super._getPcbCircuitJsonBounds();let i=1/0,r=-1/0,s=1/0,o=-1/0;for(let a of t.points)i=Math.min(i,a.x),r=Math.max(r,a.x),s=Math.min(s,a.y),o=Math.max(o,a.y);return{center:{x:(i+r)/2,y:(s+o)/2},bounds:{left:i,top:o,right:r,bottom:s},width:r-i,height:o-s}}return super._getPcbCircuitJsonBounds()}_setPositionFromLayout(e){if(!this.pcb_cutout_id)return;let{db:t}=this.root,i=t.pcb_cutout.get(this.pcb_cutout_id);if(i){if(i.shape==="rect"||i.shape==="circle")t.pcb_cutout.update(this.pcb_cutout_id,{...i,center:e});else if(i.shape==="polygon"){let r=this._getPcbCircuitJsonBounds().center,s=e.x-r.x,o=e.y-r.y,a=i.points.map(c=>({x:c.x+s,y:c.y+o}));t.pcb_cutout.update(this.pcb_cutout_id,{...i,points:a})}}}},VRt=({elm:n,pinLabels:e,layer:t,readableRotation:i,anchorAlignment:r})=>{let s=n.text.replace(/[{}]/g,"").toLowerCase(),o=s;if(Array.isArray(e)){let a=parseInt(s.replace(/[^\d]/g,""),10)-1;o=String(e[a]??s)}else typeof e=="object"&&(o=String(e[s]??s));return new JS({anchorAlignment:r||"center",text:o??s,layer:t||"top",fontSize:n.font_size+.2,pcbX:isNaN(n.anchor_position.x)?0:n.anchor_position.x,pcbY:n.anchor_position.y,pcbRotation:i??0})},GRt=(n,e)=>{let t=parseInt(n||"0",10),i;return e!=null?i=e-t:i=t,(i%360+360)%360},G_=({componentName:n,componentRotation:e,footprinterString:t,pinLabels:i,pcbPinLabels:r},s)=>{let o=[];for(let a of s)if(a.type==="pcb_smtpad"&&a.shape==="rect")o.push(new D1({pcbX:a.x,pcbY:a.y,layer:a.layer,shape:"rect",height:a.height,width:a.width,portHints:a.port_hints,rectBorderRadius:a.rect_border_radius}));else if(a.type==="pcb_smtpad"&&a.shape==="circle")o.push(new D1({pcbX:a.x,pcbY:a.y,layer:a.layer,shape:"circle",radius:a.radius,portHints:a.port_hints}));else if(a.type==="pcb_smtpad"&&a.shape==="pill")o.push(new D1({shape:"pill",height:a.height,width:a.width,radius:a.radius,portHints:a.port_hints,pcbX:a.x,pcbY:a.y,layer:a.layer}));else if(a.type==="pcb_silkscreen_path")o.push(new c9({layer:a.layer,route:a.route,strokeWidth:a.stroke_width}));else if(a.type==="pcb_plated_hole")a.shape==="circle"?o.push(new U_({pcbX:a.x,pcbY:a.y,shape:"circle",holeDiameter:a.hole_diameter,outerDiameter:a.outer_diameter,portHints:a.port_hints})):a.shape==="circular_hole_with_rect_pad"?o.push(new U_({pcbX:a.x,pcbY:a.y,shape:"circular_hole_with_rect_pad",holeDiameter:a.hole_diameter,rectPadHeight:a.rect_pad_height,rectPadWidth:a.rect_pad_width,portHints:a.port_hints,rectBorderRadius:a.rect_border_radius,holeOffsetX:a.hole_offset_x,holeOffsetY:a.hole_offset_y})):a.shape==="pill"||a.shape==="oval"?o.push(new U_({pcbX:a.x,pcbY:a.y,shape:a.shape,holeWidth:a.hole_width,holeHeight:a.hole_height,outerWidth:a.outer_width,outerHeight:a.outer_height,portHints:a.port_hints})):a.shape==="pill_hole_with_rect_pad"&&o.push(new U_({pcbX:a.x,pcbY:a.y,shape:"pill_hole_with_rect_pad",holeShape:"pill",padShape:"rect",holeWidth:a.hole_width,holeHeight:a.hole_height,rectPadWidth:a.rect_pad_width,rectPadHeight:a.rect_pad_height,portHints:a.port_hints,holeOffsetX:a.hole_offset_x,holeOffsetY:a.hole_offset_y}));else if(a.type==="pcb_keepout"&&a.shape==="circle")o.push(new HS({pcbX:a.center.x,pcbY:a.center.y,shape:"circle",radius:a.radius}));else if(a.type==="pcb_keepout"&&a.shape==="rect")o.push(new HS({pcbX:a.center.x,pcbY:a.center.y,shape:"rect",width:a.width,height:a.height}));else if(a.type==="pcb_hole"&&a.hole_shape==="circle")o.push(new V_({pcbX:a.x,pcbY:a.y,diameter:a.hole_diameter}));else if(a.type==="pcb_hole"&&a.hole_shape==="rect")o.push(new V_({pcbX:a.x,pcbY:a.y,shape:"rect",width:a.hole_width,height:a.hole_height}));else if(a.type==="pcb_hole"&&a.hole_shape==="pill")o.push(new V_({pcbX:a.x,pcbY:a.y,shape:"pill",width:a.hole_width,height:a.hole_height}));else if(a.type==="pcb_hole"&&a.hole_shape==="rotated_pill")o.push(new V_({pcbX:a.x,pcbY:a.y,shape:"pill",width:a.hole_width,height:a.hole_height,pcbRotation:a.ccw_rotation}));else if(a.type==="pcb_cutout")a.shape==="rect"?o.push(new $1({pcbX:a.center.x,pcbY:a.center.y,shape:"rect",width:a.width,height:a.height})):a.shape==="circle"?o.push(new $1({pcbX:a.center.x,pcbY:a.center.y,shape:"circle",radius:a.radius})):a.shape==="polygon"&&o.push(new $1({shape:"polygon",points:a.points}));else if(a.type==="pcb_silkscreen_text"){let c=GRt(e,a.ccw_rotation);t?.includes("pinrow")&&a.text.includes("PIN")?o.push(VRt({elm:a,pinLabels:r??i??{},layer:a.layer,readableRotation:c,anchorAlignment:a.anchor_alignment})):o.push(new JS({anchorAlignment:a.anchor_alignment||"center",text:n,fontSize:a.font_size+.2,pcbX:Number.isNaN(a.anchor_position.x)?0:a.anchor_position.x,pcbY:a.anchor_position.y,pcbRotation:c??0}))}else a.type==="pcb_trace"&&o.push(new l9({route:a.route}));return o};function QS(n){let e=1/0,t=1/0,i=-1/0,r=-1/0,s=!1;for(let c of n)if(c.isPcbPrimitive&&!c.componentName.startsWith("Silkscreen")){let{x:l,y:u}=c._getGlobalPcbPositionBeforeLayout(),{width:p,height:f}=c.getPcbSize();e=Math.min(e,l-p/2),t=Math.min(t,u-f/2),i=Math.max(i,l+p/2),r=Math.max(r,u+f/2),s=!0}else if(c.children.length>0){let l=QS(c.children);(l.width>0||l.height>0)&&(e=Math.min(e,l.minX),t=Math.min(t,l.minY),i=Math.max(i,l.maxX),r=Math.max(r,l.maxY),s=!0)}if(!s)return{minX:0,minY:0,maxX:0,maxY:0,width:0,height:0};let o=i-e,a=r-t;return o<0&&(o=0),a<0&&(a=0),{minX:e,minY:t,maxX:i,maxY:r,width:o,height:a}}function tet(n){let e=n%360;return e<0?e+360:e}function HRt(n,e,t,i){return i==="counterclockwise"?t>=e?n>=e&&n<=t:n>=e||n<=t:t<=e?n<=e&&n>=t:n<=e||n>=t}function WRt(n){let e=n.center,t=n.radius,i=n.start_angle_degrees,r=n.end_angle_degrees,s=n.direction??"counterclockwise";if(!e||typeof e.x!="number"||typeof e.y!="number"||typeof t!="number"||typeof i!="number"||typeof r!="number")return null;let o=tet(i),a=tet(r),c=new Set([o,a]),l=[0,90,180,270];for(let g of l)HRt(g,o,a,s)&&c.add(g);let u=1/0,p=1/0,f=-1/0,y=-1/0;for(let g of c){let x=g*Math.PI/180,v=e.x+t*Math.cos(x),S=e.y+t*Math.sin(x);u=Math.min(u,v),f=Math.max(f,v),p=Math.min(p,S),y=Math.max(y,S)}return!Number.isFinite(u)||!Number.isFinite(p)?null:{minX:u,maxX:f,minY:p,maxY:y}}function Ret(n){let e=1/0,t=1/0,i=-1/0,r=-1/0;for(let s of n){let o,a,c,l;if(s.type==="schematic_component")o=s.center?.x,a=s.center?.y,c=s.size?.width,l=s.size?.height;else if(s.type==="schematic_box")o=s.x,a=s.y,c=s.width,l=s.height;else if(s.type==="schematic_port")o=s.center?.x,a=s.center?.y,c=.2,l=.2;else if(s.type==="schematic_text")o=s.position?.x,a=s.position?.y,c=(s.text?.length??0)*.1,l=.2;else if(s.type==="schematic_line"){let u=s.x1??0,p=s.y1??0,f=s.x2??0,y=s.y2??0;o=(u+f)/2,a=(p+y)/2,c=Math.abs(f-u),l=Math.abs(y-p)}else if(s.type==="schematic_rect")o=s.center?.x,a=s.center?.y,c=s.width,l=s.height;else if(s.type==="schematic_circle"){o=s.center?.x,a=s.center?.y;let u=s.radius;typeof u=="number"&&(c=u*2,l=u*2)}else if(s.type==="schematic_arc"){let u=WRt(s);u&&(e=Math.min(e,u.minX),i=Math.max(i,u.maxX),t=Math.min(t,u.minY),r=Math.max(r,u.maxY));continue}typeof o=="number"&&typeof a=="number"&&typeof c=="number"&&typeof l=="number"&&(e=Math.min(e,o-c/2),i=Math.max(i,o+c/2),t=Math.min(t,a-l/2),r=Math.max(r,a+l/2))}return{minX:e,maxX:i,minY:t,maxY:r}}function qRt(n,e){let t=e.x-n.x,i=e.y-n.y;return Math.abs(t)>Math.abs(i)?t>=0?"right":"left":i>=0?"up":"down"}var eet=n=>{if(n.length<=1)return!0;let e=n.map(s=>{let o=s._getPcbCircuitJsonBounds();return{left:o.bounds.left,right:o.bounds.right,top:o.bounds.top,bottom:o.bounds.bottom}}),t=Array(e.length).fill(!1).map(()=>Array(e.length).fill(!1));for(let s=0;s<e.length;s++)for(let o=s+1;o<e.length;o++){let a=e[s],c=e[o];t[s][o]=t[o][s]=!(a.right<c.left||a.left>c.right||a.bottom>c.top||a.top<c.bottom)}let i=new Set,r=s=>{i.add(s);for(let o=0;o<e.length;o++)t[s][o]&&!i.has(o)&&r(o)};return r(0),i.size===e.length},net=n=>{if(n.length===0)throw new Error("Cannot get center of empty PCB primitives array");let e=n.map(r=>r._getPcbCircuitJsonBounds().center).filter(Boolean),t=e.reduce((r,s)=>r+s.x,0),i=e.reduce((r,s)=>r+s.y,0);return{x:t/e.length,y:i/e.length}},ZRt=h.object({name:h.string().optional(),pinNumber:h.number().optional(),aliases:h.array(h.string()).optional(),layer:h.string().optional(),layers:h.array(h.string()).optional(),schX:h.number().optional(),schY:h.number().optional(),direction:h.enum(["up","down","left","right"]).optional(),connectsTo:h.union([h.string(),h.array(h.string())]).optional()}),Vi=class extends Te{constructor(e,t={}){if(!e.name&&e.pinNumber!==void 0&&(e.name=`pin${e.pinNumber}`),!e.name)throw new Error("Port must have a name or a pinNumber");super(e);d(this,"source_port_id",null);d(this,"pcb_port_id",null);d(this,"schematic_port_id",null);d(this,"schematicSymbolPortDef",null);d(this,"matchedComponents");d(this,"facingDirection",null);d(this,"originDescription",null);t.originDescription&&(this.originDescription=t.originDescription),this.matchedComponents=[]}get config(){return{componentName:"Port",zodProps:ZRt}}isGroupPort(){return this.parent?.componentName==="Group"}isComponentPort(){return!this.isGroupPort()}_getConnectedPortsFromConnectsTo(){let{_parsedProps:e}=this,t=e.connectsTo;if(!t)return[];let i=[],r=Array.isArray(t)?t:[t];for(let s of r){let o=this.getSubcircuit().selectOne(s,{type:"port"});o&&i.push(o)}return i}_isBoardPinoutFromAttributes(){let e=this.parent;if(e?._parsedProps?.pinAttributes){let t=e._parsedProps.pinAttributes;for(let i of this.getNameAndAliases())if(t[i]?.includeInBoardPinout)return!0}}_getGlobalPcbPositionBeforeLayout(){let e=this.matchedComponents.find(i=>i.isPcbPrimitive),t=this.parent;if(t&&!t.props.footprint)throw new Error(`${t.componentName} "${t.props.name}" does not have a footprint. Add a footprint prop, e.g. <${t.componentName.toLowerCase()} footprint="..." />`);if(!e)throw new Error(`Port ${this} has no matching PCB primitives. This often means the footprint's pads lack matching port hints.`);return e?._getGlobalPcbPositionBeforeLayout()??{x:0,y:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_port_id)return super._getPcbCircuitJsonBounds();let{db:e}=this.root,t=e.pcb_port.get(this.pcb_port_id);return{center:{x:t.x,y:t.y},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getGlobalPcbPositionAfterLayout(){return this._getPcbCircuitJsonBounds().center}_getPortsInternallyConnectedToThisPort(){let e=this.parent;if(!e||!e._getInternallyConnectedPins)return[];let t=e._getInternallyConnectedPins();for(let i of t)if(i.some(r=>r===this))return i;return[]}_hasSchematicPort(){let{schX:e,schY:t}=this._parsedProps;if(e!==void 0&&t!==void 0)return!0;let i=this.getParentNormalComponent();if(i?.getSchematicSymbol())return!!(this.schematicSymbolPortDef||this._getPortsInternallyConnectedToThisPort().some(a=>a.schematicSymbolPortDef));let s=i?._getSchematicBoxDimensions();return!!(s&&this.props.pinNumber!==void 0&&s.getPortPositionByPinNumber(this.props.pinNumber))}_getGlobalSchematicPositionBeforeLayout(){let{schX:e,schY:t}=this._parsedProps;if(e!==void 0&&t!==void 0)return{x:e,y:t};let i=this.getParentNormalComponent(),r=i?.getSchematicSymbol();if(r){let o=this.schematicSymbolPortDef;if(!o&&(o=this._getPortsInternallyConnectedToThisPort().find(c=>c.schematicSymbolPortDef)?.schematicSymbolPortDef??null,!o))throw new Error(`Couldn't find schematicSymbolPortDef for port ${this.getString()}, searched internally connected ports and none had a schematicSymbolPortDef. Why are we trying to get the schematic position of this port?`);let a=mi(i.computeSchematicGlobalTransform(),Nn(-r.center.x,-r.center.y));return ze(a,o)}let s=i?._getSchematicBoxDimensions();if(s&&this.props.pinNumber!==void 0){let o=s.getPortPositionByPinNumber(this.props.pinNumber);if(!o)throw new Error(`Couldn't find position for schematic_port for port ${this.getString()} inside of the schematic box`);return ze(i.computeSchematicGlobalTransform(),o)}throw new Error(`Couldn't find position for schematic_port for port ${this.getString()}`)}_getGlobalSchematicPositionAfterLayout(){let{db:e}=this.root;if(!this.schematic_port_id)throw new Error(`Can't get schematic port position after layout for "${this.getString()}", no schematic_port_id`);let t=e.schematic_port.get(this.schematic_port_id);if(!t)throw new Error(`Schematic port not found when trying to get post-layout position: ${this.schematic_port_id}`);return t.center}registerMatch(e){this.matchedComponents.push(e)}getNameAndAliases(){let{_parsedProps:e}=this;return Array.from(new Set([...e.name?[e.name]:[],...e.aliases??[],...typeof e.pinNumber=="number"?[`pin${e.pinNumber}`,e.pinNumber.toString()]:[],...this.externallyAddedAliases??[]]))}_getMatchingPinAttributes(){let e=this.parent?._parsedProps?.pinAttributes;if(!e)return[];let t=[];for(let i of this.getNameAndAliases()){let r=e[i];r&&t.push(r)}return t}_shouldIncludeInBoardPinout(){return this._getMatchingPinAttributes().some(e=>e.includeInBoardPinout===!0)}isMatchingPort(e){return this.isMatchingAnyOf(e.getNameAndAliases())}getPortSelector(){return`.${(this.getParentNormalComponent()??this.parent)?.props.name} > port.${this.props.name}`}getAvailablePcbLayers(){let{layer:e,layers:t}=this._parsedProps;return t||(e?[e]:Array.from(new Set(this.matchedComponents.flatMap(i=>i.getAvailablePcbLayers()))))}_getDirectlyConnectedTraces(){return this.getSubcircuit().selectAll("trace").filter(i=>!i._couldNotFindPort).filter(i=>i._isExplicitlyConnectedToPort(this))}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=this.getNameAndAliases(),r=this.getParentNormalComponent(),o=(this.parent?.source_component_id?this.parent:r)?.source_component_id??null,a=e.source_port.insert({name:t.name,pin_number:t.pinNumber,port_hints:i,source_component_id:o,subcircuit_id:this.getSubcircuit()?.subcircuit_id});this.source_port_id=a.source_port_id}doInitialSourceParentAttachment(){let{db:e}=this.root,t=this.getParentNormalComponent(),i=this.parent?.source_component_id?this.parent:t;if(this.isGroupPort()){e.source_port.update(this.source_port_id,{source_component_id:null,subcircuit_id:this.getSubcircuit()?.subcircuit_id});return}if(!i?.source_component_id)throw new Error(`${this.getString()} has no parent source component (parent: ${this.parent?.getString()})`);e.source_port.update(this.source_port_id,{source_component_id:i.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id}),this.source_component_id=i.source_component_id}doInitialPcbPortRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{matchedComponents:t}=this;if(this.isGroupPort()){let a=this._getConnectedPortsFromConnectsTo();if(a.length===0)return;let c=a[0];if(!c.pcb_port_id)return;let l=e.pcb_port.get(c.pcb_port_id),u={x:l.x,y:l.y},p=this.getSubcircuit(),f=e.pcb_port.insert({pcb_component_id:void 0,layers:c.getAvailablePcbLayers(),subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...u,source_port_id:this.source_port_id,is_board_pinout:!1});this.pcb_port_id=f.pcb_port_id;return}let i=this.getParentNormalComponent(),r=this.parent?.pcb_component_id?this.parent:i;if(!r?.pcb_component_id)throw new Error(`${this.getString()} has no parent pcb component, cannot render pcb_port (parent: ${this.parent?.getString()}, parentNormalComponent: ${i?.getString()})`);let s=t.filter(a=>a.isPcbPrimitive);if(s.length===0)return;let o=null;if(s.length===1&&(o=s[0]._getPcbCircuitJsonBounds().center),s.length>1){if(!eet(s))throw new Error(`${this.getString()} has multiple non-overlapping pcb matches, unclear how to place pcb_port: ${s.map(a=>a.getString()).join(", ")}. (Note: tscircuit core does not currently allow you to specify internally connected pcb primitives with the same port hints, try giving them different port hints and specifying they are connected externally- or file an issue)`);o=net(s)}if(o){let a=this.getSubcircuit(),c=this._shouldIncludeInBoardPinout(),l=e.pcb_port.insert({pcb_component_id:r.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:a?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...c?{is_board_pinout:!0}:{},...o,source_port_id:this.source_port_id,is_board_pinout:this._isBoardPinoutFromAttributes()});this.pcb_port_id=l.pcb_port_id}else{let a=s[0];throw new Error(`${a.getString()} does not have a center or _getGlobalPcbPositionBeforeLayout method (needed for pcb_port placement)`)}}updatePcbPortRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root;if(this.pcb_port_id)return;if(this.isGroupPort()){let l=this._getConnectedPortsFromConnectsTo();if(l.length===0)return;let u=l[0];if(!u.pcb_port_id)return;let p=e.pcb_port.get(u.pcb_port_id),f={x:p.x,y:p.y},y=this.getSubcircuit(),g=e.pcb_port.insert({pcb_component_id:void 0,layers:u.getAvailablePcbLayers(),subcircuit_id:y?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...f,source_port_id:this.source_port_id,is_board_pinout:!1});this.pcb_port_id=g.pcb_port_id;return}let t=this.matchedComponents.filter(l=>l.isPcbPrimitive);if(t.length===0)return;let i=null;if(t.length===1&&(i=t[0]._getPcbCircuitJsonBounds().center),t.length>1)try{eet(t)&&(i=net(t))}catch{}if(!i)return;let r=this.getParentNormalComponent(),s=this.parent?.pcb_component_id?this.parent:r,o=this.getSubcircuit(),a=this._shouldIncludeInBoardPinout(),c=e.pcb_port.insert({pcb_component_id:s?.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...a?{is_board_pinout:!0}:{},...i,source_port_id:this.source_port_id,is_board_pinout:this._isBoardPinoutFromAttributes()});this.pcb_port_id=c.pcb_port_id}_getBestDisplayPinLabel(){let{db:e}=this.root,t=e.source_port.get(this.source_port_id),i=[];for(let o of t?.port_hints??[])o.match(/^(pin)?\d+$/)||o.match(/^(left|right)/)&&!t?.name.match(/^(left|right)/)||i.push(o);if(this.getParentNormalComponent()?.props?.showPinAliases&&i.length>0)return i.join("/");if(i.length>0)return i[0]}doInitialSchematicPortRender(){let{db:e}=this.root,{_parsedProps:t}=this,{schX:i,schY:r}=t,s=i!==void 0&&r!==void 0?this.getParentNormalComponent():this.getPrimitiveContainer();if(!s||!this._hasSchematicPort())return;let o=s._getGlobalSchematicPositionBeforeLayout(),a=this._getGlobalSchematicPositionBeforeLayout(),c=null,l=s._getSchematicBoxDimensions();l&&t.pinNumber!==void 0&&(c=l.getPortPositionByPinNumber(t.pinNumber)),this.getSubcircuit().props._schDebugObjectsEnabled&&e.schematic_debug_object.insert({shape:"rect",center:a,size:{width:.1,height:.1},label:"obstacle"}),c?.side?this.facingDirection={left:"left",right:"right",top:"up",bottom:"down"}[c.side]:this.facingDirection=qRt(o,a);let u=this._getBestDisplayPinLabel(),f={type:"schematic_port",schematic_component_id:this.getParentNormalComponent()?.schematic_component_id,center:a,source_port_id:this.source_port_id,facing_direction:this.facingDirection,distance_from_component_edge:.4,side_of_component:c?.side,pin_number:t.pinNumber,true_ccw_index:c?.trueIndex,display_pin_label:u,is_connected:!1};for(let g of this._getMatchingPinAttributes())g.requiresPower&&(f.has_input_arrow=!0),g.providesPower&&(f.has_output_arrow=!0);let y=e.schematic_port.insert(f);this.schematic_port_id=y.schematic_port_id}_getSubcircuitConnectivityKey(){return this.root?.db.source_port.get(this.source_port_id)?.subcircuit_connectivity_map_key}_setPositionFromLayout(e){let{db:t}=this.root;this.pcb_port_id&&t.pcb_port.update(this.pcb_port_id,{x:e.x,y:e.y})}_hasMatchedPcbPrimitive(){return this.matchedComponents.some(e=>e.isPcbPrimitive)}_getNetLabelText(){return`${this.parent?.props.name}_${this.props.name}`}},Oet=n=>{let e=n.find(t=>/^(pin)?\d+$/.test(t));return e?Number.parseInt(e.replace(/^pin/,"")):null};function O1(n,e){let t=Oet(n);if(!t)return null;let r=[...n.filter(s=>s.toString()!==t.toString()&&s!==`pin${t}`),...e?.additionalAliases?.[`pin${t}`]??[]];return new Vi({pinNumber:t,aliases:r})}var KRt=n=>{for(let e of["leftSide","rightSide","topSide","bottomSide"])if(e in n&&typeof n[e]=="number")throw new Error(`A number was specified for "${e}", you probably meant to use "size" not "side"`);return"leftSide"in n||"rightSide"in n||"topSide"in n||"bottomSide"in n},JRt=n=>{if(KRt(n))return{leftSize:n.leftSide?.pins.length??0,rightSize:n.rightSide?.pins.length??0,topSize:n.topSide?.pins.length??0,bottomSize:n.bottomSide?.pins.length??0};let{leftSize:e=0,rightSize:t=0,topSize:i=0,bottomSize:r=0}=n;return{leftSize:e,rightSize:t,topSize:i,bottomSize:r}},BS=.4;function Let(n){let e=n;return e.leftSide!==void 0||e.rightSide!==void 0||e.topSide!==void 0||e.bottomSide!==void 0}var QRt=n=>{let e=n.portDistanceFromEdge??.4,t=n.schPortArrangement?JRt(n.schPortArrangement):null,i={left:0,right:0,top:0,bottom:0},r=n.pinCount??null;if(r===null)if(t)r=t.leftSize+t.rightSize+t.topSize;else throw new Error("Could not determine pin count for the schematic box");if(r&&!t){let g=Math.floor(r/2);t={leftSize:r-g,rightSize:g,topSize:0,bottomSize:0}}t||(t={leftSize:0,rightSize:0,topSize:0,bottomSize:0});let s=({side:g,sideIndex:x,truePinIndex:v})=>{if(!n.schPortArrangement||!Let(n.schPortArrangement))return v+1;let S={left:"top-to-bottom",bottom:"left-to-right",right:"bottom-to-top",top:"right-to-left"}[g],P=n.schPortArrangement?.[`${g}Side`]?.direction??S,T=n.schPortArrangement?.[`${g}Side`]?.pins,k=x;return P!==S&&(k=T.length-x-1),j1(T[k],n.pinLabels)},o=[],a=0,c=0;for(let g=0;g<t.leftSize;g++){let x=s({side:"left",sideIndex:g,truePinIndex:c}),v=n.numericSchPinStyle?.[`pin${x}`]??n.numericSchPinStyle?.[x];v?.topMargin&&(a+=v.topMargin),o.push({trueIndex:c,pinNumber:x,side:"left",distanceFromOrthogonalEdge:a}),v?.bottomMargin&&(a+=v.bottomMargin),g===t.leftSize-1?i.left=a:a+=n.schPinSpacing,c++}a=0;for(let g=0;g<t.bottomSize;g++){let x=s({side:"bottom",sideIndex:g,truePinIndex:c}),v=n.numericSchPinStyle?.[`pin${x}`]??n.numericSchPinStyle?.[x];v?.leftMargin&&(a+=v.leftMargin),o.push({trueIndex:c,pinNumber:x,side:"bottom",distanceFromOrthogonalEdge:a}),v?.rightMargin&&(a+=v.rightMargin),g===t.bottomSize-1?i.bottom=a:a+=n.schPinSpacing,c++}a=0;for(let g=0;g<t.rightSize;g++){let x=s({side:"right",sideIndex:g,truePinIndex:c}),v=n.numericSchPinStyle?.[`pin${x}`]??n.numericSchPinStyle?.[x];v?.bottomMargin&&(a+=v.bottomMargin),o.push({trueIndex:c,pinNumber:x,side:"right",distanceFromOrthogonalEdge:a}),v?.topMargin&&(a+=v.topMargin),g===t.rightSize-1?i.right=a:a+=n.schPinSpacing,c++}a=0;for(let g=0;g<t.topSize;g++){let x=s({side:"top",sideIndex:g,truePinIndex:c}),v=n.numericSchPinStyle?.[`pin${x}`]??n.numericSchPinStyle?.[x];v?.rightMargin&&(a+=v.rightMargin),o.push({trueIndex:c,pinNumber:x,side:"top",distanceFromOrthogonalEdge:a}),v?.leftMargin&&(a+=v.leftMargin),g===t.topSize-1?i.top=a:a+=n.schPinSpacing,c++}let l=n.schWidth;if(l===void 0){l=Math.max(i.top+BS,i.bottom+BS),n.pinLabels&&o.filter(P=>P.side==="left"||P.side==="right").some(P=>n.pinLabels?.[`pin${P.pinNumber}`]||n.pinLabels?.[P.pinNumber])&&(l=Math.max(l,.5));let g=n.pinLabels?Math.max(...Object.values(n.pinLabels).map(v=>v.length*.1)):0,x=g>0?1.1:0;l=Math.max(l,g+x)}let u=n.schHeight;u||(u=Math.max(i.left+BS,i.right+BS));let p={left:{x:-l/2-e,y:i.left/2},bottom:{x:-i.bottom/2,y:-u/2-e},right:{x:l/2+e,y:-i.right/2},top:{x:i.top/2,y:u/2+e}},f={left:{x:0,y:-1},right:{x:0,y:1},top:{x:-1,y:0},bottom:{x:1,y:0}},y=o.map(g=>{let{distanceFromOrthogonalEdge:x,side:v}=g,S=p[v],P=f[v];return{x:S.x+x*P.x,y:S.y+x*P.y,...g}});return{getPortPositionByPinNumber(g){let x=y.find(v=>v.pinNumber.toString()===g.toString());return x||null},getSize(){return{width:l,height:u}},getSizeIncludingPins(){return{width:l+(t.leftSize||t.rightSize?.4:0),height:u+(t.topSize||t.bottomSize?.4:0)}},pinCount:r}},tOt=(0,Fet.default)("tscircuit:core:footprint"),zet=class extends Te{get config(){return{componentName:"Footprint",zodProps:OH}}doInitialPcbFootprintLayout(){if(this.root?.pcbDisabled)return;let n=this.children.filter(p=>p.componentName==="Constraint");if(n.length===0)return;let{isFlipped:e}=this._getPcbPrimitiveFlippedHelpers(),t=p=>e&&"left"in p&&"right"in p?{...p,left:p.right,right:p.left}:p,i=n.flatMap(p=>p._getAllReferencedComponents().componentsWithSelectors).map(({component:p,selector:f,componentSelector:y,edge:g})=>({component:p,selector:f,componentSelector:y,edge:g,bounds:p._getPcbCircuitJsonBounds()}));if(i.some(p=>p.edge))throw new Error("edge constraints not implemented yet for footprint layout, contributions welcome!");function r(p){return i.find(({selector:f})=>f===p)}let s=new e_,o={};function a(p){return p in o||(o[p]=new Ca(p),s.addEditVariable(o[p],Rn.weak)),o[p]}for(let{selector:p,bounds:f}of i){let y=a(`${p}_x`),g=a(`${p}_y`);s.suggestValue(y,f.center.x),s.suggestValue(g,f.center.y)}for(let p of n){let f=p._parsedProps;if("xDist"in f){let{xDist:y,left:g,right:x,edgeToEdge:v,centerToCenter:S}=t(f),P=a(`${g}_x`),T=a(`${x}_x`),k=r(g)?.bounds,C=r(x)?.bounds;if(S){let E=new Dn(T,[-1,P]);s.addConstraint(new Pi(E,si.Eq,f.xDist,Rn.required))}else if(v){let E=new Dn(T,-C.width/2,[-1,P],-k.width/2);s.addConstraint(new Pi(E,si.Eq,f.xDist,Rn.required))}}else if("yDist"in f){let{yDist:y,top:g,bottom:x,edgeToEdge:v,centerToCenter:S}=f,P=a(`${g}_y`),T=a(`${x}_y`),k=r(g)?.bounds,C=r(x)?.bounds;if(S){let E=new Dn(P,[-1,T]);s.addConstraint(new Pi(E,si.Eq,f.yDist,Rn.required))}else if(v){let E=new Dn(P,k.height/2,[-1,T],-C.height/2);s.addConstraint(new Pi(E,si.Eq,f.yDist,Rn.required))}}else if("sameY"in f){let{for:y}=f;if(y.length<2)continue;let g=y.map(v=>a(`${v}_y`)),x=new Dn(...g.slice(1));s.addConstraint(new Pi(x,si.Eq,g[0],Rn.required))}else if("sameX"in f){let{for:y}=f;if(y.length<2)continue;let g=y.map(v=>a(`${v}_x`)),x=new Dn(...g.slice(1));s.addConstraint(new Pi(x,si.Eq,g[0],Rn.required))}}s.updateVariables(),tOt.enabled&&(console.log("Solution to layout constraints:"),console.table(Object.entries(o).map(([p,f])=>({var:p,val:f.value()}))));let c={left:1/0,right:-1/0,top:-1/0,bottom:1/0};for(let{selector:p,bounds:{width:f,height:y}}of i){let g=a(`${p}_x`),x=a(`${p}_y`),v=g.value()-f/2,S=g.value()+f/2,P=x.value()+y/2,T=x.value()-y/2;c.left=Math.min(c.left,v),c.right=Math.max(c.right,S),c.top=Math.max(c.top,P),c.bottom=Math.min(c.bottom,T)}let l={x:-(c.right+c.left)/2,y:-(c.top+c.bottom)/2},u=this.getPrimitiveContainer()._getGlobalPcbPositionBeforeLayout();l.x+=u.x,l.y+=u.y;for(let{component:p,selector:f}of i){let y=a(`${f}_x`),g=a(`${f}_y`);p._setPositionFromLayout({x:y.value()+l.x,y:g.value()+l.y})}}},Det=n=>{if(!n)return null;let t=n.split("?")[0].split("#")[0],i=t.split("/").pop()??t;return i.includes(".")?i.split(".").pop()?.toLowerCase()??null:null},eOt=(n,e)=>{let t=n.replace(/\/+$/,""),i=e.replace(/^\/+/,"");return`${t}/${i}`},$et=(n,e)=>{if(!e||!n.startsWith("/"))return n;try{let t=new URL(e);return t.pathname!=="/"&&n.startsWith(t.pathname)?new URL(n,t.origin).toString():eOt(e,n)}catch{return n}},VA=h.union([h.number(),h.string()]),iet=h.object({x:VA,y:VA,z:VA}),jet=class extends Te{get config(){return{componentName:"CadModel",zodProps:sW}}doInitialCadModelRender(){let n=this._findParentWithPcbComponent();if(!n||!n.pcb_component_id)return;let{db:e}=this.root,{boardThickness:t=0}=this.root?._getBoard()??{},i=n._getPcbCircuitJsonBounds(),r=e.pcb_component.get(n.pcb_component_id),s=this._parsedProps;if(!s||typeof s.modelUrl!="string"&&typeof s.stepUrl!="string")return;let o=n._computePcbGlobalTransformBeforeLayout(),c=Js(o).rotation.angle*180/Math.PI,l=iet.parse({x:0,y:0,z:0});if(typeof s.rotationOffset=="number")l.z=Number(s.rotationOffset);else if(typeof s.rotationOffset=="object"){let v=iet.parse(s.rotationOffset);l.x=Number(v.x),l.y=Number(v.y),l.z=Number(v.z)}let u=uw.parse({x:s.pcbX??0,y:s.pcbY??0,z:s.pcbZ??0,...typeof s.positionOffset=="object"?s.positionOffset:{}}),p=s.zOffsetFromSurface!==void 0?X.parse(s.zOffsetFromSurface):0,f=n.props.layer==="bottom"?"bottom":"top",y=s.modelUrl?Det(s.modelUrl):void 0,g={};if(y==="stl"?g.model_stl_url=this._addCachebustToModelUrl(s.modelUrl):y==="obj"?g.model_obj_url=this._addCachebustToModelUrl(s.modelUrl):y==="gltf"?g.model_gltf_url=this._addCachebustToModelUrl(s.modelUrl):y==="glb"?g.model_glb_url=this._addCachebustToModelUrl(s.modelUrl):y==="step"||y==="stp"?g.model_step_url=this._addCachebustToModelUrl(s.modelUrl):y==="wrl"||y==="vrml"?g.model_wrl_url=this._addCachebustToModelUrl(s.modelUrl):g.model_stl_url=this._addCachebustToModelUrl(s.modelUrl),s.stepUrl){let v=this._addCachebustToModelUrl(s.stepUrl);v&&(g.model_step_url=v)}let x=e.cad_component.insert({position:{x:i.center.x+Number(u.x),y:i.center.y+Number(u.y),z:(f==="bottom"?-t/2:t/2)+(f==="bottom"?-p:p)+Number(u.z)},rotation:{x:Number(l.x),y:(f==="top"?0:180)+Number(l.y),z:f==="bottom"?-(c+Number(l.z))+180:c+Number(l.z)},pcb_component_id:n.pcb_component_id,source_component_id:n.source_component_id,model_unit_to_mm_scale_factor:typeof s.modelUnitToMmScale=="number"?s.modelUnitToMmScale:void 0,...g});this.cad_component_id=x.cad_component_id}_findParentWithPcbComponent(){let n=this.parent;for(;n&&!n.pcb_component_id;)n=n.parent;return n}_addCachebustToModelUrl(n){if(!n)return n;let e=this.root?.platform?.projectBaseUrl,t=$et(n,e);if(!t.includes("modelcdn.tscircuit.com"))return t;let i=this.root?.getClientOrigin()??"";return`${t}${t.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(i)}`}},Bet=class extends Te{constructor(){super(...arguments);d(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"CadAssembly",zodProps:rW}}},nOt=(n,e)=>{if(!n)return;let t={};for(let[i,r]of Object.entries(n)){let s=j1(i,e),o={leftMargin:r.marginLeft??r.leftMargin,rightMargin:r.marginRight??r.rightMargin,topMargin:r.marginTop??r.topMargin,bottomMargin:r.marginBottom??r.bottomMargin};t[`pin${s}`]={...t[`pin${s}`],...o}}return t},ret=class{constructor({input:n}){d(this,"input");this.input=n}solveAndMapToTraces(){let n=[];for(let e of this.input.connections){if(e.pointsToConnect.length!==2)continue;let[t,i]=e.pointsToConnect,r={type:"pcb_trace",pcb_trace_id:"",connection_name:e.name,route:[{route_type:"wire",x:t.x,y:t.y,layer:"top",width:.1},{route_type:"wire",x:i.x,y:i.y,layer:"top",width:.1}]};n.push(r)}return n}},iOt=n=>{let e=Math.min(...n.map(s=>s.center.x)),t=Math.max(...n.map(s=>s.center.x)),i=Math.min(...n.map(s=>s.center.y)),r=Math.max(...n.map(s=>s.center.y));return{minX:e,maxX:t,minY:i,maxY:r}},set=["top","bottom","inner1","inner2"],VS=(n,e=[])=>{let t=[];if(e.length===0){let a=n[0].layers;for(let c of a)t.push(...VS(n.slice(1),[c]));return t}if(n.length===0)return[];let i=n[0],r=i.via||i.optional_via,s=e[e.length-1];if(n.length===1){let a=i;return a.layers&&r?a.layers.map(c=>({layer_path:[...e,c]})):a.layers?.includes(s)?[{layer_path:[...e,s]}]:[]}if(!r)return i.layers&&!i.layers.includes(s)?[]:VS(n.slice(1),e.concat([s]));let o=(i.optional_via?set:set.filter(a=>a!==s)).filter(a=>!i.layers||i.layers?.includes(a));for(let a of o)t.push(...VS(n.slice(1),e.concat(a)));return t};function oet(n){let e={x:n.to.x-n.from.x,y:n.to.y-n.from.y},t=Math.abs(e.x),i=Math.abs(e.y);return t>i?e.x>0?"right":"left":e.y>0?"down":"up"}function $_(n,e){return Math.hypot(n.x-e.x,n.y-e.y)}var rOt=n=>{if(n.length===1)return n[0];if(n.some(c=>c.length===0))throw new Error("Cannot merge routes with zero length");let e=[],t=n[0][0],i=n[0][n[0].length-1],r=n[1][0],s=n[1][n[1].length-1],o=Math.min($_(t,r),$_(t,s)),a=Math.min($_(i,r),$_(i,s));o<a?e.push(...n[0].reverse()):e.push(...n[0]);for(let c=1;c<n.length;c++){let l=e[e.length-1],u=n[c],p=u[0],f=u[u.length-1],y=$_(l,p),g=$_(l,f);y<g?e.push(...u):e.push(...u.reverse())}for(let c=1;c<e.length-1;c++){let l=e[c-1],u=e[c];l.route_type==="wire"&&u.route_type==="wire"&&l.layer!==u.layer&&e.splice(c,0,{x:l.x,y:l.y,from_layer:l.layer,to_layer:u.layer,route_type:"via"})}return e},sOt=(n,e)=>{let t="_getGlobalPcbPositionBeforeLayout"in n?n._getGlobalPcbPositionBeforeLayout():n,i="_getGlobalPcbPositionBeforeLayout"in e?e._getGlobalPcbPositionBeforeLayout():e;return Math.sqrt((t.x-i.x)**2+(t.y-i.y)**2)};function oOt(n,e){if(e.length===0)throw new Error("No candidates given to getClosest method");let t=e[0],i=1/0;for(let r of e){let s=sOt(n,r);s<i&&(t=r,i=s)}return t}var aOt=(n,e)=>{let t=0;t+=n.length??0,t+=e.filter(i=>i.is_crossing).length;for(let i=1;i<e.length;i++){let r=e[i-1],s=e[i],o=Math.abs(r.from.x-r.to.x)<.01,a=Math.abs(s.from.x-s.to.x)<.01;o!==a&&t++}return t},B1=n=>({up:"bottom",down:"top",left:"right",right:"left"})[n]??null,KA=({firstEdge:n,firstEdgePort:e,firstDominantDirection:t,lastEdge:i,lastEdgePort:r,lastDominantDirection:s})=>{if(n&&e)return KA({lastEdge:{from:n.to,to:n.from},lastEdgePort:e,lastDominantDirection:t}).reverse().map(a=>({from:a.to,to:a.from}));let o=[];if(i&&r){let a={x:i.to.x,y:i.to.y};s==="left"||s==="right"?(a.x=r.position.x,o.push({from:i.to,to:{...a}}),o.push({from:a,to:{...r.position}})):(a.y=r.position.y,o.push({from:i.to,to:{...a}}),o.push({from:a,to:{...r.position}}))}return o=o.filter(a=>Fi(a.from,a.to)>.01),o};function cOt(n){try{return[n(),null]}catch(e){return[null,e]}}var lOt=(n,{db:e})=>{let t=n.map(i=>{let r=e.source_port.get(i.source_port_id);if(!r?.source_component_id)return null;let s=e.source_component.get(r.source_component_id);return s?.ftype==="simple_capacitor"?s.max_decoupling_trace_length:null}).filter(i=>i!==null);if(t.length!==0)return Math.min(...t)};function uOt({ports:n,nets:e}){if(n.length>=2)return`${n[0]?.selector} to ${n[1]?.selector}`;if(n.length===1&&e.length===1)return`${n[0]?.selector} to net.${e[0]._parsedProps.name}`}var pOt=(n,{db:e})=>{let t=e.pcb_board.list()[0];if(t.outline){let c=t.outline,l=(u,p)=>{let f=!1;for(let y=0,g=p.length-1;y<p.length;g=y++){let x=p[y].x,v=p[y].y,S=p[g].x,P=p[g].y;v>u.y!=P>u.y&&u.x<(S-x)*(u.y-v)/(P-v)+x&&(f=!f)}return f};return n.some(u=>!l(u,c))}let i=t.width,r=t.height,s=t.center.x,o=t.center.y;return n.some(c=>c.x<s-i/2||c.y<o-r/2||c.x>s+i/2||c.y>o+r/2)},aet=(n,e)=>Math.abs(n-e)<1e-4,hOt=(n,e,{viaDiameter:t=.5}={})=>{let i=[];for(let r=0;r<n.length-1;r++){let[s,o]=[n[r],n[r+1]],a=r-1>=0?n[r-1]:null,c=aet(s.y,o.y),l=aet(s.x,o.x);if(!c&&!l)throw new Error(`getObstaclesFromTrace currently only supports horizontal and vertical traces (not diagonals) Conflicting trace: ${e}, start: (${s.x}, ${s.y}), end: (${o.x}, ${o.y})`);let u={type:"rect",layers:[s.layer],center:{x:(s.x+o.x)/2,y:(s.y+o.y)/2},width:c?Math.abs(s.x-o.x):.1,height:l?Math.abs(s.y-o.y):.1,connectedTo:[e]};if(i.push(u),a&&a.layer===s.layer&&s.layer!==o.layer){let p={type:"rect",layers:[s.layer,o.layer],center:{x:s.x,y:s.y},connectedTo:[e],width:t,height:t};i.push(p)}}return i};function dOt(n,e=4){let{center:t,width:i,height:r,rotation:s}=n,o=[],a=s*Math.PI/180,c=Math.cos(a),l=Math.sin(a),u=(s%360+360)%360;if(r<=i?u>=45&&u<135||u>=225&&u<315:u>=135&&u<225||u>=315||u<45){let f=i/e;for(let y=0;y<e;y++){let g=(y-e/2+.5)*f,x=-g*c,v=-g*l,S=f*1.1,P=Math.abs(r*c)+Math.abs(f*l);o.push({center:{x:t.x+x,y:t.y+v},width:S,height:P})}}else{let f=r/e;for(let y=0;y<e;y++){let g=(y-e/2+.5)*f,x=-g*l,v=g*c,S=Math.abs(i*c)+Math.abs(f*l),P=f*1.1;o.push({center:{x:t.x+x,y:t.y+v},width:S,height:P})}}return o}function fOt(n,e={}){if(n.length<3)return[];let{rectHeight:t=.1}=e,i=[],r=n.map(a=>a.y),s=Math.min(...r),o=Math.max(...r);for(let a=s;a<o;a+=t){let c=a+t/2,l=[];for(let u=0;u<n.length;u++){let p=n[u],f=n[(u+1)%n.length];if(p.y<=c&&f.y>c||f.y<=c&&p.y>c){let y=(c-p.y)*(f.x-p.x)/(f.y-p.y)+p.x;l.push(y)}}l.sort((u,p)=>u-p);for(let u=0;u<l.length;u+=2)if(u+1<l.length){let p=l[u],y=l[u+1]-p;y>1e-6&&i.push({center:{x:p+y/2,y:c},width:y,height:t})}}return i}function mOt(n,e={}){let{center:t,radius:i}=n,{rectHeight:r=.1}=e,s=[],o=Math.ceil(i*2/r);for(let a=0;a<o;a++){let c=t.y-i+(a+.5)*r,l=c-t.y,u=Math.sqrt(i*i-l*l);u>0&&s.push({center:{x:t.x,y:c},width:u*2,height:r})}return s}var Ba=["top","inner1","inner2","bottom"],Yet=(n,e)=>{let t=r=>e?r.concat(r.map(s=>e?.getNetConnectedToId(s)).filter(Boolean)):r,i=[];for(let r of n)if(r.type==="pcb_smtpad"){if(r.shape==="circle")i.push({type:"oval",layers:[r.layer],center:{x:r.x,y:r.y},width:r.radius*2,height:r.radius*2,connectedTo:t([r.pcb_smtpad_id])});else if(r.shape==="rect")i.push({type:"rect",layers:[r.layer],center:{x:r.x,y:r.y},width:r.width,height:r.height,connectedTo:t([r.pcb_smtpad_id])});else if(r.shape==="rotated_rect"){let s={center:{x:r.x,y:r.y},width:r.width,height:r.height,rotation:r.ccw_rotation},o=dOt(s);for(let a of o)i.push({type:"rect",layers:[r.layer],center:a.center,width:a.width,height:a.height,connectedTo:t([r.pcb_smtpad_id])})}}else if(r.type==="pcb_keepout")r.shape==="circle"?i.push({type:"oval",layers:r.layers,center:{x:r.center.x,y:r.center.y},width:r.radius*2,height:r.radius*2,connectedTo:[]}):r.shape==="rect"&&i.push({type:"rect",layers:r.layers,center:{x:r.center.x,y:r.center.y},width:r.width,height:r.height,connectedTo:[]});else if(r.type==="pcb_cutout"){if(r.shape==="rect")i.push({type:"rect",layers:Ba,center:{x:r.center.x,y:r.center.y},width:r.width,height:r.height,connectedTo:[]});else if(r.shape==="circle"){let s=mOt({center:r.center,radius:r.radius},{rectHeight:.6});for(let o of s)i.push({type:"rect",layers:Ba,center:o.center,width:o.width,height:o.height,connectedTo:[]})}else if(r.shape==="polygon"){let s=fOt(r.points,{rectHeight:.6});for(let o of s)i.push({type:"rect",layers:Ba,center:o.center,width:o.width,height:o.height,connectedTo:[]})}}else if(r.type==="pcb_hole")r.hole_shape==="oval"?i.push({type:"oval",center:{x:r.x,y:r.y},width:r.hole_width,height:r.hole_height,connectedTo:[]}):r.hole_shape==="rect"?i.push({type:"rect",layers:Ba,center:{x:r.x,y:r.y},width:r.hole_width,height:r.hole_height,connectedTo:[]}):r.hole_shape==="square"?i.push({type:"rect",layers:Ba,center:{x:r.x,y:r.y},width:r.hole_diameter,height:r.hole_diameter,connectedTo:[]}):(r.hole_shape==="round"||r.hole_shape==="circle")&&i.push({type:"rect",layers:Ba,center:{x:r.x,y:r.y},width:r.hole_diameter,height:r.hole_diameter,connectedTo:[]});else if(r.type==="pcb_plated_hole")r.shape==="circle"?i.push({type:"oval",layers:Ba,center:{x:r.x,y:r.y},width:r.outer_diameter,height:r.outer_diameter,connectedTo:t([r.pcb_plated_hole_id])}):r.shape==="circular_hole_with_rect_pad"?i.push({type:"rect",layers:Ba,center:{x:r.x,y:r.y},width:r.rect_pad_width,height:r.rect_pad_height,connectedTo:t([r.pcb_plated_hole_id])}):(r.shape==="oval"||r.shape==="pill")&&i.push({type:"oval",layers:Ba,center:{x:r.x,y:r.y},width:r.outer_width,height:r.outer_height,connectedTo:t([r.pcb_plated_hole_id])});else if(r.type==="pcb_trace"){let s=hOt(r.route.map(o=>({x:o.x,y:o.y,layer:"layer"in o?o.layer:o.from_layer})),r.source_trace_id);i.push(...s)}else if(r.type==="pcb_via"){let s=!!(r.net_is_assignable??r.netIsAssignable);i.push({type:"rect",layers:r.layers,center:{x:r.x,y:r.y},connectedTo:[],width:r.outer_diameter,height:r.outer_diameter,netIsAssignable:s||void 0})}return i},ml=({anchor_position:n,anchor_side:e,text:t,font_size:i=.18})=>{let r=.1*(i/.18),s=t.length*r,o=i,a={...n};switch(e){case"right":a.x-=s/2;break;case"left":a.x+=s/2;break;case"top":a.y-=o/2;break;case"bottom":a.y+=o/2;break}return a},u9=({db:n,source_trace_id:e,sameNetOnly:t,differentNetOnly:i})=>{!t&&!i&&(i=!0);let r=n.source_trace.get(e),s=[];for(let o of n.schematic_trace.list()){if(o.source_trace_id===e)continue;let c=n.source_trace.get(o.source_trace_id)?.subcircuit_connectivity_map_key===r.subcircuit_connectivity_map_key;i&&c||t&&!c||s.push(o)}return s},_Ot=({edges:n,otherEdges:e})=>{let t=[...n];for(let i=0;i<t.length;i++){if(i>2e3)throw new Error("Over 2000 iterations spent inside createSchematicTraceCrossingSegments, you have triggered an infinite loop, please report this!");let r=t[i],s=Math.abs(r.from.x-r.to.x)<.01?"vertical":r.from.y===r.to.y?"horizontal":"not-orthogonal";if(s==="not-orthogonal")continue;let o=[];for(let x of e){let v=x.from.x===x.to.x?"vertical":x.from.y===x.to.y?"horizontal":"not-orthogonal";if(v==="not-orthogonal"||s===v)continue;if(Ia([r.from,r.to],[x.from,x.to],{lineThickness:.01})){let P=s==="vertical"?r.from.x:x.from.x,T=s==="vertical"?x.from.y:r.from.y,k={x:P,y:T};o.push({otherEdge:x,crossingPoint:k,distanceFromEdgeFrom:Fi(r.from,k)})}}if(o.length===0)continue;let a=o[0];for(let x of o)x.distanceFromEdgeFrom<a.distanceFromEdgeFrom&&(a=x);let c=a.crossingPoint,l=.075;if(c.x===r.from.x&&c.y===r.from.y)continue;let u=bw(r.from,c),p={x:c.x-u.x*l/2,y:c.y-u.y*l/2},f={x:c.x+u.x*l/2,y:c.y+u.y*l/2},y=Fi(f,r.to)<l,g=[{from:r.from,to:p},{from:p,to:f,is_crossing:!0},{from:f,to:r.to}];t.splice(i,1,...g),i+=g.length-2,y&&i++}return t},JA=.001,j_=(n,e)=>{let t=Math.min(e.from.x,e.to.x),i=Math.max(e.from.x,e.to.x),r=Math.min(e.from.y,e.to.y),s=Math.max(e.from.y,e.to.y);return n.x>=t&&n.x<=i&&n.y>=r&&n.y<=s},cet=n=>{let e=Math.abs(n.from.x-n.to.x)<JA,t=Math.abs(n.from.y-n.to.y)<JA;return e?"vertical":t?"horizontal":"diagonal"},yOt=(n,e)=>{let t=cet(n),i=cet(e);if(t===i)return null;if(t==="vertical"&&i==="horizontal"||t==="horizontal"&&i==="vertical"){let p=t==="vertical"?n:e,f=t==="horizontal"?n:e,y=p.from.x,g=f.from.y,x={x:y,y:g};return j_(x,n)&&j_(x,e)?x:null}if(t==="vertical"||i==="vertical"){let p=t==="vertical"?n:e,f=t==="vertical"?e:n,y=p.from.x,g=(f.to.y-f.from.y)/(f.to.x-f.from.x),x=f.from.y-g*f.from.x,v=g*y+x,S={x:y,y:v};return j_(S,n)&&j_(S,e)?S:null}let r=(n.to.y-n.from.y)/(n.to.x-n.from.x),s=n.from.y-r*n.from.x,o=(e.to.y-e.from.y)/(e.to.x-e.from.x),a=e.from.y-o*e.from.x;if(Math.abs(r-o)<JA)return null;let c=(a-s)/(r-o),l=r*c+s,u={x:c,y:l};return j_(u,n)&&j_(u,e)?u:null},gOt=({edges:n,db:e,source_trace_id:t})=>{let i=u9({db:e,source_trace_id:t,sameNetOnly:!0}).flatMap(s=>s.edges),r=new Map;for(let s of n)for(let o of i){let a=yOt(s,o);if(a){let c=`${a.x.toFixed(6)},${a.y.toFixed(6)}`;r.has(c)||r.set(c,a)}}return Array.from(r.values())};function xOt(n,e={}){let{minX:t,maxX:i,minY:r,maxY:s}=n,o=e.padding??1;if(!isFinite(t)||!isFinite(i)||!isFinite(r)||!isFinite(s))return[];let a=t-o,c=i+o,l=s+o,u=r-o,p=.01;return[{type:"rect",layers:["top"],center:{x:(a+c)/2,y:l},width:c-a,height:p,connectedTo:[]},{type:"rect",layers:["top"],center:{x:(a+c)/2,y:u},width:c-a,height:p,connectedTo:[]},{type:"rect",layers:["top"],center:{x:a,y:(l+u)/2},width:p,height:l-u,connectedTo:[]},{type:"rect",layers:["top"],center:{x:c,y:(l+u)/2},width:p,height:l-u,connectedTo:[]}]}var bOt=n=>{let e=n.root.db,t=n._findConnectedPorts().ports??[],i=new Set(t.map(o=>o.schematic_port_id)),r=[];for(let o of e.toArray()){if(o.type==="schematic_component"){let a=!!o.symbol_name,c=o.size.width>o.size.height?"horz":"vert";r.push({type:"rect",layers:["top"],center:o.center,width:o.size.width+(a&&c==="horz"?-.5:0),height:o.size.height+(a&&c==="vert"?-.5:0),connectedTo:[]})}if(o.type==="schematic_port"){if(i.has(o.schematic_port_id))continue;let a=o.facing_direction?vw(o.facing_direction):{x:0,y:0};r.push({type:"rect",layers:["top"],center:{x:o.center.x-a.x*.1,y:o.center.y-a.y*.1},width:.1+Math.abs(a.x)*.3,height:.1+Math.abs(a.y)*.3,connectedTo:[]})}o.type==="schematic_text"&&r.push({type:"rect",layers:["top"],center:o.position,width:(o.text?.length??0)*.1,height:.2,connectedTo:[]}),o.type==="schematic_box"&&r.push({type:"rect",layers:["top"],center:{x:o.x,y:o.y},width:o.width,height:o.height,connectedTo:[]})}let s=Ret(e.toArray());return r.push(...xOt(s,{padding:1})),r},vOt=({edges:n,db:e,source_trace_id:t})=>{let i=e.source_trace.get(t),r=u9({db:e,source_trace_id:t,differentNetOnly:!0}).flatMap(o=>o.edges),s=o=>{let{from:a,to:c}=o;return a.x===c.x?"vertical":"horizontal"};for(let o of n){let a=s(o),c=()=>r.find(u=>s(u)===a&&Ia([o.from,o.to],[u.from,u.to],{lineThickness:.05})),l=c();for(;l;)a==="horizontal"?(o.from.y+=.1,o.to.y+=.1):(o.from.x+=.1,o.to.x+=.1),l=c()}},QA=n=>{switch(n){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:}},wOt=VW.version??"unknown",L1=class extends Error{constructor(n){super(`${n} (capacity-autorouter@${wOt})`),this.name="AutorouterError"}},WS=class extends Error{constructor(n){super(n.message),this.errorData=n,this.name="TraceConnectionError"}},SOt=n=>{if(n.root?._featureMspSchematicTraceRouting||n._couldNotFindPort||n.root?.schematicDisabled)return;let{db:e}=n.root,{_parsedProps:t,parent:i}=n;if(!i)throw new Error("Trace has no parent");let r,s;try{let U=n._findConnectedPorts();r=U.allPortsFound,s=U.portsWithSelectors??[]}catch(U){if(U instanceof WS){e.source_trace_not_connected_error.insert({...U.errorData,error_type:"source_trace_not_connected_error"});return}throw U}let{netsWithSelectors:o}=n._findConnectedNets();if(!r)return;let c=s.map(U=>U.port.schematic_port_id).sort().join(","),l=n.root?._getBoard();if(l?._connectedSchematicPortPairs&&l._connectedSchematicPortPairs.has(c))return;let u={name:n.source_trace_id,pointsToConnect:[]},p=bOt(n),f=s.filter(({port:U})=>U.schematic_port_id!==null).map(({port:U})=>({port:U,position:U._getGlobalSchematicPositionAfterLayout(),schematic_port_id:U.schematic_port_id??void 0,facingDirection:U.facingDirection}));if(f.length===1&&o.length===1){let U=o[0].net,{port:H,position:Q}=f[0],tt=n.getSubcircuit().selectAll("netlabel").find(nt=>{let et=nt._parsedProps.connection??nt._parsedProps.connectsTo;return et?Array.isArray(et)?et.some(dt=>n.getSubcircuit().selectOne(dt,{port:!0})===H):n.getSubcircuit().selectOne(et,{port:!0})===H:!1});if(!tt){let nt=e.schematic_net_label.getWhere({source_trace_id:n.source_trace_id});nt&&(tt=nt)}if(tt){let nt="_getGlobalSchematicPositionBeforeLayout"in tt?tt._getGlobalSchematicPositionBeforeLayout():tt.anchor_position,et=[];Q.x===nt.x||Q.y===nt.y?et.push({from:Q,to:nt}):(et.push({from:Q,to:{x:nt.x,y:Q.y}}),et.push({from:{x:nt.x,y:Q.y},to:nt}));let ht=e.schematic_trace.insert({source_trace_id:n.source_trace_id,edges:et,junctions:[],subcircuit_connectivity_map_key:n.subcircuit_connectivity_map_key??void 0});n.schematic_trace_id=ht.schematic_trace_id;return}if(n.props.schDisplayLabel){let nt=B1(H.facingDirection)??"bottom";e.schematic_net_label.insert({text:n.props.schDisplayLabel,source_net_id:U.source_net_id,anchor_position:Q,center:ml({anchor_position:Q,anchor_side:nt,text:n.props.schDisplayLabel}),anchor_side:nt});return}let V=B1(H.facingDirection)??"bottom",ot=e.schematic_net_label.insert({text:U._parsedProps.name,source_net_id:U.source_net_id,anchor_position:Q,center:ml({anchor_position:Q,anchor_side:V,text:U._parsedProps.name}),anchor_side:V});return}if(n.props.schDisplayLabel&&("from"in n.props&&"to"in n.props||"path"in n.props)){n._doInitialSchematicTraceRenderWithDisplayLabel();return}if(f.length<2)return;let x=(()=>{let U=[];for(let Q=0;Q<f.length-1;Q++){let tt=f[Q],V=f[Q+1],ot=Wc({x:tt.position.x,y:tt.position.y,facingDirection:QA(tt.facingDirection)},{x:V.position.x,y:V.position.y,facingDirection:QA(V.facingDirection)});for(let nt=0;nt<ot.length-1;nt++)U.push({from:ot[nt],to:ot[nt+1]})}let H=(Q,tt)=>{let V=tt.width/2,ot=tt.height/2,nt=tt.center.x-V,et=tt.center.x+V,ht=tt.center.y-ot,dt=tt.center.y+ot,St=ut=>ut.x>=nt&&ut.x<=et&&ut.y>=ht&&ut.y<=dt;return St(Q.from)||St(Q.to)?!0:[[{x:nt,y:ht},{x:et,y:ht}],[{x:et,y:ht},{x:et,y:dt}],[{x:et,y:dt},{x:nt,y:dt}],[{x:nt,y:dt},{x:nt,y:ht}]].some(ut=>Ia([Q.from,Q.to],ut,{lineThickness:0}))};for(let Q of U)for(let tt of p)if(H(Q,tt))return null;return U})();x&&x.length===0&&(x=null),u.pointsToConnect=f.map(({position:U})=>({...U,layer:"top"}));let v=iOt(p),S=2,P={minTraceWidth:.1,obstacles:p,connections:[u],bounds:{minX:v.minX-S,maxX:v.maxX+S,minY:v.minY-S,maxY:v.maxY+S},layerCount:1},T=aw,k=!1;if(n.getSubcircuit().props._schDirectLineRoutingEnabled&&(T=ret,k=!0),!x){let H=new T({input:P,MAX_ITERATIONS:100,OBSTACLE_MARGIN:.1,isRemovePathLoopsEnabled:!0,isShortenPathWithShortcutsEnabled:!0,marginsWithCosts:[{margin:1,enterCost:0,travelCostFactor:1},{margin:.3,enterCost:0,travelCostFactor:1},{margin:.2,enterCost:0,travelCostFactor:2},{margin:.1,enterCost:0,travelCostFactor:3}]}).solveAndMapToTraces();if(H.length===0){if(n._isSymbolToChipConnection()||n._isSymbolToSymbolConnection()||n._isChipToChipConnection()){n._doInitialSchematicTraceRenderWithDisplayLabel();return}H=new ret({input:P}).solveAndMapToTraces(),k=!0}let[{route:Q}]=H;x=[];for(let tt=0;tt<Q.length-1;tt++)x.push({from:Q[tt],to:Q[tt+1]})}let C=n.source_trace_id,E=[];if(!k){vOt({edges:x,db:e,source_trace_id:C});let U=u9({db:e,source_trace_id:C,differentNetOnly:!0}).flatMap(H=>H.edges);x=_Ot({edges:x,otherEdges:U}),E=gOt({edges:x,db:e,source_trace_id:n.source_trace_id})}if(!x||x.length===0)return;let N=x[x.length-1],I=f[f.length-1],A=oet(N);x.push(...KA({lastEdge:N,lastEdgePort:I,lastDominantDirection:A}));let R=x[0],j=f[0],B=oet(R);if(x.unshift(...KA({firstEdge:R,firstEdgePort:j,firstDominantDirection:B})),!n.source_trace_id)throw new Error("Missing source_trace_id for schematic trace insertion.");if(n.getSubcircuit()._parsedProps.schTraceAutoLabelEnabled&&aOt(E,x)>=5&&(n._isSymbolToChipConnection()||n._isSymbolToSymbolConnection()||n._isChipToChipConnection())){n._doInitialSchematicTraceRenderWithDisplayLabel();return}let G=e.schematic_trace.insert({source_trace_id:n.source_trace_id,edges:x,junctions:E,subcircuit_connectivity_map_key:n.subcircuit_connectivity_map_key??void 0});n.schematic_trace_id=G.schematic_trace_id;for(let{port:U}of s)U.schematic_port_id&&e.schematic_port.update(U.schematic_port_id,{is_connected:!0});l?._connectedSchematicPortPairs&&l._connectedSchematicPortPairs.add(c)};function Xet(n){let e=0;for(let t=0;t<n.length;t++){let i=n[t];if(i.route_type==="wire"){let r=n[t+1];if(r){let s=r.x-i.x,o=r.y-i.y;e+=Math.sqrt(s*s+o*o)}}else i.route_type==="via"&&(e+=1.6)}return e}var YS=n=>({...n._getGlobalPcbPositionAfterLayout(),layers:n.getAvailablePcbLayers()}),POt=!1;function kOt(n){if(n.root?.pcbDisabled)return;let{db:e}=n.root,{_parsedProps:t,parent:i}=n,r=n.getSubcircuit();if(!i)throw new Error("Trace has no parent");if(r._parsedProps.routingDisabled)return;let s=r._parsedProps.pcbRouteCache?.pcbTraces;if(s){let A=e.pcb_trace.insert({route:s.flatMap(R=>R.route),source_trace_id:n.source_trace_id,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:n.getGroup()?.pcb_group_id??void 0});n.pcb_trace_id=A.pcb_trace_id;return}if(t.pcbPath&&t.pcbPath.length>0||!r._shouldUseTraceByTraceRouting())return;let{allPortsFound:o,ports:a}=n._findConnectedPorts(),c=[];if(!o)return;let l=[];for(let A of a)A._hasMatchedPcbPrimitive()||l.push(A);if(l.length>0){e.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:n.source_trace_id,message:`Some ports did not have a matching PCB primitive (e.g. a pad or plated hole), this can happen if a footprint is missing. As a result, ${n} wasn't routed. Missing ports: ${l.map(A=>A.getString()).join(", ")}`,pcb_trace_id:n.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:l.map(A=>A.pcb_port_id).filter(Boolean)});return}let u=n._findConnectedNets().netsWithSelectors;if(a.length===0&&u.length===2){n.renderError("Trace connects two nets, we haven't implemented a way to route this yet");return}else if(a.length===1&&u.length===1){let A=a[0],j=u[0].net.getAllConnectedPorts().filter(G=>G!==A);if(j.length===0){console.log("Nothing to connect this port to, the net is empty. TODO should emit a warning!");return}let B=oOt(A,j);c.push(B),a.push(B)}else if(a.length>1&&u.length>=1){n.renderError("Trace has more than one port and one or more nets, we don't currently support this type of complex trace routing");return}let p=a.flatMap(A=>A.matchedComponents.filter(R=>R.componentName==="TraceHint")),f=(n._parsedProps.pcbRouteHints??[]).concat(p.flatMap(A=>A.getPcbRouteHints()));if(a.length>2){n.renderError(`Trace has more than two ports (${a.map(A=>A.getString()).join(", ")}), routing between more than two ports for a single trace is not implemented`);return}if(n.getSubcircuit().selectAll("trace").filter(A=>A.renderPhaseStates.PcbTraceRender.initialized).some(A=>A._portsRoutedOnPcb.length===a.length&&A._portsRoutedOnPcb.every(R=>a.includes(R))))return;let x=[];f.length===0?x=[YS(a[0]),YS(a[1])]:x=[YS(a[0]),...f,YS(a[1])];let v=VS(x);if(POt&&v.length===0){n.renderError(`Could not find a common layer (using hints) for trace ${n.getString()}`);return}let S=er(n.root.db.toArray()),[P,T]=cOt(()=>Yet(n.root.db.toArray()));if(T){n.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:n.pcb_trace_id,message:`Error getting obstacles for autorouting: ${T.message}`,source_trace_id:n.source_trace_id,center:{x:0,y:0},pcb_port_ids:a.map(A=>A.pcb_port_id),pcb_trace_id:n.pcb_trace_id,pcb_component_ids:[]});return}for(let A of P)if(A.connectedTo.length>0){let j=S.getNetConnectedToId(A.connectedTo[0]);j&&A.connectedTo.push(j)}let k=[];if(v.length===0)k=x;else{let A=v[0].layer_path;k=x.map((R,j)=>R.via?{...R,via_to_layer:A[j]}:{...R,layers:[A[j]]})}k[0].pcb_port_id=a[0].pcb_port_id,k[k.length-1].pcb_port_id=a[1].pcb_port_id;let C=[];for(let[A,R]of Aet(k)){let j="via_to_layer"in A?A.via_to_layer:null,B=2,G="layers"in A&&A.layers.length===1?A.layers[0]:j??"top",U="layers"in R&&R.layers.length===1?R.layers[0]:j??"top",H="pcb_port_id"in A?A.pcb_port_id:null,Q="pcb_port_id"in R?R.pcb_port_id:null,tt=n._getExplicitTraceThickness()??n.getSubcircuit()._parsedProps.minTraceWidth??.16,V=new aw({OBSTACLE_MARGIN:tt*2,isRemovePathLoopsEnabled:!0,optimizeWithGoalBoxes:!!(H&&Q),connMap:S,input:{obstacles:P,minTraceWidth:tt,connections:[{name:n.source_trace_id,pointsToConnect:[{...A,layer:G,pcb_port_id:H},{...R,layer:U,pcb_port_id:Q}]}],layerCount:n.getSubcircuit()._getSubcircuitLayerCount(),bounds:{minX:Math.min(A.x,R.x)-B,maxX:Math.max(A.x,R.x)+B,minY:Math.min(A.y,R.y)-B,maxY:Math.max(A.y,R.y)+B}}}),ot=null;try{ot=V.solveAndMapToTraces()}catch(ht){n.renderError({type:"pcb_trace_error",pcb_trace_error_id:n.source_trace_id,error_type:"pcb_trace_error",message:`error solving route: ${ht.message}`,source_trace_id:n.pcb_trace_id,center:{x:(A.x+R.x)/2,y:(A.y+R.y)/2},pcb_port_ids:a.map(dt=>dt.pcb_port_id),pcb_trace_id:n.pcb_trace_id,pcb_component_ids:a.map(dt=>dt.pcb_component_id)})}if(!ot)return;if(ot.length===0){n.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:n.pcb_trace_id,message:`Could not find a route for ${n}`,source_trace_id:n.source_trace_id,center:{x:(A.x+R.x)/2,y:(A.y+R.y)/2},pcb_port_ids:a.map(ht=>ht.pcb_port_id),pcb_trace_id:n.pcb_trace_id,pcb_component_ids:a.map(ht=>ht.pcb_component_id)});return}let[nt]=ot;j&&(nt.route=nt.route.map(ht=>(ht.route_type==="wire"&&!ht.layer&&(ht.layer=j),ht))),H&&nt.route[0].route_type==="wire"&&(nt.route[0].start_pcb_port_id=H);let et=nt.route[nt.route.length-1];Q&&et.route_type==="wire"&&(et.end_pcb_port_id=Q),C.push(nt.route)}let E=rOt(C),N=Xet(E),I=e.pcb_trace.insert({route:E,source_trace_id:n.source_trace_id,subcircuit_id:n.getSubcircuit()?.subcircuit_id,trace_length:N});n._portsRoutedOnPcb=a,n.pcb_trace_id=I.pcb_trace_id;for(let A of E)A.route_type==="via"&&e.pcb_via.insert({pcb_trace_id:I.pcb_trace_id,x:A.x,y:A.y,hole_diameter:.3,outer_diameter:.6,layers:[A.from_layer,A.to_layer],from_layer:A.from_layer,to_layer:A.to_layer});n._insertErrorIfTraceIsOutsideBoard(E,a)}function TOt(n){if(n.root?.pcbDisabled)return;let{db:e}=n.root,{_parsedProps:t}=n,i=n.getSubcircuit();if(!t.pcbPath)return;let{allPortsFound:r,ports:s,portsWithSelectors:o}=n._findConnectedPorts();if(!r)return;let a=[];for(let P of s)P._hasMatchedPcbPrimitive()||a.push(P);if(a.length>0){e.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:n.source_trace_id,message:`Some ports did not have a matching PCB primitive (e.g. a pad or plated hole), this can happen if a footprint is missing. As a result, ${n} wasn't routed. Missing ports: ${a.map(P=>P.getString()).join(", ")}`,pcb_trace_id:n.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:a.map(P=>P.pcb_port_id).filter(Boolean)});return}let c;t.pcbPathRelativeTo&&(c=o.find(P=>P.selector===t.pcbPathRelativeTo)?.port,c||(c=n.getSubcircuit().selectOne(t.pcbPathRelativeTo))),c||(c=s[0]);let l=s.find(P=>P!==c)??s[1],u=c.getAvailablePcbLayers()[0]||"top",p=n._getExplicitTraceThickness()??n.getSubcircuit()._parsedProps.minTraceWidth??.16,f=c._getGlobalPcbPositionAfterLayout(),y=l._getGlobalPcbPositionAfterLayout(),g=[];g.push({route_type:"wire",x:f.x,y:f.y,width:p,layer:u,start_pcb_port_id:c.pcb_port_id});let x=c?._computePcbGlobalTransformBeforeLayout?.()||Qi();for(let P of t.pcbPath){let T,k=!1;if(typeof P=="string"){let E=n.getSubcircuit().selectOne(P,{type:"port"});if(!E){e.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:n.source_trace_id,message:`Could not resolve pcbPath selector "${P}" for ${n}`,pcb_trace_id:n.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:[]});continue}let N=E._getGlobalPcbPositionAfterLayout();T={x:N.x,y:N.y},k=!0}else T={x:P.x,y:P.y},k=!1;let C=k?T:ze(x,T);g.push({route_type:"wire",x:C.x,y:C.y,width:p,layer:u})}g.push({route_type:"wire",x:y.x,y:y.y,width:p,layer:u,end_pcb_port_id:l.pcb_port_id});let v=Xet(g),S=e.pcb_trace.insert({route:g,source_trace_id:n.source_trace_id,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:n.getGroup()?.pcb_group_id??void 0,trace_length:v});n._portsRoutedOnPcb=s,n.pcb_trace_id=S.pcb_trace_id,n._insertErrorIfTraceIsOutsideBoard(g,s)}function EOt(n){if(n.root?.schematicDisabled)return;let{db:e}=n.root,{_parsedProps:t,parent:i}=n;if(!i)throw new Error("Trace has no parent");let{allPortsFound:r,portsWithSelectors:s}=n._findConnectedPorts();if(!r)return;let o=s.map(({port:k})=>({port:k,position:k._getGlobalSchematicPositionAfterLayout(),schematic_port_id:k.schematic_port_id,facingDirection:k.facingDirection}));if(o.length<2)throw new Error("Expected at least two ports in portsWithPosition.");let a,c,l=o[0].position,u=o[0].port;if("path"in n.props){if(n.props.path.length!==2)throw new Error("Invalid 'path': Must contain exactly two elements.");[a,c]=n.props.path}else{if(!("from"in n.props&&"to"in n.props))throw new Error("Missing 'from' or 'to' properties in props.");a=n.props.from,c=n.props.to}if(!u.source_port_id)throw new Error(`Missing source_port_id for the 'from' port (${a}).`);let p=o[1].position,f=o[1].port;if(!f.source_port_id)throw new Error(`Missing source_port_id for the 'to' port (${c}).`);let y=e.schematic_net_label.list().find(k=>k.source_net_id===u.source_port_id),g=e.schematic_net_label.list().find(k=>k.source_net_id===f.source_port_id),[x,v]=s.map(({port:k})=>k),P=x.parent?.config.shouldRenderAsSchematicBox?`${x?.parent?.props.name}_${x?.props.name}`:`${v?.parent?.props.name}_${v?.props.name}`,T=n.props.schDisplayLabel??P;if(y&&y.text!==T&&(y.text=`${T} / ${y.text}`),g&&g?.text!==T&&(g.text=`${T} / ${g.text}`),!g){let k=B1(f.facingDirection)??"bottom";e.schematic_net_label.insert({text:n.props.schDisplayLabel??P,source_net_id:f.source_port_id,anchor_position:p,center:ml({anchor_position:p,anchor_side:k,text:n.props.schDisplayLabel??P}),anchor_side:k})}if(!y){let k=B1(u.facingDirection)??"bottom";e.schematic_net_label.insert({text:n.props.schDisplayLabel??P,source_net_id:u.source_port_id,anchor_position:l,center:ml({anchor_position:l,anchor_side:k,text:n.props.schDisplayLabel??P}),anchor_side:k})}}function MOt(n){let{_parsedProps:e,parent:t}=n;if(!t)throw new Error("Trace has no parent");let r=n.getTracePortPathSelectors().map(s=>({selector:s,port:n.getSubcircuit().selectOne(s,{type:"port"})??null}));for(let{selector:s,port:o}of r)if(!o){let a,c,l=s.lastIndexOf(".");if(l!==-1&&l>s.lastIndexOf(" "))a=s.slice(0,l),c=s.slice(l+1);else{let k=s.match(/^(.*[ >])?([^ >]+)$/);a=k?.[1]?.trim()??"",c=k?.[2]??s}let u=a?n.getSubcircuit().selectOne(a):null;if(!u&&a&&!/[.#\[]/.test(a)&&(u=n.getSubcircuit().selectOne(`.${a}`)),!u){let k=a?`Could not find port for selector "${s}". Component "${a}" not found`:`Could not find port for selector "${s}"`,C=n.getSubcircuit(),E=C.getGroup();throw new WS({error_type:"source_trace_not_connected_error",message:k,subcircuit_id:C.subcircuit_id??void 0,source_group_id:E?.source_group_id??void 0,source_trace_id:n.source_trace_id??void 0,selectors_not_found:[s]})}let p=u.children.filter(k=>k.componentName==="Port"),f=c.includes(".")?c.split(".").pop()??"":c,y=p.flatMap(k=>k.getNameAndAliases()),g=y.some(k=>!/^(pin\d+|\d+)$/.test(k)),x=Array.from(new Set(y)).join(", "),v;p.length===0?v="It has no ports":g?v=`It has [${x}]`:v=`It has ${p.length} pins and no pinLabels (consider adding pinLabels)`;let S=`Could not find port for selector "${s}". Component "${u.props.name??a}" found, but does not have pin "${f}". ${v}`,P=n.getSubcircuit(),T=P.getGroup();throw new WS({error_type:"source_trace_not_connected_error",message:S,subcircuit_id:P.subcircuit_id??void 0,source_group_id:T?.source_group_id??void 0,source_trace_id:n.source_trace_id??void 0,selectors_not_found:[s]})}return r.some(s=>!s.port)?{allPortsFound:!1}:{allPortsFound:!0,portsWithSelectors:r,ports:r.map(({port:s})=>s)}}var oo=class extends Te{constructor(e){super(e);d(this,"source_trace_id",null);d(this,"pcb_trace_id",null);d(this,"schematic_trace_id",null);d(this,"_portsRoutedOnPcb");d(this,"subcircuit_connectivity_map_key",null);d(this,"_traceConnectionHash",null);d(this,"_couldNotFindPort");this._portsRoutedOnPcb=[]}_getExplicitTraceThickness(){return this._parsedProps.thickness??this._parsedProps.width}get config(){return{zodProps:RH,componentName:"Trace"}}_getTracePortOrNetSelectorListFromProps(){return"from"in this.props&&"to"in this.props?[typeof this.props.from=="string"?this.props.from:this.props.from.getPortSelector(),typeof this.props.to=="string"?this.props.to:this.props.to.getPortSelector()]:"path"in this.props?this.props.path.map(e=>typeof e=="string"?e:e.getPortSelector()):[]}getTracePortPathSelectors(){return this._getTracePortOrNetSelectorListFromProps().filter(e=>!e.includes("net."))}getTracePathNetSelectors(){return this._getTracePortOrNetSelectorListFromProps().filter(e=>e.includes("net."))}_findConnectedPorts(){return MOt(this)}_resolveNet(e){let t=this.getSubcircuit().selectOne(e,{type:"net"});if(t)return t;let i=e.match(/^net\.(.+)$/),r=i?i[1]:null;if(!r)return null;let s=this.root?._getBoard();return s?s.getDescendants().find(a=>a.componentName==="Net"&&a._parsedProps.name===r)||null:(this.renderError(`Could not find a <board> ancestor for ${this}, so net "${e}" cannot be resolved`),null)}_findConnectedNets(){let e=this.getTracePathNetSelectors().map(i=>({selector:i,net:this._resolveNet(i)})),t=e.filter(i=>!i.net);return t.length>0&&this.renderError(`Could not find net for selector "${t[0].selector}" inside ${this}`),{netsWithSelectors:e,nets:e.map(i=>i.net)}}_getAllTracesConnectedToSameNet(){let e=this.getSubcircuit().selectAll("trace"),t=this._findConnectedNets().nets,i=this._findConnectedPorts().ports??[];return e.filter(r=>{if(r===this)return!1;let s=r._findConnectedNets().nets,o=r._findConnectedPorts().ports??[];return s.some(a=>t.includes(a))||o.some(a=>i.includes(a))})}_isExplicitlyConnectedToPort(e){let{allPortsFound:t,portsWithSelectors:i}=this._findConnectedPorts();return t?i.map(s=>s.port).includes(e):!1}_isExplicitlyConnectedToNet(e){return this._findConnectedNets().nets.includes(e)}doInitialCreateNetsFromProps(){KS(this,this.getTracePathNetSelectors())}_computeTraceConnectionHash(){let{allPortsFound:e,ports:t}=this._findConnectedPorts();return!e||!t?null:[...t].sort((s,o)=>(s.pcb_port_id||"").localeCompare(o.pcb_port_id||"")).map(s=>s.pcb_port_id).join(",")}doInitialSourceTraceRender(){let{db:e}=this.root,{_parsedProps:t,parent:i}=this;if(!i){this.renderError("Trace has no parent");return}let r,s;try{let p=this._findConnectedPorts();r=p.allPortsFound,s=p.portsWithSelectors??[]}catch(p){if(p instanceof WS){e.source_trace_not_connected_error.insert({...p.errorData,error_type:"source_trace_not_connected_error"}),this._couldNotFindPort=!0;return}throw p}if(!r)return;this._traceConnectionHash=this._computeTraceConnectionHash();let a=e.source_trace.list().find(p=>p.subcircuit_connectivity_map_key===this.subcircuit_connectivity_map_key&&p.connected_source_port_ids.sort().join(",")===this._traceConnectionHash);if(a){this.source_trace_id=a.source_trace_id;return}let c=this._findConnectedNets().nets,l=uOt({ports:s,nets:c}),u=e.source_trace.insert({connected_source_port_ids:s.map(p=>p.port.source_port_id),connected_source_net_ids:c.map(p=>p.source_net_id),subcircuit_id:this.getSubcircuit()?.subcircuit_id,max_length:lOt(s.map(p=>p.port),{db:e})??t.maxLength,display_name:l,min_trace_thickness:this._getExplicitTraceThickness()});this.source_trace_id=u.source_trace_id}_insertErrorIfTraceIsOutsideBoard(e,t){let{db:i}=this.root;pOt(e,{db:i})&&i.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:this.source_trace_id,message:`Trace ${this.getString()} routed outside the board boundaries.`,pcb_trace_id:this.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:t.map(s=>s.pcb_port_id)})}doInitialPcbManualTraceRender(){TOt(this)}doInitialPcbTraceRender(){kOt(this)}_doInitialSchematicTraceRenderWithDisplayLabel(){EOt(this)}_isSymbolToChipConnection(){let{allPortsFound:e,ports:t}=this._findConnectedPorts();if(!e||t.length!==2)return!1;let[i,r]=t;if(!i?.parent||!r?.parent)return!1;let s=i.parent.config.shouldRenderAsSchematicBox,o=r.parent.config.shouldRenderAsSchematicBox;return s&&!o||!s&&o}_isSymbolToSymbolConnection(){let{allPortsFound:e,ports:t}=this._findConnectedPorts();if(!e||t.length!==2)return!1;let[i,r]=t;if(!i?.parent||!r?.parent)return!1;let s=!i.parent.config.shouldRenderAsSchematicBox,o=!r.parent.config.shouldRenderAsSchematicBox;return s&&o}_isChipToChipConnection(){let{allPortsFound:e,ports:t}=this._findConnectedPorts();if(!e||t.length!==2)return!1;let[i,r]=t;if(!i?.parent||!r?.parent)return!1;let s=i.parent.config.shouldRenderAsSchematicBox,o=r.parent.config.shouldRenderAsSchematicBox;return s&&o}doInitialSchematicTraceRender(){SOt(this)}},COt=n=>{let{db:e}=n.root;if(n.pcb_component_id){let t=e.pcb_component.get(n.pcb_component_id);return t?{width:t.width,height:t.height}:null}if(n.pcb_group_id){let t=e.pcb_group.get(n.pcb_group_id);if(!t)return null;if(t.outline&&t.outline.length>0){let i=Ro(t.outline);return i?{width:i.maxX-i.minX,height:i.maxY-i.minY}:null}return{width:t.width??0,height:t.height??0}}return null},IOt=(n,e)=>{let{db:t}=n.root,i=t.toArray();if(n.pcb_component_id){ww(i,n.pcb_component_id,e);return}if(n.source_group_id){Sw(i,n.source_group_id,e);return}throw new Error(`Cannot reposition component ${n.getString()}: no pcb_component_id or source_group_id`)},NOt=n=>{let{db:e}=n.root;if(!n.source_component_id)return;let t=n.selectAll("port"),i=e.source_trace.list(),r=new Set;for(let o of i)for(let a of o.connected_source_port_ids)r.add(a);let s=n._getInternallyConnectedPins();for(let o of s)if(o.some(a=>a.source_port_id&&r.has(a.source_port_id)))for(let a of o)a.source_port_id&&r.add(a.source_port_id);for(let o of t)o.source_port_id&&AOt(n,o)&&(r.has(o.source_port_id)||e.source_pin_missing_trace_warning.insert({message:`Port ${o.getNameAndAliases()[0]} on ${n.props.name} is missing a trace`,source_component_id:n.source_component_id,source_port_id:o.source_port_id,subcircuit_id:n.getSubcircuit().subcircuit_id??void 0,warning_type:"source_pin_missing_trace_warning"}))},AOt=(n,e)=>{if(n.config.componentName==="Chip"){let t=n.props.pinAttributes;if(!t)return!1;for(let i of e.getNameAndAliases()){let r=t[i];if(r?.requiresPower||r?.requiresGround||r?.requiresVoltage!==void 0)return!0}return!1}return!0};function ROt(n){let e=n.font_size,t=n.text.length*e*.6,i=e,r=n.anchor_alignment||"center",s=n.anchor_position.x,o=n.anchor_position.y;switch(r){case"top_left":s=n.anchor_position.x+t/2,o=n.anchor_position.y+i/2;break;case"top_center":s=n.anchor_position.x,o=n.anchor_position.y+i/2;break;case"top_right":s=n.anchor_position.x-t/2,o=n.anchor_position.y+i/2;break;case"center_left":s=n.anchor_position.x+t/2,o=n.anchor_position.y;break;case"center":s=n.anchor_position.x,o=n.anchor_position.y;break;case"center_right":s=n.anchor_position.x-t/2,o=n.anchor_position.y;break;case"bottom_left":s=n.anchor_position.x+t/2,o=n.anchor_position.y-i/2;break;case"bottom_center":s=n.anchor_position.x,o=n.anchor_position.y-i/2;break;case"bottom_right":s=n.anchor_position.x-t/2,o=n.anchor_position.y-i/2;break;default:s=n.anchor_position.x,o=n.anchor_position.y;break}return{x:s-t/2,y:o-i/2,width:t,height:i}}function OOt(n){if(!n._adjustSilkscreenTextAutomatically||n.root?.pcbDisabled||!n.pcb_component_id)return;let{db:e}=n.root,i=n._getPcbCircuitJsonBounds().center,r=e.pcb_silkscreen_text.list({pcb_component_id:n.pcb_component_id}).filter(c=>c.text===n.name);if(r.length===0)return;let a=n.getSubcircuit().selectAll("[_isNormalComponent=true]").filter(c=>c!==n&&c.pcb_component_id).map(c=>{let l=c._getPcbCircuitJsonBounds(),u={center:l.center,width:l.width,height:l.height};return eo(u)});for(let c of r){let l=c.anchor_position,u=ROt(c),p={center:{x:u.x+u.width/2,y:u.y+u.height/2},width:u.width,height:u.height},f=eo(p);if(!a.some(T=>Hc(f,T)))continue;let g=2*i.x-l.x,x=2*i.y-l.y,v={center:{x:g,y:x},width:u.width,height:u.height},S=eo(v);a.some(T=>Hc(S,T))||e.pcb_silkscreen_text.update(c.pcb_silkscreen_text_id,{anchor_position:{x:g,y:x}})}}function LOt(n){if(!n)return{validPinLabels:n,invalidPinLabelsMessages:[]};let e={},t=[];for(let[i,r]of Object.entries(n)){let s=Array.isArray(r)?r.slice():[r],o=[];for(let a of s)FOt(i,a)?o.push(a):t.push(`Invalid pin label: ${i} = '${a}' - excluding from component. Please use a valid pin label.`);o.length>0&&(e[i]=Array.isArray(r)?o:o[0])}return{validPinLabels:Object.keys(e).length>0?e:void 0,invalidPinLabelsMessages:t}}function FOt(n,e){try{let t={name:"test",footprint:"test",pinLabels:{[n]:e}};return t_.safeParse(t).success}catch{return!1}}var H_=n=>n.startsWith("http://")||n.startsWith("https://"),e9=n=>{if(H_(n))return null;let e=n.indexOf(":");if(e<=0)return null;let t=n.slice(0,e),i=n.slice(e+1);return!t||!i?null:{footprintLib:t,footprintName:i}},n9=n=>n.startsWith("/"),zOt=(0,Uet.default)("tscircuit:core:resolveStaticFileImport");async function Vet(n,e){if(!n)return n;let t=e?.resolveProjectStaticFileImportUrl;if(t&&n.startsWith("/"))try{let i=await t(n);if(i)return i}catch(i){zOt("failed to resolve static file via platform resolver",i)}return $et(n,e?.projectBaseUrl)}function DOt(n,e){let{footprint:t}=n.props;if(t??(t=n._getImpliedFootprintString?.()),!t)return;let{pcbRotation:i,pinLabels:r,pcbPinLabels:s}=n.props,o=Det(String(t)),a=o?n.root?.platform?.footprintFileParserMap?.[o]:null;if(typeof t=="string"&&(H_(t)||n9(t))&&a){if(n._hasStartedFootprintUrlLoad)return;n._hasStartedFootprintUrlLoad=!0,e("load-footprint-from-platform-file-parser",async()=>{let c=H_(t)?t:await Vet(t,n.root?.platform);try{let l=await a.loadFromUrl(c),u=G_({componentName:n.name,componentRotation:i,footprinterString:c,pinLabels:r,pcbPinLabels:s},l.footprintCircuitJson);n.addAll(u),n._markDirty("InitializePortsFromChildren")}catch(l){let u=n.root?.db;if(u&&n.source_component_id&&n.pcb_component_id){let p=n.getSubcircuit(),f=`${n.getString()} failed to load footprint "${c}": `+(l instanceof Error?l.message:String(l)),y=Nm.parse({type:"external_footprint_load_error",message:f,pcb_component_id:n.pcb_component_id,source_component_id:n.source_component_id,subcircuit_id:p.subcircuit_id??void 0,pcb_group_id:n.getGroup()?.pcb_group_id??void 0,footprinter_string:c});u.external_footprint_load_error.insert(y)}throw l}});return}if(typeof t=="string"&&H_(t)){if(n._hasStartedFootprintUrlLoad)return;n._hasStartedFootprintUrlLoad=!0;let c=t;e("load-footprint-url",async()=>{try{let l=await fetch(c);if(!l.ok)throw new Error(`Failed to fetch footprint: ${l.status}`);let u=await l.json(),p=G_({componentName:n.name,componentRotation:i,footprinterString:c,pinLabels:r,pcbPinLabels:s},u);n.addAll(p),n._markDirty("InitializePortsFromChildren")}catch(l){let u=n.root?.db;if(u&&n.source_component_id&&n.pcb_component_id){let p=n.getSubcircuit(),f=`${n.getString()} failed to load external footprint "${c}": `+(l instanceof Error?l.message:String(l)),y=Nm.parse({type:"external_footprint_load_error",message:f,pcb_component_id:n.pcb_component_id,source_component_id:n.source_component_id,subcircuit_id:p.subcircuit_id??void 0,pcb_group_id:n.getGroup()?.pcb_group_id??void 0,footprinter_string:c});u.external_footprint_load_error.insert(y)}throw l}});return}if(typeof t=="string"){let c=e9(t);if(!c||n._hasStartedFootprintUrlLoad)return;n._hasStartedFootprintUrlLoad=!0;let u=n.root?.platform?.footprintLibraryMap?.[c.footprintLib],p;if(typeof u=="function"&&(p=u),!p)return;let f=n.getInheritedMergedProperty("pcbStyle");e("load-lib-footprint",async()=>{try{let y=await p(c.footprintName,{resolvedPcbStyle:f}),g=null;if(Array.isArray(y)?g=y:Array.isArray(y.footprintCircuitJson)&&(g=y.footprintCircuitJson),!g)return;let x=G_({componentName:n.name,componentRotation:i,footprinterString:t,pinLabels:r,pcbPinLabels:s},g);n.addAll(x),!Array.isArray(y)&&y.cadModel&&(n._asyncFootprintCadModel=y.cadModel);for(let v of n.children)v.componentName==="Port"&&v._markDirty?.("PcbPortRender");n._markDirty("InitializePortsFromChildren")}catch(y){let g=n.root?.db;if(g&&n.source_component_id&&n.pcb_component_id){let x=n.getSubcircuit(),v=`${n.getString()} failed to load external footprint "${t}": `+(y instanceof Error?y.message:String(y)),S=Nm.parse({type:"external_footprint_load_error",message:v,pcb_component_id:n.pcb_component_id,source_component_id:n.source_component_id,subcircuit_id:x.subcircuit_id??void 0,pcb_group_id:n.getGroup()?.pcb_group_id??void 0,footprinter_string:t});g.external_footprint_load_error.insert(S)}throw y}});return}if(!(0,t9.isValidElement)(t)&&t.componentName==="Footprint"&&n.add(t),Array.isArray(t)&&!(0,t9.isValidElement)(t)&&t.length>0){try{let c=G_({componentName:n.name,componentRotation:i,footprinterString:"",pinLabels:r,pcbPinLabels:s},t);n.addAll(c)}catch(c){let l=n.root?.db;if(l&&n.source_component_id&&n.pcb_component_id){let u=n.getSubcircuit(),p=`${n.getString()} failed to load json footprint: `+(c instanceof Error?c.message:String(c)),f=Vx.parse({type:"circuit_json_footprint_load_error",message:p,pcb_component_id:n.pcb_component_id,source_component_id:n.source_component_id,subcircuit_id:u.subcircuit_id??void 0,pcb_group_id:n.getGroup()?.pcb_group_id??void 0});l.circuit_json_footprint_load_error.insert(f)}throw c}return}}function $Ot(n){if(n.root?.pcbDisabled||!n.pcb_component_id)return;let{pcbX:e,pcbY:t}=n._parsedProps,i=n.props?.pcbPositionAnchor;if(!i||e===void 0&&t===void 0)return;let r=QS(n.children);if(r.width===0||r.height===0)return;let o={...{x:(r.minX+r.maxX)/2,y:(r.minY+r.maxY)/2}},a=null;if(new Set(["center","top_left","top_center","top_right","center_left","center_right","bottom_left","bottom_center","bottom_right"]).has(i)){let u={left:r.minX,right:r.maxX,top:r.minY,bottom:r.maxY};switch(i){case"center":a=o;break;case"top_left":a={x:u.left,y:u.top};break;case"top_center":a={x:o.x,y:u.top};break;case"top_right":a={x:u.right,y:u.top};break;case"center_left":a={x:u.left,y:o.y};break;case"center_right":a={x:u.right,y:o.y};break;case"bottom_left":a={x:u.left,y:u.bottom};break;case"bottom_center":a={x:o.x,y:u.bottom};break;case"bottom_right":a={x:u.right,y:u.bottom};break}}else try{let u=n.portMap[i];u&&(a=u._getGlobalPcbPositionBeforeLayout())}catch{}if(!a)return;let l={...o};e!==void 0&&(l.x+=e-a.x),t!==void 0&&(l.y+=t-a.y),(Math.abs(l.x-o.x)>1e-6||Math.abs(l.y-o.y)>1e-6)&&n._repositionOnPcb(l)}var jOt=(0,Tet.default)("tscircuit:core"),BOt=h.object({x:He,y:He,z:He}),Gn=class extends Te{constructor(e){let t={...e},i=[];if(t.pinLabels&&!Array.isArray(t.pinLabels)){let{validPinLabels:r,invalidPinLabelsMessages:s}=LOt(t.pinLabels);t.pinLabels=r,i=s}super(t);d(this,"reactSubtrees",[]);d(this,"_impliedFootprint");d(this,"isPrimitiveContainer",!0);d(this,"_isNormalComponent",!0);d(this,"_attributeLowerToCamelNameMap",{_isnormalcomponent:"_isNormalComponent"});d(this,"_asyncSupplierPartNumbers");d(this,"_asyncFootprintCadModel");d(this,"_isCadModelChild");d(this,"pcb_missing_footprint_error_id");d(this,"_hasStartedFootprintUrlLoad",!1);d(this,"_invalidPinLabelMessages",[]);d(this,"_adjustSilkscreenTextAutomatically",!1);this._invalidPinLabelMessages=i,this._addChildrenFromStringFootprint(),this.initPorts()}get defaultInternallyConnectedPinNames(){return[]}get internallyConnectedPinNames(){return(this._parsedProps.internallyConnectedPins??this.defaultInternallyConnectedPinNames).map(t=>t.map(i=>typeof i=="number"?`pin${i}`:i))}doInitialSourceNameDuplicateComponentRemoval(){if(!this.name)return;let e=this.root;if(this.getSubcircuit().selectAll(`.${this.name}`).filter(r=>r!==this&&r._isNormalComponent&&r.renderPhaseStates?.SourceNameDuplicateComponentRemoval?.initialized).length>0){let r=this._getGlobalPcbPositionBeforeLayout(),s=this._getGlobalSchematicPositionBeforeLayout();e.db.source_failed_to_create_component_error.insert({component_name:this.name,error_type:"source_failed_to_create_component_error",message:`Cannot create component "${this.name}": A component with the same name already exists`,pcb_center:r,schematic_center:s}),this.shouldBeRemoved=!0;let o=[...this.children];for(let a of o)this.remove(a)}}initPorts(e={}){if(this.root?.schematicDisabled)return;let{config:t}=this,i=[],r=this._getSchematicPortArrangement();if(r&&!this._parsedProps.pinLabels){for(let l in r){let u=r[l].pins;if(Array.isArray(u))for(let p of u){let f=j1(p,this._parsedProps.pinLabels);i.push(new Vi({pinNumber:f,aliases:e.additionalAliases?.[`pin${f}`]??[]},{originDescription:`schPortArrangement:${l}`}))}}let a=["left","right","top","bottom"],c=1;for(let l of a){let u=r[`${l}Size`];for(let p=0;p<u;p++)i.push(new Vi({pinNumber:c++,aliases:e.additionalAliases?.[`pin${c}`]??[]},{originDescription:`schPortArrangement:${l}`}))}}let s=this._parsedProps.pinLabels;if(s)for(let[a,c]of Object.entries(s)){a=a.replace("pin","");let l=i.find(f=>f._parsedProps.pinNumber===Number(a)),u=Array.isArray(c)?c[0]:c,p=Array.isArray(c)?c.slice(1):[];l?(l.externallyAddedAliases.push(u,...p),l.props.name=u):(l=new Vi({pinNumber:parseInt(a),name:u,aliases:[...p,...e.additionalAliases?.[`pin${parseInt(a)}`]??[]]},{originDescription:`pinLabels:pin${a}`}),i.push(l))}if(t.schematicSymbolName&&!e.ignoreSymbolPorts){let a=_i[this._getSchematicSymbolNameOrThrow()];if(!a)return;for(let c of a.ports){let l=Oet(c.labels);if(!l)continue;let u=i.find(p=>p._parsedProps.pinNumber===Number(l));if(u)u.schematicSymbolPortDef=c;else{let p=O1(c.labels.concat(e.additionalAliases?.[`pin${l}`]??[]));p&&(p.originDescription=`schematicSymbol:labels[0]:${c.labels[0]}`,p.schematicSymbolPortDef=c,i.push(p))}}this.addAll(i)}if(!this._getSchematicPortArrangement()){let a=this.getPortsFromFootprint(e);for(let c of a)i.some(l=>l.isMatchingAnyOf(c.getNameAndAliases()))||i.push(c)}let o=e.pinCount??this._getPinCount()??0;for(let a=1;a<=o;a++){if(i.find(l=>l._parsedProps.pinNumber===a))continue;if(!r){i.push(new Vi({pinNumber:a,aliases:e.additionalAliases?.[`pin${a}`]??[]}));continue}let c=[...r.leftSide?.pins??[],...r.rightSide?.pins??[],...r.topSide?.pins??[],...r.bottomSide?.pins??[]].map(l=>j1(l,this._parsedProps.pinLabels));["leftSize","rightSize","topSize","bottomSize","leftPinCount","rightPinCount","topPinCount","bottomPinCount"].some(l=>l in r)&&(c=Array.from({length:this._getPinCount()},(l,u)=>u+1)),c.includes(a)&&i.push(new Vi({pinNumber:a,aliases:e.additionalAliases?.[`pin${a}`]??[]},{originDescription:`notOtherwiseAddedButDeducedFromPinCount:${a}`}))}i.length>0&&this.addAll(i)}_getImpliedFootprintString(){return null}_addChildrenFromStringFootprint(){let{pcbRotation:e,pinLabels:t,pcbPinLabels:i}=this.props,{footprint:r}=this.props;if(r??(r=this._getImpliedFootprintString?.()),!!r&&typeof r=="string"){if(H_(r)||n9(r)||e9(r))return;let s=_E.string(r).soup(),o=G_({componentName:this.name??this.componentName,componentRotation:e,footprinterString:r,pinLabels:t,pcbPinLabels:i},s);this.addAll(o)}}get portMap(){return new Proxy({},{get:(e,t)=>{let i=this.children.find(r=>r.componentName==="Port"&&r.isMatchingNameOrAlias(t));if(!i)throw new Error(`There was an issue finding the port "${t.toString()}" inside of a ${this.componentName} component with name: "${this.props.name}". This is a bug in @tscircuit/core`);return i}})}getInstanceForReactElement(e){for(let t of this.reactSubtrees)if(t.element===e)return t.component;return null}doInitialSourceRender(){let e=this.config.sourceFtype;if(!e)return;let{db:t}=this.root,{_parsedProps:i}=this,r=t.source_component.insert({ftype:e,name:this.name,manufacturer_part_number:i.manufacturerPartNumber??i.mfn,supplier_part_numbers:i.supplierPartNumbers});this.source_component_id=r.source_component_id}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root;if(this._invalidPinLabelMessages?.length&&this.root?.db)for(let s of this._invalidPinLabelMessages){let o="pinLabels",a=s.match(/^Invalid pin label:\s*([^=]+)=\s*'([^']+)'/);a&&(o=`pinLabels['${a[2]}']`),this.root.db.source_property_ignored_warning.insert({source_component_id:this.source_component_id,property_name:o,message:s,error_type:"source_property_ignored_warning"})}let{schematicSymbolName:t}=this.config,{_parsedProps:i}=this;i.symbol&&(0,Ua.isValidElement)(i.symbol)?this._doInitialSchematicComponentRenderWithReactSymbol(i.symbol):t?this._doInitialSchematicComponentRenderWithSymbol():this._getSchematicBoxDimensions()&&this._doInitialSchematicComponentRenderWithSchematicBoxDimensions();let r=this.getSubcircuit()?._getSchematicManualPlacementForComponent(this);if(this.schematic_component_id&&(this.props.schX!==void 0||this.props.schY!==void 0)&&r){if(!this.schematic_component_id)return;let s=Xx.parse({type:"schematic_manual_edit_conflict_warning",schematic_manual_edit_conflict_warning_id:`schematic_manual_edit_conflict_${this.source_component_id}`,message:`${this.getString()} has both manual placement and prop coordinates. schX and schY will be used. Remove schX/schY or clear the manual placement.`,schematic_component_id:this.schematic_component_id,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id});e.schematic_manual_edit_conflict_warning.insert(s)}}_getSchematicSymbolDisplayValue(){}_getInternallyConnectedPins(){if(this.internallyConnectedPinNames.length===0)return[];let e=[];for(let t of this.internallyConnectedPinNames){let i=[];for(let r of t)i.push(this.portMap[r]);e.push(i)}return e}_doInitialSchematicComponentRenderWithSymbol(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getSchematicSymbolNameOrThrow(),r=_i[i],s=this._getGlobalSchematicPositionBeforeLayout();if(r){let o=e.schematic_component.insert({center:s,size:r.size,source_component_id:this.source_component_id,is_box_with_pins:!0,symbol_name:i,symbol_display_value:this._getSchematicSymbolDisplayValue()});this.schematic_component_id=o.schematic_component_id}}_doInitialSchematicComponentRenderWithReactSymbol(e){if(this.root?.schematicDisabled)return;let{db:t}=this.root,i=this._getGlobalSchematicPositionBeforeLayout(),r=t.schematic_component.insert({center:i,size:{width:0,height:0},source_component_id:this.source_component_id,symbol_display_value:this._getSchematicSymbolDisplayValue(),is_box_with_pins:!1});this.schematic_component_id=r.schematic_component_id}_doInitialSchematicComponentRenderWithSchematicBoxDimensions(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getSchematicBoxDimensions(),r={};if(Array.isArray(t.pinLabels))t.pinLabels.forEach((y,g)=>{r[String(g+1)]=y});else for(let[y,g]of Object.entries(t.pinLabels??{}))r[y]=Array.isArray(g)?g[0]:g;let s=this._getGlobalSchematicPositionBeforeLayout(),o=this._getSchematicPortArrangement(),a=e.schematic_component.insert({center:s,rotation:t.schRotation??0,size:i.getSize(),port_arrangement:YRt(o),pin_spacing:t.schPinSpacing??.2,pin_styles:BRt(t.schPinStyle,t.pinLabels),port_labels:r,source_component_id:this.source_component_id}),c=o?.topSide!==void 0||o?.bottomSide!==void 0,l=i?.getSize().width,u=i?.getSize().height,p=e.schematic_text.insert({text:t.manufacturerPartNumber??"",schematic_component_id:a.schematic_component_id,anchor:"left",rotation:0,position:{x:c?s.x+(l??0)/2+.1:s.x-(l??0)/2,y:c?s.y+(u??0)/2+.35:s.y-(u??0)/2-.13},color:"#006464",font_size:.18}),f=e.schematic_text.insert({text:t.name??"",schematic_component_id:a.schematic_component_id,anchor:"left",rotation:0,position:{x:c?s.x+(l??0)/2+.1:s.x-(l??0)/2,y:c?s.y+(u??0)/2+.55:s.y+(u??0)/2+.13},color:"#006464",font_size:.18});this.schematic_component_id=a.schematic_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this.getSubcircuit(),r=t.layer??"top";if(r!=="top"&&r!=="bottom"){let p=Am.parse({type:"pcb_component_invalid_layer_error",message:`Component cannot be placed on layer '${r}'. Components can only be placed on 'top' or 'bottom' layers.`,source_component_id:this.source_component_id,layer:r,subcircuit_id:i.subcircuit_id??void 0});e.pcb_component_invalid_layer_error.insert(p)}let s=this._computePcbGlobalTransformBeforeLayout(),a=Js(s).rotation.angle*180/Math.PI,c=e.pcb_component.insert({center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,layer:r==="top"||r==="bottom"?r:"top",rotation:t.pcbRotation??a,source_component_id:this.source_component_id,subcircuit_id:i.subcircuit_id??void 0,do_not_place:t.doNotPlace??!1,obstructs_within_bounds:t.obstructsWithinBounds??!0});if(!(t.footprint??this._getImpliedFootprintString())&&!this.isGroup){let p=e.pcb_missing_footprint_error.insert({message:`No footprint found for component: ${this.getString()}`,source_component_id:`${this.source_component_id}`,error_type:"pcb_missing_footprint_error"});this.pcb_missing_footprint_error_id=p.pcb_missing_footprint_error_id}this.pcb_component_id=c.pcb_component_id;let u=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if((this.props.pcbX!==void 0||this.props.pcbY!==void 0)&&u){let p=Gx.parse({type:"pcb_manual_edit_conflict_warning",pcb_manual_edit_conflict_warning_id:`pcb_manual_edit_conflict_${this.source_component_id}`,message:`${this.getString()} has both manual placement and prop coordinates. pcbX and pcbY will be used. Remove pcbX/pcbY or clear the manual placement.`,pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,subcircuit_id:i.subcircuit_id??void 0});e.pcb_manual_edit_conflict_warning.insert(p)}}doInitialPcbComponentSizeCalculation(){if(this.root?.pcbDisabled||!this.pcb_component_id)return;let{db:e}=this.root,{_parsedProps:t}=this,i=QS(this.children);if(i.width===0||i.height===0)return;let r={x:(i.minX+i.maxX)/2,y:(i.minY+i.maxY)/2};e.pcb_component.update(this.pcb_component_id,{center:r,width:i.width,height:i.height})}updatePcbComponentSizeCalculation(){this.doInitialPcbComponentSizeCalculation()}doInitialSchematicComponentSizeCalculation(){if(this.root?.schematicDisabled||!this.schematic_component_id)return;let{db:e}=this.root;if(!e.schematic_component.get(this.schematic_component_id))return;let i=[],r=u=>{for(let p of u){if(p.isSchematicPrimitive&&p.componentName==="SchematicLine"){let f=e.schematic_line.get(p.schematic_line_id);f&&i.push(f)}if(p.isSchematicPrimitive&&p.componentName==="SchematicRect"){let f=e.schematic_rect.get(p.schematic_rect_id);f&&i.push(f)}if(p.isSchematicPrimitive&&p.componentName==="SchematicCircle"){let f=e.schematic_circle.get(p.schematic_circle_id);f&&i.push(f)}if(p.isSchematicPrimitive&&p.componentName==="SchematicArc"){let f=e.schematic_arc.get(p.schematic_arc_id);f&&i.push(f)}if(p.isSchematicPrimitive&&p.componentName==="SchematicText"){let f=e.schematic_text.get(p.schematic_text_id);f&&i.push(f)}p.children&&p.children.length>0&&r(p.children)}};if(r(this.children),i.length===0)return;let s=Ret(i),o=Math.abs(s.maxX-s.minX),a=Math.abs(s.maxY-s.minY);if(o===0&&a===0)return;let c=(s.minX+s.maxX)/2,l=(s.minY+s.maxY)/2;e.schematic_component.update(this.schematic_component_id,{center:{x:c,y:l},size:{width:o,height:a}})}updateSchematicComponentSizeCalculation(){this.doInitialSchematicComponentSizeCalculation()}doInitialPcbComponentAnchorAlignment(){$Ot(this)}updatePcbComponentAnchorAlignment(){this.doInitialPcbComponentAnchorAlignment()}_renderReactSubtree(e){let t=Net(e);return{element:e,component:t}}doInitialInitializePortsFromChildren(){this.initPorts()}doInitialReactSubtreesRender(){let e=this.props.footprint;(0,Ua.isValidElement)(e)&&(this.children.some(s=>s.componentName==="Footprint")||this.add(e));let t=this.props.symbol;(0,Ua.isValidElement)(t)&&(this.children.some(s=>s.componentName==="Symbol")||this.add(t));let i=this.props.cadModel;if((0,Ua.isValidElement)(i)){this._isCadModelChild=!0;let r=this.children.some(o=>o.componentName==="CadAssembly"),s=this.children.some(o=>o.componentName==="CadModel");!r&&!s&&this.add(i)}}doInitialPcbFootprintStringRender(){DOt(this,(e,t)=>this._queueAsyncEffect(e,t))}_hasExistingPortExactly(e){return this.children.filter(i=>i.componentName==="Port").some(i=>{let r=e.getNameAndAliases(),s=i.getNameAndAliases();return r.length===s.length&&r.every(o=>s.includes(o))})}add(e){let t;if((0,Ua.isValidElement)(e)){let i=this._renderReactSubtree(e);this.reactSubtrees.push(i),t=i.component}else t=e;if(t.componentName==="Port"){if(this._hasExistingPortExactly(t))return;let r=this.children.filter(s=>s.componentName==="Port").find(s=>s.isMatchingAnyOf(t.getNameAndAliases()));r&&jOt(`Similar ports added. Port 1: ${r}, Port 2: ${t}`)}super.add(t)}getPortsFromFootprint(e){let{footprint:t}=this.props;if((!t||(0,Ua.isValidElement)(t))&&(t=this.children.find(r=>r.componentName==="Footprint")),typeof t=="string"){if(H_(t))return[];if(n9(t))return[];if(e9(t))return[];let r=_E.string(t).soup(),s=[];for(let o of r)if("port_hints"in o&&o.port_hints){let a=O1(o.port_hints,e);if(!a)continue;a.originDescription=`footprint:string:${t}:port_hints[0]:${o.port_hints[0]}`,s.push(a)}return s}if(!(0,Ua.isValidElement)(t)&&t&&t.componentName==="Footprint"){let r=t,s=1,o=[];for(let a of r.children){if(!a.props.portHints)continue;let c=a.props.portHints;c.some(p=>p.startsWith("pin"))||(c=[...c,`pin${s}`]),s++;let u=O1(c);u&&(u.originDescription=`footprint:${t}`,o.push(u))}return o}let i=[];if(!t){for(let r of this.children)if(r.props.portHints&&r.isPcbPrimitive){let s=O1(r.props.portHints);s&&i.push(s)}}return i}getPortsFromSchematicSymbol(){if(this.root?.schematicDisabled)return[];let{config:e}=this;if(!e.schematicSymbolName)return[];let t=_i[e.schematicSymbolName];if(!t)return[];let i=[];for(let r of t.ports){let s=O1(r.labels);s&&(s.schematicSymbolPortDef=r,i.push(s))}return i}doInitialCreateNetsFromProps(){this._createNetsFromProps(this._getNetsFromConnectionsProp())}_getNetsFromConnectionsProp(){let{_parsedProps:e}=this,t=[];if(e.connections)for(let[i,r]of Object.entries(e.connections)){let s=Array.isArray(r)?r:[r];for(let o of s)t.push(String(o))}return t}_createNetsFromProps(e){KS(this,e)}_getPcbCircuitJsonBounds(){let{db:e}=this.root;if(!this.pcb_component_id)return super._getPcbCircuitJsonBounds();let t=e.pcb_component.get(this.pcb_component_id);return{center:{x:t.center.x,y:t.center.y},bounds:{left:t.center.x-t.width/2,top:t.center.y-t.height/2,right:t.center.x+t.width/2,bottom:t.center.y+t.height/2},width:t.width,height:t.height}}_getPinCountFromSchematicPortArrangement(){let e=this._getSchematicPortArrangement();if(!e)return 0;if(!Let(e))return(e.leftSize??e.leftPinCount??0)+(e.rightSize??e.rightPinCount??0)+(e.topSize??e.topPinCount??0)+(e.bottomSize??e.bottomPinCount??0);let{leftSide:i,rightSide:r,topSide:s,bottomSide:o}=e;return Math.max(...i?.pins??[],...r?.pins??[],...s?.pins??[],...o?.pins??[])}_getPinCount(){if(this._getSchematicPortArrangement())return this._getPinCountFromSchematicPortArrangement();let t=this.getPortsFromFootprint();if(t.length>0)return t.length;let{pinLabels:i}=this._parsedProps;if(i){if(Array.isArray(i))return i.length;let r=Object.keys(i).map(s=>s.startsWith("pin")?parseInt(s.slice(3)):parseInt(s)).filter(s=>!Number.isNaN(s));return r.length>0?Math.max(...r):Object.keys(i).length}return 0}_getSchematicPortArrangement(){return this._parsedProps.schPinArrangement??this._parsedProps.schPortArrangement}_getPinLabelsFromPorts(){let e=this.selectAll("port"),t={};for(let i of e){let r=i.props.pinNumber;if(r!==void 0){let s=i._getBestDisplayPinLabel();s&&(t[`pin${r}`]=s)}}return t}_getSchematicBoxDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;let{_parsedProps:e}=this,t=this._getPinCount(),i=e.schPinSpacing??.2,s={...this._getPinLabelsFromPorts(),...e.pinLabels};return QRt({schWidth:e.schWidth,schHeight:e.schHeight,schPinSpacing:i,numericSchPinStyle:nOt(e.schPinStyle,s),pinCount:t,schPortArrangement:this._getSchematicPortArrangement(),pinLabels:s})}getFootprinterString(){return typeof this._parsedProps.footprint=="string"?this._parsedProps.footprint:null}doInitialCadModelRender(){if(this._isCadModelChild||this.props.doNotPlace)return;let{db:e}=this.root,{boardThickness:t=0}=this.root?._getBoard()??{},i=this._parsedProps.cadModel,r=i===void 0?this._asyncFootprintCadModel:i,s=this.getFootprinterString()??this._getImpliedFootprintString();if(!this.pcb_component_id||!r&&!s||r===null)return;let o=this._getPcbCircuitJsonBounds();if(typeof r=="string")throw new Error("String cadModel not yet implemented");let a=BOt.parse({x:0,y:0,z:typeof r?.rotationOffset=="number"?r.rotationOffset:0,...typeof r?.rotationOffset=="object"?r.rotationOffset??{}:{}}),c=zh.parse({x:0,y:0,z:0,...typeof r?.positionOffset=="object"?r.positionOffset:{}}),l=r&&typeof r=="object"&&"zOffsetFromSurface"in r&&r.zOffsetFromSurface!==void 0?X.parse(r.zOffsetFromSurface):0,u=this.props.layer==="bottom"?"bottom":"top",p=this._computePcbGlobalTransformBeforeLayout(),y=Js(p).rotation.angle*180/Math.PI,g=u==="bottom",x=y+(a.z??0),v=sd(x),S=e.cad_component.insert({position:{x:o.center.x+c.x,y:o.center.y+c.y,z:(u==="bottom"?-t/2:t/2)+(u==="bottom"?-l:l)+c.z},rotation:{x:a.x,y:a.y+(g?180:0),z:sd(g?-v:v)},pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,model_stl_url:"stlUrl"in(r??{})?this._addCachebustToModelUrl(r.stlUrl):void 0,model_obj_url:"objUrl"in(r??{})?this._addCachebustToModelUrl(r.objUrl):void 0,model_mtl_url:"mtlUrl"in(r??{})?this._addCachebustToModelUrl(r.mtlUrl):void 0,model_gltf_url:"gltfUrl"in(r??{})?this._addCachebustToModelUrl(r.gltfUrl):void 0,model_glb_url:"glbUrl"in(r??{})?this._addCachebustToModelUrl(r.glbUrl):void 0,model_step_url:"stepUrl"in(r??{})?this._addCachebustToModelUrl(r.stepUrl):void 0,model_wrl_url:"wrlUrl"in(r??{})?this._addCachebustToModelUrl(r.wrlUrl):void 0,model_jscad:"jscad"in(r??{})?r.jscad:void 0,model_unit_to_mm_scale_factor:typeof r?.modelUnitToMmScale=="number"?r.modelUnitToMmScale:void 0,footprinter_string:typeof s=="string"&&!r?s:void 0});this.cad_component_id=S.cad_component_id}_addCachebustToModelUrl(e){if(!e||!e.includes("modelcdn.tscircuit.com"))return e;let t=this.root?.getClientOrigin()??"";return`${e}${e.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(t)}`}_getPartsEngineCacheKey(e,t){return JSON.stringify({ftype:e.ftype,name:e.name,manufacturer_part_number:e.manufacturer_part_number,footprinterString:t})}async _getSupplierPartNumbers(e,t,i){if(this.props.doNotPlace)return{};let r=this.root?.platform?.localCacheEngine,s=this._getPartsEngineCacheKey(t,i);if(r){let c=await r.getItem(s);if(c)try{return JSON.parse(c)}catch{}}let o=await Promise.resolve(e.findPart({sourceComponent:t,footprinterString:i}));if(typeof o=="string"){if(o.includes("<!DOCTYPE")||o.includes("<html"))throw new Error(`Failed to fetch supplier part numbers: Received HTML response instead of JSON. Response starts with: ${o.substring(0,100)}`);if(o==="Not found")return{};throw new Error(`Invalid supplier part numbers format: Expected object but got string: "${o}"`)}if(!o||Array.isArray(o)||typeof o!="object"){let c=o===null?"null":Array.isArray(o)?"array":typeof o;throw new Error(`Invalid supplier part numbers format: Expected object but got ${c}`)}let a=o;if(r)try{await r.setItem(s,JSON.stringify(a))}catch{}return a}doInitialPartsEngineRender(){if(this.props.doNotPlace)return;let e=this.getInheritedProperty("partsEngine");if(!e)return;let{db:t}=this.root,i=t.source_component.get(this.source_component_id);if(!i||i.supplier_part_numbers)return;let r;this.props.footprint&&typeof this.props.footprint=="string"&&(r=this.props.footprint);let s=this._getSupplierPartNumbers(e,i,r);if(!(s instanceof Promise)){t.source_component.update(this.source_component_id,{supplier_part_numbers:s});return}this._queueAsyncEffect("get-supplier-part-numbers",async()=>{await s.then(o=>{this._asyncSupplierPartNumbers=o,this._markDirty("PartsEngineRender")}).catch(o=>{this._asyncSupplierPartNumbers={};let a=Bx.parse({type:"unknown_error_finding_part",message:`Failed to fetch supplier part numbers for ${this.getString()}: ${o.message}`,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id});t.unknown_error_finding_part.insert(a),this._markDirty("PartsEngineRender")})})}updatePartsEngineRender(){if(this.props.doNotPlace)return;let{db:e}=this.root,t=e.source_component.get(this.source_component_id);if(t&&!t.supplier_part_numbers&&this._asyncSupplierPartNumbers){e.source_component.update(this.source_component_id,{supplier_part_numbers:this._asyncSupplierPartNumbers});return}}doInitialAssignFallbackProps(){let{_parsedProps:e}=this;e.connections&&!this.name&&(this.fallbackUnassignedName=this.getSubcircuit().getNextAvailableName(this))}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}_createTracesFromConnectionsProp(){let{_parsedProps:e}=this;if(e.connections)for(let[t,i]of Object.entries(e.connections)){let r=Array.isArray(i)?i:[i];for(let s of r)this.add(new oo({from:`.${this.name} > .${t}`,to:String(s)}))}}doInitialSourceDesignRuleChecks(){NOt(this)}_getMinimumFlexContainerSize(){return COt(this)}_repositionOnPcb(e){return IOt(this,e)}doInitialSilkscreenOverlapAdjustment(){return OOt(this)}isRelativelyPositioned(){return this._parsedProps.pcbX!==void 0||this._parsedProps.pcbY!==void 0}},YOt=({boardAnchorPosition:n,boardAnchorAlignment:e,width:t,height:i})=>{let{x:r,y:s}=n,o=r,a=s;switch(e){case"top_left":o=r+t/2,a=s-i/2;break;case"top_right":o=r-t/2,a=s-i/2;break;case"bottom_left":o=r+t/2,a=s+i/2;break;case"bottom_right":o=r-t/2,a=s+i/2;break;case"top":o=r,a=s-i/2;break;case"bottom":o=r,a=s+i/2;break;case"left":o=r+t/2,a=s;break;case"right":o=r-t/2,a=s;break;case"center":default:break}return{x:o,y:a}},XOt=class{constructor(n,e={}){d(this,"input");d(this,"isRouting",!1);d(this,"solver");d(this,"eventHandlers",{complete:[],error:[],progress:[]});d(this,"cycleCount",0);d(this,"stepDelay");d(this,"timeoutId");this.input=n;let{capacityDepth:t,targetMinCapacity:i,stepDelay:r=0,useAssignableViaSolver:s=!1}=e,{AutoroutingPipelineSolver:o,AssignableViaAutoroutingPipelineSolver:a}=X4,c=s?a:o;this.solver=new c(n,{capacityDepth:t,targetMinCapacity:i,cacheProvider:null}),this.stepDelay=r}start(){this.isRouting||(this.isRouting=!0,this.cycleCount=0,this.runCycleAndQueueNextCycle())}runCycleAndQueueNextCycle(){if(this.isRouting)try{if(this.solver.solved||this.solver.failed){this.solver.failed?this.emitEvent({type:"error",error:new L1(this.solver.error||"Routing failed")}):this.emitEvent({type:"complete",traces:this.solver.getOutputSimpleRouteJson().traces||[]}),this.isRouting=!1;return}let n=Date.now(),e=this.solver.iterations;for(;Date.now()-n<250&&!this.solver.failed&&!this.solver.solved;)this.solver.step();let t=(this.solver.iterations-e)/(Date.now()-n)*1e3;this.cycleCount++;let i=this.solver?.preview()||void 0,r=this.solver.progress;this.emitEvent({type:"progress",steps:this.cycleCount,iterationsPerSecond:t,progress:r,phase:this.solver.getCurrentPhase(),debugGraphics:i}),this.stepDelay>0?this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),this.stepDelay):this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),0)}catch(n){this.emitEvent({type:"error",error:n instanceof Error?new L1(n.message):new L1(String(n))}),this.isRouting=!1}}stop(){this.isRouting&&(this.isRouting=!1,this.timeoutId!==void 0&&(clearTimeout(this.timeoutId),this.timeoutId=void 0))}on(n,e){n==="complete"?this.eventHandlers.complete.push(e):n==="error"?this.eventHandlers.error.push(e):n==="progress"&&this.eventHandlers.progress.push(e)}emitEvent(n){if(n.type==="complete")for(let e of this.eventHandlers.complete)e(n);else if(n.type==="error")for(let e of this.eventHandlers.error)e(n);else if(n.type==="progress")for(let e of this.eventHandlers.progress)e(n)}solveSync(){if(this.solver.solve(),this.solver.failed)throw new L1(this.solver.error||"Routing failed");return this.solver.getOutputSimpleRouteJson().traces||[]}},p9=class extends Te{constructor(){super(...arguments);d(this,"matchedPort",null)}get config(){return{componentName:"TraceHint",zodProps:wW}}doInitialPortMatching(){let{db:e}=this.root,{_parsedProps:t,parent:i}=this;if(!i)return;if(i.componentName==="Trace"){this.renderError(`Port inference inside trace is not yet supported (${this})`);return}if(!i)throw new Error("TraceHint has no parent");if(!t.for){this.renderError(`TraceHint has no for property (${this})`);return}let r=i.selectOne(t.for,{type:"port"});r||this.renderError(`${this} could not find port for selector "${t.for}"`),this.matchedPort=r,r.registerMatch(this)}getPcbRouteHints(){let{_parsedProps:e}=this,t=e.offset?[e.offset]:e.offsets;if(!t)return[];let i=this._computePcbGlobalTransformBeforeLayout();return t.map(r=>({...ze(i,r),via:r.via,to_layer:r.to_layer,trace_width:r.trace_width}))}doInitialPcbTraceHintRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this;e.pcb_trace_hint.insert({pcb_component_id:this.matchedPort?.pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,route:this.getPcbRouteHints()})}},Get=({circuitJson:n,editEvents:e,manualEditsFile:t})=>{let i={...t,pcb_placements:[...t.pcb_placements??[]]};for(let r of e)if(r.edit_event_type==="edit_pcb_component_location"){let{pcb_component_id:s,new_center:o}=r,a=Be(n).pcb_component.get(s);if(!a)continue;let c=Be(n).source_component.get(a.source_component_id);if(!c)continue;let l=i.pcb_placements?.findIndex(p=>p.selector===c.name),u={selector:c.name,center:o,relative_to:"group_center"};l>=0?i.pcb_placements[l]=u:i.pcb_placements.push(u)}return i},Het=({circuitJson:n,editEvents:e,manualEditsFile:t})=>{let i={...t,schematic_placements:[...t.schematic_placements??[]]};for(let r of e)if(r.edit_event_type==="edit_schematic_component_location"){let{schematic_component_id:s,new_center:o}=r,a=Be(n).schematic_component.get(s);if(!a||!a.source_component_id)continue;let c=Be(n).source_component.get(a.source_component_id);if(!c)continue;let l=i.schematic_placements?.findIndex(p=>p.selector===c.name),u={selector:c.name,center:o,relative_to:"group_center"};l>=0?i.schematic_placements[l]=u:i.schematic_placements.push(u)}return i},UOt=({circuitJson:n,editEvents:e,manualEditsFile:t})=>{let i=e.filter(o=>o.edit_event_type==="edit_schematic_component_location"),r=e.filter(o=>o.edit_event_type==="edit_pcb_component_location"),s=t;return i.length>0&&(s=Het({circuitJson:n,editEvents:i,manualEditsFile:s})),r.length>0&&(s=Get({circuitJson:n,editEvents:r,manualEditsFile:s})),s},VOt=(n,e)=>{if(Be(n).pcb_trace_hint.get(e.pcb_trace_hint_id))n=n.map(i=>i.pcb_trace_hint_id===e.pcb_trace_hint_id?{...i,route:e.route}:i);else{let i=Be(n).pcb_port.get(e.pcb_port_id);n=n.filter(r=>!(r.type==="pcb_trace_hint"&&r.pcb_port_id===e.pcb_port_id)).concat([{type:"pcb_trace_hint",pcb_trace_hint_id:e.pcb_trace_hint_id,route:e.route,pcb_port_id:e.pcb_port_id,pcb_component_id:i?.pcb_component_id}])}return n},GOt=({circuitJson:n,editEvents:e})=>{n=JSON.parse(JSON.stringify(n));for(let t of e)if(t.edit_event_type==="edit_pcb_component_location"){let i=n.find(s=>s.type==="pcb_component"&&s.pcb_component_id===t.pcb_component_id);if((!i||i.center.x!==t.new_center.x||i.center.y!==t.new_center.y)&&t.original_center){let s=Nn(t.new_center.x-t.original_center.x,t.new_center.y-t.original_center.y);n=n.map(o=>o.pcb_component_id!==t.pcb_component_id?o:f4(o,s))}}else t.edit_event_type==="edit_schematic_component_location"?n=n.map(i=>i.type==="schematic_component"&&i.schematic_component_id===t.schematic_component_id?{...i,center:t.new_center}:i):t.edit_event_type==="edit_pcb_trace_hint"&&(n=VOt(n,t));return n},Wet=(n,e)=>{let t=n.source_group.list(),i=[],r=s=>{let o=t.filter(a=>a.parent_subcircuit_id===s);for(let a of o)a.subcircuit_id&&(i.push(a.subcircuit_id),r(a.subcircuit_id))};return r(e),i},i9=({db:n,circuitJson:e,subcircuit_id:t,minTraceWidth:i=.1})=>{if(!n&&e&&(n=Be(e)),!n)throw new Error("db or circuitJson is required");let r=n.pcb_trace_hint.list(),s=t?new Set([t]):null;if(t){let N=Wet(n,t);for(let I of N)s.add(I)}let o=(e??n.toArray()).filter(N=>!t||"subcircuit_id"in N&&s.has(N.subcircuit_id)),a=n.pcb_board.list()[0];n=Be(o);let c=er(o),l=Yet([...n.pcb_component.list(),...n.pcb_smtpad.list(),...n.pcb_plated_hole.list(),...n.pcb_hole.list(),...n.pcb_via.list(),...n.pcb_cutout.list()].filter(N=>!t||s?.has(N.subcircuit_id)),c);for(let N of l){let I=N.connectedTo.flatMap(A=>c.getIdsConnectedToNet(A));N.connectedTo.push(...I)}let u=l.flatMap(N=>[{x:N.center.x-N.width/2,y:N.center.y-N.height/2},{x:N.center.x+N.width/2,y:N.center.y+N.height/2}]).concat(a?.outline??[]),p;if(a&&!a.outline?p={minX:a.center.x-a.width/2,maxX:a.center.x+a.width/2,minY:a.center.y-a.height/2,maxY:a.center.y+a.height/2}:p={minX:Math.min(...u.map(N=>N.x))-1,maxX:Math.max(...u.map(N=>N.x))+1,minY:Math.min(...u.map(N=>N.y))-1,maxY:Math.max(...u.map(N=>N.y))+1},t){let N=n.pcb_group.getWhere({subcircuit_id:t});if(N?.width&&N.height){let I={minX:N.center.x-N.width/2,maxX:N.center.x+N.width/2,minY:N.center.y-N.height/2,maxY:N.center.y+N.height/2};p={minX:Math.min(p.minX,I.minX),maxX:Math.max(p.maxX,I.maxX),minY:Math.min(p.minY,I.minY),maxY:Math.max(p.maxY,I.maxY)}}}let f=new Set(n.pcb_trace.list().map(N=>N.source_trace_id).filter(N=>!!N)),y=n.source_trace.list().filter(N=>!f.has(N.source_trace_id)).map(N=>{let I=N.connected_source_port_ids.map(H=>{let Q=n.source_port.get(H),tt=n.pcb_port.getWhere({source_port_id:H});return{...Q,...tt}});if(I.length<2)return null;let[A,R]=I,j=A.layers?.[0]??"top",B=R.layers?.[0]??"top",G=r.filter(H=>H.pcb_port_id===A.pcb_port_id||H.pcb_port_id===R.pcb_port_id),U=[];for(let H of G){let tt=n.pcb_port.get(H.pcb_port_id)?.layers?.[0]??"top";for(let V of H.route)U.push({x:V.x,y:V.y,layer:tt})}return{name:N.source_trace_id??c.getNetConnectedToId(N.source_trace_id)??"",source_trace_id:N.source_trace_id,width:N.min_trace_thickness,pointsToConnect:[{x:A.x,y:A.y,layer:j,pointId:A.pcb_port_id,pcb_port_id:A.pcb_port_id},...U,{x:R.x,y:R.y,layer:B,pointId:R.pcb_port_id,pcb_port_id:R.pcb_port_id}]}}).filter(N=>N!==null),g=new Map(y.map(N=>[N.source_trace_id,N])),x=n.source_net.list().filter(N=>!t||s?.has(N.subcircuit_id)),v=[];for(let N of x){let I=n.source_trace.list().filter(A=>A.connected_source_net_ids?.includes(N.source_net_id));v.push({name:N.source_net_id??c.getNetConnectedToId(N.source_net_id),pointsToConnect:I.flatMap(A=>n.pcb_port.list().filter(j=>A.connected_source_port_ids.includes(j.source_port_id)).map(j=>({x:j.x,y:j.y,layer:j.layers?.[0]??"top",pointId:j.pcb_port_id,pcb_port_id:j.pcb_port_id})))})}let S=n.pcb_breakout_point.list().filter(N=>!t||s?.has(N.subcircuit_id)),P=[],T=new Map;for(let N of S){let I={x:N.x,y:N.y,layer:"top"};if(N.source_trace_id){let A=g.get(N.source_trace_id)??T.get(N.source_trace_id);if(A)A.pointsToConnect.push(I);else{let R={name:N.source_trace_id,source_trace_id:N.source_trace_id,pointsToConnect:[I]};P.push(R),T.set(N.source_trace_id,R)}}else if(N.source_net_id){let A=v.find(R=>R.name===N.source_net_id);A?A.pointsToConnect.push(I):P.push({name:N.source_net_id,pointsToConnect:[I]})}else if(N.source_port_id){let A=n.pcb_port.getWhere({source_port_id:N.source_port_id});A&&P.push({name:N.source_port_id,source_trace_id:void 0,pointsToConnect:[{x:A.x,y:A.y,layer:A.layers?.[0]??"top",pointId:A.pcb_port_id,pcb_port_id:A.pcb_port_id},I]})}}let k=[...y,...v,...P],C=new Map;for(let N of k)for(let I of N.pointsToConnect)I.pointId&&C.set(I.pointId,N);let E=n.pcb_trace.list().filter(N=>!t||s?.has(N.subcircuit_id));for(let N of E){let I=new Set;for(let j of N.route)j.start_pcb_port_id&&I.add(j.start_pcb_port_id),j.end_pcb_port_id&&I.add(j.end_pcb_port_id);if(I.size<2)continue;let A=I.values().next().value;if(!A)continue;let R=C.get(A);R&&[...I].every(j=>C.get(j)===R)&&(R.externallyConnectedPointIds??(R.externallyConnectedPointIds=[]),R.externallyConnectedPointIds.push([...I]))}return{simpleRouteJson:{bounds:p,obstacles:l,connections:k,layerCount:a?.num_layers??2,minTraceWidth:i,outline:a?.outline?.map(N=>({...N}))},connMap:c}},HOt=n=>{let e={};if(!n)return e;for(let i of Xa)e[i]=0;let t=new Map;for(let i of n){let[,,r,s]=i.type.split(":");if(s==="start"){t.set(`${r}:${i.renderId}`,i);continue}if(s==="end"){let o=t.get(`${r}:${i.renderId}`);if(o){let a=i.createdAt-o.createdAt;e[r]=(e[r]||0)+a}}}return e},WOt=n=>{let e=n.map(c=>[...new Set(c)]),t=e.map(()=>[]),i=e.map(()=>null);for(let c=0;c<e.length;c++)for(let l of e[c])if(/^\d+$/.test(l)){i[c]=Number.parseInt(l);break}let r=0,s=new Set;for(let c=0;c<i.length;c++){let l=i[c];if(l===null||l<1)continue;if(!s.has(l)){s.add(l),t[c].push(`pin${l}`),r=Math.max(r,l);continue}let u=0;for(let p of t[c])p.startsWith(`pin${l}_alt`)&&u++;t[c].push(`pin${l}_alt${u+1}`)}for(let c=0;c<t.length;c++)t[c][0]?.includes("_alt")&&(r++,t[c].unshift(`pin${r}`));for(let c=0;c<t.length;c++)t[c].length===0&&(r++,t[c].push(`pin${r}`));let o={};for(let c of e)for(let l of c)/^\d+$/.test(l)||(o[l]=(o[l]??0)+1);let a={};for(let c=0;c<e.length;c++){let l=e[c];for(let u of l)/^\d+$/.test(u)||(o[u]===1?t[c].push(u):(a[u]=(a[u]??0)+1,t[c].push(`${u}${a[u]}`)))}return t};function h9({db:n,schematicComponentId:e,deltaX:t,deltaY:i}){let r=n.schematic_rect.list({schematic_component_id:e});for(let c of r)c.center.x+=t,c.center.y+=i;let s=n.schematic_line.list({schematic_component_id:e});for(let c of s)c.x1+=t,c.y1+=i,c.x2+=t,c.y2+=i;let o=n.schematic_circle.list({schematic_component_id:e});for(let c of o)c.center.x+=t,c.center.y+=i;let a=n.schematic_arc.list({schematic_component_id:e});for(let c of a)c.center.x+=t,c.center.y+=i}var uet=(0,qet.default)("Group_doInitialSchematicLayoutMatchAdapt");function qOt(n){let{db:e}=n.root,t=Ng(e.toArray(),{source_group_id:n.source_group_id}),i=U4(t);uet.enabled&&global?.debugGraphics&&global.debugGraphics?.push(il(i,{title:`floatingBpcGraph-${n.name}`}));let r=U4(t),s={boxes:r.boxes,pins:r.pins.map(c=>({...c,color:c.color.replace("not_connected","normal")}))},{result:o}=XK([{variantName:"default",floatingGraph:r},{variantName:"noNotConnected",floatingGraph:s}],{singletonKeys:["vcc/2","gnd/2"],centerPinColors:["netlabel_center","component_center"],floatingBoxIdsWithMutablePinOffsets:new Set(r.boxes.filter(c=>r.pins.filter(p=>p.boxId===c.boxId).filter(p=>!p.color.includes("center")).length<=2).map(c=>c.boxId)),corpus:{}});uet.enabled&&global?.debugGraphics&&global.debugGraphics?.push(il(o,{title:`laidOutBpcGraph-${n.name}`}));let a=n._getGlobalSchematicPositionBeforeLayout();for(let c of o.boxes){if(!c.center)continue;let l=e.schematic_component.get(c.boxId);if(l){let p={x:c.center.x+a.x,y:c.center.y+a.y},f=e.schematic_port.list({schematic_component_id:l.schematic_component_id}),y=e.schematic_text.list({schematic_component_id:l.schematic_component_id}),g={x:p.x-l.center.x,y:p.y-l.center.y};for(let x of f)x.center.x+=g.x,x.center.y+=g.y;for(let x of y)x.position.x+=g.x,x.position.y+=g.y;h9({db:e,schematicComponentId:l.schematic_component_id,deltaX:g.x,deltaY:g.y}),l.center=p;continue}let u=e.schematic_net_label.get(c.boxId);if(u){let p=o.pins.find(y=>y.boxId===c.boxId&&y.color==="netlabel_center");if(!p)throw new Error(`No pin found for net label: ${c.boxId}`);let f={x:c.center.x+a.x,y:c.center.y+a.y};u.center=f,u.anchor_position={x:f.x+p.offset.x,y:f.y+p.offset.y};continue}console.error(`No schematic element found for box: ${c.boxId}. This is a bug in the matchAdapt binding with @tscircuit/core`)}}var xe=(0,Zet.default)("Group_doInitialSchematicLayoutMatchpack");function pet(n){switch(n){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:return"y+"}}function het(n,e){let t=["right","up","left","down"],i=t.indexOf(n);if(i===-1)return n;let r=Math.round(e/90),s=(i+r)%4;return t[s<0?s+4:s]}function ZOt(n,e,t){let i={chipMap:{},chipPinMap:{},netMap:{},pinStrongConnMap:{},netConnMap:{},chipGap:.6,decouplingCapsGap:.4,partitionGap:1.2};xe(`[${t.name}] Processing ${n.childNodes.length} child nodes for input problem`),n.childNodes.forEach((s,o)=>{if(xe(`[${t.name}] Processing child ${o}: nodeType=${s.nodeType}`),s.nodeType==="component"?xe(`[${t.name}] - Component: ${s.sourceComponent?.name}`):s.nodeType==="group"&&xe(`[${t.name}] - Group: ${s.sourceGroup?.name}`),s.nodeType==="component"&&s.sourceComponent){let a=s.sourceComponent.name||`chip_${o}`,c=e.schematic_component.getWhere({source_component_id:s.sourceComponent.source_component_id});if(!c)return;let l=t.children.find(P=>P.source_component_id===s.sourceComponent?.source_component_id),u=[0,90,180,270];l?._parsedProps?.schOrientation&&(u=[0]),l?._parsedProps?.schRotation!==void 0&&(u=[0]),l?._parsedProps?.facingDirection&&(u=[0]),l?._parsedProps?.schFacingDirection&&(u=[0]),l?.componentName==="Chip"&&(u=[0]);let p=l?._parsedProps?.schMarginLeft??l?._parsedProps?.schMarginX??0,f=l?._parsedProps?.schMarginRight??l?._parsedProps?.schMarginX??0,y=l?._parsedProps?.schMarginTop??l?._parsedProps?.schMarginY??0,g=l?._parsedProps?.schMarginBottom??l?._parsedProps?.schMarginY??0;l?.config.shouldRenderAsSchematicBox&&(y+=.4,g+=.4);let x=(f-p)/2,v=(y-g)/2;i.chipMap[a]={chipId:a,pins:[],size:{x:(c.size?.width||1)+p+f,y:(c.size?.height||1)+y+g},availableRotations:u};let S=e.schematic_port.list({schematic_component_id:c.schematic_component_id});for(let P of S){let T=e.source_port.get(P.source_port_id);if(!T)continue;let k=`${a}.${T.pin_number||T.name||P.schematic_port_id}`;i.chipMap[a].pins.push(k);let C=pet(P.facing_direction);i.chipPinMap[k]={pinId:k,offset:{x:(P.center?.x||0)-(c.center.x||0)+x,y:(P.center?.y||0)-(c.center.y||0)+v},side:C}}}else if(s.nodeType==="group"&&s.sourceGroup){let a=s.sourceGroup.name||`group_${o}`;xe(`[${t.name}] Processing nested group: ${a}`);let c=e.schematic_group?.getWhere?.({source_group_id:s.sourceGroup.source_group_id}),l=t.children.find(u=>u.source_group_id===s.sourceGroup?.source_group_id);if(xe(`[${t.name}] Found schematic_group for ${a}:`,c),c){xe(`[${t.name}] Treating group ${a} as composite chip`);let u=e.schematic_component.list({schematic_group_id:c.schematic_group_id});xe(`[${t.name}] Group ${a} has ${u.length} components:`,u.map(A=>A.source_component_id));let p=1/0,f=-1/0,y=1/0,g=-1/0,x=!1;for(let A of u)if(A.center&&A.size){x=!0;let R=A.size.width/2,j=A.size.height/2;p=Math.min(p,A.center.x-R),f=Math.max(f,A.center.x+R),y=Math.min(y,A.center.y-j),g=Math.max(g,A.center.y+j)}let v=l?._parsedProps?.schMarginLeft??l?._parsedProps?.schMarginX??0,S=l?._parsedProps?.schMarginRight??l?._parsedProps?.schMarginX??0,P=l?._parsedProps?.schMarginTop??l?._parsedProps?.schMarginY??0,T=l?._parsedProps?.schMarginBottom??l?._parsedProps?.schMarginY??0,k=(S-v)/2,C=(P-T)/2,E=(x?f-p:2)+v+S,N=(x?g-y:2)+P+T;xe(`[${t.name}] Group ${a} computed size: ${E} x ${N}`);let I=[];for(let A of u){let R=e.schematic_port.list({schematic_component_id:A.schematic_component_id});for(let j of R){let B=e.source_port.get(j.source_port_id);if(!B)continue;let G=`${a}.${B.pin_number||B.name||j.schematic_port_id}`;I.push(G);let U=c.center||{x:0,y:0},H=pet(j.facing_direction);i.chipPinMap[G]={pinId:G,offset:{x:(j.center?.x||0)-U.x+k,y:(j.center?.y||0)-U.y+C},side:H}}}xe(`[${t.name}] Group ${a} has ${I.length} pins:`,I),i.chipMap[a]={chipId:a,pins:I,size:{x:E,y:N}},xe(`[${t.name}] Added group ${a} to chipMap`)}else xe(`[${t.name}] Warning: No schematic_group found for group ${a}`)}}),xe(`[${t.name}] Creating connections using connectivity keys`);let r=new Map;for(let[s,o]of Object.entries(i.chipMap))for(let a of o.pins){let c=a.split(".").pop(),l=n.childNodes.find(u=>u.nodeType==="component"&&u.sourceComponent?u.sourceComponent.name===s:u.nodeType==="group"&&u.sourceGroup?`group_${n.childNodes.indexOf(u)}`===s:!1);if(l?.nodeType==="group"&&l.sourceGroup){let u=e.schematic_group?.getWhere?.({source_group_id:l.sourceGroup.source_group_id});if(u){let p=e.schematic_component.list({schematic_group_id:u.schematic_group_id});for(let f of p){let y=e.source_port.list({source_component_id:f.source_component_id});for(let g of y){let x=g.pin_number||g.name;if(String(x)===String(c))if(g.subcircuit_connectivity_map_key){let v=g.subcircuit_connectivity_map_key;r.has(v)||r.set(v,[]),r.get(v).push(a),xe(`[${t.name}] \u2713 Pin ${a} has connectivity key: ${v}`)}else xe(`[${t.name}] Pin ${a} has no connectivity key`)}}}}else if(l?.nodeType==="component"&&l.sourceComponent){let u=e.source_port.list({source_component_id:l.sourceComponent.source_component_id});for(let p of u){let f=p.pin_number||p.name;if(String(f)===String(c)&&p.subcircuit_connectivity_map_key){let y=p.subcircuit_connectivity_map_key;r.has(y)||r.set(y,[]),r.get(y).push(a),xe(`[${t.name}] Pin ${a} has connectivity key: ${y}`)}}}}xe(`[${t.name}] Found ${r.size} connectivity groups:`,Array.from(r.entries()).map(([s,o])=>({key:s,pins:o})));for(let[s,o]of r)if(o.length>=2){let a=e.source_trace.list().filter(u=>u.subcircuit_connectivity_map_key===s),c=a.some(u=>u.connected_source_net_ids&&u.connected_source_net_ids.length>0),l=a.some(u=>u.connected_source_port_ids&&u.connected_source_port_ids.length>=2);if(xe(`[${t.name}] Connectivity ${s}: hasNetConnections=${c}, hasDirectConnections=${l}`),l){for(let u of a)if(u.connected_source_port_ids&&u.connected_source_port_ids.length>=2){let p=[];for(let f of u.connected_source_port_ids)for(let y of o){let g=y.split(".").pop(),x=e.source_port.get(f);if(x&&String(x.pin_number||x.name)===String(g)){let v=y.split(".")[0],S=n.childNodes.find(P=>P.nodeType==="component"&&P.sourceComponent?P.sourceComponent.name===v:P.nodeType==="group"&&P.sourceGroup?`group_${n.childNodes.indexOf(P)}`===v:!1);S?.nodeType==="component"&&S.sourceComponent&&e.source_port.list({source_component_id:S.sourceComponent.source_component_id}).some(T=>T.source_port_id===f)&&p.push(y)}}for(let f=0;f<p.length;f++)for(let y=f+1;y<p.length;y++){let g=p[f],x=p[y];i.pinStrongConnMap[`${g}-${x}`]=!0,i.pinStrongConnMap[`${x}-${g}`]=!0,xe(`[${t.name}] Created strong connection: ${g} <-> ${x}`)}}}if(c){let u=e.source_net.getWhere({subcircuit_connectivity_map_key:s}),p=u?.is_ground??!1,f=u?.is_power??!1;i.netMap[s]={netId:s,isGround:p,isPositiveVoltageSource:f};for(let y of o)i.netConnMap[`${y}-${s}`]=!0;xe(`[${t.name}] Created net ${s} with ${o.length} pins:`,o)}}return i}function KOt(n){let{db:e}=n.root,t=s_(e.toArray(),{source_group_id:n.source_group_id});if(xe(`[${n.name}] Starting matchpack layout with ${t.childNodes.length} children`),xe(`[${n.name}] Tree structure:`,JSON.stringify(t,null,2)),t.childNodes.length<=1){xe(`[${n.name}] Only ${t.childNodes.length} children, skipping layout`);return}xe("Converting circuit tree to InputProblem...");let i=ZOt(t,e,n);xe.enabled&&n.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`matchpack-input-problem-${n.name}`,content:JSON.stringify(i,null,2)});let r=new HJ(i);if(xe("Starting LayoutPipelineSolver..."),xe.enabled&&global?.debugGraphics){let c=r.visualize();global.debugGraphics.push({...c,title:`matchpack-initial-${n.name}`})}if(r.solve(),xe(`Solver completed in ${r.iterations} iterations`),xe(`Solved: ${r.solved}, Failed: ${r.failed}`),r.failed)throw xe(`Solver failed with error: ${r.error}`),new Error(`Matchpack layout solver failed: ${r.error}`);let s=r.getOutputLayout();if(xe("OutputLayout:",JSON.stringify(s,null,2)),xe("Solver completed successfully:",!r.failed),xe.enabled&&global?.debugGraphics){let c=r.visualize();global.debugGraphics.push({...c,title:`matchpack-final-${n.name}`})}let o=r.checkForOverlaps(s);if(o.length>0){xe(`Warning: Found ${o.length} overlapping components:`);for(let c of o)xe(` ${c.chip1} overlaps ${c.chip2} (area: ${c.overlapArea})`)}let a=n._getGlobalSchematicPositionBeforeLayout();xe(`Group offset: x=${a.x}, y=${a.y}`),xe(`Applying layout results for ${Object.keys(s.chipPlacements).length} chip placements`);for(let[c,l]of Object.entries(s.chipPlacements)){xe(`Processing placement for chip: ${c} at (${l.x}, ${l.y})`);let u=t.childNodes.find(f=>{if(f.nodeType==="component"&&f.sourceComponent){let y=f.sourceComponent.name===c;return xe(` Checking component ${f.sourceComponent.name}: matches=${y}`),y}if(f.nodeType==="group"&&f.sourceGroup){let y=f.sourceGroup.name,g=`group_${t.childNodes.indexOf(f)}`,x=g===c;return xe(` Checking group ${y} (expected chipId: ${g}): matches=${x}`),x}return!1});if(!u){xe(`Warning: No tree node found for chip: ${c}`),xe("Available tree nodes:",t.childNodes.map((f,y)=>({type:f.nodeType,name:f.nodeType==="component"?f.sourceComponent?.name:f.sourceGroup?.name,expectedChipId:f.nodeType==="group"?`group_${y}`:f.sourceComponent?.name})));continue}let p={x:l.x+a.x,y:l.y+a.y};if(u.nodeType==="component"&&u.sourceComponent){let f=e.schematic_component.getWhere({source_component_id:u.sourceComponent.source_component_id});if(f){xe(`Moving component ${c} to (${p.x}, ${p.y})`);let y=e.schematic_port.list({schematic_component_id:f.schematic_component_id}),g=e.schematic_text.list({schematic_component_id:f.schematic_component_id}),x={x:p.x-f.center.x,y:p.y-f.center.y};for(let v of y)v.center.x+=x.x,v.center.y+=x.y;for(let v of g)v.position.x+=x.x,v.position.y+=x.y;if(h9({db:e,schematicComponentId:f.schematic_component_id,deltaX:x.x,deltaY:x.y}),f.center=p,l.ccwRotationDegrees!==0){xe(`Component ${c} has rotation: ${l.ccwRotationDegrees}\xB0`);let v=l.ccwRotationDegrees*Math.PI/180,S=Math.cos(v),P=Math.sin(v);for(let T of y){let k=T.center.x-p.x,C=T.center.y-p.y,E=k*S-C*P,N=k*P+C*S;T.center.x=p.x+E,T.center.y=p.y+N;let I=T.facing_direction||"right";T.facing_direction=het(I,l.ccwRotationDegrees),T.side_of_component=(T.facing_direction==="up"?"top":T.facing_direction==="down"?"bottom":T.facing_direction)||T.side_of_component}for(let T of g){let k=T.position.x-p.x,C=T.position.y-p.y,E=k*S-C*P,N=k*P+C*S;T.position.x=p.x+E,T.position.y=p.y+N}if(f.symbol_name){let T=f.symbol_name.match(/_(right|left|up|down)$/);T&&(f.symbol_name=f.symbol_name.replace(T[0],`_${het(T[1],l.ccwRotationDegrees)}`))}}}}else if(u.nodeType==="group"&&u.sourceGroup){let f=e.schematic_group?.getWhere?.({source_group_id:u.sourceGroup.source_group_id});if(f){xe(`Moving group ${c} to (${p.x}, ${p.y}) from (${f.center?.x}, ${f.center?.y})`);let y=e.schematic_component.list({schematic_group_id:f.schematic_group_id});xe(`Group ${c} has ${y.length} components to move`);let g=f.center||{x:0,y:0},x={x:p.x-g.x,y:p.y-g.y};xe(`Position delta for group ${c}: (${x.x}, ${x.y})`);for(let v of y)if(v.center){let S={...v.center};v.center.x+=x.x,v.center.y+=x.y,xe(`Moved component ${v.source_component_id} from (${S.x}, ${S.y}) to (${v.center.x}, ${v.center.y})`);let P=e.schematic_port.list({schematic_component_id:v.schematic_component_id}),T=e.schematic_text.list({schematic_component_id:v.schematic_component_id});for(let k of P)k.center&&(k.center.x+=x.x,k.center.y+=x.y);for(let k of T)k.position&&(k.position.x+=x.x,k.position.y+=x.y)}f.center=p,xe(`Updated group ${c} center to (${p.x}, ${p.y})`)}}}xe("Matchpack layout completed successfully")}function JOt(n){if(!n.isSubcircuit)return;let{db:e}=n.root,t=n.selectAll("trace"),i=n.selectAll("via"),r=n.selectAll("net"),s=new Zm({});s.addConnections(t.map(u=>{let p=e.source_trace.get(u.source_trace_id);return p?[p.source_trace_id,...p.connected_source_port_ids,...p.connected_source_net_ids]:null}).filter(u=>u!==null));let o=e.source_net.list().filter(u=>u.subcircuit_id===n.subcircuit_id);for(let u of o)s.addConnections([[u.source_net_id]]);let{name:a}=n._parsedProps;for(let u of t){if(!u.source_trace_id)continue;let p=s.getNetConnectedToId(u.source_trace_id);p&&(u.subcircuit_connectivity_map_key=`${a??`unnamedsubcircuit${n._renderId}`}_${p}`,e.source_trace.update(u.source_trace_id,{subcircuit_connectivity_map_key:u.subcircuit_connectivity_map_key}))}let c=new Set;for(let u of t){if(!u.source_trace_id)continue;let p=e.source_trace.get(u.source_trace_id);if(p)for(let f of p.connected_source_port_ids)c.add(f)}for(let u of c){let p=s.getNetConnectedToId(u);if(!p)continue;let f=`${a??`unnamedsubcircuit${n._renderId}`}_${p}`;e.source_port.update(u,{subcircuit_connectivity_map_key:f})}let l=new Set;for(let u of t){if(!u.source_trace_id)continue;let p=e.source_trace.get(u.source_trace_id);if(p)for(let f of p.connected_source_net_ids)l.add(f)}for(let u of o)l.add(u.source_net_id);for(let u of l){let p=s.getNetConnectedToId(u);if(!p)continue;let f=`${a??`unnamedsubcircuit${n._renderId}`}_${p}`;e.source_net.update(u,{subcircuit_connectivity_map_key:f});let y=r.find(g=>g.source_net_id===u);y&&(y.subcircuit_connectivity_map_key=f)}for(let u of i){let p=u._getConnectedNetOrTrace();p&&p.subcircuit_connectivity_map_key&&(u.subcircuit_connectivity_map_key=p.subcircuit_connectivity_map_key)}}function QOt(n){let{db:e}=n.root,t=n._parsedProps,i=n.children.filter(C=>{let E=C._parsedProps?.schX!==void 0||C._parsedProps?.schY!==void 0;return C.schematic_component_id&&!E});if(i.length===0)return;let r=0,s=0;for(let C of i){let E=e.schematic_component.get(C.schematic_component_id);E?.size&&(r=Math.max(r,E.size.width),s=Math.max(s,E.size.height))}r===0&&i.length>0&&(r=1),s===0&&i.length>0&&(s=1);let o=t.gridCols,a,c=t.gridGap,l=t.gridRowGap,u=t.gridColumnGap;t.schLayout?.grid&&(o=t.schLayout.grid.cols??o,a=t.schLayout.grid.rows,c=t.schLayout.gridGap??c,l=t.schLayout.gridRowGap??l,u=t.schLayout.gridColumnGap??u);let p,f;o!==void 0&&a!==void 0?(p=o,f=a):o!==void 0?(p=o,f=Math.ceil(i.length/p)):a!==void 0?(f=a,p=Math.ceil(i.length/f)):(p=Math.ceil(Math.sqrt(i.length)),f=Math.ceil(i.length/p)),p===0&&i.length>0&&(p=1),f===0&&i.length>0&&(f=i.length);let y,g,x=C=>{if(C!==void 0)return typeof C=="number"?C:$.parse(C)};if(l!==void 0||u!==void 0){let C=typeof c=="object"&&c!==null?c.x:c,E=typeof c=="object"&&c!==null?c.y:c;y=x(u??C)??1,g=x(l??E)??1}else if(typeof c=="number")y=c,g=c;else if(typeof c=="string"){let C=$.parse(c);y=C,g=C}else if(typeof c=="object"&&c!==null){let C=c.x,E=c.y;y=typeof C=="number"?C:$.parse(C??"0mm"),g=typeof E=="number"?E:$.parse(E??"0mm")}else y=1,g=1;let v=p*r+Math.max(0,p-1)*y,S=f*s+Math.max(0,f-1)*g,P=n._getGlobalSchematicPositionBeforeLayout(),T=P.x-v/2+r/2,k=P.y+S/2-s/2;for(let C=0;C<i.length;C++){let E=i[C];if(!E.schematic_component_id)continue;let N=Math.floor(C/p),I=C%p;if(N>=f||I>=p){console.warn(`Schematic grid layout: Child ${E.getString()} at index ${C} (row ${N}, col ${I}) exceeds specified grid dimensions (${f}x${p}). Skipping placement.`);continue}let A=T+I*(r+y),R=k-N*(s+g),j=e.schematic_component.get(E.schematic_component_id);if(j){let B=j.center,G={x:A,y:R};e.schematic_component.update(E.schematic_component_id,{center:G});let U=G.x-B.x,H=G.y-B.y,Q=e.schematic_port.list({schematic_component_id:E.schematic_component_id});for(let V of Q)e.schematic_port.update(V.schematic_port_id,{center:{x:V.center.x+U,y:V.center.y+H}});let tt=e.schematic_text.list({schematic_component_id:E.schematic_component_id});for(let V of tt)e.schematic_text.update(V.schematic_text_id,{position:{x:V.position.x+U,y:V.position.y+H}});h9({db:e,schematicComponentId:E.schematic_component_id,deltaX:U,deltaY:H})}}n.schematic_group_id&&e.schematic_group.update(n.schematic_group_id,{width:v,height:S,center:P})}var det=(n,e)=>{let{sourceComponent:t,sourceGroup:i}=e;if(e.nodeType==="component"){let r=n.schematic_component.getWhere({source_component_id:t?.source_component_id});return r?.size?{width:r.size.width,height:r.size.height}:null}if(e.nodeType==="group"){let r=n.schematic_group.getWhere({source_group_id:i?.source_group_id});if(r?.width&&r?.height)return{width:r.width,height:r.height};let s=n.schematic_component.list({schematic_group_id:r?.schematic_group_id}),o=1/0,a=-1/0,c=1/0,l=-1/0;for(let f of s)if(f.center&&f.size){let y=f.size.width/2,g=f.size.height/2;o=Math.min(o,f.center.x-y),a=Math.max(a,f.center.x+y),c=Math.min(c,f.center.y-g),l=Math.max(l,f.center.y+g)}let u=a-o,p=l-c;return{width:u,height:p}}return null},tLt=n=>{let{db:e}=n.root,t=n._parsedProps,i=s_(e.toArray(),{source_group_id:n.source_group_id}),r=t.schJustifyContent??t.justifyContent,s=t.schAlignItems??t.alignItems,o=t.schFlexGap??t.schGap??t.gap,a=t.schFlexDirection??"row",c={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"space-between","space-between":"space-between","space-around":"space-around","space-evenly":"space-evenly",center:"center"}[r??"space-between"],l={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[s??"center"];if(!c)throw new Error(`Invalid justifyContent value: "${r}"`);if(!l)throw new Error(`Invalid alignItems value: "${s}"`);let u=0,p=0;typeof o=="object"?(u=o.y??0,p=o.x??0):typeof o=="number"?(u=o,p=o):typeof o=="string"&&(u=$.parse(o),p=$.parse(o));let f,y=t.width??t.schWidth??void 0,g=t.height??t.schHeight??void 0;(y===void 0||g===void 0)&&(f=Pw(i.childNodes.map(k=>det(e,k)).filter(k=>k!==null),{alignItems:l,justifyContent:c,direction:a,rowGap:u,columnGap:p}),y=f.width,g=f.height);let v=new ES(y,g,{alignItems:l,justifyContent:c,direction:a,rowGap:u,columnGap:p});for(let k of i.childNodes){let C=det(e,k);v.addChild({metadata:k,width:C?.width??0,height:C?.height??0,flexBasis:C?a==="row"?C.width:C.height:void 0})}v.build();let S={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let k of v.children)S.minX=Math.min(S.minX,k.position.x),S.minY=Math.min(S.minY,k.position.y),S.maxX=Math.max(S.maxX,k.position.x+k.size.width),S.maxY=Math.max(S.maxY,k.position.y+k.size.height);S.width=S.maxX-S.minX,S.height=S.maxY-S.minY;let P={x:-(S.maxX+S.minX)/2,y:-(S.maxY+S.minY)/2},T=e.toArray();for(let k of v.children){let{sourceComponent:C,sourceGroup:E}=k.metadata;if(C){let N=e.schematic_component.getWhere({source_component_id:C.source_component_id});if(!N)continue;tq(T,N.schematic_component_id,{x:k.position.x+k.size.width/2+P.x,y:k.position.y+k.size.height/2+P.y})}if(E){if(!e.schematic_group.getWhere({source_group_id:E.source_group_id}))continue;nq(T,E.source_group_id,{x:k.position.x+k.size.width/2+P.x,y:k.position.y+k.size.height/2+P.y})}}n.schematic_group_id&&e.schematic_group.update(n.schematic_group_id,{width:S.width,height:S.height})},GA=1;function eLt(n){let{db:e}=n.root,t=n._parsedProps,i=nLt(n);if(i.length===0)return;let r=iLt({db:e,pcbChildren:i}),s=rLt(t),o=sLt({props:t,pcbChildren:i,childDimensions:r,gridConfig:s}),a=cLt({pcbChildren:i,childDimensions:r,gridLayout:o,gridConfig:s}),{itemCoordinates:c}=a.layout();lLt({db:e,group:n,pcbChildren:i,itemCoordinates:c,gridLayout:o}),uLt({db:e,group:n,props:t,gridLayout:o})}function nLt(n){return n.children.filter(e=>e.pcb_component_id||e.pcb_group_id)}function iLt(n){let{db:e,pcbChildren:t}=n,i=0,r=0;for(let s of t){let o=0,a=0;if(s.pcb_group_id){let c=e.pcb_group.get(s.pcb_group_id);o=c?.width??0,a=c?.height??0}else if(s.pcb_component_id){let c=e.pcb_component.get(s.pcb_component_id);o=c?.width??0,a=c?.height??0}i=Math.max(i,o),r=Math.max(r,a)}return{width:i,height:r}}function rLt(n){let e=n.pcbGridCols??n.gridCols??n.pcbLayout?.grid?.cols,t=n.pcbGridRows??n.pcbLayout?.grid?.rows,i=n.pcbGridTemplateColumns,r=n.pcbGridTemplateRows,s=p=>p===void 0?GA:typeof p=="number"?p:$.parse(p),o=n.pcbGridGap??n.gridGap??n.pcbLayout?.gridGap,a=n.pcbGridRowGap??n.gridRowGap??n.pcbLayout?.gridRowGap,c=n.pcbGridColumnGap??n.gridColumnGap??n.pcbLayout?.gridColumnGap,l=GA,u=GA;if(a!==void 0||c!==void 0){let p=typeof o=="object"?o?.x:o,f=typeof o=="object"?o?.y:o;l=s(c??p),u=s(a??f)}else if(typeof o=="object"&&o!==null)l=s(o.x),u=s(o.y);else{let p=s(o);l=p,u=p}return{cols:e,rows:t,gapX:l,gapY:u,templateColumns:i,templateRows:r}}function sLt(n){let{props:e,pcbChildren:t,childDimensions:i,gridConfig:r}=n;return e.pcbGridTemplateColumns||e.pcbGridTemplateRows?oLt({props:e,gridConfig:r,pcbChildren:t,childDimensions:i}):aLt({gridConfig:r,pcbChildren:t,childDimensions:i})}function oLt(n){let{props:e,gridConfig:t,pcbChildren:i,childDimensions:r}=n,s=e.pcbGridTemplateColumns??"",o=e.pcbGridTemplateRows??"",a=f=>{let y=f.match(/repeat\((\d+),/);return y?parseInt(y[1]):Math.ceil(Math.sqrt(i.length))},c=e.pcbGridTemplateColumns?a(s):Math.ceil(Math.sqrt(i.length)),l=e.pcbGridTemplateRows?a(o):Math.ceil(i.length/c),u=c*r.width+Math.max(0,c-1)*t.gapX,p=l*r.height+Math.max(0,l-1)*t.gapY;return{gridTemplateColumns:s,gridTemplateRows:o,containerWidth:u,containerHeight:p}}function aLt(n){let{gridConfig:e,pcbChildren:t,childDimensions:i}=n,r,s;e.cols!==void 0&&e.rows!==void 0?(r=e.cols,s=e.rows):e.cols!==void 0?(r=e.cols,s=Math.ceil(t.length/r)):e.rows!==void 0?(s=e.rows,r=Math.ceil(t.length/s)):(r=Math.ceil(Math.sqrt(t.length)),s=Math.ceil(t.length/r)),r=Math.max(1,r),s=Math.max(1,s);let o=r*i.width+Math.max(0,r-1)*e.gapX,a=s*i.height+Math.max(0,s-1)*e.gapY,c=`repeat(${r}, ${i.width}px)`,l=`repeat(${s}, ${i.height}px)`;return{gridTemplateColumns:c,gridTemplateRows:l,containerWidth:o,containerHeight:a}}function cLt(n){let{pcbChildren:e,childDimensions:t,gridLayout:i,gridConfig:r}=n,s=e.map((o,a)=>({key:o.getString()||`child-${a}`,contentWidth:t.width,contentHeight:t.height}));return new nQ({containerWidth:i.containerWidth,containerHeight:i.containerHeight,gridTemplateColumns:i.gridTemplateColumns,gridTemplateRows:i.gridTemplateRows,gap:[r.gapY,r.gapX],children:s})}function lLt(n){let{db:e,group:t,pcbChildren:i,itemCoordinates:r,gridLayout:s}=n,o=t._getGlobalPcbPositionBeforeLayout(),a=e.toArray();for(let c=0;c<i.length;c++){let l=i[c],u=l.getString()||`child-${c}`,p=r[u];if(!p){console.warn(`PCB grid layout: No coordinates found for child ${u}`);continue}let f=o.x-s.containerWidth/2+p.x+p.width/2,y=o.y+s.containerHeight/2-p.y-p.height/2;if(l.pcb_component_id)ww(a,l.pcb_component_id,{x:f,y});else{let g=l;g.pcb_group_id&&g.source_group_id&&Sw(a,g.source_group_id,{x:f,y})}}}function uLt(n){let{db:e,group:t,props:i,gridLayout:r}=n;if(t.pcb_group_id){let s=t._getGlobalPcbPositionBeforeLayout();e.pcb_group.update(t.pcb_group_id,{width:i.width??r.containerWidth,height:i.height??r.containerHeight,center:s})}}function pLt(n){let e={serverUrl:"https://registry-api.tscircuit.com",serverMode:"job",serverCacheEnabled:!0};if(typeof n=="object"&&!n.preset)return{local:!(n.serverUrl||n.serverMode||n.serverCacheEnabled),...e,...n};let t=typeof n=="object"?n.preset:n,i=typeof n=="object"?n:{};switch(typeof t=="string"?t.replace(/_/g,"-"):t){case"auto-local":return{local:!0,groupMode:"subcircuit"};case"sequential-trace":return{local:!0,groupMode:"sequential-trace"};case"subcircuit":return{local:!0,groupMode:"subcircuit"};case"auto-cloud":{let{preset:s,local:o,groupMode:a,...c}=i;return{local:!1,groupMode:"subcircuit",...e,...c}}case"laser-prefab":{let{preset:s,local:o,groupMode:a,...c}=i;return{local:!0,groupMode:"subcircuit",preset:"laser_prefab",...c}}default:return{local:!0,groupMode:"subcircuit"}}}var hLt=(n,e)=>{let t=n.children.filter(p=>p.componentName==="Constraint"&&p._parsedProps.pcb),i=new Map,r={},s=p=>(r[p]!==p&&(r[p]=s(r[p])),r[p]),o=(p,f)=>{let y=s(p),g=s(f);y!==g&&(r[g]=y)},a=p=>{p in r||(r[p]=p)},c=p=>{let f=p.startsWith(".")?p.slice(1):p;return n.children.find(g=>g.name===f)?.pcb_component_id??void 0};for(let p of t){let f=p._parsedProps;if("left"in f&&"right"in f){let y=c(f.left),g=c(f.right);y&&g&&(a(y),a(g),o(y,g))}else if("top"in f&&"bottom"in f){let y=c(f.top),g=c(f.bottom);y&&g&&(a(y),a(g),o(y,g))}else if("for"in f&&Array.isArray(f.for)){let y=f.for.map(g=>c(g)).filter(g=>!!g);for(let g of y)a(g);for(let g=1;g<y.length;g++)o(y[0],y[g])}}for(let p of Object.keys(r)){let f=s(p);i.has(f)||i.set(f,{componentIds:[],constraints:[]}),i.get(f).componentIds.push(p)}for(let p of t){let f=p._parsedProps,y;if("left"in f?y=c(f.left):"top"in f?y=c(f.top):"for"in f&&(y=c(f.for[0])),!y)continue;let g=s(y);i.get(g)?.constraints.push(p)}let l={},u=Object.fromEntries(e.components.map(p=>[p.componentId,p]));for(let[p,f]of i.entries()){if(f.componentIds.length<=1)continue;let y=new e_,g={},x=(A,R)=>{let j=`${A}_${R}`;return g[j]||(g[j]=new Ca(j)),g[j]},v=f.componentIds[0];y.addConstraint(new Pi(x(v,"x"),si.Eq,0,Rn.required)),y.addConstraint(new Pi(x(v,"y"),si.Eq,0,Rn.required));for(let A of f.constraints){let R=A._parsedProps;if("xDist"in R){let j=c(R.left),B=c(R.right);j&&B&&y.addConstraint(new Pi(new Dn(x(B,"x"),[-1,x(j,"x")]),si.Eq,R.xDist,Rn.required))}else if("yDist"in R){let j=c(R.top),B=c(R.bottom);j&&B&&y.addConstraint(new Pi(new Dn(x(j,"y"),[-1,x(B,"y")]),si.Eq,R.yDist,Rn.required))}else if("sameX"in R&&Array.isArray(R.for)){let j=R.for.map(B=>c(B)).filter(B=>!!B);if(j.length>1){let B=x(j[0],"x");for(let G=1;G<j.length;G++)y.addConstraint(new Pi(new Dn(x(j[G],"x"),[-1,B]),si.Eq,0,Rn.required))}}else if("sameY"in R&&Array.isArray(R.for)){let j=R.for.map(B=>c(B)).filter(B=>!!B);if(j.length>1){let B=x(j[0],"y");for(let G=1;G<j.length;G++)y.addConstraint(new Pi(new Dn(x(j[G],"y"),[-1,B]),si.Eq,0,Rn.required))}}}y.updateVariables();let S={};for(let A of f.componentIds)S[A]={x:x(A,"x").value(),y:x(A,"y").value()};let P=1/0,T=1/0,k=-1/0,C=-1/0;for(let A of f.componentIds){let R=u[A],j=S[A];if(R)for(let B of R.pads){let G=j.x+B.offset.x,U=j.y+B.offset.y;P=Math.min(P,G-B.size.x/2),k=Math.max(k,G+B.size.x/2),T=Math.min(T,U-B.size.y/2),C=Math.max(C,U+B.size.y/2)}}let E={x:(P+k)/2,y:(T+C)/2},N=[],I={};for(let A of f.componentIds){let R=u[A],j=S[A];if(R){I[A]={x:j.x-E.x,y:j.y-E.y};for(let B of R.pads)N.push({padId:B.padId,networkId:B.networkId,type:B.type,size:B.size,offset:{x:j.x+B.offset.x-E.x,y:j.y+B.offset.y-E.y}})}}e.components=e.components.filter(A=>!f.componentIds.includes(A.componentId)),e.components.push({componentId:f.componentIds[0],pads:N,availableRotationDegrees:[0]}),f.relativeCenters=I,l[f.componentIds[0]]=f}return l},fet=({db:n,pcbComponentId:e,rotationDegrees:t,layer:i})=>{if(t==null||!n?.cad_component?.list)return;let r=n.cad_component.getWhere({pcb_component_id:e});if(!r)return;let s=i?.toLowerCase?.()==="bottom"?-t:t,o=r.rotation?.z??0,a={...r.rotation??{x:0,y:0,z:0},z:sd(o+s)};n.cad_component.update(r.cad_component_id,{rotation:a}),r.rotation=a},F1=(n,e,t)=>{if(e===t)return!0;let i=n.source_group.get(e);return!i||!i.parent_source_group_id?!1:F1(n,i.parent_source_group_id,t)},dLt=(n,e,t)=>{let{db:i}=n.root;for(let r of e.components){let{center:s,componentId:o,ccwRotationOffset:a,ccwRotationDegrees:c}=r,l=t[o];if(l){let v=c??a??0,S=v*Math.PI/180;for(let P of l.componentIds){let T=l.relativeCenters[P];if(!T)continue;let k={x:T.x*Math.cos(S)-T.y*Math.sin(S),y:T.x*Math.sin(S)+T.y*Math.cos(S)},C=i.pcb_component.get(P);if(!C)continue;let E=C.center,N=mi(n._computePcbGlobalTransformBeforeLayout(),Nn(s.x+k.x,s.y+k.y),Dc(S),Nn(-E.x,-E.y)),I=i.toArray().filter(A=>"pcb_component_id"in A&&A.pcb_component_id===P);i_(I,N),fet({db:i,pcbComponentId:P,rotationDegrees:v,layer:C.layer})}continue}let u=i.pcb_component.get(o);if(u){let v=n.source_group_id,P=i.source_component.get(u.source_component_id)?.source_group_id;if(P!==void 0&&!F1(i,P,v))continue;let T=u.center,k=c??a??0,C=mi(n._computePcbGlobalTransformBeforeLayout(),Nn(s.x,s.y),Dc(k*Math.PI/180),Nn(-T.x,-T.y)),E=i.toArray().filter(N=>"pcb_component_id"in N&&N.pcb_component_id===o);i_(E,C),fet({db:i,pcbComponentId:o,rotationDegrees:k,layer:u.layer});continue}let p=i.pcb_group.list().find(v=>v.source_group_id===o);if(!p)continue;let f=p.center,y=c??a??0,g=mi(n._computePcbGlobalTransformBeforeLayout(),Nn(s.x,s.y),Dc(y*Math.PI/180),Nn(-f.x,-f.y)),x=i.toArray().filter(v=>{if("source_group_id"in v&&v.source_group_id&&(v.source_group_id===o||F1(i,v.source_group_id,o)))return!0;if("source_component_id"in v&&v.source_component_id){let S=i.source_component.get(v.source_component_id);if(S?.source_group_id&&(S.source_group_id===o||F1(i,S.source_group_id,o)))return!0}if("pcb_component_id"in v&&v.pcb_component_id){let S=i.pcb_component.get(v.pcb_component_id);if(S?.source_component_id){let P=i.source_component.get(S.source_component_id);if(P?.source_group_id&&(P.source_group_id===o||F1(i,P.source_group_id,o)))return!0}}return!1});i_(x,g),i.pcb_group.update(p.pcb_group_id,{center:s})}};function fLt(n){switch(n.shape){case"rect":case"rotated_rect":case"pill":case"rotated_pill":return{width:n.width,height:n.height};case"circle":return{width:n.radius*2,height:n.radius*2};case"polygon":if(!n.points||n.points.length===0)return null;let e=n.points.map(a=>a.x),t=n.points.map(a=>a.y),i=Math.min(...e),r=Math.max(...e),s=Math.min(...t),o=Math.max(...t);return{width:r-i,height:o-s};default:return null}}function mLt(n){switch(n.shape){case"circular_hole_with_rect_pad":case"pill_hole_with_rect_pad":case"rotated_pill_hole_with_rect_pad":return{width:n.rect_pad_width,height:n.rect_pad_height};case"circle":return{width:n.outer_diameter,height:n.outer_diameter};case"oval":return{width:n.outer_width,height:n.outer_height};case"pill":return{width:n.outer_width,height:n.outer_height};default:return null}}var _Lt="1mm",met=(0,Ket.default)("Group_doInitialPcbLayoutPack"),yLt=n=>{let{db:e}=n.root,{_parsedProps:t}=n,{packOrderStrategy:i,packPlacementStrategy:r,gap:s,pcbGap:o,pcbPackGap:a}=t,c=a??o??s,l=$.parse(c??_Lt),u={},p=new Set,f=k=>{if(k?.pcb_component_id&&k?._parsedProps){let C=k._parsedProps,E=$.parse(C.pcbMarginLeft??C.pcbMarginX??0),N=$.parse(C.pcbMarginRight??C.pcbMarginX??0),I=$.parse(C.pcbMarginTop??C.pcbMarginY??0),A=$.parse(C.pcbMarginBottom??C.pcbMarginY??0);(E||N||I||A)&&(u[k.pcb_component_id]={left:E,right:N,top:I,bottom:A})}k?.children&&k.children.forEach(f)};f(n);let y=new Set;for(let k of n.children){let C=k;C._isNormalComponent&&C.isRelativelyPositioned?.()&&(C.pcb_component_id&&p.add(C.pcb_component_id),C.pcb_group_id&&y.add(C.pcb_group_id))}let g=e.toArray().filter(k=>k.type==="pcb_component"?!p.has(k.pcb_component_id):k.type==="pcb_group"?!y.has(k.pcb_group_id):!0),x=[];for(let k of p){let C=e.toArray().find(R=>R.type==="pcb_component"&&R.pcb_component_id===k);if(!C)continue;let E=C.center.x,N=C.center.y,I=e.toArray().filter(R=>R.type==="pcb_smtpad"&&R.pcb_component_id===k);for(let R of I){let j=fLt(R);if(!j||j.width===0||j.height===0)continue;let B,G;if(R.shape==="polygon"){let U=R.points.map(Q=>Q.x),H=R.points.map(Q=>Q.y);B=E+(Math.min(...U)+Math.max(...U))/2,G=N+(Math.min(...H)+Math.max(...H))/2}else B=E+R.x,G=N+R.y;x.push({obstacleId:R.pcb_smtpad_id,absoluteCenter:{x:B,y:G},width:j.width,height:j.height})}let A=e.toArray().filter(R=>R.type==="pcb_plated_hole"&&R.pcb_component_id===k);for(let R of A){let j=mLt(R);if(!j||j.width===0||j.height===0)continue;let B=E+R.x,G=N+R.y;x.push({obstacleId:R.pcb_plated_hole_id,absoluteCenter:{x:B,y:G},width:j.width,height:j.height})}}let v;if(t.width!==void 0&&t.height!==void 0){let k=$.parse(t.width),C=$.parse(t.height);v={minX:-k/2,maxX:k/2,minY:-C/2,maxY:C/2}}let S={...VJ(UJ(g,{source_group_id:n.source_group_id,shouldAddInnerObstacles:!0,chipMarginsMap:u})),orderStrategy:i??"largest_to_smallest",placementStrategy:r??"minimum_sum_squared_distance_to_network",minGap:l,obstacles:x,bounds:v},P=hLt(n,S);met.enabled&&(n.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-circuitjson-${n.name}`,content:JSON.stringify(e.toArray())}),n.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-${n.name}`,content:S}));let T=PS(S);if(met.enabled&&global?.debugGraphics){let k=eA(T);k.title=`packOutput-${n.name}`,global.debugGraphics?.push(k)}dLt(n,T,P)},gLt=n=>{let{db:e}=n.root,{_parsedProps:t}=n,i=n.children.filter(C=>C.pcb_component_id||C.pcb_group_id);if(i.some(C=>{let E=C._parsedProps;return E?.pcbX!==void 0||E?.pcbY!==void 0}))return;let s=t.pcbJustifyContent??t.justifyContent,o=t.pcbAlignItems??t.alignItems,a=t.pcbFlexGap??t.pcbGap??t.gap,c=t.pcbFlexDirection??"row",l={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"space-between","space-between":"space-between","space-around":"space-around","space-evenly":"space-evenly",center:"center"}[s??"space-between"],u={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[o??"center"];if(!l)throw new Error(`Invalid justifyContent value: "${s}"`);if(!u)throw new Error(`Invalid alignItems value: "${o}"`);let p=0,f=0;typeof a=="object"?(p=a.y??0,f=a.x??0):typeof a=="number"?(p=a,f=a):typeof a=="string"&&(p=$.parse(a),f=$.parse(a));let y,g=t.width??t.pcbWidth??void 0,x=t.height??t.pcbHeight??void 0;(g===void 0||x===void 0)&&(y=Pw(i.map(C=>C._getMinimumFlexContainerSize()).filter(C=>C!==null),{alignItems:u,justifyContent:l,direction:c,rowGap:p,columnGap:f}),g=y.width,x=y.height);let S=new ES(g,x,{alignItems:u,justifyContent:l,direction:c,rowGap:p,columnGap:f});for(let C of i){let E=C._getMinimumFlexContainerSize();S.addChild({metadata:C,width:E?.width??0,height:E?.height??0,flexBasis:E?c==="row"?E.width:E.height:void 0})}S.build();let P={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let C of S.children)P.minX=Math.min(P.minX,C.position.x),P.minY=Math.min(P.minY,C.position.y),P.maxX=Math.max(P.maxX,C.position.x+C.size.width),P.maxY=Math.max(P.maxY,C.position.y+C.size.height);P.width=P.maxX-P.minX,P.height=P.maxY-P.minY;let T=n._getGlobalPcbPositionBeforeLayout(),k={x:T.x-(P.maxX+P.minX)/2,y:T.y-(P.maxY+P.minY)/2};for(let C of S.children)C.metadata._repositionOnPcb({x:C.position.x+C.size.width/2+k.x,y:C.position.y+C.size.height/2+k.y});e.pcb_group.update(n.pcb_group_id,{width:P.width,height:P.height,center:T})};function xLt(n){let{db:e}=n.root,t=new Map,i=new Map,r=new Set,o=n.selectAll("trace").filter(R=>R._parsedProps?.schDisplayLabel),a=n.selectAll("group"),c=[n.schematic_group_id,...a.map(R=>R.schematic_group_id)],l=e.schematic_component.list().filter(R=>c.includes(R.schematic_group_id)),u=[],p=new Map,f=new Map;for(let R of l){let j=R.schematic_component_id,B=[],G=e.source_component.getWhere({source_component_id:R.source_component_id}),U=e.schematic_port.list({schematic_component_id:R.schematic_component_id});for(let H of U){let Q=`${G?.name??R.schematic_component_id}.${H.pin_number}`;p.set(Q,H.schematic_port_id),f.set(H.schematic_port_id,Q)}for(let H of U){let Q=f.get(H.schematic_port_id);B.push({pinId:Q,x:H.center.x,y:H.center.y})}u.push({chipId:j,center:R.center,width:R.size.width,height:R.size.height,pins:B})}let y=new Set,g=new Map,x=new Map,v=new Map;for(let R of l){let j=e.schematic_port.list({schematic_component_id:R.schematic_component_id});for(let B of j)y.add(B.schematic_port_id),B.source_port_id&&(g.set(B.schematic_port_id,B.source_port_id),x.set(B.source_port_id,B.schematic_port_id))}let S=new Set;n.subcircuit_id&&S.add(n.subcircuit_id);for(let R of a)R.subcircuit_id&&S.add(R.subcircuit_id);let T=e.source_trace.list().filter(R=>{if(R.subcircuit_id===n.subcircuit_id)return!0;for(let j of R.connected_source_port_ids)if(x.has(j))return!0;return!1}).flatMap(R=>R.connected_source_net_ids);for(let R of T){let j=e.source_net.get(R);j?.subcircuit_id&&S.add(j.subcircuit_id)}let k=[],C=new Map;for(let R of e.source_trace.list()){if(R.subcircuit_id&&!S.has(R.subcircuit_id))continue;let j=(R.connected_source_port_ids??[]).map(B=>x.get(B)).filter(B=>!!B&&y.has(B));if(j.length>=2){let[B,G]=j.slice(0,2),U=[B,G].sort().join("::");if(!C.has(U)){C.set(U,R.source_trace_id);let H=R.display_name??R.source_trace_id;R.subcircuit_connectivity_map_key&&(r.add(R.subcircuit_connectivity_map_key),v.set(H,R.subcircuit_connectivity_map_key),i.set(R.subcircuit_connectivity_map_key,H)),k.push({pinIds:[B,G].map(Q=>f.get(Q)),netId:H})}}}let E=[];for(let R of e.source_net.list().filter(j=>!j.subcircuit_id||S.has(j.subcircuit_id)))R.subcircuit_connectivity_map_key&&(r.add(R.subcircuit_connectivity_map_key),t.set(R.subcircuit_connectivity_map_key,R));let N=new Map;for(let[R,j]of g){let B=e.source_port.get(j);if(!B?.subcircuit_connectivity_map_key)continue;let G=B.subcircuit_connectivity_map_key;r.add(G),N.has(G)||N.set(G,[]),N.get(G).push(R)}for(let[R,j]of N){let B=t.get(R);if(B&&j.length>=2){let G=String(B.name||B.source_net_id||R);v.set(G,R),i.set(R,G);let H=.1*(.18/.18),Q=Number((String(G).length*H).toFixed(2));E.push({netId:G,pinIds:j.map(tt=>f.get(tt)),netLabelWidth:Q})}}let I=(()=>{let R={},j=new Set(E.map(B=>B.netId));for(let B of e.source_net.list().filter(G=>!G.subcircuit_id||S.has(G.subcircuit_id)))B.name&&j.has(B.name)&&(B.is_ground||B.name.toLowerCase().startsWith("gnd")?R[B.name]=["y-"]:B.is_power||B.name.toLowerCase().startsWith("v")?R[B.name]=["y+"]:R[B.name]=["x-","x+"]);return R})();return{inputProblem:{chips:u,directConnections:k,netConnections:E,availableNetLabelOrientations:I,maxMspPairDistance:n._parsedProps.schMaxTraceDistance??2.4},pinIdToSchematicPortId:p,pairKeyToSourceTraceId:C,sckToSourceNet:t,sckToUserNetId:i,userNetIdToSck:v,allSourceAndSchematicPortIdsInScope:y,schPortIdToSourcePortId:g,displayLabelTraces:o,allScks:r}}var gr=1e-6;function _et(n){let e=Math.abs(n.to.x-n.from.x),t=Math.abs(n.to.y-n.from.y);return e>=t}function qS(n,e){return Math.hypot(e.x-n.x,e.y-n.y)}function yet(n,e,t){return{x:n.x+(e.x-n.x)*t,y:n.y+(e.y-n.y)*t}}function get(n,e,t){let i=qS(n,e);if(i<gr)return 0;let r=((t.x-n.x)*(e.x-n.x)+(t.y-n.y)*(e.y-n.y))/((e.x-n.x)*(e.x-n.x)+(e.y-n.y)*(e.y-n.y));return Math.max(0,Math.min(1,r))*i}function XS(n,e,t,i){return n*i-e*t}function bLt(n,e,t,i){let r={x:e.x-n.x,y:e.y-n.y},s={x:i.x-t.x,y:i.y-t.y},o=XS(r.x,r.y,s.x,s.y),a={x:t.x-n.x,y:t.y-n.y},c=XS(a.x,a.y,r.x,r.y);if(Math.abs(o)<gr&&Math.abs(c)<gr||Math.abs(o)<gr&&Math.abs(c)>=gr)return null;let l=XS(a.x,a.y,s.x,s.y)/o,u=XS(a.x,a.y,r.x,r.y)/o;return l<-gr||l>1+gr||u<-gr||u>1+gr?null:{x:n.x+l*r.x,y:n.y+l*r.y}}function vLt(n,e=gr){if(n.length===0)return n;n.sort((r,s)=>r.start-s.start);let t=[],i={...n[0]};for(let r=1;r<n.length;r++){let s=n[r];s.start<=i.end+e?i.end=Math.max(i.end,s.end):(t.push(i),i={...s})}return t.push(i),t}function wLt(n,e,t){let i=qS(n.from,n.to);if(i<gr||e.length===0)return[n];let r=t/2,s=e.map(p=>({start:Math.max(0,p-r),end:Math.min(i,p+r)})).filter(p=>p.end-p.start>gr),o=vLt(s),a=[],c=0,l={x:n.to.x-n.from.x,y:n.to.y-n.from.y},u=(p,f,y)=>{if(f-p<=gr)return;let g=p/i,x=f/i;a.push({from:yet(n.from,n.to,g),to:yet(n.from,n.to,x),...y?{is_crossing:!0}:{}})};for(let p of o)p.start-c>gr&&u(c,p.start,!1),u(p.start,p.end,!0),c=p.end;return i-c>gr&&u(c,i,!1),a.length>0?a:[n]}function SLt(n,e={}){let t=e.crossSegmentLength??.075,i=e.tolerance??gr,r=new Map,s=c=>`${c.traceIdx}:${c.edgeIdx}`,o=c=>n[c.traceIdx].edges[c.edgeIdx];for(let c=0;c<n.length;c++){let l=n[c];for(let u=0;u<l.edges.length;u++){let p=l.edges[u];for(let f=c;f<n.length;f++){let y=n[f];for(let g=f===c?u+1:0;g<y.edges.length;g++){let x=y.edges[g],v=bLt(p.from,p.to,x.from,x.to);if(!v)continue;let S=qS(p.from,p.to),P=qS(x.from,x.to);if(S<i||P<i)continue;let T=get(p.from,p.to,v),k=get(x.from,x.to,v),C=T<=i||Math.abs(S-T)<=i||Number.isNaN(T),E=k<=i||Math.abs(P-k)<=i||Number.isNaN(k);if(!C&&!E){let N=_et(p),I=_et(x),A;if(N!==I)A=N;else{let B=Math.abs(p.to.x-p.from.x),G=Math.abs(p.to.y-p.from.y),U=Math.abs(x.to.x-x.from.x),H=Math.abs(x.to.y-x.from.y),Q=B-G,tt=U-H;A=Q===tt?!0:Q>tt}let R=s({traceIdx:A?c:f,edgeIdx:A?u:g}),j=r.get(R)??[];j.push(A?T:k),r.set(R,j)}}}}}let a=n.map(c=>({source_trace_id:c.source_trace_id,edges:[]}));for(let c=0;c<n.length;c++){let l=n[c];for(let u=0;u<l.edges.length;u++){let p=s({traceIdx:c,edgeIdx:u}),f=r.get(p)??[];if(f.length===0){a[c].edges.push(l.edges[u]);continue}let y=Array.from(new Set(f.map(x=>Number(x.toFixed(6))))).sort((x,v)=>x-v),g=wLt(l.edges[u],y,t);a[c].edges.push(...g)}}return a}var Vo=1e-6;function ZS(n,e,t=Vo){return Math.abs(n-e)<=t}function W_(n,e,t=Vo){return ZS(n.x,e.x,t)&&ZS(n.y,e.y,t)}function xet(n,e,t,i=Vo){let r=Math.min(e.x,t.x)-i,s=Math.max(e.x,t.x)+i,o=Math.min(e.y,t.y)-i,a=Math.max(e.y,t.y)+i;return n.x<r||n.x>s||n.y<o||n.y>a?!1:Math.abs((t.x-e.x)*(n.y-e.y)-(t.y-e.y)*(n.x-e.x))<=i}function bet(n,e=Vo){let t=new Map;for(let i of n){let r=`${i.x.toFixed(6)},${i.y.toFixed(6)}`;t.has(r)||t.set(r,i)}return Array.from(t.values())}function vet(n){return{x:n.to.x-n.from.x,y:n.to.y-n.from.y}}function HA(n,e,t=Vo){let i=vet(n),r=vet(e),s=Math.hypot(i.x,i.y),o=Math.hypot(r.x,r.y);if(s<t||o<t)return!0;let a=i.x*r.y-i.y*r.x;return Math.abs(a)<=t*s*o}function z1(n,e,t=Vo){return n.edges.filter(i=>W_(i.from,e,t)||W_(i.to,e,t))}function wet(n,e,t=Vo){for(let i of n.edges){if(W_(i.from,e,t))return i.from;if(W_(i.to,e,t))return i.to}return null}function PLt(n,e,t=Vo){let i=W_(n.from,e,t)||ZS(n.from.x,e.x,t)&&ZS(n.from.y,e.y,t)?n.to:n.from,r=i.x-e.x,s=i.y-e.y;return Math.abs(r)<t&&Math.abs(s)<t?null:Math.abs(r)>=Math.abs(s)?r>=0?"right":"left":s>=0?"up":"down"}function B_(n,e,t=Vo){let i=z1(n,e,t);if(i.length<2)return null;let r=i.map(p=>PLt(p,e,t)),s=r.includes("up"),o=r.includes("down"),a=r.includes("left"),c=r.includes("right"),l=s?"up":o?"down":null,u=c?"right":a?"left":null;return l&&u?`${l}-${u}`:null}function kLt(n,e={}){let t=e.tolerance??Vo,i={};for(let s of n)i[s.source_trace_id]=[];let r=n.map(s=>{let o=[];for(let a of s.edges)o.push(a.from,a.to);return bet(o,t)});for(let s=0;s<n.length;s++){let o=n[s],a=r[s];for(let c=s+1;c<n.length;c++){let l=n[c],u=r[c];for(let p of a)for(let f of u)if(W_(p,f,t)){let y=z1(o,p,t),g=z1(l,f,t),x=y.some(T=>g.some(k=>!HA(T,k,t))),v=B_(o,p,t),S=B_(l,f,t);x&&!(v!==null&&S!==null&&v===S)&&(i[o.source_trace_id].push(p),o.source_trace_id!==l.source_trace_id&&i[l.source_trace_id].push(f))}for(let p of a)for(let f of l.edges)if(xet(p,f.from,f.to,t)){let g=z1(o,p,t).some(T=>!HA(T,f,t)),x=B_(o,p,t),v=wet(l,p,t*1e3),S=v?B_(l,v,t):null;g&&!(x!==null&&S!==null&&x===S)&&(i[o.source_trace_id].push(p),o.source_trace_id!==l.source_trace_id&&i[l.source_trace_id].push(p))}for(let p of u)for(let f of o.edges)if(xet(p,f.from,f.to,t)){let g=z1(l,p,t).some(T=>!HA(f,T,t)),x=B_(l,p,t),v=wet(o,p,t*1e3),S=v?B_(o,v,t):null;g&&!(S!==null&&x!==null&&S===x)&&(i[l.source_trace_id].push(p),o.source_trace_id!==l.source_trace_id&&i[o.source_trace_id].push(p))}}}for(let s of Object.keys(i))i[s]=bet(i[s],t);return i}var WA=(0,Qet.default)("Group_doInitialSchematicTraceRender");function TLt(n){let{group:e,solver:t,pinIdToSchematicPortId:i,userNetIdToSck:r}=n,{db:s}=e.root,o=t.traceCleanupSolver?.getOutput().traces??t.traceLabelOverlapAvoidanceSolver?.getOutput().traces??t.schematicTraceLinesSolver?.solvedTracePaths,a=[];WA(`Traces inside SchematicTraceSolver output: ${(o??[]).length}`);for(let u of o??[]){let p=u?.tracePath;if(!Array.isArray(p)||p.length<2){WA(`Skipping trace ${u?.pinIds.join(",")} because it has less than 2 points`);continue}let f=[];for(let x=0;x<p.length-1;x++)f.push({from:{x:p[x].x,y:p[x].y},to:{x:p[x+1].x,y:p[x+1].y}});let y=null,g;if(Array.isArray(u?.pins)&&u.pins.length===2){let x=i.get(u.pins[0]?.pinId),v=i.get(u.pins[1]?.pinId);if(x&&v){for(let S of[x,v])s.schematic_port.get(S)&&s.schematic_port.update(S,{is_connected:!0});g=r.get(String(u.userNetId))}}y||(y=`solver_${u?.mspPairId}`,g=r.get(String(u.userNetId))),a.push({source_trace_id:y,edges:f,subcircuit_connectivity_map_key:g})}WA(`Applying ${a.length} traces from SchematicTraceSolver output`);let c=SLt(a.map(u=>({source_trace_id:u.source_trace_id,edges:u.edges}))),l=kLt(c);for(let u of c)s.schematic_trace.insert({source_trace_id:u.source_trace_id,edges:u.edges,junctions:l[u.source_trace_id]??[],subcircuit_connectivity_map_key:a.find(p=>p.source_trace_id===u.source_trace_id)?.subcircuit_connectivity_map_key})}var ELt=n=>{switch(n){case"x+":return"left";case"x-":return"right";case"y+":return"bottom";case"y-":return"top";case"left":return"right";case"top":return"bottom";case"right":return"left";case"bottom":return"top"}},MLt=n=>{for(let t of n){let i=t._getDirectlyConnectedTraces();for(let r of i){let s=r._parsedProps.schDisplayLabel;if(s)return{name:s,wasAssignedDisplayLabel:!0}}}return{name:n.map(t=>t._getNetLabelText()).join("/"),wasAssignedDisplayLabel:!1}},qA=(0,tnt.default)("Group_doInitialSchematicTraceRender");function CLt(n){let{group:e,solver:t,sckToSourceNet:i,allScks:r,allSourceAndSchematicPortIdsInScope:s,schPortIdToSourcePortId:o,userNetIdToSck:a,pinIdToSchematicPortId:c,schematicPortIdsWithPreExistingNetLabels:l,schematicPortIdsWithRoutedTraces:u}=n,{db:p}=e.root,f=t.netLabelPlacementSolver?.netLabelPlacements??t.traceLabelOverlapAvoidanceSolver?.getOutput().netLabelPlacements??[],y=t.mspConnectionPairSolver.globalConnMap;for(let g of f){qA(`processing placement: ${g.netId}`);let x=y.getIdsConnectedToNet(g.globalConnNetId).find(R=>a.get(R)),v=a.get(x),S=g.anchorPoint,P=g.orientation,T=ELt(P),k=v?i.get(v):void 0,C=g.pinIds.map(R=>c.get(R));if(C.some(R=>l.has(R))){qA(`skipping net label placement for "${g.netId}" REASON:schematic port has pre-existing net label`);continue}if(k){let R=k.name,j=ml({anchor_position:S,anchor_side:T,text:R});p.schematic_net_label.insert({text:R,anchor_position:S,center:j,anchor_side:T,...k?.source_net_id?{source_net_id:k.source_net_id}:{}});continue}let E=e.selectAll("port").filter(R=>R._getSubcircuitConnectivityKey()===v),{name:N,wasAssignedDisplayLabel:I}=MLt(E);if(!I&&C.some(R=>u.has(R))){qA(`skipping net label placement for "${g.netId}" REASON:schematic port has routed traces and no display label`);continue}let A=ml({anchor_position:S,anchor_side:T,text:N});p.schematic_net_label.insert({text:N,anchor_position:S,center:A,anchor_side:T})}}var ILt=({allSourceAndSchematicPortIdsInScope:n,group:e,schPortIdToSourcePortId:t,sckToSourceNet:i,pinIdToSchematicPortId:r,schematicPortIdsWithPreExistingNetLabels:s})=>{let{db:o}=e.root;for(let a of Array.from(n)){let c=o.schematic_port.get(a);if(!c||c.is_connected)continue;let l=t.get(a);if(!l)continue;let p=o.source_port.get(l)?.subcircuit_connectivity_map_key;if(!p)continue;let f=i.get(p);if(!f||o.schematic_net_label.list().some(S=>Math.abs(S.anchor_position.x-c.center.x)<.1&&Math.abs(S.anchor_position.y-c.center.y)<.1?f.source_net_id&&S.source_net_id?S.source_net_id===f.source_net_id:S.text===(f.name||p):!1))continue;let g=f.name||f.source_net_id||p,x=B1(c.facing_direction||"right")||"right",v=ml({anchor_position:c.center,anchor_side:x,text:g});o.schematic_net_label.insert({text:g,anchor_position:c.center,center:v,anchor_side:x,...f.source_net_id?{source_net_id:f.source_net_id}:{}})}},NLt=n=>{let e=new Set,t=n.selectAll("netlabel");for(let i of t){let r=i._getConnectedPorts();for(let s of r)s.schematic_port_id&&e.add(s.schematic_port_id)}return e},ALt=({solver:n,pinIdToSchematicPortId:e})=>{let t=n.schematicTraceLinesSolver.solvedTracePaths,i=new Set;for(let r of t)for(let s of r.pinIds){let o=e.get(s);o&&i.add(o)}return i},RLt=(0,Jet.default)("Group_doInitialSchematicTraceRender"),OLt=n=>{if(!n.root?._featureMspSchematicTraceRouting||!n.isSubcircuit||n.root?.schematicDisabled)return;let{inputProblem:e,pinIdToSchematicPortId:t,pairKeyToSourceTraceId:i,sckToSourceNet:r,allSourceAndSchematicPortIdsInScope:s,schPortIdToSourcePortId:o,displayLabelTraces:a,allScks:c,userNetIdToSck:l}=xLt(n),u=NLt(n);RLt.enabled&&n.root?.emit("debug:logOutput",{type:"debug:logOutput",name:"group-trace-render-input-problem",content:JSON.stringify(e,null,2)});let p=new bQ(e);p.solve();let f=ALt({solver:p,pinIdToSchematicPortId:t});TLt({group:n,solver:p,pinIdToSchematicPortId:t,userNetIdToSck:l}),CLt({group:n,solver:p,sckToSourceNet:r,allSourceAndSchematicPortIdsInScope:s,schPortIdToSourcePortId:o,pinIdToSchematicPortId:t,allScks:c,userNetIdToSck:l,schematicPortIdsWithPreExistingNetLabels:u,schematicPortIdsWithRoutedTraces:f}),ILt({group:n,allSourceAndSchematicPortIdsInScope:s,schPortIdToSourcePortId:o,sckToSourceNet:r,pinIdToSchematicPortId:t,schematicPortIdsWithPreExistingNetLabels:u})},LLt=()=>({async simulate(n){let e="spice-experiment-1",{circuit:t,tran:i}=SQ(n);return{simulationResultCircuitJson:PQ(i,t,e)}}}),Ya=(0,ent.default)("tscircuit:core:Group_doInitialSimulationSpiceEngineRender");function FLt(n){if(!n.isSubcircuit)return;let{root:e}=n;if(!e)return;let t=n.selectAll("analogsimulation");if(t.length===0)return;let i={...e.platform?.spiceEngineMap};i.spicey||(i.spicey=LLt());let r=e.db.toArray(),s;try{s=wQ(r).toSpiceString(),Ya(`Generated SPICE string:
248
+ ${y.message}`):y}}let o=i.nodes.count()-1;for(let a=0;a<i.V.length;a++){let c=i.V[a];c&&(c.index=o+a)}for(let a of i.S){let c=e.get(a.modelName);if(!c)throw new Error(`Unknown .model ${a.modelName} referenced by switch ${a.name}`);a.model=c,a.isOn=!1}for(let a of i.D){let c=t.get(a.modelName);if(!c)throw new Error(`Unknown .model ${a.modelName} referenced by diode ${a.name}`);a.model=c}return i}var rn=class Da{constructor(e=0,t=0){d(this,"re");d(this,"im");this.re=e,this.im=t}static from(e,t=0){return new Da(e,t)}static fromPolar(e,t=0){let i=t*Math.PI/180;return new Da(e*Math.cos(i),e*Math.sin(i))}clone(){return new Da(this.re,this.im)}add(e){return new Da(this.re+e.re,this.im+e.im)}sub(e){return new Da(this.re-e.re,this.im-e.im)}mul(e){return new Da(this.re*e.re-this.im*e.im,this.re*e.im+this.im*e.re)}div(e){let t=e.re*e.re+e.im*e.im;if(t<oi)throw new Error("Complex divide by ~0");return new Da((this.re*e.re+this.im*e.im)/t,(this.im*e.re-this.re*e.im)/t)}inv(){let e=this.re*this.re+this.im*this.im;if(e<oi)throw new Error("Complex invert by ~0");return new Da(this.re/e,-this.im/e)}abs(){return Math.hypot(this.re,this.im)}phaseDeg(){return Math.atan2(this.im,this.re)*180/Math.PI}};function KAt(n,e){let t=n.length;for(let r=0;r<t;r++){let s=n[r],o=e[r];if(!s||!o)throw new Error("Matrix dimensions mismatch");let a=s.map(c=>c.clone());a.push(o.clone()),n[r]=a}for(let r=0;r<t;r++){let s=r,o=n[r];if(!o)throw new Error("Matrix row missing");let a=o[r]?.abs()??0;for(let u=r+1;u<t;u++){let p=n[u];if(!p)throw new Error("Matrix row missing");let f=p[r]?.abs()??0;f>a&&(a=f,s=u)}if(a<oi)throw new Error("Singular matrix (complex)");if(s!==r){let u=n[r];n[r]=n[s],n[s]=u}let c=n[r];if(!c)throw new Error("Pivot row missing");let l=c[r];if(!l)throw new Error("Zero pivot encountered");for(let u=r+1;u<t;u++){let p=n[u];if(!p)throw new Error("Matrix row missing");let f=p[r];if(!f)continue;let y=f.div(l);if(!(y.abs()<oi))for(let g=r;g<=t;g++){let x=p[g],v=c[g];!x||!v||(p[g]=x.sub(y.mul(v)))}}}let i=new Array(t);for(let r=t-1;r>=0;r--){let s=n[r];if(!s)throw new Error("Matrix row missing");let o=s[t];if(!o)throw new Error("Augmented column missing");for(let c=r+1;c<t;c++){let l=s[c],u=i[c];!l||!u||(o=o.sub(l.mul(u)))}let a=s[r];if(!a)throw new Error("Zero pivot on back-substitution");i[r]=o.div(a)}return i}function JAt(n,e,t){if(n<=0||e<=0)throw new Error(".ac frequencies must be > 0");e<n&&([n,e]=[e,n]);let i=Math.log10(e/n),r=Math.max(1,Math.ceil(i*t)),s=[];for(let a=0;a<=r;a++)s.push(n*Math.pow(10,a/t));let o=s[s.length-1];return(o==null||o<e*(1-oi))&&s.push(e),s}function xA(n,e,t,i,r){let s=e.matrixIndexOfNode(t),o=e.matrixIndexOfNode(i);if(s>=0){let a=n[s];if(!a)throw new Error("Matrix row missing while stamping");a[s]=a[s]?.add(r)??r}if(o>=0){let a=n[o];if(!a)throw new Error("Matrix row missing while stamping");a[o]=a[o]?.add(r)??r}if(s>=0&&o>=0){let a=n[s],c=n[o];if(!a||!c)throw new Error("Matrix row missing while stamping");a[o]=a[o]?.sub(r)??rn.from(0,0).sub(r),c[s]=c[s]?.sub(r)??rn.from(0,0).sub(r)}}function QAt(n,e,t,i,r){let s=t.matrixIndexOfNode(i.n1),o=t.matrixIndexOfNode(i.n2),a=i.index,c=rn.from(1,0);if(s>=0){let u=n[s];if(!u)throw new Error("Matrix row missing while stamping voltage source");u[a]=u[a]?.add(c)??c}if(o>=0){let u=n[o];if(!u)throw new Error("Matrix row missing while stamping voltage source");u[a]=u[a]?.sub(c)??rn.from(0,0).sub(c)}let l=n[a];if(!l)throw new Error("Branch row missing while stamping voltage source");s>=0&&(l[s]=l[s]?.add(c)??c),o>=0&&(l[o]=l[o]?.sub(c)??rn.from(0,0).sub(c)),e[a]=(e[a]??rn.from(0,0)).add(r)}function t9t(n){var f,y,g,x;if(!n.analyses.ac)return null;let{mode:e,N:t,f1:i,f2:r}=n.analyses.ac,s=n.nodes.count()-1,o=n.V.length,a=s+o,c=e==="dec"?JAt(i,r,t):(()=>{let v=[],S=Math.max(2,t),P=(r-i)/(S-1);for(let T=0;T<S;T++)v.push(i+T*P);return v})(),l={};n.nodes.rev.forEach((v,S)=>{S!==0&&(l[v]=[])});let u={},p=2*Math.PI;for(let v of c){let S=Array.from({length:a},()=>Array.from({length:a},()=>rn.from(0,0))),P=Array.from({length:a},()=>rn.from(0,0));for(let k of n.R){if(k.R<=0)throw new Error(`R ${k.name} must be > 0`);let C=rn.from(1/k.R,0);xA(S,n.nodes,k.n1,k.n2,C)}for(let k of n.C){let C=rn.from(0,p*v*k.C);xA(S,n.nodes,k.n1,k.n2,C)}for(let k of n.L){let C=rn.from(0,p*v*k.L),E=C.abs()<oi?rn.from(0,0):rn.from(1,0).div(C);xA(S,n.nodes,k.n1,k.n2,E)}for(let k of n.V){let C=rn.fromPolar(k.acMag||0,k.acPhaseDeg||0);QAt(S,P,n.nodes,k,C)}let T=KAt(S,P);for(let k=1;k<n.nodes.count();k++){let C=k-1,E=n.nodes.rev[k];if(!E)continue;let N=l[E];N&&N.push(T[C]??rn.from(0,0))}for(let k of n.R){let C=k.n1===0?rn.from(0,0):T[k.n1-1]??rn.from(0,0),E=k.n2===0?rn.from(0,0):T[k.n2-1]??rn.from(0,0),I=rn.from(1/k.R,0).mul(C.sub(E));(u[f=k.name]||(u[f]=[])).push(I)}for(let k of n.C){let C=k.n1===0?rn.from(0,0):T[k.n1-1]??rn.from(0,0),E=k.n2===0?rn.from(0,0):T[k.n2-1]??rn.from(0,0),I=rn.from(0,p*v*k.C).mul(C.sub(E));(u[y=k.name]||(u[y]=[])).push(I)}for(let k of n.L){let C=k.n1===0?rn.from(0,0):T[k.n1-1]??rn.from(0,0),E=k.n2===0?rn.from(0,0):T[k.n2-1]??rn.from(0,0),N=rn.from(0,p*v*k.L),A=(N.abs()<oi?rn.from(0,0):rn.from(1,0).div(N)).mul(C.sub(E));(u[g=k.name]||(u[g]=[])).push(A)}for(let k of n.V){let C=T[k.index]??rn.from(0,0);(u[x=k.name]||(u[x]=[])).push(C)}}return{freqs:c,nodeVoltages:l,elementCurrents:u}}function e9t(n,e){let t=n.length;for(let r=0;r<t;r++){let s=n[r],o=e[r];if(!s||o==null)throw new Error("Matrix dimensions mismatch");let a=s.slice();a.push(o),n[r]=a}for(let r=0;r<t;r++){let s=r,o=n[r];if(!o)throw new Error("Matrix row missing");let a=Math.abs(o[r]??0);for(let u=r+1;u<t;u++){let p=n[u];if(!p)throw new Error("Matrix row missing");let f=Math.abs(p[r]??0);f>a&&(a=f,s=u)}if(a<oi)throw new Error("Singular matrix (real)");if(s!==r){let u=n[r];n[r]=n[s],n[s]=u}let c=n[r];if(!c)throw new Error("Pivot row missing");let l=c[r];if(l==null)throw new Error("Zero pivot encountered");for(let u=r+1;u<t;u++){let p=n[u];if(!p)throw new Error("Matrix row missing");let f=p[r];if(f==null)continue;let y=f/l;if(!(Math.abs(y)<oi))for(let g=r;g<=t;g++){let x=p[g],v=c[g];x==null||v==null||(p[g]=x-y*v)}}}let i=new Array(t).fill(0);for(let r=t-1;r>=0;r--){let s=n[r];if(!s)throw new Error("Matrix row missing");let o=s[t];if(o==null)throw new Error("Augmented column missing");for(let c=r+1;c<t;c++){let l=s[c],u=i[c];l==null||u==null||(o-=l*u)}let a=s[r];if(a==null)throw new Error("Zero pivot on back-substitution");i[r]=o/a}return i}function w1(n,e,t,i,r){let s=e.matrixIndexOfNode(t),o=e.matrixIndexOfNode(i);if(s>=0){let a=n[s];if(!a)throw new Error("Matrix row missing while stamping");a[s]=(a[s]??0)+r}if(o>=0){let a=n[o];if(!a)throw new Error("Matrix row missing while stamping");a[o]=(a[o]??0)+r}if(s>=0&&o>=0){let a=n[s],c=n[o];if(!a||!c)throw new Error("Matrix row missing while stamping");a[o]=(a[o]??0)-r,c[s]=(c[s]??0)-r}}function bA(n,e,t,i,r){let s=e.matrixIndexOfNode(t),o=e.matrixIndexOfNode(i);s>=0&&(n[s]=(n[s]??0)-r),o>=0&&(n[o]=(n[o]??0)+r)}function n9t(n,e,t,i,r){let s=t.matrixIndexOfNode(i.n1),o=t.matrixIndexOfNode(i.n2),a=i.index;if(s>=0){let l=n[s];if(!l)throw new Error("Matrix row missing while stamping voltage source");l[a]=(l[a]??0)+1}if(o>=0){let l=n[o];if(!l)throw new Error("Matrix row missing while stamping voltage source");l[a]=(l[a]??0)-1}let c=n[a];if(!c)throw new Error("Branch row missing while stamping voltage source");s>=0&&(c[s]=(c[s]??0)+1),o>=0&&(c[o]=(c[o]??0)-1),e[a]=(e[a]??0)+r}function i9t(n){var y,g,x,v,S,P;if(!n.analyses.tran)return null;let{dt:e,tstop:t}=n.analyses.tran,i=e>oi?e:Math.max(t/1e3,oi),r=Math.max(1,Math.ceil(t/Math.max(i,oi))),s=r>0?t/r:t,o=n.nodes.count()-1,a=n.V.length,c=o+a,l=[],u={};n.nodes.rev.forEach((T,k)=>{k!==0&&(u[T]=[])});let p={},f=0;for(let T=0;T<=r;T++,f=T*s){l.push(f);let k=new Array(c).fill(0);for(let C=0;C<20;C++){let E=Array.from({length:c},()=>new Array(c).fill(0)),N=new Array(c).fill(0);for(let R of n.R){let j=1/R.R;w1(E,n.nodes,R.n1,R.n2,j)}for(let R of n.C){let j=R.C/Math.max(s,oi);w1(E,n.nodes,R.n1,R.n2,j);let B=-j*R.vPrev;bA(N,n.nodes,R.n1,R.n2,B)}for(let R of n.L){let j=Math.max(s,oi)/R.L;w1(E,n.nodes,R.n1,R.n2,j),bA(N,n.nodes,R.n1,R.n2,R.iPrev)}for(let R of n.S){let j=R.model;if(!j)continue;let B=R.isOn?j.Ron:j.Roff,U=1/Math.max(Math.abs(B),oi);w1(E,n.nodes,R.n1,R.n2,U)}for(let R of n.V){let j=R.waveform?R.waveform(f):R.dc||0;n9t(E,N,n.nodes,R,j)}let I=.02585;for(let R of n.D){let j=R.model;if(!j)continue;let{nPlus:B,nMinus:G}=R,U=n.nodes.matrixIndexOfNode(B),H=n.nodes.matrixIndexOfNode(G),Q=B===0?0:k[U]??0,tt=G===0?0:k[H]??0,V=Q-tt,ot=C===0?R.vdPrev:V,nt=j.N*I,et=ot;ot>.8&&(et=.8),ot<-1&&(et=-1);let ht=Math.exp(et/nt),dt=j.Is*(ht-1),St=Math.max(j.Is/nt*ht,1e-12),Pt=dt-St*et;w1(E,n.nodes,B,G,St),bA(N,n.nodes,B,G,Pt)}k=e9t(E,N);let A=!1;for(let R of n.S){let j=R.model;if(!j)continue;let B=R.ncPos===0?0:k[R.ncPos-1]??0,G=R.ncNeg===0?0:k[R.ncNeg-1]??0,U=B-G,H=R.isOn;R.isOn?U<j.Voff&&(H=!1):U>j.Von&&(H=!0),H!==R.isOn&&(R.isOn=H,A=!0)}if(!A||C===19)break}for(let C=1;C<n.nodes.count();C++){let E=C-1,N=n.nodes.rev[C];if(!N)continue;let I=u[N];I&&I.push(k[E]??0)}for(let C of n.R){let E=C.n1===0?0:k[C.n1-1]??0,N=C.n2===0?0:k[C.n2-1]??0,I=(E-N)/C.R;(p[y=C.name]||(p[y]=[])).push(I)}for(let C of n.C){let E=C.n1===0?0:k[C.n1-1]??0,N=C.n2===0?0:k[C.n2-1]??0,I=C.C*(E-N-C.vPrev)/Math.max(s,oi);(p[g=C.name]||(p[g]=[])).push(I)}for(let C of n.L){let E=C.n1===0?0:k[C.n1-1]??0,N=C.n2===0?0:k[C.n2-1]??0,A=Math.max(s,oi)/C.L*(E-N)+C.iPrev;(p[x=C.name]||(p[x]=[])).push(A)}for(let C of n.V){let E=k[C.index]??0;(p[v=C.name]||(p[v]=[])).push(E)}for(let C of n.S){let E=C.model;if(!E)continue;let N=C.n1===0?0:k[C.n1-1]??0,I=C.n2===0?0:k[C.n2-1]??0,A=C.isOn?E.Ron:E.Roff,R=Math.max(Math.abs(A),oi),j=(N-I)/R;(p[S=C.name]||(p[S]=[])).push(j)}for(let C of n.D){if(!C.model)continue;let{nPlus:E,nMinus:N,model:I}=C,A=E===0?0:k[E-1]??0,R=N===0?0:k[N-1]??0,j=A-R,G=I.N*.02585,U=Math.exp(j/G),H=I.Is*(U-1);(p[P=C.name]||(p[P]=[])).push(H)}for(let C of n.C){let E=C.n1===0?0:k[C.n1-1]??0,N=C.n2===0?0:k[C.n2-1]??0;C.vPrev=E-N}for(let C of n.L){let E=C.n1===0?0:k[C.n1-1]??0,N=C.n2===0?0:k[C.n2-1]??0,I=Math.max(s,oi)/C.L;C.iPrev=I*(E-N)+C.iPrev}for(let C of n.D){let E=C.nPlus===0?0:k[C.nPlus-1]??0,N=C.nMinus===0?0:k[C.nMinus-1]??0;C.vdPrev=E-N}}if(n.probes.tran.length>0){let T={},k=n.probes.tran.map(C=>C.toUpperCase());for(let C in u)k.includes(C.toUpperCase())&&(T[C]=u[C]);return{times:l,nodeVoltages:T,elementCurrents:p}}return{times:l,nodeVoltages:u,elementCurrents:p}}function SQ(n){let e=ZAt(n),t=t9t(e),i=i9t(e);return{circuit:e,ac:t,tran:i}}function PQ(n,e,t){if(!n||!e.analyses.tran)return[];let{dt:i,tstop:r}=e.analyses.tran,{times:s,nodeVoltages:o}=n,a=[];for(let c in o){let l=o[c];a.push({type:"simulation_transient_voltage_graph",simulation_transient_voltage_graph_id:`stvg_${t}_${c}`,simulation_experiment_id:t,timestamps_ms:s.map(u=>u*1e3),voltage_levels:l,time_per_step:i*1e3,start_time_ms:0,end_time_ms:r*1e3,name:`V(${c})`})}return a}nr();Oe();nr();Oe();Oe();wt();Oe();Oe();ri();Oe();nr();Oe();nr();Oe();Oe();nr();Oe();function kQ(n,e,t,i){return Math.sqrt((t-n)**2+(i-e)**2)}var r9t=n=>{let e=n.filter(s=>s.type==="pcb_port"),t=n.filter(s=>s.type==="pcb_smtpad"),i=n.filter(s=>s.type==="pcb_trace");function r(s,o={}){let a=o.traceWidth||0,c=e.find(l=>kQ(l.x,l.y,s.x,s.y)<.01);if(c)return c.pcb_port_id;if(o.isFirstOrLastPoint){let l=t.find(u=>{if(u.shape==="rect")return Math.abs(s.x-u.x)<u.width/2+a/2&&Math.abs(s.y-u.y)<u.height/2+a/2;if(u.shape==="circle")return kQ(s.x,s.y,u.x,u.y)<u.radius});if(l)return l.pcb_port_id??null}return null}for(let s of i)for(let o=0;o<s.route.length;o++){let a=s.route[o],c=o===0||o===s.route.length-1;if(a.route_type==="wire"){if(!a.start_pcb_port_id&&o===0){let l=r(a,{isFirstOrLastPoint:c,traceWidth:a.width});l&&(a.start_pcb_port_id=l)}if(!a.end_pcb_port_id&&o===s.route.length-1){let l=r(a,{isFirstOrLastPoint:c,traceWidth:a.width});l&&(a.end_pcb_port_id=l)}}}};function EQ(n){r9t(n);let e=n.filter(o=>o.type==="source_trace"),t=n.filter(o=>o.type==="pcb_port"),i=[],r=er(n),s=new Map;for(let o of t)s.set(o.source_port_id,o);for(let o of e){let a=o.connected_source_port_ids;if(a.length<2)continue;let c=[],l=[];for(let g of a){let x=s.get(g);x?c.push(x):l.push(g)}if(c.length<2)continue;let u=c[0],p=r.getNetConnectedToId(u.pcb_port_id);r.getIdsConnectedToNet(p).filter(g=>n.some(x=>x.type==="pcb_trace"&&("pcb_trace_id"in x&&x.pcb_trace_id===g||"route_id"in x&&x.route_id===g))).length===0&&new Set(c.map(x=>x.pcb_component_id)).size>1&&i.push({type:"pcb_port_not_connected_error",message:`pcb_port_not_connected_error: Pcb ports [${c.map(x=>x.pcb_port_id).join(", ")}] are not connected together through the same net.`,error_type:"pcb_port_not_connected_error",pcb_port_ids:c.map(x=>x.pcb_port_id),pcb_component_ids:c.map(x=>x.pcb_component_id),pcb_port_not_connected_error_id:`pcb_port_not_connected_error_trace_${o.source_trace_id}`})}return i}var s9t=class{constructor({objects:n,getBounds:e,getId:t,CELL_SIZE:i}){d(this,"buckets");d(this,"objectsById");d(this,"getBounds");d(this,"getId");d(this,"CELL_SIZE",.4);d(this,"_idCounter",0);this.buckets=new Map,this.objectsById=new Map,this.getBounds=e,this.getId=t??(()=>this._getNextId()),this.CELL_SIZE=i??this.CELL_SIZE;for(let r of n)this.addObject(r)}_getNextId(){return`${this._idCounter++}`}addObject(n){let e=this.getBounds(n),t=this.getId(n),i={...n,spatialIndexId:t};this.objectsById.set(t,i);let r=Math.floor(e.minX/this.CELL_SIZE),s=Math.floor(e.minY/this.CELL_SIZE),o=Math.floor(e.maxX/this.CELL_SIZE),a=Math.floor(e.maxY/this.CELL_SIZE);for(let c=r;c<=o;c++)for(let l=s;l<=a;l++){let u=`${c}x${l}`,p=this.buckets.get(u);p?p.push(i):this.buckets.set(u,[i])}}removeObject(n){let e=this.objectsById.get(n);if(!e)return!1;this.objectsById.delete(n);let t=this.getBounds(e),i=Math.floor(t.minX/this.CELL_SIZE),r=Math.floor(t.minY/this.CELL_SIZE),s=Math.floor(t.maxX/this.CELL_SIZE),o=Math.floor(t.maxY/this.CELL_SIZE);for(let a=i;a<=s;a++)for(let c=r;c<=o;c++){let l=`${a}x${c}`,u=this.buckets.get(l);if(u){let p=u.findIndex(f=>f.spatialIndexId===n);p!==-1&&(u.splice(p,1),u.length===0&&this.buckets.delete(l))}}return!0}getBucketKey(n,e){return`${Math.floor(n/this.CELL_SIZE)}x${Math.floor(e/this.CELL_SIZE)}`}getObjectsInBounds(n,e=0){let t=[],i=new Set,r=Math.floor((n.minX-e)/this.CELL_SIZE),s=Math.floor((n.minY-e)/this.CELL_SIZE),o=Math.floor((n.maxX+e)/this.CELL_SIZE),a=Math.floor((n.maxY+e)/this.CELL_SIZE);for(let c=r;c<=o;c++)for(let l=s;l<=a;l++){let u=`${c}x${l}`,p=this.buckets.get(u)||[];for(let f of p){let y=f.spatialIndexId;i.has(y)||(i.add(y),t.push(f))}}return t}},S1=n=>n.type==="pcb_trace_segment"?{minX:Math.min(n.x1,n.x2),minY:Math.min(n.y1,n.y2),maxX:Math.max(n.x1,n.x2),maxY:Math.max(n.y1,n.y2)}:r_([n]),vA=.1,o9t=.15;var a9t=.2,c9t=.3,P1=.005;function l9t(n){let e=new Set;for(let t of n.route)t.route_type==="wire"&&(t.start_pcb_port_id&&e.add(t.start_pcb_port_id),t.end_pcb_port_id&&e.add(t.end_pcb_port_id));return Array.from(e)}function wA(n){let e=new Set;for(let t of n)for(let i of l9t(t))e.add(i);return Array.from(e)}var u9t=(n,e)=>{let t={x:n.x1,y:n.y1},i={x:n.x2,y:n.y2},r={x:e.x1,y:e.y1},s={x:e.x2,y:e.y2},o={x:i.x-t.x,y:i.y-t.y},a={x:s.x-r.x,y:s.y-r.y},c=o.x*o.x+o.y*o.y,l=a.x*a.x+a.y*a.y;if(c===0||l===0){if(c===0&&l===0)return{x:(t.x+r.x)/2,y:(t.y+r.y)/2};if(c===0){let j=Uo(((t.x-r.x)*a.x+(t.y-r.y)*a.y)/l,0,1),B={x:r.x+j*a.x,y:r.y+j*a.y};return{x:(t.x+B.x)/2,y:(t.y+B.y)/2}}let A=Uo(((r.x-t.x)*o.x+(r.y-t.y)*o.y)/c,0,1),R={x:t.x+A*o.x,y:t.y+A*o.y};return{x:(R.x+r.x)/2,y:(R.y+r.y)/2}}let u={x:t.x-r.x,y:t.y-r.y},p=o.x*o.x+o.y*o.y,f=o.x*a.x+o.y*a.y,y=o.x*u.x+o.y*u.y,g=a.x*a.x+a.y*a.y,x=a.x*u.x+a.y*u.y,v=p*g-f*f;if(v<1e-10)return p9t(t,i,r,s,o,a,c,l);let S=(f*x-g*y)/v,P=(p*x-f*y)/v;S=Uo(S,0,1),P=Uo(P,0,1),P=(S*f+x)/g,P=Uo(P,0,1),S=(P*f-y)/p,S=Uo(S,0,1);let T={x:t.x+S*o.x,y:t.y+S*o.y},k={x:r.x+P*a.x,y:r.y+P*a.y},C=T.x-k.x,E=T.y-k.y,N=Math.sqrt(C*C+E*E);return{x:(T.x+k.x)/2,y:(T.y+k.y)/2}},p9t=(n,e,t,i,r,s,o,a)=>{let c=((t.x-n.x)*r.x+(t.y-n.y)*r.y)/o;c=Uo(c,0,1);let l={x:n.x+c*r.x,y:n.y+c*r.y},u=((i.x-n.x)*r.x+(i.y-n.y)*r.y)/o;u=Uo(u,0,1);let p={x:n.x+u*r.x,y:n.y+u*r.y},f=((n.x-t.x)*s.x+(n.y-t.y)*s.y)/a;f=Uo(f,0,1);let y={x:t.x+f*s.x,y:t.y+f*s.y},g=((e.x-t.x)*s.x+(e.y-t.y)*s.y)/a;g=Uo(g,0,1);let x={x:t.x+g*s.x,y:t.y+g*s.y},S=[{pointA:l,pointB:t,distance:Math.sqrt((l.x-t.x)**2+(l.y-t.y)**2)},{pointA:p,pointB:i,distance:Math.sqrt((p.x-i.x)**2+(p.y-i.y)**2)},{pointA:n,pointB:y,distance:Math.sqrt((n.x-y.x)**2+(n.y-y.y)**2)},{pointA:e,pointB:x,distance:Math.sqrt((e.x-x.x)**2+(e.y-x.y)**2)}].reduce((P,T)=>T.distance<P.distance?T:P);return{x:(S.pointA.x+S.pointB.x)/2,y:(S.pointA.y+S.pointB.y)/2}},Uo=(n,e,t)=>Math.max(e,Math.min(t,n)),h9t=n=>{if(n.type==="pcb_via"||n.type==="pcb_plated_hole"&&n.shape==="circle")return n.outer_diameter/2;if(n.type==="pcb_hole"&&n.hole_shape==="circle")return n.hole_diameter/2;if(n.type==="pcb_smtpad"&&n.shape==="circle")return n.radius;throw new Error(`Could not determine radius of element: ${JSON.stringify(n)}`)},TQ=(n,e)=>{let t={x:n.x1,y:n.y1},i={x:n.x2,y:n.y2},r=e.minX,s=e.minY,o=e.maxX,a=e.maxY;if(t.x===i.x&&t.y===i.y){let I=Math.max(r,Math.min(o,t.x)),A=Math.max(s,Math.min(a,t.y));return I===t.x&&A===t.y?{x:t.x,y:t.y}:{x:I,y:A}}let c=i.x-t.x,l=i.y-t.y,u=c!==0?(r-t.x)/c:Number.NEGATIVE_INFINITY,p=c!==0?(o-t.x)/c:Number.POSITIVE_INFINITY,f=l!==0?(s-t.y)/l:Number.NEGATIVE_INFINITY,y=l!==0?(a-t.y)/l:Number.POSITIVE_INFINITY,g=Math.max(Math.min(u,p),Math.min(f,y)),x=Math.min(Math.max(u,p),Math.max(f,y));if(g<=x&&x>=0&&g<=1){let I=Math.max(0,Math.min(1,g));return{x:t.x+I*c,y:t.y+I*l}}let v={x:Math.max(r,Math.min(o,t.x)),y:Math.max(s,Math.min(a,t.y))},S={x:Math.max(r,Math.min(o,i.x)),y:Math.max(s,Math.min(a,i.y))},P=(v.x-t.x)**2+(v.y-t.y)**2,T=(S.x-i.x)**2+(S.y-i.y)**2,k=[{start:{x:r,y:s},end:{x:o,y:s}},{start:{x:o,y:s},end:{x:o,y:a}},{start:{x:o,y:a},end:{x:r,y:a}},{start:{x:r,y:a},end:{x:r,y:s}}],C=Math.min(P,T),E=P<=T?v:S,N=(I,A,R)=>Math.max(A,Math.min(R,I));for(let I of k){let A={x:i.x-t.x,y:i.y-t.y},R={x:I.end.x-I.start.x,y:I.end.y-I.start.y},j={x:t.x-I.start.x,y:t.y-I.start.y},B=A.x*A.x+A.y*A.y,G=A.x*R.x+A.y*R.y,U=A.x*j.x+A.y*j.y,H=R.x*R.x+R.y*R.y,Q=R.x*j.x+R.y*j.y,tt=B*H-G*G;if(Math.abs(tt)<1e-10)continue;let V=(G*Q-H*U)/tt,ot=(B*Q-G*U)/tt;V=N(V,0,1),ot=N(ot,0,1);let nt={x:t.x+V*A.x,y:t.y+V*A.y},et={x:I.start.x+ot*R.x,y:I.start.y+ot*R.y},ht=nt.x-et.x,dt=nt.y-et.y,St=ht*ht+dt*dt;St<C&&(C=St,E={x:(nt.x+et.x)/2,y:(nt.y+et.y)/2})}return E};function d9t(n){return n.type==="pcb_trace_segment"?[n.layer]:n.type==="pcb_smtpad"?[n.layer]:n.type==="pcb_plated_hole"?Array.isArray(n.layers)?n.layers:[...Im]:n.type==="pcb_hole"?[...Im]:n.type==="pcb_via"?Array.isArray(n.layers)?n.layers:[...Im]:n.type==="pcb_keepout"?Array.isArray(n.layers)?n.layers:[]:[]}function MQ(n,{connMap:e}={}){let t=[];e??(e=er(n));let r=Ke(n).pcb_trace.list().flatMap(g=>{let x=[];for(let v=0;v<g.route.length-1;v++){let S=g.route[v],P=g.route[v+1];S.route_type==="wire"&&P.route_type==="wire"&&S.layer===P.layer&&x.push({type:"pcb_trace_segment",pcb_trace_id:g.pcb_trace_id,_pcbTrace:g,thickness:"width"in S?S.width:"width"in P?P.width:o9t,layer:S.layer,x1:S.x,y1:S.y,x2:P.x,y2:P.y})}return x}),s=Ke(n).pcb_smtpad.list(),o=Ke(n).pcb_plated_hole.list(),a=Ke(n).pcb_hole.list(),c=Ke(n).pcb_via.list(),l=Ke(n).pcb_keepout.list(),u=[...r,...s,...o,...a,...c,...l],p=new s9t({objects:u,getBounds:S1}),f=g=>Is(n,g),y=new Set;for(let g of r){let x=vA,v=S1(g),S=p.getObjectsInBounds(v,x+g.thickness/2);if(!(g.x1===g.x2&&g.y1===g.y2))for(let P of S){if(!d9t(P).includes(g.layer))continue;if(P.type==="pcb_trace_segment"){let E=P;if(g.layer!==E.layer||e.areIdsConnected(g.pcb_trace_id,E.pcb_trace_id))continue;let N=n_({x:g.x1,y:g.y1},{x:g.x2,y:g.y2},{x:E.x1,y:E.y1},{x:E.x2,y:E.y2})-g.thickness/2-E.thickness/2;if(N>vA-P1)continue;let I=`overlap_${g.pcb_trace_id}_${E.pcb_trace_id}`,A=`overlap_${E.pcb_trace_id}_${g.pcb_trace_id}`;if(y.has(I)||y.has(A))continue;y.add(I),t.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${f(g.pcb_trace_id)} overlaps with ${f(E.pcb_trace_id)} ${N<0?"(accidental contact)":`(gap: ${N.toFixed(3)}mm)`}`,pcb_trace_id:g.pcb_trace_id,source_trace_id:"",pcb_trace_error_id:I,pcb_component_ids:[],center:u9t(g,E),pcb_port_ids:wA([g._pcbTrace,E._pcbTrace])});continue}let T=Oo(P);if(e.areIdsConnected(g.pcb_trace_id,"pcb_trace_id"in P?P.pcb_trace_id:T))continue;if(P.type==="pcb_via"||P.type==="pcb_plated_hole"&&P.shape==="circle"||P.type==="pcb_hole"||P.type==="pcb_smtpad"&&P.shape==="circle"){let E=h9t(P),I=gw({x:g.x1,y:g.y1},{x:g.x2,y:g.y2},{x:P.x,y:P.y,radius:E})-g.thickness/2;if(I>vA-P1)continue;let A=`overlap_${g.pcb_trace_id}_${T}`;if(y.has(A))continue;y.add(A),t.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${f(g.pcb_trace_id)} overlaps with ${P.type} "${f(Oo(P))}" ${I<0?"(accidental contact)":`(gap: ${I.toFixed(3)}mm)`}`,pcb_trace_id:g.pcb_trace_id,center:TQ(g,S1(P)),source_trace_id:"",pcb_trace_error_id:A,pcb_component_ids:["pcb_component_id"in P?P.pcb_component_id:void 0].filter(Boolean),pcb_port_ids:[...wA([g._pcbTrace]),"pcb_port_id"in P?P.pcb_port_id:void 0].filter(Boolean)})}let C=Cg({x:g.x1,y:g.y1},{x:g.x2,y:g.y2},S1(P))-g.thickness/2;if(C+P1<x){let E=`overlap_${g.pcb_trace_id}_${T}`;if(y.has(E))continue;y.add(E),t.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${f(g.pcb_trace_id)} overlaps with ${P.type} "${f(Oo(P))}" ${C<0?"(accidental contact)":`(gap: ${C.toFixed(3)}mm)`}`,pcb_trace_id:g.pcb_trace_id,source_trace_id:"",pcb_trace_error_id:E,pcb_component_ids:["pcb_component_id"in P?P.pcb_component_id:void 0].filter(Boolean),center:TQ(g,S1(P)),pcb_port_ids:[...wA([g._pcbTrace]),"pcb_port_id"in P?P.pcb_port_id:void 0].filter(Boolean)})}}}return t}function CQ(n){return n.area()>=0}function IQ({center:n,size:e,rotationDeg:t=0}){let i=n.x,r=n.y,s=e.width/2,o=e.height/2,a=[new Xo(i-s,r-o),new Xo(i+s,r-o),new Xo(i+s,r+o),new Xo(i-s,r+o)],c=new m1(a);if(t){let l=nw(t,i,r),u=a.map(p=>{let f=oe(l,{x:p.x,y:p.y});return new Xo(f.x,f.y)});c=new m1(u)}return CQ(c)||c.reverse(),c}function f9t({board:n}){if(n.outline&&n.outline.length>0){let e=n.outline.map(i=>new Xo(i.x,i.y)),t=new m1(e);return CQ(t)||t.reverse(),t}return n.center&&typeof n.width=="number"&&typeof n.height=="number"?IQ({center:n.center,size:{width:n.width,height:n.height},rotationDeg:0}):null}function m9t({circuitJson:n,component:e}){if(e.source_component_id){let t=n.find(i=>i.type==="source_component"&&i.source_component_id===e.source_component_id);if(t&&"name"in t&&t.name)return t.name}return Is(n,e.pcb_component_id)||"Unknown"}function _9t(n,e,t,i,r,s){let o=new Xo(t.x,t.y);if(!e.contains(o)){let x=e.distanceTo(o);return Array.isArray(x)?x[0]:Number(x)||0}let a=i/2,c=r/2,l=[{x:t.x-a,y:t.y-c},{x:t.x+a,y:t.y-c},{x:t.x+a,y:t.y+c},{x:t.x-a,y:t.y+c}],u=[];for(let x=0;x<4;x++){let v=(x+1)%4;u.push({x:(l[x].x+l[v].x)/2,y:(l[x].y+l[v].y)/2})}let p=nw(s,t.x,t.y),f=x=>{let v=oe(p,x);return new Xo(v.x,v.y)},y=l.concat(u).map(f),g=0;for(let x of y)if(!e.contains(x)){let v=e.distanceTo(x),S=Array.isArray(v)?v[0]:Number(v)||0;S>g&&(g=S)}if(g>0)return g;try{let x=WN.intersect(n,e),v=0;x?Array.isArray(x)?v=x.reduce((P,T)=>P+(typeof T.area=="function"?T.area():0),0):typeof x.area=="function"?v=x.area():v=0:v=0;let S=n.area();if(v>0&&v<S){let P=1-v/S,T=Math.abs(i),k=Math.abs(r);return Math.min(T,k)*P}else return .1}catch{return .1}}function NQ(n){let e=n.find(s=>s.type==="pcb_board");if(!e)return[];let t=f9t({board:e});if(!t)return[];let i=n.filter(s=>s.type==="pcb_component");if(i.length===0)return[];let r=[];for(let s of i){if(!s.center||typeof s.width!="number"||typeof s.height!="number"||s.width<=0||s.height<=0)continue;let o=IQ({center:s.center,size:{width:s.width,height:s.height},rotationDeg:s.rotation||0});if(o.area()===0||t.contains(o))continue;let c=_9t(o,t,s.center,s.width,s.height,s.rotation||0),l=m9t({circuitJson:n,component:s}),u=Math.round(c*100)/100;r.push({type:"pcb_component_outside_board_error",error_type:"pcb_component_outside_board_error",pcb_component_outside_board_error_id:`pcb_component_outside_board_${s.pcb_component_id}`,message:`Component ${l} (${s.pcb_component_id}) extends outside board boundaries by ${u}mm`,pcb_component_id:s.pcb_component_id,pcb_board_id:e.pcb_board_id,component_center:s.center,component_bounds:{min_x:o.box.xmin,max_x:o.box.xmax,min_y:o.box.ymin,max_y:o.box.ymax},subcircuit_id:s.subcircuit_id,source_component_id:s.source_component_id})}return r}function y9t(n,e){return Math.hypot(n.x-e.x,n.y-e.y)}function AQ(n,{connMap:e,minSpacing:t=a9t}={}){let i=n.filter(o=>o.type==="pcb_via");if(i.length<2)return[];e??(e=er(n));let r=[],s=new Set;for(let o=0;o<i.length;o++)for(let a=o+1;a<i.length;a++){let c=i[o],l=i[a];if(!e.areIdsConnected(c.pcb_via_id,l.pcb_via_id))continue;let u=y9t(c,l)-c.outer_diameter/2-l.outer_diameter/2;if(u+P1>=t)continue;let p=[c.pcb_via_id,l.pcb_via_id].sort().join("_");s.has(p)||(s.add(p),r.push({type:"pcb_via_clearance_error",pcb_error_id:`same_net_vias_close_${p}`,message:`Vias ${Is(n,c.pcb_via_id)} and ${Is(n,l.pcb_via_id)} are too close together (gap: ${u.toFixed(3)}mm)`,error_type:"pcb_via_clearance_error",pcb_via_ids:[c.pcb_via_id,l.pcb_via_id],minimum_clearance:t,actual_clearance:u,pcb_center:{x:(c.x+l.x)/2,y:(c.y+l.y)/2}}))}return r}function g9t(n,e){return Math.hypot(n.x-e.x,n.y-e.y)}function RQ(n,{connMap:e,minSpacing:t=c9t}={}){let i=n.filter(o=>o.type==="pcb_via");if(i.length<2)return[];e??(e=er(n));let r=[],s=new Set;for(let o=0;o<i.length;o++)for(let a=o+1;a<i.length;a++){let c=i[o],l=i[a];if(e.areIdsConnected(c.pcb_via_id,l.pcb_via_id))continue;let u=g9t(c,l)-c.outer_diameter/2-l.outer_diameter/2;if(u+P1>=t)continue;let p=[c.pcb_via_id,l.pcb_via_id].sort().join("_");s.has(p)||(s.add(p),r.push({type:"pcb_via_clearance_error",pcb_error_id:`different_net_vias_close_${p}`,message:`Vias ${Is(n,c.pcb_via_id)} and ${Is(n,l.pcb_via_id)} from different nets are too close together (gap: ${u.toFixed(3)}mm)`,error_type:"pcb_via_clearance_error",pcb_via_ids:[c.pcb_via_id,l.pcb_via_id],minimum_clearance:t,actual_clearance:u,pcb_center:{x:(c.x+l.x)/2,y:(c.y+l.y)/2}}))}return r}var x9t=.2;function b9t(n){if(n.outline&&n.outline.length>0)return n.outline.map(e=>({x:e.x,y:e.y}));if(n.center&&typeof n.width=="number"&&typeof n.height=="number"){let e=n.center.x,t=n.center.y,i=n.width/2,r=n.height/2;return[{x:e-i,y:t-r},{x:e+i,y:t-r},{x:e+i,y:t+r},{x:e-i,y:t+r}]}return null}function OQ(n,e={}){let t=[],i=e.margin??x9t,r=n.find(a=>a.type==="pcb_board");if(!r)return t;let s=b9t(r);if(!s)return t;let o=Ke(n).pcb_trace.list();for(let a of o)if(!(a.route.length<2))for(let c=0;c<a.route.length-1;c++){let l=a.route[c],u=a.route[c+1];if(l.route_type!=="wire"||u.route_type!=="wire")continue;let p="width"in l?l.width:"width"in u?u.width:.1,f={x:l.x,y:l.y},y={x:u.x,y:u.y},g=1/0;for(let v=0;v<s.length;v++){let S=s[v],P=s[(v+1)%s.length],T=n_(f,y,S,P);T<g&&(g=T)}let x=p/2+i;if(g<x){let v={type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:`trace_too_close_to_board_${a.pcb_trace_id}_segment_${c}`,message:`Trace too close to board edge (${g.toFixed(3)}mm < ${x.toFixed(3)}mm required, margin: ${i}mm)`,pcb_trace_id:a.pcb_trace_id,source_trace_id:a.source_trace_id||"",center:{x:(f.x+y.x)/2,y:(f.y+y.y)/2},pcb_component_ids:[],pcb_port_ids:[]};t.push(v)}}return t}function v9t(n,e){let t=r_([n]),i=r_([e]);return Hc(t,i)}function LQ(n){let e=[],t=er(n),i=Ke(n).pcb_smtpad.list(),r=Ke(n).pcb_plated_hole.list(),s=Ke(n).pcb_hole.list(),o=new Map;for(let c of i){let l=c.pcb_component_id||`standalone_pad_${Oo(c)}`;o.has(l)||o.set(l,{component_id:l,elements:[],bounds:{minX:0,minY:0,maxX:0,maxY:0}}),o.get(l).elements.push(c)}for(let c of r){let l=c.pcb_component_id||`standalone_plated_hole_${Oo(c)}`;o.has(l)||o.set(l,{component_id:l,elements:[],bounds:{minX:0,minY:0,maxX:0,maxY:0}}),o.get(l).elements.push(c)}for(let c of s){let l=`standalone_hole_${Oo(c)}`;o.set(l,{component_id:l,elements:[c],bounds:{minX:0,minY:0,maxX:0,maxY:0}})}for(let[c,l]of o)l.elements.length>0&&(l.bounds=r_(l.elements));let a=Array.from(o.values());for(let c=0;c<a.length;c++)for(let l=c+1;l<a.length;l++){let u=a[c],p=a[l];if(Hc(u.bounds,p.bounds))for(let f of u.elements)for(let y of p.elements){let g=Oo(f),x=Oo(y);if(!(f.type==="pcb_smtpad"&&y.type==="pcb_smtpad"&&t.areIdsConnected(g,x))&&v9t(f,y)){let v={type:"pcb_footprint_overlap_error",pcb_error_id:`pcb_footprint_overlap_${g}_${x}`,error_type:"pcb_footprint_overlap_error",message:`PCB component ${f.type} "${g}" overlaps with ${y.type} "${x}"`};(f.type==="pcb_smtpad"||y.type==="pcb_smtpad")&&(v.pcb_smtpad_ids=[],f.type==="pcb_smtpad"&&v.pcb_smtpad_ids.push(g),y.type==="pcb_smtpad"&&v.pcb_smtpad_ids.push(x)),(f.type==="pcb_plated_hole"||y.type==="pcb_plated_hole")&&(v.pcb_plated_hole_ids=[],f.type==="pcb_plated_hole"&&v.pcb_plated_hole_ids.push(g),y.type==="pcb_plated_hole"&&v.pcb_plated_hole_ids.push(x)),(f.type==="pcb_hole"||y.type==="pcb_hole")&&(v.pcb_hole_ids=[],f.type==="pcb_hole"&&v.pcb_hole_ids.push(g),y.type==="pcb_hole"&&v.pcb_hole_ids.push(x)),e.push(v)}}}return e}wt();var SA=[{value:1e12,symbol:"T"},{value:1e9,symbol:"G"},{value:1e6,symbol:"M"},{value:1e3,symbol:"k"},{value:1,symbol:""},{value:.001,symbol:"m"},{value:1e-6,symbol:"\xB5"},{value:1e-9,symbol:"n"},{value:1e-12,symbol:"p"}];function gi(n){if(n==null)return"";if(n===0)return"0";let e=Math.abs(n),t=SA.find(s=>{let o=e/s.value;return o>=1&&o<1e3})||SA[SA.length-1],r=(n/t.value).toPrecision(3);return r.includes(".")&&!/\.0+$/.test(r)&&(r=r.replace(/0+$/,"")),r=r.replace(/\.0+$/,""),`${r}${t.symbol}`}wt();wt();J();Oe();Ig();var w9t=class{constructor(){d(this,"MAX_ITERATIONS",1e5);d(this,"solved",!1);d(this,"failed",!1);d(this,"iterations",0);d(this,"progress",0);d(this,"error",null);d(this,"activeSubSolver");d(this,"failedSubSolvers");d(this,"timeToSolve");d(this,"stats",{});d(this,"_setupDone",!1)}setup(){this._setupDone||(this._setup(),this._setupDone=!0)}_setup(){}step(){if(this._setupDone||this.setup(),!this.solved&&!this.failed){this.iterations++;try{this._step()}catch(n){throw this.error=`${this.constructor.name} error: ${n}`,console.error(this.error),this.failed=!0,n}!this.solved&&this.iterations>=this.MAX_ITERATIONS&&this.tryFinalAcceptance(),!this.solved&&this.iterations>=this.MAX_ITERATIONS&&(this.error=`${this.constructor.name} ran out of iterations`,console.error(this.error),this.failed=!0),"computeProgress"in this&&(this.progress=this.computeProgress())}}_step(){}getConstructorParams(){throw new Error("getConstructorParams not implemented")}getOutput(){return null}solve(){let n=Date.now();for(;!this.solved&&!this.failed;)this.step();let e=Date.now();this.timeToSolve=e-n}visualize(){return{lines:[],points:[],rects:[],circles:[]}}tryFinalAcceptance(){}preview(){return{lines:[],points:[],rects:[],circles:[]}}};var FQ=class extends w9t{constructor(e){super();d(this,"startTimeOfPhase",{});d(this,"endTimeOfPhase",{});d(this,"timeSpentOnPhase",{});d(this,"firstIterationOfPhase",{});d(this,"currentPipelineStepIndex",0);d(this,"inputProblem");d(this,"pipelineOutputs",{});this.inputProblem=e,this.MAX_ITERATIONS=1e6}_step(){let e=this.pipelineDef[this.currentPipelineStepIndex];if(!e){this.solved=!0;return}if(this.activeSubSolver){if(this.activeSubSolver.step(),this.activeSubSolver.solved){this.endTimeOfPhase[e.solverName]=performance.now(),this.timeSpentOnPhase[e.solverName]=this.endTimeOfPhase[e.solverName]-this.startTimeOfPhase[e.solverName];let i=this.activeSubSolver.getOutput();i!==null&&(this.pipelineOutputs[e.solverName]=i),e.onSolved?.(this),this.activeSubSolver=null,this.currentPipelineStepIndex++}else this.activeSubSolver.failed&&(this.error=this.activeSubSolver?.error,this.failed=!0,this.activeSubSolver=null);return}let t=e.getConstructorParams(this);this.activeSubSolver=new e.solverClass(...t),this[e.solverName]=this.activeSubSolver,this.timeSpentOnPhase[e.solverName]=0,this.startTimeOfPhase[e.solverName]=performance.now(),this.firstIterationOfPhase[e.solverName]=this.iterations}solveUntilPhase(e){for(;this.getCurrentPhase().toLowerCase()!==e.toLowerCase()&&(this.step(),!(this.failed||this.solved)););}getCurrentPhase(){return this.pipelineDef[this.currentPipelineStepIndex]?.solverName??"none"}getPhaseProgress(){let e=this.pipelineDef.length;if(e===0)return 1;let t=this.activeSubSolver?.progress??0;return(this.currentPipelineStepIndex+t)/e}getPhaseStats(){let e={};for(let t of this.pipelineDef){let i=this.timeSpentOnPhase[t.solverName]||0,r=this.firstIterationOfPhase[t.solverName]||0,s=this.iterations,o=t.solverName===this.getCurrentPhase()?s-r:0,a=this.currentPipelineStepIndex>this.pipelineDef.findIndex(c=>c.solverName===t.solverName);e[t.solverName]={timeSpent:i,iterations:o,completed:a}}return e}visualize(){if(!this.solved&&this.activeSubSolver)return this.activeSubSolver.visualize();let e=this.pipelineDef.map((t,i)=>{let s=this[t.solverName]?.visualize();if(!s)return null;for(let o of s.rects??[])o.step=i;for(let o of s.points??[])o.step=i;for(let o of s.circles??[])o.step=i;for(let o of s.texts??[])o.step=i;for(let o of s.lines??[])o.step=i;return s}).filter(Boolean);return e.length===0?{points:[],rects:[],lines:[],circles:[],texts:[]}:e.length===1?e[0]:{points:e.flatMap(t=>t.points||[]),rects:e.flatMap(t=>t.rects||[]),lines:e.flatMap(t=>t.lines||[]),circles:e.flatMap(t=>t.circles||[]),texts:e.flatMap(t=>t.texts||[])}}preview(){return this.activeSubSolver?this.activeSubSolver.preview():super.preview()}computeProgress(){return this.getPhaseProgress()}getStepOutput(e){return this.pipelineOutputs[e]}getAllOutputs(){return{...this.pipelineOutputs}}hasStepOutput(e){return e in this.pipelineOutputs}getSolver(e){return this[e]}};var S9t=n=>{let e=n.board_edge_margin??0;if(n.outline&&n.outline.length>0){let r=new L.Polygon(n.outline.map(s=>L.point(s.x,s.y)));return r.orientation()===L.ORIENTATION.CW&&r.reverse(),r}let{bounds:t}=n,i={minX:t.minX+e,minY:t.minY+e,maxX:t.maxX-e,maxY:t.maxY-e};return i.minX>=i.maxX||i.minY>=i.maxY?new L.Polygon:new L.Polygon(new L.Box(i.minX,i.minY,i.maxX,i.maxY).toPoints())},PA=(n,e=32)=>{let t=[];for(let i=0;i<e;i++){let r=i/e*2*Math.PI;t.push(new L.Point(n.center.x+n.r*Math.cos(r),n.center.y+n.r*Math.sin(r)))}return new L.Polygon(t)},P9t=n=>n.shape==="rect",k9t=n=>n.shape==="trace",T9t=n=>n.shape==="circle",E9t=n=>n.shape==="polygon",M9t=(n,e,t,i)=>{let r=[],{padMargin:s,traceMargin:o,board_edge_margin:a,cutoutMargin:c}=t;if(i&&i.length>0&&a&&a>0){let l=new L.Polygon(i.map(p=>L.point(p.x,p.y)));l.area()<0&&l.reverse();let u=l.vertices;for(let p=0;p<u.length;p++){let f=u[p===0?u.length-1:p-1],y=u[p],g=u[(p+1)%u.length];if(!f||!y||!g)continue;let x=new L.Vector(f,y),v=new L.Vector(y,g),S=x.cross(v),P=new L.Circle(y,a);if(r.push(PA(P)),S<0){let T=new L.Box(y.x-a,y.y-a,y.x+a,y.y+a);r.push(new L.Polygon(T.toPoints()))}}for(let p=0;p<u.length;p++){let f=u[p],y=u[(p+1)%u.length];if(!f||!y)continue;let g=Math.hypot(f.x-y.x,f.y-y.y);if(g===0)continue;let x=a*2,v=(f.x+y.x)/2,S=(f.y+y.y)/2,P=Math.atan2(y.y-f.y,y.x-f.x)*180/Math.PI,T=g/2,k=x/2,C=P*Math.PI/180,E=Math.cos(C),N=Math.sin(C),A=[{x:-T,y:-k},{x:T,y:-k},{x:T,y:k},{x:-T,y:k}].map(R=>({x:v+R.x*E-R.y*N,y:S+R.x*N+R.y*E}));r.push(new L.Polygon(A.map(R=>L.point(R.x,R.y))))}}for(let l of n){if(l.connectivityKey===e)continue;let p=l.connectivityKey.startsWith("hole:")||l.connectivityKey.startsWith("cutout:");if(T9t(l)){let f=p?c??0:s,y=new L.Circle(new L.Point(l.x,l.y),l.radius+f);r.push(PA(y));continue}if(P9t(l)){let f=p?c??0:s,{bounds:y}=l,g=new L.Box(y.minX-f,y.minY-f,y.maxX+f,y.maxY+f);r.push(new L.Polygon(g.toPoints()));continue}if(E9t(l)){let f=p?c??0:0,y=new Set,g=l.points.filter(T=>{let k=`${T.x},${T.y}`;return y.has(k)?!1:(y.add(k),!0)});if(g.length<3)continue;let x=new L.Polygon(g.map(T=>L.point(T.x,T.y)));if(Math.abs(x.area())<1e-9)continue;if(f<=0){r.push(x);continue}x.area()>0&&x.reverse();let v=[],S=x.vertices;for(let T=0;T<S.length;T++){let k=S[T],C=S[(T+1)%S.length],E=L.segment(k,C);if(E.length===0)continue;let N=L.line(E.start,E.end),I=N.norm,A=N.translate(I.multiply(-f));v.push(A)}let P=[];for(let T=0;T<v.length;T++){let k=v[T],C=v[(T+1)%v.length],E=k.intersect(C);E.length>0&&P.push(E[0])}P.length>=3&&r.push(new L.Polygon(P));continue}if(k9t(l)){for(let f of l.segments){let y=new L.Circle(new L.Point(f.x,f.y),l.width/2+o);r.push(PA(y))}for(let f=0;f<l.segments.length-1;f++){let y=l.segments[f],g=l.segments[f+1];if(!y||!g)continue;let x=Math.hypot(y.x-g.x,y.y-g.y);if(x===0)continue;let v=l.width+o*2,S=(y.x+g.x)/2,P=(y.y+g.y)/2,T=Math.atan2(g.y-y.y,g.x-y.x)*180/Math.PI,k=x/2,C=v/2,E=T*Math.PI/180,N=Math.cos(E),I=Math.sin(E),R=[{x:-k,y:-C},{x:k,y:-C},{x:k,y:C},{x:-k,y:C}].map(j=>({x:S+j.x*N-j.y*I,y:P+j.x*I+j.y*N}));r.push(new L.Polygon(R.map(j=>L.point(j.x,j.y))))}continue}}return{polygonsToSubtract:r}},zQ=n=>n.edges.map(e=>{let t={x:e.start.x,y:e.start.y};if(e.isArc){let i=Math.tan(e.shape.sweep/4);Math.abs(i)>1e-9&&(t.bulge=i)}return t}),C9t=n=>{let e=[],t=Array.isArray(n)?n:[n];for(let i of t){let r=i.splitToIslands();for(let s of r){if(s.isEmpty())continue;let o=[...s.faces],a=o.find(p=>p.orientation()===L.ORIENTATION.CCW),c=o.filter(p=>p.orientation()===L.ORIENTATION.CW);if(!a)continue;a.reverse();let l=zQ(a),u=c.map(p=>(p.reverse(),{vertices:zQ(p)}));e.push({outer_ring:{vertices:l},inner_rings:u})}}return e},DQ=class extends FQ{constructor(e){super(e);d(this,"pipelineDef",[]);this.input=e}getOutput(){let e=[];for(let t of this.input.regionsForPour){let i=S9t(t),r=this.input.pads.filter(c=>c.layer===t.layer),{polygonsToSubtract:s}=M9t(r,t.connectivityKey,{padMargin:t.padMargin,traceMargin:t.traceMargin,board_edge_margin:t.board_edge_margin,cutoutMargin:t.cutout_margin},t.outline),o=i;for(let c of s){let l=Array.isArray(o)?o:[o],u=[];for(let p of l){let f=L.BooleanOperations.subtract(p,c);f&&(Array.isArray(f)?u.push(...f.filter(y=>!y.isEmpty())):f.isEmpty()||u.push(f))}o=u}let a=C9t(o);e.push(...a)}return{brep_shapes:e}}},$Q=(n,e)=>{let t=n.filter(T=>T.type==="source_port"),i=n.filter(T=>T.type==="pcb_port"),r=n.filter(T=>T.type==="source_trace"),s=n.filter(T=>T.type==="pcb_trace"),o=n.filter(T=>T.type==="source_net"),a=n.find(T=>T.type==="pcb_board");if(!a)throw new Error("No pcb_board found in circuit json");let c=Object.fromEntries(t.map(T=>[T.source_port_id,T.subcircuit_connectivity_map_key])),l=Object.fromEntries(i.map(T=>[T.pcb_port_id,c[T.source_port_id]])),u={};for(let T of i)T.pcb_port_id&&(u[T.pcb_port_id]=l[T.pcb_port_id]);let p=Object.fromEntries(r.map(T=>[T.source_trace_id,T.subcircuit_connectivity_map_key])),f=Object.fromEntries(o.map(T=>[T.source_net_id,T.subcircuit_connectivity_map_key])),y={...p,...f},g=Object.fromEntries(s.map(T=>[T.pcb_trace_id,T.source_trace_id?y[T.source_trace_id]:void 0]).filter(T=>!!T[1])),x=[];for(let T of n)if(T.type==="pcb_smtpad"){let k=T;if(k.layer!==e.layer)continue;let C;k.pcb_port_id&&(C=l[k.pcb_port_id]),C||(C=`unconnected:${k.pcb_smtpad_id}`),k.shape==="rect"?x.push({shape:"rect",padId:k.pcb_smtpad_id,layer:k.layer,connectivityKey:C,bounds:{minX:k.x-k.width/2,minY:k.y-k.height/2,maxX:k.x+k.width/2,maxY:k.y+k.height/2}}):k.shape==="circle"&&x.push({shape:"circle",padId:k.pcb_smtpad_id,layer:k.layer,connectivityKey:C,x:k.x,y:k.y,radius:k.radius})}else if(T.type==="pcb_plated_hole"){let k=T;if(k.shape!=="circle"||!k.layers.includes(e.layer))continue;let C=u[k.pcb_plated_hole_id];C||(C=`unconnected-plated-hole:${k.pcb_plated_hole_id}`),x.push({shape:"circle",padId:k.pcb_plated_hole_id,layer:e.layer,connectivityKey:C,x:k.x,y:k.y,radius:k.outer_diameter/2})}else if(T.type==="pcb_hole"){let k=T;if(k.hole_shape!=="circle")continue;x.push({shape:"circle",padId:k.pcb_hole_id,layer:e.layer,connectivityKey:`hole:${k.pcb_hole_id}`,x:k.x,y:k.y,radius:k.hole_diameter/2})}else if(T.type==="pcb_cutout"){let k=T;k.shape==="rect"?x.push({shape:"rect",padId:k.pcb_cutout_id,layer:e.layer,connectivityKey:`cutout:${k.pcb_cutout_id}`,bounds:{minX:k.center.x-k.width/2,minY:k.center.y-k.height/2,maxX:k.center.x+k.width/2,maxY:k.center.y+k.height/2}}):k.shape==="circle"?x.push({shape:"circle",padId:k.pcb_cutout_id,layer:e.layer,connectivityKey:`cutout:${k.pcb_cutout_id}`,x:k.center.x,y:k.center.y,radius:k.radius}):k.shape==="polygon"&&x.push({shape:"polygon",padId:k.pcb_cutout_id,layer:e.layer,connectivityKey:`cutout:${k.pcb_cutout_id}`,points:k.points})}else if(T.type==="pcb_via"){let k=T;if(!k.layers.includes(e.layer))continue;let C=k.subcircuit_connectivity_map_key??g[k.pcb_trace_id??""]??`unconnected-via:${k.pcb_via_id}`;x.push({shape:"circle",padId:k.pcb_via_id,layer:e.layer,connectivityKey:C,x:k.x,y:k.y,radius:k.outer_diameter/2})}else if(T.type==="pcb_trace"){let k=T;if(!k.source_trace_id)continue;let C=y[k.source_trace_id];if(!C)continue;let E=[],N=null,I=()=>{E.length>1&&x.push({shape:"trace",padId:`${k.pcb_trace_id}-${x.length}`,layer:e.layer,connectivityKey:C,segments:E,width:N}),E=[],N=null};for(let A of k.route){let R=A;R.route_type==="wire"&&R.layer===e.layer?(N===null&&(N=R.width),E.push({x:R.x,y:R.y})):I()}I()}let{width:v,height:S}=a,P=[{shape:"rect",layer:e.layer,bounds:{minX:-v/2,minY:-S/2,maxX:v/2,maxY:S/2},outline:a.outline,connectivityKey:e.pour_connectivity_key,padMargin:e.pad_margin,traceMargin:e.trace_margin,board_edge_margin:e.board_edge_margin??0,cutout_margin:e.cutout_margin}];return{pads:x,regionsForPour:P}};Pa();wt();Oe();var Jnt=Ht(Hs(),1);var r9=Ht(An(),1),X_=Ht(Hs(),1),Nge=Ht(Hs(),1);var Id=Ht(kd(),1);var Qnt=Ht(kd(),1),tit=Ht(kd(),1);var eit=Ht(kd(),1);var nit=Ht(kd(),1);var iit=Ht(kd(),1),rit=Ht(Hs(),1);var IRt=Object.defineProperty,NRt=(n,e)=>{for(var t in e)IRt(n,t,{get:e[t],enumerable:!0})},ket={};NRt(ket,{AnalogSimulation:()=>Znt,Battery:()=>Int,Board:()=>nnt,Breakout:()=>wnt,BreakoutPoint:()=>Snt,CadAssembly:()=>Bet,CadModel:()=>jet,Capacitor:()=>d9,Chip:()=>Y1,Constraint:()=>pnt,CopperPour:()=>Cnt,Crystal:()=>Lnt,Cutout:()=>$1,Diode:()=>f9,FabricationNoteDimension:()=>mnt,FabricationNotePath:()=>dnt,FabricationNoteRect:()=>hnt,FabricationNoteText:()=>fnt,Footprint:()=>zet,Fuse:()=>snt,Group:()=>_l,Hole:()=>V_,Inductor:()=>_9,Jumper:()=>ont,Keepout:()=>HS,Led:()=>cnt,Mosfet:()=>znt,Net:()=>a9,NetLabel:()=>Pnt,NormalComponent:()=>Gn,Panel:()=>int,PcbNoteDimension:()=>bnt,PcbNoteLine:()=>_nt,PcbNotePath:()=>xnt,PcbNoteRect:()=>ynt,PcbNoteText:()=>gnt,PcbTrace:()=>l9,PinHeader:()=>Nnt,Pinout:()=>rnt,PlatedHole:()=>U_,Port:()=>Vi,Potentiometer:()=>Rnt,PowerSource:()=>lnt,PrimitiveComponent:()=>Te,PushButton:()=>Ont,Renderable:()=>s9,Resistor:()=>m9,Resonator:()=>Ant,SchematicArc:()=>Xnt,SchematicBox:()=>Vnt,SchematicCell:()=>Wnt,SchematicCircle:()=>Unt,SchematicLine:()=>Bnt,SchematicRect:()=>Ynt,SchematicRow:()=>Hnt,SchematicTable:()=>Gnt,SchematicText:()=>jnt,SilkscreenCircle:()=>knt,SilkscreenLine:()=>Ent,SilkscreenPath:()=>c9,SilkscreenRect:()=>Tnt,SilkscreenText:()=>JS,SmtPad:()=>D1,SolderJumper:()=>ant,Subcircuit:()=>vnt,Switch:()=>Dnt,Symbol:()=>qnt,TestPoint:()=>$nt,Trace:()=>oo,TraceHint:()=>p9,Transistor:()=>Fnt,Via:()=>Mnt,VoltageProbe:()=>Knt,VoltageSource:()=>unt});var ARt=(0,Met.default)("tscircuit:renderable"),Xa=["ReactSubtreesRender","InflateSubcircuitCircuitJson","SourceNameDuplicateComponentRemoval","PcbFootprintStringRender","InitializePortsFromChildren","CreateNetsFromProps","AssignFallbackProps","CreateTracesFromProps","CreateTracesFromNetLabels","CreateTraceHintsFromProps","SourceGroupRender","AssignNameToUnnamedComponents","SourceRender","SourceParentAttachment","PortMatching","OptimizeSelectorCache","SourceTraceRender","SourceAddConnectivityMapKey","SourceDesignRuleChecks","SimulationRender","SchematicComponentRender","SchematicPortRender","SchematicPrimitiveRender","SchematicComponentSizeCalculation","SchematicLayout","SchematicTraceRender","SchematicReplaceNetLabelsWithSymbols","PcbComponentRender","PcbPrimitiveRender","PcbFootprintLayout","PcbPortRender","PcbPortAttachment","PcbComponentSizeCalculation","PcbComponentAnchorAlignment","PcbLayout","PcbBoardAutoSize","PcbTraceHintRender","PcbManualTraceRender","PcbTraceRender","PcbRouteNetIslands","PcbCopperPourRender","PcbDesignRuleChecks","SilkscreenOverlapAdjustment","CadModelRender","PartsEngineRender","SimulationSpiceEngineRender"],RRt={PcbFootprintLayout:["PcbFootprintStringRender"],PcbComponentSizeCalculation:["PcbFootprintStringRender"],PcbLayout:["PcbFootprintStringRender"],PcbBoardAutoSize:["PcbFootprintStringRender"],PcbTraceHintRender:["PcbFootprintStringRender"],PcbManualTraceRender:["PcbFootprintStringRender"],PcbCopperPourRender:["PcbFootprintStringRender","PcbTraceRender","PcbRouteNetIslands"],PcbTraceRender:["PcbFootprintStringRender"],PcbRouteNetIslands:["PcbFootprintStringRender"],PcbDesignRuleChecks:["PcbFootprintStringRender"],SilkscreenOverlapAdjustment:["PcbFootprintStringRender"],CadModelRender:["PcbFootprintStringRender"],PartsEngineRender:["PcbFootprintStringRender"],PcbComponentAnchorAlignment:["PcbFootprintStringRender"]},ORt=0,s9=class Cet{constructor(e){d(this,"renderPhaseStates");d(this,"shouldBeRemoved",!1);d(this,"children");d(this,"isPcbPrimitive",!1);d(this,"isSchematicPrimitive",!1);d(this,"_renderId");d(this,"_currentRenderPhase",null);d(this,"_asyncEffects",[]);d(this,"parent",null);this._renderId=`${ORt++}`,this.children=[],this.renderPhaseStates={};for(let t of Xa)this.renderPhaseStates[t]={initialized:!1,dirty:!1}}_markDirty(e){this.renderPhaseStates[e].dirty=!0;let t=Xa.indexOf(e);for(let i=t+1;i<Xa.length;i++)this.renderPhaseStates[Xa[i]].dirty=!0;this.parent?._markDirty&&this.parent._markDirty(e)}_queueAsyncEffect(e,t){let i={promise:t(),phase:this._currentRenderPhase,effectName:e,complete:!1};this._asyncEffects.push(i),"root"in this&&this.root&&this.root.emit("asyncEffect:start",{effectName:e,componentDisplayName:this.getString(),phase:i.phase}),i.promise.then(()=>{i.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:e,componentDisplayName:this.getString(),phase:i.phase})}).catch(r=>{console.error(`Async effect error in ${i.phase} "${e}":
249
+ ${r.stack}`),i.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:e,componentDisplayName:this.getString(),phase:i.phase,error:r.toString()})})}_emitRenderLifecycleEvent(e,t){ARt(`${e}:${t} ${this.getString()}`);let i=`renderable:renderLifecycle:${e}:${t}`,r={renderId:this._renderId,componentDisplayName:this.getString(),type:i};"root"in this&&this.root&&(this.root.emit(i,r),this.root.emit("renderable:renderLifecycle:anyEvent",{...r,type:i}))}getString(){return this.constructor.name}_hasIncompleteAsyncEffects(){return this._asyncEffects.some(e=>!e.complete)}_hasIncompleteAsyncEffectsInSubtreeForPhase(e){for(let t of this._asyncEffects)if(!t.complete&&t.phase===e)return!0;for(let t of this.children)if(t._hasIncompleteAsyncEffectsInSubtreeForPhase(e))return!0;return!1}getCurrentRenderPhase(){return this._currentRenderPhase}getRenderGraph(){return{id:this._renderId,currentPhase:this._currentRenderPhase,renderPhaseStates:this.renderPhaseStates,shouldBeRemoved:this.shouldBeRemoved,children:this.children.map(e=>e.getRenderGraph())}}getTopLevelRenderable(){let e=this;for(;e.parent&&e.parent instanceof Cet;)e=e.parent;return e}runRenderCycle(){for(let e of Xa)this.runRenderPhaseForChildren(e),this.runRenderPhase(e)}runRenderPhase(e){this._currentRenderPhase=e;let t=this.renderPhaseStates[e],i=t.initialized,r=t.dirty;if(!i&&this.shouldBeRemoved)return;if(this.shouldBeRemoved&&i){this._emitRenderLifecycleEvent(e,"start"),this?.[`remove${e}`]?.(),t.initialized=!1,t.dirty=!1,this._emitRenderLifecycleEvent(e,"end");return}let s=Xa.indexOf(e)-1;if(s>=0){let a=Xa[s];if(this._asyncEffects.filter(l=>l.phase===a).some(l=>!l.complete))return}let o=RRt[e]||[];if(o.length>0){let a=this.getTopLevelRenderable();for(let c of o)if(a._hasIncompleteAsyncEffectsInSubtreeForPhase(c))return}if(this._emitRenderLifecycleEvent(e,"start"),i){r&&(this?.[`update${e}`]?.(),t.dirty=!1),this._emitRenderLifecycleEvent(e,"end");return}t.dirty=!1,this?.[`doInitial${e}`]?.(),t.initialized=!0,this._emitRenderLifecycleEvent(e,"end")}runRenderPhaseForChildren(e){for(let t of this.children)t.runRenderPhaseForChildren(e),t.runRenderPhase(e)}renderError(e){throw typeof e=="string"?new Error(e):new Error(JSON.stringify(e,null,2))}},GS={},Iet=n=>{let e=Object.fromEntries(Object.entries(n).map(([t,i])=>[t.toLowerCase(),i]));Object.assign(GS,n),Object.assign(GS,e)},LRt=class extends Error{constructor(n,e,t){let i,r=Object.keys(t).filter(c=>c!=="_errors"),s=[],o=e.pinLabels;if(o)for(let[c,l]of Object.entries(o)){let u=Array.isArray(l)?l:[l];for(let p of u)typeof p=="string"&&(p.startsWith(" ")||p.endsWith(" "))&&s.push(`pinLabels.${c} ("${p}" has leading or trailing spaces)`)}let a=r.map(c=>c==="pinLabels"&&s.length>0?s.join(", "):t[c]._errors[0]?`${c} (${t[c]._errors[0]})`:`${c} (${JSON.stringify(t[c])})`).join(", ");"name"in e?i=`Invalid props for ${n} "${e.name}": ${a}`:"footprint"in e&&typeof e.footprint=="string"?i=`Invalid props for ${n} (unnamed ${e.footprint} component): ${a}`:i=`Invalid props for ${n} (unnamed): ${a}`,super(i),this.componentName=n,this.originalProps=e,this.formattedError=t}};function XA(n,e){let t=e.match(/^#(\w+)/);if(t)return n.props.id===t[1];let i=e.match(/^\.(\w+)/);if(i)return n.isMatchingNameOrAlias(i[1]);let[r,...s]=e.split(/(?=[#.[])/);return r==="pin"&&(r="port"),r&&r!=="*"&&n.lowercaseComponentName!==r.toLowerCase()?!1:s.every(o=>{if(o.startsWith("#"))return n.props.id===o.slice(1);if(o.startsWith("."))return n.isMatchingNameOrAlias(o.slice(1));let a=o.match(/\[(\w+)=['"]?(.+?)['"]?\]/);if(!a)return!0;let[,c,l]=a;return n.props[c].toString()===l})}var o9={isTag:n=>!0,getParent:n=>n.parent,getChildren:n=>n.children,getName:n=>n.lowercaseComponentName,getAttributeValue:(n,e)=>{if(e==="class"&&"getNameAndAliases"in n)return n.getNameAndAliases().join(" ");if(e==="name"&&n._parsedProps?.name)return n._parsedProps.name;if(n._parsedProps&&e in n._parsedProps){let i=n._parsedProps[e];return typeof i=="string"?i:i!=null?String(i):null}if(e in n){let i=n[e];return typeof i=="string"?i:i!=null?String(i):null}let t=n._attributeLowerToCamelNameMap;if(t){let i=t[e];if(i&&i in n){let r=n[i];return typeof r=="string"?r:r!=null?String(r):null}}return null},hasAttrib:(n,e)=>{if(e==="class")return!!n._parsedProps?.name;if(n._parsedProps&&e in n._parsedProps||e in n)return!0;let t=n._attributeLowerToCamelNameMap;if(t){let i=t[e];if(i&&i in n)return!0}return!1},getSiblings:n=>n.parent?n.parent.children:[],prevElementSibling:n=>{if(!n.parent)return null;let e=n.parent.children,t=e.indexOf(n);return t>0?e[t-1]:null},getText:()=>"",removeSubsets:n=>n.filter((e,t)=>!n.some((i,r)=>t!==r&&i!==e&&i.getDescendants().includes(e))),existsOne:(n,e)=>e.some(n),findAll:(n,e)=>{let t=[],i=r=>{n(r)&&t.push(r);for(let s of r.children)i(s)};for(let r of e)i(r);return t},findOne:(n,e)=>{for(let t of e){if(n(t))return t;let i=t.children;if(i.length>0){let r=o9.findOne(n,i);if(r)return r}}return null},equals:(n,e)=>n._renderId===e._renderId,isHovered:n=>!1,isVisited:n=>!1,isActive:n=>!1},FRt={...o9,getChildren:n=>n.children.filter(e=>!e.isSubcircuit)},Jtt={...o9,getChildren:n=>n.children.filter(e=>e.isSubcircuit)},Qtt=n=>{if(/net\.[^\s>]*\./.test(n))throw new Error('Net names cannot contain a period, try using "sel.net..." to autocomplete with conventional net names, e.g. V3_3');if(/net\.[^\s>]*[+-]/.test(n))throw new Error('Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P');if(/net\.[0-9]/.test(n)){let e=n.match(/net\.([^ >]+)/),t=e?e[1]:"";throw new Error(`Net name "${t}" cannot start with a number, try using a prefix like "VBUS1"`)}return n.replace(/ pin(?=[\d.])/g," port").replace(/ subcircuit\./g," group[isSubcircuit=true]").replace(/([^ ])\>([^ ])/g,"$1 > $2").replace(/(^|[ >])(?!pin\.)(?!port\.)(?!net\.)([A-Z][A-Za-z0-9_-]*)\.([A-Za-z0-9_-]+)/g,(e,t,i,r)=>{let s=/^\d+$/.test(r)?`pin${r}`:r;return`${t}.${i} > .${s}`}).trim()},UA={adapter:FRt,cacheResults:!0},Te=class extends s9{constructor(e){super(e);d(this,"parent",null);d(this,"children");d(this,"childrenPendingRemoval");d(this,"props");d(this,"_parsedProps");d(this,"externallyAddedAliases");d(this,"isPrimitiveContainer",!1);d(this,"canHaveTextChildren",!1);d(this,"source_group_id",null);d(this,"source_component_id",null);d(this,"schematic_component_id",null);d(this,"pcb_component_id",null);d(this,"cad_component_id",null);d(this,"fallbackUnassignedName");d(this,"_cachedSelectAllQueries",new Map);d(this,"_cachedSelectOneQueries",new Map);this.children=[],this.childrenPendingRemoval=[],this.props=e??{},this.externallyAddedAliases=[];let i=("partial"in this.config.zodProps?this.config.zodProps.partial({name:!0}):this.config.zodProps).safeParse(e??{});if(i.success)this._parsedProps=i.data;else throw new LRt(this.lowercaseComponentName,this.props,i.error.format())}get config(){return{componentName:"",zodProps:h.object({}).passthrough()}}get componentName(){return this.config.componentName}getInheritedProperty(e){let t=this;for(;t;){if(t._parsedProps&&e in t._parsedProps)return t._parsedProps[e];t=t.parent}if(this.root?.platform&&e in this.root.platform)return this.root.platform[e]}getInheritedMergedProperty(e){let t=this.parent?.getInheritedMergedProperty?.(e),i=this._parsedProps?.[e];return{...t,...i}}get lowercaseComponentName(){return this.componentName.toLowerCase()}get isSubcircuit(){return!!this.props.subcircuit||this.lowercaseComponentName==="group"&&this?.parent?.isRoot}get isGroup(){return this.lowercaseComponentName==="group"}get name(){return this._parsedProps.name??this.fallbackUnassignedName}setProps(e){let t=this.config.zodProps.parse({...this.props,...e}),i=this.props;this.props=t,this._parsedProps=this.config.zodProps.parse(e),this.onPropsChange({oldProps:i,newProps:t,changedProps:Object.keys(e)}),this.parent?.onChildChanged?.(this)}_getPcbRotationBeforeLayout(){let{pcbRotation:e}=this.props;return typeof e=="string"?parseFloat(e):e??null}computePcbPropsTransform(){let{_parsedProps:e}=this,t=this._getPcbRotationBeforeLayout()??0;return mi(Nn(e.pcbX??0,e.pcbY??0),Dc(t*Math.PI/180))}_computePcbGlobalTransformBeforeLayout(){let e=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if(e&&this.props.pcbX===void 0&&this.props.pcbY===void 0){let t=this._getPcbRotationBeforeLayout()??0;return mi(this.parent?._computePcbGlobalTransformBeforeLayout()??Qi(),mi(Nn(e.x,e.y),Dc(t*Math.PI/180)))}if(this.isPcbPrimitive){let t=this.getPrimitiveContainer();if(t&&t._parsedProps.layer==="bottom")return mi(this.parent?._computePcbGlobalTransformBeforeLayout()??Qi(),gB(),this.computePcbPropsTransform())}return mi(this.parent?._computePcbGlobalTransformBeforeLayout()??Qi(),this.computePcbPropsTransform())}getPrimitiveContainer(){return this.isPrimitiveContainer?this:this.parent?.getPrimitiveContainer?.()??null}getParentNormalComponent(){let e=this.parent;for(;e;){if(e.isPrimitiveContainer&&e.doInitialPcbComponentRender)return e;e=e.parent}return null}_getPcbCircuitJsonBounds(){return{center:{x:0,y:0},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getPcbPrimitiveFlippedHelpers(){let e=this.getPrimitiveContainer(),t=e?e._parsedProps.layer==="bottom":!1;return{isFlipped:t,maybeFlipLayer:r=>t?r==="top"?"bottom":"top":r}}_setPositionFromLayout(e){throw new Error(`_setPositionFromLayout not implemented for ${this.componentName}`)}computeSchematicPropsTransform(){let{_parsedProps:e}=this;return mi(Nn(e.schX??0,e.schY??0))}computeSchematicGlobalTransform(){let e=this._getSchematicGlobalManualPlacementTransform(this);return e||mi(this.parent?.computeSchematicGlobalTransform?.()??Qi(),this.computeSchematicPropsTransform())}_getSchematicSymbolName(){let{_parsedProps:e}=this,t=this.config.schematicSymbolName,i={horizontal:0,pos_left:0,neg_right:0,pos_right:180,neg_left:180,pos_top:270,neg_bottom:90,vertical:270,pos_bottom:90,neg_top:90},r=e.schOrientation!==void 0?i[e.schOrientation]:e.schRotation;if(r===void 0&&(r=0),r=r%360,r<0&&(r+=360),e.schRotation!==void 0&&r%90!==0)throw new Error(`Schematic rotation ${e.schRotation} is not supported for ${this.componentName}`);let s=`${t}_horz`,o=`${t}_vert`,a=`${t}_up`,c=`${t}_down`,l=`${t}_left`,u=`${t}_right`;if(u in _i&&r===0)return u;if(a in _i&&r===90)return a;if(l in _i&&r===180)return l;if(c in _i&&r===270)return c;if(s in _i&&(r===0||r===180))return s;if(o in _i&&(r===90||r===270))return o;if(t in _i)return t}_getSchematicSymbolNameOrThrow(){let e=this._getSchematicSymbolName();if(!e)throw new Error(`No schematic symbol found (given: "${this.config.schematicSymbolName}")`);return e}getSchematicSymbol(){let e=this._getSchematicSymbolName();return e?_i[e]??null:null}_getPcbManualPlacementForComponent(e){if(!this.isSubcircuit)return null;let t=this.props.manualEdits;if(!t)return null;let i=t?.pcb_placements;if(!i)return null;for(let r of i)if(XA(e,r.selector)||e.props.name===r.selector)return ze(this._computePcbGlobalTransformBeforeLayout(),r.center);return null}_getSchematicManualPlacementForComponent(e){if(!this.isSubcircuit)return null;let t=this.props.manualEdits;if(!t)return null;let i=t.schematic_placements;if(!i)return null;for(let r of i)if(XA(e,r.selector)||e.props.name===r.selector)return ze(this.computeSchematicGlobalTransform(),r.center);return null}_getSchematicGlobalManualPlacementTransform(e){let t=this.getSubcircuit()?._parsedProps.manualEdits;if(!t)return null;for(let i of t.schematic_placements??[])if((XA(e,i.selector)||e.props.name===i.selector)&&i.relative_to==="group_center")return mi(this.parent?._computePcbGlobalTransformBeforeLayout()??Qi(),Nn(i.center.x,i.center.y));return null}_getGlobalPcbPositionBeforeLayout(){return ze(this._computePcbGlobalTransformBeforeLayout(),{x:0,y:0})}_getGlobalSchematicPositionBeforeLayout(){return ze(this.computeSchematicGlobalTransform(),{x:0,y:0})}get root(){return this.parent?.root??null}onAddToParent(e){this.parent=e}onPropsChange(e){}onChildChanged(e){this.parent?.onChildChanged?.(e)}add(e){let t=e.__text;if(typeof t=="string"){if(this.canHaveTextChildren||t.trim()==="")return;throw new Error(`Invalid JSX Element: Expected a React component but received text "${t}"`)}if(Object.keys(e).length!==0){if(this.lowercaseComponentName==="board"&&e.lowercaseComponentName==="board")throw new Error("Nested boards are not supported");if(e.lowercaseComponentName==="panel")throw new Error("<panel> must be a root-level element");if(!e.onAddToParent)throw new Error(`Invalid JSX Element: Expected a React component but received "${JSON.stringify(e)}"`);e.onAddToParent(this),e.parent=this,this.children.push(e)}}addAll(e){for(let t of e)this.add(t)}remove(e){this.children=this.children.filter(t=>t!==e),this.childrenPendingRemoval.push(e),e.shouldBeRemoved=!0}getSubcircuitSelector(){let e=this.name,t=e?`${this.lowercaseComponentName}.${e}`:this.lowercaseComponentName;return!this.parent||this.parent.isSubcircuit?t:`${this.parent.getSubcircuitSelector()} > ${t}`}getFullPathSelector(){let e=this.name,t=e?`${this.lowercaseComponentName}.${e}`:this.lowercaseComponentName,i=this.parent?.getFullPathSelector?.();return i?`${i} > ${t}`:t}getNameAndAliases(){return[this.name,...this._parsedProps.portHints??[]].filter(Boolean)}isMatchingNameOrAlias(e){return this.getNameAndAliases().includes(e)}isMatchingAnyOf(e){return this.getNameAndAliases().some(t=>e.map(i=>i.toString()).includes(t))}getPcbSize(){throw new Error(`getPcbSize not implemented for ${this.componentName}`)}doesSelectorMatch(e){let t=[this.componentName,this.lowercaseComponentName],i=[this.name].filter(Boolean),r=e.trim().split(/\> /)[0],s=r[0];return r.length>1?!1:!!(e==="*"||e[0]==="#"&&e.slice(1)===this.props.id||e[0]==="."&&i.includes(e.slice(1))||/^[a-zA-Z0-9_]/.test(s)&&t.includes(s))}getSubcircuit(){if(this.isSubcircuit)return this;let e=this.parent?.getSubcircuit?.();if(!e)throw new Error("Component is not inside an opaque group (no board?)");return e}getGroup(){return this.isGroup?this:this.parent?.getGroup?.()??null}doInitialAssignNameToUnnamedComponents(){this._parsedProps.name||(this.fallbackUnassignedName=this.getSubcircuit().getNextAvailableName(this))}doInitialOptimizeSelectorCache(){if(!this.isSubcircuit)return;let e=this.selectAll("port");for(let t of e){let r=(t.getParentNormalComponent?.()??t.parent)?.getNameAndAliases(),s=t.getNameAndAliases();if(r)for(let o of r)for(let a of s){let c=[`.${o} > .${a}`,`.${o} .${a}`];for(let l of c){let u=this._cachedSelectAllQueries.get(l);u?u.push(t):this._cachedSelectAllQueries.set(l,[t])}}}for(let[t,i]of this._cachedSelectAllQueries.entries())i.length===1&&this._cachedSelectOneQueries.set(t,i[0])}selectAll(e){if(this._cachedSelectAllQueries.has(e))return this._cachedSelectAllQueries.get(e);let t=Qtt(e),i=F5(t,this,UA);if(i.length>0)return this._cachedSelectAllQueries.set(e,i),i;let[r,...s]=t.split(" "),o=tw(r,this,{adapter:Jtt});if(!o)return[];let a=o.selectAll(s.join(" "));return this._cachedSelectAllQueries.set(e,a),a}selectOne(e,t){if(this._cachedSelectOneQueries.has(e))return this._cachedSelectOneQueries.get(e);let i=Qtt(e);t?.port&&(t.type="port");let r=null;if(t?.type&&(r=F5(i,this,UA).find(l=>l.lowercaseComponentName===t.type)),r??(r=tw(i,this,UA)),r)return this._cachedSelectOneQueries.set(e,r),r;let[s,...o]=i.split(" "),a=tw(s,this,{adapter:Jtt});return a?(r=a.selectOne(o.join(" "),t),this._cachedSelectOneQueries.set(e,r),r):null}getAvailablePcbLayers(){if(this.isPcbPrimitive){let{maybeFlipLayer:e}=this._getPcbPrimitiveFlippedHelpers();return"layer"in this._parsedProps||this.componentName==="SmtPad"?[e(this._parsedProps.layer??"top")]:"layers"in this._parsedProps?this._parsedProps.layers:this.componentName==="PlatedHole"?this.root?._getBoard()?.allLayers??["top","bottom"]:[]}return[]}getDescendants(){let e=[];for(let t of this.children)e.push(t),e.push(...t.getDescendants());return e}getSelectableDescendants(){let e=[];for(let t of this.children)t.isSubcircuit?e.push(t):(e.push(t),e.push(...t.getSelectableDescendants()));return e}_getPinCount(){return 0}_getSchematicBoxDimensions(){return null}_getSchematicBoxComponentDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;let{_parsedProps:e}=this;return{schWidth:e.schWidth,schHeight:e.schHeight}}renderError(e){if(typeof e=="string")return super.renderError(e);switch(e.type){case"pcb_placement_error":this.root?.db.pcb_placement_error.insert(e);break;case"pcb_via_clearance_error":this.root?.db.pcb_via_clearance_error.insert(e);break;case"pcb_trace_error":this.root?.db.pcb_trace_error.insert(e);break;case"pcb_manual_edit_conflict_warning":this.root?.db.pcb_manual_edit_conflict_warning.insert(e);break;default:this.root?.db.pcb_placement_error.insert(e)}}getString(){let{lowercaseComponentName:e,_parsedProps:t,parent:i}=this;return t?.pinNumber!==void 0&&i?.props?.name&&t?.name?`<${e}#${this._renderId}(pin:${t.pinNumber} .${i?.props.name}>.${t.name}) />`:i?.props?.name&&t?.name?`<${e}#${this._renderId}(.${i?.props.name}>.${t?.name}) />`:t?.from&&t?.to?`<${e}#${this._renderId}(from:${t.from} to:${t?.to}) />`:t?.name?`<${e}#${this._renderId} name=".${t?.name}" />`:t?.portHints?`<${e}#${this._renderId}(${t.portHints.map(r=>`.${r}`).join(", ")}) />`:`<${e}#${this._renderId} />`}get[Symbol.toStringTag](){return this.getString()}[Symbol.for("nodejs.util.inspect.custom")](){return this.getString()}},zRt=class extends Te{constructor(n,e){super(n),this._parsedProps={...n,error:e,type:n.type||"unknown",component_name:n.name,error_type:"source_failed_to_create_component_error",message:e instanceof Error?e.message:String(e),pcbX:n.pcbX,pcbY:n.pcbY,schX:n.schX,schY:n.schY}}get config(){return{componentName:"ErrorPlaceholder",zodProps:h.object({}).passthrough()}}doInitialSourceRender(){if(this.root?.db){let n=this._getGlobalPcbPositionBeforeLayout(),e=this._getGlobalSchematicPositionBeforeLayout();this.root.db.source_failed_to_create_component_error.insert({component_name:this._parsedProps.component_name,error_type:"source_failed_to_create_component_error",message:`Could not create ${this._parsedProps.componentType??"component"}${this._parsedProps.name?` "${this._parsedProps.name}"`:""}. ${this._parsedProps.error?.formattedError?._errors?.join("; ")||this._parsedProps.message}`,pcb_center:n,schematic_center:e})}}};function DRt(n,e){return new zRt(n,e)}function $Rt(n,e){let t=n;return t.__tsci={...e},n}var jRt={supportsMutation:!0,createInstance(n,e){let t=GS[n];if(!t)throw Object.keys(GS).length===0?new Error("No components registered in catalogue, did you forget to import lib/register-catalogue in your test file?"):new Error(`Unsupported component type "${n}". No element with this name is registered in the @tscircuit/core catalogue. Check for typos or see https://docs.tscircuit.com/category/built-in-elements for a list of valid components. To add your own component, see docs/CREATING_NEW_COMPONENTS.md`);try{return $Rt(new t(e),{})}catch(i){return DRt({...e,componentType:n},i)}},createTextInstance(n){return{__text:n}},appendInitialChild(n,e){n.add(e)},appendChild(n,e){n.add(e)},appendChildToContainer(n,e){n.add(e)},finalizeInitialChildren(){return!1},prepareUpdate(){return null},shouldSetTextContent(){return!1},getRootHostContext(){return{}},getChildHostContext(){return{}},prepareForCommit(){return null},resetAfterCommit(){},commitMount(){},commitUpdate(){},removeChild(){},clearContainer(){},supportsPersistence:!1,getPublicInstance(n){return n},preparePortalMount(n){throw new Error("Function not implemented.")},scheduleTimeout(n,e){throw new Error("Function not implemented.")},cancelTimeout(n){throw new Error("Function not implemented.")},noTimeout:void 0,isPrimaryRenderer:!1,getInstanceFromNode(n){throw new Error("Function not implemented.")},beforeActiveInstanceBlur(){throw new Error("Function not implemented.")},afterActiveInstanceBlur(){throw new Error("Function not implemented.")},prepareScopeUpdate:(n,e)=>{throw new Error("Function not implemented.")},getInstanceFromScope:n=>{throw new Error("Function not implemented.")},detachDeletedInstance:n=>{throw new Error("Function not implemented.")},getCurrentEventPriority:()=>US.DefaultEventPriority,getCurrentUpdatePriority:()=>US.DefaultEventPriority,resolveUpdatePriority:()=>US.DefaultEventPriority,setCurrentUpdatePriority:()=>{},maySuspendCommit:()=>!1,supportsHydration:!1},jS=(0,Eet.default)(jRt),Net=n=>{let e={children:[],props:{name:"$root"},add(s){s.parent=this,this.children.push(s)},computePcbGlobalTransform(){return Qi()}},t=[],i=jS.createContainer(e,0,null,!1,null,"tsci",s=>{console.log("Error in createContainer"),console.error(s),t.push(s)},null);if(jS.updateContainerSync(n,i,null,()=>{}),jS.flushSyncWork(),t.length>0)throw t[0];let r=jS.getPublicRootInstance(i);return r||e.children[0]},j1=(n,e)=>{if(typeof n=="number")return n;if(n.startsWith("pin"))return Number(n.slice(3));if(!e)throw new Error(`No pin labels provided and pin number or label is not a number: "${n}"`);for(let t in e)if((Array.isArray(e[t])?e[t]:[e[t]]).includes(n))return Number(t.replace("pin",""));throw new Error(`No pin labels provided and pin number or label is not a number: "${n}"`)},BRt=(n,e)=>{if(!n)return;let t={},i={};for(let[r,s]of Object.entries(n)){let o=j1(r,e);i[o]={...i[o],...s}}for(let[r,s]of Object.entries(i)){let o=`pin${r}`;t[o]={bottom_margin:s.bottomMargin,left_margin:s.leftMargin,right_margin:s.rightMargin,top_margin:s.topMargin}}return t},YRt=n=>{if(n){if("leftSide"in n||"rightSide"in n||"topSide"in n||"bottomSide"in n)return{left_side:n.leftSide,right_side:n.rightSide,top_side:n.topSide,bottom_side:n.bottomSide};if("leftPinCount"in n||"rightPinCount"in n||"topPinCount"in n||"bottomPinCount"in n)return{left_size:n.leftPinCount,right_size:n.rightPinCount,top_size:n.topPinCount,bottom_size:n.bottomPinCount};if("leftSize"in n||"rightSize"in n||"topSize"in n||"bottomSize"in n)return{left_size:n.leftSize,right_size:n.rightSize,top_size:n.topSize,bottom_size:n.bottomSize}}};function Aet(n){let e=[];for(let t=0;t<n.length-1;t++)e.push([n[t],n[t+1]]);return e}var XRt=h.object({name:h.string().refine(n=>!/[+-]/.test(n),'Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P')}),a9=class extends Te{constructor(){super(...arguments);d(this,"source_net_id");d(this,"subcircuit_connectivity_map_key",null)}get config(){return{componentName:"Net",zodProps:XRt}}getPortSelector(){return`net.${this.props.name}`}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=t.name.startsWith("GND"),r=t.name.startsWith("V"),s=e.source_net.insert({name:t.name,member_source_group_ids:[],is_ground:i,is_power:r,is_positive_voltage_source:r});this.source_net_id=s.source_net_id}doInitialSourceParentAttachment(){let e=this.getSubcircuit();if(!e)return;let{db:t}=this.root;t.source_net.update(this.source_net_id,{subcircuit_id:e.subcircuit_id})}getAllConnectedPorts(){let e=this.getSubcircuit().selectAll("port"),t=[];for(let i of e){let r=i._getDirectlyConnectedTraces();for(let s of r)if(s._isExplicitlyConnectedToNet(this)){t.push(i);break}}return t}_getAllDirectlyConnectedTraces(){let e=this.getSubcircuit().selectAll("trace"),t=[];for(let i of e)i._isExplicitlyConnectedToNet(this)&&t.push(i);return t}doInitialPcbRouteNetIslands(){if(this.root?.pcbDisabled||this.getSubcircuit()._parsedProps.routingDisabled||this.getSubcircuit()._getAutorouterConfig().groupMode!=="sequential-trace")return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getAllDirectlyConnectedTraces().filter(o=>(o._portsRoutedOnPcb?.length??0)>0),r=[];for(let o of i){let a=o._portsRoutedOnPcb,c=r.find(l=>a.some(u=>l.ports.includes(u)));if(!c){r.push({ports:[...a],traces:[o]});continue}c.traces.push(o),c.ports.push(...a)}if(r.length===0)return;let s=Aet(r);for(let[o,a]of s){let c=o.ports.map(S=>S._getGlobalPcbPositionBeforeLayout()),l=a.ports.map(S=>S._getGlobalPcbPositionBeforeLayout()),u=1/0,p=[-1,-1];for(let S=0;S<c.length;S++){let P=c[S];for(let T=0;T<l.length;T++){let k=l[T],C=Math.sqrt((P.x-k.x)**2+(P.y-k.y)**2);C<u&&(u=C,p=[S,T])}}let f=o.ports[p[0]],y=a.ports[p[1]],g=e.toArray().filter(S=>S.type==="pcb_smtpad"||S.type==="pcb_trace"||S.type==="pcb_plated_hole"||S.type==="pcb_hole"||S.type==="source_port"||S.type==="pcb_port"),{solution:x}=sH(g.concat([{type:"source_trace",source_trace_id:"__net_trace_tmp",connected_source_port_ids:[f.source_port_id,y.source_port_id]}])),v=x[0];if(!v){this.renderError({pcb_trace_error_id:"",pcb_trace_id:"__net_trace_tmp",pcb_component_ids:[f.pcb_component_id,y.pcb_component_id].filter(Boolean),pcb_port_ids:[f.pcb_port_id,y.pcb_port_id].filter(Boolean),type:"pcb_trace_error",error_type:"pcb_trace_error",message:`Failed to route net islands for "${this.getString()}"`,source_trace_id:"__net_trace_tmp"});return}e.pcb_trace.insert(v)}}renderError(e){if(typeof e=="string")return super.renderError(e);this.root?.db.pcb_trace_error.insert(e)}},KS=(n,e)=>{for(let t of e)if(typeof t=="string"&&t.startsWith("net.")){if(/net\.[^\s>]*\./.test(t))throw new Error('Net names cannot contain a period, try using "sel.net..." to autocomplete with conventional net names, e.g. V3_3');if(/net\.[^\s>]*[+-]/.test(t))throw new Error('Net names cannot contain "+" or "-", try using underscores instead, e.g. VCC_P');if(/net\.[0-9]/.test(t)){let r=t.split("net.")[1];throw new Error(`Net name "${r}" cannot start with a number, try using a prefix like "VBUS1"`)}let i=n.getSubcircuit();if(!i.selectOne(t)){let r=new a9({name:t.split("net.")[1]});i.add(r)}}},D1=class extends Te{constructor(){super(...arguments);d(this,"pcb_smtpad_id",null);d(this,"matchedPort",null);d(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SmtPad",zodProps:NH}}getPcbSize(){let{_parsedProps:e}=this;if(e.shape==="circle")return{width:e.radius*2,height:e.radius*2};if(e.shape==="rect")return{width:e.width,height:e.height};if(e.shape==="rotated_rect"){let i=(e.ccwRotation??0)*Math.PI/180,r=Math.cos(i),s=Math.sin(i),o=Math.abs(e.width*r)+Math.abs(e.height*s),a=Math.abs(e.width*s)+Math.abs(e.height*r);return{width:o,height:a}}if(e.shape==="polygon"){let t=e.points,i=t.map(l=>l.x),r=t.map(l=>l.y),s=Math.min(...i),o=Math.max(...i),a=Math.min(...r),c=Math.max(...r);return{width:o-s,height:c-a}}if(e.shape==="pill")return{width:e.width,height:e.height};throw new Error(`getPcbSize for shape "${e.shape}" not implemented for ${this.componentName}`)}doInitialPortMatching(){let e=this.getPrimitiveContainer()?.selectAll("port");if(this.props.portHints){for(let t of e)if(t.isMatchingAnyOf(this.props.portHints)){this.matchedPort=t,t.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=t.coveredWithSolderMask??!1,r=!i,s=this.getSubcircuit(),o=this._getGlobalPcbPositionBeforeLayout(),a=this._computePcbGlobalTransformBeforeLayout(),u=(Js(this._computePcbGlobalTransformBeforeLayout()).rotation.angle*180/Math.PI%360+360)%360,p=.01,f=Math.abs(u)<p||Math.abs(u-180)<p||Math.abs(u-360)<p,y=Math.abs(u-90)<p||Math.abs(u-270)<p,g=Math.abs(u-360)<p?0:u,x=g,{maybeFlipLayer:v,isFlipped:S}=this._getPcbPrimitiveFlippedHelpers();S&&(g=(360-g+360)%360);let P=t.portHints?.map(C=>C.toString())??[],T=null,k=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id;if(t.shape==="circle")T=e.pcb_smtpad.insert({pcb_component_id:k,pcb_port_id:this.matchedPort?.pcb_port_id,layer:v(t.layer??"top"),shape:"circle",radius:t.radius,port_hints:P,is_covered_with_solder_mask:i,x:o.x,y:o.y,subcircuit_id:s?.subcircuit_id??void 0}),r&&e.pcb_solder_paste.insert({layer:T.layer,shape:"circle",radius:T.radius*.7,x:T.x,y:T.y,pcb_component_id:T.pcb_component_id,pcb_smtpad_id:T.pcb_smtpad_id,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});else if(t.shape==="rect")!f&&!y?T=e.pcb_smtpad.insert({pcb_component_id:k,pcb_port_id:this.matchedPort?.pcb_port_id,layer:v(t.layer??"top"),shape:"rotated_rect",width:t.width,height:t.height,corner_radius:t.cornerRadius??void 0,x:o.x,y:o.y,ccw_rotation:g,port_hints:P,is_covered_with_solder_mask:i,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):T=e.pcb_smtpad.insert({pcb_component_id:k,pcb_port_id:this.matchedPort?.pcb_port_id,layer:v(t.layer??"top"),shape:"rect",width:y?t.height:t.width,height:y?t.width:t.height,corner_radius:t.cornerRadius??void 0,port_hints:P,is_covered_with_solder_mask:i,x:o.x,y:o.y,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),r&&(T.shape==="rect"?e.pcb_solder_paste.insert({layer:v(t.layer??"top"),shape:"rect",width:T.width*.7,height:T.height*.7,x:T.x,y:T.y,pcb_component_id:T.pcb_component_id,pcb_smtpad_id:T.pcb_smtpad_id,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):T.shape==="rotated_rect"&&e.pcb_solder_paste.insert({layer:v(t.layer??"top"),shape:"rotated_rect",width:T.width*.7,height:T.height*.7,x:T.x,y:T.y,ccw_rotation:T.ccw_rotation,pcb_component_id:T.pcb_component_id,pcb_smtpad_id:T.pcb_smtpad_id,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}));else if(t.shape==="rotated_rect"){let C=t.ccwRotation??0,E=(x+C+360)%360,N=S?(360-E+360)%360:E;T=e.pcb_smtpad.insert({pcb_component_id:k,pcb_port_id:this.matchedPort?.pcb_port_id,layer:v(t.layer??"top"),shape:"rotated_rect",width:t.width,height:t.height,corner_radius:t.cornerRadius??void 0,x:o.x,y:o.y,ccw_rotation:N,port_hints:P,is_covered_with_solder_mask:i,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),r&&e.pcb_solder_paste.insert({layer:v(t.layer??"top"),shape:"rotated_rect",width:T.width*.7,height:T.height*.7,x:o.x,y:o.y,ccw_rotation:N,pcb_component_id:k,pcb_smtpad_id:T.pcb_smtpad_id,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(t.shape==="polygon"){let C=t.points.map(E=>{let N=ze(a,{x:X.parse(E.x),y:X.parse(E.y)});return{x:N.x,y:N.y}});T=e.pcb_smtpad.insert({pcb_component_id:k,pcb_port_id:this.matchedPort?.pcb_port_id,layer:v(t.layer??"top"),shape:"polygon",points:C,port_hints:P,is_covered_with_solder_mask:i,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else t.shape==="pill"&&(T=e.pcb_smtpad.insert({pcb_component_id:k,pcb_port_id:this.matchedPort?.pcb_port_id,layer:v(t.layer??"top"),shape:"pill",x:o.x,y:o.y,radius:t.radius,height:t.height,width:t.width,port_hints:P,is_covered_with_solder_mask:i,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}));T&&(this.pcb_smtpad_id=T.pcb_smtpad_id)}doInitialPcbPortAttachment(){if(this.root?.pcbDisabled)return;let{db:e}=this.root;e.pcb_smtpad.update(this.pcb_smtpad_id,{pcb_port_id:this.matchedPort?.pcb_port_id})}_getPcbCircuitJsonBounds(){let{db:e}=this.root,t=e.pcb_smtpad.get(this.pcb_smtpad_id);if(t.shape==="rect")return{center:{x:t.x,y:t.y},bounds:{left:t.x-t.width/2,top:t.y+t.height/2,right:t.x+t.width/2,bottom:t.y-t.height/2},width:t.width,height:t.height};if(t.shape==="rotated_rect"){let i=t.ccw_rotation*Math.PI/180,r=Math.cos(i),s=Math.sin(i),o=t.width/2,a=t.height/2,c=Math.abs(o*r)+Math.abs(a*s),l=Math.abs(o*s)+Math.abs(a*r);return{center:{x:t.x,y:t.y},bounds:{left:t.x-c,right:t.x+c,top:t.y-l,bottom:t.y+l},width:c*2,height:l*2}}if(t.shape==="circle")return{center:{x:t.x,y:t.y},bounds:{left:t.x-t.radius,top:t.y-t.radius,right:t.x+t.radius,bottom:t.y+t.radius},width:t.radius*2,height:t.radius*2};if(t.shape==="polygon"){let i=t.points,r=i.map(u=>u.x),s=i.map(u=>u.y),o=Math.min(...r),a=Math.max(...r),c=Math.min(...s),l=Math.max(...s);return{center:{x:(o+a)/2,y:(c+l)/2},bounds:{left:o,top:l,right:a,bottom:c},width:a-o,height:l-c}}if(t.shape==="pill"){let i=t.width/2,r=t.height/2;return{center:{x:t.x,y:t.y},bounds:{left:t.x-i,top:t.y-r,right:t.x+i,bottom:t.y+r},width:t.width,height:t.height}}throw new Error(`circuitJson bounds calculation not implemented for shape "${t.shape}"`)}_setPositionFromLayout(e){let{db:t}=this.root;t.pcb_smtpad.update(this.pcb_smtpad_id,{x:e.x,y:e.y});let i=t.pcb_solder_paste.list().find(r=>r.pcb_smtpad_id===this.pcb_smtpad_id);i&&t.pcb_solder_paste.update(i.pcb_solder_paste_id,{x:e.x,y:e.y}),this.matchedPort?._setPositionFromLayout(e)}},c9=class extends Te{constructor(){super(...arguments);d(this,"pcb_silkscreen_path_id",null);d(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenPath",zodProps:gW}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(t.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenPath. Must be "top" or "bottom".`);let s=this._computePcbGlobalTransformBeforeLayout(),o=this.getSubcircuit(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,c=e.pcb_silkscreen_path.insert({pcb_component_id:a,layer:r,route:t.route.map(l=>{let u=ze(s,{x:l.x,y:l.y});return{...l,x:u.x,y:u.y}}),stroke_width:t.strokeWidth??.1,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_path_id=c.pcb_silkscreen_path_id}_setPositionFromLayout(e){let{db:t}=this.root,{_parsedProps:i}=this,r=t.pcb_silkscreen_path.get(this.pcb_silkscreen_path_id);if(!r)return;let s=0,o=0;for(let u of r.route)s+=u.x,o+=u.y;s/=r.route.length,o/=r.route.length;let a=e.x-s,c=e.y-o,l=r.route.map(u=>({...u,x:u.x+a,y:u.y+c}));t.pcb_silkscreen_path.update(this.pcb_silkscreen_path_id,{route:l})}getPcbSize(){let{_parsedProps:e}=this;if(!e.route||e.route.length===0)return{width:0,height:0};let t=1/0,i=-1/0,r=1/0,s=-1/0;for(let o of e.route)t=Math.min(t,o.x),i=Math.max(i,o.x),r=Math.min(r,o.y),s=Math.max(s,o.y);return{width:i-t,height:s-r}}},URt=h.object({route:h.array(Ux),source_trace_id:h.string().optional()}),l9=class extends Te{constructor(){super(...arguments);d(this,"pcb_trace_id",null);d(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbTrace",zodProps:URt}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this.getPrimitiveContainer(),r=this.getSubcircuit(),{maybeFlipLayer:s}=this._getPcbPrimitiveFlippedHelpers(),o=this._computePcbGlobalTransformBeforeLayout(),a=t.route.map(l=>{let{x:u,y:p,...f}=l,y=ze(o,{x:u,y:p});return l.route_type==="wire"&&l.layer?{...y,...f,layer:s(l.layer)}:{...y,...f}}),c=e.pcb_trace.insert({pcb_component_id:i.pcb_component_id,source_trace_id:t.source_trace_id,route:a,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_trace_id=c.pcb_trace_id}getPcbSize(){let{_parsedProps:e}=this;if(!e.route||e.route.length===0)return{width:0,height:0};let t=1/0,i=-1/0,r=1/0,s=-1/0;for(let o of e.route)t=Math.min(t,o.x),i=Math.max(i,o.x),r=Math.min(r,o.y),s=Math.max(s,o.y),o.route_type==="wire"&&(t=Math.min(t,o.x-o.width/2),i=Math.max(i,o.x+o.width/2),r=Math.min(r,o.y-o.width/2),s=Math.max(s,o.y+o.width/2));return t===1/0||i===-1/0||r===1/0||s===-1/0?{width:0,height:0}:{width:i-t,height:s-r}}},U_=class extends Te{constructor(){super(...arguments);d(this,"pcb_plated_hole_id",null);d(this,"matchedPort",null);d(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PlatedHole",zodProps:vH}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){let{_parsedProps:e}=this;if(e.shape==="circle")return{width:e.outerDiameter,height:e.outerDiameter};if(e.shape==="oval"||e.shape==="pill")return{width:e.outerWidth,height:e.outerHeight};if(e.shape==="circular_hole_with_rect_pad")return{width:e.rectPadWidth,height:e.rectPadHeight};if(e.shape==="pill_hole_with_rect_pad")return{width:e.rectPadWidth,height:e.rectPadHeight};throw new Error(`getPcbSize for shape "${e.shape}" not implemented for ${this.componentName}`)}_getPcbCircuitJsonBounds(){let{db:e}=this.root,t=e.pcb_plated_hole.get(this.pcb_plated_hole_id),i=this.getPcbSize();return{center:{x:t.x,y:t.y},bounds:{left:t.x-i.width/2,top:t.y+i.height/2,right:t.x+i.width/2,bottom:t.y-i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(e){let{db:t}=this.root;t.pcb_plated_hole.update(this.pcb_plated_hole_id,{x:e.x,y:e.y}),this.matchedPort?._setPositionFromLayout(e)}doInitialPortMatching(){let e=this.getPrimitiveContainer()?.selectAll("port");if(this.props.portHints){for(let t of e)if(t.isMatchingAnyOf(this.props.portHints)){this.matchedPort=t,t.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalPcbPositionBeforeLayout(),r=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,s=this.getSubcircuit();if(t.shape==="circle"){let o=e.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,outer_diameter:t.outerDiameter,hole_diameter:t.holeDiameter,shape:"circle",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=o.pcb_plated_hole_id,e.pcb_solder_paste.insert({layer:"top",shape:"circle",radius:t.outerDiameter/2,x:i.x,y:i.y,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),e.pcb_solder_paste.insert({layer:"bottom",shape:"circle",radius:t.outerDiameter/2,x:i.x,y:i.y,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(t.shape==="pill"&&t.rectPad){let o=e.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:t.outerWidth,outer_height:t.outerHeight,hole_width:t.holeWidth,hole_height:t.holeHeight,shape:"rotated_pill_hole_with_rect_pad",type:"pcb_plated_hole",port_hints:this.getNameAndAliases(),pcb_plated_hole_id:this.pcb_plated_hole_id,x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_shape:"rotated_pill",pad_shape:"rect",hole_ccw_rotation:t.pcbRotation??0,rect_ccw_rotation:t.pcbRotation??0,rect_pad_width:t.outerWidth,rect_pad_height:t.outerHeight,hole_offset_x:t.holeOffsetX,hole_offset_y:t.holeOffsetY});this.pcb_plated_hole_id=o.pcb_plated_hole_id}else if(t.shape==="pill"||t.shape==="oval"){let o=e.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:t.outerWidth,outer_height:t.outerHeight,hole_width:t.holeWidth,hole_height:t.holeHeight,shape:t.shape,port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,ccw_rotation:t.pcbRotation??0});this.pcb_plated_hole_id=o.pcb_plated_hole_id,e.pcb_solder_paste.insert({layer:"top",shape:t.shape,width:t.outerWidth,height:t.outerHeight,x:i.x,y:i.y,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),e.pcb_solder_paste.insert({layer:"bottom",shape:t.shape,width:t.outerWidth,height:t.outerHeight,x:i.x,y:i.y,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(t.shape==="circular_hole_with_rect_pad"){let o=e.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,hole_diameter:t.holeDiameter,rect_pad_width:t.rectPadWidth,rect_pad_height:t.rectPadHeight,shape:"circular_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_offset_x:t.holeOffsetX,hole_offset_y:t.holeOffsetY,rect_border_radius:t.rectBorderRadius??0});this.pcb_plated_hole_id=o.pcb_plated_hole_id}else if(t.shape==="pill_hole_with_rect_pad"){let o=e.pcb_plated_hole.insert({pcb_component_id:r,pcb_port_id:this.matchedPort?.pcb_port_id,hole_width:t.holeWidth,hole_height:t.holeHeight,rect_pad_width:t.rectPadWidth,rect_pad_height:t.rectPadHeight,hole_offset_x:t.holeOffsetX,hole_offset_y:t.holeOffsetY,shape:"pill_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=o.pcb_plated_hole_id}}doInitialPcbPortAttachment(){if(this.root?.pcbDisabled)return;let{db:e}=this.root;e.pcb_plated_hole.update(this.pcb_plated_hole_id,{pcb_port_id:this.matchedPort?.pcb_port_id})}},HS=class extends Te{constructor(){super(...arguments);d(this,"pcb_keepout_id",null);d(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Keepout",zodProps:nW}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let e=this.getSubcircuit(),{db:t}=this.root,{_parsedProps:i}=this,r=this._getGlobalPcbPositionBeforeLayout(),s=Js(this._computePcbGlobalTransformBeforeLayout()),o=Math.abs(s.rotation.angle*(180/Math.PI)-90)%180<.01,a=null;i.shape==="circle"?a=t.pcb_keepout.insert({layers:["top"],shape:"circle",radius:i.radius,center:{x:r.x,y:r.y},subcircuit_id:e?.subcircuit_id??void 0,pcb_group_id:e?.getGroup()?.pcb_group_id??void 0}):i.shape==="rect"&&(a=t.pcb_keepout.insert({layers:["top"],shape:"rect",...o?{width:i.height,height:i.width}:{width:i.width,height:i.height},center:{x:r.x,y:r.y},subcircuit_id:e?.subcircuit_id??void 0,pcb_group_id:e?.getGroup()?.pcb_group_id??void 0})),a&&(this.pcb_keepout_id=a.pcb_keepout_id)}},V_=class extends Te{constructor(){super(...arguments);d(this,"pcb_hole_id",null);d(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Hole",zodProps:AH}}getPcbSize(){let{_parsedProps:e}=this,t=e.shape==="pill",i=e.shape==="rect";return t?{width:e.width,height:e.height}:i?{width:e.width,height:e.height}:{width:e.diameter,height:e.diameter}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this.getSubcircuit(),r=this._getGlobalPcbPositionBeforeLayout();if(t.shape==="pill")if(t.pcbRotation&&t.pcbRotation!==0){let s=e.pcb_hole.insert({type:"pcb_hole",hole_shape:"rotated_pill",hole_width:t.width,hole_height:t.height,x:r.x,y:r.y,ccw_rotation:t.pcbRotation,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:i?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=s.pcb_hole_id}else{let s=e.pcb_hole.insert({type:"pcb_hole",hole_shape:"pill",hole_width:t.width,hole_height:t.height,x:r.x,y:r.y,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:i?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=s.pcb_hole_id}else if(t.shape==="rect"){let s=e.pcb_hole.insert({type:"pcb_hole",hole_shape:"rect",hole_width:t.width,hole_height:t.height,x:r.x,y:r.y,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:i?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=s.pcb_hole_id}else{let s=e.pcb_hole.insert({type:"pcb_hole",hole_shape:"circle",hole_diameter:t.diameter,x:r.x,y:r.y,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:i?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=s.pcb_hole_id}}_getPcbCircuitJsonBounds(){let{db:e}=this.root,t=e.pcb_hole.get(this.pcb_hole_id),i=this.getPcbSize();return{center:{x:t.x,y:t.y},bounds:{left:t.x-i.width/2,top:t.y-i.height/2,right:t.x+i.width/2,bottom:t.y+i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(e){let{db:t}=this.root;t.pcb_hole.update(this.pcb_hole_id,{x:e.x,y:e.y})}},JS=class extends Te{constructor(){super(...arguments);d(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenText",zodProps:yW}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this.getPrimitiveContainer(),r=this._getGlobalPcbPositionBeforeLayout(),{maybeFlipLayer:s,isFlipped:o}=this._getPcbPrimitiveFlippedHelpers(),a=this.getSubcircuit(),c=0;if(t.pcbRotation!==void 0&&t.pcbRotation!==0)c=t.pcbRotation;else{let f=this._computePcbGlobalTransformBeforeLayout();c=Js(f).rotation.angle*180/Math.PI}o&&(c=(c+180)%360);let l=new Set(t.layers);t.layer&&l.add(t.layer);let u=l.size>0?Array.from(l):["top"],p=t.fontSize??this.getInheritedProperty("pcbStyle")?.silkscreenFontSize??1;for(let f of u)e.pcb_silkscreen_text.insert({anchor_alignment:t.anchorAlignment,anchor_position:{x:r.x,y:r.y},font:t.font??"tscircuit2024",font_size:p,layer:s(f),text:t.text??"",ccw_rotation:c,pcb_component_id:i.pcb_component_id,subcircuit_id:a?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}getPcbSize(){let{_parsedProps:e}=this,t=e.fontSize??this.getInheritedProperty("pcbStyle")?.silkscreenFontSize??1,r=(e.text??"").length*t,s=t;return{width:r*t,height:s*t}}},$1=class extends Te{constructor(){super(...arguments);d(this,"pcb_cutout_id",null);d(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Cutout",zodProps:IH}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this.getSubcircuit(),r=this.getGroup()?.pcb_group_id??void 0,s=this._getGlobalPcbPositionBeforeLayout(),a=this.getPrimitiveContainer()?._parsedProps.pcbRotation??0,c;if(t.shape==="rect"){let l=typeof a=="string"?parseInt(a.replace("deg",""),10):a,u=Math.abs(l%180)===90,p={shape:"rect",center:s,width:u?t.height:t.width,height:u?t.width:t.height,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r};c=e.pcb_cutout.insert(p)}else if(t.shape==="circle"){let l={shape:"circle",center:s,radius:t.radius,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r};c=e.pcb_cutout.insert(l)}else if(t.shape==="polygon"){let l=this._computePcbGlobalTransformBeforeLayout(),p={shape:"polygon",points:t.points.map(f=>ze(l,f)),subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r};c=e.pcb_cutout.insert(p)}c&&(this.pcb_cutout_id=c.pcb_cutout_id)}getPcbSize(){let{_parsedProps:e}=this;if(e.shape==="rect")return{width:e.width,height:e.height};if(e.shape==="circle")return{width:e.radius*2,height:e.radius*2};if(e.shape==="polygon"){if(e.points.length===0)return{width:0,height:0};let t=1/0,i=-1/0,r=1/0,s=-1/0;for(let o of e.points)t=Math.min(t,o.x),i=Math.max(i,o.x),r=Math.min(r,o.y),s=Math.max(s,o.y);return{width:i-t,height:s-r}}return{width:0,height:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_cutout_id)return super._getPcbCircuitJsonBounds();let{db:e}=this.root,t=e.pcb_cutout.get(this.pcb_cutout_id);if(!t)return super._getPcbCircuitJsonBounds();if(t.shape==="rect")return{center:t.center,bounds:{left:t.center.x-t.width/2,top:t.center.y+t.height/2,right:t.center.x+t.width/2,bottom:t.center.y-t.height/2},width:t.width,height:t.height};if(t.shape==="circle")return{center:t.center,bounds:{left:t.center.x-t.radius,top:t.center.y+t.radius,right:t.center.x+t.radius,bottom:t.center.y-t.radius},width:t.radius*2,height:t.radius*2};if(t.shape==="polygon"){if(t.points.length===0)return super._getPcbCircuitJsonBounds();let i=1/0,r=-1/0,s=1/0,o=-1/0;for(let a of t.points)i=Math.min(i,a.x),r=Math.max(r,a.x),s=Math.min(s,a.y),o=Math.max(o,a.y);return{center:{x:(i+r)/2,y:(s+o)/2},bounds:{left:i,top:o,right:r,bottom:s},width:r-i,height:o-s}}return super._getPcbCircuitJsonBounds()}_setPositionFromLayout(e){if(!this.pcb_cutout_id)return;let{db:t}=this.root,i=t.pcb_cutout.get(this.pcb_cutout_id);if(i){if(i.shape==="rect"||i.shape==="circle")t.pcb_cutout.update(this.pcb_cutout_id,{...i,center:e});else if(i.shape==="polygon"){let r=this._getPcbCircuitJsonBounds().center,s=e.x-r.x,o=e.y-r.y,a=i.points.map(c=>({x:c.x+s,y:c.y+o}));t.pcb_cutout.update(this.pcb_cutout_id,{...i,points:a})}}}},VRt=({elm:n,pinLabels:e,layer:t,readableRotation:i,anchorAlignment:r})=>{let s=n.text.replace(/[{}]/g,"").toLowerCase(),o=s;if(Array.isArray(e)){let a=parseInt(s.replace(/[^\d]/g,""),10)-1;o=String(e[a]??s)}else typeof e=="object"&&(o=String(e[s]??s));return new JS({anchorAlignment:r||"center",text:o??s,layer:t||"top",fontSize:n.font_size+.2,pcbX:isNaN(n.anchor_position.x)?0:n.anchor_position.x,pcbY:n.anchor_position.y,pcbRotation:i??0})},GRt=(n,e)=>{let t=parseInt(n||"0",10),i;return e!=null?i=e-t:i=t,(i%360+360)%360},G_=({componentName:n,componentRotation:e,footprinterString:t,pinLabels:i,pcbPinLabels:r},s)=>{let o=[];for(let a of s)if(a.type==="pcb_smtpad"&&a.shape==="rect")o.push(new D1({pcbX:a.x,pcbY:a.y,layer:a.layer,shape:"rect",height:a.height,width:a.width,portHints:a.port_hints,rectBorderRadius:a.rect_border_radius}));else if(a.type==="pcb_smtpad"&&a.shape==="circle")o.push(new D1({pcbX:a.x,pcbY:a.y,layer:a.layer,shape:"circle",radius:a.radius,portHints:a.port_hints}));else if(a.type==="pcb_smtpad"&&a.shape==="pill")o.push(new D1({shape:"pill",height:a.height,width:a.width,radius:a.radius,portHints:a.port_hints,pcbX:a.x,pcbY:a.y,layer:a.layer}));else if(a.type==="pcb_silkscreen_path")o.push(new c9({layer:a.layer,route:a.route,strokeWidth:a.stroke_width}));else if(a.type==="pcb_plated_hole")a.shape==="circle"?o.push(new U_({pcbX:a.x,pcbY:a.y,shape:"circle",holeDiameter:a.hole_diameter,outerDiameter:a.outer_diameter,portHints:a.port_hints})):a.shape==="circular_hole_with_rect_pad"?o.push(new U_({pcbX:a.x,pcbY:a.y,shape:"circular_hole_with_rect_pad",holeDiameter:a.hole_diameter,rectPadHeight:a.rect_pad_height,rectPadWidth:a.rect_pad_width,portHints:a.port_hints,rectBorderRadius:a.rect_border_radius,holeOffsetX:a.hole_offset_x,holeOffsetY:a.hole_offset_y})):a.shape==="pill"||a.shape==="oval"?o.push(new U_({pcbX:a.x,pcbY:a.y,shape:a.shape,holeWidth:a.hole_width,holeHeight:a.hole_height,outerWidth:a.outer_width,outerHeight:a.outer_height,portHints:a.port_hints})):a.shape==="pill_hole_with_rect_pad"&&o.push(new U_({pcbX:a.x,pcbY:a.y,shape:"pill_hole_with_rect_pad",holeShape:"pill",padShape:"rect",holeWidth:a.hole_width,holeHeight:a.hole_height,rectPadWidth:a.rect_pad_width,rectPadHeight:a.rect_pad_height,portHints:a.port_hints,holeOffsetX:a.hole_offset_x,holeOffsetY:a.hole_offset_y}));else if(a.type==="pcb_keepout"&&a.shape==="circle")o.push(new HS({pcbX:a.center.x,pcbY:a.center.y,shape:"circle",radius:a.radius}));else if(a.type==="pcb_keepout"&&a.shape==="rect")o.push(new HS({pcbX:a.center.x,pcbY:a.center.y,shape:"rect",width:a.width,height:a.height}));else if(a.type==="pcb_hole"&&a.hole_shape==="circle")o.push(new V_({pcbX:a.x,pcbY:a.y,diameter:a.hole_diameter}));else if(a.type==="pcb_hole"&&a.hole_shape==="rect")o.push(new V_({pcbX:a.x,pcbY:a.y,shape:"rect",width:a.hole_width,height:a.hole_height}));else if(a.type==="pcb_hole"&&a.hole_shape==="pill")o.push(new V_({pcbX:a.x,pcbY:a.y,shape:"pill",width:a.hole_width,height:a.hole_height}));else if(a.type==="pcb_hole"&&a.hole_shape==="rotated_pill")o.push(new V_({pcbX:a.x,pcbY:a.y,shape:"pill",width:a.hole_width,height:a.hole_height,pcbRotation:a.ccw_rotation}));else if(a.type==="pcb_cutout")a.shape==="rect"?o.push(new $1({pcbX:a.center.x,pcbY:a.center.y,shape:"rect",width:a.width,height:a.height})):a.shape==="circle"?o.push(new $1({pcbX:a.center.x,pcbY:a.center.y,shape:"circle",radius:a.radius})):a.shape==="polygon"&&o.push(new $1({shape:"polygon",points:a.points}));else if(a.type==="pcb_silkscreen_text"){let c=GRt(e,a.ccw_rotation);t?.includes("pinrow")&&a.text.includes("PIN")?o.push(VRt({elm:a,pinLabels:r??i??{},layer:a.layer,readableRotation:c,anchorAlignment:a.anchor_alignment})):o.push(new JS({anchorAlignment:a.anchor_alignment||"center",text:n,fontSize:a.font_size+.2,pcbX:Number.isNaN(a.anchor_position.x)?0:a.anchor_position.x,pcbY:a.anchor_position.y,pcbRotation:c??0}))}else a.type==="pcb_trace"&&o.push(new l9({route:a.route}));return o};function QS(n){let e=1/0,t=1/0,i=-1/0,r=-1/0,s=!1;for(let c of n)if(c.isPcbPrimitive&&!c.componentName.startsWith("Silkscreen")){let{x:l,y:u}=c._getGlobalPcbPositionBeforeLayout(),{width:p,height:f}=c.getPcbSize();e=Math.min(e,l-p/2),t=Math.min(t,u-f/2),i=Math.max(i,l+p/2),r=Math.max(r,u+f/2),s=!0}else if(c.children.length>0){let l=QS(c.children);(l.width>0||l.height>0)&&(e=Math.min(e,l.minX),t=Math.min(t,l.minY),i=Math.max(i,l.maxX),r=Math.max(r,l.maxY),s=!0)}if(!s)return{minX:0,minY:0,maxX:0,maxY:0,width:0,height:0};let o=i-e,a=r-t;return o<0&&(o=0),a<0&&(a=0),{minX:e,minY:t,maxX:i,maxY:r,width:o,height:a}}function tet(n){let e=n%360;return e<0?e+360:e}function HRt(n,e,t,i){return i==="counterclockwise"?t>=e?n>=e&&n<=t:n>=e||n<=t:t<=e?n<=e&&n>=t:n<=e||n>=t}function WRt(n){let e=n.center,t=n.radius,i=n.start_angle_degrees,r=n.end_angle_degrees,s=n.direction??"counterclockwise";if(!e||typeof e.x!="number"||typeof e.y!="number"||typeof t!="number"||typeof i!="number"||typeof r!="number")return null;let o=tet(i),a=tet(r),c=new Set([o,a]),l=[0,90,180,270];for(let g of l)HRt(g,o,a,s)&&c.add(g);let u=1/0,p=1/0,f=-1/0,y=-1/0;for(let g of c){let x=g*Math.PI/180,v=e.x+t*Math.cos(x),S=e.y+t*Math.sin(x);u=Math.min(u,v),f=Math.max(f,v),p=Math.min(p,S),y=Math.max(y,S)}return!Number.isFinite(u)||!Number.isFinite(p)?null:{minX:u,maxX:f,minY:p,maxY:y}}function Ret(n){let e=1/0,t=1/0,i=-1/0,r=-1/0;for(let s of n){let o,a,c,l;if(s.type==="schematic_component")o=s.center?.x,a=s.center?.y,c=s.size?.width,l=s.size?.height;else if(s.type==="schematic_box")o=s.x,a=s.y,c=s.width,l=s.height;else if(s.type==="schematic_port")o=s.center?.x,a=s.center?.y,c=.2,l=.2;else if(s.type==="schematic_text")o=s.position?.x,a=s.position?.y,c=(s.text?.length??0)*.1,l=.2;else if(s.type==="schematic_line"){let u=s.x1??0,p=s.y1??0,f=s.x2??0,y=s.y2??0;o=(u+f)/2,a=(p+y)/2,c=Math.abs(f-u),l=Math.abs(y-p)}else if(s.type==="schematic_rect")o=s.center?.x,a=s.center?.y,c=s.width,l=s.height;else if(s.type==="schematic_circle"){o=s.center?.x,a=s.center?.y;let u=s.radius;typeof u=="number"&&(c=u*2,l=u*2)}else if(s.type==="schematic_arc"){let u=WRt(s);u&&(e=Math.min(e,u.minX),i=Math.max(i,u.maxX),t=Math.min(t,u.minY),r=Math.max(r,u.maxY));continue}typeof o=="number"&&typeof a=="number"&&typeof c=="number"&&typeof l=="number"&&(e=Math.min(e,o-c/2),i=Math.max(i,o+c/2),t=Math.min(t,a-l/2),r=Math.max(r,a+l/2))}return{minX:e,maxX:i,minY:t,maxY:r}}function qRt(n,e){let t=e.x-n.x,i=e.y-n.y;return Math.abs(t)>Math.abs(i)?t>=0?"right":"left":i>=0?"up":"down"}var eet=n=>{if(n.length<=1)return!0;let e=n.map(s=>{let o=s._getPcbCircuitJsonBounds();return{left:o.bounds.left,right:o.bounds.right,top:o.bounds.top,bottom:o.bounds.bottom}}),t=Array(e.length).fill(!1).map(()=>Array(e.length).fill(!1));for(let s=0;s<e.length;s++)for(let o=s+1;o<e.length;o++){let a=e[s],c=e[o];t[s][o]=t[o][s]=!(a.right<c.left||a.left>c.right||a.bottom>c.top||a.top<c.bottom)}let i=new Set,r=s=>{i.add(s);for(let o=0;o<e.length;o++)t[s][o]&&!i.has(o)&&r(o)};return r(0),i.size===e.length},net=n=>{if(n.length===0)throw new Error("Cannot get center of empty PCB primitives array");let e=n.map(r=>r._getPcbCircuitJsonBounds().center).filter(Boolean),t=e.reduce((r,s)=>r+s.x,0),i=e.reduce((r,s)=>r+s.y,0);return{x:t/e.length,y:i/e.length}},ZRt=h.object({name:h.string().optional(),pinNumber:h.number().optional(),aliases:h.array(h.string()).optional(),layer:h.string().optional(),layers:h.array(h.string()).optional(),schX:h.number().optional(),schY:h.number().optional(),direction:h.enum(["up","down","left","right"]).optional(),connectsTo:h.union([h.string(),h.array(h.string())]).optional()}),Vi=class extends Te{constructor(e,t={}){if(!e.name&&e.pinNumber!==void 0&&(e.name=`pin${e.pinNumber}`),!e.name)throw new Error("Port must have a name or a pinNumber");super(e);d(this,"source_port_id",null);d(this,"pcb_port_id",null);d(this,"schematic_port_id",null);d(this,"schematicSymbolPortDef",null);d(this,"matchedComponents");d(this,"facingDirection",null);d(this,"originDescription",null);t.originDescription&&(this.originDescription=t.originDescription),this.matchedComponents=[]}get config(){return{componentName:"Port",zodProps:ZRt}}isGroupPort(){return this.parent?.componentName==="Group"}isComponentPort(){return!this.isGroupPort()}_getConnectedPortsFromConnectsTo(){let{_parsedProps:e}=this,t=e.connectsTo;if(!t)return[];let i=[],r=Array.isArray(t)?t:[t];for(let s of r){let o=this.getSubcircuit().selectOne(s,{type:"port"});o&&i.push(o)}return i}_isBoardPinoutFromAttributes(){let e=this.parent;if(e?._parsedProps?.pinAttributes){let t=e._parsedProps.pinAttributes;for(let i of this.getNameAndAliases())if(t[i]?.includeInBoardPinout)return!0}}_getGlobalPcbPositionBeforeLayout(){let e=this.matchedComponents.find(i=>i.isPcbPrimitive),t=this.parent;if(t&&!t.props.footprint)throw new Error(`${t.componentName} "${t.props.name}" does not have a footprint. Add a footprint prop, e.g. <${t.componentName.toLowerCase()} footprint="..." />`);if(!e)throw new Error(`Port ${this} has no matching PCB primitives. This often means the footprint's pads lack matching port hints.`);return e?._getGlobalPcbPositionBeforeLayout()??{x:0,y:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_port_id)return super._getPcbCircuitJsonBounds();let{db:e}=this.root,t=e.pcb_port.get(this.pcb_port_id);return{center:{x:t.x,y:t.y},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getGlobalPcbPositionAfterLayout(){return this._getPcbCircuitJsonBounds().center}_getPortsInternallyConnectedToThisPort(){let e=this.parent;if(!e||!e._getInternallyConnectedPins)return[];let t=e._getInternallyConnectedPins();for(let i of t)if(i.some(r=>r===this))return i;return[]}_hasSchematicPort(){let{schX:e,schY:t}=this._parsedProps;if(e!==void 0&&t!==void 0)return!0;let i=this.getParentNormalComponent();if(i?.getSchematicSymbol())return!!(this.schematicSymbolPortDef||this._getPortsInternallyConnectedToThisPort().some(a=>a.schematicSymbolPortDef));let s=i?._getSchematicBoxDimensions();return!!(s&&this.props.pinNumber!==void 0&&s.getPortPositionByPinNumber(this.props.pinNumber))}_getGlobalSchematicPositionBeforeLayout(){let{schX:e,schY:t}=this._parsedProps;if(e!==void 0&&t!==void 0)return{x:e,y:t};let i=this.getParentNormalComponent(),r=i?.getSchematicSymbol();if(r){let o=this.schematicSymbolPortDef;if(!o&&(o=this._getPortsInternallyConnectedToThisPort().find(c=>c.schematicSymbolPortDef)?.schematicSymbolPortDef??null,!o))throw new Error(`Couldn't find schematicSymbolPortDef for port ${this.getString()}, searched internally connected ports and none had a schematicSymbolPortDef. Why are we trying to get the schematic position of this port?`);let a=mi(i.computeSchematicGlobalTransform(),Nn(-r.center.x,-r.center.y));return ze(a,o)}let s=i?._getSchematicBoxDimensions();if(s&&this.props.pinNumber!==void 0){let o=s.getPortPositionByPinNumber(this.props.pinNumber);if(!o)throw new Error(`Couldn't find position for schematic_port for port ${this.getString()} inside of the schematic box`);return ze(i.computeSchematicGlobalTransform(),o)}throw new Error(`Couldn't find position for schematic_port for port ${this.getString()}`)}_getGlobalSchematicPositionAfterLayout(){let{db:e}=this.root;if(!this.schematic_port_id)throw new Error(`Can't get schematic port position after layout for "${this.getString()}", no schematic_port_id`);let t=e.schematic_port.get(this.schematic_port_id);if(!t)throw new Error(`Schematic port not found when trying to get post-layout position: ${this.schematic_port_id}`);return t.center}registerMatch(e){this.matchedComponents.push(e)}getNameAndAliases(){let{_parsedProps:e}=this;return Array.from(new Set([...e.name?[e.name]:[],...e.aliases??[],...typeof e.pinNumber=="number"?[`pin${e.pinNumber}`,e.pinNumber.toString()]:[],...this.externallyAddedAliases??[]]))}_getMatchingPinAttributes(){let e=this.parent?._parsedProps?.pinAttributes;if(!e)return[];let t=[];for(let i of this.getNameAndAliases()){let r=e[i];r&&t.push(r)}return t}_shouldIncludeInBoardPinout(){return this._getMatchingPinAttributes().some(e=>e.includeInBoardPinout===!0)}isMatchingPort(e){return this.isMatchingAnyOf(e.getNameAndAliases())}getPortSelector(){return`.${(this.getParentNormalComponent()??this.parent)?.props.name} > port.${this.props.name}`}getAvailablePcbLayers(){let{layer:e,layers:t}=this._parsedProps;return t||(e?[e]:Array.from(new Set(this.matchedComponents.flatMap(i=>i.getAvailablePcbLayers()))))}_getDirectlyConnectedTraces(){return this.getSubcircuit().selectAll("trace").filter(i=>!i._couldNotFindPort).filter(i=>i._isExplicitlyConnectedToPort(this))}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=this.getNameAndAliases(),r=this.getParentNormalComponent(),o=(this.parent?.source_component_id?this.parent:r)?.source_component_id??null,a=e.source_port.insert({name:t.name,pin_number:t.pinNumber,port_hints:i,source_component_id:o,subcircuit_id:this.getSubcircuit()?.subcircuit_id});this.source_port_id=a.source_port_id}doInitialSourceParentAttachment(){let{db:e}=this.root,t=this.getParentNormalComponent(),i=this.parent?.source_component_id?this.parent:t;if(this.isGroupPort()){e.source_port.update(this.source_port_id,{source_component_id:null,subcircuit_id:this.getSubcircuit()?.subcircuit_id});return}if(!i?.source_component_id)throw new Error(`${this.getString()} has no parent source component (parent: ${this.parent?.getString()})`);e.source_port.update(this.source_port_id,{source_component_id:i.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id}),this.source_component_id=i.source_component_id}doInitialPcbPortRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{matchedComponents:t}=this;if(this.isGroupPort()){let a=this._getConnectedPortsFromConnectsTo();if(a.length===0)return;let c=a[0];if(!c.pcb_port_id)return;let l=e.pcb_port.get(c.pcb_port_id),u={x:l.x,y:l.y},p=this.getSubcircuit(),f=e.pcb_port.insert({pcb_component_id:void 0,layers:c.getAvailablePcbLayers(),subcircuit_id:p?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...u,source_port_id:this.source_port_id,is_board_pinout:!1});this.pcb_port_id=f.pcb_port_id;return}let i=this.getParentNormalComponent(),r=this.parent?.pcb_component_id?this.parent:i;if(!r?.pcb_component_id)throw new Error(`${this.getString()} has no parent pcb component, cannot render pcb_port (parent: ${this.parent?.getString()}, parentNormalComponent: ${i?.getString()})`);let s=t.filter(a=>a.isPcbPrimitive);if(s.length===0)return;let o=null;if(s.length===1&&(o=s[0]._getPcbCircuitJsonBounds().center),s.length>1){if(!eet(s))throw new Error(`${this.getString()} has multiple non-overlapping pcb matches, unclear how to place pcb_port: ${s.map(a=>a.getString()).join(", ")}. (Note: tscircuit core does not currently allow you to specify internally connected pcb primitives with the same port hints, try giving them different port hints and specifying they are connected externally- or file an issue)`);o=net(s)}if(o){let a=this.getSubcircuit(),c=this._shouldIncludeInBoardPinout(),l=e.pcb_port.insert({pcb_component_id:r.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:a?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...c?{is_board_pinout:!0}:{},...o,source_port_id:this.source_port_id,is_board_pinout:this._isBoardPinoutFromAttributes()});this.pcb_port_id=l.pcb_port_id}else{let a=s[0];throw new Error(`${a.getString()} does not have a center or _getGlobalPcbPositionBeforeLayout method (needed for pcb_port placement)`)}}updatePcbPortRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root;if(this.pcb_port_id)return;if(this.isGroupPort()){let l=this._getConnectedPortsFromConnectsTo();if(l.length===0)return;let u=l[0];if(!u.pcb_port_id)return;let p=e.pcb_port.get(u.pcb_port_id),f={x:p.x,y:p.y},y=this.getSubcircuit(),g=e.pcb_port.insert({pcb_component_id:void 0,layers:u.getAvailablePcbLayers(),subcircuit_id:y?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...f,source_port_id:this.source_port_id,is_board_pinout:!1});this.pcb_port_id=g.pcb_port_id;return}let t=this.matchedComponents.filter(l=>l.isPcbPrimitive);if(t.length===0)return;let i=null;if(t.length===1&&(i=t[0]._getPcbCircuitJsonBounds().center),t.length>1)try{eet(t)&&(i=net(t))}catch{}if(!i)return;let r=this.getParentNormalComponent(),s=this.parent?.pcb_component_id?this.parent:r,o=this.getSubcircuit(),a=this._shouldIncludeInBoardPinout(),c=e.pcb_port.insert({pcb_component_id:s?.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...a?{is_board_pinout:!0}:{},...i,source_port_id:this.source_port_id,is_board_pinout:this._isBoardPinoutFromAttributes()});this.pcb_port_id=c.pcb_port_id}_getBestDisplayPinLabel(){let{db:e}=this.root,t=e.source_port.get(this.source_port_id),i=[];for(let o of t?.port_hints??[])o.match(/^(pin)?\d+$/)||o.match(/^(left|right)/)&&!t?.name.match(/^(left|right)/)||i.push(o);if(this.getParentNormalComponent()?.props?.showPinAliases&&i.length>0)return i.join("/");if(i.length>0)return i[0]}doInitialSchematicPortRender(){let{db:e}=this.root,{_parsedProps:t}=this,{schX:i,schY:r}=t,s=i!==void 0&&r!==void 0?this.getParentNormalComponent():this.getPrimitiveContainer();if(!s||!this._hasSchematicPort())return;let o=s._getGlobalSchematicPositionBeforeLayout(),a=this._getGlobalSchematicPositionBeforeLayout(),c=null,l=s._getSchematicBoxDimensions();l&&t.pinNumber!==void 0&&(c=l.getPortPositionByPinNumber(t.pinNumber)),this.getSubcircuit().props._schDebugObjectsEnabled&&e.schematic_debug_object.insert({shape:"rect",center:a,size:{width:.1,height:.1},label:"obstacle"}),c?.side?this.facingDirection={left:"left",right:"right",top:"up",bottom:"down"}[c.side]:this.facingDirection=qRt(o,a);let u=this._getBestDisplayPinLabel(),f={type:"schematic_port",schematic_component_id:this.getParentNormalComponent()?.schematic_component_id,center:a,source_port_id:this.source_port_id,facing_direction:this.facingDirection,distance_from_component_edge:.4,side_of_component:c?.side,pin_number:t.pinNumber,true_ccw_index:c?.trueIndex,display_pin_label:u,is_connected:!1};for(let g of this._getMatchingPinAttributes())g.requiresPower&&(f.has_input_arrow=!0),g.providesPower&&(f.has_output_arrow=!0);let y=e.schematic_port.insert(f);this.schematic_port_id=y.schematic_port_id}_getSubcircuitConnectivityKey(){return this.root?.db.source_port.get(this.source_port_id)?.subcircuit_connectivity_map_key}_setPositionFromLayout(e){let{db:t}=this.root;this.pcb_port_id&&t.pcb_port.update(this.pcb_port_id,{x:e.x,y:e.y})}_hasMatchedPcbPrimitive(){return this.matchedComponents.some(e=>e.isPcbPrimitive)}_getNetLabelText(){return`${this.parent?.props.name}_${this.props.name}`}},Oet=n=>{let e=n.find(t=>/^(pin)?\d+$/.test(t));return e?Number.parseInt(e.replace(/^pin/,"")):null};function O1(n,e){let t=Oet(n);if(!t)return null;let r=[...n.filter(s=>s.toString()!==t.toString()&&s!==`pin${t}`),...e?.additionalAliases?.[`pin${t}`]??[]];return new Vi({pinNumber:t,aliases:r})}var KRt=n=>{for(let e of["leftSide","rightSide","topSide","bottomSide"])if(e in n&&typeof n[e]=="number")throw new Error(`A number was specified for "${e}", you probably meant to use "size" not "side"`);return"leftSide"in n||"rightSide"in n||"topSide"in n||"bottomSide"in n},JRt=n=>{if(KRt(n))return{leftSize:n.leftSide?.pins.length??0,rightSize:n.rightSide?.pins.length??0,topSize:n.topSide?.pins.length??0,bottomSize:n.bottomSide?.pins.length??0};let{leftSize:e=0,rightSize:t=0,topSize:i=0,bottomSize:r=0}=n;return{leftSize:e,rightSize:t,topSize:i,bottomSize:r}},BS=.4;function Let(n){let e=n;return e.leftSide!==void 0||e.rightSide!==void 0||e.topSide!==void 0||e.bottomSide!==void 0}var QRt=n=>{let e=n.portDistanceFromEdge??.4,t=n.schPortArrangement?JRt(n.schPortArrangement):null,i={left:0,right:0,top:0,bottom:0},r=n.pinCount??null;if(r===null)if(t)r=t.leftSize+t.rightSize+t.topSize;else throw new Error("Could not determine pin count for the schematic box");if(r&&!t){let g=Math.floor(r/2);t={leftSize:r-g,rightSize:g,topSize:0,bottomSize:0}}t||(t={leftSize:0,rightSize:0,topSize:0,bottomSize:0});let s=({side:g,sideIndex:x,truePinIndex:v})=>{if(!n.schPortArrangement||!Let(n.schPortArrangement))return v+1;let S={left:"top-to-bottom",bottom:"left-to-right",right:"bottom-to-top",top:"right-to-left"}[g],P=n.schPortArrangement?.[`${g}Side`]?.direction??S,T=n.schPortArrangement?.[`${g}Side`]?.pins,k=x;return P!==S&&(k=T.length-x-1),j1(T[k],n.pinLabels)},o=[],a=0,c=0;for(let g=0;g<t.leftSize;g++){let x=s({side:"left",sideIndex:g,truePinIndex:c}),v=n.numericSchPinStyle?.[`pin${x}`]??n.numericSchPinStyle?.[x];v?.topMargin&&(a+=v.topMargin),o.push({trueIndex:c,pinNumber:x,side:"left",distanceFromOrthogonalEdge:a}),v?.bottomMargin&&(a+=v.bottomMargin),g===t.leftSize-1?i.left=a:a+=n.schPinSpacing,c++}a=0;for(let g=0;g<t.bottomSize;g++){let x=s({side:"bottom",sideIndex:g,truePinIndex:c}),v=n.numericSchPinStyle?.[`pin${x}`]??n.numericSchPinStyle?.[x];v?.leftMargin&&(a+=v.leftMargin),o.push({trueIndex:c,pinNumber:x,side:"bottom",distanceFromOrthogonalEdge:a}),v?.rightMargin&&(a+=v.rightMargin),g===t.bottomSize-1?i.bottom=a:a+=n.schPinSpacing,c++}a=0;for(let g=0;g<t.rightSize;g++){let x=s({side:"right",sideIndex:g,truePinIndex:c}),v=n.numericSchPinStyle?.[`pin${x}`]??n.numericSchPinStyle?.[x];v?.bottomMargin&&(a+=v.bottomMargin),o.push({trueIndex:c,pinNumber:x,side:"right",distanceFromOrthogonalEdge:a}),v?.topMargin&&(a+=v.topMargin),g===t.rightSize-1?i.right=a:a+=n.schPinSpacing,c++}a=0;for(let g=0;g<t.topSize;g++){let x=s({side:"top",sideIndex:g,truePinIndex:c}),v=n.numericSchPinStyle?.[`pin${x}`]??n.numericSchPinStyle?.[x];v?.rightMargin&&(a+=v.rightMargin),o.push({trueIndex:c,pinNumber:x,side:"top",distanceFromOrthogonalEdge:a}),v?.leftMargin&&(a+=v.leftMargin),g===t.topSize-1?i.top=a:a+=n.schPinSpacing,c++}let l=n.schWidth;if(l===void 0){l=Math.max(i.top+BS,i.bottom+BS),n.pinLabels&&o.filter(P=>P.side==="left"||P.side==="right").some(P=>n.pinLabels?.[`pin${P.pinNumber}`]||n.pinLabels?.[P.pinNumber])&&(l=Math.max(l,.5));let g=n.pinLabels?Math.max(...Object.values(n.pinLabels).map(v=>v.length*.1)):0,x=g>0?1.1:0;l=Math.max(l,g+x)}let u=n.schHeight;u||(u=Math.max(i.left+BS,i.right+BS));let p={left:{x:-l/2-e,y:i.left/2},bottom:{x:-i.bottom/2,y:-u/2-e},right:{x:l/2+e,y:-i.right/2},top:{x:i.top/2,y:u/2+e}},f={left:{x:0,y:-1},right:{x:0,y:1},top:{x:-1,y:0},bottom:{x:1,y:0}},y=o.map(g=>{let{distanceFromOrthogonalEdge:x,side:v}=g,S=p[v],P=f[v];return{x:S.x+x*P.x,y:S.y+x*P.y,...g}});return{getPortPositionByPinNumber(g){let x=y.find(v=>v.pinNumber.toString()===g.toString());return x||null},getSize(){return{width:l,height:u}},getSizeIncludingPins(){return{width:l+(t.leftSize||t.rightSize?.4:0),height:u+(t.topSize||t.bottomSize?.4:0)}},pinCount:r}},tOt=(0,Fet.default)("tscircuit:core:footprint"),zet=class extends Te{get config(){return{componentName:"Footprint",zodProps:OH}}doInitialPcbFootprintLayout(){if(this.root?.pcbDisabled)return;let n=this.children.filter(p=>p.componentName==="Constraint");if(n.length===0)return;let{isFlipped:e}=this._getPcbPrimitiveFlippedHelpers(),t=p=>e&&"left"in p&&"right"in p?{...p,left:p.right,right:p.left}:p,i=n.flatMap(p=>p._getAllReferencedComponents().componentsWithSelectors).map(({component:p,selector:f,componentSelector:y,edge:g})=>({component:p,selector:f,componentSelector:y,edge:g,bounds:p._getPcbCircuitJsonBounds()}));if(i.some(p=>p.edge))throw new Error("edge constraints not implemented yet for footprint layout, contributions welcome!");function r(p){return i.find(({selector:f})=>f===p)}let s=new e_,o={};function a(p){return p in o||(o[p]=new Ca(p),s.addEditVariable(o[p],Rn.weak)),o[p]}for(let{selector:p,bounds:f}of i){let y=a(`${p}_x`),g=a(`${p}_y`);s.suggestValue(y,f.center.x),s.suggestValue(g,f.center.y)}for(let p of n){let f=p._parsedProps;if("xDist"in f){let{xDist:y,left:g,right:x,edgeToEdge:v,centerToCenter:S}=t(f),P=a(`${g}_x`),T=a(`${x}_x`),k=r(g)?.bounds,C=r(x)?.bounds;if(S){let E=new Dn(T,[-1,P]);s.addConstraint(new Pi(E,si.Eq,f.xDist,Rn.required))}else if(v){let E=new Dn(T,-C.width/2,[-1,P],-k.width/2);s.addConstraint(new Pi(E,si.Eq,f.xDist,Rn.required))}}else if("yDist"in f){let{yDist:y,top:g,bottom:x,edgeToEdge:v,centerToCenter:S}=f,P=a(`${g}_y`),T=a(`${x}_y`),k=r(g)?.bounds,C=r(x)?.bounds;if(S){let E=new Dn(P,[-1,T]);s.addConstraint(new Pi(E,si.Eq,f.yDist,Rn.required))}else if(v){let E=new Dn(P,k.height/2,[-1,T],-C.height/2);s.addConstraint(new Pi(E,si.Eq,f.yDist,Rn.required))}}else if("sameY"in f){let{for:y}=f;if(y.length<2)continue;let g=y.map(v=>a(`${v}_y`)),x=new Dn(...g.slice(1));s.addConstraint(new Pi(x,si.Eq,g[0],Rn.required))}else if("sameX"in f){let{for:y}=f;if(y.length<2)continue;let g=y.map(v=>a(`${v}_x`)),x=new Dn(...g.slice(1));s.addConstraint(new Pi(x,si.Eq,g[0],Rn.required))}}s.updateVariables(),tOt.enabled&&(console.log("Solution to layout constraints:"),console.table(Object.entries(o).map(([p,f])=>({var:p,val:f.value()}))));let c={left:1/0,right:-1/0,top:-1/0,bottom:1/0};for(let{selector:p,bounds:{width:f,height:y}}of i){let g=a(`${p}_x`),x=a(`${p}_y`),v=g.value()-f/2,S=g.value()+f/2,P=x.value()+y/2,T=x.value()-y/2;c.left=Math.min(c.left,v),c.right=Math.max(c.right,S),c.top=Math.max(c.top,P),c.bottom=Math.min(c.bottom,T)}let l={x:-(c.right+c.left)/2,y:-(c.top+c.bottom)/2},u=this.getPrimitiveContainer()._getGlobalPcbPositionBeforeLayout();l.x+=u.x,l.y+=u.y;for(let{component:p,selector:f}of i){let y=a(`${f}_x`),g=a(`${f}_y`);p._setPositionFromLayout({x:y.value()+l.x,y:g.value()+l.y})}}},Det=n=>{if(!n)return null;let t=n.split("?")[0].split("#")[0],i=t.split("/").pop()??t;return i.includes(".")?i.split(".").pop()?.toLowerCase()??null:null},eOt=(n,e)=>{let t=n.replace(/\/+$/,""),i=e.replace(/^\/+/,"");return`${t}/${i}`},$et=(n,e)=>{if(!e||!n.startsWith("/"))return n;try{let t=new URL(e);return t.pathname!=="/"&&n.startsWith(t.pathname)?new URL(n,t.origin).toString():eOt(e,n)}catch{return n}},VA=h.union([h.number(),h.string()]),iet=h.object({x:VA,y:VA,z:VA}),jet=class extends Te{get config(){return{componentName:"CadModel",zodProps:sW}}doInitialCadModelRender(){let n=this._findParentWithPcbComponent();if(!n||!n.pcb_component_id)return;let{db:e}=this.root,{boardThickness:t=0}=this.root?._getBoard()??{},i=n._getPcbCircuitJsonBounds(),r=e.pcb_component.get(n.pcb_component_id),s=this._parsedProps;if(!s||typeof s.modelUrl!="string"&&typeof s.stepUrl!="string")return;let o=n._computePcbGlobalTransformBeforeLayout(),c=Js(o).rotation.angle*180/Math.PI,l=iet.parse({x:0,y:0,z:0});if(typeof s.rotationOffset=="number")l.z=Number(s.rotationOffset);else if(typeof s.rotationOffset=="object"){let v=iet.parse(s.rotationOffset);l.x=Number(v.x),l.y=Number(v.y),l.z=Number(v.z)}let u=uw.parse({x:s.pcbX??0,y:s.pcbY??0,z:s.pcbZ??0,...typeof s.positionOffset=="object"?s.positionOffset:{}}),p=s.zOffsetFromSurface!==void 0?X.parse(s.zOffsetFromSurface):0,f=n.props.layer==="bottom"?"bottom":"top",y=s.modelUrl?Det(s.modelUrl):void 0,g={};if(y==="stl"?g.model_stl_url=this._addCachebustToModelUrl(s.modelUrl):y==="obj"?g.model_obj_url=this._addCachebustToModelUrl(s.modelUrl):y==="gltf"?g.model_gltf_url=this._addCachebustToModelUrl(s.modelUrl):y==="glb"?g.model_glb_url=this._addCachebustToModelUrl(s.modelUrl):y==="step"||y==="stp"?g.model_step_url=this._addCachebustToModelUrl(s.modelUrl):y==="wrl"||y==="vrml"?g.model_wrl_url=this._addCachebustToModelUrl(s.modelUrl):g.model_stl_url=this._addCachebustToModelUrl(s.modelUrl),s.stepUrl){let v=this._addCachebustToModelUrl(s.stepUrl);v&&(g.model_step_url=v)}let x=e.cad_component.insert({position:{x:i.center.x+Number(u.x),y:i.center.y+Number(u.y),z:(f==="bottom"?-t/2:t/2)+(f==="bottom"?-p:p)+Number(u.z)},rotation:{x:Number(l.x),y:(f==="top"?0:180)+Number(l.y),z:f==="bottom"?-(c+Number(l.z))+180:c+Number(l.z)},pcb_component_id:n.pcb_component_id,source_component_id:n.source_component_id,model_unit_to_mm_scale_factor:typeof s.modelUnitToMmScale=="number"?s.modelUnitToMmScale:void 0,...g});this.cad_component_id=x.cad_component_id}_findParentWithPcbComponent(){let n=this.parent;for(;n&&!n.pcb_component_id;)n=n.parent;return n}_addCachebustToModelUrl(n){if(!n)return n;let e=this.root?.platform?.projectBaseUrl,t=$et(n,e);if(!t.includes("modelcdn.tscircuit.com"))return t;let i=this.root?.getClientOrigin()??"";return`${t}${t.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(i)}`}},Bet=class extends Te{constructor(){super(...arguments);d(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"CadAssembly",zodProps:rW}}},nOt=(n,e)=>{if(!n)return;let t={};for(let[i,r]of Object.entries(n)){let s=j1(i,e),o={leftMargin:r.marginLeft??r.leftMargin,rightMargin:r.marginRight??r.rightMargin,topMargin:r.marginTop??r.topMargin,bottomMargin:r.marginBottom??r.bottomMargin};t[`pin${s}`]={...t[`pin${s}`],...o}}return t},ret=class{constructor({input:n}){d(this,"input");this.input=n}solveAndMapToTraces(){let n=[];for(let e of this.input.connections){if(e.pointsToConnect.length!==2)continue;let[t,i]=e.pointsToConnect,r={type:"pcb_trace",pcb_trace_id:"",connection_name:e.name,route:[{route_type:"wire",x:t.x,y:t.y,layer:"top",width:.1},{route_type:"wire",x:i.x,y:i.y,layer:"top",width:.1}]};n.push(r)}return n}},iOt=n=>{let e=Math.min(...n.map(s=>s.center.x)),t=Math.max(...n.map(s=>s.center.x)),i=Math.min(...n.map(s=>s.center.y)),r=Math.max(...n.map(s=>s.center.y));return{minX:e,maxX:t,minY:i,maxY:r}},set=["top","bottom","inner1","inner2"],VS=(n,e=[])=>{let t=[];if(e.length===0){let a=n[0].layers;for(let c of a)t.push(...VS(n.slice(1),[c]));return t}if(n.length===0)return[];let i=n[0],r=i.via||i.optional_via,s=e[e.length-1];if(n.length===1){let a=i;return a.layers&&r?a.layers.map(c=>({layer_path:[...e,c]})):a.layers?.includes(s)?[{layer_path:[...e,s]}]:[]}if(!r)return i.layers&&!i.layers.includes(s)?[]:VS(n.slice(1),e.concat([s]));let o=(i.optional_via?set:set.filter(a=>a!==s)).filter(a=>!i.layers||i.layers?.includes(a));for(let a of o)t.push(...VS(n.slice(1),e.concat(a)));return t};function oet(n){let e={x:n.to.x-n.from.x,y:n.to.y-n.from.y},t=Math.abs(e.x),i=Math.abs(e.y);return t>i?e.x>0?"right":"left":e.y>0?"down":"up"}function $_(n,e){return Math.hypot(n.x-e.x,n.y-e.y)}var rOt=n=>{if(n.length===1)return n[0];if(n.some(c=>c.length===0))throw new Error("Cannot merge routes with zero length");let e=[],t=n[0][0],i=n[0][n[0].length-1],r=n[1][0],s=n[1][n[1].length-1],o=Math.min($_(t,r),$_(t,s)),a=Math.min($_(i,r),$_(i,s));o<a?e.push(...n[0].reverse()):e.push(...n[0]);for(let c=1;c<n.length;c++){let l=e[e.length-1],u=n[c],p=u[0],f=u[u.length-1],y=$_(l,p),g=$_(l,f);y<g?e.push(...u):e.push(...u.reverse())}for(let c=1;c<e.length-1;c++){let l=e[c-1],u=e[c];l.route_type==="wire"&&u.route_type==="wire"&&l.layer!==u.layer&&e.splice(c,0,{x:l.x,y:l.y,from_layer:l.layer,to_layer:u.layer,route_type:"via"})}return e},sOt=(n,e)=>{let t="_getGlobalPcbPositionBeforeLayout"in n?n._getGlobalPcbPositionBeforeLayout():n,i="_getGlobalPcbPositionBeforeLayout"in e?e._getGlobalPcbPositionBeforeLayout():e;return Math.sqrt((t.x-i.x)**2+(t.y-i.y)**2)};function oOt(n,e){if(e.length===0)throw new Error("No candidates given to getClosest method");let t=e[0],i=1/0;for(let r of e){let s=sOt(n,r);s<i&&(t=r,i=s)}return t}var aOt=(n,e)=>{let t=0;t+=n.length??0,t+=e.filter(i=>i.is_crossing).length;for(let i=1;i<e.length;i++){let r=e[i-1],s=e[i],o=Math.abs(r.from.x-r.to.x)<.01,a=Math.abs(s.from.x-s.to.x)<.01;o!==a&&t++}return t},B1=n=>({up:"bottom",down:"top",left:"right",right:"left"})[n]??null,KA=({firstEdge:n,firstEdgePort:e,firstDominantDirection:t,lastEdge:i,lastEdgePort:r,lastDominantDirection:s})=>{if(n&&e)return KA({lastEdge:{from:n.to,to:n.from},lastEdgePort:e,lastDominantDirection:t}).reverse().map(a=>({from:a.to,to:a.from}));let o=[];if(i&&r){let a={x:i.to.x,y:i.to.y};s==="left"||s==="right"?(a.x=r.position.x,o.push({from:i.to,to:{...a}}),o.push({from:a,to:{...r.position}})):(a.y=r.position.y,o.push({from:i.to,to:{...a}}),o.push({from:a,to:{...r.position}}))}return o=o.filter(a=>Fi(a.from,a.to)>.01),o};function cOt(n){try{return[n(),null]}catch(e){return[null,e]}}var lOt=(n,{db:e})=>{let t=n.map(i=>{let r=e.source_port.get(i.source_port_id);if(!r?.source_component_id)return null;let s=e.source_component.get(r.source_component_id);return s?.ftype==="simple_capacitor"?s.max_decoupling_trace_length:null}).filter(i=>i!==null);if(t.length!==0)return Math.min(...t)};function uOt({ports:n,nets:e}){if(n.length>=2)return`${n[0]?.selector} to ${n[1]?.selector}`;if(n.length===1&&e.length===1)return`${n[0]?.selector} to net.${e[0]._parsedProps.name}`}var pOt=(n,{db:e})=>{let t=e.pcb_board.list()[0];if(t.outline){let c=t.outline,l=(u,p)=>{let f=!1;for(let y=0,g=p.length-1;y<p.length;g=y++){let x=p[y].x,v=p[y].y,S=p[g].x,P=p[g].y;v>u.y!=P>u.y&&u.x<(S-x)*(u.y-v)/(P-v)+x&&(f=!f)}return f};return n.some(u=>!l(u,c))}let i=t.width,r=t.height,s=t.center.x,o=t.center.y;return n.some(c=>c.x<s-i/2||c.y<o-r/2||c.x>s+i/2||c.y>o+r/2)},aet=(n,e)=>Math.abs(n-e)<1e-4,hOt=(n,e,{viaDiameter:t=.5}={})=>{let i=[];for(let r=0;r<n.length-1;r++){let[s,o]=[n[r],n[r+1]],a=r-1>=0?n[r-1]:null,c=aet(s.y,o.y),l=aet(s.x,o.x);if(!c&&!l)throw new Error(`getObstaclesFromTrace currently only supports horizontal and vertical traces (not diagonals) Conflicting trace: ${e}, start: (${s.x}, ${s.y}), end: (${o.x}, ${o.y})`);let u={type:"rect",layers:[s.layer],center:{x:(s.x+o.x)/2,y:(s.y+o.y)/2},width:c?Math.abs(s.x-o.x):.1,height:l?Math.abs(s.y-o.y):.1,connectedTo:[e]};if(i.push(u),a&&a.layer===s.layer&&s.layer!==o.layer){let p={type:"rect",layers:[s.layer,o.layer],center:{x:s.x,y:s.y},connectedTo:[e],width:t,height:t};i.push(p)}}return i};function dOt(n,e=4){let{center:t,width:i,height:r,rotation:s}=n,o=[],a=s*Math.PI/180,c=Math.cos(a),l=Math.sin(a),u=(s%360+360)%360;if(r<=i?u>=45&&u<135||u>=225&&u<315:u>=135&&u<225||u>=315||u<45){let f=i/e;for(let y=0;y<e;y++){let g=(y-e/2+.5)*f,x=-g*c,v=-g*l,S=f*1.1,P=Math.abs(r*c)+Math.abs(f*l);o.push({center:{x:t.x+x,y:t.y+v},width:S,height:P})}}else{let f=r/e;for(let y=0;y<e;y++){let g=(y-e/2+.5)*f,x=-g*l,v=g*c,S=Math.abs(i*c)+Math.abs(f*l),P=f*1.1;o.push({center:{x:t.x+x,y:t.y+v},width:S,height:P})}}return o}function fOt(n,e={}){if(n.length<3)return[];let{rectHeight:t=.1}=e,i=[],r=n.map(a=>a.y),s=Math.min(...r),o=Math.max(...r);for(let a=s;a<o;a+=t){let c=a+t/2,l=[];for(let u=0;u<n.length;u++){let p=n[u],f=n[(u+1)%n.length];if(p.y<=c&&f.y>c||f.y<=c&&p.y>c){let y=(c-p.y)*(f.x-p.x)/(f.y-p.y)+p.x;l.push(y)}}l.sort((u,p)=>u-p);for(let u=0;u<l.length;u+=2)if(u+1<l.length){let p=l[u],y=l[u+1]-p;y>1e-6&&i.push({center:{x:p+y/2,y:c},width:y,height:t})}}return i}function mOt(n,e={}){let{center:t,radius:i}=n,{rectHeight:r=.1}=e,s=[],o=Math.ceil(i*2/r);for(let a=0;a<o;a++){let c=t.y-i+(a+.5)*r,l=c-t.y,u=Math.sqrt(i*i-l*l);u>0&&s.push({center:{x:t.x,y:c},width:u*2,height:r})}return s}var Ba=["top","inner1","inner2","bottom"],Yet=(n,e)=>{let t=r=>e?r.concat(r.map(s=>e?.getNetConnectedToId(s)).filter(Boolean)):r,i=[];for(let r of n)if(r.type==="pcb_smtpad"){if(r.shape==="circle")i.push({type:"oval",layers:[r.layer],center:{x:r.x,y:r.y},width:r.radius*2,height:r.radius*2,connectedTo:t([r.pcb_smtpad_id])});else if(r.shape==="rect")i.push({type:"rect",layers:[r.layer],center:{x:r.x,y:r.y},width:r.width,height:r.height,connectedTo:t([r.pcb_smtpad_id])});else if(r.shape==="rotated_rect"){let s={center:{x:r.x,y:r.y},width:r.width,height:r.height,rotation:r.ccw_rotation},o=dOt(s);for(let a of o)i.push({type:"rect",layers:[r.layer],center:a.center,width:a.width,height:a.height,connectedTo:t([r.pcb_smtpad_id])})}}else if(r.type==="pcb_keepout")r.shape==="circle"?i.push({type:"oval",layers:r.layers,center:{x:r.center.x,y:r.center.y},width:r.radius*2,height:r.radius*2,connectedTo:[]}):r.shape==="rect"&&i.push({type:"rect",layers:r.layers,center:{x:r.center.x,y:r.center.y},width:r.width,height:r.height,connectedTo:[]});else if(r.type==="pcb_cutout"){if(r.shape==="rect")i.push({type:"rect",layers:Ba,center:{x:r.center.x,y:r.center.y},width:r.width,height:r.height,connectedTo:[]});else if(r.shape==="circle"){let s=mOt({center:r.center,radius:r.radius},{rectHeight:.6});for(let o of s)i.push({type:"rect",layers:Ba,center:o.center,width:o.width,height:o.height,connectedTo:[]})}else if(r.shape==="polygon"){let s=fOt(r.points,{rectHeight:.6});for(let o of s)i.push({type:"rect",layers:Ba,center:o.center,width:o.width,height:o.height,connectedTo:[]})}}else if(r.type==="pcb_hole")r.hole_shape==="oval"?i.push({type:"oval",center:{x:r.x,y:r.y},width:r.hole_width,height:r.hole_height,connectedTo:[]}):r.hole_shape==="rect"?i.push({type:"rect",layers:Ba,center:{x:r.x,y:r.y},width:r.hole_width,height:r.hole_height,connectedTo:[]}):r.hole_shape==="square"?i.push({type:"rect",layers:Ba,center:{x:r.x,y:r.y},width:r.hole_diameter,height:r.hole_diameter,connectedTo:[]}):(r.hole_shape==="round"||r.hole_shape==="circle")&&i.push({type:"rect",layers:Ba,center:{x:r.x,y:r.y},width:r.hole_diameter,height:r.hole_diameter,connectedTo:[]});else if(r.type==="pcb_plated_hole")r.shape==="circle"?i.push({type:"oval",layers:Ba,center:{x:r.x,y:r.y},width:r.outer_diameter,height:r.outer_diameter,connectedTo:t([r.pcb_plated_hole_id])}):r.shape==="circular_hole_with_rect_pad"?i.push({type:"rect",layers:Ba,center:{x:r.x,y:r.y},width:r.rect_pad_width,height:r.rect_pad_height,connectedTo:t([r.pcb_plated_hole_id])}):(r.shape==="oval"||r.shape==="pill")&&i.push({type:"oval",layers:Ba,center:{x:r.x,y:r.y},width:r.outer_width,height:r.outer_height,connectedTo:t([r.pcb_plated_hole_id])});else if(r.type==="pcb_trace"){let s=hOt(r.route.map(o=>({x:o.x,y:o.y,layer:"layer"in o?o.layer:o.from_layer})),r.source_trace_id);i.push(...s)}else if(r.type==="pcb_via"){let s=!!(r.net_is_assignable??r.netIsAssignable);i.push({type:"rect",layers:r.layers,center:{x:r.x,y:r.y},connectedTo:[],width:r.outer_diameter,height:r.outer_diameter,netIsAssignable:s||void 0})}return i},ml=({anchor_position:n,anchor_side:e,text:t,font_size:i=.18})=>{let r=.1*(i/.18),s=t.length*r,o=i,a={...n};switch(e){case"right":a.x-=s/2;break;case"left":a.x+=s/2;break;case"top":a.y-=o/2;break;case"bottom":a.y+=o/2;break}return a},u9=({db:n,source_trace_id:e,sameNetOnly:t,differentNetOnly:i})=>{!t&&!i&&(i=!0);let r=n.source_trace.get(e),s=[];for(let o of n.schematic_trace.list()){if(o.source_trace_id===e)continue;let c=n.source_trace.get(o.source_trace_id)?.subcircuit_connectivity_map_key===r.subcircuit_connectivity_map_key;i&&c||t&&!c||s.push(o)}return s},_Ot=({edges:n,otherEdges:e})=>{let t=[...n];for(let i=0;i<t.length;i++){if(i>2e3)throw new Error("Over 2000 iterations spent inside createSchematicTraceCrossingSegments, you have triggered an infinite loop, please report this!");let r=t[i],s=Math.abs(r.from.x-r.to.x)<.01?"vertical":r.from.y===r.to.y?"horizontal":"not-orthogonal";if(s==="not-orthogonal")continue;let o=[];for(let x of e){let v=x.from.x===x.to.x?"vertical":x.from.y===x.to.y?"horizontal":"not-orthogonal";if(v==="not-orthogonal"||s===v)continue;if(Ia([r.from,r.to],[x.from,x.to],{lineThickness:.01})){let P=s==="vertical"?r.from.x:x.from.x,T=s==="vertical"?x.from.y:r.from.y,k={x:P,y:T};o.push({otherEdge:x,crossingPoint:k,distanceFromEdgeFrom:Fi(r.from,k)})}}if(o.length===0)continue;let a=o[0];for(let x of o)x.distanceFromEdgeFrom<a.distanceFromEdgeFrom&&(a=x);let c=a.crossingPoint,l=.075;if(c.x===r.from.x&&c.y===r.from.y)continue;let u=bw(r.from,c),p={x:c.x-u.x*l/2,y:c.y-u.y*l/2},f={x:c.x+u.x*l/2,y:c.y+u.y*l/2},y=Fi(f,r.to)<l,g=[{from:r.from,to:p},{from:p,to:f,is_crossing:!0},{from:f,to:r.to}];t.splice(i,1,...g),i+=g.length-2,y&&i++}return t},JA=.001,j_=(n,e)=>{let t=Math.min(e.from.x,e.to.x),i=Math.max(e.from.x,e.to.x),r=Math.min(e.from.y,e.to.y),s=Math.max(e.from.y,e.to.y);return n.x>=t&&n.x<=i&&n.y>=r&&n.y<=s},cet=n=>{let e=Math.abs(n.from.x-n.to.x)<JA,t=Math.abs(n.from.y-n.to.y)<JA;return e?"vertical":t?"horizontal":"diagonal"},yOt=(n,e)=>{let t=cet(n),i=cet(e);if(t===i)return null;if(t==="vertical"&&i==="horizontal"||t==="horizontal"&&i==="vertical"){let p=t==="vertical"?n:e,f=t==="horizontal"?n:e,y=p.from.x,g=f.from.y,x={x:y,y:g};return j_(x,n)&&j_(x,e)?x:null}if(t==="vertical"||i==="vertical"){let p=t==="vertical"?n:e,f=t==="vertical"?e:n,y=p.from.x,g=(f.to.y-f.from.y)/(f.to.x-f.from.x),x=f.from.y-g*f.from.x,v=g*y+x,S={x:y,y:v};return j_(S,n)&&j_(S,e)?S:null}let r=(n.to.y-n.from.y)/(n.to.x-n.from.x),s=n.from.y-r*n.from.x,o=(e.to.y-e.from.y)/(e.to.x-e.from.x),a=e.from.y-o*e.from.x;if(Math.abs(r-o)<JA)return null;let c=(a-s)/(r-o),l=r*c+s,u={x:c,y:l};return j_(u,n)&&j_(u,e)?u:null},gOt=({edges:n,db:e,source_trace_id:t})=>{let i=u9({db:e,source_trace_id:t,sameNetOnly:!0}).flatMap(s=>s.edges),r=new Map;for(let s of n)for(let o of i){let a=yOt(s,o);if(a){let c=`${a.x.toFixed(6)},${a.y.toFixed(6)}`;r.has(c)||r.set(c,a)}}return Array.from(r.values())};function xOt(n,e={}){let{minX:t,maxX:i,minY:r,maxY:s}=n,o=e.padding??1;if(!isFinite(t)||!isFinite(i)||!isFinite(r)||!isFinite(s))return[];let a=t-o,c=i+o,l=s+o,u=r-o,p=.01;return[{type:"rect",layers:["top"],center:{x:(a+c)/2,y:l},width:c-a,height:p,connectedTo:[]},{type:"rect",layers:["top"],center:{x:(a+c)/2,y:u},width:c-a,height:p,connectedTo:[]},{type:"rect",layers:["top"],center:{x:a,y:(l+u)/2},width:p,height:l-u,connectedTo:[]},{type:"rect",layers:["top"],center:{x:c,y:(l+u)/2},width:p,height:l-u,connectedTo:[]}]}var bOt=n=>{let e=n.root.db,t=n._findConnectedPorts().ports??[],i=new Set(t.map(o=>o.schematic_port_id)),r=[];for(let o of e.toArray()){if(o.type==="schematic_component"){let a=!!o.symbol_name,c=o.size.width>o.size.height?"horz":"vert";r.push({type:"rect",layers:["top"],center:o.center,width:o.size.width+(a&&c==="horz"?-.5:0),height:o.size.height+(a&&c==="vert"?-.5:0),connectedTo:[]})}if(o.type==="schematic_port"){if(i.has(o.schematic_port_id))continue;let a=o.facing_direction?vw(o.facing_direction):{x:0,y:0};r.push({type:"rect",layers:["top"],center:{x:o.center.x-a.x*.1,y:o.center.y-a.y*.1},width:.1+Math.abs(a.x)*.3,height:.1+Math.abs(a.y)*.3,connectedTo:[]})}o.type==="schematic_text"&&r.push({type:"rect",layers:["top"],center:o.position,width:(o.text?.length??0)*.1,height:.2,connectedTo:[]}),o.type==="schematic_box"&&r.push({type:"rect",layers:["top"],center:{x:o.x,y:o.y},width:o.width,height:o.height,connectedTo:[]})}let s=Ret(e.toArray());return r.push(...xOt(s,{padding:1})),r},vOt=({edges:n,db:e,source_trace_id:t})=>{let i=e.source_trace.get(t),r=u9({db:e,source_trace_id:t,differentNetOnly:!0}).flatMap(o=>o.edges),s=o=>{let{from:a,to:c}=o;return a.x===c.x?"vertical":"horizontal"};for(let o of n){let a=s(o),c=()=>r.find(u=>s(u)===a&&Ia([o.from,o.to],[u.from,u.to],{lineThickness:.05})),l=c();for(;l;)a==="horizontal"?(o.from.y+=.1,o.to.y+=.1):(o.from.x+=.1,o.to.x+=.1),l=c()}},QA=n=>{switch(n){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:}},wOt=VW.version??"unknown",L1=class extends Error{constructor(n){super(`${n} (capacity-autorouter@${wOt})`),this.name="AutorouterError"}},WS=class extends Error{constructor(n){super(n.message),this.errorData=n,this.name="TraceConnectionError"}},SOt=n=>{if(n.root?._featureMspSchematicTraceRouting||n._couldNotFindPort||n.root?.schematicDisabled)return;let{db:e}=n.root,{_parsedProps:t,parent:i}=n;if(!i)throw new Error("Trace has no parent");let r,s;try{let U=n._findConnectedPorts();r=U.allPortsFound,s=U.portsWithSelectors??[]}catch(U){if(U instanceof WS){e.source_trace_not_connected_error.insert({...U.errorData,error_type:"source_trace_not_connected_error"});return}throw U}let{netsWithSelectors:o}=n._findConnectedNets();if(!r)return;let c=s.map(U=>U.port.schematic_port_id).sort().join(","),l=n.root?._getBoard();if(l?._connectedSchematicPortPairs&&l._connectedSchematicPortPairs.has(c))return;let u={name:n.source_trace_id,pointsToConnect:[]},p=bOt(n),f=s.filter(({port:U})=>U.schematic_port_id!==null).map(({port:U})=>({port:U,position:U._getGlobalSchematicPositionAfterLayout(),schematic_port_id:U.schematic_port_id??void 0,facingDirection:U.facingDirection}));if(f.length===1&&o.length===1){let U=o[0].net,{port:H,position:Q}=f[0],tt=n.getSubcircuit().selectAll("netlabel").find(nt=>{let et=nt._parsedProps.connection??nt._parsedProps.connectsTo;return et?Array.isArray(et)?et.some(dt=>n.getSubcircuit().selectOne(dt,{port:!0})===H):n.getSubcircuit().selectOne(et,{port:!0})===H:!1});if(!tt){let nt=e.schematic_net_label.getWhere({source_trace_id:n.source_trace_id});nt&&(tt=nt)}if(tt){let nt="_getGlobalSchematicPositionBeforeLayout"in tt?tt._getGlobalSchematicPositionBeforeLayout():tt.anchor_position,et=[];Q.x===nt.x||Q.y===nt.y?et.push({from:Q,to:nt}):(et.push({from:Q,to:{x:nt.x,y:Q.y}}),et.push({from:{x:nt.x,y:Q.y},to:nt}));let ht=e.schematic_trace.insert({source_trace_id:n.source_trace_id,edges:et,junctions:[],subcircuit_connectivity_map_key:n.subcircuit_connectivity_map_key??void 0});n.schematic_trace_id=ht.schematic_trace_id;return}if(n.props.schDisplayLabel){let nt=B1(H.facingDirection)??"bottom";e.schematic_net_label.insert({text:n.props.schDisplayLabel,source_net_id:U.source_net_id,anchor_position:Q,center:ml({anchor_position:Q,anchor_side:nt,text:n.props.schDisplayLabel}),anchor_side:nt});return}let V=B1(H.facingDirection)??"bottom",ot=e.schematic_net_label.insert({text:U._parsedProps.name,source_net_id:U.source_net_id,anchor_position:Q,center:ml({anchor_position:Q,anchor_side:V,text:U._parsedProps.name}),anchor_side:V});return}if(n.props.schDisplayLabel&&("from"in n.props&&"to"in n.props||"path"in n.props)){n._doInitialSchematicTraceRenderWithDisplayLabel();return}if(f.length<2)return;let x=(()=>{let U=[];for(let Q=0;Q<f.length-1;Q++){let tt=f[Q],V=f[Q+1],ot=Wc({x:tt.position.x,y:tt.position.y,facingDirection:QA(tt.facingDirection)},{x:V.position.x,y:V.position.y,facingDirection:QA(V.facingDirection)});for(let nt=0;nt<ot.length-1;nt++)U.push({from:ot[nt],to:ot[nt+1]})}let H=(Q,tt)=>{let V=tt.width/2,ot=tt.height/2,nt=tt.center.x-V,et=tt.center.x+V,ht=tt.center.y-ot,dt=tt.center.y+ot,St=ut=>ut.x>=nt&&ut.x<=et&&ut.y>=ht&&ut.y<=dt;return St(Q.from)||St(Q.to)?!0:[[{x:nt,y:ht},{x:et,y:ht}],[{x:et,y:ht},{x:et,y:dt}],[{x:et,y:dt},{x:nt,y:dt}],[{x:nt,y:dt},{x:nt,y:ht}]].some(ut=>Ia([Q.from,Q.to],ut,{lineThickness:0}))};for(let Q of U)for(let tt of p)if(H(Q,tt))return null;return U})();x&&x.length===0&&(x=null),u.pointsToConnect=f.map(({position:U})=>({...U,layer:"top"}));let v=iOt(p),S=2,P={minTraceWidth:.1,obstacles:p,connections:[u],bounds:{minX:v.minX-S,maxX:v.maxX+S,minY:v.minY-S,maxY:v.maxY+S},layerCount:1},T=aw,k=!1;if(n.getSubcircuit().props._schDirectLineRoutingEnabled&&(T=ret,k=!0),!x){let H=new T({input:P,MAX_ITERATIONS:100,OBSTACLE_MARGIN:.1,isRemovePathLoopsEnabled:!0,isShortenPathWithShortcutsEnabled:!0,marginsWithCosts:[{margin:1,enterCost:0,travelCostFactor:1},{margin:.3,enterCost:0,travelCostFactor:1},{margin:.2,enterCost:0,travelCostFactor:2},{margin:.1,enterCost:0,travelCostFactor:3}]}).solveAndMapToTraces();if(H.length===0){if(n._isSymbolToChipConnection()||n._isSymbolToSymbolConnection()||n._isChipToChipConnection()){n._doInitialSchematicTraceRenderWithDisplayLabel();return}H=new ret({input:P}).solveAndMapToTraces(),k=!0}let[{route:Q}]=H;x=[];for(let tt=0;tt<Q.length-1;tt++)x.push({from:Q[tt],to:Q[tt+1]})}let C=n.source_trace_id,E=[];if(!k){vOt({edges:x,db:e,source_trace_id:C});let U=u9({db:e,source_trace_id:C,differentNetOnly:!0}).flatMap(H=>H.edges);x=_Ot({edges:x,otherEdges:U}),E=gOt({edges:x,db:e,source_trace_id:n.source_trace_id})}if(!x||x.length===0)return;let N=x[x.length-1],I=f[f.length-1],A=oet(N);x.push(...KA({lastEdge:N,lastEdgePort:I,lastDominantDirection:A}));let R=x[0],j=f[0],B=oet(R);if(x.unshift(...KA({firstEdge:R,firstEdgePort:j,firstDominantDirection:B})),!n.source_trace_id)throw new Error("Missing source_trace_id for schematic trace insertion.");if(n.getSubcircuit()._parsedProps.schTraceAutoLabelEnabled&&aOt(E,x)>=5&&(n._isSymbolToChipConnection()||n._isSymbolToSymbolConnection()||n._isChipToChipConnection())){n._doInitialSchematicTraceRenderWithDisplayLabel();return}let G=e.schematic_trace.insert({source_trace_id:n.source_trace_id,edges:x,junctions:E,subcircuit_connectivity_map_key:n.subcircuit_connectivity_map_key??void 0});n.schematic_trace_id=G.schematic_trace_id;for(let{port:U}of s)U.schematic_port_id&&e.schematic_port.update(U.schematic_port_id,{is_connected:!0});l?._connectedSchematicPortPairs&&l._connectedSchematicPortPairs.add(c)};function Xet(n){let e=0;for(let t=0;t<n.length;t++){let i=n[t];if(i.route_type==="wire"){let r=n[t+1];if(r){let s=r.x-i.x,o=r.y-i.y;e+=Math.sqrt(s*s+o*o)}}else i.route_type==="via"&&(e+=1.6)}return e}var YS=n=>({...n._getGlobalPcbPositionAfterLayout(),layers:n.getAvailablePcbLayers()}),POt=!1;function kOt(n){if(n.root?.pcbDisabled)return;let{db:e}=n.root,{_parsedProps:t,parent:i}=n,r=n.getSubcircuit();if(!i)throw new Error("Trace has no parent");if(r._parsedProps.routingDisabled)return;let s=r._parsedProps.pcbRouteCache?.pcbTraces;if(s){let A=e.pcb_trace.insert({route:s.flatMap(R=>R.route),source_trace_id:n.source_trace_id,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:n.getGroup()?.pcb_group_id??void 0});n.pcb_trace_id=A.pcb_trace_id;return}if(t.pcbPath&&t.pcbPath.length>0||!r._shouldUseTraceByTraceRouting())return;let{allPortsFound:o,ports:a}=n._findConnectedPorts(),c=[];if(!o)return;let l=[];for(let A of a)A._hasMatchedPcbPrimitive()||l.push(A);if(l.length>0){e.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:n.source_trace_id,message:`Some ports did not have a matching PCB primitive (e.g. a pad or plated hole), this can happen if a footprint is missing. As a result, ${n} wasn't routed. Missing ports: ${l.map(A=>A.getString()).join(", ")}`,pcb_trace_id:n.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:l.map(A=>A.pcb_port_id).filter(Boolean)});return}let u=n._findConnectedNets().netsWithSelectors;if(a.length===0&&u.length===2){n.renderError("Trace connects two nets, we haven't implemented a way to route this yet");return}else if(a.length===1&&u.length===1){let A=a[0],j=u[0].net.getAllConnectedPorts().filter(G=>G!==A);if(j.length===0){console.log("Nothing to connect this port to, the net is empty. TODO should emit a warning!");return}let B=oOt(A,j);c.push(B),a.push(B)}else if(a.length>1&&u.length>=1){n.renderError("Trace has more than one port and one or more nets, we don't currently support this type of complex trace routing");return}let p=a.flatMap(A=>A.matchedComponents.filter(R=>R.componentName==="TraceHint")),f=(n._parsedProps.pcbRouteHints??[]).concat(p.flatMap(A=>A.getPcbRouteHints()));if(a.length>2){n.renderError(`Trace has more than two ports (${a.map(A=>A.getString()).join(", ")}), routing between more than two ports for a single trace is not implemented`);return}if(n.getSubcircuit().selectAll("trace").filter(A=>A.renderPhaseStates.PcbTraceRender.initialized).some(A=>A._portsRoutedOnPcb.length===a.length&&A._portsRoutedOnPcb.every(R=>a.includes(R))))return;let x=[];f.length===0?x=[YS(a[0]),YS(a[1])]:x=[YS(a[0]),...f,YS(a[1])];let v=VS(x);if(POt&&v.length===0){n.renderError(`Could not find a common layer (using hints) for trace ${n.getString()}`);return}let S=er(n.root.db.toArray()),[P,T]=cOt(()=>Yet(n.root.db.toArray()));if(T){n.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:n.pcb_trace_id,message:`Error getting obstacles for autorouting: ${T.message}`,source_trace_id:n.source_trace_id,center:{x:0,y:0},pcb_port_ids:a.map(A=>A.pcb_port_id),pcb_trace_id:n.pcb_trace_id,pcb_component_ids:[]});return}for(let A of P)if(A.connectedTo.length>0){let j=S.getNetConnectedToId(A.connectedTo[0]);j&&A.connectedTo.push(j)}let k=[];if(v.length===0)k=x;else{let A=v[0].layer_path;k=x.map((R,j)=>R.via?{...R,via_to_layer:A[j]}:{...R,layers:[A[j]]})}k[0].pcb_port_id=a[0].pcb_port_id,k[k.length-1].pcb_port_id=a[1].pcb_port_id;let C=[];for(let[A,R]of Aet(k)){let j="via_to_layer"in A?A.via_to_layer:null,B=2,G="layers"in A&&A.layers.length===1?A.layers[0]:j??"top",U="layers"in R&&R.layers.length===1?R.layers[0]:j??"top",H="pcb_port_id"in A?A.pcb_port_id:null,Q="pcb_port_id"in R?R.pcb_port_id:null,tt=n._getExplicitTraceThickness()??n.getSubcircuit()._parsedProps.minTraceWidth??.16,V=new aw({OBSTACLE_MARGIN:tt*2,isRemovePathLoopsEnabled:!0,optimizeWithGoalBoxes:!!(H&&Q),connMap:S,input:{obstacles:P,minTraceWidth:tt,connections:[{name:n.source_trace_id,pointsToConnect:[{...A,layer:G,pcb_port_id:H},{...R,layer:U,pcb_port_id:Q}]}],layerCount:n.getSubcircuit()._getSubcircuitLayerCount(),bounds:{minX:Math.min(A.x,R.x)-B,maxX:Math.max(A.x,R.x)+B,minY:Math.min(A.y,R.y)-B,maxY:Math.max(A.y,R.y)+B}}}),ot=null;try{ot=V.solveAndMapToTraces()}catch(ht){n.renderError({type:"pcb_trace_error",pcb_trace_error_id:n.source_trace_id,error_type:"pcb_trace_error",message:`error solving route: ${ht.message}`,source_trace_id:n.pcb_trace_id,center:{x:(A.x+R.x)/2,y:(A.y+R.y)/2},pcb_port_ids:a.map(dt=>dt.pcb_port_id),pcb_trace_id:n.pcb_trace_id,pcb_component_ids:a.map(dt=>dt.pcb_component_id)})}if(!ot)return;if(ot.length===0){n.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:n.pcb_trace_id,message:`Could not find a route for ${n}`,source_trace_id:n.source_trace_id,center:{x:(A.x+R.x)/2,y:(A.y+R.y)/2},pcb_port_ids:a.map(ht=>ht.pcb_port_id),pcb_trace_id:n.pcb_trace_id,pcb_component_ids:a.map(ht=>ht.pcb_component_id)});return}let[nt]=ot;j&&(nt.route=nt.route.map(ht=>(ht.route_type==="wire"&&!ht.layer&&(ht.layer=j),ht))),H&&nt.route[0].route_type==="wire"&&(nt.route[0].start_pcb_port_id=H);let et=nt.route[nt.route.length-1];Q&&et.route_type==="wire"&&(et.end_pcb_port_id=Q),C.push(nt.route)}let E=rOt(C),N=Xet(E),I=e.pcb_trace.insert({route:E,source_trace_id:n.source_trace_id,subcircuit_id:n.getSubcircuit()?.subcircuit_id,trace_length:N});n._portsRoutedOnPcb=a,n.pcb_trace_id=I.pcb_trace_id;for(let A of E)A.route_type==="via"&&e.pcb_via.insert({pcb_trace_id:I.pcb_trace_id,x:A.x,y:A.y,hole_diameter:.3,outer_diameter:.6,layers:[A.from_layer,A.to_layer],from_layer:A.from_layer,to_layer:A.to_layer});n._insertErrorIfTraceIsOutsideBoard(E,a)}function TOt(n){if(n.root?.pcbDisabled)return;let{db:e}=n.root,{_parsedProps:t}=n,i=n.getSubcircuit();if(!t.pcbPath)return;let{allPortsFound:r,ports:s,portsWithSelectors:o}=n._findConnectedPorts();if(!r)return;let a=[];for(let P of s)P._hasMatchedPcbPrimitive()||a.push(P);if(a.length>0){e.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:n.source_trace_id,message:`Some ports did not have a matching PCB primitive (e.g. a pad or plated hole), this can happen if a footprint is missing. As a result, ${n} wasn't routed. Missing ports: ${a.map(P=>P.getString()).join(", ")}`,pcb_trace_id:n.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:a.map(P=>P.pcb_port_id).filter(Boolean)});return}let c;t.pcbPathRelativeTo&&(c=o.find(P=>P.selector===t.pcbPathRelativeTo)?.port,c||(c=n.getSubcircuit().selectOne(t.pcbPathRelativeTo))),c||(c=s[0]);let l=s.find(P=>P!==c)??s[1],u=c.getAvailablePcbLayers()[0]||"top",p=n._getExplicitTraceThickness()??n.getSubcircuit()._parsedProps.minTraceWidth??.16,f=c._getGlobalPcbPositionAfterLayout(),y=l._getGlobalPcbPositionAfterLayout(),g=[];g.push({route_type:"wire",x:f.x,y:f.y,width:p,layer:u,start_pcb_port_id:c.pcb_port_id});let x=c?._computePcbGlobalTransformBeforeLayout?.()||Qi();for(let P of t.pcbPath){let T,k=!1;if(typeof P=="string"){let E=n.getSubcircuit().selectOne(P,{type:"port"});if(!E){e.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:n.source_trace_id,message:`Could not resolve pcbPath selector "${P}" for ${n}`,pcb_trace_id:n.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:[]});continue}let N=E._getGlobalPcbPositionAfterLayout();T={x:N.x,y:N.y},k=!0}else T={x:P.x,y:P.y},k=!1;let C=k?T:ze(x,T);g.push({route_type:"wire",x:C.x,y:C.y,width:p,layer:u})}g.push({route_type:"wire",x:y.x,y:y.y,width:p,layer:u,end_pcb_port_id:l.pcb_port_id});let v=Xet(g),S=e.pcb_trace.insert({route:g,source_trace_id:n.source_trace_id,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:n.getGroup()?.pcb_group_id??void 0,trace_length:v});n._portsRoutedOnPcb=s,n.pcb_trace_id=S.pcb_trace_id,n._insertErrorIfTraceIsOutsideBoard(g,s)}function EOt(n){if(n.root?.schematicDisabled)return;let{db:e}=n.root,{_parsedProps:t,parent:i}=n;if(!i)throw new Error("Trace has no parent");let{allPortsFound:r,portsWithSelectors:s}=n._findConnectedPorts();if(!r)return;let o=s.map(({port:k})=>({port:k,position:k._getGlobalSchematicPositionAfterLayout(),schematic_port_id:k.schematic_port_id,facingDirection:k.facingDirection}));if(o.length<2)throw new Error("Expected at least two ports in portsWithPosition.");let a,c,l=o[0].position,u=o[0].port;if("path"in n.props){if(n.props.path.length!==2)throw new Error("Invalid 'path': Must contain exactly two elements.");[a,c]=n.props.path}else{if(!("from"in n.props&&"to"in n.props))throw new Error("Missing 'from' or 'to' properties in props.");a=n.props.from,c=n.props.to}if(!u.source_port_id)throw new Error(`Missing source_port_id for the 'from' port (${a}).`);let p=o[1].position,f=o[1].port;if(!f.source_port_id)throw new Error(`Missing source_port_id for the 'to' port (${c}).`);let y=e.schematic_net_label.list().find(k=>k.source_net_id===u.source_port_id),g=e.schematic_net_label.list().find(k=>k.source_net_id===f.source_port_id),[x,v]=s.map(({port:k})=>k),P=x.parent?.config.shouldRenderAsSchematicBox?`${x?.parent?.props.name}_${x?.props.name}`:`${v?.parent?.props.name}_${v?.props.name}`,T=n.props.schDisplayLabel??P;if(y&&y.text!==T&&(y.text=`${T} / ${y.text}`),g&&g?.text!==T&&(g.text=`${T} / ${g.text}`),!g){let k=B1(f.facingDirection)??"bottom";e.schematic_net_label.insert({text:n.props.schDisplayLabel??P,source_net_id:f.source_port_id,anchor_position:p,center:ml({anchor_position:p,anchor_side:k,text:n.props.schDisplayLabel??P}),anchor_side:k})}if(!y){let k=B1(u.facingDirection)??"bottom";e.schematic_net_label.insert({text:n.props.schDisplayLabel??P,source_net_id:u.source_port_id,anchor_position:l,center:ml({anchor_position:l,anchor_side:k,text:n.props.schDisplayLabel??P}),anchor_side:k})}}function MOt(n){let{_parsedProps:e,parent:t}=n;if(!t)throw new Error("Trace has no parent");let r=n.getTracePortPathSelectors().map(s=>({selector:s,port:n.getSubcircuit().selectOne(s,{type:"port"})??null}));for(let{selector:s,port:o}of r)if(!o){let a,c,l=s.lastIndexOf(".");if(l!==-1&&l>s.lastIndexOf(" "))a=s.slice(0,l),c=s.slice(l+1);else{let k=s.match(/^(.*[ >])?([^ >]+)$/);a=k?.[1]?.trim()??"",c=k?.[2]??s}let u=a?n.getSubcircuit().selectOne(a):null;if(!u&&a&&!/[.#\[]/.test(a)&&(u=n.getSubcircuit().selectOne(`.${a}`)),!u){let k=a?`Could not find port for selector "${s}". Component "${a}" not found`:`Could not find port for selector "${s}"`,C=n.getSubcircuit(),E=C.getGroup();throw new WS({error_type:"source_trace_not_connected_error",message:k,subcircuit_id:C.subcircuit_id??void 0,source_group_id:E?.source_group_id??void 0,source_trace_id:n.source_trace_id??void 0,selectors_not_found:[s]})}let p=u.children.filter(k=>k.componentName==="Port"),f=c.includes(".")?c.split(".").pop()??"":c,y=p.flatMap(k=>k.getNameAndAliases()),g=y.some(k=>!/^(pin\d+|\d+)$/.test(k)),x=Array.from(new Set(y)).join(", "),v;p.length===0?v="It has no ports":g?v=`It has [${x}]`:v=`It has ${p.length} pins and no pinLabels (consider adding pinLabels)`;let S=`Could not find port for selector "${s}". Component "${u.props.name??a}" found, but does not have pin "${f}". ${v}`,P=n.getSubcircuit(),T=P.getGroup();throw new WS({error_type:"source_trace_not_connected_error",message:S,subcircuit_id:P.subcircuit_id??void 0,source_group_id:T?.source_group_id??void 0,source_trace_id:n.source_trace_id??void 0,selectors_not_found:[s]})}return r.some(s=>!s.port)?{allPortsFound:!1}:{allPortsFound:!0,portsWithSelectors:r,ports:r.map(({port:s})=>s)}}var oo=class extends Te{constructor(e){super(e);d(this,"source_trace_id",null);d(this,"pcb_trace_id",null);d(this,"schematic_trace_id",null);d(this,"_portsRoutedOnPcb");d(this,"subcircuit_connectivity_map_key",null);d(this,"_traceConnectionHash",null);d(this,"_couldNotFindPort");this._portsRoutedOnPcb=[]}_getExplicitTraceThickness(){return this._parsedProps.thickness??this._parsedProps.width}get config(){return{zodProps:RH,componentName:"Trace"}}_getTracePortOrNetSelectorListFromProps(){return"from"in this.props&&"to"in this.props?[typeof this.props.from=="string"?this.props.from:this.props.from.getPortSelector(),typeof this.props.to=="string"?this.props.to:this.props.to.getPortSelector()]:"path"in this.props?this.props.path.map(e=>typeof e=="string"?e:e.getPortSelector()):[]}getTracePortPathSelectors(){return this._getTracePortOrNetSelectorListFromProps().filter(e=>!e.includes("net."))}getTracePathNetSelectors(){return this._getTracePortOrNetSelectorListFromProps().filter(e=>e.includes("net."))}_findConnectedPorts(){return MOt(this)}_resolveNet(e){let t=this.getSubcircuit().selectOne(e,{type:"net"});if(t)return t;let i=e.match(/^net\.(.+)$/),r=i?i[1]:null;if(!r)return null;let s=this.root?._getBoard();return s?s.getDescendants().find(a=>a.componentName==="Net"&&a._parsedProps.name===r)||null:(this.renderError(`Could not find a <board> ancestor for ${this}, so net "${e}" cannot be resolved`),null)}_findConnectedNets(){let e=this.getTracePathNetSelectors().map(i=>({selector:i,net:this._resolveNet(i)})),t=e.filter(i=>!i.net);return t.length>0&&this.renderError(`Could not find net for selector "${t[0].selector}" inside ${this}`),{netsWithSelectors:e,nets:e.map(i=>i.net)}}_getAllTracesConnectedToSameNet(){let e=this.getSubcircuit().selectAll("trace"),t=this._findConnectedNets().nets,i=this._findConnectedPorts().ports??[];return e.filter(r=>{if(r===this)return!1;let s=r._findConnectedNets().nets,o=r._findConnectedPorts().ports??[];return s.some(a=>t.includes(a))||o.some(a=>i.includes(a))})}_isExplicitlyConnectedToPort(e){let{allPortsFound:t,portsWithSelectors:i}=this._findConnectedPorts();return t?i.map(s=>s.port).includes(e):!1}_isExplicitlyConnectedToNet(e){return this._findConnectedNets().nets.includes(e)}doInitialCreateNetsFromProps(){KS(this,this.getTracePathNetSelectors())}_computeTraceConnectionHash(){let{allPortsFound:e,ports:t}=this._findConnectedPorts();return!e||!t?null:[...t].sort((s,o)=>(s.pcb_port_id||"").localeCompare(o.pcb_port_id||"")).map(s=>s.pcb_port_id).join(",")}doInitialSourceTraceRender(){let{db:e}=this.root,{_parsedProps:t,parent:i}=this;if(!i){this.renderError("Trace has no parent");return}let r,s;try{let p=this._findConnectedPorts();r=p.allPortsFound,s=p.portsWithSelectors??[]}catch(p){if(p instanceof WS){e.source_trace_not_connected_error.insert({...p.errorData,error_type:"source_trace_not_connected_error"}),this._couldNotFindPort=!0;return}throw p}if(!r)return;this._traceConnectionHash=this._computeTraceConnectionHash();let a=e.source_trace.list().find(p=>p.subcircuit_connectivity_map_key===this.subcircuit_connectivity_map_key&&p.connected_source_port_ids.sort().join(",")===this._traceConnectionHash);if(a){this.source_trace_id=a.source_trace_id;return}let c=this._findConnectedNets().nets,l=uOt({ports:s,nets:c}),u=e.source_trace.insert({connected_source_port_ids:s.map(p=>p.port.source_port_id),connected_source_net_ids:c.map(p=>p.source_net_id),subcircuit_id:this.getSubcircuit()?.subcircuit_id,max_length:lOt(s.map(p=>p.port),{db:e})??t.maxLength,display_name:l,min_trace_thickness:this._getExplicitTraceThickness()});this.source_trace_id=u.source_trace_id}_insertErrorIfTraceIsOutsideBoard(e,t){let{db:i}=this.root;pOt(e,{db:i})&&i.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:this.source_trace_id,message:`Trace ${this.getString()} routed outside the board boundaries.`,pcb_trace_id:this.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:t.map(s=>s.pcb_port_id)})}doInitialPcbManualTraceRender(){TOt(this)}doInitialPcbTraceRender(){kOt(this)}_doInitialSchematicTraceRenderWithDisplayLabel(){EOt(this)}_isSymbolToChipConnection(){let{allPortsFound:e,ports:t}=this._findConnectedPorts();if(!e||t.length!==2)return!1;let[i,r]=t;if(!i?.parent||!r?.parent)return!1;let s=i.parent.config.shouldRenderAsSchematicBox,o=r.parent.config.shouldRenderAsSchematicBox;return s&&!o||!s&&o}_isSymbolToSymbolConnection(){let{allPortsFound:e,ports:t}=this._findConnectedPorts();if(!e||t.length!==2)return!1;let[i,r]=t;if(!i?.parent||!r?.parent)return!1;let s=!i.parent.config.shouldRenderAsSchematicBox,o=!r.parent.config.shouldRenderAsSchematicBox;return s&&o}_isChipToChipConnection(){let{allPortsFound:e,ports:t}=this._findConnectedPorts();if(!e||t.length!==2)return!1;let[i,r]=t;if(!i?.parent||!r?.parent)return!1;let s=i.parent.config.shouldRenderAsSchematicBox,o=r.parent.config.shouldRenderAsSchematicBox;return s&&o}doInitialSchematicTraceRender(){SOt(this)}},COt=n=>{let{db:e}=n.root;if(n.pcb_component_id){let t=e.pcb_component.get(n.pcb_component_id);return t?{width:t.width,height:t.height}:null}if(n.pcb_group_id){let t=e.pcb_group.get(n.pcb_group_id);if(!t)return null;if(t.outline&&t.outline.length>0){let i=Ro(t.outline);return i?{width:i.maxX-i.minX,height:i.maxY-i.minY}:null}return{width:t.width??0,height:t.height??0}}return null},IOt=(n,e)=>{let{db:t}=n.root,i=t.toArray();if(n.pcb_component_id){ww(i,n.pcb_component_id,e);return}if(n.source_group_id){Sw(i,n.source_group_id,e);return}throw new Error(`Cannot reposition component ${n.getString()}: no pcb_component_id or source_group_id`)},NOt=n=>{let{db:e}=n.root;if(!n.source_component_id)return;let t=n.selectAll("port"),i=e.source_trace.list(),r=new Set;for(let o of i)for(let a of o.connected_source_port_ids)r.add(a);let s=n._getInternallyConnectedPins();for(let o of s)if(o.some(a=>a.source_port_id&&r.has(a.source_port_id)))for(let a of o)a.source_port_id&&r.add(a.source_port_id);for(let o of t)o.source_port_id&&AOt(n,o)&&(r.has(o.source_port_id)||e.source_pin_missing_trace_warning.insert({message:`Port ${o.getNameAndAliases()[0]} on ${n.props.name} is missing a trace`,source_component_id:n.source_component_id,source_port_id:o.source_port_id,subcircuit_id:n.getSubcircuit().subcircuit_id??void 0,warning_type:"source_pin_missing_trace_warning"}))},AOt=(n,e)=>{if(n.config.componentName==="Chip"){let t=n.props.pinAttributes;if(!t)return!1;for(let i of e.getNameAndAliases()){let r=t[i];if(r?.requiresPower||r?.requiresGround||r?.requiresVoltage!==void 0)return!0}return!1}return!0};function ROt(n){let e=n.font_size,t=n.text.length*e*.6,i=e,r=n.anchor_alignment||"center",s=n.anchor_position.x,o=n.anchor_position.y;switch(r){case"top_left":s=n.anchor_position.x+t/2,o=n.anchor_position.y+i/2;break;case"top_center":s=n.anchor_position.x,o=n.anchor_position.y+i/2;break;case"top_right":s=n.anchor_position.x-t/2,o=n.anchor_position.y+i/2;break;case"center_left":s=n.anchor_position.x+t/2,o=n.anchor_position.y;break;case"center":s=n.anchor_position.x,o=n.anchor_position.y;break;case"center_right":s=n.anchor_position.x-t/2,o=n.anchor_position.y;break;case"bottom_left":s=n.anchor_position.x+t/2,o=n.anchor_position.y-i/2;break;case"bottom_center":s=n.anchor_position.x,o=n.anchor_position.y-i/2;break;case"bottom_right":s=n.anchor_position.x-t/2,o=n.anchor_position.y-i/2;break;default:s=n.anchor_position.x,o=n.anchor_position.y;break}return{x:s-t/2,y:o-i/2,width:t,height:i}}function OOt(n){if(!n._adjustSilkscreenTextAutomatically||n.root?.pcbDisabled||!n.pcb_component_id)return;let{db:e}=n.root,i=n._getPcbCircuitJsonBounds().center,r=e.pcb_silkscreen_text.list({pcb_component_id:n.pcb_component_id}).filter(c=>c.text===n.name);if(r.length===0)return;let a=n.getSubcircuit().selectAll("[_isNormalComponent=true]").filter(c=>c!==n&&c.pcb_component_id).map(c=>{let l=c._getPcbCircuitJsonBounds(),u={center:l.center,width:l.width,height:l.height};return eo(u)});for(let c of r){let l=c.anchor_position,u=ROt(c),p={center:{x:u.x+u.width/2,y:u.y+u.height/2},width:u.width,height:u.height},f=eo(p);if(!a.some(T=>Hc(f,T)))continue;let g=2*i.x-l.x,x=2*i.y-l.y,v={center:{x:g,y:x},width:u.width,height:u.height},S=eo(v);a.some(T=>Hc(S,T))||e.pcb_silkscreen_text.update(c.pcb_silkscreen_text_id,{anchor_position:{x:g,y:x}})}}function LOt(n){if(!n)return{validPinLabels:n,invalidPinLabelsMessages:[]};let e={},t=[];for(let[i,r]of Object.entries(n)){let s=Array.isArray(r)?r.slice():[r],o=[];for(let a of s)FOt(i,a)?o.push(a):t.push(`Invalid pin label: ${i} = '${a}' - excluding from component. Please use a valid pin label.`);o.length>0&&(e[i]=Array.isArray(r)?o:o[0])}return{validPinLabels:Object.keys(e).length>0?e:void 0,invalidPinLabelsMessages:t}}function FOt(n,e){try{let t={name:"test",footprint:"test",pinLabels:{[n]:e}};return t_.safeParse(t).success}catch{return!1}}var H_=n=>n.startsWith("http://")||n.startsWith("https://"),e9=n=>{if(H_(n))return null;let e=n.indexOf(":");if(e<=0)return null;let t=n.slice(0,e),i=n.slice(e+1);return!t||!i?null:{footprintLib:t,footprintName:i}},n9=n=>n.startsWith("/"),zOt=(0,Uet.default)("tscircuit:core:resolveStaticFileImport");async function Vet(n,e){if(!n)return n;let t=e?.resolveProjectStaticFileImportUrl;if(t&&n.startsWith("/"))try{let i=await t(n);if(i)return i}catch(i){zOt("failed to resolve static file via platform resolver",i)}return $et(n,e?.projectBaseUrl)}function DOt(n,e){let{footprint:t}=n.props;if(t??(t=n._getImpliedFootprintString?.()),!t)return;let{pcbRotation:i,pinLabels:r,pcbPinLabels:s}=n.props,o=Det(String(t)),a=o?n.root?.platform?.footprintFileParserMap?.[o]:null;if(typeof t=="string"&&(H_(t)||n9(t))&&a){if(n._hasStartedFootprintUrlLoad)return;n._hasStartedFootprintUrlLoad=!0,e("load-footprint-from-platform-file-parser",async()=>{let c=H_(t)?t:await Vet(t,n.root?.platform);try{let l=await a.loadFromUrl(c),u=G_({componentName:n.name,componentRotation:i,footprinterString:c,pinLabels:r,pcbPinLabels:s},l.footprintCircuitJson);n.addAll(u),n._markDirty("InitializePortsFromChildren")}catch(l){let u=n.root?.db;if(u&&n.source_component_id&&n.pcb_component_id){let p=n.getSubcircuit(),f=`${n.getString()} failed to load footprint "${c}": `+(l instanceof Error?l.message:String(l)),y=Nm.parse({type:"external_footprint_load_error",message:f,pcb_component_id:n.pcb_component_id,source_component_id:n.source_component_id,subcircuit_id:p.subcircuit_id??void 0,pcb_group_id:n.getGroup()?.pcb_group_id??void 0,footprinter_string:c});u.external_footprint_load_error.insert(y)}throw l}});return}if(typeof t=="string"&&H_(t)){if(n._hasStartedFootprintUrlLoad)return;n._hasStartedFootprintUrlLoad=!0;let c=t;e("load-footprint-url",async()=>{try{let l=await fetch(c);if(!l.ok)throw new Error(`Failed to fetch footprint: ${l.status}`);let u=await l.json(),p=G_({componentName:n.name,componentRotation:i,footprinterString:c,pinLabels:r,pcbPinLabels:s},u);n.addAll(p),n._markDirty("InitializePortsFromChildren")}catch(l){let u=n.root?.db;if(u&&n.source_component_id&&n.pcb_component_id){let p=n.getSubcircuit(),f=`${n.getString()} failed to load external footprint "${c}": `+(l instanceof Error?l.message:String(l)),y=Nm.parse({type:"external_footprint_load_error",message:f,pcb_component_id:n.pcb_component_id,source_component_id:n.source_component_id,subcircuit_id:p.subcircuit_id??void 0,pcb_group_id:n.getGroup()?.pcb_group_id??void 0,footprinter_string:c});u.external_footprint_load_error.insert(y)}throw l}});return}if(typeof t=="string"){let c=e9(t);if(!c||n._hasStartedFootprintUrlLoad)return;n._hasStartedFootprintUrlLoad=!0;let u=n.root?.platform?.footprintLibraryMap?.[c.footprintLib],p;if(typeof u=="function"&&(p=u),!p)return;let f=n.getInheritedMergedProperty("pcbStyle");e("load-lib-footprint",async()=>{try{let y=await p(c.footprintName,{resolvedPcbStyle:f}),g=null;if(Array.isArray(y)?g=y:Array.isArray(y.footprintCircuitJson)&&(g=y.footprintCircuitJson),!g)return;let x=G_({componentName:n.name,componentRotation:i,footprinterString:t,pinLabels:r,pcbPinLabels:s},g);n.addAll(x),!Array.isArray(y)&&y.cadModel&&(n._asyncFootprintCadModel=y.cadModel);for(let v of n.children)v.componentName==="Port"&&v._markDirty?.("PcbPortRender");n._markDirty("InitializePortsFromChildren")}catch(y){let g=n.root?.db;if(g&&n.source_component_id&&n.pcb_component_id){let x=n.getSubcircuit(),v=`${n.getString()} failed to load external footprint "${t}": `+(y instanceof Error?y.message:String(y)),S=Nm.parse({type:"external_footprint_load_error",message:v,pcb_component_id:n.pcb_component_id,source_component_id:n.source_component_id,subcircuit_id:x.subcircuit_id??void 0,pcb_group_id:n.getGroup()?.pcb_group_id??void 0,footprinter_string:t});g.external_footprint_load_error.insert(S)}throw y}});return}if(!(0,t9.isValidElement)(t)&&t.componentName==="Footprint"&&n.add(t),Array.isArray(t)&&!(0,t9.isValidElement)(t)&&t.length>0){try{let c=G_({componentName:n.name,componentRotation:i,footprinterString:"",pinLabels:r,pcbPinLabels:s},t);n.addAll(c)}catch(c){let l=n.root?.db;if(l&&n.source_component_id&&n.pcb_component_id){let u=n.getSubcircuit(),p=`${n.getString()} failed to load json footprint: `+(c instanceof Error?c.message:String(c)),f=Vx.parse({type:"circuit_json_footprint_load_error",message:p,pcb_component_id:n.pcb_component_id,source_component_id:n.source_component_id,subcircuit_id:u.subcircuit_id??void 0,pcb_group_id:n.getGroup()?.pcb_group_id??void 0});l.circuit_json_footprint_load_error.insert(f)}throw c}return}}function $Ot(n){if(n.root?.pcbDisabled||!n.pcb_component_id)return;let{pcbX:e,pcbY:t}=n._parsedProps,i=n.props?.pcbPositionAnchor;if(!i||e===void 0&&t===void 0)return;let r=QS(n.children);if(r.width===0||r.height===0)return;let o={...{x:(r.minX+r.maxX)/2,y:(r.minY+r.maxY)/2}},a=null;if(new Set(["center","top_left","top_center","top_right","center_left","center_right","bottom_left","bottom_center","bottom_right"]).has(i)){let u={left:r.minX,right:r.maxX,top:r.minY,bottom:r.maxY};switch(i){case"center":a=o;break;case"top_left":a={x:u.left,y:u.top};break;case"top_center":a={x:o.x,y:u.top};break;case"top_right":a={x:u.right,y:u.top};break;case"center_left":a={x:u.left,y:o.y};break;case"center_right":a={x:u.right,y:o.y};break;case"bottom_left":a={x:u.left,y:u.bottom};break;case"bottom_center":a={x:o.x,y:u.bottom};break;case"bottom_right":a={x:u.right,y:u.bottom};break}}else try{let u=n.portMap[i];u&&(a=u._getGlobalPcbPositionBeforeLayout())}catch{}if(!a)return;let l={...o};e!==void 0&&(l.x+=e-a.x),t!==void 0&&(l.y+=t-a.y),(Math.abs(l.x-o.x)>1e-6||Math.abs(l.y-o.y)>1e-6)&&n._repositionOnPcb(l)}var jOt=(0,Tet.default)("tscircuit:core"),BOt=h.object({x:He,y:He,z:He}),Gn=class extends Te{constructor(e){let t={...e},i=[];if(t.pinLabels&&!Array.isArray(t.pinLabels)){let{validPinLabels:r,invalidPinLabelsMessages:s}=LOt(t.pinLabels);t.pinLabels=r,i=s}super(t);d(this,"reactSubtrees",[]);d(this,"_impliedFootprint");d(this,"isPrimitiveContainer",!0);d(this,"_isNormalComponent",!0);d(this,"_attributeLowerToCamelNameMap",{_isnormalcomponent:"_isNormalComponent"});d(this,"_asyncSupplierPartNumbers");d(this,"_asyncFootprintCadModel");d(this,"_isCadModelChild");d(this,"pcb_missing_footprint_error_id");d(this,"_hasStartedFootprintUrlLoad",!1);d(this,"_invalidPinLabelMessages",[]);d(this,"_adjustSilkscreenTextAutomatically",!1);this._invalidPinLabelMessages=i,this._addChildrenFromStringFootprint(),this.initPorts()}get defaultInternallyConnectedPinNames(){return[]}get internallyConnectedPinNames(){return(this._parsedProps.internallyConnectedPins??this.defaultInternallyConnectedPinNames).map(t=>t.map(i=>typeof i=="number"?`pin${i}`:i))}doInitialSourceNameDuplicateComponentRemoval(){if(!this.name)return;let e=this.root;if(this.getSubcircuit().selectAll(`.${this.name}`).filter(r=>r!==this&&r._isNormalComponent&&r.renderPhaseStates?.SourceNameDuplicateComponentRemoval?.initialized).length>0){let r=this._getGlobalPcbPositionBeforeLayout(),s=this._getGlobalSchematicPositionBeforeLayout();e.db.source_failed_to_create_component_error.insert({component_name:this.name,error_type:"source_failed_to_create_component_error",message:`Cannot create component "${this.name}": A component with the same name already exists`,pcb_center:r,schematic_center:s}),this.shouldBeRemoved=!0;let o=[...this.children];for(let a of o)this.remove(a)}}initPorts(e={}){if(this.root?.schematicDisabled)return;let{config:t}=this,i=[],r=this._getSchematicPortArrangement();if(r&&!this._parsedProps.pinLabels){for(let l in r){let u=r[l].pins;if(Array.isArray(u))for(let p of u){let f=j1(p,this._parsedProps.pinLabels);i.push(new Vi({pinNumber:f,aliases:e.additionalAliases?.[`pin${f}`]??[]},{originDescription:`schPortArrangement:${l}`}))}}let a=["left","right","top","bottom"],c=1;for(let l of a){let u=r[`${l}Size`];for(let p=0;p<u;p++)i.push(new Vi({pinNumber:c++,aliases:e.additionalAliases?.[`pin${c}`]??[]},{originDescription:`schPortArrangement:${l}`}))}}let s=this._parsedProps.pinLabels;if(s)for(let[a,c]of Object.entries(s)){a=a.replace("pin","");let l=i.find(f=>f._parsedProps.pinNumber===Number(a)),u=Array.isArray(c)?c[0]:c,p=Array.isArray(c)?c.slice(1):[];l?(l.externallyAddedAliases.push(u,...p),l.props.name=u):(l=new Vi({pinNumber:parseInt(a),name:u,aliases:[...p,...e.additionalAliases?.[`pin${parseInt(a)}`]??[]]},{originDescription:`pinLabels:pin${a}`}),i.push(l))}if(t.schematicSymbolName&&!e.ignoreSymbolPorts){let a=_i[this._getSchematicSymbolNameOrThrow()];if(!a)return;for(let c of a.ports){let l=Oet(c.labels);if(!l)continue;let u=i.find(p=>p._parsedProps.pinNumber===Number(l));if(u)u.schematicSymbolPortDef=c;else{let p=O1(c.labels.concat(e.additionalAliases?.[`pin${l}`]??[]));p&&(p.originDescription=`schematicSymbol:labels[0]:${c.labels[0]}`,p.schematicSymbolPortDef=c,i.push(p))}}this.addAll(i)}if(!this._getSchematicPortArrangement()){let a=this.getPortsFromFootprint(e);for(let c of a)i.some(l=>l.isMatchingAnyOf(c.getNameAndAliases()))||i.push(c)}let o=e.pinCount??this._getPinCount()??0;for(let a=1;a<=o;a++){if(i.find(l=>l._parsedProps.pinNumber===a))continue;if(!r){i.push(new Vi({pinNumber:a,aliases:e.additionalAliases?.[`pin${a}`]??[]}));continue}let c=[...r.leftSide?.pins??[],...r.rightSide?.pins??[],...r.topSide?.pins??[],...r.bottomSide?.pins??[]].map(l=>j1(l,this._parsedProps.pinLabels));["leftSize","rightSize","topSize","bottomSize","leftPinCount","rightPinCount","topPinCount","bottomPinCount"].some(l=>l in r)&&(c=Array.from({length:this._getPinCount()},(l,u)=>u+1)),c.includes(a)&&i.push(new Vi({pinNumber:a,aliases:e.additionalAliases?.[`pin${a}`]??[]},{originDescription:`notOtherwiseAddedButDeducedFromPinCount:${a}`}))}i.length>0&&this.addAll(i)}_getImpliedFootprintString(){return null}_addChildrenFromStringFootprint(){let{pcbRotation:e,pinLabels:t,pcbPinLabels:i}=this.props,{footprint:r}=this.props;if(r??(r=this._getImpliedFootprintString?.()),!!r&&typeof r=="string"){if(H_(r)||n9(r)||e9(r))return;let s=_E.string(r).soup(),o=G_({componentName:this.name??this.componentName,componentRotation:e,footprinterString:r,pinLabels:t,pcbPinLabels:i},s);this.addAll(o)}}get portMap(){return new Proxy({},{get:(e,t)=>{let i=this.children.find(r=>r.componentName==="Port"&&r.isMatchingNameOrAlias(t));if(!i)throw new Error(`There was an issue finding the port "${t.toString()}" inside of a ${this.componentName} component with name: "${this.props.name}". This is a bug in @tscircuit/core`);return i}})}getInstanceForReactElement(e){for(let t of this.reactSubtrees)if(t.element===e)return t.component;return null}doInitialSourceRender(){let e=this.config.sourceFtype;if(!e)return;let{db:t}=this.root,{_parsedProps:i}=this,r=t.source_component.insert({ftype:e,name:this.name,manufacturer_part_number:i.manufacturerPartNumber??i.mfn,supplier_part_numbers:i.supplierPartNumbers});this.source_component_id=r.source_component_id}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root;if(this._invalidPinLabelMessages?.length&&this.root?.db)for(let s of this._invalidPinLabelMessages){let o="pinLabels",a=s.match(/^Invalid pin label:\s*([^=]+)=\s*'([^']+)'/);a&&(o=`pinLabels['${a[2]}']`),this.root.db.source_property_ignored_warning.insert({source_component_id:this.source_component_id,property_name:o,message:s,error_type:"source_property_ignored_warning"})}let{schematicSymbolName:t}=this.config,{_parsedProps:i}=this;i.symbol&&(0,Ua.isValidElement)(i.symbol)?this._doInitialSchematicComponentRenderWithReactSymbol(i.symbol):t?this._doInitialSchematicComponentRenderWithSymbol():this._getSchematicBoxDimensions()&&this._doInitialSchematicComponentRenderWithSchematicBoxDimensions();let r=this.getSubcircuit()?._getSchematicManualPlacementForComponent(this);if(this.schematic_component_id&&(this.props.schX!==void 0||this.props.schY!==void 0)&&r){if(!this.schematic_component_id)return;let s=Xx.parse({type:"schematic_manual_edit_conflict_warning",schematic_manual_edit_conflict_warning_id:`schematic_manual_edit_conflict_${this.source_component_id}`,message:`${this.getString()} has both manual placement and prop coordinates. schX and schY will be used. Remove schX/schY or clear the manual placement.`,schematic_component_id:this.schematic_component_id,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id});e.schematic_manual_edit_conflict_warning.insert(s)}}_getSchematicSymbolDisplayValue(){}_getInternallyConnectedPins(){if(this.internallyConnectedPinNames.length===0)return[];let e=[];for(let t of this.internallyConnectedPinNames){let i=[];for(let r of t)i.push(this.portMap[r]);e.push(i)}return e}_doInitialSchematicComponentRenderWithSymbol(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getSchematicSymbolNameOrThrow(),r=_i[i],s=this._getGlobalSchematicPositionBeforeLayout();if(r){let o=e.schematic_component.insert({center:s,size:r.size,source_component_id:this.source_component_id,is_box_with_pins:!0,symbol_name:i,symbol_display_value:this._getSchematicSymbolDisplayValue()});this.schematic_component_id=o.schematic_component_id}}_doInitialSchematicComponentRenderWithReactSymbol(e){if(this.root?.schematicDisabled)return;let{db:t}=this.root,i=this._getGlobalSchematicPositionBeforeLayout(),r=t.schematic_component.insert({center:i,size:{width:0,height:0},source_component_id:this.source_component_id,symbol_display_value:this._getSchematicSymbolDisplayValue(),is_box_with_pins:!1});this.schematic_component_id=r.schematic_component_id}_doInitialSchematicComponentRenderWithSchematicBoxDimensions(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getSchematicBoxDimensions(),r={};if(Array.isArray(t.pinLabels))t.pinLabels.forEach((y,g)=>{r[String(g+1)]=y});else for(let[y,g]of Object.entries(t.pinLabels??{}))r[y]=Array.isArray(g)?g[0]:g;let s=this._getGlobalSchematicPositionBeforeLayout(),o=this._getSchematicPortArrangement(),a=e.schematic_component.insert({center:s,rotation:t.schRotation??0,size:i.getSize(),port_arrangement:YRt(o),pin_spacing:t.schPinSpacing??.2,pin_styles:BRt(t.schPinStyle,t.pinLabels),port_labels:r,source_component_id:this.source_component_id}),c=o?.topSide!==void 0||o?.bottomSide!==void 0,l=i?.getSize().width,u=i?.getSize().height,p=e.schematic_text.insert({text:t.manufacturerPartNumber??"",schematic_component_id:a.schematic_component_id,anchor:"left",rotation:0,position:{x:c?s.x+(l??0)/2+.1:s.x-(l??0)/2,y:c?s.y+(u??0)/2+.35:s.y-(u??0)/2-.13},color:"#006464",font_size:.18}),f=e.schematic_text.insert({text:t.name??"",schematic_component_id:a.schematic_component_id,anchor:"left",rotation:0,position:{x:c?s.x+(l??0)/2+.1:s.x-(l??0)/2,y:c?s.y+(u??0)/2+.55:s.y+(u??0)/2+.13},color:"#006464",font_size:.18});this.schematic_component_id=a.schematic_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this.getSubcircuit(),r=t.layer??"top";if(r!=="top"&&r!=="bottom"){let p=Am.parse({type:"pcb_component_invalid_layer_error",message:`Component cannot be placed on layer '${r}'. Components can only be placed on 'top' or 'bottom' layers.`,source_component_id:this.source_component_id,layer:r,subcircuit_id:i.subcircuit_id??void 0});e.pcb_component_invalid_layer_error.insert(p)}let s=this._computePcbGlobalTransformBeforeLayout(),a=Js(s).rotation.angle*180/Math.PI,c=e.pcb_component.insert({center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,layer:r==="top"||r==="bottom"?r:"top",rotation:t.pcbRotation??a,source_component_id:this.source_component_id,subcircuit_id:i.subcircuit_id??void 0,do_not_place:t.doNotPlace??!1,obstructs_within_bounds:t.obstructsWithinBounds??!0});if(!(t.footprint??this._getImpliedFootprintString())&&!this.isGroup){let p=e.pcb_missing_footprint_error.insert({message:`No footprint found for component: ${this.getString()}`,source_component_id:`${this.source_component_id}`,error_type:"pcb_missing_footprint_error"});this.pcb_missing_footprint_error_id=p.pcb_missing_footprint_error_id}this.pcb_component_id=c.pcb_component_id;let u=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if((this.props.pcbX!==void 0||this.props.pcbY!==void 0)&&u){let p=Gx.parse({type:"pcb_manual_edit_conflict_warning",pcb_manual_edit_conflict_warning_id:`pcb_manual_edit_conflict_${this.source_component_id}`,message:`${this.getString()} has both manual placement and prop coordinates. pcbX and pcbY will be used. Remove pcbX/pcbY or clear the manual placement.`,pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,subcircuit_id:i.subcircuit_id??void 0});e.pcb_manual_edit_conflict_warning.insert(p)}}doInitialPcbComponentSizeCalculation(){if(this.root?.pcbDisabled||!this.pcb_component_id)return;let{db:e}=this.root,{_parsedProps:t}=this,i=QS(this.children);if(i.width===0||i.height===0)return;let r={x:(i.minX+i.maxX)/2,y:(i.minY+i.maxY)/2};e.pcb_component.update(this.pcb_component_id,{center:r,width:i.width,height:i.height})}updatePcbComponentSizeCalculation(){this.doInitialPcbComponentSizeCalculation()}doInitialSchematicComponentSizeCalculation(){if(this.root?.schematicDisabled||!this.schematic_component_id)return;let{db:e}=this.root;if(!e.schematic_component.get(this.schematic_component_id))return;let i=[],r=u=>{for(let p of u){if(p.isSchematicPrimitive&&p.componentName==="SchematicLine"){let f=e.schematic_line.get(p.schematic_line_id);f&&i.push(f)}if(p.isSchematicPrimitive&&p.componentName==="SchematicRect"){let f=e.schematic_rect.get(p.schematic_rect_id);f&&i.push(f)}if(p.isSchematicPrimitive&&p.componentName==="SchematicCircle"){let f=e.schematic_circle.get(p.schematic_circle_id);f&&i.push(f)}if(p.isSchematicPrimitive&&p.componentName==="SchematicArc"){let f=e.schematic_arc.get(p.schematic_arc_id);f&&i.push(f)}if(p.isSchematicPrimitive&&p.componentName==="SchematicText"){let f=e.schematic_text.get(p.schematic_text_id);f&&i.push(f)}p.children&&p.children.length>0&&r(p.children)}};if(r(this.children),i.length===0)return;let s=Ret(i),o=Math.abs(s.maxX-s.minX),a=Math.abs(s.maxY-s.minY);if(o===0&&a===0)return;let c=(s.minX+s.maxX)/2,l=(s.minY+s.maxY)/2;e.schematic_component.update(this.schematic_component_id,{center:{x:c,y:l},size:{width:o,height:a}})}updateSchematicComponentSizeCalculation(){this.doInitialSchematicComponentSizeCalculation()}doInitialPcbComponentAnchorAlignment(){$Ot(this)}updatePcbComponentAnchorAlignment(){this.doInitialPcbComponentAnchorAlignment()}_renderReactSubtree(e){let t=Net(e);return{element:e,component:t}}doInitialInitializePortsFromChildren(){this.initPorts()}doInitialReactSubtreesRender(){let e=this.props.footprint;(0,Ua.isValidElement)(e)&&(this.children.some(s=>s.componentName==="Footprint")||this.add(e));let t=this.props.symbol;(0,Ua.isValidElement)(t)&&(this.children.some(s=>s.componentName==="Symbol")||this.add(t));let i=this.props.cadModel;if((0,Ua.isValidElement)(i)){this._isCadModelChild=!0;let r=this.children.some(o=>o.componentName==="CadAssembly"),s=this.children.some(o=>o.componentName==="CadModel");!r&&!s&&this.add(i)}}doInitialPcbFootprintStringRender(){DOt(this,(e,t)=>this._queueAsyncEffect(e,t))}_hasExistingPortExactly(e){return this.children.filter(i=>i.componentName==="Port").some(i=>{let r=e.getNameAndAliases(),s=i.getNameAndAliases();return r.length===s.length&&r.every(o=>s.includes(o))})}add(e){let t;if((0,Ua.isValidElement)(e)){let i=this._renderReactSubtree(e);this.reactSubtrees.push(i),t=i.component}else t=e;if(t.componentName==="Port"){if(this._hasExistingPortExactly(t))return;let r=this.children.filter(s=>s.componentName==="Port").find(s=>s.isMatchingAnyOf(t.getNameAndAliases()));r&&jOt(`Similar ports added. Port 1: ${r}, Port 2: ${t}`)}super.add(t)}getPortsFromFootprint(e){let{footprint:t}=this.props;if((!t||(0,Ua.isValidElement)(t))&&(t=this.children.find(r=>r.componentName==="Footprint")),typeof t=="string"){if(H_(t))return[];if(n9(t))return[];if(e9(t))return[];let r=_E.string(t).soup(),s=[];for(let o of r)if("port_hints"in o&&o.port_hints){let a=O1(o.port_hints,e);if(!a)continue;a.originDescription=`footprint:string:${t}:port_hints[0]:${o.port_hints[0]}`,s.push(a)}return s}if(!(0,Ua.isValidElement)(t)&&t&&t.componentName==="Footprint"){let r=t,s=1,o=[];for(let a of r.children){if(!a.props.portHints)continue;let c=a.props.portHints;c.some(p=>p.startsWith("pin"))||(c=[...c,`pin${s}`]),s++;let u=O1(c);u&&(u.originDescription=`footprint:${t}`,o.push(u))}return o}let i=[];if(!t){for(let r of this.children)if(r.props.portHints&&r.isPcbPrimitive){let s=O1(r.props.portHints);s&&i.push(s)}}return i}getPortsFromSchematicSymbol(){if(this.root?.schematicDisabled)return[];let{config:e}=this;if(!e.schematicSymbolName)return[];let t=_i[e.schematicSymbolName];if(!t)return[];let i=[];for(let r of t.ports){let s=O1(r.labels);s&&(s.schematicSymbolPortDef=r,i.push(s))}return i}doInitialCreateNetsFromProps(){this._createNetsFromProps(this._getNetsFromConnectionsProp())}_getNetsFromConnectionsProp(){let{_parsedProps:e}=this,t=[];if(e.connections)for(let[i,r]of Object.entries(e.connections)){let s=Array.isArray(r)?r:[r];for(let o of s)t.push(String(o))}return t}_createNetsFromProps(e){KS(this,e)}_getPcbCircuitJsonBounds(){let{db:e}=this.root;if(!this.pcb_component_id)return super._getPcbCircuitJsonBounds();let t=e.pcb_component.get(this.pcb_component_id);return{center:{x:t.center.x,y:t.center.y},bounds:{left:t.center.x-t.width/2,top:t.center.y-t.height/2,right:t.center.x+t.width/2,bottom:t.center.y+t.height/2},width:t.width,height:t.height}}_getPinCountFromSchematicPortArrangement(){let e=this._getSchematicPortArrangement();if(!e)return 0;if(!Let(e))return(e.leftSize??e.leftPinCount??0)+(e.rightSize??e.rightPinCount??0)+(e.topSize??e.topPinCount??0)+(e.bottomSize??e.bottomPinCount??0);let{leftSide:i,rightSide:r,topSide:s,bottomSide:o}=e;return Math.max(...i?.pins??[],...r?.pins??[],...s?.pins??[],...o?.pins??[])}_getPinCount(){if(this._getSchematicPortArrangement())return this._getPinCountFromSchematicPortArrangement();let t=this.getPortsFromFootprint();if(t.length>0)return t.length;let{pinLabels:i}=this._parsedProps;if(i){if(Array.isArray(i))return i.length;let r=Object.keys(i).map(s=>s.startsWith("pin")?parseInt(s.slice(3)):parseInt(s)).filter(s=>!Number.isNaN(s));return r.length>0?Math.max(...r):Object.keys(i).length}return 0}_getSchematicPortArrangement(){return this._parsedProps.schPinArrangement??this._parsedProps.schPortArrangement}_getPinLabelsFromPorts(){let e=this.selectAll("port"),t={};for(let i of e){let r=i.props.pinNumber;if(r!==void 0){let s=i._getBestDisplayPinLabel();s&&(t[`pin${r}`]=s)}}return t}_getSchematicBoxDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;let{_parsedProps:e}=this,t=this._getPinCount(),i=e.schPinSpacing??.2,s={...this._getPinLabelsFromPorts(),...e.pinLabels};return QRt({schWidth:e.schWidth,schHeight:e.schHeight,schPinSpacing:i,numericSchPinStyle:nOt(e.schPinStyle,s),pinCount:t,schPortArrangement:this._getSchematicPortArrangement(),pinLabels:s})}getFootprinterString(){return typeof this._parsedProps.footprint=="string"?this._parsedProps.footprint:null}doInitialCadModelRender(){if(this._isCadModelChild||this.props.doNotPlace)return;let{db:e}=this.root,{boardThickness:t=0}=this.root?._getBoard()??{},i=this._parsedProps.cadModel,r=i===void 0?this._asyncFootprintCadModel:i,s=this.getFootprinterString()??this._getImpliedFootprintString();if(!this.pcb_component_id||!r&&!s||r===null)return;let o=this._getPcbCircuitJsonBounds();if(typeof r=="string")throw new Error("String cadModel not yet implemented");let a=BOt.parse({x:0,y:0,z:typeof r?.rotationOffset=="number"?r.rotationOffset:0,...typeof r?.rotationOffset=="object"?r.rotationOffset??{}:{}}),c=zh.parse({x:0,y:0,z:0,...typeof r?.positionOffset=="object"?r.positionOffset:{}}),l=r&&typeof r=="object"&&"zOffsetFromSurface"in r&&r.zOffsetFromSurface!==void 0?X.parse(r.zOffsetFromSurface):0,u=this.props.layer==="bottom"?"bottom":"top",p=this._computePcbGlobalTransformBeforeLayout(),y=Js(p).rotation.angle*180/Math.PI,g=u==="bottom",x=y+(a.z??0),v=sd(x),S=e.cad_component.insert({position:{x:o.center.x+c.x,y:o.center.y+c.y,z:(u==="bottom"?-t/2:t/2)+(u==="bottom"?-l:l)+c.z},rotation:{x:a.x,y:a.y+(g?180:0),z:sd(g?-v:v)},pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,model_stl_url:"stlUrl"in(r??{})?this._addCachebustToModelUrl(r.stlUrl):void 0,model_obj_url:"objUrl"in(r??{})?this._addCachebustToModelUrl(r.objUrl):void 0,model_mtl_url:"mtlUrl"in(r??{})?this._addCachebustToModelUrl(r.mtlUrl):void 0,model_gltf_url:"gltfUrl"in(r??{})?this._addCachebustToModelUrl(r.gltfUrl):void 0,model_glb_url:"glbUrl"in(r??{})?this._addCachebustToModelUrl(r.glbUrl):void 0,model_step_url:"stepUrl"in(r??{})?this._addCachebustToModelUrl(r.stepUrl):void 0,model_wrl_url:"wrlUrl"in(r??{})?this._addCachebustToModelUrl(r.wrlUrl):void 0,model_jscad:"jscad"in(r??{})?r.jscad:void 0,model_unit_to_mm_scale_factor:typeof r?.modelUnitToMmScale=="number"?r.modelUnitToMmScale:void 0,footprinter_string:typeof s=="string"&&!r?s:void 0});this.cad_component_id=S.cad_component_id}_addCachebustToModelUrl(e){if(!e||!e.includes("modelcdn.tscircuit.com"))return e;let t=this.root?.getClientOrigin()??"";return`${e}${e.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(t)}`}_getPartsEngineCacheKey(e,t){return JSON.stringify({ftype:e.ftype,name:e.name,manufacturer_part_number:e.manufacturer_part_number,footprinterString:t})}async _getSupplierPartNumbers(e,t,i){if(this.props.doNotPlace)return{};let r=this.root?.platform?.localCacheEngine,s=this._getPartsEngineCacheKey(t,i);if(r){let c=await r.getItem(s);if(c)try{return JSON.parse(c)}catch{}}let o=await Promise.resolve(e.findPart({sourceComponent:t,footprinterString:i}));if(typeof o=="string"){if(o.includes("<!DOCTYPE")||o.includes("<html"))throw new Error(`Failed to fetch supplier part numbers: Received HTML response instead of JSON. Response starts with: ${o.substring(0,100)}`);if(o==="Not found")return{};throw new Error(`Invalid supplier part numbers format: Expected object but got string: "${o}"`)}if(!o||Array.isArray(o)||typeof o!="object"){let c=o===null?"null":Array.isArray(o)?"array":typeof o;throw new Error(`Invalid supplier part numbers format: Expected object but got ${c}`)}let a=o;if(r)try{await r.setItem(s,JSON.stringify(a))}catch{}return a}doInitialPartsEngineRender(){if(this.props.doNotPlace)return;let e=this.getInheritedProperty("partsEngine");if(!e)return;let{db:t}=this.root,i=t.source_component.get(this.source_component_id);if(!i||i.supplier_part_numbers)return;let r;this.props.footprint&&typeof this.props.footprint=="string"&&(r=this.props.footprint);let s=this._getSupplierPartNumbers(e,i,r);if(!(s instanceof Promise)){t.source_component.update(this.source_component_id,{supplier_part_numbers:s});return}this._queueAsyncEffect("get-supplier-part-numbers",async()=>{await s.then(o=>{this._asyncSupplierPartNumbers=o,this._markDirty("PartsEngineRender")}).catch(o=>{this._asyncSupplierPartNumbers={};let a=Bx.parse({type:"unknown_error_finding_part",message:`Failed to fetch supplier part numbers for ${this.getString()}: ${o.message}`,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id});t.unknown_error_finding_part.insert(a),this._markDirty("PartsEngineRender")})})}updatePartsEngineRender(){if(this.props.doNotPlace)return;let{db:e}=this.root,t=e.source_component.get(this.source_component_id);if(t&&!t.supplier_part_numbers&&this._asyncSupplierPartNumbers){e.source_component.update(this.source_component_id,{supplier_part_numbers:this._asyncSupplierPartNumbers});return}}doInitialAssignFallbackProps(){let{_parsedProps:e}=this;e.connections&&!this.name&&(this.fallbackUnassignedName=this.getSubcircuit().getNextAvailableName(this))}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}_createTracesFromConnectionsProp(){let{_parsedProps:e}=this;if(e.connections)for(let[t,i]of Object.entries(e.connections)){let r=Array.isArray(i)?i:[i];for(let s of r)this.add(new oo({from:`.${this.name} > .${t}`,to:String(s)}))}}doInitialSourceDesignRuleChecks(){NOt(this)}_getMinimumFlexContainerSize(){return COt(this)}_repositionOnPcb(e){return IOt(this,e)}doInitialSilkscreenOverlapAdjustment(){return OOt(this)}isRelativelyPositioned(){return this._parsedProps.pcbX!==void 0||this._parsedProps.pcbY!==void 0}},YOt=({boardAnchorPosition:n,boardAnchorAlignment:e,width:t,height:i})=>{let{x:r,y:s}=n,o=r,a=s;switch(e){case"top_left":o=r+t/2,a=s-i/2;break;case"top_right":o=r-t/2,a=s-i/2;break;case"bottom_left":o=r+t/2,a=s+i/2;break;case"bottom_right":o=r-t/2,a=s+i/2;break;case"top":o=r,a=s-i/2;break;case"bottom":o=r,a=s+i/2;break;case"left":o=r+t/2,a=s;break;case"right":o=r-t/2,a=s;break;case"center":default:break}return{x:o,y:a}},XOt=class{constructor(n,e={}){d(this,"input");d(this,"isRouting",!1);d(this,"solver");d(this,"eventHandlers",{complete:[],error:[],progress:[]});d(this,"cycleCount",0);d(this,"stepDelay");d(this,"timeoutId");this.input=n;let{capacityDepth:t,targetMinCapacity:i,stepDelay:r=0,useAssignableViaSolver:s=!1}=e,{AutoroutingPipelineSolver:o,AssignableViaAutoroutingPipelineSolver:a}=X4,c=s?a:o;this.solver=new c(n,{capacityDepth:t,targetMinCapacity:i,cacheProvider:null}),this.stepDelay=r}start(){this.isRouting||(this.isRouting=!0,this.cycleCount=0,this.runCycleAndQueueNextCycle())}runCycleAndQueueNextCycle(){if(this.isRouting)try{if(this.solver.solved||this.solver.failed){this.solver.failed?this.emitEvent({type:"error",error:new L1(this.solver.error||"Routing failed")}):this.emitEvent({type:"complete",traces:this.solver.getOutputSimpleRouteJson().traces||[]}),this.isRouting=!1;return}let n=Date.now(),e=this.solver.iterations;for(;Date.now()-n<250&&!this.solver.failed&&!this.solver.solved;)this.solver.step();let t=(this.solver.iterations-e)/(Date.now()-n)*1e3;this.cycleCount++;let i=this.solver?.preview()||void 0,r=this.solver.progress;this.emitEvent({type:"progress",steps:this.cycleCount,iterationsPerSecond:t,progress:r,phase:this.solver.getCurrentPhase(),debugGraphics:i}),this.stepDelay>0?this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),this.stepDelay):this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),0)}catch(n){this.emitEvent({type:"error",error:n instanceof Error?new L1(n.message):new L1(String(n))}),this.isRouting=!1}}stop(){this.isRouting&&(this.isRouting=!1,this.timeoutId!==void 0&&(clearTimeout(this.timeoutId),this.timeoutId=void 0))}on(n,e){n==="complete"?this.eventHandlers.complete.push(e):n==="error"?this.eventHandlers.error.push(e):n==="progress"&&this.eventHandlers.progress.push(e)}emitEvent(n){if(n.type==="complete")for(let e of this.eventHandlers.complete)e(n);else if(n.type==="error")for(let e of this.eventHandlers.error)e(n);else if(n.type==="progress")for(let e of this.eventHandlers.progress)e(n)}solveSync(){if(this.solver.solve(),this.solver.failed)throw new L1(this.solver.error||"Routing failed");return this.solver.getOutputSimpleRouteJson().traces||[]}},p9=class extends Te{constructor(){super(...arguments);d(this,"matchedPort",null)}get config(){return{componentName:"TraceHint",zodProps:wW}}doInitialPortMatching(){let{db:e}=this.root,{_parsedProps:t,parent:i}=this;if(!i)return;if(i.componentName==="Trace"){this.renderError(`Port inference inside trace is not yet supported (${this})`);return}if(!i)throw new Error("TraceHint has no parent");if(!t.for){this.renderError(`TraceHint has no for property (${this})`);return}let r=i.selectOne(t.for,{type:"port"});r||this.renderError(`${this} could not find port for selector "${t.for}"`),this.matchedPort=r,r.registerMatch(this)}getPcbRouteHints(){let{_parsedProps:e}=this,t=e.offset?[e.offset]:e.offsets;if(!t)return[];let i=this._computePcbGlobalTransformBeforeLayout();return t.map(r=>({...ze(i,r),via:r.via,to_layer:r.to_layer,trace_width:r.trace_width}))}doInitialPcbTraceHintRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this;e.pcb_trace_hint.insert({pcb_component_id:this.matchedPort?.pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,route:this.getPcbRouteHints()})}},Get=({circuitJson:n,editEvents:e,manualEditsFile:t})=>{let i={...t,pcb_placements:[...t.pcb_placements??[]]};for(let r of e)if(r.edit_event_type==="edit_pcb_component_location"){let{pcb_component_id:s,new_center:o}=r,a=Be(n).pcb_component.get(s);if(!a)continue;let c=Be(n).source_component.get(a.source_component_id);if(!c)continue;let l=i.pcb_placements?.findIndex(p=>p.selector===c.name),u={selector:c.name,center:o,relative_to:"group_center"};l>=0?i.pcb_placements[l]=u:i.pcb_placements.push(u)}return i},Het=({circuitJson:n,editEvents:e,manualEditsFile:t})=>{let i={...t,schematic_placements:[...t.schematic_placements??[]]};for(let r of e)if(r.edit_event_type==="edit_schematic_component_location"){let{schematic_component_id:s,new_center:o}=r,a=Be(n).schematic_component.get(s);if(!a||!a.source_component_id)continue;let c=Be(n).source_component.get(a.source_component_id);if(!c)continue;let l=i.schematic_placements?.findIndex(p=>p.selector===c.name),u={selector:c.name,center:o,relative_to:"group_center"};l>=0?i.schematic_placements[l]=u:i.schematic_placements.push(u)}return i},UOt=({circuitJson:n,editEvents:e,manualEditsFile:t})=>{let i=e.filter(o=>o.edit_event_type==="edit_schematic_component_location"),r=e.filter(o=>o.edit_event_type==="edit_pcb_component_location"),s=t;return i.length>0&&(s=Het({circuitJson:n,editEvents:i,manualEditsFile:s})),r.length>0&&(s=Get({circuitJson:n,editEvents:r,manualEditsFile:s})),s},VOt=(n,e)=>{if(Be(n).pcb_trace_hint.get(e.pcb_trace_hint_id))n=n.map(i=>i.pcb_trace_hint_id===e.pcb_trace_hint_id?{...i,route:e.route}:i);else{let i=Be(n).pcb_port.get(e.pcb_port_id);n=n.filter(r=>!(r.type==="pcb_trace_hint"&&r.pcb_port_id===e.pcb_port_id)).concat([{type:"pcb_trace_hint",pcb_trace_hint_id:e.pcb_trace_hint_id,route:e.route,pcb_port_id:e.pcb_port_id,pcb_component_id:i?.pcb_component_id}])}return n},GOt=({circuitJson:n,editEvents:e})=>{n=JSON.parse(JSON.stringify(n));for(let t of e)if(t.edit_event_type==="edit_pcb_component_location"){let i=n.find(s=>s.type==="pcb_component"&&s.pcb_component_id===t.pcb_component_id);if((!i||i.center.x!==t.new_center.x||i.center.y!==t.new_center.y)&&t.original_center){let s=Nn(t.new_center.x-t.original_center.x,t.new_center.y-t.original_center.y);n=n.map(o=>o.pcb_component_id!==t.pcb_component_id?o:f4(o,s))}}else t.edit_event_type==="edit_schematic_component_location"?n=n.map(i=>i.type==="schematic_component"&&i.schematic_component_id===t.schematic_component_id?{...i,center:t.new_center}:i):t.edit_event_type==="edit_pcb_trace_hint"&&(n=VOt(n,t));return n},Wet=(n,e)=>{let t=n.source_group.list(),i=[],r=s=>{let o=t.filter(a=>a.parent_subcircuit_id===s);for(let a of o)a.subcircuit_id&&(i.push(a.subcircuit_id),r(a.subcircuit_id))};return r(e),i},i9=({db:n,circuitJson:e,subcircuit_id:t,minTraceWidth:i=.1})=>{if(!n&&e&&(n=Be(e)),!n)throw new Error("db or circuitJson is required");let r=n.pcb_trace_hint.list(),s=t?new Set([t]):null;if(t){let N=Wet(n,t);for(let I of N)s.add(I)}let o=(e??n.toArray()).filter(N=>!t||"subcircuit_id"in N&&s.has(N.subcircuit_id)),a=n.pcb_board.list()[0];n=Be(o);let c=er(o),l=Yet([...n.pcb_component.list(),...n.pcb_smtpad.list(),...n.pcb_plated_hole.list(),...n.pcb_hole.list(),...n.pcb_via.list(),...n.pcb_cutout.list()].filter(N=>!t||s?.has(N.subcircuit_id)),c);for(let N of l){let I=N.connectedTo.flatMap(A=>c.getIdsConnectedToNet(A));N.connectedTo.push(...I)}let u=l.flatMap(N=>[{x:N.center.x-N.width/2,y:N.center.y-N.height/2},{x:N.center.x+N.width/2,y:N.center.y+N.height/2}]).concat(a?.outline??[]),p;if(a&&!a.outline?p={minX:a.center.x-a.width/2,maxX:a.center.x+a.width/2,minY:a.center.y-a.height/2,maxY:a.center.y+a.height/2}:p={minX:Math.min(...u.map(N=>N.x))-1,maxX:Math.max(...u.map(N=>N.x))+1,minY:Math.min(...u.map(N=>N.y))-1,maxY:Math.max(...u.map(N=>N.y))+1},t){let N=n.pcb_group.getWhere({subcircuit_id:t});if(N?.width&&N.height){let I={minX:N.center.x-N.width/2,maxX:N.center.x+N.width/2,minY:N.center.y-N.height/2,maxY:N.center.y+N.height/2};p={minX:Math.min(p.minX,I.minX),maxX:Math.max(p.maxX,I.maxX),minY:Math.min(p.minY,I.minY),maxY:Math.max(p.maxY,I.maxY)}}}let f=new Set(n.pcb_trace.list().map(N=>N.source_trace_id).filter(N=>!!N)),y=n.source_trace.list().filter(N=>!f.has(N.source_trace_id)).map(N=>{let I=N.connected_source_port_ids.map(H=>{let Q=n.source_port.get(H),tt=n.pcb_port.getWhere({source_port_id:H});return{...Q,...tt}});if(I.length<2)return null;let[A,R]=I,j=A.layers?.[0]??"top",B=R.layers?.[0]??"top",G=r.filter(H=>H.pcb_port_id===A.pcb_port_id||H.pcb_port_id===R.pcb_port_id),U=[];for(let H of G){let tt=n.pcb_port.get(H.pcb_port_id)?.layers?.[0]??"top";for(let V of H.route)U.push({x:V.x,y:V.y,layer:tt})}return{name:N.source_trace_id??c.getNetConnectedToId(N.source_trace_id)??"",source_trace_id:N.source_trace_id,width:N.min_trace_thickness,pointsToConnect:[{x:A.x,y:A.y,layer:j,pointId:A.pcb_port_id,pcb_port_id:A.pcb_port_id},...U,{x:R.x,y:R.y,layer:B,pointId:R.pcb_port_id,pcb_port_id:R.pcb_port_id}]}}).filter(N=>N!==null),g=new Map(y.map(N=>[N.source_trace_id,N])),x=n.source_net.list().filter(N=>!t||s?.has(N.subcircuit_id)),v=[];for(let N of x){let I=n.source_trace.list().filter(A=>A.connected_source_net_ids?.includes(N.source_net_id));v.push({name:N.source_net_id??c.getNetConnectedToId(N.source_net_id),pointsToConnect:I.flatMap(A=>n.pcb_port.list().filter(j=>A.connected_source_port_ids.includes(j.source_port_id)).map(j=>({x:j.x,y:j.y,layer:j.layers?.[0]??"top",pointId:j.pcb_port_id,pcb_port_id:j.pcb_port_id})))})}let S=n.pcb_breakout_point.list().filter(N=>!t||s?.has(N.subcircuit_id)),P=[],T=new Map;for(let N of S){let I={x:N.x,y:N.y,layer:"top"};if(N.source_trace_id){let A=g.get(N.source_trace_id)??T.get(N.source_trace_id);if(A)A.pointsToConnect.push(I);else{let R={name:N.source_trace_id,source_trace_id:N.source_trace_id,pointsToConnect:[I]};P.push(R),T.set(N.source_trace_id,R)}}else if(N.source_net_id){let A=v.find(R=>R.name===N.source_net_id);A?A.pointsToConnect.push(I):P.push({name:N.source_net_id,pointsToConnect:[I]})}else if(N.source_port_id){let A=n.pcb_port.getWhere({source_port_id:N.source_port_id});A&&P.push({name:N.source_port_id,source_trace_id:void 0,pointsToConnect:[{x:A.x,y:A.y,layer:A.layers?.[0]??"top",pointId:A.pcb_port_id,pcb_port_id:A.pcb_port_id},I]})}}let k=[...y,...v,...P],C=new Map;for(let N of k)for(let I of N.pointsToConnect)I.pointId&&C.set(I.pointId,N);let E=n.pcb_trace.list().filter(N=>!t||s?.has(N.subcircuit_id));for(let N of E){let I=new Set;for(let j of N.route)j.start_pcb_port_id&&I.add(j.start_pcb_port_id),j.end_pcb_port_id&&I.add(j.end_pcb_port_id);if(I.size<2)continue;let A=I.values().next().value;if(!A)continue;let R=C.get(A);R&&[...I].every(j=>C.get(j)===R)&&(R.externallyConnectedPointIds??(R.externallyConnectedPointIds=[]),R.externallyConnectedPointIds.push([...I]))}return{simpleRouteJson:{bounds:p,obstacles:l,connections:k,layerCount:a?.num_layers??2,minTraceWidth:i,outline:a?.outline?.map(N=>({...N}))},connMap:c}},HOt=n=>{let e={};if(!n)return e;for(let i of Xa)e[i]=0;let t=new Map;for(let i of n){let[,,r,s]=i.type.split(":");if(s==="start"){t.set(`${r}:${i.renderId}`,i);continue}if(s==="end"){let o=t.get(`${r}:${i.renderId}`);if(o){let a=i.createdAt-o.createdAt;e[r]=(e[r]||0)+a}}}return e},WOt=n=>{let e=n.map(c=>[...new Set(c)]),t=e.map(()=>[]),i=e.map(()=>null);for(let c=0;c<e.length;c++)for(let l of e[c])if(/^\d+$/.test(l)){i[c]=Number.parseInt(l);break}let r=0,s=new Set;for(let c=0;c<i.length;c++){let l=i[c];if(l===null||l<1)continue;if(!s.has(l)){s.add(l),t[c].push(`pin${l}`),r=Math.max(r,l);continue}let u=0;for(let p of t[c])p.startsWith(`pin${l}_alt`)&&u++;t[c].push(`pin${l}_alt${u+1}`)}for(let c=0;c<t.length;c++)t[c][0]?.includes("_alt")&&(r++,t[c].unshift(`pin${r}`));for(let c=0;c<t.length;c++)t[c].length===0&&(r++,t[c].push(`pin${r}`));let o={};for(let c of e)for(let l of c)/^\d+$/.test(l)||(o[l]=(o[l]??0)+1);let a={};for(let c=0;c<e.length;c++){let l=e[c];for(let u of l)/^\d+$/.test(u)||(o[u]===1?t[c].push(u):(a[u]=(a[u]??0)+1,t[c].push(`${u}${a[u]}`)))}return t};function h9({db:n,schematicComponentId:e,deltaX:t,deltaY:i}){let r=n.schematic_rect.list({schematic_component_id:e});for(let c of r)c.center.x+=t,c.center.y+=i;let s=n.schematic_line.list({schematic_component_id:e});for(let c of s)c.x1+=t,c.y1+=i,c.x2+=t,c.y2+=i;let o=n.schematic_circle.list({schematic_component_id:e});for(let c of o)c.center.x+=t,c.center.y+=i;let a=n.schematic_arc.list({schematic_component_id:e});for(let c of a)c.center.x+=t,c.center.y+=i}var uet=(0,qet.default)("Group_doInitialSchematicLayoutMatchAdapt");function qOt(n){let{db:e}=n.root,t=Ng(e.toArray(),{source_group_id:n.source_group_id}),i=U4(t);uet.enabled&&global?.debugGraphics&&global.debugGraphics?.push(il(i,{title:`floatingBpcGraph-${n.name}`}));let r=U4(t),s={boxes:r.boxes,pins:r.pins.map(c=>({...c,color:c.color.replace("not_connected","normal")}))},{result:o}=XK([{variantName:"default",floatingGraph:r},{variantName:"noNotConnected",floatingGraph:s}],{singletonKeys:["vcc/2","gnd/2"],centerPinColors:["netlabel_center","component_center"],floatingBoxIdsWithMutablePinOffsets:new Set(r.boxes.filter(c=>r.pins.filter(p=>p.boxId===c.boxId).filter(p=>!p.color.includes("center")).length<=2).map(c=>c.boxId)),corpus:{}});uet.enabled&&global?.debugGraphics&&global.debugGraphics?.push(il(o,{title:`laidOutBpcGraph-${n.name}`}));let a=n._getGlobalSchematicPositionBeforeLayout();for(let c of o.boxes){if(!c.center)continue;let l=e.schematic_component.get(c.boxId);if(l){let p={x:c.center.x+a.x,y:c.center.y+a.y},f=e.schematic_port.list({schematic_component_id:l.schematic_component_id}),y=e.schematic_text.list({schematic_component_id:l.schematic_component_id}),g={x:p.x-l.center.x,y:p.y-l.center.y};for(let x of f)x.center.x+=g.x,x.center.y+=g.y;for(let x of y)x.position.x+=g.x,x.position.y+=g.y;h9({db:e,schematicComponentId:l.schematic_component_id,deltaX:g.x,deltaY:g.y}),l.center=p;continue}let u=e.schematic_net_label.get(c.boxId);if(u){let p=o.pins.find(y=>y.boxId===c.boxId&&y.color==="netlabel_center");if(!p)throw new Error(`No pin found for net label: ${c.boxId}`);let f={x:c.center.x+a.x,y:c.center.y+a.y};u.center=f,u.anchor_position={x:f.x+p.offset.x,y:f.y+p.offset.y};continue}console.error(`No schematic element found for box: ${c.boxId}. This is a bug in the matchAdapt binding with @tscircuit/core`)}}var xe=(0,Zet.default)("Group_doInitialSchematicLayoutMatchpack");function pet(n){switch(n){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:return"y+"}}function het(n,e){let t=["right","up","left","down"],i=t.indexOf(n);if(i===-1)return n;let r=Math.round(e/90),s=(i+r)%4;return t[s<0?s+4:s]}function ZOt(n,e,t){let i={chipMap:{},chipPinMap:{},netMap:{},pinStrongConnMap:{},netConnMap:{},chipGap:.6,decouplingCapsGap:.4,partitionGap:1.2};xe(`[${t.name}] Processing ${n.childNodes.length} child nodes for input problem`),n.childNodes.forEach((s,o)=>{if(xe(`[${t.name}] Processing child ${o}: nodeType=${s.nodeType}`),s.nodeType==="component"?xe(`[${t.name}] - Component: ${s.sourceComponent?.name}`):s.nodeType==="group"&&xe(`[${t.name}] - Group: ${s.sourceGroup?.name}`),s.nodeType==="component"&&s.sourceComponent){let a=s.sourceComponent.name||`chip_${o}`,c=e.schematic_component.getWhere({source_component_id:s.sourceComponent.source_component_id});if(!c)return;let l=t.children.find(P=>P.source_component_id===s.sourceComponent?.source_component_id),u=[0,90,180,270];l?._parsedProps?.schOrientation&&(u=[0]),l?._parsedProps?.schRotation!==void 0&&(u=[0]),l?._parsedProps?.facingDirection&&(u=[0]),l?._parsedProps?.schFacingDirection&&(u=[0]),l?.componentName==="Chip"&&(u=[0]);let p=l?._parsedProps?.schMarginLeft??l?._parsedProps?.schMarginX??0,f=l?._parsedProps?.schMarginRight??l?._parsedProps?.schMarginX??0,y=l?._parsedProps?.schMarginTop??l?._parsedProps?.schMarginY??0,g=l?._parsedProps?.schMarginBottom??l?._parsedProps?.schMarginY??0;l?.config.shouldRenderAsSchematicBox&&(y+=.4,g+=.4);let x=(f-p)/2,v=(y-g)/2;i.chipMap[a]={chipId:a,pins:[],size:{x:(c.size?.width||1)+p+f,y:(c.size?.height||1)+y+g},availableRotations:u};let S=e.schematic_port.list({schematic_component_id:c.schematic_component_id});for(let P of S){let T=e.source_port.get(P.source_port_id);if(!T)continue;let k=`${a}.${T.pin_number||T.name||P.schematic_port_id}`;i.chipMap[a].pins.push(k);let C=pet(P.facing_direction);i.chipPinMap[k]={pinId:k,offset:{x:(P.center?.x||0)-(c.center.x||0)+x,y:(P.center?.y||0)-(c.center.y||0)+v},side:C}}}else if(s.nodeType==="group"&&s.sourceGroup){let a=s.sourceGroup.name||`group_${o}`;xe(`[${t.name}] Processing nested group: ${a}`);let c=e.schematic_group?.getWhere?.({source_group_id:s.sourceGroup.source_group_id}),l=t.children.find(u=>u.source_group_id===s.sourceGroup?.source_group_id);if(xe(`[${t.name}] Found schematic_group for ${a}:`,c),c){xe(`[${t.name}] Treating group ${a} as composite chip`);let u=e.schematic_component.list({schematic_group_id:c.schematic_group_id});xe(`[${t.name}] Group ${a} has ${u.length} components:`,u.map(A=>A.source_component_id));let p=1/0,f=-1/0,y=1/0,g=-1/0,x=!1;for(let A of u)if(A.center&&A.size){x=!0;let R=A.size.width/2,j=A.size.height/2;p=Math.min(p,A.center.x-R),f=Math.max(f,A.center.x+R),y=Math.min(y,A.center.y-j),g=Math.max(g,A.center.y+j)}let v=l?._parsedProps?.schMarginLeft??l?._parsedProps?.schMarginX??0,S=l?._parsedProps?.schMarginRight??l?._parsedProps?.schMarginX??0,P=l?._parsedProps?.schMarginTop??l?._parsedProps?.schMarginY??0,T=l?._parsedProps?.schMarginBottom??l?._parsedProps?.schMarginY??0,k=(S-v)/2,C=(P-T)/2,E=(x?f-p:2)+v+S,N=(x?g-y:2)+P+T;xe(`[${t.name}] Group ${a} computed size: ${E} x ${N}`);let I=[];for(let A of u){let R=e.schematic_port.list({schematic_component_id:A.schematic_component_id});for(let j of R){let B=e.source_port.get(j.source_port_id);if(!B)continue;let G=`${a}.${B.pin_number||B.name||j.schematic_port_id}`;I.push(G);let U=c.center||{x:0,y:0},H=pet(j.facing_direction);i.chipPinMap[G]={pinId:G,offset:{x:(j.center?.x||0)-U.x+k,y:(j.center?.y||0)-U.y+C},side:H}}}xe(`[${t.name}] Group ${a} has ${I.length} pins:`,I),i.chipMap[a]={chipId:a,pins:I,size:{x:E,y:N}},xe(`[${t.name}] Added group ${a} to chipMap`)}else xe(`[${t.name}] Warning: No schematic_group found for group ${a}`)}}),xe(`[${t.name}] Creating connections using connectivity keys`);let r=new Map;for(let[s,o]of Object.entries(i.chipMap))for(let a of o.pins){let c=a.split(".").pop(),l=n.childNodes.find(u=>u.nodeType==="component"&&u.sourceComponent?u.sourceComponent.name===s:u.nodeType==="group"&&u.sourceGroup?`group_${n.childNodes.indexOf(u)}`===s:!1);if(l?.nodeType==="group"&&l.sourceGroup){let u=e.schematic_group?.getWhere?.({source_group_id:l.sourceGroup.source_group_id});if(u){let p=e.schematic_component.list({schematic_group_id:u.schematic_group_id});for(let f of p){let y=e.source_port.list({source_component_id:f.source_component_id});for(let g of y){let x=g.pin_number||g.name;if(String(x)===String(c))if(g.subcircuit_connectivity_map_key){let v=g.subcircuit_connectivity_map_key;r.has(v)||r.set(v,[]),r.get(v).push(a),xe(`[${t.name}] \u2713 Pin ${a} has connectivity key: ${v}`)}else xe(`[${t.name}] Pin ${a} has no connectivity key`)}}}}else if(l?.nodeType==="component"&&l.sourceComponent){let u=e.source_port.list({source_component_id:l.sourceComponent.source_component_id});for(let p of u){let f=p.pin_number||p.name;if(String(f)===String(c)&&p.subcircuit_connectivity_map_key){let y=p.subcircuit_connectivity_map_key;r.has(y)||r.set(y,[]),r.get(y).push(a),xe(`[${t.name}] Pin ${a} has connectivity key: ${y}`)}}}}xe(`[${t.name}] Found ${r.size} connectivity groups:`,Array.from(r.entries()).map(([s,o])=>({key:s,pins:o})));for(let[s,o]of r)if(o.length>=2){let a=e.source_trace.list().filter(u=>u.subcircuit_connectivity_map_key===s),c=a.some(u=>u.connected_source_net_ids&&u.connected_source_net_ids.length>0),l=a.some(u=>u.connected_source_port_ids&&u.connected_source_port_ids.length>=2);if(xe(`[${t.name}] Connectivity ${s}: hasNetConnections=${c}, hasDirectConnections=${l}`),l){for(let u of a)if(u.connected_source_port_ids&&u.connected_source_port_ids.length>=2){let p=[];for(let f of u.connected_source_port_ids)for(let y of o){let g=y.split(".").pop(),x=e.source_port.get(f);if(x&&String(x.pin_number||x.name)===String(g)){let v=y.split(".")[0],S=n.childNodes.find(P=>P.nodeType==="component"&&P.sourceComponent?P.sourceComponent.name===v:P.nodeType==="group"&&P.sourceGroup?`group_${n.childNodes.indexOf(P)}`===v:!1);S?.nodeType==="component"&&S.sourceComponent&&e.source_port.list({source_component_id:S.sourceComponent.source_component_id}).some(T=>T.source_port_id===f)&&p.push(y)}}for(let f=0;f<p.length;f++)for(let y=f+1;y<p.length;y++){let g=p[f],x=p[y];i.pinStrongConnMap[`${g}-${x}`]=!0,i.pinStrongConnMap[`${x}-${g}`]=!0,xe(`[${t.name}] Created strong connection: ${g} <-> ${x}`)}}}if(c){let u=e.source_net.getWhere({subcircuit_connectivity_map_key:s}),p=u?.is_ground??!1,f=u?.is_power??!1;i.netMap[s]={netId:s,isGround:p,isPositiveVoltageSource:f};for(let y of o)i.netConnMap[`${y}-${s}`]=!0;xe(`[${t.name}] Created net ${s} with ${o.length} pins:`,o)}}return i}function KOt(n){let{db:e}=n.root,t=s_(e.toArray(),{source_group_id:n.source_group_id});if(xe(`[${n.name}] Starting matchpack layout with ${t.childNodes.length} children`),xe(`[${n.name}] Tree structure:`,JSON.stringify(t,null,2)),t.childNodes.length<=1){xe(`[${n.name}] Only ${t.childNodes.length} children, skipping layout`);return}xe("Converting circuit tree to InputProblem...");let i=ZOt(t,e,n);xe.enabled&&n.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`matchpack-input-problem-${n.name}`,content:JSON.stringify(i,null,2)});let r=new HJ(i);if(xe("Starting LayoutPipelineSolver..."),xe.enabled&&global?.debugGraphics){let c=r.visualize();global.debugGraphics.push({...c,title:`matchpack-initial-${n.name}`})}if(r.solve(),xe(`Solver completed in ${r.iterations} iterations`),xe(`Solved: ${r.solved}, Failed: ${r.failed}`),r.failed)throw xe(`Solver failed with error: ${r.error}`),new Error(`Matchpack layout solver failed: ${r.error}`);let s=r.getOutputLayout();if(xe("OutputLayout:",JSON.stringify(s,null,2)),xe("Solver completed successfully:",!r.failed),xe.enabled&&global?.debugGraphics){let c=r.visualize();global.debugGraphics.push({...c,title:`matchpack-final-${n.name}`})}let o=r.checkForOverlaps(s);if(o.length>0){xe(`Warning: Found ${o.length} overlapping components:`);for(let c of o)xe(` ${c.chip1} overlaps ${c.chip2} (area: ${c.overlapArea})`)}let a=n._getGlobalSchematicPositionBeforeLayout();xe(`Group offset: x=${a.x}, y=${a.y}`),xe(`Applying layout results for ${Object.keys(s.chipPlacements).length} chip placements`);for(let[c,l]of Object.entries(s.chipPlacements)){xe(`Processing placement for chip: ${c} at (${l.x}, ${l.y})`);let u=t.childNodes.find(f=>{if(f.nodeType==="component"&&f.sourceComponent){let y=f.sourceComponent.name===c;return xe(` Checking component ${f.sourceComponent.name}: matches=${y}`),y}if(f.nodeType==="group"&&f.sourceGroup){let y=f.sourceGroup.name,g=`group_${t.childNodes.indexOf(f)}`,x=g===c;return xe(` Checking group ${y} (expected chipId: ${g}): matches=${x}`),x}return!1});if(!u){xe(`Warning: No tree node found for chip: ${c}`),xe("Available tree nodes:",t.childNodes.map((f,y)=>({type:f.nodeType,name:f.nodeType==="component"?f.sourceComponent?.name:f.sourceGroup?.name,expectedChipId:f.nodeType==="group"?`group_${y}`:f.sourceComponent?.name})));continue}let p={x:l.x+a.x,y:l.y+a.y};if(u.nodeType==="component"&&u.sourceComponent){let f=e.schematic_component.getWhere({source_component_id:u.sourceComponent.source_component_id});if(f){xe(`Moving component ${c} to (${p.x}, ${p.y})`);let y=e.schematic_port.list({schematic_component_id:f.schematic_component_id}),g=e.schematic_text.list({schematic_component_id:f.schematic_component_id}),x={x:p.x-f.center.x,y:p.y-f.center.y};for(let v of y)v.center.x+=x.x,v.center.y+=x.y;for(let v of g)v.position.x+=x.x,v.position.y+=x.y;if(h9({db:e,schematicComponentId:f.schematic_component_id,deltaX:x.x,deltaY:x.y}),f.center=p,l.ccwRotationDegrees!==0){xe(`Component ${c} has rotation: ${l.ccwRotationDegrees}\xB0`);let v=l.ccwRotationDegrees*Math.PI/180,S=Math.cos(v),P=Math.sin(v);for(let T of y){let k=T.center.x-p.x,C=T.center.y-p.y,E=k*S-C*P,N=k*P+C*S;T.center.x=p.x+E,T.center.y=p.y+N;let I=T.facing_direction||"right";T.facing_direction=het(I,l.ccwRotationDegrees),T.side_of_component=(T.facing_direction==="up"?"top":T.facing_direction==="down"?"bottom":T.facing_direction)||T.side_of_component}for(let T of g){let k=T.position.x-p.x,C=T.position.y-p.y,E=k*S-C*P,N=k*P+C*S;T.position.x=p.x+E,T.position.y=p.y+N}if(f.symbol_name){let T=f.symbol_name.match(/_(right|left|up|down)$/);T&&(f.symbol_name=f.symbol_name.replace(T[0],`_${het(T[1],l.ccwRotationDegrees)}`))}}}}else if(u.nodeType==="group"&&u.sourceGroup){let f=e.schematic_group?.getWhere?.({source_group_id:u.sourceGroup.source_group_id});if(f){xe(`Moving group ${c} to (${p.x}, ${p.y}) from (${f.center?.x}, ${f.center?.y})`);let y=e.schematic_component.list({schematic_group_id:f.schematic_group_id});xe(`Group ${c} has ${y.length} components to move`);let g=f.center||{x:0,y:0},x={x:p.x-g.x,y:p.y-g.y};xe(`Position delta for group ${c}: (${x.x}, ${x.y})`);for(let v of y)if(v.center){let S={...v.center};v.center.x+=x.x,v.center.y+=x.y,xe(`Moved component ${v.source_component_id} from (${S.x}, ${S.y}) to (${v.center.x}, ${v.center.y})`);let P=e.schematic_port.list({schematic_component_id:v.schematic_component_id}),T=e.schematic_text.list({schematic_component_id:v.schematic_component_id});for(let k of P)k.center&&(k.center.x+=x.x,k.center.y+=x.y);for(let k of T)k.position&&(k.position.x+=x.x,k.position.y+=x.y)}f.center=p,xe(`Updated group ${c} center to (${p.x}, ${p.y})`)}}}xe("Matchpack layout completed successfully")}function JOt(n){if(!n.isSubcircuit)return;let{db:e}=n.root,t=n.selectAll("trace"),i=n.selectAll("via"),r=n.selectAll("net"),s=new Zm({});s.addConnections(t.map(u=>{let p=e.source_trace.get(u.source_trace_id);return p?[p.source_trace_id,...p.connected_source_port_ids,...p.connected_source_net_ids]:null}).filter(u=>u!==null));let o=e.source_net.list().filter(u=>u.subcircuit_id===n.subcircuit_id);for(let u of o)s.addConnections([[u.source_net_id]]);let{name:a}=n._parsedProps;for(let u of t){if(!u.source_trace_id)continue;let p=s.getNetConnectedToId(u.source_trace_id);p&&(u.subcircuit_connectivity_map_key=`${a??`unnamedsubcircuit${n._renderId}`}_${p}`,e.source_trace.update(u.source_trace_id,{subcircuit_connectivity_map_key:u.subcircuit_connectivity_map_key}))}let c=new Set;for(let u of t){if(!u.source_trace_id)continue;let p=e.source_trace.get(u.source_trace_id);if(p)for(let f of p.connected_source_port_ids)c.add(f)}for(let u of c){let p=s.getNetConnectedToId(u);if(!p)continue;let f=`${a??`unnamedsubcircuit${n._renderId}`}_${p}`;e.source_port.update(u,{subcircuit_connectivity_map_key:f})}let l=new Set;for(let u of t){if(!u.source_trace_id)continue;let p=e.source_trace.get(u.source_trace_id);if(p)for(let f of p.connected_source_net_ids)l.add(f)}for(let u of o)l.add(u.source_net_id);for(let u of l){let p=s.getNetConnectedToId(u);if(!p)continue;let f=`${a??`unnamedsubcircuit${n._renderId}`}_${p}`;e.source_net.update(u,{subcircuit_connectivity_map_key:f});let y=r.find(g=>g.source_net_id===u);y&&(y.subcircuit_connectivity_map_key=f)}for(let u of i){let p=u._getConnectedNetOrTrace();p&&p.subcircuit_connectivity_map_key&&(u.subcircuit_connectivity_map_key=p.subcircuit_connectivity_map_key)}}function QOt(n){let{db:e}=n.root,t=n._parsedProps,i=n.children.filter(C=>{let E=C._parsedProps?.schX!==void 0||C._parsedProps?.schY!==void 0;return C.schematic_component_id&&!E});if(i.length===0)return;let r=0,s=0;for(let C of i){let E=e.schematic_component.get(C.schematic_component_id);E?.size&&(r=Math.max(r,E.size.width),s=Math.max(s,E.size.height))}r===0&&i.length>0&&(r=1),s===0&&i.length>0&&(s=1);let o=t.gridCols,a,c=t.gridGap,l=t.gridRowGap,u=t.gridColumnGap;t.schLayout?.grid&&(o=t.schLayout.grid.cols??o,a=t.schLayout.grid.rows,c=t.schLayout.gridGap??c,l=t.schLayout.gridRowGap??l,u=t.schLayout.gridColumnGap??u);let p,f;o!==void 0&&a!==void 0?(p=o,f=a):o!==void 0?(p=o,f=Math.ceil(i.length/p)):a!==void 0?(f=a,p=Math.ceil(i.length/f)):(p=Math.ceil(Math.sqrt(i.length)),f=Math.ceil(i.length/p)),p===0&&i.length>0&&(p=1),f===0&&i.length>0&&(f=i.length);let y,g,x=C=>{if(C!==void 0)return typeof C=="number"?C:$.parse(C)};if(l!==void 0||u!==void 0){let C=typeof c=="object"&&c!==null?c.x:c,E=typeof c=="object"&&c!==null?c.y:c;y=x(u??C)??1,g=x(l??E)??1}else if(typeof c=="number")y=c,g=c;else if(typeof c=="string"){let C=$.parse(c);y=C,g=C}else if(typeof c=="object"&&c!==null){let C=c.x,E=c.y;y=typeof C=="number"?C:$.parse(C??"0mm"),g=typeof E=="number"?E:$.parse(E??"0mm")}else y=1,g=1;let v=p*r+Math.max(0,p-1)*y,S=f*s+Math.max(0,f-1)*g,P=n._getGlobalSchematicPositionBeforeLayout(),T=P.x-v/2+r/2,k=P.y+S/2-s/2;for(let C=0;C<i.length;C++){let E=i[C];if(!E.schematic_component_id)continue;let N=Math.floor(C/p),I=C%p;if(N>=f||I>=p){console.warn(`Schematic grid layout: Child ${E.getString()} at index ${C} (row ${N}, col ${I}) exceeds specified grid dimensions (${f}x${p}). Skipping placement.`);continue}let A=T+I*(r+y),R=k-N*(s+g),j=e.schematic_component.get(E.schematic_component_id);if(j){let B=j.center,G={x:A,y:R};e.schematic_component.update(E.schematic_component_id,{center:G});let U=G.x-B.x,H=G.y-B.y,Q=e.schematic_port.list({schematic_component_id:E.schematic_component_id});for(let V of Q)e.schematic_port.update(V.schematic_port_id,{center:{x:V.center.x+U,y:V.center.y+H}});let tt=e.schematic_text.list({schematic_component_id:E.schematic_component_id});for(let V of tt)e.schematic_text.update(V.schematic_text_id,{position:{x:V.position.x+U,y:V.position.y+H}});h9({db:e,schematicComponentId:E.schematic_component_id,deltaX:U,deltaY:H})}}n.schematic_group_id&&e.schematic_group.update(n.schematic_group_id,{width:v,height:S,center:P})}var det=(n,e)=>{let{sourceComponent:t,sourceGroup:i}=e;if(e.nodeType==="component"){let r=n.schematic_component.getWhere({source_component_id:t?.source_component_id});return r?.size?{width:r.size.width,height:r.size.height}:null}if(e.nodeType==="group"){let r=n.schematic_group.getWhere({source_group_id:i?.source_group_id});if(r?.width&&r?.height)return{width:r.width,height:r.height};let s=n.schematic_component.list({schematic_group_id:r?.schematic_group_id}),o=1/0,a=-1/0,c=1/0,l=-1/0;for(let f of s)if(f.center&&f.size){let y=f.size.width/2,g=f.size.height/2;o=Math.min(o,f.center.x-y),a=Math.max(a,f.center.x+y),c=Math.min(c,f.center.y-g),l=Math.max(l,f.center.y+g)}let u=a-o,p=l-c;return{width:u,height:p}}return null},tLt=n=>{let{db:e}=n.root,t=n._parsedProps,i=s_(e.toArray(),{source_group_id:n.source_group_id}),r=t.schJustifyContent??t.justifyContent,s=t.schAlignItems??t.alignItems,o=t.schFlexGap??t.schGap??t.gap,a=t.schFlexDirection??"row",c={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"space-between","space-between":"space-between","space-around":"space-around","space-evenly":"space-evenly",center:"center"}[r??"space-between"],l={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[s??"center"];if(!c)throw new Error(`Invalid justifyContent value: "${r}"`);if(!l)throw new Error(`Invalid alignItems value: "${s}"`);let u=0,p=0;typeof o=="object"?(u=o.y??0,p=o.x??0):typeof o=="number"?(u=o,p=o):typeof o=="string"&&(u=$.parse(o),p=$.parse(o));let f,y=t.width??t.schWidth??void 0,g=t.height??t.schHeight??void 0;(y===void 0||g===void 0)&&(f=Pw(i.childNodes.map(k=>det(e,k)).filter(k=>k!==null),{alignItems:l,justifyContent:c,direction:a,rowGap:u,columnGap:p}),y=f.width,g=f.height);let v=new ES(y,g,{alignItems:l,justifyContent:c,direction:a,rowGap:u,columnGap:p});for(let k of i.childNodes){let C=det(e,k);v.addChild({metadata:k,width:C?.width??0,height:C?.height??0,flexBasis:C?a==="row"?C.width:C.height:void 0})}v.build();let S={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let k of v.children)S.minX=Math.min(S.minX,k.position.x),S.minY=Math.min(S.minY,k.position.y),S.maxX=Math.max(S.maxX,k.position.x+k.size.width),S.maxY=Math.max(S.maxY,k.position.y+k.size.height);S.width=S.maxX-S.minX,S.height=S.maxY-S.minY;let P={x:-(S.maxX+S.minX)/2,y:-(S.maxY+S.minY)/2},T=e.toArray();for(let k of v.children){let{sourceComponent:C,sourceGroup:E}=k.metadata;if(C){let N=e.schematic_component.getWhere({source_component_id:C.source_component_id});if(!N)continue;tq(T,N.schematic_component_id,{x:k.position.x+k.size.width/2+P.x,y:k.position.y+k.size.height/2+P.y})}if(E){if(!e.schematic_group.getWhere({source_group_id:E.source_group_id}))continue;nq(T,E.source_group_id,{x:k.position.x+k.size.width/2+P.x,y:k.position.y+k.size.height/2+P.y})}}n.schematic_group_id&&e.schematic_group.update(n.schematic_group_id,{width:S.width,height:S.height})},GA=1;function eLt(n){let{db:e}=n.root,t=n._parsedProps,i=nLt(n);if(i.length===0)return;let r=iLt({db:e,pcbChildren:i}),s=rLt(t),o=sLt({props:t,pcbChildren:i,childDimensions:r,gridConfig:s}),a=cLt({pcbChildren:i,childDimensions:r,gridLayout:o,gridConfig:s}),{itemCoordinates:c}=a.layout();lLt({db:e,group:n,pcbChildren:i,itemCoordinates:c,gridLayout:o}),uLt({db:e,group:n,props:t,gridLayout:o})}function nLt(n){return n.children.filter(e=>e.pcb_component_id||e.pcb_group_id)}function iLt(n){let{db:e,pcbChildren:t}=n,i=0,r=0;for(let s of t){let o=0,a=0;if(s.pcb_group_id){let c=e.pcb_group.get(s.pcb_group_id);o=c?.width??0,a=c?.height??0}else if(s.pcb_component_id){let c=e.pcb_component.get(s.pcb_component_id);o=c?.width??0,a=c?.height??0}i=Math.max(i,o),r=Math.max(r,a)}return{width:i,height:r}}function rLt(n){let e=n.pcbGridCols??n.gridCols??n.pcbLayout?.grid?.cols,t=n.pcbGridRows??n.pcbLayout?.grid?.rows,i=n.pcbGridTemplateColumns,r=n.pcbGridTemplateRows,s=p=>p===void 0?GA:typeof p=="number"?p:$.parse(p),o=n.pcbGridGap??n.gridGap??n.pcbLayout?.gridGap,a=n.pcbGridRowGap??n.gridRowGap??n.pcbLayout?.gridRowGap,c=n.pcbGridColumnGap??n.gridColumnGap??n.pcbLayout?.gridColumnGap,l=GA,u=GA;if(a!==void 0||c!==void 0){let p=typeof o=="object"?o?.x:o,f=typeof o=="object"?o?.y:o;l=s(c??p),u=s(a??f)}else if(typeof o=="object"&&o!==null)l=s(o.x),u=s(o.y);else{let p=s(o);l=p,u=p}return{cols:e,rows:t,gapX:l,gapY:u,templateColumns:i,templateRows:r}}function sLt(n){let{props:e,pcbChildren:t,childDimensions:i,gridConfig:r}=n;return e.pcbGridTemplateColumns||e.pcbGridTemplateRows?oLt({props:e,gridConfig:r,pcbChildren:t,childDimensions:i}):aLt({gridConfig:r,pcbChildren:t,childDimensions:i})}function oLt(n){let{props:e,gridConfig:t,pcbChildren:i,childDimensions:r}=n,s=e.pcbGridTemplateColumns??"",o=e.pcbGridTemplateRows??"",a=f=>{let y=f.match(/repeat\((\d+),/);return y?parseInt(y[1]):Math.ceil(Math.sqrt(i.length))},c=e.pcbGridTemplateColumns?a(s):Math.ceil(Math.sqrt(i.length)),l=e.pcbGridTemplateRows?a(o):Math.ceil(i.length/c),u=c*r.width+Math.max(0,c-1)*t.gapX,p=l*r.height+Math.max(0,l-1)*t.gapY;return{gridTemplateColumns:s,gridTemplateRows:o,containerWidth:u,containerHeight:p}}function aLt(n){let{gridConfig:e,pcbChildren:t,childDimensions:i}=n,r,s;e.cols!==void 0&&e.rows!==void 0?(r=e.cols,s=e.rows):e.cols!==void 0?(r=e.cols,s=Math.ceil(t.length/r)):e.rows!==void 0?(s=e.rows,r=Math.ceil(t.length/s)):(r=Math.ceil(Math.sqrt(t.length)),s=Math.ceil(t.length/r)),r=Math.max(1,r),s=Math.max(1,s);let o=r*i.width+Math.max(0,r-1)*e.gapX,a=s*i.height+Math.max(0,s-1)*e.gapY,c=`repeat(${r}, ${i.width}px)`,l=`repeat(${s}, ${i.height}px)`;return{gridTemplateColumns:c,gridTemplateRows:l,containerWidth:o,containerHeight:a}}function cLt(n){let{pcbChildren:e,childDimensions:t,gridLayout:i,gridConfig:r}=n,s=e.map((o,a)=>({key:o.getString()||`child-${a}`,contentWidth:t.width,contentHeight:t.height}));return new nQ({containerWidth:i.containerWidth,containerHeight:i.containerHeight,gridTemplateColumns:i.gridTemplateColumns,gridTemplateRows:i.gridTemplateRows,gap:[r.gapY,r.gapX],children:s})}function lLt(n){let{db:e,group:t,pcbChildren:i,itemCoordinates:r,gridLayout:s}=n,o=t._getGlobalPcbPositionBeforeLayout(),a=e.toArray();for(let c=0;c<i.length;c++){let l=i[c],u=l.getString()||`child-${c}`,p=r[u];if(!p){console.warn(`PCB grid layout: No coordinates found for child ${u}`);continue}let f=o.x-s.containerWidth/2+p.x+p.width/2,y=o.y+s.containerHeight/2-p.y-p.height/2;if(l.pcb_component_id)ww(a,l.pcb_component_id,{x:f,y});else{let g=l;g.pcb_group_id&&g.source_group_id&&Sw(a,g.source_group_id,{x:f,y})}}}function uLt(n){let{db:e,group:t,props:i,gridLayout:r}=n;if(t.pcb_group_id){let s=t._getGlobalPcbPositionBeforeLayout();e.pcb_group.update(t.pcb_group_id,{width:i.width??r.containerWidth,height:i.height??r.containerHeight,center:s})}}function pLt(n){let e={serverUrl:"https://registry-api.tscircuit.com",serverMode:"job",serverCacheEnabled:!0};if(typeof n=="object"&&!n.preset)return{local:!(n.serverUrl||n.serverMode||n.serverCacheEnabled),...e,...n};let t=typeof n=="object"?n.preset:n,i=typeof n=="object"?n:{};switch(typeof t=="string"?t.replace(/_/g,"-"):t){case"auto-local":return{local:!0,groupMode:"subcircuit"};case"sequential-trace":return{local:!0,groupMode:"sequential-trace"};case"subcircuit":return{local:!0,groupMode:"subcircuit"};case"auto-cloud":{let{preset:s,local:o,groupMode:a,...c}=i;return{local:!1,groupMode:"subcircuit",...e,...c}}case"laser-prefab":{let{preset:s,local:o,groupMode:a,...c}=i;return{local:!0,groupMode:"subcircuit",preset:"laser_prefab",...c}}default:return{local:!0,groupMode:"subcircuit"}}}var hLt=(n,e)=>{let t=n.children.filter(p=>p.componentName==="Constraint"&&p._parsedProps.pcb),i=new Map,r={},s=p=>(r[p]!==p&&(r[p]=s(r[p])),r[p]),o=(p,f)=>{let y=s(p),g=s(f);y!==g&&(r[g]=y)},a=p=>{p in r||(r[p]=p)},c=p=>{let f=p.startsWith(".")?p.slice(1):p;return n.children.find(g=>g.name===f)?.pcb_component_id??void 0};for(let p of t){let f=p._parsedProps;if("left"in f&&"right"in f){let y=c(f.left),g=c(f.right);y&&g&&(a(y),a(g),o(y,g))}else if("top"in f&&"bottom"in f){let y=c(f.top),g=c(f.bottom);y&&g&&(a(y),a(g),o(y,g))}else if("for"in f&&Array.isArray(f.for)){let y=f.for.map(g=>c(g)).filter(g=>!!g);for(let g of y)a(g);for(let g=1;g<y.length;g++)o(y[0],y[g])}}for(let p of Object.keys(r)){let f=s(p);i.has(f)||i.set(f,{componentIds:[],constraints:[]}),i.get(f).componentIds.push(p)}for(let p of t){let f=p._parsedProps,y;if("left"in f?y=c(f.left):"top"in f?y=c(f.top):"for"in f&&(y=c(f.for[0])),!y)continue;let g=s(y);i.get(g)?.constraints.push(p)}let l={},u=Object.fromEntries(e.components.map(p=>[p.componentId,p]));for(let[p,f]of i.entries()){if(f.componentIds.length<=1)continue;let y=new e_,g={},x=(A,R)=>{let j=`${A}_${R}`;return g[j]||(g[j]=new Ca(j)),g[j]},v=f.componentIds[0];y.addConstraint(new Pi(x(v,"x"),si.Eq,0,Rn.required)),y.addConstraint(new Pi(x(v,"y"),si.Eq,0,Rn.required));for(let A of f.constraints){let R=A._parsedProps;if("xDist"in R){let j=c(R.left),B=c(R.right);j&&B&&y.addConstraint(new Pi(new Dn(x(B,"x"),[-1,x(j,"x")]),si.Eq,R.xDist,Rn.required))}else if("yDist"in R){let j=c(R.top),B=c(R.bottom);j&&B&&y.addConstraint(new Pi(new Dn(x(j,"y"),[-1,x(B,"y")]),si.Eq,R.yDist,Rn.required))}else if("sameX"in R&&Array.isArray(R.for)){let j=R.for.map(B=>c(B)).filter(B=>!!B);if(j.length>1){let B=x(j[0],"x");for(let G=1;G<j.length;G++)y.addConstraint(new Pi(new Dn(x(j[G],"x"),[-1,B]),si.Eq,0,Rn.required))}}else if("sameY"in R&&Array.isArray(R.for)){let j=R.for.map(B=>c(B)).filter(B=>!!B);if(j.length>1){let B=x(j[0],"y");for(let G=1;G<j.length;G++)y.addConstraint(new Pi(new Dn(x(j[G],"y"),[-1,B]),si.Eq,0,Rn.required))}}}y.updateVariables();let S={};for(let A of f.componentIds)S[A]={x:x(A,"x").value(),y:x(A,"y").value()};let P=1/0,T=1/0,k=-1/0,C=-1/0;for(let A of f.componentIds){let R=u[A],j=S[A];if(R)for(let B of R.pads){let G=j.x+B.offset.x,U=j.y+B.offset.y;P=Math.min(P,G-B.size.x/2),k=Math.max(k,G+B.size.x/2),T=Math.min(T,U-B.size.y/2),C=Math.max(C,U+B.size.y/2)}}let E={x:(P+k)/2,y:(T+C)/2},N=[],I={};for(let A of f.componentIds){let R=u[A],j=S[A];if(R){I[A]={x:j.x-E.x,y:j.y-E.y};for(let B of R.pads)N.push({padId:B.padId,networkId:B.networkId,type:B.type,size:B.size,offset:{x:j.x+B.offset.x-E.x,y:j.y+B.offset.y-E.y}})}}e.components=e.components.filter(A=>!f.componentIds.includes(A.componentId)),e.components.push({componentId:f.componentIds[0],pads:N,availableRotationDegrees:[0]}),f.relativeCenters=I,l[f.componentIds[0]]=f}return l},fet=({db:n,pcbComponentId:e,rotationDegrees:t,layer:i})=>{if(t==null||!n?.cad_component?.list)return;let r=n.cad_component.getWhere({pcb_component_id:e});if(!r)return;let s=i?.toLowerCase?.()==="bottom"?-t:t,o=r.rotation?.z??0,a={...r.rotation??{x:0,y:0,z:0},z:sd(o+s)};n.cad_component.update(r.cad_component_id,{rotation:a}),r.rotation=a},F1=(n,e,t)=>{if(e===t)return!0;let i=n.source_group.get(e);return!i||!i.parent_source_group_id?!1:F1(n,i.parent_source_group_id,t)},dLt=(n,e,t)=>{let{db:i}=n.root;for(let r of e.components){let{center:s,componentId:o,ccwRotationOffset:a,ccwRotationDegrees:c}=r,l=t[o];if(l){let v=c??a??0,S=v*Math.PI/180;for(let P of l.componentIds){let T=l.relativeCenters[P];if(!T)continue;let k={x:T.x*Math.cos(S)-T.y*Math.sin(S),y:T.x*Math.sin(S)+T.y*Math.cos(S)},C=i.pcb_component.get(P);if(!C)continue;let E=C.center,N=mi(n._computePcbGlobalTransformBeforeLayout(),Nn(s.x+k.x,s.y+k.y),Dc(S),Nn(-E.x,-E.y)),I=i.toArray().filter(A=>"pcb_component_id"in A&&A.pcb_component_id===P);i_(I,N),fet({db:i,pcbComponentId:P,rotationDegrees:v,layer:C.layer})}continue}let u=i.pcb_component.get(o);if(u){let v=n.source_group_id,P=i.source_component.get(u.source_component_id)?.source_group_id;if(P!==void 0&&!F1(i,P,v))continue;let T=u.center,k=c??a??0,C=mi(n._computePcbGlobalTransformBeforeLayout(),Nn(s.x,s.y),Dc(k*Math.PI/180),Nn(-T.x,-T.y)),E=i.toArray().filter(N=>"pcb_component_id"in N&&N.pcb_component_id===o);i_(E,C),fet({db:i,pcbComponentId:o,rotationDegrees:k,layer:u.layer});continue}let p=i.pcb_group.list().find(v=>v.source_group_id===o);if(!p)continue;let f=p.center,y=c??a??0,g=mi(n._computePcbGlobalTransformBeforeLayout(),Nn(s.x,s.y),Dc(y*Math.PI/180),Nn(-f.x,-f.y)),x=i.toArray().filter(v=>{if("source_group_id"in v&&v.source_group_id&&(v.source_group_id===o||F1(i,v.source_group_id,o)))return!0;if("source_component_id"in v&&v.source_component_id){let S=i.source_component.get(v.source_component_id);if(S?.source_group_id&&(S.source_group_id===o||F1(i,S.source_group_id,o)))return!0}if("pcb_component_id"in v&&v.pcb_component_id){let S=i.pcb_component.get(v.pcb_component_id);if(S?.source_component_id){let P=i.source_component.get(S.source_component_id);if(P?.source_group_id&&(P.source_group_id===o||F1(i,P.source_group_id,o)))return!0}}return!1});i_(x,g),i.pcb_group.update(p.pcb_group_id,{center:s})}};function fLt(n){switch(n.shape){case"rect":case"rotated_rect":case"pill":case"rotated_pill":return{width:n.width,height:n.height};case"circle":return{width:n.radius*2,height:n.radius*2};case"polygon":if(!n.points||n.points.length===0)return null;let e=n.points.map(a=>a.x),t=n.points.map(a=>a.y),i=Math.min(...e),r=Math.max(...e),s=Math.min(...t),o=Math.max(...t);return{width:r-i,height:o-s};default:return null}}function mLt(n){switch(n.shape){case"circular_hole_with_rect_pad":case"pill_hole_with_rect_pad":case"rotated_pill_hole_with_rect_pad":return{width:n.rect_pad_width,height:n.rect_pad_height};case"circle":return{width:n.outer_diameter,height:n.outer_diameter};case"oval":return{width:n.outer_width,height:n.outer_height};case"pill":return{width:n.outer_width,height:n.outer_height};default:return null}}var _Lt="1mm",met=(0,Ket.default)("Group_doInitialPcbLayoutPack"),yLt=n=>{let{db:e}=n.root,{_parsedProps:t}=n,{packOrderStrategy:i,packPlacementStrategy:r,gap:s,pcbGap:o,pcbPackGap:a}=t,c=a??o??s,l=$.parse(c??_Lt),u={},p=new Set,f=k=>{if(k?.pcb_component_id&&k?._parsedProps){let C=k._parsedProps,E=$.parse(C.pcbMarginLeft??C.pcbMarginX??0),N=$.parse(C.pcbMarginRight??C.pcbMarginX??0),I=$.parse(C.pcbMarginTop??C.pcbMarginY??0),A=$.parse(C.pcbMarginBottom??C.pcbMarginY??0);(E||N||I||A)&&(u[k.pcb_component_id]={left:E,right:N,top:I,bottom:A})}k?.children&&k.children.forEach(f)};f(n);let y=new Set;for(let k of n.children){let C=k;C._isNormalComponent&&C.isRelativelyPositioned?.()&&(C.pcb_component_id&&p.add(C.pcb_component_id),C.pcb_group_id&&y.add(C.pcb_group_id))}let g=e.toArray().filter(k=>k.type==="pcb_component"?!p.has(k.pcb_component_id):k.type==="pcb_group"?!y.has(k.pcb_group_id):!0),x=[];for(let k of p){let C=e.toArray().find(R=>R.type==="pcb_component"&&R.pcb_component_id===k);if(!C)continue;let E=C.center.x,N=C.center.y,I=e.toArray().filter(R=>R.type==="pcb_smtpad"&&R.pcb_component_id===k);for(let R of I){let j=fLt(R);if(!j||j.width===0||j.height===0)continue;let B,G;if(R.shape==="polygon"){let U=R.points.map(Q=>Q.x),H=R.points.map(Q=>Q.y);B=E+(Math.min(...U)+Math.max(...U))/2,G=N+(Math.min(...H)+Math.max(...H))/2}else B=E+R.x,G=N+R.y;x.push({obstacleId:R.pcb_smtpad_id,absoluteCenter:{x:B,y:G},width:j.width,height:j.height})}let A=e.toArray().filter(R=>R.type==="pcb_plated_hole"&&R.pcb_component_id===k);for(let R of A){let j=mLt(R);if(!j||j.width===0||j.height===0)continue;let B=E+R.x,G=N+R.y;x.push({obstacleId:R.pcb_plated_hole_id,absoluteCenter:{x:B,y:G},width:j.width,height:j.height})}}let v;if(t.width!==void 0&&t.height!==void 0){let k=$.parse(t.width),C=$.parse(t.height);v={minX:-k/2,maxX:k/2,minY:-C/2,maxY:C/2}}let S={...VJ(UJ(g,{source_group_id:n.source_group_id,shouldAddInnerObstacles:!0,chipMarginsMap:u})),orderStrategy:i??"largest_to_smallest",placementStrategy:r??"minimum_sum_squared_distance_to_network",minGap:l,obstacles:x,bounds:v},P=hLt(n,S);met.enabled&&(n.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-circuitjson-${n.name}`,content:JSON.stringify(e.toArray())}),n.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-${n.name}`,content:S}));let T=PS(S);if(met.enabled&&global?.debugGraphics){let k=eA(T);k.title=`packOutput-${n.name}`,global.debugGraphics?.push(k)}dLt(n,T,P)},gLt=n=>{let{db:e}=n.root,{_parsedProps:t}=n,i=n.children.filter(C=>C.pcb_component_id||C.pcb_group_id);if(i.some(C=>{let E=C._parsedProps;return E?.pcbX!==void 0||E?.pcbY!==void 0}))return;let s=t.pcbJustifyContent??t.justifyContent,o=t.pcbAlignItems??t.alignItems,a=t.pcbFlexGap??t.pcbGap??t.gap,c=t.pcbFlexDirection??"row",l={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"space-between","space-between":"space-between","space-around":"space-around","space-evenly":"space-evenly",center:"center"}[s??"space-between"],u={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[o??"center"];if(!l)throw new Error(`Invalid justifyContent value: "${s}"`);if(!u)throw new Error(`Invalid alignItems value: "${o}"`);let p=0,f=0;typeof a=="object"?(p=a.y??0,f=a.x??0):typeof a=="number"?(p=a,f=a):typeof a=="string"&&(p=$.parse(a),f=$.parse(a));let y,g=t.width??t.pcbWidth??void 0,x=t.height??t.pcbHeight??void 0;(g===void 0||x===void 0)&&(y=Pw(i.map(C=>C._getMinimumFlexContainerSize()).filter(C=>C!==null),{alignItems:u,justifyContent:l,direction:c,rowGap:p,columnGap:f}),g=y.width,x=y.height);let S=new ES(g,x,{alignItems:u,justifyContent:l,direction:c,rowGap:p,columnGap:f});for(let C of i){let E=C._getMinimumFlexContainerSize();S.addChild({metadata:C,width:E?.width??0,height:E?.height??0,flexBasis:E?c==="row"?E.width:E.height:void 0})}S.build();let P={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let C of S.children)P.minX=Math.min(P.minX,C.position.x),P.minY=Math.min(P.minY,C.position.y),P.maxX=Math.max(P.maxX,C.position.x+C.size.width),P.maxY=Math.max(P.maxY,C.position.y+C.size.height);P.width=P.maxX-P.minX,P.height=P.maxY-P.minY;let T=n._getGlobalPcbPositionBeforeLayout(),k={x:T.x-(P.maxX+P.minX)/2,y:T.y-(P.maxY+P.minY)/2};for(let C of S.children)C.metadata._repositionOnPcb({x:C.position.x+C.size.width/2+k.x,y:C.position.y+C.size.height/2+k.y});e.pcb_group.update(n.pcb_group_id,{width:P.width,height:P.height,center:T})};function xLt(n){let{db:e}=n.root,t=new Map,i=new Map,r=new Set,o=n.selectAll("trace").filter(R=>R._parsedProps?.schDisplayLabel),a=n.selectAll("group"),c=[n.schematic_group_id,...a.map(R=>R.schematic_group_id)],l=e.schematic_component.list().filter(R=>c.includes(R.schematic_group_id)),u=[],p=new Map,f=new Map;for(let R of l){let j=R.schematic_component_id,B=[],G=e.source_component.getWhere({source_component_id:R.source_component_id}),U=e.schematic_port.list({schematic_component_id:R.schematic_component_id});for(let H of U){let Q=`${G?.name??R.schematic_component_id}.${H.pin_number}`;p.set(Q,H.schematic_port_id),f.set(H.schematic_port_id,Q)}for(let H of U){let Q=f.get(H.schematic_port_id);B.push({pinId:Q,x:H.center.x,y:H.center.y})}u.push({chipId:j,center:R.center,width:R.size.width,height:R.size.height,pins:B})}let y=new Set,g=new Map,x=new Map,v=new Map;for(let R of l){let j=e.schematic_port.list({schematic_component_id:R.schematic_component_id});for(let B of j)y.add(B.schematic_port_id),B.source_port_id&&(g.set(B.schematic_port_id,B.source_port_id),x.set(B.source_port_id,B.schematic_port_id))}let S=new Set;n.subcircuit_id&&S.add(n.subcircuit_id);for(let R of a)R.subcircuit_id&&S.add(R.subcircuit_id);let T=e.source_trace.list().filter(R=>{if(R.subcircuit_id===n.subcircuit_id)return!0;for(let j of R.connected_source_port_ids)if(x.has(j))return!0;return!1}).flatMap(R=>R.connected_source_net_ids);for(let R of T){let j=e.source_net.get(R);j?.subcircuit_id&&S.add(j.subcircuit_id)}let k=[],C=new Map;for(let R of e.source_trace.list()){if(R.subcircuit_id&&!S.has(R.subcircuit_id))continue;let j=(R.connected_source_port_ids??[]).map(B=>x.get(B)).filter(B=>!!B&&y.has(B));if(j.length>=2){let[B,G]=j.slice(0,2),U=[B,G].sort().join("::");if(!C.has(U)){C.set(U,R.source_trace_id);let H=R.display_name??R.source_trace_id;R.subcircuit_connectivity_map_key&&(r.add(R.subcircuit_connectivity_map_key),v.set(H,R.subcircuit_connectivity_map_key),i.set(R.subcircuit_connectivity_map_key,H)),k.push({pinIds:[B,G].map(Q=>f.get(Q)),netId:H})}}}let E=[];for(let R of e.source_net.list().filter(j=>!j.subcircuit_id||S.has(j.subcircuit_id)))R.subcircuit_connectivity_map_key&&(r.add(R.subcircuit_connectivity_map_key),t.set(R.subcircuit_connectivity_map_key,R));let N=new Map;for(let[R,j]of g){let B=e.source_port.get(j);if(!B?.subcircuit_connectivity_map_key)continue;let G=B.subcircuit_connectivity_map_key;r.add(G),N.has(G)||N.set(G,[]),N.get(G).push(R)}for(let[R,j]of N){let B=t.get(R);if(B&&j.length>=2){let G=String(B.name||B.source_net_id||R);v.set(G,R),i.set(R,G);let H=.1*(.18/.18),Q=Number((String(G).length*H).toFixed(2));E.push({netId:G,pinIds:j.map(tt=>f.get(tt)),netLabelWidth:Q})}}let I=(()=>{let R={},j=new Set(E.map(B=>B.netId));for(let B of e.source_net.list().filter(G=>!G.subcircuit_id||S.has(G.subcircuit_id)))B.name&&j.has(B.name)&&(B.is_ground||B.name.toLowerCase().startsWith("gnd")?R[B.name]=["y-"]:B.is_power||B.name.toLowerCase().startsWith("v")?R[B.name]=["y+"]:R[B.name]=["x-","x+"]);return R})();return{inputProblem:{chips:u,directConnections:k,netConnections:E,availableNetLabelOrientations:I,maxMspPairDistance:n._parsedProps.schMaxTraceDistance??2.4},pinIdToSchematicPortId:p,pairKeyToSourceTraceId:C,sckToSourceNet:t,sckToUserNetId:i,userNetIdToSck:v,allSourceAndSchematicPortIdsInScope:y,schPortIdToSourcePortId:g,displayLabelTraces:o,allScks:r}}var gr=1e-6;function _et(n){let e=Math.abs(n.to.x-n.from.x),t=Math.abs(n.to.y-n.from.y);return e>=t}function qS(n,e){return Math.hypot(e.x-n.x,e.y-n.y)}function yet(n,e,t){return{x:n.x+(e.x-n.x)*t,y:n.y+(e.y-n.y)*t}}function get(n,e,t){let i=qS(n,e);if(i<gr)return 0;let r=((t.x-n.x)*(e.x-n.x)+(t.y-n.y)*(e.y-n.y))/((e.x-n.x)*(e.x-n.x)+(e.y-n.y)*(e.y-n.y));return Math.max(0,Math.min(1,r))*i}function XS(n,e,t,i){return n*i-e*t}function bLt(n,e,t,i){let r={x:e.x-n.x,y:e.y-n.y},s={x:i.x-t.x,y:i.y-t.y},o=XS(r.x,r.y,s.x,s.y),a={x:t.x-n.x,y:t.y-n.y},c=XS(a.x,a.y,r.x,r.y);if(Math.abs(o)<gr&&Math.abs(c)<gr||Math.abs(o)<gr&&Math.abs(c)>=gr)return null;let l=XS(a.x,a.y,s.x,s.y)/o,u=XS(a.x,a.y,r.x,r.y)/o;return l<-gr||l>1+gr||u<-gr||u>1+gr?null:{x:n.x+l*r.x,y:n.y+l*r.y}}function vLt(n,e=gr){if(n.length===0)return n;n.sort((r,s)=>r.start-s.start);let t=[],i={...n[0]};for(let r=1;r<n.length;r++){let s=n[r];s.start<=i.end+e?i.end=Math.max(i.end,s.end):(t.push(i),i={...s})}return t.push(i),t}function wLt(n,e,t){let i=qS(n.from,n.to);if(i<gr||e.length===0)return[n];let r=t/2,s=e.map(p=>({start:Math.max(0,p-r),end:Math.min(i,p+r)})).filter(p=>p.end-p.start>gr),o=vLt(s),a=[],c=0,l={x:n.to.x-n.from.x,y:n.to.y-n.from.y},u=(p,f,y)=>{if(f-p<=gr)return;let g=p/i,x=f/i;a.push({from:yet(n.from,n.to,g),to:yet(n.from,n.to,x),...y?{is_crossing:!0}:{}})};for(let p of o)p.start-c>gr&&u(c,p.start,!1),u(p.start,p.end,!0),c=p.end;return i-c>gr&&u(c,i,!1),a.length>0?a:[n]}function SLt(n,e={}){let t=e.crossSegmentLength??.075,i=e.tolerance??gr,r=new Map,s=c=>`${c.traceIdx}:${c.edgeIdx}`,o=c=>n[c.traceIdx].edges[c.edgeIdx];for(let c=0;c<n.length;c++){let l=n[c];for(let u=0;u<l.edges.length;u++){let p=l.edges[u];for(let f=c;f<n.length;f++){let y=n[f];for(let g=f===c?u+1:0;g<y.edges.length;g++){let x=y.edges[g],v=bLt(p.from,p.to,x.from,x.to);if(!v)continue;let S=qS(p.from,p.to),P=qS(x.from,x.to);if(S<i||P<i)continue;let T=get(p.from,p.to,v),k=get(x.from,x.to,v),C=T<=i||Math.abs(S-T)<=i||Number.isNaN(T),E=k<=i||Math.abs(P-k)<=i||Number.isNaN(k);if(!C&&!E){let N=_et(p),I=_et(x),A;if(N!==I)A=N;else{let B=Math.abs(p.to.x-p.from.x),G=Math.abs(p.to.y-p.from.y),U=Math.abs(x.to.x-x.from.x),H=Math.abs(x.to.y-x.from.y),Q=B-G,tt=U-H;A=Q===tt?!0:Q>tt}let R=s({traceIdx:A?c:f,edgeIdx:A?u:g}),j=r.get(R)??[];j.push(A?T:k),r.set(R,j)}}}}}let a=n.map(c=>({source_trace_id:c.source_trace_id,edges:[]}));for(let c=0;c<n.length;c++){let l=n[c];for(let u=0;u<l.edges.length;u++){let p=s({traceIdx:c,edgeIdx:u}),f=r.get(p)??[];if(f.length===0){a[c].edges.push(l.edges[u]);continue}let y=Array.from(new Set(f.map(x=>Number(x.toFixed(6))))).sort((x,v)=>x-v),g=wLt(l.edges[u],y,t);a[c].edges.push(...g)}}return a}var Vo=1e-6;function ZS(n,e,t=Vo){return Math.abs(n-e)<=t}function W_(n,e,t=Vo){return ZS(n.x,e.x,t)&&ZS(n.y,e.y,t)}function xet(n,e,t,i=Vo){let r=Math.min(e.x,t.x)-i,s=Math.max(e.x,t.x)+i,o=Math.min(e.y,t.y)-i,a=Math.max(e.y,t.y)+i;return n.x<r||n.x>s||n.y<o||n.y>a?!1:Math.abs((t.x-e.x)*(n.y-e.y)-(t.y-e.y)*(n.x-e.x))<=i}function bet(n,e=Vo){let t=new Map;for(let i of n){let r=`${i.x.toFixed(6)},${i.y.toFixed(6)}`;t.has(r)||t.set(r,i)}return Array.from(t.values())}function vet(n){return{x:n.to.x-n.from.x,y:n.to.y-n.from.y}}function HA(n,e,t=Vo){let i=vet(n),r=vet(e),s=Math.hypot(i.x,i.y),o=Math.hypot(r.x,r.y);if(s<t||o<t)return!0;let a=i.x*r.y-i.y*r.x;return Math.abs(a)<=t*s*o}function z1(n,e,t=Vo){return n.edges.filter(i=>W_(i.from,e,t)||W_(i.to,e,t))}function wet(n,e,t=Vo){for(let i of n.edges){if(W_(i.from,e,t))return i.from;if(W_(i.to,e,t))return i.to}return null}function PLt(n,e,t=Vo){let i=W_(n.from,e,t)||ZS(n.from.x,e.x,t)&&ZS(n.from.y,e.y,t)?n.to:n.from,r=i.x-e.x,s=i.y-e.y;return Math.abs(r)<t&&Math.abs(s)<t?null:Math.abs(r)>=Math.abs(s)?r>=0?"right":"left":s>=0?"up":"down"}function B_(n,e,t=Vo){let i=z1(n,e,t);if(i.length<2)return null;let r=i.map(p=>PLt(p,e,t)),s=r.includes("up"),o=r.includes("down"),a=r.includes("left"),c=r.includes("right"),l=s?"up":o?"down":null,u=c?"right":a?"left":null;return l&&u?`${l}-${u}`:null}function kLt(n,e={}){let t=e.tolerance??Vo,i={};for(let s of n)i[s.source_trace_id]=[];let r=n.map(s=>{let o=[];for(let a of s.edges)o.push(a.from,a.to);return bet(o,t)});for(let s=0;s<n.length;s++){let o=n[s],a=r[s];for(let c=s+1;c<n.length;c++){let l=n[c],u=r[c];for(let p of a)for(let f of u)if(W_(p,f,t)){let y=z1(o,p,t),g=z1(l,f,t),x=y.some(T=>g.some(k=>!HA(T,k,t))),v=B_(o,p,t),S=B_(l,f,t);x&&!(v!==null&&S!==null&&v===S)&&(i[o.source_trace_id].push(p),o.source_trace_id!==l.source_trace_id&&i[l.source_trace_id].push(f))}for(let p of a)for(let f of l.edges)if(xet(p,f.from,f.to,t)){let g=z1(o,p,t).some(T=>!HA(T,f,t)),x=B_(o,p,t),v=wet(l,p,t*1e3),S=v?B_(l,v,t):null;g&&!(x!==null&&S!==null&&x===S)&&(i[o.source_trace_id].push(p),o.source_trace_id!==l.source_trace_id&&i[l.source_trace_id].push(p))}for(let p of u)for(let f of o.edges)if(xet(p,f.from,f.to,t)){let g=z1(l,p,t).some(T=>!HA(f,T,t)),x=B_(l,p,t),v=wet(o,p,t*1e3),S=v?B_(o,v,t):null;g&&!(S!==null&&x!==null&&S===x)&&(i[l.source_trace_id].push(p),o.source_trace_id!==l.source_trace_id&&i[o.source_trace_id].push(p))}}}for(let s of Object.keys(i))i[s]=bet(i[s],t);return i}var WA=(0,Qet.default)("Group_doInitialSchematicTraceRender");function TLt(n){let{group:e,solver:t,pinIdToSchematicPortId:i,userNetIdToSck:r}=n,{db:s}=e.root,o=t.traceCleanupSolver?.getOutput().traces??t.traceLabelOverlapAvoidanceSolver?.getOutput().traces??t.schematicTraceLinesSolver?.solvedTracePaths,a=[];WA(`Traces inside SchematicTraceSolver output: ${(o??[]).length}`);for(let u of o??[]){let p=u?.tracePath;if(!Array.isArray(p)||p.length<2){WA(`Skipping trace ${u?.pinIds.join(",")} because it has less than 2 points`);continue}let f=[];for(let x=0;x<p.length-1;x++)f.push({from:{x:p[x].x,y:p[x].y},to:{x:p[x+1].x,y:p[x+1].y}});let y=null,g;if(Array.isArray(u?.pins)&&u.pins.length===2){let x=i.get(u.pins[0]?.pinId),v=i.get(u.pins[1]?.pinId);if(x&&v){for(let S of[x,v])s.schematic_port.get(S)&&s.schematic_port.update(S,{is_connected:!0});g=r.get(String(u.userNetId))}}y||(y=`solver_${u?.mspPairId}`,g=r.get(String(u.userNetId))),a.push({source_trace_id:y,edges:f,subcircuit_connectivity_map_key:g})}WA(`Applying ${a.length} traces from SchematicTraceSolver output`);let c=SLt(a.map(u=>({source_trace_id:u.source_trace_id,edges:u.edges}))),l=kLt(c);for(let u of c)s.schematic_trace.insert({source_trace_id:u.source_trace_id,edges:u.edges,junctions:l[u.source_trace_id]??[],subcircuit_connectivity_map_key:a.find(p=>p.source_trace_id===u.source_trace_id)?.subcircuit_connectivity_map_key})}var ELt=n=>{switch(n){case"x+":return"left";case"x-":return"right";case"y+":return"bottom";case"y-":return"top";case"left":return"right";case"top":return"bottom";case"right":return"left";case"bottom":return"top"}},MLt=n=>{for(let t of n){let i=t._getDirectlyConnectedTraces();for(let r of i){let s=r._parsedProps.schDisplayLabel;if(s)return{name:s,wasAssignedDisplayLabel:!0}}}return{name:n.map(t=>t._getNetLabelText()).join("/"),wasAssignedDisplayLabel:!1}},qA=(0,tnt.default)("Group_doInitialSchematicTraceRender");function CLt(n){let{group:e,solver:t,sckToSourceNet:i,allScks:r,allSourceAndSchematicPortIdsInScope:s,schPortIdToSourcePortId:o,userNetIdToSck:a,pinIdToSchematicPortId:c,schematicPortIdsWithPreExistingNetLabels:l,schematicPortIdsWithRoutedTraces:u}=n,{db:p}=e.root,f=t.netLabelPlacementSolver?.netLabelPlacements??t.traceLabelOverlapAvoidanceSolver?.getOutput().netLabelPlacements??[],y=t.mspConnectionPairSolver.globalConnMap;for(let g of f){qA(`processing placement: ${g.netId}`);let x=y.getIdsConnectedToNet(g.globalConnNetId).find(R=>a.get(R)),v=a.get(x),S=g.anchorPoint,P=g.orientation,T=ELt(P),k=v?i.get(v):void 0,C=g.pinIds.map(R=>c.get(R));if(C.some(R=>l.has(R))){qA(`skipping net label placement for "${g.netId}" REASON:schematic port has pre-existing net label`);continue}if(k){let R=k.name,j=ml({anchor_position:S,anchor_side:T,text:R});p.schematic_net_label.insert({text:R,anchor_position:S,center:j,anchor_side:T,...k?.source_net_id?{source_net_id:k.source_net_id}:{}});continue}let E=e.selectAll("port").filter(R=>R._getSubcircuitConnectivityKey()===v),{name:N,wasAssignedDisplayLabel:I}=MLt(E);if(!I&&C.some(R=>u.has(R))){qA(`skipping net label placement for "${g.netId}" REASON:schematic port has routed traces and no display label`);continue}let A=ml({anchor_position:S,anchor_side:T,text:N});p.schematic_net_label.insert({text:N,anchor_position:S,center:A,anchor_side:T})}}var ILt=({allSourceAndSchematicPortIdsInScope:n,group:e,schPortIdToSourcePortId:t,sckToSourceNet:i,pinIdToSchematicPortId:r,schematicPortIdsWithPreExistingNetLabels:s})=>{let{db:o}=e.root;for(let a of Array.from(n)){let c=o.schematic_port.get(a);if(!c||c.is_connected)continue;let l=t.get(a);if(!l)continue;let p=o.source_port.get(l)?.subcircuit_connectivity_map_key;if(!p)continue;let f=i.get(p);if(!f||o.schematic_net_label.list().some(S=>Math.abs(S.anchor_position.x-c.center.x)<.1&&Math.abs(S.anchor_position.y-c.center.y)<.1?f.source_net_id&&S.source_net_id?S.source_net_id===f.source_net_id:S.text===(f.name||p):!1))continue;let g=f.name||f.source_net_id||p,x=B1(c.facing_direction||"right")||"right",v=ml({anchor_position:c.center,anchor_side:x,text:g});o.schematic_net_label.insert({text:g,anchor_position:c.center,center:v,anchor_side:x,...f.source_net_id?{source_net_id:f.source_net_id}:{}})}},NLt=n=>{let e=new Set,t=n.selectAll("netlabel");for(let i of t){let r=i._getConnectedPorts();for(let s of r)s.schematic_port_id&&e.add(s.schematic_port_id)}return e},ALt=({solver:n,pinIdToSchematicPortId:e})=>{let t=n.schematicTraceLinesSolver.solvedTracePaths,i=new Set;for(let r of t)for(let s of r.pinIds){let o=e.get(s);o&&i.add(o)}return i},RLt=(0,Jet.default)("Group_doInitialSchematicTraceRender"),OLt=n=>{if(!n.root?._featureMspSchematicTraceRouting||!n.isSubcircuit||n.root?.schematicDisabled)return;let{inputProblem:e,pinIdToSchematicPortId:t,pairKeyToSourceTraceId:i,sckToSourceNet:r,allSourceAndSchematicPortIdsInScope:s,schPortIdToSourcePortId:o,displayLabelTraces:a,allScks:c,userNetIdToSck:l}=xLt(n),u=NLt(n);RLt.enabled&&n.root?.emit("debug:logOutput",{type:"debug:logOutput",name:"group-trace-render-input-problem",content:JSON.stringify(e,null,2)});let p=new bQ(e);p.solve();let f=ALt({solver:p,pinIdToSchematicPortId:t});TLt({group:n,solver:p,pinIdToSchematicPortId:t,userNetIdToSck:l}),CLt({group:n,solver:p,sckToSourceNet:r,allSourceAndSchematicPortIdsInScope:s,schPortIdToSourcePortId:o,pinIdToSchematicPortId:t,allScks:c,userNetIdToSck:l,schematicPortIdsWithPreExistingNetLabels:u,schematicPortIdsWithRoutedTraces:f}),ILt({group:n,allSourceAndSchematicPortIdsInScope:s,schPortIdToSourcePortId:o,sckToSourceNet:r,pinIdToSchematicPortId:t,schematicPortIdsWithPreExistingNetLabels:u})},LLt=()=>({async simulate(n){let e="spice-experiment-1",{circuit:t,tran:i}=SQ(n);return{simulationResultCircuitJson:PQ(i,t,e)}}}),Ya=(0,ent.default)("tscircuit:core:Group_doInitialSimulationSpiceEngineRender");function FLt(n){if(!n.isSubcircuit)return;let{root:e}=n;if(!e)return;let t=n.selectAll("analogsimulation");if(t.length===0)return;let i={...e.platform?.spiceEngineMap};i.spicey||(i.spicey=LLt());let r=e.db.toArray(),s;try{s=wQ(r).toSpiceString(),Ya(`Generated SPICE string:
250
250
  ${s}`)}catch(o){Ya(`Failed to convert circuit JSON to SPICE: ${o}`);return}for(let o of t){let a=o._parsedProps.spiceEngine??"spicey",c=i[a];if(!c)throw new Error(`SPICE engine "${a}" not found in platform config. Available engines: ${JSON.stringify(Object.keys(i).filter(u=>u!=="spicey"))}`);let l=`spice-simulation-${a}-${o.source_component_id}`;Ya(`Queueing simulation for spice engine: ${a} (id: ${l})`),n._queueAsyncEffect(l,async()=>{try{Ya(`Running simulation with engine: ${a}`);let u=await c.simulate(s);Ya(`Simulation completed, received ${u.simulationResultCircuitJson.length} elements`);let p=e.db.simulation_experiment.list()[0];if(!p){Ya("No simulation experiment found, skipping result insertion");return}for(let f of u.simulationResultCircuitJson){f.type==="simulation_transient_voltage_graph"&&(f.simulation_experiment_id=p.simulation_experiment_id);let y=f.type;y&&e.db[y]?(e.db[y].insert(f),Ya(`Inserted ${y} into database`)):(Ya(`Warning: Unknown element type ${y}, adding to raw db`),e.db._addElement(f))}n._markDirty("SimulationSpiceEngineRender")}catch(u){Ya(`Simulation failed for engine ${a}: ${u}`);let p=e.db.simulation_experiment.list()[0];e.db.simulation_unknown_experiment_error.insert({simulation_experiment_id:p?.simulation_experiment_id,error_type:"simulation_unknown_experiment_error",message:u instanceof Error?u.message:String(u)})}})}}function zLt(n){if(n.root?.pcbDisabled||!n.pcb_group_id)return;let e=n._parsedProps?.pcbPositionAnchor;if(!e)return;let t=n._getGlobalPcbPositionBeforeLayout(),{pcbX:i,pcbY:r}=n._parsedProps;if(i===void 0&&r===void 0)return;let{db:s}=n.root,o=s.pcb_group.get(n.pcb_group_id);if(!o)return;let a=o.width,c=o.height,{center:l}=o;if(o.outline&&o.outline.length>0){let x=Ro(o.outline);x&&(a=x.maxX-x.minX,c=x.maxY-x.minY)}if(!a||!c)return;let u={left:l.x-a/2,right:l.x+a/2,top:l.y+c/2,bottom:l.y-c/2},p={...l},f=null;if(new Set(["center","top_left","top_center","top_right","center_left","center_right","bottom_left","bottom_center","bottom_right"]).has(e))switch(e){case"center":f=p;break;case"top_left":f={x:u.left,y:u.top};break;case"top_center":f={x:p.x,y:u.top};break;case"top_right":f={x:u.right,y:u.top};break;case"center_left":f={x:u.left,y:p.y};break;case"center_right":f={x:u.right,y:p.y};break;case"bottom_left":f={x:u.left,y:u.bottom};break;case"bottom_center":f={x:p.x,y:u.bottom};break;case"bottom_right":f={x:u.right,y:u.bottom};break}if(!f)return;let g={...p};t.x!==void 0&&(g.x+=t.x-f.x),t.y!==void 0&&(g.y+=t.y-f.y),(Math.abs(g.x-p.x)>1e-6||Math.abs(g.y-p.y)>1e-6)&&(n._repositionOnPcb(g),s.pcb_group.update(n.pcb_group_id,{center:g})),s.pcb_group.update(n.pcb_group_id,{anchor_position:t,anchor_alignment:e})}var _l=class extends Gn{constructor(){super(...arguments);d(this,"pcb_group_id",null);d(this,"schematic_group_id",null);d(this,"subcircuit_id",null);d(this,"_hasStartedAsyncAutorouting",!1);d(this,"_asyncAutoroutingResult",null);d(this,"unnamedElementCounter",{})}get config(){return{zodProps:_H,componentName:"Group"}}doInitialSourceGroupRender(){let{db:e}=this.root,t=typeof this._parsedProps.name=="string"&&this._parsedProps.name.length>0,i=e.source_group.insert({name:this.name,is_subcircuit:this.isSubcircuit,was_automatically_named:!t});this.source_group_id=i.source_group_id,this.isSubcircuit&&(this.subcircuit_id=`subcircuit_${i.source_group_id}`,e.source_group.update(i.source_group_id,{subcircuit_id:this.subcircuit_id}))}doInitialSourceRender(){let{db:e}=this.root;for(let t of this.children)e.source_component.update(t.source_component_id,{source_group_id:this.source_group_id})}doInitialSourceParentAttachment(){let{db:e}=this.root,t=this.parent?.getGroup?.();if(t?.source_group_id&&e.source_group.update(this.source_group_id,{parent_source_group_id:t.source_group_id}),!this.isSubcircuit)return;let i=this.parent?.getSubcircuit?.()?.subcircuit_id;i&&e.source_group.update(this.source_group_id,{parent_subcircuit_id:i})}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=t,r=i.outline&&i.outline.length>0,s=r?i.outline.map(a=>({x:X.parse(a.x),y:X.parse(a.y)})):void 0,o=e.pcb_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id??this.getSubcircuit()?.subcircuit_id,name:this.name,center:this._getGlobalPcbPositionBeforeLayout(),...r?{outline:s}:{width:0,height:0},pcb_component_ids:[],source_group_id:this.source_group_id,autorouter_configuration:t.autorouter?{trace_clearance:t.autorouter.traceClearance}:void 0});this.pcb_group_id=o.pcb_group_id;for(let a of this.children)e.pcb_component.update(a.pcb_component_id,{pcb_group_id:o.pcb_group_id})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,t=this._parsedProps,i=t.outline&&t.outline.length>0;if(this.pcb_group_id){let r=this._parsedProps.pcbX!==void 0||this._parsedProps.pcbY!==void 0;if(i){let p=t.outline.map(v=>({x:X.parse(v.x),y:X.parse(v.y)})),f=Ro(p);if(!f)return;let y=(f.minX+f.maxX)/2,g=(f.minY+f.maxY)/2,x=r?e.pcb_group.get(this.pcb_group_id)?.center??{x:y,y:g}:{x:y,y:g};e.pcb_group.update(this.pcb_group_id,{center:x});return}let s=QS(this.children),o=s.width,a=s.height,c=(s.minX+s.maxX)/2,l=(s.minY+s.maxY)/2;if(this.isSubcircuit){let{padLeft:p,padRight:f,padTop:y,padBottom:g}=this._resolvePcbPadding();o+=p+f,a+=y+g,c+=(f-p)/2,l+=(y-g)/2}let u=r?e.pcb_group.get(this.pcb_group_id)?.center??{x:c,y:l}:{x:c,y:l};e.pcb_group.update(this.pcb_group_id,{width:Number(t.width??o),height:Number(t.height??a),center:u})}}getNextAvailableName(e){var t,i;return(t=this.unnamedElementCounter)[i=e.lowercaseComponentName]??(t[i]=1),`unnamed_${e.lowercaseComponentName}${this.unnamedElementCounter[e.lowercaseComponentName]++}`}_resolvePcbPadding(){let e=this._parsedProps,t=e.pcbLayout,i=p=>{let f=t?.[p],y=e[p];if(typeof f=="number")return f;if(typeof y=="number")return y},r=i("padding")??0,s=i("paddingX"),o=i("paddingY"),a=i("paddingLeft")??s??r,c=i("paddingRight")??s??r,l=i("paddingTop")??o??r,u=i("paddingBottom")??o??r;return{padLeft:a,padRight:c,padTop:l,padBottom:u}}doInitialCreateTraceHintsFromProps(){let{_parsedProps:e}=this,{db:t}=this.root,i=e;if(!this.isSubcircuit)return;let r=i.manualEdits?.manual_trace_hints;if(r)for(let s of r)this.add(new p9({for:s.pcb_port_selector,offsets:s.offsets}))}doInitialSourceAddConnectivityMapKey(){JOt(this)}_areChildSubcircuitsRouted(){let e=this.selectAll("group").filter(t=>t.isSubcircuit);for(let t of e)if(t._shouldRouteAsync()&&!t._asyncAutoroutingResult)return!1;return!0}_shouldRouteAsync(){let e=this._getAutorouterConfig();return e.groupMode==="sequential-trace"?!1:!!(e.local&&e.groupMode==="subcircuit"||!e.local)}_hasTracesToRoute(){let e=(0,Y_.default)("tscircuit:core:_hasTracesToRoute"),t=this.selectAll("trace");return e(`[${this.getString()}] has ${t.length} traces to route`),t.length>0}async _runEffectMakeHttpAutoroutingRequest(){let{db:e}=this.root,t=(0,Y_.default)("tscircuit:core:_runEffectMakeHttpAutoroutingRequest"),i=this._parsedProps,r=this._getAutorouterConfig(),s=r.serverUrl,o=r.serverMode,a=(u,p)=>(t("fetching",u),p.headers&&(p.headers["Tscircuit-Core-Version"]=this.root?.getCoreVersion()),fetch(u,p)),c=this.root.db.toArray().filter(u=>u.type.startsWith("source_")||u.type.startsWith("pcb_"));if(o==="solve-endpoint"){if(this.props.autorouter?.inputFormat==="simplified"){let{autorouting_result:p}=await a(`${s}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_simple_route_json:i9({db:e,minTraceWidth:this.props.autorouter?.minTraceWidth??.15,subcircuit_id:this.subcircuit_id}).simpleRouteJson,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(f=>f.json());this._asyncAutoroutingResult=p,this._markDirty("PcbTraceRender");return}let{autorouting_result:u}=await a(`${s}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_circuit_json:c,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(p=>p.json());this._asyncAutoroutingResult=u,this._markDirty("PcbTraceRender");return}let{autorouting_job:l}=await a(`${s}/autorouting/jobs/create`,{method:"POST",body:JSON.stringify({input_circuit_json:c,provider:"freerouting",autostart:!0,display_name:this.root?.name,subcircuit_id:this.subcircuit_id,server_cache_enabled:r.serverCacheEnabled}),headers:{"Content-Type":"application/json"}}).then(u=>u.json());for(;;){let{autorouting_job:u}=await a(`${s}/autorouting/jobs/get`,{method:"POST",body:JSON.stringify({autorouting_job_id:l.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(p=>p.json());if(u.is_finished){let{autorouting_job_output:p}=await a(`${s}/autorouting/jobs/get_output`,{method:"POST",body:JSON.stringify({autorouting_job_id:l.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(f=>f.json());this._asyncAutoroutingResult={output_pcb_traces:p.output_pcb_traces},this._markDirty("PcbTraceRender");break}if(u.has_error){let p=new L1(`Autorouting job failed: ${JSON.stringify(u.error)}`);throw e.pcb_autorouting_error.insert({pcb_error_id:l.autorouting_job_id,error_type:"pcb_autorouting_error",message:p.message}),p}await new Promise(p=>setTimeout(p,100))}}async _runLocalAutorouting(){let{db:e}=this.root,t=this._parsedProps,i=(0,Y_.default)("tscircuit:core:_runLocalAutorouting");i(`[${this.getString()}] starting local autorouting`);let r=this._getAutorouterConfig(),s=this._isLaserPrefabAutorouter(r),{simpleRouteJson:o}=i9({db:e,minTraceWidth:this.props.autorouter?.minTraceWidth??.15,subcircuit_id:this.subcircuit_id});if(i.enabled&&global.debugOutputArray?.push({name:`simpleroutejson-${this.props.name}.json`,obj:o}),i.enabled){let l=Xg(o);l.title=`autorouting-${this.props.name}`,global.debugGraphics?.push(l)}this.root?.emit("autorouting:start",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),simpleRouteJson:o});let a;r.algorithmFn?a=await r.algorithmFn(o):a=new XOt(o,{capacityDepth:this.props.autorouter?.capacityDepth,targetMinCapacity:this.props.autorouter?.targetMinCapacity,useAssignableViaSolver:s});let c=new Promise((l,u)=>{a.on("complete",p=>{i(`[${this.getString()}] local autorouting complete`),l(p.traces)}),a.on("error",p=>{i(`[${this.getString()}] local autorouting error: ${p.error.message}`),u(p.error)})});a.on("progress",l=>{this.root?.emit("autorouting:progress",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),...l})}),a.start();try{let l=await c;this._asyncAutoroutingResult={output_pcb_traces:l},this._markDirty("PcbTraceRender")}catch(l){let{db:u}=this.root;throw u.pcb_autorouting_error.insert({pcb_error_id:`pcb_autorouter_error_subcircuit_${this.subcircuit_id}`,error_type:"pcb_autorouting_error",message:l instanceof Error?l.message:String(l)}),this.root?.emit("autorouting:error",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),error:{message:l instanceof Error?l.message:String(l)},simpleRouteJson:o}),l}finally{a.stop()}}_startAsyncAutorouting(){this._hasStartedAsyncAutorouting||(this._hasStartedAsyncAutorouting=!0,this._getAutorouterConfig().local?this._queueAsyncEffect("capacity-mesh-autorouting",async()=>this._runLocalAutorouting()):this._queueAsyncEffect("make-http-autorouting-request",async()=>this._runEffectMakeHttpAutoroutingRequest()))}doInitialPcbTraceRender(){let e=(0,Y_.default)("tscircuit:core:doInitialPcbTraceRender");if(this.isSubcircuit&&!this.root?.pcbDisabled&&!this.getInheritedProperty("routingDisabled")&&!this._shouldUseTraceByTraceRouting()){if(!this._areChildSubcircuitsRouted()){e(`[${this.getString()}] child subcircuits are not routed, skipping async autorouting until subcircuits routed`);return}e(`[${this.getString()}] no child subcircuits to wait for, initiating async routing`),this._hasTracesToRoute()&&this._startAsyncAutorouting()}}doInitialSchematicTraceRender(){OLt(this)}updatePcbTraceRender(){let e=(0,Y_.default)("tscircuit:core:updatePcbTraceRender");if(e(`[${this.getString()}] updating...`),!this.isSubcircuit)return;if(this._shouldRouteAsync()&&this._hasTracesToRoute()&&!this._hasStartedAsyncAutorouting){this._areChildSubcircuitsRouted()&&(e(`[${this.getString()}] child subcircuits are now routed, starting async autorouting`),this._startAsyncAutorouting());return}if(!this._asyncAutoroutingResult||this._shouldUseTraceByTraceRouting())return;let{db:t}=this.root;if(this._asyncAutoroutingResult.output_simple_route_json){e(`[${this.getString()}] updating PCB traces from simple route json (${this._asyncAutoroutingResult.output_simple_route_json.traces?.length} traces)`),this._updatePcbTraceRenderFromSimpleRouteJson();return}if(this._asyncAutoroutingResult.output_pcb_traces){e(`[${this.getString()}] updating PCB traces from ${this._asyncAutoroutingResult.output_pcb_traces.length} traces`),this._updatePcbTraceRenderFromPcbTraces();return}}_updatePcbTraceRenderFromSimpleRouteJson(){let{db:e}=this.root,{traces:t}=this._asyncAutoroutingResult.output_simple_route_json;if(t)for(let i of t){let r=e.pcb_trace.insert({subcircuit_id:this.subcircuit_id,route:i.route})}}_updatePcbTraceRenderFromPcbTraces(){let{output_pcb_traces:e}=this._asyncAutoroutingResult;if(!e)return;let{db:t}=this.root;for(let i of e)if(i.type==="pcb_trace"){if(i.subcircuit_id=this.subcircuit_id,i.connection_name){let r=i.connection_name;i.source_trace_id=r}t.pcb_trace.insert(i)}for(let i of e)if(i.type!=="pcb_via"&&i.type==="pcb_trace")for(let r of i.route)r.route_type==="via"&&t.pcb_via.insert({pcb_trace_id:i.pcb_trace_id,x:r.x,y:r.y,hole_diameter:.3,outer_diameter:.6,layers:[r.from_layer,r.to_layer],from_layer:r.from_layer,to_layer:r.to_layer})}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=e.schematic_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id,name:this.name,center:this._getGlobalSchematicPositionBeforeLayout(),width:0,height:0,schematic_component_ids:[],source_group_id:this.source_group_id});this.schematic_group_id=i.schematic_group_id;for(let r of this.children)r.schematic_component_id&&e.schematic_component.update(r.schematic_component_id,{schematic_group_id:i.schematic_group_id})}_getSchematicLayoutMode(){let e=this._parsedProps;if(e.schLayout?.layoutMode==="none"||e.schLayout?.layoutMode==="relative")return"relative";if(e.schLayout?.matchAdapt)return"match-adapt";if(e.schLayout?.flex)return"flex";if(e.schLayout?.grid)return"grid";if(e.schMatchAdapt)return"match-adapt";if(e.schFlex)return"flex";if(e.schGrid)return"grid";if(e.matchAdapt)return"match-adapt";if(e.flex)return"flex";if(e.grid)return"grid";if(e.relative||e.schRelative)return"relative";let t=this.children.some(r=>{let s=r._parsedProps;return s?.schX!==void 0||s?.schY!==void 0}),i=(e.manualEdits?.schematic_placements?.length??0)>0;return!t&&!i?"match-adapt":"relative"}doInitialSchematicLayout(){let e=this._getSchematicLayoutMode();e==="match-adapt"&&this._doInitialSchematicLayoutMatchpack(),e==="grid"&&this._doInitialSchematicLayoutGrid(),e==="flex"&&this._doInitialSchematicLayoutFlex(),this._insertSchematicBorder()}_doInitialSchematicLayoutMatchAdapt(){qOt(this)}_doInitialSchematicLayoutMatchpack(){KOt(this)}_doInitialSchematicLayoutGrid(){QOt(this)}_doInitialSchematicLayoutFlex(){tLt(this)}_getPcbLayoutMode(){let e=this._parsedProps;if(e.pcbRelative)return"none";if(e.pcbLayout?.matchAdapt)return"match-adapt";if(e.pcbLayout?.flex)return"flex";if(e.pcbLayout?.grid)return"grid";if(e.pcbLayout?.pack)return"pack";if(e.pcbFlex)return"flex";if(e.pcbGrid)return"grid";if(e.pcbPack||e.pack)return"pack";if(e.matchAdapt)return"match-adapt";if(e.flex)return"flex";if(e.grid)return"grid";let t=e.pcbX!==void 0||e.pcbY!==void 0,i=(e.manualEdits?.pcb_placements?.length??0)>0,r=this.children.reduce((s,o)=>{if(!o.pcb_component_id&&!o.pcb_group_id)return s;let a=o._parsedProps,c=a?.pcbX!==void 0||a?.pcbY!==void 0;return s+(c?0:1)},0);return!t&&!i&&r>1?"pack":"none"}doInitialPcbLayout(){let e=this._getPcbLayoutMode();e==="grid"?this._doInitialPcbLayoutGrid():e==="pack"?this._doInitialPcbLayoutPack():e==="flex"&&this._doInitialPcbLayoutFlex()}_doInitialPcbLayoutGrid(){eLt(this)}_doInitialPcbLayoutPack(){yLt(this)}_doInitialPcbLayoutFlex(){gLt(this)}_insertSchematicBorder(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,t=this._parsedProps;if(!t.border)return;let i=typeof t.schWidth=="number"?t.schWidth:void 0,r=typeof t.schHeight=="number"?t.schHeight:void 0,s=typeof t.schPadding=="number"?t.schPadding:0,o=typeof t.schPaddingLeft=="number"?t.schPaddingLeft:s,a=typeof t.schPaddingRight=="number"?t.schPaddingRight:s,c=typeof t.schPaddingTop=="number"?t.schPaddingTop:s,l=typeof t.schPaddingBottom=="number"?t.schPaddingBottom:s,u=this.schematic_group_id?e.schematic_group.get(this.schematic_group_id):null;if(u&&(i===void 0&&typeof u.width=="number"&&(i=u.width),r===void 0&&typeof u.height=="number"&&(r=u.height)),i===void 0||r===void 0)return;let p=u?.center??this._getGlobalSchematicPositionBeforeLayout(),f=p.x-i/2-o,y=p.y-r/2-l,g=i+o+a,x=r+c+l;e.schematic_box.insert({width:g,height:x,x:f,y,is_dashed:t.border?.dashed??!1})}_determineSideFromPosition(e,t){if(!e.center||!t.center)return"left";let i=e.center.x-t.center.x,r=e.center.y-t.center.y;return Math.abs(i)>Math.abs(r)?i>0?"right":"left":r>0?"bottom":"top"}_calculateSchematicBounds(e){if(e.length===0)return{minX:0,maxX:0,minY:0,maxY:0};let t=1/0,i=-1/0,r=1/0,s=-1/0;for(let a of e)t=Math.min(t,a.centerX),i=Math.max(i,a.centerX),r=Math.min(r,a.centerY),s=Math.max(s,a.centerY);let o=2;return{minX:t-o,maxX:i+o,minY:r-o,maxY:s+o}}_getAutorouterConfig(){let e=this._parsedProps.autorouter||this.getInheritedProperty("autorouter");return pLt(e)}_isLaserPrefabAutorouter(e=this._getAutorouterConfig()){let t=this.props.autorouter,i=r=>r?.replace(/-/g,"_")??r;return e.preset==="laser_prefab"?!0:typeof t=="string"?i(t)==="laser_prefab":typeof t=="object"&&t?i(t.preset)==="laser_prefab":!1}_getSubcircuitLayerCount(){let e=this.getInheritedProperty("layers");return typeof e=="number"?e:2}_shouldUseTraceByTraceRouting(){return this._getAutorouterConfig().groupMode==="sequential-trace"}doInitialPcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db:e}=this.root;if(this.isSubcircuit){let t=new Map;for(let i of this.children)if(!i.isSubcircuit&&i._parsedProps.name){let r=t.get(i._parsedProps.name)||[];r.push(i),t.set(i._parsedProps.name,r)}for(let[i,r]of t.entries())r.length>1&&e.pcb_trace_error.insert({error_type:"pcb_trace_error",message:`Multiple components found with name "${i}" in subcircuit "${this.name||"unnamed"}". Component names must be unique within a subcircuit.`,source_trace_id:"",pcb_trace_id:"",pcb_component_ids:r.map(s=>s.pcb_component_id).filter(Boolean),pcb_port_ids:[]})}}doInitialSchematicReplaceNetLabelsWithSymbols(){if(this.root?.schematicDisabled||!this.isSubcircuit)return;let{db:e}=this.root,t=e;for(let i of t.schematic_net_label.list()){let r=t.source_net.get(i.source_net_id),s=i.text||r?.name||"";if(i.anchor_side==="top"&&/^gnd/i.test(s)){t.schematic_net_label.update(i.schematic_net_label_id,{symbol_name:"rail_down"});continue}i.anchor_side==="bottom"&&/^v/i.test(s)&&t.schematic_net_label.update(i.schematic_net_label_id,{symbol_name:"rail_up"})}}doInitialSimulationSpiceEngineRender(){FLt(this)}doInitialPcbComponentAnchorAlignment(){zLt(this)}updatePcbComponentAnchorAlignment(){this.doInitialPcbComponentAnchorAlignment()}_getMinimumFlexContainerSize(){return super._getMinimumFlexContainerSize()}_repositionOnPcb(e){return super._repositionOnPcb(e)}},DLt=.01,Pet=(n,e,t)=>{let i=n/2,r=e/2,s=Math.min(t,i,r);if(s<DLt)return[{x:-i,y:-r},{x:i,y:-r},{x:i,y:r},{x:-i,y:r}];let a=Math.max(1,Math.ceil(Math.PI/2*s/.1)),c=Math.PI/2/a,l=[];l.push({x:-i+s,y:-r}),l.push({x:i-s,y:-r});for(let u=1;u<=a;u++){let p=-Math.PI/2+u*c;l.push({x:i-s+s*Math.cos(p),y:-r+s+s*Math.sin(p)})}l.push({x:i,y:r-s});for(let u=1;u<=a;u++){let p=0+u*c;l.push({x:i-s+s*Math.cos(p),y:r-s+s*Math.sin(p)})}l.push({x:-i+s,y:r});for(let u=1;u<=a;u++){let p=Math.PI/2+u*c;l.push({x:-i+s+s*Math.cos(p),y:r-s+s*Math.sin(p)})}l.push({x:-i,y:-r+s});for(let u=1;u<=a;u++){let p=Math.PI+u*c;l.push({x:-i+s+s*Math.cos(p),y:-r+s+s*Math.sin(p)})}return l},nnt=class extends _l{constructor(){super(...arguments);d(this,"pcb_board_id",null);d(this,"source_board_id",null);d(this,"_drcChecksComplete",!1);d(this,"_connectedSchematicPortPairs",new Set)}get isSubcircuit(){return!0}get isGroup(){return!0}get config(){return{componentName:"Board",zodProps:s4}}get boardThickness(){let{_parsedProps:e}=this;return e.thickness??1.4}get allLayers(){return(this._parsedProps.layers??2)===4?["top","bottom","inner1","inner2"]:["top","bottom"]}_getSubcircuitLayerCount(){return this._parsedProps.layers??2}doInitialPcbBoardAutoSize(){if(this.root?.pcbDisabled||!this.pcb_board_id)return;let{db:e}=this.root,{_parsedProps:t}=this;if(t.width&&t.height||t.outline)return;let i=1/0,r=1/0,s=-1/0,o=-1/0,a=Wet(e,this.subcircuit_id),c=new Set([this.subcircuit_id,...a]),l=e.pcb_component.list().filter(C=>C.subcircuit_id&&c.has(C.subcircuit_id)),u=e.pcb_group.list().filter(C=>C.subcircuit_id&&c.has(C.subcircuit_id)),p=!1,f=(C,E,N)=>{E===0||N===0||(p=!0,i=Math.min(i,C.x-E/2),r=Math.min(r,C.y-N/2),s=Math.max(s,C.x+E/2),o=Math.max(o,C.y+N/2))};for(let C of l)f(C.center,C.width,C.height);for(let C of u){let E=C.width??0,N=C.height??0;if(C.outline&&C.outline.length>0){let I=Ro(C.outline);I&&(E=I.maxX-I.minX,N=I.maxY-I.minY)}f(C.center,E,N)}if(t.boardAnchorPosition){let{x:C,y:E}=t.boardAnchorPosition;i=Math.min(i,C),r=Math.min(r,E),s=Math.max(s,C),o=Math.max(o,E)}let y=2,g=p?s-i+y*2:0,x=p?o-r+y*2:0,v={x:p?(i+s)/2+(t.outlineOffsetX??0):t.outlineOffsetX??0,y:p?(r+o)/2+(t.outlineOffsetY??0):t.outlineOffsetY??0},S=t.width??g,P=t.height??x,T=t.outline;!T&&t.borderRadius!=null&&S>0&&P>0&&(T=Pet(S,P,t.borderRadius));let k={width:S,height:P,center:v};T&&(k.outline=T.map(C=>({x:C.x+(t.outlineOffsetX??0),y:C.y+(t.outlineOffsetY??0)}))),e.pcb_board.update(this.pcb_board_id,k)}updatePcbBoardAutoSize(){this.doInitialPcbBoardAutoSize()}_addBoardInformationToSilkscreen(){let e=this.root?.platform;if(!e?.printBoardInformationToSilkscreen)return;let t=this.root.db.pcb_board.get(this.pcb_board_id);if(!t)return;let i=[];if(e.projectName&&i.push(e.projectName),e.version&&i.push(`v${e.version}`),e.url&&i.push(e.url),i.length===0)return;let r=i.join(`
251
- `),a={x:t.center.x+t.width/2-.25,y:t.center.y-t.height/2+1};this.root.db.pcb_silkscreen_text.insert({pcb_component_id:this.pcb_board_id,layer:"top",font:"tscircuit2024",font_size:.45,text:r,ccw_rotation:0,anchor_alignment:"bottom_right",anchor_position:a})}doInitialSourceRender(){super.doInitialSourceRender();let{db:e}=this.root,t=e.source_board.insert({source_group_id:this.source_group_id,title:this.props.title||this.props.name});this.source_board_id=t.source_board_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=t.width??0,r=t.height??0,s={x:(t.pcbX??0)+(t.outlineOffsetX??0),y:(t.pcbY??0)+(t.outlineOffsetY??0)},{boardAnchorPosition:o,boardAnchorAlignment:a}=t;if(o&&(s=YOt({boardAnchorPosition:o,boardAnchorAlignment:a??"center",width:i,height:r})),t.outline){let u=t.outline.map(v=>v.x),p=t.outline.map(v=>v.y),f=Math.min(...u),y=Math.max(...u),g=Math.min(...p),x=Math.max(...p);i=y-f,r=x-g,s={x:(f+y)/2+(t.outlineOffsetX??0),y:(g+x)/2+(t.outlineOffsetY??0)}}let c=t.outline;!c&&t.borderRadius!=null&&i>0&&r>0&&(c=Pet(i,r,t.borderRadius));let l=e.pcb_board.insert({center:s,thickness:this.boardThickness,num_layers:this.allLayers.length,width:i,height:r,outline:c?.map(u=>({x:u.x+(t.outlineOffsetX??0),y:u.y+(t.outlineOffsetY??0)})),material:t.material});this.pcb_board_id=l.pcb_board_id,this._addBoardInformationToSilkscreen()}removePcbComponentRender(){let{db:e}=this.root;this.pcb_board_id&&(e.pcb_board.delete(this.pcb_board_id),this.pcb_board_id=null)}_computePcbGlobalTransformBeforeLayout(){return Qi()}doInitialPcbDesignRuleChecks(){this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled")||super.doInitialPcbDesignRuleChecks()}updatePcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db:e}=this.root;if(!this._areChildSubcircuitsRouted()||this._drcChecksComplete)return;this._drcChecksComplete=!0;let t=MQ(e.toArray());for(let l of t)e.pcb_trace_error.insert(l);let i=EQ(e.toArray());for(let l of i)e.pcb_port_not_connected_error.insert(l);let r=NQ(e.toArray());for(let l of r)e.pcb_component_outside_board_error.insert(l);let s=OQ(e.toArray());for(let l of s)e.pcb_trace_error.insert(l);let o=RQ(e.toArray());for(let l of o)e.pcb_via_clearance_error.insert(l);let a=AQ(e.toArray());for(let l of a)e.pcb_via_clearance_error.insert(l);let c=LQ(e.toArray());for(let l of c)e.pcb_footprint_overlap_error.insert(l)}_emitRenderLifecycleEvent(e,t){super._emitRenderLifecycleEvent(e,t),t==="start"&&this.root?.emit("board:renderPhaseStarted",{renderId:this._renderId,phase:e})}},int=class extends _l{get config(){return{componentName:"Panel",zodProps:yH}}get isGroup(){return!0}add(n){if(n.lowercaseComponentName!=="board")throw new Error("<panel> can only contain <board> elements");super.add(n)}runRenderCycle(){if(!this.children.some(n=>n.componentName==="Board"))throw new Error("<panel> must contain at least one <board>");super.runRenderCycle()}},$Lt=new Proxy({},{get:(n,e)=>e}),Va=$Lt,tP="rgba(132, 0, 0)",eP=.12,d9=class extends Gn{constructor(){super(...arguments);d(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Capacitor",schematicSymbolName:this.props.polarized?"capacitor_polarized":this.props.symbolName??"capacitor",zodProps:EH,sourceFtype:Va.simple_capacitor}}initPorts(){typeof this.props.footprint=="string"?super.initPorts({additionalAliases:{pin1:["anode","pos"],pin2:["cathode","neg"]}}):super.initPorts()}_getSchematicSymbolDisplayValue(){let e=this.props.capacitance,t=typeof e=="string"?e:`${gi(this._parsedProps.capacitance)}F`;return this._parsedProps.schShowRatings&&this._parsedProps.maxVoltageRating?`${t}/${gi(this._parsedProps.maxVoltageRating)}V`:t}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.decouplingFor,this.props.decouplingTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.decouplingFor&&this.props.decouplingTo&&(this.add(new oo({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.decouplingFor})),this.add(new oo({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.decouplingTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_capacitor",name:this.name,manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,capacitance:t.capacitance,max_voltage_rating:t.maxVoltageRating,max_decoupling_trace_length:t.maxDecouplingTraceLength,display_capacitance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!t.polarized});this.source_component_id=i.source_component_id}},Y1=class extends Gn{constructor(e){super(e);d(this,"schematicBoxDimensions",null)}get config(){return{componentName:"Chip",zodProps:t_,shouldRenderAsSchematicBox:!0}}initPorts(e={}){super.initPorts(e);let{_parsedProps:t}=this;if(t.externallyConnectedPins){let i=new Set;for(let[r,s]of t.externallyConnectedPins)i.add(r),i.add(s);for(let r of i)if(!this.children.find(o=>o instanceof Vi&&o.isMatchingAnyOf([r]))){let o=r.match(/^pin(\d+)$/);if(o){let a=parseInt(o[1]);this.add(new Vi({pinNumber:a,aliases:[r]}))}else this.add(new Vi({name:r,aliases:[r]}))}}}doInitialSchematicComponentRender(){let{_parsedProps:e}=this;e?.noSchematicRepresentation!==!0&&super.doInitialSchematicComponentRender()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=t.layer??"top";if(i!=="top"&&i!=="bottom"){let s=this.getSubcircuit(),o=Am.parse({type:"pcb_component_invalid_layer_error",message:`Component cannot be placed on layer '${i}'. Components can only be placed on 'top' or 'bottom' layers.`,source_component_id:this.source_component_id,layer:i,subcircuit_id:s.subcircuit_id??void 0});e.pcb_component_invalid_layer_error.insert(o)}let r=e.pcb_component.insert({center:{x:t.pcbX??0,y:t.pcbY??0},width:2,height:3,layer:i==="top"||i==="bottom"?i:"top",rotation:t.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:t.doNotPlace??!1,obstructs_within_bounds:t.obstructsWithinBounds??!0});this.pcb_component_id=r.pcb_component_id}doInitialCreateTracesFromProps(){let{_parsedProps:e}=this;if(e.externallyConnectedPins)for(let[t,i]of e.externallyConnectedPins)this.add(new oo({from:`${this.getSubcircuitSelector()} > port.${t}`,to:`${this.getSubcircuitSelector()} > port.${i}`}));this._createTracesFromConnectionsProp()}doInitialSimulationRender(){let{db:e}=this.root,{pinAttributes:t}=this.props;if(!t)return;let i=null,r=null,s,o=this.selectAll("port");for(let p of o)for(let f of p.getNameAndAliases())if(t[f]){let y=t[f];y.providesPower&&(i=p,s=y.providesVoltage),y.providesGround&&(r=p)}if(!i||!r||s===void 0)return;let a=e.source_port.get(i.source_port_id);if(!a?.subcircuit_connectivity_map_key)return;let c=e.source_port.get(r.source_port_id);if(!c?.subcircuit_connectivity_map_key)return;let l=e.source_net.getWhere({subcircuit_connectivity_map_key:a.subcircuit_connectivity_map_key}),u=e.source_net.getWhere({subcircuit_connectivity_map_key:c.subcircuit_connectivity_map_key});!l||!u||e.simulation_voltage_source.insert({type:"simulation_voltage_source",positive_source_port_id:i.source_port_id,positive_source_net_id:l.source_net_id,negative_source_port_id:r.source_port_id,negative_source_net_id:u.source_net_id,voltage:s})}},rnt=class extends Y1{constructor(n){super(n)}get config(){return{...super.config,componentName:"Pinout",zodProps:gH}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=n.source_component.insert({ftype:"simple_pinout",name:this.name,manufacturer_part_number:e.manufacturerPartNumber,supplier_part_numbers:e.supplierPartNumbers});this.source_component_id=t.source_component_id}},f9=class extends Gn{constructor(){super(...arguments);d(this,"pos",this.portMap.pin1);d(this,"anode",this.portMap.pin1);d(this,"neg",this.portMap.pin2);d(this,"cathode",this.portMap.pin2)}get config(){let e={schottky:"schottky_diode",avalanche:"avalanche_diode",zener:"zener_diode",photodiode:"photodiode"},t=this.props.schottky?"schottky":this.props.avalanche?"avalanche":this.props.zener?"zener":this.props.photo?"photodiode":null;return{schematicSymbolName:t?e[t]:this.props.symbolName??"diode",componentName:"Diode",zodProps:UH,sourceFtype:"simple_diode"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_diode",name:this.name,manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},snt=class extends Gn{get config(){return{componentName:"fuse",schematicSymbolName:this.props.symbolName??"fuse",zodProps:bH,sourceFtype:Va.simple_fuse}}_getSchematicSymbolDisplayValue(){let n=this._parsedProps.currentRating,e=this._parsedProps.voltageRating,t=typeof n=="string"?parseFloat(n):n,i=typeof e=="string"?parseFloat(e):e;return`${gi(t)}A / ${gi(i)}V`}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=typeof e.currentRating=="string"?parseFloat(e.currentRating):e.currentRating,i=typeof e.voltageRating=="string"?parseFloat(e.voltageRating):e.voltageRating,r=n.source_component.insert({name:this.name,ftype:Va.simple_fuse,current_rating_amps:t,voltage_rating_volts:i,display_current_rating:`${gi(t)}A`,display_voltage_rating:`${gi(i)}V`});this.source_component_id=r.source_component_id}},ont=class extends Gn{constructor(){super(...arguments);d(this,"schematicDimensions",null)}get config(){return{schematicSymbolName:void 0,componentName:"Jumper",zodProps:o4,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let e=super._getSchematicPortArrangement();if(e&&Object.keys(e).length>0)return e;let t=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length),i=this._parsedProps.schDirection??"right";return{leftSize:i==="left"?t:0,rightSize:i==="right"?t:0}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=e.pcb_component.insert({center:{x:t.pcbX??0,y:t.pcbY??0},width:2,height:3,layer:t.layer??"top",rotation:t.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:t.doNotPlace??!1,obstructs_within_bounds:t.obstructsWithinBounds??!0});this.pcb_component_id=i.pcb_component_id}doInitialPcbTraceRender(){let{db:e}=this.root,t=e.pcb_port.list({pcb_component_id:this.pcb_component_id}),i={};for(let o=0;o<t.length;o++){let a=t[o],c=e.source_port.get(a.source_port_id),l="";if(typeof c?.pin_number=="number")l=c.pin_number.toString();else if(Array.isArray(c?.port_hints)){let u=c.port_hints.find(p=>/^(pin)?\d+$/.test(p));u&&(/^pin\d+$/.test(u)?l=u.replace(/^pin/,""):l=u)}i[l]=a.pcb_port_id}let r=e.pcb_trace.list({pcb_component_id:this.pcb_component_id}),s=o=>{if(o&&typeof o=="string"&&o.startsWith("{PIN")){let a=o.replace("{PIN","").replace("}","");return i[a]||o}return o};for(let o of r)if(o.route)for(let a of o.route)a.route_type==="wire"&&(a.start_pcb_port_id=s(a.start_pcb_port_id),a.end_pcb_port_id=s(a.end_pcb_port_id))}},ant=class extends Gn{constructor(){super(...arguments);d(this,"schematicDimensions",null)}_getPinNumberFromBridgedPinName(e){return this.selectOne(`port.${e}`,{type:"port"})?._parsedProps.pinNumber??null}get defaultInternallyConnectedPinNames(){if(this._parsedProps.bridged){let e=this.children.filter(t=>t.componentName==="Port").map(t=>t.name);return e.length>0?[e]:[]}return this._parsedProps.bridgedPins??[]}get config(){let e=this._parsedProps??this.props,t=e.pinCount;if(e.pinCount==null&&!e.footprint&&(t=2),e.pinCount==null){let s=(e.bridgedPins??[]).flat().map(l=>this._getPinNumberFromBridgedPinName(l)).filter(l=>l!==null),o=s.length>0?Math.max(...s):0,a=e.pinLabels?Object.keys(e.pinLabels).length:0,c=Math.max(o,a);(c===2||c===3)&&(t=c),t==null&&e.footprint&&[2,3].includes(this.getPortsFromFootprint().length)&&(t=this.getPortsFromFootprint().length)}let i="";t?i+=`solderjumper${t}`:i="solderjumper";let r=[];return Array.isArray(e.bridgedPins)&&e.bridgedPins.length>0?r=Array.from(new Set(e.bridgedPins.flat().map(s=>this._getPinNumberFromBridgedPinName(s)).filter(s=>s!==null))).sort((s,o)=>s-o):e.bridged&&t&&(r=Array.from({length:t},(s,o)=>o+1)),r.length>0&&(i+=`_bridged${r.join("")}`),{schematicSymbolName:e.symbolName??i,componentName:"SolderJumper",zodProps:xH,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let e=super._getSchematicPortArrangement();if(e&&Object.keys(e).length>0)return e;let t=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length);t==null&&!this._parsedProps.footprint&&(t=2);let i=this._parsedProps.schDirection??"right";return{leftSize:i==="left"?t:0,rightSize:i==="right"?t:0}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=e.pcb_component.insert({center:{x:t.pcbX??0,y:t.pcbY??0},width:2,height:3,layer:t.layer??"top",rotation:t.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:t.doNotPlace??!1,obstructs_within_bounds:t.obstructsWithinBounds??!0});this.pcb_component_id=i.pcb_component_id}doInitialPcbTraceRender(){let{db:e}=this.root,t=e.pcb_port.list({pcb_component_id:this.pcb_component_id}),i={};for(let o=0;o<t.length;o++){let a=t[o],c=e.source_port.get(a.source_port_id),l="";if(typeof c?.pin_number=="number")l=c.pin_number.toString();else if(Array.isArray(c?.port_hints)){let u=c.port_hints.find(p=>/^(pin)?\d+$/.test(p));u&&(/^pin\d+$/.test(u)?l=u.replace(/^pin/,""):l=u)}i[l]=a.pcb_port_id}let r=e.pcb_trace.list({pcb_component_id:this.pcb_component_id}),s=o=>{if(o&&typeof o=="string"&&o.startsWith("{PIN")){let a=o.replace("{PIN","").replace("}","");return i[a]||o}return o};for(let o of r)if(o.route)for(let a of o.route)a.route_type==="wire"&&(a.start_pcb_port_id=s(a.start_pcb_port_id),a.end_pcb_port_id=s(a.end_pcb_port_id))}},cnt=class extends Gn{constructor(){super(...arguments);d(this,"pos",this.portMap.pin1);d(this,"anode",this.portMap.pin1);d(this,"neg",this.portMap.pin2);d(this,"cathode",this.portMap.pin2)}get config(){let e={laser:"laser_diode"},t=this.props.laser?"laser":null;return{schematicSymbolName:t?e[t]:this.props.symbolName??"led",componentName:"Led",zodProps:GH,sourceFtype:"simple_led"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return this._parsedProps.schDisplayValue||this._parsedProps.color||void 0}getFootprinterString(){let e=super.getFootprinterString();return e&&this.props.color?`${e}_color(${this.props.color})`:e}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_led",name:this.name,wave_length:t.wavelength,color:t.color,symbol_display_value:this._getSchematicSymbolDisplayValue(),manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},lnt=class extends Gn{constructor(){super(...arguments);d(this,"pos",this.portMap.pin1);d(this,"positive",this.portMap.pin1);d(this,"neg",this.portMap.pin2);d(this,"negative",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"power_factor_meter_horz",componentName:"PowerSource",zodProps:oW,sourceFtype:"simple_power_source"}}initPorts(){this.add(new Vi({name:"pin1",pinNumber:1,aliases:["positive","pos"]})),this.add(new Vi({name:"pin2",pinNumber:2,aliases:["negative","neg"]}))}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_power_source",name:this.name,voltage:t.voltage,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},jLt=Kn.extend({voltage:Si.optional(),frequency:pr.optional(),peakToPeakVoltage:Si.optional(),waveShape:h.enum(["sinewave","square","triangle","sawtooth"]).optional(),phase:He.optional(),dutyCycle:h.number().optional()}),unt=class extends Gn{constructor(){super(...arguments);d(this,"terminal1",this.portMap.terminal1);d(this,"terminal2",this.portMap.terminal2)}get config(){return{componentName:"VoltageSource",schematicSymbolName:this.props.waveShape==="square"?"square_wave":"ac_voltmeter",zodProps:jLt,sourceFtype:"simple_voltage_source"}}runRenderPhaseForChildren(e){if(!e.startsWith("Pcb"))for(let t of this.children)t.runRenderPhaseForChildren(e),t.runRenderPhase(e)}doInitialPcbComponentRender(){}initPorts(){super.initPorts({additionalAliases:{pin1:["terminal1"],pin2:["terminal2"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_voltage_source",name:this.name,voltage:t.voltage,frequency:t.frequency,peak_to_peak_voltage:t.peakToPeakVoltage,wave_shape:t.waveShape,phase:t.phase,duty_cycle:t.dutyCycle,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialSimulationRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=this.portMap.terminal1,r=this.portMap.terminal2;e.simulation_voltage_source.insert({type:"simulation_voltage_source",is_dc_source:!1,terminal1_source_port_id:i.source_port_id,terminal2_source_port_id:r.source_port_id,voltage:t.voltage,frequency:t.frequency,peak_to_peak_voltage:t.peakToPeakVoltage,wave_shape:t.waveShape,phase:t.phase,duty_cycle:t.dutyCycle})}},m9=class extends Gn{constructor(){super(...arguments);d(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Resistor",schematicSymbolName:this.props.symbolName??"boxresistor",zodProps:wH,sourceFtype:"simple_resistor"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return`${gi(this._parsedProps.resistance)}\u03A9`}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.pullupFor,this.props.pullupTo,this.props.pulldownFor,this.props.pulldownTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.pullupFor&&this.props.pullupTo&&(this.add(new oo({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pullupFor})),this.add(new oo({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pullupTo}))),this.props.pulldownFor&&this.props.pulldownTo&&(this.add(new oo({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pulldownFor})),this.add(new oo({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pulldownTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_resistor",name:this.name,manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,resistance:t.resistance,display_resistance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}},BLt=["leftedge","rightedge","topedge","bottomedge","center"],pnt=class extends Te{get config(){return{componentName:"Constraint",zodProps:CH}}constructor(n){if(super(n),("xdist"in n||"ydist"in n)&&!("edgeToEdge"in n)&&!("centerToCenter"in n))throw new Error(`edgeToEdge, centerToCenter must be set for xDist or yDist for ${this}`);if("for"in n&&n.for.length<2)throw new Error(`"for" must have at least two selectors for ${this}`)}_getAllReferencedComponents(){let n=[],e=this.getPrimitiveContainer();function t(i){let r=i.split(" ").pop(),s=BLt.includes(r)?r:void 0,o=s?i.replace(` ${s}`,""):i,a=e.selectOne(o,{pcbPrimitive:!0});a&&n.push({selector:i,component:a,componentSelector:o,edge:s})}for(let i of["left","right","top","bottom"])i in this._parsedProps&&t(this._parsedProps[i]);if("for"in this._parsedProps)for(let i of this._parsedProps.for)t(i);return{componentsWithSelectors:n}}},hnt=class extends Te{constructor(){super(...arguments);d(this,"fabrication_note_rect_id",null)}get config(){return{componentName:"FabricationNoteRect",zodProps:ZH}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(t.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for FabricationNoteRect. Must be "top" or "bottom".`);let s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,o=this.getSubcircuit(),a=t.hasStroke??(t.strokeWidth!==void 0&&t.strokeWidth!==null),c=e.pcb_fabrication_note_rect.insert({pcb_component_id:s,layer:r,color:t.color,center:{x:t.pcbX??0,y:t.pcbY??0},width:t.width,height:t.height,stroke_width:t.strokeWidth??1,is_filled:t.isFilled??!1,has_stroke:a,is_stroke_dashed:t.isStrokeDashed??!1,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,corner_radius:t.cornerRadius??void 0});this.fabrication_note_rect_id=c.pcb_fabrication_note_rect_id}getPcbSize(){let{_parsedProps:e}=this;return{width:e.width,height:e.height}}},dnt=class extends Te{constructor(){super(...arguments);d(this,"fabrication_note_path_id",null)}get config(){return{componentName:"FabricationNotePath",zodProps:KH}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,t=this.getSubcircuit(),{_parsedProps:i}=this,r=i.layer??"top";if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenPath. Must be "top" or "bottom".`);let s=this._computePcbGlobalTransformBeforeLayout(),o=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=e.pcb_fabrication_note_path.insert({pcb_component_id:o,layer:r,color:i.color,route:i.route.map(c=>{let l=ze(s,{x:c.x,y:c.y});return{...c,x:l.x,y:l.y}}),stroke_width:i.strokeWidth??.1,subcircuit_id:t?.subcircuit_id??void 0});this.fabrication_note_path_id=a.pcb_fabrication_note_path_id}},fnt=class extends Te{get config(){return{componentName:"FabricationNoteText",zodProps:qH}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:n}=this.root,{_parsedProps:e}=this,t=this.getPrimitiveContainer(),i=this.getSubcircuit();n.pcb_fabrication_note_text.insert({anchor_alignment:e.anchorAlignment,anchor_position:{x:e.pcbX??0,y:e.pcbY??0},font:e.font??"tscircuit2024",font_size:e.fontSize??1,layer:"top",color:e.color,text:e.text??"",pcb_component_id:t.pcb_component_id,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}},mnt=class extends Te{constructor(){super(...arguments);d(this,"fabrication_note_dimension_id",null);d(this,"isPcbPrimitive",!0)}get config(){return{componentName:"FabricationNoteDimension",zodProps:JH}}_resolvePoint(e,t){if(typeof e=="string"){let s=this.getSubcircuit().selectOne(e);return s?s._getGlobalPcbPositionBeforeLayout():(this.renderError(`FabricationNoteDimension could not find selector "${e}"`),ze(t,{x:0,y:0}))}let i=typeof e.x=="string"?parseFloat(e.x):e.x,r=typeof e.y=="string"?parseFloat(e.y):e.y;return ze(t,{x:i,y:r})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=this._resolvePoint(t.from,i),s=this._resolvePoint(t.to,i),o=this.getSubcircuit(),a=this.getGroup(),{maybeFlipLayer:c}=this._getPcbPrimitiveFlippedHelpers(),l=c(t.layer??"top");if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for FabricationNoteDimension. Must be "top" or "bottom".`);let u=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,p=t.text??this._formatDistanceText({from:r,to:s,units:t.units??"mm"}),f=e.pcb_fabrication_note_dimension.insert({pcb_component_id:u,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:a?.pcb_group_id??void 0,layer:l,from:r,to:s,text:p,offset:t.offset,font:t.font??"tscircuit2024",font_size:t.fontSize??1,color:t.color,arrow_size:t.arrowSize??1});this.fabrication_note_dimension_id=f.pcb_fabrication_note_dimension_id}getPcbSize(){let e=this._computePcbGlobalTransformBeforeLayout(),t=this._resolvePoint(this._parsedProps.from,e),i=this._resolvePoint(this._parsedProps.to,e);return{width:Math.abs(i.x-t.x),height:Math.abs(i.y-t.y)}}_formatDistanceText({from:e,to:t,units:i}){let r=t.x-e.x,s=t.y-e.y,o=Math.sqrt(r*r+s*s),a=i==="in"?o/25.4:o,c=Math.round(a);if(Math.abs(a-c)<1e-9)return`${c}${i}`;let u=i==="in"?3:2;return`${i==="in"?Number(a.toFixed(u)).toString():a.toFixed(u)}${i}`}},_nt=class extends Te{constructor(){super(...arguments);d(this,"pcb_note_line_id",null);d(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteLine",zodProps:TW}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this.getSubcircuit(),r=this.getGroup(),s=this._computePcbGlobalTransformBeforeLayout(),o=ze(s,{x:t.x1,y:t.y1}),a=ze(s,{x:t.x2,y:t.y2}),c=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,l=e.pcb_note_line.insert({pcb_component_id:c,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r?.pcb_group_id??void 0,x1:o.x,y1:o.y,x2:a.x,y2:a.y,stroke_width:t.strokeWidth??.1,color:t.color,is_dashed:t.isDashed});this.pcb_note_line_id=l.pcb_note_line_id}getPcbSize(){let{_parsedProps:e}=this;return{width:Math.abs(e.x2-e.x1),height:Math.abs(e.y2-e.y1)}}},ynt=class extends Te{constructor(){super(...arguments);d(this,"pcb_note_rect_id",null);d(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteRect",zodProps:PW}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=ze(i,{x:0,y:0}),s=this.getSubcircuit(),o=this.getGroup(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,c=e.pcb_note_rect.insert({pcb_component_id:a,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:o?.pcb_group_id??void 0,center:r,width:t.width,height:t.height,stroke_width:t.strokeWidth??.1,is_filled:t.isFilled??!1,has_stroke:t.hasStroke??!0,is_stroke_dashed:t.isStrokeDashed??!1,color:t.color,corner_radius:t.cornerRadius??void 0});this.pcb_note_rect_id=c.pcb_note_rect_id}getPcbSize(){let{_parsedProps:e}=this,t=typeof e.width=="string"?parseFloat(e.width):e.width,i=typeof e.height=="string"?parseFloat(e.height):e.height;return{width:t,height:i}}},gnt=class extends Te{constructor(){super(...arguments);d(this,"pcb_note_text_id",null);d(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteText",zodProps:SW}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=ze(i,{x:0,y:0}),s=this.getSubcircuit(),o=this.getGroup(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,c=e.pcb_note_text.insert({pcb_component_id:a,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:o?.pcb_group_id??void 0,font:t.font??"tscircuit2024",font_size:t.fontSize??1,text:t.text,anchor_position:r,anchor_alignment:t.anchorAlignment??"center",color:t.color});this.pcb_note_text_id=c.pcb_note_text_id}getPcbSize(){let{_parsedProps:e}=this,t=typeof e.fontSize=="string"?parseFloat(e.fontSize):e.fontSize??1,i=t*.6;return{width:e.text.length*i,height:t}}},xnt=class extends Te{constructor(){super(...arguments);d(this,"pcb_note_path_id",null);d(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNotePath",zodProps:kW}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=this.getSubcircuit(),s=this.getGroup(),o=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,a=t.route.map(l=>{let{x:u,y:p,...f}=l,y=typeof u=="string"?parseFloat(u):u,g=typeof p=="string"?parseFloat(p):p,x=ze(i,{x:y,y:g});return{...f,x:x.x,y:x.y}}),c=e.pcb_note_path.insert({pcb_component_id:o,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:s?.pcb_group_id??void 0,route:a,stroke_width:t.strokeWidth??.1,color:t.color});this.pcb_note_path_id=c.pcb_note_path_id}getPcbSize(){let{_parsedProps:e}=this;if(e.route.length===0)return{width:0,height:0};let t=e.route.map(c=>typeof c.x=="string"?parseFloat(c.x):c.x),i=e.route.map(c=>typeof c.y=="string"?parseFloat(c.y):c.y),r=Math.min(...t),s=Math.max(...t),o=Math.min(...i),a=Math.max(...i);return{width:s-r,height:a-o}}},bnt=class extends Te{constructor(){super(...arguments);d(this,"pcb_note_dimension_id",null);d(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteDimension",zodProps:EW}}_resolvePoint(e,t){if(typeof e=="string"){let s=this.getSubcircuit().selectOne(`.${e}`);return s?s._getGlobalPcbPositionBeforeLayout():(this.renderError(`PcbNoteDimension could not find selector "${e}"`),ze(t,{x:0,y:0}))}let i=typeof e.x=="string"?parseFloat(e.x):e.x,r=typeof e.y=="string"?parseFloat(e.y):e.y;return ze(t,{x:i,y:r})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=this._resolvePoint(t.from,i),s=this._resolvePoint(t.to,i),o=this.getSubcircuit(),a=this.getGroup(),c=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,l=t.text??this._formatDistanceText({from:r,to:s,units:t.units??"mm"}),u=e.pcb_note_dimension.insert({pcb_component_id:c,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:a?.pcb_group_id??void 0,from:r,to:s,text:l,font:t.font??"tscircuit2024",font_size:t.fontSize??1,color:t.color,arrow_size:t.arrowSize??1});this.pcb_note_dimension_id=u.pcb_note_dimension_id}getPcbSize(){let e=this._computePcbGlobalTransformBeforeLayout(),t=this._resolvePoint(this._parsedProps.from,e),i=this._resolvePoint(this._parsedProps.to,e);return{width:Math.abs(i.x-t.x),height:Math.abs(i.y-t.y)}}_formatDistanceText({from:e,to:t,units:i}){let r=t.x-e.x,s=t.y-e.y,o=Math.sqrt(r*r+s*s),a=i==="in"?o/25.4:o,c=Math.round(a);if(Math.abs(a-c)<1e-9)return`${c}${i}`;let u=i==="in"?3:2;return`${i==="in"?Number(a.toFixed(u)).toString():a.toFixed(u)}${i}`}},X1=(n,e)=>{let{injectionDb:t,normalComponent:i}=e;if(!i)return;let r=G_({componentName:i.name,componentRotation:"0deg"},t.toArray().filter(s=>"pcb_component_id"in s&&s.pcb_component_id===n.pcb_component_id));i.addAll(r)};function YLt(n,e){let{injectionDb:t,subcircuit:i,groupsMap:r}=e,s=t.pcb_component.getWhere({source_component_id:n.source_component_id}),o=t.cad_component.getWhere({source_component_id:n.source_component_id}),a=new m9({name:n.name,resistance:n.resistance});s&&X1(s,{...e,normalComponent:a}),n.source_group_id&&r?.has(n.source_group_id)?r.get(n.source_group_id).add(a):i.add(a)}function XLt(n,e){let{injectionDb:t,subcircuit:i}=e;if(n.source_component_id!==null)return;let r=t.pcb_port.getWhere({source_port_id:n.source_port_id}),s=new Vi({name:n.name,pinNumber:n.pin_number});i.add(s),s.source_port_id=n.source_port_id;let o=i.root;if(o&&r){let{db:a}=o,c=a.pcb_port.insert({pcb_component_id:void 0,layers:r.layers,subcircuit_id:i.subcircuit_id??void 0,pcb_group_id:i.getGroup()?.pcb_group_id??void 0,x:r.x,y:r.y,source_port_id:n.source_port_id,is_board_pinout:!1});s.pcb_port_id=c.pcb_port_id}}function ULt(n,e){let{subcircuit:t,groupsMap:i}=e,r=new _l({name:n.name});return r.source_group_id=n.source_group_id,t.add(r),i&&i.set(n.source_group_id,r),r}var VLt=(n,e)=>{if(!n||n.length===0)return;let{injectionDb:t}=e,i=n.map(r=>r.map(s=>{let o=t.source_port.get(s);return o?o.pin_number!==void 0&&o.pin_number!==null?`pin${o.pin_number}`:o.name:null}).filter(s=>s!==null)).filter(r=>r.length>0);return i.length>0?i:void 0},GLt=(n,e)=>{let{injectionDb:t,subcircuit:i,groupsMap:r}=e,s=t.pcb_component.getWhere({source_component_id:n.source_component_id}),o=t.schematic_component.getWhere({source_component_id:n.source_component_id}),a=t.cad_component.getWhere({source_component_id:n.source_component_id}),c=VLt(n.internally_connected_source_port_ids,e),l=new Y1({name:n.name,manufacturerPartNumber:n.manufacturer_part_number,supplierPartNumbers:n.supplier_part_numbers??void 0,pinLabels:o?.port_labels??void 0,schWidth:o?.size?.width,schHeight:o?.size?.height,schPinSpacing:o?.pin_spacing,schX:o?.center?.x,schY:o?.center?.y,layer:s?.layer,pcbX:s?.center?.x,pcbY:s?.center?.y,pcbRotation:s?.rotation,doNotPlace:s?.do_not_place,obstructsWithinBounds:s?.obstructs_within_bounds,internallyConnectedPins:c}),u=a?.footprinter_string??"soic8";u&&(Object.assign(l.props,{footprint:u}),Object.assign(l._parsedProps,{footprint:u}),a||l._addChildrenFromStringFootprint?.()),s&&X1(s,{...e,normalComponent:l}),n.source_group_id&&r?.has(n.source_group_id)?r.get(n.source_group_id).add(l):i.add(l)};function HLt(n,e){let{injectionDb:t,subcircuit:i,groupsMap:r}=e,s=t.pcb_component.getWhere({source_component_id:n.source_component_id}),o=t.cad_component.getWhere({source_component_id:n.source_component_id}),a=new d9({name:n.name,capacitance:n.capacitance});s&&X1(s,{...e,normalComponent:a}),n.source_group_id&&r?.has(n.source_group_id)?r.get(n.source_group_id).add(a):i.add(a)}var _9=class extends Gn{constructor(){super(...arguments);d(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Inductor",schematicSymbolName:this.props.symbolName??"inductor",zodProps:XH,sourceFtype:Va.simple_inductor}}_getSchematicSymbolDisplayValue(){return`${gi(this._parsedProps.inductance)}H`}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({name:this.name,ftype:Va.simple_inductor,inductance:t.inductance,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}};function WLt(n,e){let{injectionDb:t,subcircuit:i,groupsMap:r}=e,s=t.pcb_component.getWhere({source_component_id:n.source_component_id}),o=t.cad_component.getWhere({source_component_id:n.source_component_id}),a=new _9({name:n.name,inductance:n.inductance});s&&X1(s,{...e,normalComponent:a}),n.source_group_id&&r?.has(n.source_group_id)?r.get(n.source_group_id).add(a):i.add(a)}function qLt(n,e){let{injectionDb:t,subcircuit:i,groupsMap:r}=e,s=t.pcb_component.getWhere({source_component_id:n.source_component_id}),o=t.cad_component.getWhere({source_component_id:n.source_component_id}),a=new f9({name:n.name});s&&X1(s,{...e,normalComponent:a}),n.source_group_id&&r?.has(n.source_group_id)?r.get(n.source_group_id).add(a):i.add(a)}var vnt=class extends _l{constructor(n){super({...n,subcircuit:!0})}doInitialInflateSubcircuitCircuitJson(){let{circuitJson:n,children:e}=this._parsedProps;if(!n)return;let t=Ke(n);if(n&&e?.length>0)throw new Error("Subcircuit cannot have both circuitJson and children");let r={injectionDb:t,subcircuit:this,groupsMap:new Map},s=t.source_group.list();for(let c of s)ULt(c,r);let o=t.source_component.list();for(let c of o)switch(c.ftype){case"simple_resistor":YLt(c,r);break;case"simple_capacitor":HLt(c,r);break;case"simple_inductor":WLt(c,r);break;case"simple_diode":qLt(c,r);break;case"simple_chip":GLt(c,r);break;default:throw new Error(`No inflator implemented for source component ftype: "${c.ftype}"`)}let a=t.source_port.list();for(let c of a)XLt(c,r)}},wnt=class extends _l{constructor(n){super({...n,subcircuit:!0})}doInitialPcbPrimitiveRender(){if(super.doInitialPcbPrimitiveRender(),this.root?.pcbDisabled)return;let{db:n}=this.root,e=this._parsedProps;if(!this.pcb_group_id)return;let t=n.pcb_group.get(this.pcb_group_id),i=e.paddingLeft??e.padding??0,r=e.paddingRight??e.padding??0,s=e.paddingTop??e.padding??0,o=e.paddingBottom??e.padding??0;n.pcb_group.update(this.pcb_group_id,{width:(t.width??0)+i+r,height:(t.height??0)+s+o,center:{x:t.center.x+(r-i)/2,y:t.center.y+(s-o)/2}})}},Snt=class extends Te{constructor(){super(...arguments);d(this,"pcb_breakout_point_id",null);d(this,"matchedPort",null);d(this,"matchedNet",null);d(this,"isPcbPrimitive",!0)}get config(){return{componentName:"BreakoutPoint",zodProps:eW}}_matchConnection(){let{connection:e}=this._parsedProps,t=this.getSubcircuit();t&&(this.matchedPort=t.selectOne(e,{type:"port"}),this.matchedPort||(this.matchedNet=t.selectOne(e,{type:"net"})),!this.matchedPort&&!this.matchedNet&&this.renderError(`Could not find connection target "${e}"`))}_getSourceTraceIdForPort(e){let{db:t}=this.root;return t.source_trace.list().find(r=>r.connected_source_port_ids.includes(e.source_port_id))?.source_trace_id}_getSourceNetIdForPort(e){let{db:t}=this.root;return t.source_trace.list().find(r=>r.connected_source_port_ids.includes(e.source_port_id))?.connected_source_net_ids[0]}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root;this._matchConnection();let{pcbX:t=0,pcbY:i=0}=this._parsedProps,r=this.parent?.getGroup(),s=this.getSubcircuit();if(!r||!r.pcb_group_id)return;let o=e.pcb_breakout_point.insert({pcb_group_id:r.pcb_group_id,subcircuit_id:s?.subcircuit_id??void 0,source_port_id:this.matchedPort?.source_port_id??void 0,source_trace_id:this.matchedPort?this._getSourceTraceIdForPort(this.matchedPort):void 0,source_net_id:this.matchedNet?this.matchedNet.source_net_id:this.matchedPort?this._getSourceNetIdForPort(this.matchedPort):void 0,x:t,y:i});this.pcb_breakout_point_id=o.pcb_breakout_point_id}_getPcbCircuitJsonBounds(){let{pcbX:e=0,pcbY:t=0}=this._parsedProps;return{center:{x:e,y:t},bounds:{left:e,top:t,right:e,bottom:t},width:0,height:0}}_setPositionFromLayout(e){let{db:t}=this.root;this.pcb_breakout_point_id&&t.pcb_breakout_point.update(this.pcb_breakout_point_id,{x:e.x,y:e.y})}getPcbSize(){return{width:0,height:0}}},Pnt=class extends Te{constructor(){super(...arguments);d(this,"source_net_label_id")}get config(){return{componentName:"NetLabel",zodProps:DH}}_getAnchorSide(){let{_parsedProps:e}=this;if(e.anchorSide)return e.anchorSide;if(!this._resolveConnectsTo())return"right";let i=this._getGlobalSchematicPositionBeforeLayout(),r=this._getConnectedPorts();if(r.length===0)return"right";let s=r[0]._getGlobalSchematicPositionBeforeLayout(),o=s.x-i.x,a=s.y-i.y;if(Math.abs(o)>Math.abs(a)){if(o>0)return"right";if(o<0)return"left"}else{if(a>0)return"top";if(a<0)return"bottom"}return"right"}_getConnectedPorts(){let e=this._resolveConnectsTo();if(!e)return[];let t=[];for(let i of e){let r=this.getSubcircuit().selectOne(i);r&&t.push(r)}return t}computeSchematicPropsTransform(){let{_parsedProps:e}=this;if(e.schX===void 0&&e.schY===void 0){let t=this._getConnectedPorts();if(t.length>0){let i=t[0]._getGlobalSchematicPositionBeforeLayout(),r=ze(this.parent?.computeSchematicGlobalTransform?.()??Qi(),{x:0,y:0});return Nn(i.x-r.x,i.y-r.y)}}return super.computeSchematicPropsTransform()}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getSubcircuit().selectOne(`net.${this._getNetName()}`),s=t.anchorSide??"right",o=ml({anchor_position:i,anchor_side:s,text:t.net}),a=e.schematic_net_label.insert({text:t.net,source_net_id:r.source_net_id,anchor_position:i,center:o,anchor_side:this._getAnchorSide()});this.source_net_label_id=a.source_net_id}_resolveConnectsTo(){let{_parsedProps:e}=this,t=e.connectsTo??e.connection;if(Array.isArray(t))return t;if(typeof t=="string")return[t]}_getNetName(){let{_parsedProps:e}=this;return e.net}doInitialCreateNetsFromProps(){let{_parsedProps:e}=this;e.net&&KS(this,[`net.${e.net}`])}doInitialCreateTracesFromNetLabels(){if(this.root?.schematicDisabled)return;let e=this._resolveConnectsTo();if(e)for(let t of e)this.add(new oo({from:t,to:`net.${this._getNetName()}`}))}doInitialSchematicTraceRender(){if(!this.root?._featureMspSchematicTraceRouting||this.root?.schematicDisabled)return;let{db:e}=this.root,t=this._resolveConnectsTo();if(!t||t.length===0)return;let i=this._getGlobalSchematicPositionBeforeLayout(),r=this._getAnchorSide(),o={left:"x-",right:"x+",top:"y+",bottom:"y-"}[r],a=this.getSubcircuit().selectOne(`net.${this._getNetName()}`);for(let c of t){let l=this.getSubcircuit().selectOne(c,{type:"port"});if(!l||!l.schematic_port_id)continue;let u=!1;if(a?.source_net_id){let S=e.source_trace.list().find(P=>P.connected_source_net_ids?.includes(a.source_net_id)&&P.connected_source_port_ids?.includes(l.source_port_id??""));if(S&&(u=e.schematic_trace.list().some(P=>P.source_trace_id===S.source_trace_id)),u)continue}let p=l._getGlobalSchematicPositionAfterLayout(),f=QA(l.facingDirection??"right")??"x+",y=Wc({x:p.x,y:p.y,facingDirection:f},{x:i.x,y:i.y,facingDirection:o});if(!Array.isArray(y)||y.length<2)continue;let g=[];for(let S=0;S<y.length-1;S++)g.push({from:{x:y[S].x,y:y[S].y},to:{x:y[S+1].x,y:y[S+1].y}});let x,v;if(a?.source_net_id&&l.source_port_id){let S=e.source_trace.list().find(P=>P.connected_source_net_ids?.includes(a.source_net_id)&&P.connected_source_port_ids?.includes(l.source_port_id));x=S?.source_trace_id,v=S?.subcircuit_connectivity_map_key||e.source_net.get(a.source_net_id)?.subcircuit_connectivity_map_key}e.schematic_trace.insert({source_trace_id:x,edges:g,junctions:[],subcircuit_connectivity_map_key:v}),e.schematic_port.update(l.schematic_port_id,{is_connected:!0})}}},knt=class extends Te{constructor(){super(...arguments);d(this,"pcb_silkscreen_circle_id",null);d(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenCircle",zodProps:vW}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(t.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenCircle. Must be "top" or "bottom".`);let s=this._computePcbGlobalTransformBeforeLayout(),o=this.getSubcircuit(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,c=e.pcb_silkscreen_circle.insert({pcb_component_id:a,layer:r,center:{x:t.pcbX??0,y:t.pcbY??0},radius:t.radius,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,stroke_width:t.strokeWidth??.1});this.pcb_silkscreen_circle_id=c.pcb_silkscreen_circle_id}getPcbSize(){let{_parsedProps:e}=this,t=e.radius*2;return{width:t,height:t}}},Tnt=class extends Te{constructor(){super(...arguments);d(this,"pcb_silkscreen_rect_id",null);d(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenRect",zodProps:bW}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(t.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenRect. Must be "top" or "bottom".`);let s=this.getSubcircuit(),o=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=e.pcb_silkscreen_rect.insert({pcb_component_id:o,layer:r,center:{x:t.pcbX??0,y:t.pcbY??0},width:t.width,height:t.height,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this?.getGroup()?.pcb_group_id??void 0,stroke_width:t.strokeWidth??.1,is_filled:t.filled??!1,corner_radius:t.cornerRadius??void 0});this.pcb_silkscreen_rect_id=a.pcb_silkscreen_rect_id}getPcbSize(){let{_parsedProps:e}=this;return{width:e.width,height:e.height}}},Ent=class extends Te{constructor(){super(...arguments);d(this,"pcb_silkscreen_line_id",null);d(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenLine",zodProps:xW}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(t.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenLine. Must be "top" or "bottom".`);let s=this.getSubcircuit(),o=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=e.pcb_silkscreen_line.insert({pcb_component_id:o,layer:r,x1:t.x1,y1:t.y1,x2:t.x2,y2:t.y2,stroke_width:t.strokeWidth??.1,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:s?.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_line_id=a.pcb_silkscreen_line_id}getPcbSize(){let{_parsedProps:e}=this,t=Math.abs(e.x2-e.x1),i=Math.abs(e.y2-e.y1);return{width:t,height:i}}},Mnt=class extends Te{constructor(e){super(e);d(this,"pcb_via_id",null);d(this,"matchedPort",null);d(this,"isPcbPrimitive",!0);d(this,"source_manually_placed_via_id",null);d(this,"subcircuit_connectivity_map_key",null);let t=this._getLayers();this._parsedProps.layers=t,this.initPorts()}get config(){return{componentName:"Via",zodProps:QH}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){let{_parsedProps:e}=this;return{width:e.outerDiameter,height:e.outerDiameter}}_getPcbCircuitJsonBounds(){let{db:e}=this.root,t=e.pcb_via.get(this.pcb_via_id),i=this.getPcbSize();return{center:{x:t.x,y:t.y},bounds:{left:t.x-i.width/2,top:t.y-i.height/2,right:t.x+i.width/2,bottom:t.y+i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(e){let{db:t}=this.root;t.pcb_via.update(this.pcb_via_id,{x:e.x,y:e.y})}_getLayers(){let{fromLayer:e="top",toLayer:t="bottom"}=this._parsedProps;return e===t?[e]:[e,t]}initPorts(){let e=this._parsedProps.layers;for(let i of e){let r=new Vi({name:i,layer:i});r.registerMatch(this),this.add(r)}let t=new Vi({name:"pin1"});t.registerMatch(this),this.add(t)}_getConnectedNetOrTrace(){let e=this._parsedProps.connectsTo;if(!e)return null;let t=this.getSubcircuit(),i=Array.isArray(e)?e:[e];for(let r of i)if(r.startsWith("net.")){let s=t.selectOne(r,{type:"net"});if(s)return s}return null}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalPcbPositionBeforeLayout(),r=this.getSubcircuit(),s=e.pcb_component.insert({center:i,width:t.outerDiameter,height:t.outerDiameter,layer:t.fromLayer??"top",rotation:0,source_component_id:this.source_component_id,subcircuit_id:r?.subcircuit_id??void 0,obstructs_within_bounds:!0});this.pcb_component_id=s.pcb_component_id}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=this.getGroup(),r=this.getSubcircuit(),s=e.source_manually_placed_via.insert({source_group_id:i?.source_group_id,source_net_id:t.net??"",subcircuit_id:r?.subcircuit_id??void 0});this.source_component_id=s.source_manually_placed_via_id}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalPcbPositionBeforeLayout(),r=this.getSubcircuit(),s=e.pcb_via.insert({x:i.x,y:i.y,hole_diameter:t.holeDiameter,outer_diameter:t.outerDiameter,layers:["bottom","top"],from_layer:t.fromLayer||"bottom",to_layer:t.toLayer||"top",subcircuit_id:r?.subcircuit_id??void 0,subcircuit_connectivity_map_key:this.subcircuit_connectivity_map_key??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,net_is_assignable:t.netIsAssignable??void 0});this.pcb_via_id=s.pcb_via_id}},Cnt=class extends Te{constructor(){super(...arguments);d(this,"isPcbPrimitive",!0)}get config(){return{componentName:"CopperPour",zodProps:iW}}getPcbSize(){return{width:0,height:0}}doInitialCreateNetsFromProps(){let{_parsedProps:e}=this;KS(this,[e.connectsTo])}doInitialPcbCopperPourRender(){this.root?.pcbDisabled||this._queueAsyncEffect("PcbCopperPourRender",async()=>{let{db:e}=this.root,{_parsedProps:t}=this,i=this.getSubcircuit().selectOne(t.connectsTo);if(!i||!i.source_net_id){this.renderError(`Net "${t.connectsTo}" not found for copper pour`);return}let r=this.getSubcircuit(),s=e.toArray().filter(p=>p.type==="source_net"&&p.name===i.name)[0]||"",o=t.clearance??.2,a=$Q(e.toArray(),{layer:t.layer,pour_connectivity_key:s.subcircuit_connectivity_map_key||"",pad_margin:t.padMargin??o,trace_margin:t.traceMargin??o,board_edge_margin:t.boardEdgeMargin??o,cutout_margin:t.cutoutMargin??o}),c=new DQ(a),{brep_shapes:l}=c.getOutput(),u=t.coveredWithSolderMask??!1;for(let p of l)e.pcb_copper_pour.insert({shape:"brep",layer:t.layer,brep_shape:p,source_net_id:i.source_net_id,subcircuit_id:r?.subcircuit_id??void 0,covered_with_solder_mask:u})})}},Int=class extends Gn{get config(){return{componentName:"Battery",schematicSymbolName:this.props.symbolName??"battery",zodProps:FH,sourceFtype:"simple_power_source"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=n.source_component.insert({name:this.name,ftype:"simple_power_source",capacity:e.capacity,supplier_part_numbers:e.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=t.source_component_id}},Nnt=class extends Gn{_getPcbRotationBeforeLayout(){let n=this.props.pcbOrientation==="vertical"?-90:0;return(super._getPcbRotationBeforeLayout()??0)+n}get config(){return{componentName:"PinHeader",zodProps:zH,shouldRenderAsSchematicBox:!0}}_getImpliedFootprintString(){let n=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:0),e=this._parsedProps.holeDiameter,t=this._parsedProps.platedDiameter,i=this._parsedProps.pitch,r=this._parsedProps.showSilkscreenPinLabels;if(n>0){let s;if(i)!e&&!t?s=`pinrow${n}_p${i}`:s=`pinrow${n}_p${i}_id${e}_od${t}`;else if(!e&&!t)s=`pinrow${n}`;else return null;return r!==!0&&(s+="_nopinlabels"),s}return null}initPorts(){let n=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:1);for(let e=1;e<=n;e++){let t=Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels[e-1]:this._parsedProps.pinLabels?.[`pin${e}`];if(t){let i=Array.isArray(t)?t[0]:t,r=Array.isArray(t)?t.slice(1):[];this.add(new Vi({pinNumber:e,name:i,aliases:[`pin${e}`,...r]}))}else this.add(new Vi({pinNumber:e,name:`pin${e}`}))}}_getSchematicPortArrangement(){let n=this._parsedProps.pinCount??1,e=this._parsedProps.schFacingDirection??this._parsedProps.facingDirection??"right",t=this._parsedProps.schPinArrangement;return e==="left"?{leftSide:{direction:t?.leftSide?.direction??"top-to-bottom",pins:t?.leftSide?.pins??Array.from({length:n},(i,r)=>`pin${r+1}`)}}:{rightSide:{direction:t?.rightSide?.direction??"top-to-bottom",pins:t?.rightSide?.pins??Array.from({length:n},(i,r)=>`pin${r+1}`)}}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=n.source_component.insert({ftype:"simple_pin_header",name:this.name,supplier_part_numbers:e.supplierPartNumbers,pin_count:e.pinCount,gender:e.gender,are_pins_interchangeable:!0});this.source_component_id=t.source_component_id}};function ZLt(n){switch(n){case"two_ground_pins":return"crystal_4pin";case"ground_pin":return"resonator";case"no_ground":return"crystal";default:return"crystal"}}var Ant=class extends Gn{get config(){return{componentName:"Resonator",schematicSymbolName:this.props.symbolName??ZLt(this.props.pinVariant),zodProps:TH,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=e.pinVariant||"no_ground",i=n.source_component.insert({ftype:"simple_resonator",name:this.name,frequency:e.frequency,load_capacitance:e.loadCapacitance,supplier_part_numbers:e.supplierPartNumbers,pin_variant:t,are_pins_interchangeable:t==="no_ground"||t==="ground_pin"});this.source_component_id=i.source_component_id}_getSchematicSymbolDisplayValue(){let n=`${gi(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${n} / ${gi(this._parsedProps.loadCapacitance)}F`:n}};function KLt(n){switch(n){case"three_pin":return"potentiometer3";case"two_pin":return"potentiometer2";default:return"potentiometer2"}}var Rnt=class extends Gn{get config(){return{componentName:"Potentiometer",schematicSymbolName:this.props.symbolName??KLt(this.props.pinVariant),zodProps:PH,shouldRenderAsSchematicBox:!1}}_getSchematicSymbolDisplayValue(){return`${gi(this._parsedProps.maxResistance)}\u03A9`}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=e.pinVariant||"two_pin",i=n.source_component.insert({ftype:"simple_potentiometer",name:this.name,max_resistance:e.maxResistance,pin_variant:t,are_pins_interchangeable:t==="two_pin"});this.source_component_id=i.source_component_id}},Ont=class extends Gn{get config(){return{componentName:"PushButton",schematicSymbolName:this.props.symbolName??"push_button_normally_open_momentary",zodProps:$H,sourceFtype:Va.simple_push_button}}get defaultInternallyConnectedPinNames(){return[]}initPorts(){super.initPorts({pinCount:2,ignoreSymbolPorts:!0});let n=_i[this._getSchematicSymbolNameOrThrow()],e=n.ports.find(l=>l.labels.includes("1")),t=n.ports.find(l=>l.labels.includes("2")),i=this.selectAll("port"),r=i.find(l=>l.props.pinNumber===1),s=i.find(l=>l.props.pinNumber===2),o=i.find(l=>l.props.pinNumber===3),a=i.find(l=>l.props.pinNumber===4),{internallyConnectedPins:c}=this._parsedProps;r.schematicSymbolPortDef=e,(!c||c.length===0)&&(s.schematicSymbolPortDef=t);for(let[l,u]of[[2,s],[3,o],[4,a]]){let p=c?.find(([y,g])=>y===`pin${l}`||g===`pin${l}`);if(!p){u.schematicSymbolPortDef=t;break}(p?.[0]===`pin${l}`?p[1]:p?.[0])!=="pin1"&&(u.schematicSymbolPortDef=t)}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=n.source_component.insert({name:this.name,ftype:Va.simple_push_button,supplier_part_numbers:e.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=t.source_component_id}},Lnt=class extends Gn{get config(){return{schematicSymbolName:this.props.symbolName??(this.props.pinVariant==="four_pin"?"crystal_4pin":"crystal"),componentName:"Crystal",zodProps:kH,sourceFtype:"simple_crystal"}}initPorts(){let n=this.props.pinVariant==="four_pin"?{pin1:["left1","1"],pin2:["top1","2","gnd1"],pin3:["right1","3"],pin4:["bottom1","4","gnd2"]}:{pin1:["pos","left"],pin2:["neg","right"]};super.initPorts({additionalAliases:n})}_getSchematicSymbolDisplayValue(){let n=`${gi(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${n} / ${gi(this._parsedProps.loadCapacitance)}F`:n}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=n.source_component.insert({name:this.name,ftype:"simple_crystal",frequency:e.frequency,load_capacitance:e.loadCapacitance,pin_variant:e.pinVariant||"two_pin",are_pins_interchangeable:(e.pinVariant||"two_pin")==="two_pin"});this.source_component_id=t.source_component_id}},Fnt=class extends Gn{constructor(){super(...arguments);d(this,"emitter",this.portMap.pin1);d(this,"collector",this.portMap.pin2);d(this,"base",this.portMap.pin3)}get config(){let e=this.props.type==="npn"?"npn_bipolar_transistor":"pnp_bipolar_transistor";return{componentName:"Transistor",schematicSymbolName:this.props.symbolName??e,zodProps:BH,sourceFtype:"simple_transistor",shouldRenderAsSchematicBox:!1}}initPorts(){let e={pin1:["collector","c"],pin2:["emitter","e"],pin3:["base","b"]};super.initPorts({pinCount:3,additionalAliases:e})}doInitialCreateNetsFromProps(){this._createNetsFromProps([...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_transistor",name:this.name,transistor_type:t.type});this.source_component_id=i.source_component_id}},znt=class extends Gn{get config(){let n=this.props.mosfetMode==="depletion"?"d":"e",t=`${this.props.channelType}_channel_${n}_mosfet_transistor`;return{componentName:"Mosfet",schematicSymbolName:this.props.symbolName??t,zodProps:YH,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=n.source_component.insert({ftype:"simple_mosfet",name:this.name,mosfet_mode:e.mosfetMode,channel_type:e.channelType});this.source_component_id=t.source_component_id}};function JLt(n){return n.simSwitchFrequency!==void 0||n.simCloseAt!==void 0||n.simOpenAt!==void 0||n.simStartClosed!==void 0||n.simStartOpen!==void 0}var Dnt=class extends Gn{_getSwitchType(){let n=this._parsedProps;return n?n.dpdt?"dpdt":n.spst?"spst":n.spdt?"spdt":n.dpst?"dpst":n.type??"spst":"spst"}get config(){let n=this._getSwitchType(),e=this._parsedProps?.isNormallyClosed??!1,t={spst:e?"spst_normally_closed_switch":"spst_switch",spdt:e?"spdt_normally_closed_switch":"spdt_switch",dpst:e?"dpst_normally_closed_switch":"dpst_switch",dpdt:e?"dpdt_normally_closed_switch":"dpdt_switch"};return{componentName:"Switch",schematicSymbolName:this.props.symbolName??t[n],zodProps:WH,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:n}=this.root,e=this._parsedProps??{},t=n.source_component.insert({ftype:"simple_switch",name:this.name,are_pins_interchangeable:this._getSwitchType()==="spst"});this.source_component_id=t.source_component_id}doInitialSimulationRender(){let{_parsedProps:n}=this;if(!JLt(n))return;let{db:e}=this.root,t={type:"simulation_switch",source_component_id:this.source_component_id||""};n.simSwitchFrequency!==void 0&&(t.switching_frequency=pr.parse(n.simSwitchFrequency)),n.simCloseAt!==void 0&&(t.closes_at=ur.parse(n.simCloseAt)),n.simOpenAt!==void 0&&(t.opens_at=ur.parse(n.simOpenAt)),n.simStartOpen!==void 0&&(t.starts_closed=!n.simStartOpen),n.simStartClosed!==void 0&&(t.starts_closed=n.simStartClosed),e.simulation_switch.insert(t)}},ZA={HOLE_DIAMETER:.5,SMT_CIRCLE_DIAMETER:1.2,SMT_RECT_SIZE:2},$nt=class extends Gn{get config(){return{componentName:"TestPoint",schematicSymbolName:this.props.symbolName??"testpoint",zodProps:tW,sourceFtype:Va.simple_test_point}}_getPropsWithDefaults(){let{padShape:n,holeDiameter:e,footprintVariant:t,padDiameter:i,width:r,height:s}=this._parsedProps;return!t&&e&&(t="through_hole"),t??(t="through_hole"),n??(n="circle"),t==="pad"?n==="circle"?i??(i=ZA.SMT_CIRCLE_DIAMETER):n==="rect"&&(r??(r=ZA.SMT_RECT_SIZE),s??(s=r)):t==="through_hole"&&(e??(e=ZA.HOLE_DIAMETER)),{padShape:n,holeDiameter:e,footprintVariant:t,padDiameter:i,width:r,height:s}}_getImpliedFootprintString(){let{padShape:n,holeDiameter:e,footprintVariant:t,padDiameter:i,width:r,height:s}=this._getPropsWithDefaults();if(t==="through_hole")return`platedhole_d${e}`;if(t==="pad"){if(n==="circle")return`smtpad_circle_d${i}`;if(n==="rect")return`smtpad_rect_w${r}_h${s}`}throw new Error(`Footprint variant "${t}" with pad shape "${n}" not implemented`)}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,{padShape:t,holeDiameter:i,footprintVariant:r,padDiameter:s,width:o,height:a}=this._getPropsWithDefaults(),c=n.source_component.insert({ftype:Va.simple_test_point,name:this.name,supplier_part_numbers:e.supplierPartNumbers,footprint_variant:r,pad_shape:t,pad_diameter:s,hole_diameter:i,width:o,height:a,are_pins_interchangeable:!0});this.source_component_id=c.source_component_id}},jnt=class extends Te{constructor(){super(...arguments);d(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicText",zodProps:dW}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalSchematicPositionBeforeLayout();e.schematic_text.insert({anchor:t.anchor??"center",text:t.text,font_size:t.fontSize,color:t.color||"#000000",position:{x:i.x,y:i.y},rotation:t.schRotation??0})}},Bnt=class extends Te{constructor(){super(...arguments);d(this,"isSchematicPrimitive",!0);d(this,"schematic_line_id")}get config(){return{componentName:"SchematicLine",zodProps:hW}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,s=e.schematic_line.insert({schematic_component_id:r,x1:t.x1+i.x,y1:t.y1+i.y,x2:t.x2+i.x,y2:t.y2+i.y,stroke_width:t.strokeWidth??eP,color:t.color??tP,is_dashed:!1,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_line_id=s.schematic_line_id}},Ynt=class extends Te{constructor(){super(...arguments);d(this,"isSchematicPrimitive",!0);d(this,"schematic_rect_id")}get config(){return{componentName:"SchematicRect",zodProps:pW}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,s=e.schematic_rect.insert({center:{x:i.x,y:i.y},width:t.width,height:t.height,stroke_width:t.strokeWidth??eP,color:t.color??tP,is_filled:t.isFilled,schematic_component_id:r,is_dashed:t.isDashed,rotation:t.rotation??0,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_rect_id=s.schematic_rect_id}},Xnt=class extends Te{constructor(){super(...arguments);d(this,"isSchematicPrimitive",!0);d(this,"schematic_arc_id")}get config(){return{componentName:"SchematicArc",zodProps:cW}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,s=e.schematic_arc.insert({schematic_component_id:r,center:{x:t.center.x+i.x,y:t.center.y+i.y},radius:t.radius,start_angle_degrees:t.startAngleDegrees,end_angle_degrees:t.endAngleDegrees,direction:t.direction,stroke_width:t.strokeWidth??eP,color:t.color??tP,is_dashed:t.isDashed,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_arc_id=s.schematic_arc_id}},Unt=class extends Te{constructor(){super(...arguments);d(this,"isSchematicPrimitive",!0);d(this,"schematic_circle_id")}get config(){return{componentName:"SchematicCircle",zodProps:uW}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,s=e.schematic_circle.insert({schematic_component_id:r,center:{x:t.center.x+i.x,y:t.center.y+i.y},radius:t.radius,stroke_width:t.strokeWidth??eP,color:t.color??tP,is_filled:t.isFilled,fill_color:t.fillColor,is_dashed:t.isDashed,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_circle_id=s.schematic_circle_id}};function QLt({anchor:n,x:e,y:t,width:i,height:r,isInside:s}){switch(n){case"top_left":return{x:e,y:t+r,textAnchor:s?"top_left":"bottom_left"};case"top_center":return{x:e+i/2,y:t+r,textAnchor:s?"top_center":"bottom_center"};case"top_right":return{x:e+i,y:t+r,textAnchor:s?"top_right":"bottom_right"};case"center_left":return{x:e,y:t+r/2,textAnchor:s?"center_left":"center_right"};case"center":return{x:e+i/2,y:t+r/2,textAnchor:"center"};case"center_right":return{x:e+i,y:t+r/2,textAnchor:s?"center_right":"center_left"};case"bottom_left":return{x:e,y:t,textAnchor:s?"bottom_left":"top_left"};case"bottom_center":return{x:e+i/2,y:t,textAnchor:s?"bottom_center":"top_center"};case"bottom_right":return{x:e+i,y:t,textAnchor:s?"bottom_right":"top_right"};default:return{x:e+i/2,y:t+r,textAnchor:"center"}}}var Vnt=class extends Te{constructor(){super(...arguments);d(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicBox",zodProps:lW,shouldRenderAsSchematicBox:!0}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=.6,r=typeof t.padding=="number"?t.padding:0,s=typeof t.paddingTop=="number"?t.paddingTop:r,o=typeof t.paddingBottom=="number"?t.paddingBottom:r,a=typeof t.paddingLeft=="number"?t.paddingLeft:r,c=typeof t.paddingRight=="number"?t.paddingRight:r,l=t.overlay&&t.overlay.length>0,u=typeof t.width=="number"&&typeof t.height=="number",p,f,y,g,x,v;if(l){let P=t.overlay.map(et=>({selector:et,port:this.getSubcircuit().selectOne(et,{type:"port"})})).filter(({port:et})=>et!=null).map(({port:et})=>({position:et._getGlobalSchematicPositionAfterLayout()}));if(P.length===0)return;let T=P.map(et=>et.position.x),k=P.map(et=>et.position.y),C=Math.min(...T),E=Math.max(...T),N=Math.min(...k),I=Math.max(...k),A=E-C,R=I-N,j=A===0?i:0,B=R===0?i:0,G=a+j/2,U=c+j/2,H=s+B/2,Q=o+B/2,tt=C-G,V=E+U,ot=N-Q,nt=I+H;p=V-tt,f=nt-ot,y=tt+(t.schX??0),g=ot+(t.schY??0),x=y+p/2,v=g+f/2}else if(u){p=t.width,f=t.height;let S=this._getGlobalSchematicPositionBeforeLayout();x=S.x,v=S.y,y=x-p/2,g=v-f/2}else return;if(e.schematic_box.insert({height:f,width:p,x:y,y:g,is_dashed:t.strokeStyle==="dashed"}),t.title){let S=t.titleInside,P=.1,T=t.titleAlignment,k=QLt({anchor:T,x:y,y:g,width:p,height:f,isInside:S}),C,E,N=k.textAnchor;S?(C=T.includes("top")?-P:T.includes("bottom")?P:0,E=T.includes("left")?P:T.includes("right")?-P:0):(C=T.includes("top")?P:T.includes("bottom")?-P:0,E=T.includes("center_left")?-P:T.includes("center_right")?P:0);let I=k.x+E,A=k.y+C;e.schematic_text.insert({anchor:N,text:t.title,font_size:t.titleFontSize??.18,color:t.titleColor??"#000000",position:{x:I,y:A},rotation:0})}}},Gnt=class extends Te{constructor(){super(...arguments);d(this,"isSchematicPrimitive",!0);d(this,"schematic_table_id",null)}get config(){return{componentName:"SchematicTable",zodProps:fW}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this.children.filter(f=>f.componentName==="SchematicRow");if(i.length===0)return;let r=[],s=0;for(let f of i){let y=f.children.filter(g=>g.componentName==="SchematicCell");s=Math.max(s,y.length)}for(let f=0;f<i.length;f++)r[f]=[];for(let f=0;f<i.length;f++){let g=i[f].children.filter(v=>v.componentName==="SchematicCell"),x=0;for(let v=0;v<g.length;v++){for(;r[f][x];)x++;let S=g[v],P=S._parsedProps.colSpan??1,T=S._parsedProps.rowSpan??1;for(let k=0;k<T;k++)for(let C=0;C<P;C++)r[f+k]||(r[f+k]=[]),r[f+k][x+C]=S;x+=P}}s=Math.max(0,...r.map(f=>f.length));let o=i.map((f,y)=>f._parsedProps.height??1),a=Array.from({length:s},(f,y)=>{let g=0;for(let x=0;x<i.length;x++){let v=r[x]?.[y];if(v){let S=v._parsedProps.text??v._parsedProps.children,P=v._parsedProps.width??(S?.length??2)*.5;P>g&&(g=P)}}return g||10}),c=this._getGlobalSchematicPositionBeforeLayout(),l=e.schematic_table.insert({anchor_position:c,column_widths:a,row_heights:o,cell_padding:t.cellPadding,border_width:t.borderWidth,anchor:t.anchor,subcircuit_id:this.getSubcircuit()?.subcircuit_id||"",schematic_component_id:this.parent?.schematic_component_id||""});this.schematic_table_id=l.schematic_table_id;let u=new Set,p=0;for(let f=0;f<i.length;f++){let y=0;for(let g=0;g<s;g++){let x=r[f]?.[g];if(x&&!u.has(x)){u.add(x);let v=x._parsedProps,S=v.rowSpan??1,P=v.colSpan??1,T=0;for(let C=0;C<P;C++)T+=a[g+C];let k=0;for(let C=0;C<S;C++)k+=o[f+C];e.schematic_table_cell.insert({schematic_table_id:this.schematic_table_id,start_row_index:f,end_row_index:f+S-1,start_column_index:g,end_column_index:g+P-1,text:v.text??v.children,center:{x:c.x+y+T/2,y:c.y-p-k/2},width:T,height:k,horizontal_align:v.horizontalAlign,vertical_align:v.verticalAlign,font_size:v.fontSize??t.fontSize,subcircuit_id:this.getSubcircuit()?.subcircuit_id||""})}a[g]&&(y+=a[g])}p+=o[f]}}},Hnt=class extends Te{constructor(){super(...arguments);d(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicRow",zodProps:mW}}},Wnt=class extends Te{constructor(){super(...arguments);d(this,"isSchematicPrimitive",!0);d(this,"canHaveTextChildren",!0)}get config(){return{componentName:"SchematicCell",zodProps:_W}}},qnt=class extends Te{constructor(){super(...arguments);d(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"Symbol",zodProps:LH}}},Znt=class extends Te{get config(){return{componentName:"AnalogSimulation",zodProps:jH}}doInitialSimulationRender(){let{db:n}=this.root,{duration:e,timePerStep:t}=this._parsedProps,i=e||10,r=t||.01;n.simulation_experiment.insert({name:"spice_transient_analysis",experiment_type:"spice_transient_analysis",end_time_ms:i,time_per_step:r})}},Knt=class extends Te{constructor(){super(...arguments);d(this,"simulation_voltage_probe_id",null)}get config(){return{componentName:"VoltageProbe",zodProps:aW}}doInitialSimulationRender(){let{db:e}=this.root,{connectsTo:t,name:i}=this._parsedProps,r=this.getSubcircuit();if(!r){this.renderError("VoltageProbe must be inside a subcircuit");return}let s=Array.isArray(t)?t:[t];if(s.length!==1){this.renderError("VoltageProbe must connect to exactly one port or net");return}let o=s[0],a=r.selectOne(o,{type:"port"}),c=a?null:r.selectOne(o,{type:"net"});if(c&&c.componentName!=="Net"){this.renderError(`VoltageProbe connection target "${o}" resolved to a non-net component "${c.componentName}".`);return}if(!a&&!c){this.renderError(`VoltageProbe could not find connection target "${o}"`);return}let{simulation_voltage_probe_id:l}=e.simulation_voltage_probe.insert({name:i??this.name,source_port_id:a?.source_port_id??void 0,source_net_id:c?.source_net_id??void 0,subcircuit_id:r.subcircuit_id||void 0});this.simulation_voltage_probe_id=l}},t7t={name:"@tscircuit/core",type:"module",version:"0.0.861",types:"dist/index.d.ts",main:"dist/index.js",module:"dist/index.js",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist"],repository:{type:"git",url:"https://github.com/tscircuit/core"},scripts:{build:"tsup-node index.ts --format esm --dts",format:"biome format . --write","measure-bundle":"howfat -r table .","pkg-pr-new-release":"bunx pkg-pr-new publish --comment=off --peerDeps","smoke-test:dist":"bun run scripts/smoke-tests/test-dist-simple-circuit.tsx","build:benchmarking":"bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist","build:benchmarking:watch":`chokidar "./{benchmarking,lib}/**/*.{ts,tsx}" -c 'bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist'`,"start:benchmarking":'concurrently "bun run build:benchmarking:watch" "live-server ./benchmarking-dist"',"generate-test-plan":"bun run scripts/generate-test-plan.ts"},devDependencies:{"@biomejs/biome":"^1.8.3","@resvg/resvg-js":"^2.6.2","@tscircuit/capacity-autorouter":"^0.0.140","@tscircuit/checks":"^0.0.85","@tscircuit/circuit-json-util":"^0.0.72","@tscircuit/common":"^0.0.20","@tscircuit/copper-pour-solver":"^0.0.14","@tscircuit/footprinter":"^0.0.236","@tscircuit/import-snippet":"^0.0.4","@tscircuit/infgrid-ijump-astar":"^0.0.33","@tscircuit/log-soup":"^1.0.2","@tscircuit/matchpack":"^0.0.16","@tscircuit/math-utils":"^0.0.29","@tscircuit/miniflex":"^0.0.4","@tscircuit/ngspice-spice-engine":"^0.0.2","@tscircuit/props":"^0.0.398","@tscircuit/schematic-autolayout":"^0.0.6","@tscircuit/schematic-match-adapt":"^0.0.16","@tscircuit/schematic-trace-solver":"^v0.0.45","@tscircuit/solver-utils":"^0.0.3","@types/bun":"^1.2.16","@types/debug":"^4.1.12","@types/react":"^19.1.8","@types/react-dom":"^19.1.6","@types/react-reconciler":"^0.28.9","bpc-graph":"^0.0.57","bun-match-svg":"0.0.12","calculate-elbow":"^0.0.12","chokidar-cli":"^3.0.0","circuit-json":"^0.0.306","circuit-json-to-bpc":"^0.0.13","circuit-json-to-connectivity-map":"^0.0.22","circuit-json-to-gltf":"^0.0.31","circuit-json-to-simple-3d":"^0.0.9","circuit-json-to-spice":"^0.0.16","circuit-to-svg":"^0.0.265",concurrently:"^9.1.2","connectivity-map":"^1.0.0",debug:"^4.3.6","eecircuit-engine":"^1.5.6",flatbush:"^4.5.0","graphics-debug":"^0.0.60",howfat:"^0.3.8","live-server":"^1.2.2","looks-same":"^9.0.1",minicssgrid:"^0.0.9","pkg-pr-new":"^0.0.37",poppygl:"^0.0.16",react:"^19.1.0","react-dom":"^19.1.0","schematic-symbols":"^0.0.202",spicey:"^0.0.10","ts-expect":"^1.3.0",tsup:"^8.2.4"},peerDependencies:{"@tscircuit/capacity-autorouter":"*","@tscircuit/checks":"*","@tscircuit/circuit-json-util":"*","@tscircuit/footprinter":"*","@tscircuit/infgrid-ijump-astar":"*","@tscircuit/math-utils":"*","@tscircuit/props":"*","@tscircuit/schematic-autolayout":"*","@tscircuit/schematic-match-adapt":"*","circuit-json-to-bpc":"*","bpc-graph":"*","@tscircuit/matchpack":"*","circuit-json":"*","circuit-json-to-connectivity-map":"*","schematic-symbols":"*",typescript:"^5.0.0"},dependencies:{"@flatten-js/core":"^1.6.2","@lume/kiwi":"^0.4.3","calculate-packing":"0.0.50","css-select":"5.1.0","format-si-unit":"^0.0.3",nanoid:"^5.0.7","performance-now":"^2.1.0","react-reconciler":"^0.32.0","transformation-matrix":"^2.16.1",zod:"^3.25.67"}},q_=class{constructor({platform:n,projectUrl:e}={}){d(this,"firstChild",null);d(this,"children");d(this,"db");d(this,"root",null);d(this,"isRoot",!0);d(this,"_schematicDisabledOverride");d(this,"pcbDisabled",!1);d(this,"pcbRoutingDisabled",!1);d(this,"_featureMspSchematicTraceRouting",!0);d(this,"name");d(this,"platform");d(this,"projectUrl");d(this,"_hasRenderedAtleastOnce",!1);d(this,"_eventListeners",{});this.children=[],this.db=Be([]),this.root=this,this.platform=n,this.projectUrl=e,this.pcbDisabled=n?.pcbDisabled??!1}get schematicDisabled(){return this._schematicDisabledOverride!==void 0?this._schematicDisabledOverride:this._getBoard()?._parsedProps?.schematicDisabled??!1}set schematicDisabled(n){this._schematicDisabledOverride=n}add(n){let e;(0,Jnt.isValidElement)(n)?e=Net(n):e=n,this.children.push(e)}setPlatform(n){this.platform={...this.platform,...n}}_getBoard(){let n=this.children.find(e=>e.componentName==="Board");if(n)return n}_guessRootComponent(){if(this.firstChild)return;if(this.children.length===0)throw new Error("Not able to guess root component: RootCircuit has no children (use circuit.add(...))");let n=this.children.filter(t=>t.lowercaseComponentName==="panel");if(n.length>1)throw new Error("Only one <panel> is allowed per circuit");if(n.length===1){if(this.children.length!==1)throw new Error("<panel> must be the root element of the circuit");this.firstChild=n[0];return}if(this.children.length===1&&this.children[0].isGroup){this.firstChild=this.children[0];return}let e=new _l({subcircuit:!0});e.parent=this,e.addAll(this.children),this.children=[e],this.firstChild=e}render(){this.firstChild||this._guessRootComponent();let{firstChild:n,db:e}=this;if(!n)throw new Error("RootCircuit has no root component");n.parent=this,n.runRenderCycle(),this._hasRenderedAtleastOnce=!0}async renderUntilSettled(){for(this.db.source_project_metadata.list()?.[0]||this.db.source_project_metadata.insert({software_used_string:`@tscircuit/core@${this.getCoreVersion()}`,...this.projectUrl?{project_url:this.projectUrl}:{}}),this.render();this._hasIncompleteAsyncEffects();)await new Promise(e=>setTimeout(e,100)),this.render();this.emit("renderComplete")}_hasIncompleteAsyncEffects(){return this.children.some(n=>n._hasIncompleteAsyncEffects()?!0:n.children.some(e=>e._hasIncompleteAsyncEffects()))}getCircuitJson(){return this._hasRenderedAtleastOnce||this.render(),this.db.toArray()}toJson(){return this.getCircuitJson()}async getSvg(n){let e=await Promise.resolve().then(()=>(Ktt(),Ztt)).catch(t=>{throw new Error(`To use circuit.getSvg, you must install the "circuit-to-svg" package.
251
+ `),a={x:t.center.x+t.width/2-.25,y:t.center.y-t.height/2+1};this.root.db.pcb_silkscreen_text.insert({pcb_component_id:this.pcb_board_id,layer:"top",font:"tscircuit2024",font_size:.45,text:r,ccw_rotation:0,anchor_alignment:"bottom_right",anchor_position:a})}doInitialSourceRender(){super.doInitialSourceRender();let{db:e}=this.root,t=e.source_board.insert({source_group_id:this.source_group_id,title:this.props.title||this.props.name});this.source_board_id=t.source_board_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=t.width??0,r=t.height??0,s={x:(t.pcbX??0)+(t.outlineOffsetX??0),y:(t.pcbY??0)+(t.outlineOffsetY??0)},{boardAnchorPosition:o,boardAnchorAlignment:a}=t;if(o&&(s=YOt({boardAnchorPosition:o,boardAnchorAlignment:a??"center",width:i,height:r})),t.outline){let u=t.outline.map(v=>v.x),p=t.outline.map(v=>v.y),f=Math.min(...u),y=Math.max(...u),g=Math.min(...p),x=Math.max(...p);i=y-f,r=x-g,s={x:(f+y)/2+(t.outlineOffsetX??0),y:(g+x)/2+(t.outlineOffsetY??0)}}let c=t.outline;!c&&t.borderRadius!=null&&i>0&&r>0&&(c=Pet(i,r,t.borderRadius));let l=e.pcb_board.insert({center:s,thickness:this.boardThickness,num_layers:this.allLayers.length,width:i,height:r,outline:c?.map(u=>({x:u.x+(t.outlineOffsetX??0),y:u.y+(t.outlineOffsetY??0)})),material:t.material});this.pcb_board_id=l.pcb_board_id,this._addBoardInformationToSilkscreen()}removePcbComponentRender(){let{db:e}=this.root;this.pcb_board_id&&(e.pcb_board.delete(this.pcb_board_id),this.pcb_board_id=null)}_computePcbGlobalTransformBeforeLayout(){return Qi()}doInitialPcbDesignRuleChecks(){this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled")||super.doInitialPcbDesignRuleChecks()}updatePcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db:e}=this.root;if(!this._areChildSubcircuitsRouted()||this._drcChecksComplete)return;this._drcChecksComplete=!0;let t=MQ(e.toArray());for(let l of t)e.pcb_trace_error.insert(l);let i=EQ(e.toArray());for(let l of i)e.pcb_port_not_connected_error.insert(l);let r=NQ(e.toArray());for(let l of r)e.pcb_component_outside_board_error.insert(l);let s=OQ(e.toArray());for(let l of s)e.pcb_trace_error.insert(l);let o=RQ(e.toArray());for(let l of o)e.pcb_via_clearance_error.insert(l);let a=AQ(e.toArray());for(let l of a)e.pcb_via_clearance_error.insert(l);let c=LQ(e.toArray());for(let l of c)e.pcb_footprint_overlap_error.insert(l)}_emitRenderLifecycleEvent(e,t){super._emitRenderLifecycleEvent(e,t),t==="start"&&this.root?.emit("board:renderPhaseStarted",{renderId:this._renderId,phase:e})}},int=class extends _l{constructor(){super(...arguments);d(this,"pcb_panel_id",null)}get config(){return{componentName:"Panel",zodProps:yH}}get isGroup(){return!0}get isSubcircuit(){return!0}add(e){if(e.lowercaseComponentName!=="board")throw new Error("<panel> can only contain <board> elements");super.add(e)}runRenderCycle(){if(!this.children.some(e=>e.componentName==="Board"))throw new Error("<panel> must contain at least one <board>");super.runRenderCycle()}doInitialPcbComponentRender(){if(super.doInitialPcbComponentRender(),this.root?.pcbDisabled)return;let{db:e}=this.root,t=this._parsedProps,i=e.pcb_panel.insert({width:X.parse(t.width),height:X.parse(t.height),center:this._getGlobalPcbPositionBeforeLayout(),covered_with_solder_mask:!(t.noSolderMask??!1)});this.pcb_panel_id=i.pcb_panel_id}updatePcbComponentRender(){if(this.root?.pcbDisabled||!this.pcb_panel_id)return;let{db:e}=this.root,t=this._parsedProps;e.pcb_panel.update(this.pcb_panel_id,{width:X.parse(t.width),height:X.parse(t.height),center:this._getGlobalPcbPositionBeforeLayout(),covered_with_solder_mask:!(t.noSolderMask??!1)})}removePcbComponentRender(){this.pcb_panel_id&&(this.root?.db.pcb_panel.delete(this.pcb_panel_id),this.pcb_panel_id=null)}},$Lt=new Proxy({},{get:(n,e)=>e}),Va=$Lt,tP="rgba(132, 0, 0)",eP=.12,d9=class extends Gn{constructor(){super(...arguments);d(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Capacitor",schematicSymbolName:this.props.polarized?"capacitor_polarized":this.props.symbolName??"capacitor",zodProps:EH,sourceFtype:Va.simple_capacitor}}initPorts(){typeof this.props.footprint=="string"?super.initPorts({additionalAliases:{pin1:["anode","pos"],pin2:["cathode","neg"]}}):super.initPorts()}_getSchematicSymbolDisplayValue(){let e=this.props.capacitance,t=typeof e=="string"?e:`${gi(this._parsedProps.capacitance)}F`;return this._parsedProps.schShowRatings&&this._parsedProps.maxVoltageRating?`${t}/${gi(this._parsedProps.maxVoltageRating)}V`:t}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.decouplingFor,this.props.decouplingTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.decouplingFor&&this.props.decouplingTo&&(this.add(new oo({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.decouplingFor})),this.add(new oo({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.decouplingTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_capacitor",name:this.name,manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,capacitance:t.capacitance,max_voltage_rating:t.maxVoltageRating,max_decoupling_trace_length:t.maxDecouplingTraceLength,display_capacitance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!t.polarized});this.source_component_id=i.source_component_id}},Y1=class extends Gn{constructor(e){super(e);d(this,"schematicBoxDimensions",null)}get config(){return{componentName:"Chip",zodProps:t_,shouldRenderAsSchematicBox:!0}}initPorts(e={}){super.initPorts(e);let{_parsedProps:t}=this;if(t.externallyConnectedPins){let i=new Set;for(let[r,s]of t.externallyConnectedPins)i.add(r),i.add(s);for(let r of i)if(!this.children.find(o=>o instanceof Vi&&o.isMatchingAnyOf([r]))){let o=r.match(/^pin(\d+)$/);if(o){let a=parseInt(o[1]);this.add(new Vi({pinNumber:a,aliases:[r]}))}else this.add(new Vi({name:r,aliases:[r]}))}}}doInitialSchematicComponentRender(){let{_parsedProps:e}=this;e?.noSchematicRepresentation!==!0&&super.doInitialSchematicComponentRender()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=t.layer??"top";if(i!=="top"&&i!=="bottom"){let s=this.getSubcircuit(),o=Am.parse({type:"pcb_component_invalid_layer_error",message:`Component cannot be placed on layer '${i}'. Components can only be placed on 'top' or 'bottom' layers.`,source_component_id:this.source_component_id,layer:i,subcircuit_id:s.subcircuit_id??void 0});e.pcb_component_invalid_layer_error.insert(o)}let r=e.pcb_component.insert({center:{x:t.pcbX??0,y:t.pcbY??0},width:2,height:3,layer:i==="top"||i==="bottom"?i:"top",rotation:t.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:t.doNotPlace??!1,obstructs_within_bounds:t.obstructsWithinBounds??!0});this.pcb_component_id=r.pcb_component_id}doInitialCreateTracesFromProps(){let{_parsedProps:e}=this;if(e.externallyConnectedPins)for(let[t,i]of e.externallyConnectedPins)this.add(new oo({from:`${this.getSubcircuitSelector()} > port.${t}`,to:`${this.getSubcircuitSelector()} > port.${i}`}));this._createTracesFromConnectionsProp()}doInitialSimulationRender(){let{db:e}=this.root,{pinAttributes:t}=this.props;if(!t)return;let i=null,r=null,s,o=this.selectAll("port");for(let p of o)for(let f of p.getNameAndAliases())if(t[f]){let y=t[f];y.providesPower&&(i=p,s=y.providesVoltage),y.providesGround&&(r=p)}if(!i||!r||s===void 0)return;let a=e.source_port.get(i.source_port_id);if(!a?.subcircuit_connectivity_map_key)return;let c=e.source_port.get(r.source_port_id);if(!c?.subcircuit_connectivity_map_key)return;let l=e.source_net.getWhere({subcircuit_connectivity_map_key:a.subcircuit_connectivity_map_key}),u=e.source_net.getWhere({subcircuit_connectivity_map_key:c.subcircuit_connectivity_map_key});!l||!u||e.simulation_voltage_source.insert({type:"simulation_voltage_source",positive_source_port_id:i.source_port_id,positive_source_net_id:l.source_net_id,negative_source_port_id:r.source_port_id,negative_source_net_id:u.source_net_id,voltage:s})}},rnt=class extends Y1{constructor(n){super(n)}get config(){return{...super.config,componentName:"Pinout",zodProps:gH}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=n.source_component.insert({ftype:"simple_pinout",name:this.name,manufacturer_part_number:e.manufacturerPartNumber,supplier_part_numbers:e.supplierPartNumbers});this.source_component_id=t.source_component_id}},f9=class extends Gn{constructor(){super(...arguments);d(this,"pos",this.portMap.pin1);d(this,"anode",this.portMap.pin1);d(this,"neg",this.portMap.pin2);d(this,"cathode",this.portMap.pin2)}get config(){let e={schottky:"schottky_diode",avalanche:"avalanche_diode",zener:"zener_diode",photodiode:"photodiode"},t=this.props.schottky?"schottky":this.props.avalanche?"avalanche":this.props.zener?"zener":this.props.photo?"photodiode":null;return{schematicSymbolName:t?e[t]:this.props.symbolName??"diode",componentName:"Diode",zodProps:UH,sourceFtype:"simple_diode"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_diode",name:this.name,manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},snt=class extends Gn{get config(){return{componentName:"fuse",schematicSymbolName:this.props.symbolName??"fuse",zodProps:bH,sourceFtype:Va.simple_fuse}}_getSchematicSymbolDisplayValue(){let n=this._parsedProps.currentRating,e=this._parsedProps.voltageRating,t=typeof n=="string"?parseFloat(n):n,i=typeof e=="string"?parseFloat(e):e;return`${gi(t)}A / ${gi(i)}V`}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=typeof e.currentRating=="string"?parseFloat(e.currentRating):e.currentRating,i=typeof e.voltageRating=="string"?parseFloat(e.voltageRating):e.voltageRating,r=n.source_component.insert({name:this.name,ftype:Va.simple_fuse,current_rating_amps:t,voltage_rating_volts:i,display_current_rating:`${gi(t)}A`,display_voltage_rating:`${gi(i)}V`});this.source_component_id=r.source_component_id}},ont=class extends Gn{constructor(){super(...arguments);d(this,"schematicDimensions",null)}get config(){return{schematicSymbolName:void 0,componentName:"Jumper",zodProps:o4,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let e=super._getSchematicPortArrangement();if(e&&Object.keys(e).length>0)return e;let t=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length),i=this._parsedProps.schDirection??"right";return{leftSize:i==="left"?t:0,rightSize:i==="right"?t:0}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=e.pcb_component.insert({center:{x:t.pcbX??0,y:t.pcbY??0},width:2,height:3,layer:t.layer??"top",rotation:t.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:t.doNotPlace??!1,obstructs_within_bounds:t.obstructsWithinBounds??!0});this.pcb_component_id=i.pcb_component_id}doInitialPcbTraceRender(){let{db:e}=this.root,t=e.pcb_port.list({pcb_component_id:this.pcb_component_id}),i={};for(let o=0;o<t.length;o++){let a=t[o],c=e.source_port.get(a.source_port_id),l="";if(typeof c?.pin_number=="number")l=c.pin_number.toString();else if(Array.isArray(c?.port_hints)){let u=c.port_hints.find(p=>/^(pin)?\d+$/.test(p));u&&(/^pin\d+$/.test(u)?l=u.replace(/^pin/,""):l=u)}i[l]=a.pcb_port_id}let r=e.pcb_trace.list({pcb_component_id:this.pcb_component_id}),s=o=>{if(o&&typeof o=="string"&&o.startsWith("{PIN")){let a=o.replace("{PIN","").replace("}","");return i[a]||o}return o};for(let o of r)if(o.route)for(let a of o.route)a.route_type==="wire"&&(a.start_pcb_port_id=s(a.start_pcb_port_id),a.end_pcb_port_id=s(a.end_pcb_port_id))}},ant=class extends Gn{constructor(){super(...arguments);d(this,"schematicDimensions",null)}_getPinNumberFromBridgedPinName(e){return this.selectOne(`port.${e}`,{type:"port"})?._parsedProps.pinNumber??null}get defaultInternallyConnectedPinNames(){if(this._parsedProps.bridged){let e=this.children.filter(t=>t.componentName==="Port").map(t=>t.name);return e.length>0?[e]:[]}return this._parsedProps.bridgedPins??[]}get config(){let e=this._parsedProps??this.props,t=e.pinCount;if(e.pinCount==null&&!e.footprint&&(t=2),e.pinCount==null){let s=(e.bridgedPins??[]).flat().map(l=>this._getPinNumberFromBridgedPinName(l)).filter(l=>l!==null),o=s.length>0?Math.max(...s):0,a=e.pinLabels?Object.keys(e.pinLabels).length:0,c=Math.max(o,a);(c===2||c===3)&&(t=c),t==null&&e.footprint&&[2,3].includes(this.getPortsFromFootprint().length)&&(t=this.getPortsFromFootprint().length)}let i="";t?i+=`solderjumper${t}`:i="solderjumper";let r=[];return Array.isArray(e.bridgedPins)&&e.bridgedPins.length>0?r=Array.from(new Set(e.bridgedPins.flat().map(s=>this._getPinNumberFromBridgedPinName(s)).filter(s=>s!==null))).sort((s,o)=>s-o):e.bridged&&t&&(r=Array.from({length:t},(s,o)=>o+1)),r.length>0&&(i+=`_bridged${r.join("")}`),{schematicSymbolName:e.symbolName??i,componentName:"SolderJumper",zodProps:xH,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let e=super._getSchematicPortArrangement();if(e&&Object.keys(e).length>0)return e;let t=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length);t==null&&!this._parsedProps.footprint&&(t=2);let i=this._parsedProps.schDirection??"right";return{leftSize:i==="left"?t:0,rightSize:i==="right"?t:0}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=e.pcb_component.insert({center:{x:t.pcbX??0,y:t.pcbY??0},width:2,height:3,layer:t.layer??"top",rotation:t.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:t.doNotPlace??!1,obstructs_within_bounds:t.obstructsWithinBounds??!0});this.pcb_component_id=i.pcb_component_id}doInitialPcbTraceRender(){let{db:e}=this.root,t=e.pcb_port.list({pcb_component_id:this.pcb_component_id}),i={};for(let o=0;o<t.length;o++){let a=t[o],c=e.source_port.get(a.source_port_id),l="";if(typeof c?.pin_number=="number")l=c.pin_number.toString();else if(Array.isArray(c?.port_hints)){let u=c.port_hints.find(p=>/^(pin)?\d+$/.test(p));u&&(/^pin\d+$/.test(u)?l=u.replace(/^pin/,""):l=u)}i[l]=a.pcb_port_id}let r=e.pcb_trace.list({pcb_component_id:this.pcb_component_id}),s=o=>{if(o&&typeof o=="string"&&o.startsWith("{PIN")){let a=o.replace("{PIN","").replace("}","");return i[a]||o}return o};for(let o of r)if(o.route)for(let a of o.route)a.route_type==="wire"&&(a.start_pcb_port_id=s(a.start_pcb_port_id),a.end_pcb_port_id=s(a.end_pcb_port_id))}},cnt=class extends Gn{constructor(){super(...arguments);d(this,"pos",this.portMap.pin1);d(this,"anode",this.portMap.pin1);d(this,"neg",this.portMap.pin2);d(this,"cathode",this.portMap.pin2)}get config(){let e={laser:"laser_diode"},t=this.props.laser?"laser":null;return{schematicSymbolName:t?e[t]:this.props.symbolName??"led",componentName:"Led",zodProps:GH,sourceFtype:"simple_led"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return this._parsedProps.schDisplayValue||this._parsedProps.color||void 0}getFootprinterString(){let e=super.getFootprinterString();return e&&this.props.color?`${e}_color(${this.props.color})`:e}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_led",name:this.name,wave_length:t.wavelength,color:t.color,symbol_display_value:this._getSchematicSymbolDisplayValue(),manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},lnt=class extends Gn{constructor(){super(...arguments);d(this,"pos",this.portMap.pin1);d(this,"positive",this.portMap.pin1);d(this,"neg",this.portMap.pin2);d(this,"negative",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"power_factor_meter_horz",componentName:"PowerSource",zodProps:oW,sourceFtype:"simple_power_source"}}initPorts(){this.add(new Vi({name:"pin1",pinNumber:1,aliases:["positive","pos"]})),this.add(new Vi({name:"pin2",pinNumber:2,aliases:["negative","neg"]}))}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_power_source",name:this.name,voltage:t.voltage,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},jLt=Kn.extend({voltage:Si.optional(),frequency:pr.optional(),peakToPeakVoltage:Si.optional(),waveShape:h.enum(["sinewave","square","triangle","sawtooth"]).optional(),phase:He.optional(),dutyCycle:h.number().optional()}),unt=class extends Gn{constructor(){super(...arguments);d(this,"terminal1",this.portMap.terminal1);d(this,"terminal2",this.portMap.terminal2)}get config(){return{componentName:"VoltageSource",schematicSymbolName:this.props.waveShape==="square"?"square_wave":"ac_voltmeter",zodProps:jLt,sourceFtype:"simple_voltage_source"}}runRenderPhaseForChildren(e){if(!e.startsWith("Pcb"))for(let t of this.children)t.runRenderPhaseForChildren(e),t.runRenderPhase(e)}doInitialPcbComponentRender(){}initPorts(){super.initPorts({additionalAliases:{pin1:["terminal1"],pin2:["terminal2"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_voltage_source",name:this.name,voltage:t.voltage,frequency:t.frequency,peak_to_peak_voltage:t.peakToPeakVoltage,wave_shape:t.waveShape,phase:t.phase,duty_cycle:t.dutyCycle,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialSimulationRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=this.portMap.terminal1,r=this.portMap.terminal2;e.simulation_voltage_source.insert({type:"simulation_voltage_source",is_dc_source:!1,terminal1_source_port_id:i.source_port_id,terminal2_source_port_id:r.source_port_id,voltage:t.voltage,frequency:t.frequency,peak_to_peak_voltage:t.peakToPeakVoltage,wave_shape:t.waveShape,phase:t.phase,duty_cycle:t.dutyCycle})}},m9=class extends Gn{constructor(){super(...arguments);d(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Resistor",schematicSymbolName:this.props.symbolName??"boxresistor",zodProps:wH,sourceFtype:"simple_resistor"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return`${gi(this._parsedProps.resistance)}\u03A9`}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.pullupFor,this.props.pullupTo,this.props.pulldownFor,this.props.pulldownTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.pullupFor&&this.props.pullupTo&&(this.add(new oo({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pullupFor})),this.add(new oo({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pullupTo}))),this.props.pulldownFor&&this.props.pulldownTo&&(this.add(new oo({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pulldownFor})),this.add(new oo({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pulldownTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_resistor",name:this.name,manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,resistance:t.resistance,display_resistance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}},BLt=["leftedge","rightedge","topedge","bottomedge","center"],pnt=class extends Te{get config(){return{componentName:"Constraint",zodProps:CH}}constructor(n){if(super(n),("xdist"in n||"ydist"in n)&&!("edgeToEdge"in n)&&!("centerToCenter"in n))throw new Error(`edgeToEdge, centerToCenter must be set for xDist or yDist for ${this}`);if("for"in n&&n.for.length<2)throw new Error(`"for" must have at least two selectors for ${this}`)}_getAllReferencedComponents(){let n=[],e=this.getPrimitiveContainer();function t(i){let r=i.split(" ").pop(),s=BLt.includes(r)?r:void 0,o=s?i.replace(` ${s}`,""):i,a=e.selectOne(o,{pcbPrimitive:!0});a&&n.push({selector:i,component:a,componentSelector:o,edge:s})}for(let i of["left","right","top","bottom"])i in this._parsedProps&&t(this._parsedProps[i]);if("for"in this._parsedProps)for(let i of this._parsedProps.for)t(i);return{componentsWithSelectors:n}}},hnt=class extends Te{constructor(){super(...arguments);d(this,"fabrication_note_rect_id",null)}get config(){return{componentName:"FabricationNoteRect",zodProps:ZH}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(t.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for FabricationNoteRect. Must be "top" or "bottom".`);let s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,o=this.getSubcircuit(),a=t.hasStroke??(t.strokeWidth!==void 0&&t.strokeWidth!==null),c=e.pcb_fabrication_note_rect.insert({pcb_component_id:s,layer:r,color:t.color,center:{x:t.pcbX??0,y:t.pcbY??0},width:t.width,height:t.height,stroke_width:t.strokeWidth??1,is_filled:t.isFilled??!1,has_stroke:a,is_stroke_dashed:t.isStrokeDashed??!1,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,corner_radius:t.cornerRadius??void 0});this.fabrication_note_rect_id=c.pcb_fabrication_note_rect_id}getPcbSize(){let{_parsedProps:e}=this;return{width:e.width,height:e.height}}},dnt=class extends Te{constructor(){super(...arguments);d(this,"fabrication_note_path_id",null)}get config(){return{componentName:"FabricationNotePath",zodProps:KH}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,t=this.getSubcircuit(),{_parsedProps:i}=this,r=i.layer??"top";if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenPath. Must be "top" or "bottom".`);let s=this._computePcbGlobalTransformBeforeLayout(),o=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=e.pcb_fabrication_note_path.insert({pcb_component_id:o,layer:r,color:i.color,route:i.route.map(c=>{let l=ze(s,{x:c.x,y:c.y});return{...c,x:l.x,y:l.y}}),stroke_width:i.strokeWidth??.1,subcircuit_id:t?.subcircuit_id??void 0});this.fabrication_note_path_id=a.pcb_fabrication_note_path_id}},fnt=class extends Te{get config(){return{componentName:"FabricationNoteText",zodProps:qH}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:n}=this.root,{_parsedProps:e}=this,t=this.getPrimitiveContainer(),i=this.getSubcircuit();n.pcb_fabrication_note_text.insert({anchor_alignment:e.anchorAlignment,anchor_position:{x:e.pcbX??0,y:e.pcbY??0},font:e.font??"tscircuit2024",font_size:e.fontSize??1,layer:"top",color:e.color,text:e.text??"",pcb_component_id:t.pcb_component_id,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}},mnt=class extends Te{constructor(){super(...arguments);d(this,"fabrication_note_dimension_id",null);d(this,"isPcbPrimitive",!0)}get config(){return{componentName:"FabricationNoteDimension",zodProps:JH}}_resolvePoint(e,t){if(typeof e=="string"){let s=this.getSubcircuit().selectOne(e);return s?s._getGlobalPcbPositionBeforeLayout():(this.renderError(`FabricationNoteDimension could not find selector "${e}"`),ze(t,{x:0,y:0}))}let i=typeof e.x=="string"?parseFloat(e.x):e.x,r=typeof e.y=="string"?parseFloat(e.y):e.y;return ze(t,{x:i,y:r})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=this._resolvePoint(t.from,i),s=this._resolvePoint(t.to,i),o=this.getSubcircuit(),a=this.getGroup(),{maybeFlipLayer:c}=this._getPcbPrimitiveFlippedHelpers(),l=c(t.layer??"top");if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for FabricationNoteDimension. Must be "top" or "bottom".`);let u=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,p=t.text??this._formatDistanceText({from:r,to:s,units:t.units??"mm"}),f=e.pcb_fabrication_note_dimension.insert({pcb_component_id:u,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:a?.pcb_group_id??void 0,layer:l,from:r,to:s,text:p,offset:t.offset,font:t.font??"tscircuit2024",font_size:t.fontSize??1,color:t.color,arrow_size:t.arrowSize??1});this.fabrication_note_dimension_id=f.pcb_fabrication_note_dimension_id}getPcbSize(){let e=this._computePcbGlobalTransformBeforeLayout(),t=this._resolvePoint(this._parsedProps.from,e),i=this._resolvePoint(this._parsedProps.to,e);return{width:Math.abs(i.x-t.x),height:Math.abs(i.y-t.y)}}_formatDistanceText({from:e,to:t,units:i}){let r=t.x-e.x,s=t.y-e.y,o=Math.sqrt(r*r+s*s),a=i==="in"?o/25.4:o,c=Math.round(a);if(Math.abs(a-c)<1e-9)return`${c}${i}`;let u=i==="in"?3:2;return`${i==="in"?Number(a.toFixed(u)).toString():a.toFixed(u)}${i}`}},_nt=class extends Te{constructor(){super(...arguments);d(this,"pcb_note_line_id",null);d(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteLine",zodProps:TW}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this.getSubcircuit(),r=this.getGroup(),s=this._computePcbGlobalTransformBeforeLayout(),o=ze(s,{x:t.x1,y:t.y1}),a=ze(s,{x:t.x2,y:t.y2}),c=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,l=e.pcb_note_line.insert({pcb_component_id:c,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:r?.pcb_group_id??void 0,x1:o.x,y1:o.y,x2:a.x,y2:a.y,stroke_width:t.strokeWidth??.1,color:t.color,is_dashed:t.isDashed});this.pcb_note_line_id=l.pcb_note_line_id}getPcbSize(){let{_parsedProps:e}=this;return{width:Math.abs(e.x2-e.x1),height:Math.abs(e.y2-e.y1)}}},ynt=class extends Te{constructor(){super(...arguments);d(this,"pcb_note_rect_id",null);d(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteRect",zodProps:PW}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=ze(i,{x:0,y:0}),s=this.getSubcircuit(),o=this.getGroup(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,c=e.pcb_note_rect.insert({pcb_component_id:a,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:o?.pcb_group_id??void 0,center:r,width:t.width,height:t.height,stroke_width:t.strokeWidth??.1,is_filled:t.isFilled??!1,has_stroke:t.hasStroke??!0,is_stroke_dashed:t.isStrokeDashed??!1,color:t.color,corner_radius:t.cornerRadius??void 0});this.pcb_note_rect_id=c.pcb_note_rect_id}getPcbSize(){let{_parsedProps:e}=this,t=typeof e.width=="string"?parseFloat(e.width):e.width,i=typeof e.height=="string"?parseFloat(e.height):e.height;return{width:t,height:i}}},gnt=class extends Te{constructor(){super(...arguments);d(this,"pcb_note_text_id",null);d(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteText",zodProps:SW}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=ze(i,{x:0,y:0}),s=this.getSubcircuit(),o=this.getGroup(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,c=e.pcb_note_text.insert({pcb_component_id:a,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:o?.pcb_group_id??void 0,font:t.font??"tscircuit2024",font_size:t.fontSize??1,text:t.text,anchor_position:r,anchor_alignment:t.anchorAlignment??"center",color:t.color});this.pcb_note_text_id=c.pcb_note_text_id}getPcbSize(){let{_parsedProps:e}=this,t=typeof e.fontSize=="string"?parseFloat(e.fontSize):e.fontSize??1,i=t*.6;return{width:e.text.length*i,height:t}}},xnt=class extends Te{constructor(){super(...arguments);d(this,"pcb_note_path_id",null);d(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNotePath",zodProps:kW}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=this.getSubcircuit(),s=this.getGroup(),o=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,a=t.route.map(l=>{let{x:u,y:p,...f}=l,y=typeof u=="string"?parseFloat(u):u,g=typeof p=="string"?parseFloat(p):p,x=ze(i,{x:y,y:g});return{...f,x:x.x,y:x.y}}),c=e.pcb_note_path.insert({pcb_component_id:o,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:s?.pcb_group_id??void 0,route:a,stroke_width:t.strokeWidth??.1,color:t.color});this.pcb_note_path_id=c.pcb_note_path_id}getPcbSize(){let{_parsedProps:e}=this;if(e.route.length===0)return{width:0,height:0};let t=e.route.map(c=>typeof c.x=="string"?parseFloat(c.x):c.x),i=e.route.map(c=>typeof c.y=="string"?parseFloat(c.y):c.y),r=Math.min(...t),s=Math.max(...t),o=Math.min(...i),a=Math.max(...i);return{width:s-r,height:a-o}}},bnt=class extends Te{constructor(){super(...arguments);d(this,"pcb_note_dimension_id",null);d(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteDimension",zodProps:EW}}_resolvePoint(e,t){if(typeof e=="string"){let s=this.getSubcircuit().selectOne(`.${e}`);return s?s._getGlobalPcbPositionBeforeLayout():(this.renderError(`PcbNoteDimension could not find selector "${e}"`),ze(t,{x:0,y:0}))}let i=typeof e.x=="string"?parseFloat(e.x):e.x,r=typeof e.y=="string"?parseFloat(e.y):e.y;return ze(t,{x:i,y:r})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._computePcbGlobalTransformBeforeLayout(),r=this._resolvePoint(t.from,i),s=this._resolvePoint(t.to,i),o=this.getSubcircuit(),a=this.getGroup(),c=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,l=t.text??this._formatDistanceText({from:r,to:s,units:t.units??"mm"}),u=e.pcb_note_dimension.insert({pcb_component_id:c,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:a?.pcb_group_id??void 0,from:r,to:s,text:l,font:t.font??"tscircuit2024",font_size:t.fontSize??1,color:t.color,arrow_size:t.arrowSize??1});this.pcb_note_dimension_id=u.pcb_note_dimension_id}getPcbSize(){let e=this._computePcbGlobalTransformBeforeLayout(),t=this._resolvePoint(this._parsedProps.from,e),i=this._resolvePoint(this._parsedProps.to,e);return{width:Math.abs(i.x-t.x),height:Math.abs(i.y-t.y)}}_formatDistanceText({from:e,to:t,units:i}){let r=t.x-e.x,s=t.y-e.y,o=Math.sqrt(r*r+s*s),a=i==="in"?o/25.4:o,c=Math.round(a);if(Math.abs(a-c)<1e-9)return`${c}${i}`;let u=i==="in"?3:2;return`${i==="in"?Number(a.toFixed(u)).toString():a.toFixed(u)}${i}`}},X1=(n,e)=>{let{injectionDb:t,normalComponent:i}=e;if(!i)return;let r=G_({componentName:i.name,componentRotation:"0deg"},t.toArray().filter(s=>"pcb_component_id"in s&&s.pcb_component_id===n.pcb_component_id));i.addAll(r)};function YLt(n,e){let{injectionDb:t,subcircuit:i,groupsMap:r}=e,s=t.pcb_component.getWhere({source_component_id:n.source_component_id}),o=t.cad_component.getWhere({source_component_id:n.source_component_id}),a=new m9({name:n.name,resistance:n.resistance});s&&X1(s,{...e,normalComponent:a}),n.source_group_id&&r?.has(n.source_group_id)?r.get(n.source_group_id).add(a):i.add(a)}function XLt(n,e){let{injectionDb:t,subcircuit:i}=e;if(n.source_component_id!==null)return;let r=t.pcb_port.getWhere({source_port_id:n.source_port_id}),s=new Vi({name:n.name,pinNumber:n.pin_number});i.add(s),s.source_port_id=n.source_port_id;let o=i.root;if(o&&r){let{db:a}=o,c=a.pcb_port.insert({pcb_component_id:void 0,layers:r.layers,subcircuit_id:i.subcircuit_id??void 0,pcb_group_id:i.getGroup()?.pcb_group_id??void 0,x:r.x,y:r.y,source_port_id:n.source_port_id,is_board_pinout:!1});s.pcb_port_id=c.pcb_port_id}}function ULt(n,e){let{subcircuit:t,groupsMap:i}=e,r=new _l({name:n.name});return r.source_group_id=n.source_group_id,t.add(r),i&&i.set(n.source_group_id,r),r}var VLt=(n,e)=>{if(!n||n.length===0)return;let{injectionDb:t}=e,i=n.map(r=>r.map(s=>{let o=t.source_port.get(s);return o?o.pin_number!==void 0&&o.pin_number!==null?`pin${o.pin_number}`:o.name:null}).filter(s=>s!==null)).filter(r=>r.length>0);return i.length>0?i:void 0},GLt=(n,e)=>{let{injectionDb:t,subcircuit:i,groupsMap:r}=e,s=t.pcb_component.getWhere({source_component_id:n.source_component_id}),o=t.schematic_component.getWhere({source_component_id:n.source_component_id}),a=t.cad_component.getWhere({source_component_id:n.source_component_id}),c=VLt(n.internally_connected_source_port_ids,e),l=new Y1({name:n.name,manufacturerPartNumber:n.manufacturer_part_number,supplierPartNumbers:n.supplier_part_numbers??void 0,pinLabels:o?.port_labels??void 0,schWidth:o?.size?.width,schHeight:o?.size?.height,schPinSpacing:o?.pin_spacing,schX:o?.center?.x,schY:o?.center?.y,layer:s?.layer,pcbX:s?.center?.x,pcbY:s?.center?.y,pcbRotation:s?.rotation,doNotPlace:s?.do_not_place,obstructsWithinBounds:s?.obstructs_within_bounds,internallyConnectedPins:c}),u=a?.footprinter_string??"soic8";u&&(Object.assign(l.props,{footprint:u}),Object.assign(l._parsedProps,{footprint:u}),a||l._addChildrenFromStringFootprint?.()),s&&X1(s,{...e,normalComponent:l}),n.source_group_id&&r?.has(n.source_group_id)?r.get(n.source_group_id).add(l):i.add(l)};function HLt(n,e){let{injectionDb:t,subcircuit:i,groupsMap:r}=e,s=t.pcb_component.getWhere({source_component_id:n.source_component_id}),o=t.cad_component.getWhere({source_component_id:n.source_component_id}),a=new d9({name:n.name,capacitance:n.capacitance});s&&X1(s,{...e,normalComponent:a}),n.source_group_id&&r?.has(n.source_group_id)?r.get(n.source_group_id).add(a):i.add(a)}var _9=class extends Gn{constructor(){super(...arguments);d(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Inductor",schematicSymbolName:this.props.symbolName??"inductor",zodProps:XH,sourceFtype:Va.simple_inductor}}_getSchematicSymbolDisplayValue(){return`${gi(this._parsedProps.inductance)}H`}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({name:this.name,ftype:Va.simple_inductor,inductance:t.inductance,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}};function WLt(n,e){let{injectionDb:t,subcircuit:i,groupsMap:r}=e,s=t.pcb_component.getWhere({source_component_id:n.source_component_id}),o=t.cad_component.getWhere({source_component_id:n.source_component_id}),a=new _9({name:n.name,inductance:n.inductance});s&&X1(s,{...e,normalComponent:a}),n.source_group_id&&r?.has(n.source_group_id)?r.get(n.source_group_id).add(a):i.add(a)}function qLt(n,e){let{injectionDb:t,subcircuit:i,groupsMap:r}=e,s=t.pcb_component.getWhere({source_component_id:n.source_component_id}),o=t.cad_component.getWhere({source_component_id:n.source_component_id}),a=new f9({name:n.name});s&&X1(s,{...e,normalComponent:a}),n.source_group_id&&r?.has(n.source_group_id)?r.get(n.source_group_id).add(a):i.add(a)}var vnt=class extends _l{constructor(n){super({...n,subcircuit:!0})}doInitialInflateSubcircuitCircuitJson(){let{circuitJson:n,children:e}=this._parsedProps;if(!n)return;let t=Ke(n);if(n&&e?.length>0)throw new Error("Subcircuit cannot have both circuitJson and children");let r={injectionDb:t,subcircuit:this,groupsMap:new Map},s=t.source_group.list();for(let c of s)ULt(c,r);let o=t.source_component.list();for(let c of o)switch(c.ftype){case"simple_resistor":YLt(c,r);break;case"simple_capacitor":HLt(c,r);break;case"simple_inductor":WLt(c,r);break;case"simple_diode":qLt(c,r);break;case"simple_chip":GLt(c,r);break;default:throw new Error(`No inflator implemented for source component ftype: "${c.ftype}"`)}let a=t.source_port.list();for(let c of a)XLt(c,r)}},wnt=class extends _l{constructor(n){super({...n,subcircuit:!0})}doInitialPcbPrimitiveRender(){if(super.doInitialPcbPrimitiveRender(),this.root?.pcbDisabled)return;let{db:n}=this.root,e=this._parsedProps;if(!this.pcb_group_id)return;let t=n.pcb_group.get(this.pcb_group_id),i=e.paddingLeft??e.padding??0,r=e.paddingRight??e.padding??0,s=e.paddingTop??e.padding??0,o=e.paddingBottom??e.padding??0;n.pcb_group.update(this.pcb_group_id,{width:(t.width??0)+i+r,height:(t.height??0)+s+o,center:{x:t.center.x+(r-i)/2,y:t.center.y+(s-o)/2}})}},Snt=class extends Te{constructor(){super(...arguments);d(this,"pcb_breakout_point_id",null);d(this,"matchedPort",null);d(this,"matchedNet",null);d(this,"isPcbPrimitive",!0)}get config(){return{componentName:"BreakoutPoint",zodProps:eW}}_matchConnection(){let{connection:e}=this._parsedProps,t=this.getSubcircuit();t&&(this.matchedPort=t.selectOne(e,{type:"port"}),this.matchedPort||(this.matchedNet=t.selectOne(e,{type:"net"})),!this.matchedPort&&!this.matchedNet&&this.renderError(`Could not find connection target "${e}"`))}_getSourceTraceIdForPort(e){let{db:t}=this.root;return t.source_trace.list().find(r=>r.connected_source_port_ids.includes(e.source_port_id))?.source_trace_id}_getSourceNetIdForPort(e){let{db:t}=this.root;return t.source_trace.list().find(r=>r.connected_source_port_ids.includes(e.source_port_id))?.connected_source_net_ids[0]}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root;this._matchConnection();let{pcbX:t=0,pcbY:i=0}=this._parsedProps,r=this.parent?.getGroup(),s=this.getSubcircuit();if(!r||!r.pcb_group_id)return;let o=e.pcb_breakout_point.insert({pcb_group_id:r.pcb_group_id,subcircuit_id:s?.subcircuit_id??void 0,source_port_id:this.matchedPort?.source_port_id??void 0,source_trace_id:this.matchedPort?this._getSourceTraceIdForPort(this.matchedPort):void 0,source_net_id:this.matchedNet?this.matchedNet.source_net_id:this.matchedPort?this._getSourceNetIdForPort(this.matchedPort):void 0,x:t,y:i});this.pcb_breakout_point_id=o.pcb_breakout_point_id}_getPcbCircuitJsonBounds(){let{pcbX:e=0,pcbY:t=0}=this._parsedProps;return{center:{x:e,y:t},bounds:{left:e,top:t,right:e,bottom:t},width:0,height:0}}_setPositionFromLayout(e){let{db:t}=this.root;this.pcb_breakout_point_id&&t.pcb_breakout_point.update(this.pcb_breakout_point_id,{x:e.x,y:e.y})}getPcbSize(){return{width:0,height:0}}},Pnt=class extends Te{constructor(){super(...arguments);d(this,"source_net_label_id")}get config(){return{componentName:"NetLabel",zodProps:DH}}_getAnchorSide(){let{_parsedProps:e}=this;if(e.anchorSide)return e.anchorSide;if(!this._resolveConnectsTo())return"right";let i=this._getGlobalSchematicPositionBeforeLayout(),r=this._getConnectedPorts();if(r.length===0)return"right";let s=r[0]._getGlobalSchematicPositionBeforeLayout(),o=s.x-i.x,a=s.y-i.y;if(Math.abs(o)>Math.abs(a)){if(o>0)return"right";if(o<0)return"left"}else{if(a>0)return"top";if(a<0)return"bottom"}return"right"}_getConnectedPorts(){let e=this._resolveConnectsTo();if(!e)return[];let t=[];for(let i of e){let r=this.getSubcircuit().selectOne(i);r&&t.push(r)}return t}computeSchematicPropsTransform(){let{_parsedProps:e}=this;if(e.schX===void 0&&e.schY===void 0){let t=this._getConnectedPorts();if(t.length>0){let i=t[0]._getGlobalSchematicPositionBeforeLayout(),r=ze(this.parent?.computeSchematicGlobalTransform?.()??Qi(),{x:0,y:0});return Nn(i.x-r.x,i.y-r.y)}}return super.computeSchematicPropsTransform()}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getSubcircuit().selectOne(`net.${this._getNetName()}`),s=t.anchorSide??"right",o=ml({anchor_position:i,anchor_side:s,text:t.net}),a=e.schematic_net_label.insert({text:t.net,source_net_id:r.source_net_id,anchor_position:i,center:o,anchor_side:this._getAnchorSide()});this.source_net_label_id=a.source_net_id}_resolveConnectsTo(){let{_parsedProps:e}=this,t=e.connectsTo??e.connection;if(Array.isArray(t))return t;if(typeof t=="string")return[t]}_getNetName(){let{_parsedProps:e}=this;return e.net}doInitialCreateNetsFromProps(){let{_parsedProps:e}=this;e.net&&KS(this,[`net.${e.net}`])}doInitialCreateTracesFromNetLabels(){if(this.root?.schematicDisabled)return;let e=this._resolveConnectsTo();if(e)for(let t of e)this.add(new oo({from:t,to:`net.${this._getNetName()}`}))}doInitialSchematicTraceRender(){if(!this.root?._featureMspSchematicTraceRouting||this.root?.schematicDisabled)return;let{db:e}=this.root,t=this._resolveConnectsTo();if(!t||t.length===0)return;let i=this._getGlobalSchematicPositionBeforeLayout(),r=this._getAnchorSide(),o={left:"x-",right:"x+",top:"y+",bottom:"y-"}[r],a=this.getSubcircuit().selectOne(`net.${this._getNetName()}`);for(let c of t){let l=this.getSubcircuit().selectOne(c,{type:"port"});if(!l||!l.schematic_port_id)continue;let u=!1;if(a?.source_net_id){let S=e.source_trace.list().find(P=>P.connected_source_net_ids?.includes(a.source_net_id)&&P.connected_source_port_ids?.includes(l.source_port_id??""));if(S&&(u=e.schematic_trace.list().some(P=>P.source_trace_id===S.source_trace_id)),u)continue}let p=l._getGlobalSchematicPositionAfterLayout(),f=QA(l.facingDirection??"right")??"x+",y=Wc({x:p.x,y:p.y,facingDirection:f},{x:i.x,y:i.y,facingDirection:o});if(!Array.isArray(y)||y.length<2)continue;let g=[];for(let S=0;S<y.length-1;S++)g.push({from:{x:y[S].x,y:y[S].y},to:{x:y[S+1].x,y:y[S+1].y}});let x,v;if(a?.source_net_id&&l.source_port_id){let S=e.source_trace.list().find(P=>P.connected_source_net_ids?.includes(a.source_net_id)&&P.connected_source_port_ids?.includes(l.source_port_id));x=S?.source_trace_id,v=S?.subcircuit_connectivity_map_key||e.source_net.get(a.source_net_id)?.subcircuit_connectivity_map_key}e.schematic_trace.insert({source_trace_id:x,edges:g,junctions:[],subcircuit_connectivity_map_key:v}),e.schematic_port.update(l.schematic_port_id,{is_connected:!0})}}},knt=class extends Te{constructor(){super(...arguments);d(this,"pcb_silkscreen_circle_id",null);d(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenCircle",zodProps:vW}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(t.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenCircle. Must be "top" or "bottom".`);let s=this._computePcbGlobalTransformBeforeLayout(),o=this.getSubcircuit(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,c=e.pcb_silkscreen_circle.insert({pcb_component_id:a,layer:r,center:{x:t.pcbX??0,y:t.pcbY??0},radius:t.radius,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,stroke_width:t.strokeWidth??.1});this.pcb_silkscreen_circle_id=c.pcb_silkscreen_circle_id}getPcbSize(){let{_parsedProps:e}=this,t=e.radius*2;return{width:t,height:t}}},Tnt=class extends Te{constructor(){super(...arguments);d(this,"pcb_silkscreen_rect_id",null);d(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenRect",zodProps:bW}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(t.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenRect. Must be "top" or "bottom".`);let s=this.getSubcircuit(),o=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=e.pcb_silkscreen_rect.insert({pcb_component_id:o,layer:r,center:{x:t.pcbX??0,y:t.pcbY??0},width:t.width,height:t.height,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this?.getGroup()?.pcb_group_id??void 0,stroke_width:t.strokeWidth??.1,is_filled:t.filled??!1,corner_radius:t.cornerRadius??void 0});this.pcb_silkscreen_rect_id=a.pcb_silkscreen_rect_id}getPcbSize(){let{_parsedProps:e}=this;return{width:e.width,height:e.height}}},Ent=class extends Te{constructor(){super(...arguments);d(this,"pcb_silkscreen_line_id",null);d(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenLine",zodProps:xW}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),r=i(t.layer??"top");if(r!=="top"&&r!=="bottom")throw new Error(`Invalid layer "${r}" for SilkscreenLine. Must be "top" or "bottom".`);let s=this.getSubcircuit(),o=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=e.pcb_silkscreen_line.insert({pcb_component_id:o,layer:r,x1:t.x1,y1:t.y1,x2:t.x2,y2:t.y2,stroke_width:t.strokeWidth??.1,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:s?.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_line_id=a.pcb_silkscreen_line_id}getPcbSize(){let{_parsedProps:e}=this,t=Math.abs(e.x2-e.x1),i=Math.abs(e.y2-e.y1);return{width:t,height:i}}},Mnt=class extends Te{constructor(e){super(e);d(this,"pcb_via_id",null);d(this,"matchedPort",null);d(this,"isPcbPrimitive",!0);d(this,"source_manually_placed_via_id",null);d(this,"subcircuit_connectivity_map_key",null);let t=this._getLayers();this._parsedProps.layers=t,this.initPorts()}get config(){return{componentName:"Via",zodProps:QH}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){let{_parsedProps:e}=this;return{width:e.outerDiameter,height:e.outerDiameter}}_getPcbCircuitJsonBounds(){let{db:e}=this.root,t=e.pcb_via.get(this.pcb_via_id),i=this.getPcbSize();return{center:{x:t.x,y:t.y},bounds:{left:t.x-i.width/2,top:t.y-i.height/2,right:t.x+i.width/2,bottom:t.y+i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(e){let{db:t}=this.root;t.pcb_via.update(this.pcb_via_id,{x:e.x,y:e.y})}_getLayers(){let{fromLayer:e="top",toLayer:t="bottom"}=this._parsedProps;return e===t?[e]:[e,t]}initPorts(){let e=this._parsedProps.layers;for(let i of e){let r=new Vi({name:i,layer:i});r.registerMatch(this),this.add(r)}let t=new Vi({name:"pin1"});t.registerMatch(this),this.add(t)}_getConnectedNetOrTrace(){let e=this._parsedProps.connectsTo;if(!e)return null;let t=this.getSubcircuit(),i=Array.isArray(e)?e:[e];for(let r of i)if(r.startsWith("net.")){let s=t.selectOne(r,{type:"net"});if(s)return s}return null}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalPcbPositionBeforeLayout(),r=this.getSubcircuit(),s=e.pcb_component.insert({center:i,width:t.outerDiameter,height:t.outerDiameter,layer:t.fromLayer??"top",rotation:0,source_component_id:this.source_component_id,subcircuit_id:r?.subcircuit_id??void 0,obstructs_within_bounds:!0});this.pcb_component_id=s.pcb_component_id}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=this.getGroup(),r=this.getSubcircuit(),s=e.source_manually_placed_via.insert({source_group_id:i?.source_group_id,source_net_id:t.net??"",subcircuit_id:r?.subcircuit_id??void 0});this.source_component_id=s.source_manually_placed_via_id}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalPcbPositionBeforeLayout(),r=this.getSubcircuit(),s=e.pcb_via.insert({x:i.x,y:i.y,hole_diameter:t.holeDiameter,outer_diameter:t.outerDiameter,layers:["bottom","top"],from_layer:t.fromLayer||"bottom",to_layer:t.toLayer||"top",subcircuit_id:r?.subcircuit_id??void 0,subcircuit_connectivity_map_key:this.subcircuit_connectivity_map_key??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,net_is_assignable:t.netIsAssignable??void 0});this.pcb_via_id=s.pcb_via_id}},Cnt=class extends Te{constructor(){super(...arguments);d(this,"isPcbPrimitive",!0)}get config(){return{componentName:"CopperPour",zodProps:iW}}getPcbSize(){return{width:0,height:0}}doInitialCreateNetsFromProps(){let{_parsedProps:e}=this;KS(this,[e.connectsTo])}doInitialPcbCopperPourRender(){this.root?.pcbDisabled||this._queueAsyncEffect("PcbCopperPourRender",async()=>{let{db:e}=this.root,{_parsedProps:t}=this,i=this.getSubcircuit().selectOne(t.connectsTo);if(!i||!i.source_net_id){this.renderError(`Net "${t.connectsTo}" not found for copper pour`);return}let r=this.getSubcircuit(),s=e.toArray().filter(p=>p.type==="source_net"&&p.name===i.name)[0]||"",o=t.clearance??.2,a=$Q(e.toArray(),{layer:t.layer,pour_connectivity_key:s.subcircuit_connectivity_map_key||"",pad_margin:t.padMargin??o,trace_margin:t.traceMargin??o,board_edge_margin:t.boardEdgeMargin??o,cutout_margin:t.cutoutMargin??o}),c=new DQ(a),{brep_shapes:l}=c.getOutput(),u=t.coveredWithSolderMask??!1;for(let p of l)e.pcb_copper_pour.insert({shape:"brep",layer:t.layer,brep_shape:p,source_net_id:i.source_net_id,subcircuit_id:r?.subcircuit_id??void 0,covered_with_solder_mask:u})})}},Int=class extends Gn{get config(){return{componentName:"Battery",schematicSymbolName:this.props.symbolName??"battery",zodProps:FH,sourceFtype:"simple_power_source"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=n.source_component.insert({name:this.name,ftype:"simple_power_source",capacity:e.capacity,supplier_part_numbers:e.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=t.source_component_id}},Nnt=class extends Gn{_getPcbRotationBeforeLayout(){let n=this.props.pcbOrientation==="vertical"?-90:0;return(super._getPcbRotationBeforeLayout()??0)+n}get config(){return{componentName:"PinHeader",zodProps:zH,shouldRenderAsSchematicBox:!0}}_getImpliedFootprintString(){let n=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:0),e=this._parsedProps.holeDiameter,t=this._parsedProps.platedDiameter,i=this._parsedProps.pitch,r=this._parsedProps.showSilkscreenPinLabels;if(n>0){let s;if(i)!e&&!t?s=`pinrow${n}_p${i}`:s=`pinrow${n}_p${i}_id${e}_od${t}`;else if(!e&&!t)s=`pinrow${n}`;else return null;return r!==!0&&(s+="_nopinlabels"),s}return null}initPorts(){let n=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:1);for(let e=1;e<=n;e++){let t=Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels[e-1]:this._parsedProps.pinLabels?.[`pin${e}`];if(t){let i=Array.isArray(t)?t[0]:t,r=Array.isArray(t)?t.slice(1):[];this.add(new Vi({pinNumber:e,name:i,aliases:[`pin${e}`,...r]}))}else this.add(new Vi({pinNumber:e,name:`pin${e}`}))}}_getSchematicPortArrangement(){let n=this._parsedProps.pinCount??1,e=this._parsedProps.schFacingDirection??this._parsedProps.facingDirection??"right",t=this._parsedProps.schPinArrangement;return e==="left"?{leftSide:{direction:t?.leftSide?.direction??"top-to-bottom",pins:t?.leftSide?.pins??Array.from({length:n},(i,r)=>`pin${r+1}`)}}:{rightSide:{direction:t?.rightSide?.direction??"top-to-bottom",pins:t?.rightSide?.pins??Array.from({length:n},(i,r)=>`pin${r+1}`)}}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=n.source_component.insert({ftype:"simple_pin_header",name:this.name,supplier_part_numbers:e.supplierPartNumbers,pin_count:e.pinCount,gender:e.gender,are_pins_interchangeable:!0});this.source_component_id=t.source_component_id}};function ZLt(n){switch(n){case"two_ground_pins":return"crystal_4pin";case"ground_pin":return"resonator";case"no_ground":return"crystal";default:return"crystal"}}var Ant=class extends Gn{get config(){return{componentName:"Resonator",schematicSymbolName:this.props.symbolName??ZLt(this.props.pinVariant),zodProps:TH,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=e.pinVariant||"no_ground",i=n.source_component.insert({ftype:"simple_resonator",name:this.name,frequency:e.frequency,load_capacitance:e.loadCapacitance,supplier_part_numbers:e.supplierPartNumbers,pin_variant:t,are_pins_interchangeable:t==="no_ground"||t==="ground_pin"});this.source_component_id=i.source_component_id}_getSchematicSymbolDisplayValue(){let n=`${gi(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${n} / ${gi(this._parsedProps.loadCapacitance)}F`:n}};function KLt(n){switch(n){case"three_pin":return"potentiometer3";case"two_pin":return"potentiometer2";default:return"potentiometer2"}}var Rnt=class extends Gn{get config(){return{componentName:"Potentiometer",schematicSymbolName:this.props.symbolName??KLt(this.props.pinVariant),zodProps:PH,shouldRenderAsSchematicBox:!1}}_getSchematicSymbolDisplayValue(){return`${gi(this._parsedProps.maxResistance)}\u03A9`}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=e.pinVariant||"two_pin",i=n.source_component.insert({ftype:"simple_potentiometer",name:this.name,max_resistance:e.maxResistance,pin_variant:t,are_pins_interchangeable:t==="two_pin"});this.source_component_id=i.source_component_id}},Ont=class extends Gn{get config(){return{componentName:"PushButton",schematicSymbolName:this.props.symbolName??"push_button_normally_open_momentary",zodProps:$H,sourceFtype:Va.simple_push_button}}get defaultInternallyConnectedPinNames(){return[]}initPorts(){super.initPorts({pinCount:2,ignoreSymbolPorts:!0});let n=_i[this._getSchematicSymbolNameOrThrow()],e=n.ports.find(l=>l.labels.includes("1")),t=n.ports.find(l=>l.labels.includes("2")),i=this.selectAll("port"),r=i.find(l=>l.props.pinNumber===1),s=i.find(l=>l.props.pinNumber===2),o=i.find(l=>l.props.pinNumber===3),a=i.find(l=>l.props.pinNumber===4),{internallyConnectedPins:c}=this._parsedProps;r.schematicSymbolPortDef=e,(!c||c.length===0)&&(s.schematicSymbolPortDef=t);for(let[l,u]of[[2,s],[3,o],[4,a]]){let p=c?.find(([y,g])=>y===`pin${l}`||g===`pin${l}`);if(!p){u.schematicSymbolPortDef=t;break}(p?.[0]===`pin${l}`?p[1]:p?.[0])!=="pin1"&&(u.schematicSymbolPortDef=t)}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=n.source_component.insert({name:this.name,ftype:Va.simple_push_button,supplier_part_numbers:e.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=t.source_component_id}},Lnt=class extends Gn{get config(){return{schematicSymbolName:this.props.symbolName??(this.props.pinVariant==="four_pin"?"crystal_4pin":"crystal"),componentName:"Crystal",zodProps:kH,sourceFtype:"simple_crystal"}}initPorts(){let n=this.props.pinVariant==="four_pin"?{pin1:["left1","1"],pin2:["top1","2","gnd1"],pin3:["right1","3"],pin4:["bottom1","4","gnd2"]}:{pin1:["pos","left"],pin2:["neg","right"]};super.initPorts({additionalAliases:n})}_getSchematicSymbolDisplayValue(){let n=`${gi(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${n} / ${gi(this._parsedProps.loadCapacitance)}F`:n}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=n.source_component.insert({name:this.name,ftype:"simple_crystal",frequency:e.frequency,load_capacitance:e.loadCapacitance,pin_variant:e.pinVariant||"two_pin",are_pins_interchangeable:(e.pinVariant||"two_pin")==="two_pin"});this.source_component_id=t.source_component_id}},Fnt=class extends Gn{constructor(){super(...arguments);d(this,"emitter",this.portMap.pin1);d(this,"collector",this.portMap.pin2);d(this,"base",this.portMap.pin3)}get config(){let e=this.props.type==="npn"?"npn_bipolar_transistor":"pnp_bipolar_transistor";return{componentName:"Transistor",schematicSymbolName:this.props.symbolName??e,zodProps:BH,sourceFtype:"simple_transistor",shouldRenderAsSchematicBox:!1}}initPorts(){let e={pin1:["collector","c"],pin2:["emitter","e"],pin3:["base","b"]};super.initPorts({pinCount:3,additionalAliases:e})}doInitialCreateNetsFromProps(){this._createNetsFromProps([...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,i=e.source_component.insert({ftype:"simple_transistor",name:this.name,transistor_type:t.type});this.source_component_id=i.source_component_id}},znt=class extends Gn{get config(){let n=this.props.mosfetMode==="depletion"?"d":"e",t=`${this.props.channelType}_channel_${n}_mosfet_transistor`;return{componentName:"Mosfet",schematicSymbolName:this.props.symbolName??t,zodProps:YH,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,t=n.source_component.insert({ftype:"simple_mosfet",name:this.name,mosfet_mode:e.mosfetMode,channel_type:e.channelType});this.source_component_id=t.source_component_id}};function JLt(n){return n.simSwitchFrequency!==void 0||n.simCloseAt!==void 0||n.simOpenAt!==void 0||n.simStartClosed!==void 0||n.simStartOpen!==void 0}var Dnt=class extends Gn{_getSwitchType(){let n=this._parsedProps;return n?n.dpdt?"dpdt":n.spst?"spst":n.spdt?"spdt":n.dpst?"dpst":n.type??"spst":"spst"}get config(){let n=this._getSwitchType(),e=this._parsedProps?.isNormallyClosed??!1,t={spst:e?"spst_normally_closed_switch":"spst_switch",spdt:e?"spdt_normally_closed_switch":"spdt_switch",dpst:e?"dpst_normally_closed_switch":"dpst_switch",dpdt:e?"dpdt_normally_closed_switch":"dpdt_switch"};return{componentName:"Switch",schematicSymbolName:this.props.symbolName??t[n],zodProps:WH,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:n}=this.root,e=this._parsedProps??{},t=n.source_component.insert({ftype:"simple_switch",name:this.name,are_pins_interchangeable:this._getSwitchType()==="spst"});this.source_component_id=t.source_component_id}doInitialSimulationRender(){let{_parsedProps:n}=this;if(!JLt(n))return;let{db:e}=this.root,t={type:"simulation_switch",source_component_id:this.source_component_id||""};n.simSwitchFrequency!==void 0&&(t.switching_frequency=pr.parse(n.simSwitchFrequency)),n.simCloseAt!==void 0&&(t.closes_at=ur.parse(n.simCloseAt)),n.simOpenAt!==void 0&&(t.opens_at=ur.parse(n.simOpenAt)),n.simStartOpen!==void 0&&(t.starts_closed=!n.simStartOpen),n.simStartClosed!==void 0&&(t.starts_closed=n.simStartClosed),e.simulation_switch.insert(t)}},ZA={HOLE_DIAMETER:.5,SMT_CIRCLE_DIAMETER:1.2,SMT_RECT_SIZE:2},$nt=class extends Gn{get config(){return{componentName:"TestPoint",schematicSymbolName:this.props.symbolName??"testpoint",zodProps:tW,sourceFtype:Va.simple_test_point}}_getPropsWithDefaults(){let{padShape:n,holeDiameter:e,footprintVariant:t,padDiameter:i,width:r,height:s}=this._parsedProps;return!t&&e&&(t="through_hole"),t??(t="through_hole"),n??(n="circle"),t==="pad"?n==="circle"?i??(i=ZA.SMT_CIRCLE_DIAMETER):n==="rect"&&(r??(r=ZA.SMT_RECT_SIZE),s??(s=r)):t==="through_hole"&&(e??(e=ZA.HOLE_DIAMETER)),{padShape:n,holeDiameter:e,footprintVariant:t,padDiameter:i,width:r,height:s}}_getImpliedFootprintString(){let{padShape:n,holeDiameter:e,footprintVariant:t,padDiameter:i,width:r,height:s}=this._getPropsWithDefaults();if(t==="through_hole")return`platedhole_d${e}`;if(t==="pad"){if(n==="circle")return`smtpad_circle_d${i}`;if(n==="rect")return`smtpad_rect_w${r}_h${s}`}throw new Error(`Footprint variant "${t}" with pad shape "${n}" not implemented`)}doInitialSourceRender(){let{db:n}=this.root,{_parsedProps:e}=this,{padShape:t,holeDiameter:i,footprintVariant:r,padDiameter:s,width:o,height:a}=this._getPropsWithDefaults(),c=n.source_component.insert({ftype:Va.simple_test_point,name:this.name,supplier_part_numbers:e.supplierPartNumbers,footprint_variant:r,pad_shape:t,pad_diameter:s,hole_diameter:i,width:o,height:a,are_pins_interchangeable:!0});this.source_component_id=c.source_component_id}},jnt=class extends Te{constructor(){super(...arguments);d(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicText",zodProps:dW}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalSchematicPositionBeforeLayout();e.schematic_text.insert({anchor:t.anchor??"center",text:t.text,font_size:t.fontSize,color:t.color||"#000000",position:{x:i.x,y:i.y},rotation:t.schRotation??0})}},Bnt=class extends Te{constructor(){super(...arguments);d(this,"isSchematicPrimitive",!0);d(this,"schematic_line_id")}get config(){return{componentName:"SchematicLine",zodProps:hW}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,s=e.schematic_line.insert({schematic_component_id:r,x1:t.x1+i.x,y1:t.y1+i.y,x2:t.x2+i.x,y2:t.y2+i.y,stroke_width:t.strokeWidth??eP,color:t.color??tP,is_dashed:!1,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_line_id=s.schematic_line_id}},Ynt=class extends Te{constructor(){super(...arguments);d(this,"isSchematicPrimitive",!0);d(this,"schematic_rect_id")}get config(){return{componentName:"SchematicRect",zodProps:pW}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,s=e.schematic_rect.insert({center:{x:i.x,y:i.y},width:t.width,height:t.height,stroke_width:t.strokeWidth??eP,color:t.color??tP,is_filled:t.isFilled,schematic_component_id:r,is_dashed:t.isDashed,rotation:t.rotation??0,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_rect_id=s.schematic_rect_id}},Xnt=class extends Te{constructor(){super(...arguments);d(this,"isSchematicPrimitive",!0);d(this,"schematic_arc_id")}get config(){return{componentName:"SchematicArc",zodProps:cW}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,s=e.schematic_arc.insert({schematic_component_id:r,center:{x:t.center.x+i.x,y:t.center.y+i.y},radius:t.radius,start_angle_degrees:t.startAngleDegrees,end_angle_degrees:t.endAngleDegrees,direction:t.direction,stroke_width:t.strokeWidth??eP,color:t.color??tP,is_dashed:t.isDashed,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_arc_id=s.schematic_arc_id}},Unt=class extends Te{constructor(){super(...arguments);d(this,"isSchematicPrimitive",!0);d(this,"schematic_circle_id")}get config(){return{componentName:"SchematicCircle",zodProps:uW}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this._getGlobalSchematicPositionBeforeLayout(),r=this.getPrimitiveContainer()?.parent?.schematic_component_id,s=e.schematic_circle.insert({schematic_component_id:r,center:{x:t.center.x+i.x,y:t.center.y+i.y},radius:t.radius,stroke_width:t.strokeWidth??eP,color:t.color??tP,is_filled:t.isFilled,fill_color:t.fillColor,is_dashed:t.isDashed,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_circle_id=s.schematic_circle_id}};function QLt({anchor:n,x:e,y:t,width:i,height:r,isInside:s}){switch(n){case"top_left":return{x:e,y:t+r,textAnchor:s?"top_left":"bottom_left"};case"top_center":return{x:e+i/2,y:t+r,textAnchor:s?"top_center":"bottom_center"};case"top_right":return{x:e+i,y:t+r,textAnchor:s?"top_right":"bottom_right"};case"center_left":return{x:e,y:t+r/2,textAnchor:s?"center_left":"center_right"};case"center":return{x:e+i/2,y:t+r/2,textAnchor:"center"};case"center_right":return{x:e+i,y:t+r/2,textAnchor:s?"center_right":"center_left"};case"bottom_left":return{x:e,y:t,textAnchor:s?"bottom_left":"top_left"};case"bottom_center":return{x:e+i/2,y:t,textAnchor:s?"bottom_center":"top_center"};case"bottom_right":return{x:e+i,y:t,textAnchor:s?"bottom_right":"top_right"};default:return{x:e+i/2,y:t+r,textAnchor:"center"}}}var Vnt=class extends Te{constructor(){super(...arguments);d(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicBox",zodProps:lW,shouldRenderAsSchematicBox:!0}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=.6,r=typeof t.padding=="number"?t.padding:0,s=typeof t.paddingTop=="number"?t.paddingTop:r,o=typeof t.paddingBottom=="number"?t.paddingBottom:r,a=typeof t.paddingLeft=="number"?t.paddingLeft:r,c=typeof t.paddingRight=="number"?t.paddingRight:r,l=t.overlay&&t.overlay.length>0,u=typeof t.width=="number"&&typeof t.height=="number",p,f,y,g,x,v;if(l){let P=t.overlay.map(et=>({selector:et,port:this.getSubcircuit().selectOne(et,{type:"port"})})).filter(({port:et})=>et!=null).map(({port:et})=>({position:et._getGlobalSchematicPositionAfterLayout()}));if(P.length===0)return;let T=P.map(et=>et.position.x),k=P.map(et=>et.position.y),C=Math.min(...T),E=Math.max(...T),N=Math.min(...k),I=Math.max(...k),A=E-C,R=I-N,j=A===0?i:0,B=R===0?i:0,G=a+j/2,U=c+j/2,H=s+B/2,Q=o+B/2,tt=C-G,V=E+U,ot=N-Q,nt=I+H;p=V-tt,f=nt-ot,y=tt+(t.schX??0),g=ot+(t.schY??0),x=y+p/2,v=g+f/2}else if(u){p=t.width,f=t.height;let S=this._getGlobalSchematicPositionBeforeLayout();x=S.x,v=S.y,y=x-p/2,g=v-f/2}else return;if(e.schematic_box.insert({height:f,width:p,x:y,y:g,is_dashed:t.strokeStyle==="dashed"}),t.title){let S=t.titleInside,P=.1,T=t.titleAlignment,k=QLt({anchor:T,x:y,y:g,width:p,height:f,isInside:S}),C,E,N=k.textAnchor;S?(C=T.includes("top")?-P:T.includes("bottom")?P:0,E=T.includes("left")?P:T.includes("right")?-P:0):(C=T.includes("top")?P:T.includes("bottom")?-P:0,E=T.includes("center_left")?-P:T.includes("center_right")?P:0);let I=k.x+E,A=k.y+C;e.schematic_text.insert({anchor:N,text:t.title,font_size:t.titleFontSize??.18,color:t.titleColor??"#000000",position:{x:I,y:A},rotation:0})}}},Gnt=class extends Te{constructor(){super(...arguments);d(this,"isSchematicPrimitive",!0);d(this,"schematic_table_id",null)}get config(){return{componentName:"SchematicTable",zodProps:fW}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,i=this.children.filter(f=>f.componentName==="SchematicRow");if(i.length===0)return;let r=[],s=0;for(let f of i){let y=f.children.filter(g=>g.componentName==="SchematicCell");s=Math.max(s,y.length)}for(let f=0;f<i.length;f++)r[f]=[];for(let f=0;f<i.length;f++){let g=i[f].children.filter(v=>v.componentName==="SchematicCell"),x=0;for(let v=0;v<g.length;v++){for(;r[f][x];)x++;let S=g[v],P=S._parsedProps.colSpan??1,T=S._parsedProps.rowSpan??1;for(let k=0;k<T;k++)for(let C=0;C<P;C++)r[f+k]||(r[f+k]=[]),r[f+k][x+C]=S;x+=P}}s=Math.max(0,...r.map(f=>f.length));let o=i.map((f,y)=>f._parsedProps.height??1),a=Array.from({length:s},(f,y)=>{let g=0;for(let x=0;x<i.length;x++){let v=r[x]?.[y];if(v){let S=v._parsedProps.text??v._parsedProps.children,P=v._parsedProps.width??(S?.length??2)*.5;P>g&&(g=P)}}return g||10}),c=this._getGlobalSchematicPositionBeforeLayout(),l=e.schematic_table.insert({anchor_position:c,column_widths:a,row_heights:o,cell_padding:t.cellPadding,border_width:t.borderWidth,anchor:t.anchor,subcircuit_id:this.getSubcircuit()?.subcircuit_id||"",schematic_component_id:this.parent?.schematic_component_id||""});this.schematic_table_id=l.schematic_table_id;let u=new Set,p=0;for(let f=0;f<i.length;f++){let y=0;for(let g=0;g<s;g++){let x=r[f]?.[g];if(x&&!u.has(x)){u.add(x);let v=x._parsedProps,S=v.rowSpan??1,P=v.colSpan??1,T=0;for(let C=0;C<P;C++)T+=a[g+C];let k=0;for(let C=0;C<S;C++)k+=o[f+C];e.schematic_table_cell.insert({schematic_table_id:this.schematic_table_id,start_row_index:f,end_row_index:f+S-1,start_column_index:g,end_column_index:g+P-1,text:v.text??v.children,center:{x:c.x+y+T/2,y:c.y-p-k/2},width:T,height:k,horizontal_align:v.horizontalAlign,vertical_align:v.verticalAlign,font_size:v.fontSize??t.fontSize,subcircuit_id:this.getSubcircuit()?.subcircuit_id||""})}a[g]&&(y+=a[g])}p+=o[f]}}},Hnt=class extends Te{constructor(){super(...arguments);d(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicRow",zodProps:mW}}},Wnt=class extends Te{constructor(){super(...arguments);d(this,"isSchematicPrimitive",!0);d(this,"canHaveTextChildren",!0)}get config(){return{componentName:"SchematicCell",zodProps:_W}}},qnt=class extends Te{constructor(){super(...arguments);d(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"Symbol",zodProps:LH}}},Znt=class extends Te{get config(){return{componentName:"AnalogSimulation",zodProps:jH}}doInitialSimulationRender(){let{db:n}=this.root,{duration:e,timePerStep:t}=this._parsedProps,i=e||10,r=t||.01;n.simulation_experiment.insert({name:"spice_transient_analysis",experiment_type:"spice_transient_analysis",end_time_ms:i,time_per_step:r})}},Knt=class extends Te{constructor(){super(...arguments);d(this,"simulation_voltage_probe_id",null)}get config(){return{componentName:"VoltageProbe",zodProps:aW}}doInitialSimulationRender(){let{db:e}=this.root,{connectsTo:t,name:i}=this._parsedProps,r=this.getSubcircuit();if(!r){this.renderError("VoltageProbe must be inside a subcircuit");return}let s=Array.isArray(t)?t:[t];if(s.length!==1){this.renderError("VoltageProbe must connect to exactly one port or net");return}let o=s[0],a=r.selectOne(o,{type:"port"}),c=a?null:r.selectOne(o,{type:"net"});if(c&&c.componentName!=="Net"){this.renderError(`VoltageProbe connection target "${o}" resolved to a non-net component "${c.componentName}".`);return}if(!a&&!c){this.renderError(`VoltageProbe could not find connection target "${o}"`);return}let{simulation_voltage_probe_id:l}=e.simulation_voltage_probe.insert({name:i??this.name,source_port_id:a?.source_port_id??void 0,source_net_id:c?.source_net_id??void 0,subcircuit_id:r.subcircuit_id||void 0});this.simulation_voltage_probe_id=l}},t7t={name:"@tscircuit/core",type:"module",version:"0.0.863",types:"dist/index.d.ts",main:"dist/index.js",module:"dist/index.js",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist"],repository:{type:"git",url:"https://github.com/tscircuit/core"},scripts:{build:"tsup-node index.ts --format esm --dts",format:"biome format . --write","measure-bundle":"howfat -r table .","pkg-pr-new-release":"bunx pkg-pr-new publish --comment=off --peerDeps","smoke-test:dist":"bun run scripts/smoke-tests/test-dist-simple-circuit.tsx","build:benchmarking":"bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist","build:benchmarking:watch":`chokidar "./{benchmarking,lib}/**/*.{ts,tsx}" -c 'bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist'`,"start:benchmarking":'concurrently "bun run build:benchmarking:watch" "live-server ./benchmarking-dist"',"generate-test-plan":"bun run scripts/generate-test-plan.ts"},devDependencies:{"@biomejs/biome":"^1.8.3","@resvg/resvg-js":"^2.6.2","@tscircuit/capacity-autorouter":"^0.0.140","@tscircuit/checks":"^0.0.85","@tscircuit/circuit-json-util":"^0.0.72","@tscircuit/common":"^0.0.20","@tscircuit/copper-pour-solver":"^0.0.14","@tscircuit/footprinter":"^0.0.236","@tscircuit/import-snippet":"^0.0.4","@tscircuit/infgrid-ijump-astar":"^0.0.33","@tscircuit/log-soup":"^1.0.2","@tscircuit/matchpack":"^0.0.16","@tscircuit/math-utils":"^0.0.29","@tscircuit/miniflex":"^0.0.4","@tscircuit/ngspice-spice-engine":"^0.0.2","@tscircuit/props":"^0.0.398","@tscircuit/schematic-autolayout":"^0.0.6","@tscircuit/schematic-match-adapt":"^0.0.16","@tscircuit/schematic-trace-solver":"^v0.0.45","@tscircuit/solver-utils":"^0.0.3","@types/bun":"^1.2.16","@types/debug":"^4.1.12","@types/react":"^19.1.8","@types/react-dom":"^19.1.6","@types/react-reconciler":"^0.28.9","bpc-graph":"^0.0.57","bun-match-svg":"0.0.12","calculate-elbow":"^0.0.12","chokidar-cli":"^3.0.0","circuit-json":"^0.0.307","circuit-json-to-bpc":"^0.0.13","circuit-json-to-connectivity-map":"^0.0.22","circuit-json-to-gltf":"^0.0.31","circuit-json-to-simple-3d":"^0.0.9","circuit-json-to-spice":"^0.0.16","circuit-to-svg":"^0.0.265",concurrently:"^9.1.2","connectivity-map":"^1.0.0",debug:"^4.3.6","eecircuit-engine":"^1.5.6",flatbush:"^4.5.0","graphics-debug":"^0.0.60",howfat:"^0.3.8","live-server":"^1.2.2","looks-same":"^9.0.1",minicssgrid:"^0.0.9","pkg-pr-new":"^0.0.37",poppygl:"^0.0.16",react:"^19.1.0","react-dom":"^19.1.0","schematic-symbols":"^0.0.202",spicey:"^0.0.10","ts-expect":"^1.3.0",tsup:"^8.2.4"},peerDependencies:{"@tscircuit/capacity-autorouter":"*","@tscircuit/checks":"*","@tscircuit/circuit-json-util":"*","@tscircuit/footprinter":"*","@tscircuit/infgrid-ijump-astar":"*","@tscircuit/math-utils":"*","@tscircuit/props":"*","@tscircuit/schematic-autolayout":"*","@tscircuit/schematic-match-adapt":"*","circuit-json-to-bpc":"*","bpc-graph":"*","@tscircuit/matchpack":"*","circuit-json":"*","circuit-json-to-connectivity-map":"*","schematic-symbols":"*",typescript:"^5.0.0"},dependencies:{"@flatten-js/core":"^1.6.2","@lume/kiwi":"^0.4.3","calculate-packing":"0.0.50","css-select":"5.1.0","format-si-unit":"^0.0.3",nanoid:"^5.0.7","performance-now":"^2.1.0","react-reconciler":"^0.32.0","transformation-matrix":"^2.16.1",zod:"^3.25.67"}},q_=class{constructor({platform:n,projectUrl:e}={}){d(this,"firstChild",null);d(this,"children");d(this,"db");d(this,"root",null);d(this,"isRoot",!0);d(this,"_schematicDisabledOverride");d(this,"pcbDisabled",!1);d(this,"pcbRoutingDisabled",!1);d(this,"_featureMspSchematicTraceRouting",!0);d(this,"name");d(this,"platform");d(this,"projectUrl");d(this,"_hasRenderedAtleastOnce",!1);d(this,"_eventListeners",{});this.children=[],this.db=Be([]),this.root=this,this.platform=n,this.projectUrl=e,this.pcbDisabled=n?.pcbDisabled??!1}get schematicDisabled(){return this._schematicDisabledOverride!==void 0?this._schematicDisabledOverride:this._getBoard()?._parsedProps?.schematicDisabled??!1}set schematicDisabled(n){this._schematicDisabledOverride=n}add(n){let e;(0,Jnt.isValidElement)(n)?e=Net(n):e=n,this.children.push(e)}setPlatform(n){this.platform={...this.platform,...n}}_getBoard(){let n=this.children.find(e=>e.componentName==="Board");if(n)return n}_guessRootComponent(){if(this.firstChild)return;if(this.children.length===0)throw new Error("Not able to guess root component: RootCircuit has no children (use circuit.add(...))");let n=this.children.filter(t=>t.lowercaseComponentName==="panel");if(n.length>1)throw new Error("Only one <panel> is allowed per circuit");if(n.length===1){if(this.children.length!==1)throw new Error("<panel> must be the root element of the circuit");this.firstChild=n[0];return}if(this.children.length===1&&this.children[0].isGroup){this.firstChild=this.children[0];return}let e=new _l({subcircuit:!0});e.parent=this,e.addAll(this.children),this.children=[e],this.firstChild=e}render(){this.firstChild||this._guessRootComponent();let{firstChild:n,db:e}=this;if(!n)throw new Error("RootCircuit has no root component");n.parent=this,n.runRenderCycle(),this._hasRenderedAtleastOnce=!0}async renderUntilSettled(){for(this.db.source_project_metadata.list()?.[0]||this.db.source_project_metadata.insert({software_used_string:`@tscircuit/core@${this.getCoreVersion()}`,...this.projectUrl?{project_url:this.projectUrl}:{}}),this.render();this._hasIncompleteAsyncEffects();)await new Promise(e=>setTimeout(e,100)),this.render();this.emit("renderComplete")}_hasIncompleteAsyncEffects(){return this.children.some(n=>n._hasIncompleteAsyncEffects()?!0:n.children.some(e=>e._hasIncompleteAsyncEffects()))}getCircuitJson(){return this._hasRenderedAtleastOnce||this.render(),this.db.toArray()}toJson(){return this.getCircuitJson()}async getSvg(n){let e=await Promise.resolve().then(()=>(Ktt(),Ztt)).catch(t=>{throw new Error(`To use circuit.getSvg, you must install the "circuit-to-svg" package.
252
252
 
253
- "${t.message}"`)});if(n.view==="pcb")return e.convertCircuitJsonToPcbSvg(this.getCircuitJson());if(n.view==="schematic")return e.convertCircuitJsonToSchematicSvg(this.getCircuitJson());throw new Error(`Invalid view: ${n.view}`)}getCoreVersion(){let[n,e,t]=t7t.version.split(".").map(Number);return`${n}.${e}.${t+1}`}async preview(n){let e=typeof n=="object"?n:{previewName:n};throw new Error("project.preview is not yet implemented")}computeSchematicGlobalTransform(){return Qi()}_computePcbGlobalTransformBeforeLayout(){return Qi()}selectAll(n){return this._guessRootComponent(),this.firstChild?.selectAll(n)??[]}selectOne(n,e){return this._guessRootComponent(),this.firstChild?.selectOne(n,e)??null}emit(n,...e){if(this._eventListeners[n])for(let t of this._eventListeners[n])t(...e)}on(n,e){this._eventListeners[n]||(this._eventListeners[n]=[]),this._eventListeners[n].push(e)}removeListener(n,e){this._eventListeners[n]&&(this._eventListeners[n]=this._eventListeners[n].filter(t=>t!==e))}enableDebug(n){typeof n=="string"?r9.default.enable(n):(n===null||n===!1)&&r9.default.disable()}getClientOrigin(){return typeof window<"u"&&window.location?window.location.origin:typeof self<"u"&&self.location?self.location.origin:""}},e7t=q_,n7t=q_,i7t=n=>{let[e,t]=X_.default.useState(!0),[i,r]=X_.default.useState(null),[s,o]=X_.default.useState(),[a,c]=X_.default.useState();return X_.default.useEffect(()=>{t(!0),r(null),n&&setTimeout(()=>{try{let l=new q_;l.add(n),o(l),c(l.toJson())}catch(l){r(l)}t(!1)},1)},[n]),{isLoading:e,error:i,circuit:s,circuitJson:a}},Z_=(n,e)=>(t,i)=>{let r=[];Array.isArray(e)?r.push(...e.flat()):typeof e=="object"&&r.push(...Object.values(e).flat(),...Object.keys(e));let s=o=>{if(o?.name&&o.name!==t)throw new Error(`Component name mismatch. Hook name: ${t}, Component prop name: ${o.name}`);let a={...i,...o,name:t},c=[];for(let l of r)if(a[l]){let u=`.${t} > .${l}`,p=a[l];c.push({from:u,to:p}),delete a[l]}return(0,Id.jsxs)(Id.Fragment,{children:[(0,Id.jsx)(n,{...a}),c.map((l,u)=>(0,Id.jsx)("trace",{...l},u))]})};for(let o of r)s[o]=`.${t} > .${o}`;return s},r7t=Z_(n=>(0,Qnt.jsx)("capacitor",{...n}),MH),s7t=n=>Z_(e=>(0,tit.jsx)("chip",{pinLabels:n,...e}),n),o7t=Z_(n=>(0,eit.jsx)("diode",{...n}),VH),a7t=Z_(n=>(0,nit.jsx)("led",{...n}),HH),c7t=Z_(n=>(0,iit.jsx)("resistor",{...n}),SH),l7t=new Proxy(n=>new Proxy({},{get:(e,t)=>`.${n} > .${t}`}),{get:(n,e)=>{let t=(...i)=>{let r=i[0];return new Proxy({},{get:(s,o)=>`.${e} > .${o}`})};return new Proxy(t,{get:(i,r)=>e==="net"?`net.${r}`:e==="subcircuit"?new Proxy({},{get:(s,o)=>new Proxy({},{get:(a,c)=>`subcircuit.${r} > .${o} > .${c}`})}):`.${e} > .${r}`,apply:(i,r,s)=>e==="net"?new Proxy({},{get:(o,a)=>`net.${a}`}):new Proxy({},{get:(o,a)=>{let c=`.${e} > .${a}`;return["U","J","CN"].some(u=>e.startsWith(u))?c:new Proxy(new String(c),{get:(u,p)=>typeof p=="symbol"||p==="toString"?()=>c:`.${e} > .${a} > .${p}`})}})})}});Iet(ket);Iet({Bug:Y1});var Sit=Ht(Hs(),1);var sit=n=>{let e=n.match(/:[RC]_(\d{4})_/);if(e||(e=n.match(/:(SOIC-\d+|SOT-\d+|SOD-\d+|SSOP-\d+|TSSOP-\d+|QFP-\d+|QFN-\d+)/),e))return e[1]};var y9=n=>n.includes("cap")?n.replace(/cap/g,""):n;var oit=n=>{if(n){if(n.startsWith("kicad:")){let e=sit(n);return e?y9(e):n}return y9(n)}};var g9=new Map,Tr=async(n,e)=>{let t=new URLSearchParams({...e,json:"true"}).toString();if(g9.has(t))return g9.get(t);let r=await(await fetch(`https://jlcsearch.tscircuit.com/${n}/list?${t}`)).json();return g9.set(t,r),r},Er=n=>n?[...n].sort((e,t)=>Number(t.is_basic??!1)-Number(e.is_basic??!1)):[],ait={findPart:async({sourceComponent:n,footprinterString:e})=>{let t=oit(e);if(n.type==="source_component"&&n.ftype==="simple_resistor"){let{resistors:i}=await Tr("resistors",{resistance:n.resistance,package:t});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_capacitor"){let{capacitors:i}=await Tr("capacitors",{capacitance:n.capacitance,package:t});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_pin_header"){let i;e?.includes("_p")&&(i=Number(e.split("_p")[1]));let{headers:r}=await Tr("headers",i?{pitch:i,num_pins:n.pin_count,gender:n.gender}:{num_pins:n.pin_count,gender:n.gender});return{jlcpcb:Er(r).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_potentiometer"){let{potentiometers:i}=await Tr("potentiometers",{resistance:n.max_resistance,package:t});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_diode"){let{diodes:i}=await Tr("diodes",{package:t});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_chip"){let{chips:i}=await Tr("chips",{package:t});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_transistor"){let{transistors:i}=await Tr("transistors",{package:t,transistor_type:n.transistor_type});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_power_source"){let{power_sources:i}=await Tr("power_sources",{voltage:n.voltage,package:t});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_inductor"){let{inductors:i}=await Tr("inductors",{inductance:n.inductance,package:t});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_crystal"){let{crystals:i}=await Tr("crystals",{frequency:n.frequency,load_capacitance:n.load_capacitance,package:t});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_mosfet"){let{mosfets:i}=await Tr("mosfets",{package:t,mosfet_mode:n.mosfet_mode,channel_type:n.channel_type});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_resonator"){let{resonators:i}=await Tr("resonators",{frequency:n.frequency,package:t});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_switch"){let{switches:i}=await Tr("switches",{switch_type:n.type,package:t});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_led"){let{leds:i}=await Tr("leds",{package:t});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_fuse"){let{fuses:i}=await Tr("fuses",{package:t});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}return{}}};var pit=Ht(cit(),1);J();var _it=Ht(An(),1),yit=Ht(An(),1),xi=h.tuple([h.coerce.number(),h.coerce.number()]),x7t=h.tuple([h.number(),h.number(),h.number()]),aP=h.union([xi,x7t]),b7t=h.object({kind:h.literal("arc"),start:xi,mid:xi,end:xi}),v7t=h.union([xi,b7t]),hit=h.object({at:aP,size:xi,layer:h.string(),layers:h.array(h.string()),roundrect_rratio:h.number(),uuid:h.string()}).partial(),w7t=h.object({key:h.string(),val:h.string(),attributes:hit}),rP=h.object({oval:h.boolean().default(!1),width:h.number().optional(),height:h.number().optional(),offset:xi.optional()}),dit=h.object({name:h.string(),pad_type:h.enum(["thru_hole","smd","np_thru_hole","connect"]),pad_shape:h.enum(["roundrect","circle","rect","oval","trapezoid","custom"]),at:aP,drill:h.union([h.number(),h.array(h.any()),rP]).transform(n=>typeof n=="number"?{oval:!1,width:n,height:n}:"oval"in n?n:n.length===2?{oval:!1,width:Number.parseFloat(n[0]),height:Number.parseFloat(n[0]),offset:xi.parse(n[1].slice(1))}:n.length===3||n.length===4?{oval:n[0]==="oval",width:Number.parseFloat(n[1]),height:Number.parseFloat(n[2]),offset:n[3]?xi.parse(n[3].slice(1)):void 0}:n).pipe(rP),size:h.union([h.array(h.number()).length(2).transform(([n,e])=>({width:n,height:e})),h.object({width:h.number(),height:h.number()})]),layers:h.array(h.string()).optional(),roundrect_rratio:h.number().optional(),uuid:h.string().optional()}),fit=h.object({name:h.string(),pad_type:h.enum(["thru_hole","smd","np_thru_hole","connect"]),pad_shape:h.enum(["roundrect","circle","rect","oval","trapezoid","custom"]),at:aP,size:xi,drill:h.union([h.number(),h.array(h.any()),rP]).transform(n=>typeof n=="number"?{oval:!1,width:n,height:n}:"oval"in n?n:n.length===2?{oval:!1,width:Number.parseFloat(n[0]),height:Number.parseFloat(n[0]),offset:xi.parse(n[1].slice(1))}:n.length===3||n.length===4?{oval:n[0]==="oval",width:Number.parseFloat(n[1]),height:Number.parseFloat(n[2]),offset:n[3]?xi.parse(n[3].slice(1)):void 0}:n).pipe(rP).optional(),layers:h.array(h.string()).optional(),roundrect_rratio:h.number().optional(),chamfer_ratio:h.number().optional(),solder_paste_margin:h.number().optional(),solder_paste_margin_ratio:h.number().optional(),clearance:h.number().optional(),zone_connection:h.union([h.literal(0).describe("Pad is not connect to zone"),h.literal(1).describe("Pad is connected to zone using thermal relief"),h.literal(2).describe("Pad is connected to zone using solid fill")]).optional(),thermal_width:h.number().optional(),thermal_gap:h.number().optional(),uuid:h.string().optional()}),mit=h.object({font:h.object({size:xi,thickness:h.number().optional()})}).partial(),S7t=h.object({fp_text_type:h.literal("user"),text:h.string(),at:aP,layer:h.string(),uuid:h.string().optional(),effects:mit.partial()}),P7t=h.object({start:xi,mid:xi,end:xi,stroke:h.object({width:h.number(),type:h.string()}),layer:h.string(),uuid:h.string().optional()}),k7t=h.object({center:xi,end:xi,stroke:h.object({width:h.number(),type:h.string()}),fill:h.string().optional(),layer:h.string(),uuid:h.string().optional()}),T7t=h.object({pts:h.array(v7t),stroke:h.object({width:h.number(),type:h.string()}).optional(),width:h.number().optional(),layer:h.string(),uuid:h.string().optional(),fill:h.string().optional()}).transform(n=>({...n,width:void 0,stroke:n.stroke??{width:n.width}})),E7t=h.object({start:xi,end:xi,stroke:h.object({width:h.number(),type:h.string()}).optional(),width:h.number().optional(),layer:h.string(),uuid:h.string().optional()}).transform(n=>({...n,width:void 0,stroke:n.stroke??{width:n.width}})),lit=h.object({footprint_name:h.string(),version:h.string().optional(),generator:h.string().optional(),generator_version:h.string().optional(),layer:h.string(),descr:h.string().default(""),tags:h.array(h.string()).optional(),properties:h.array(w7t),fp_lines:h.array(E7t),fp_texts:h.array(S7t),fp_arcs:h.array(P7t),fp_circles:h.array(k7t).optional(),fp_polys:h.array(T7t).optional(),pads:h.array(fit),holes:h.array(dit).optional()}),sP=(n,e)=>{if(e==="effects"&&Array.isArray(n)){let t={};for(let i of n)if(i[0]==="font"){let r={};for(let s of i.slice(1))s.length===2?r[s[0].valueOf()]=Number.parseFloat(s[1].valueOf()):r[s[0].valueOf()]=s.slice(1).map(o=>Number.parseFloat(o.valueOf()));t.font=r}return mit.parse(t)}if(e==="pts")return n.map(t=>{let i=t[0]?.valueOf?.()??t[0];if(i==="xy")return t.slice(1).map(r=>Number.parseFloat(r.valueOf()));if(i==="arc"){let r={kind:"arc"};for(let s of t.slice(1)){let o=s[0].valueOf();r[o]=s.slice(1).map(a=>Number.parseFloat(a.valueOf()))}return r}return t});if(e==="stroke"){let t={};for(let i of n){let r=i[0].valueOf();t[r]=sP(i.slice(1),r)}return t}return e==="at"||e==="size"||e==="start"||e==="mid"||e==="end"?(Array.isArray(n)?n:[n]).map(i=>i?.valueOf?.()??i).filter(i=>typeof i=="number"||typeof i=="string"&&/^[-+]?\d*\.?\d+(e[-+]?\d+)?$/i.test(i)).map(i=>typeof i=="number"?i:Number.parseFloat(i)):e==="tags"?n.map(t=>t.valueOf()):e==="generator_version"||e==="version"?n[0].valueOf():n.length===2?n.valueOf():e==="uuid"?Array.isArray(n)?n[0].valueOf():n.valueOf():/^[\d\.]+$/.test(n)&&!Number.isNaN(Number.parseFloat(n))?Number.parseFloat(n):Array.isArray(n)&&n.length===1?n[0].valueOf():Array.isArray(n)?n.map(t=>t.valueOf()):n},$e=(n,e)=>{for(let t of n)if(Array.isArray(t)&&t[0]===e)return sP(t.slice(1),e)},x9=(0,_it.default)("kicad-mod-converter"),M7t=n=>{let e=(0,pit.default)(n),t=e[1].valueOf(),i={},r=Object.entries(lit.shape).filter(([T,k])=>k._def.typeName==="ZodString"||T==="tags").map(([T])=>T);for(let T of e.slice(2)){if(!r.includes(T[0]))continue;let k=T[0].valueOf(),C=sP(T.slice(1),k);i[k]=C}let s=e.slice(2).filter(T=>T[0]==="property").map(T=>{let k=T[1].valueOf(),C=T[2].valueOf(),E=hit.parse(T.slice(3).reduce((N,I)=>{let A=I[0].valueOf();return N[A]=sP(I.slice(1),A),N},{}));return{key:k,val:C,attributes:E}}),o=e.slice(2).filter(T=>T[0]==="pad"),a=[];for(let T of o){let k=$e(T,"at"),C=$e(T,"size"),E=$e(T,"drill"),N=$e(T,"layers");if(Array.isArray(N)?N=N.map(j=>j.valueOf()):typeof N=="string"?N=[N]:N||(N=[]),!N.includes("F.Cu")){x9(`Skipping pad without F.Cu layer: layers=${N.join(", ")}`);continue}let I=$e(T,"roundrect_rratio"),A=$e(T,"uuid"),R={name:T[1].valueOf(),pad_type:T[2].valueOf(),pad_shape:T[3].valueOf(),at:k,drill:E,size:C,layers:N,roundrect_rratio:I,uuid:A};x9(`attempting to parse pad: ${JSON.stringify(R,null," ")}`),a.push(fit.parse(R))}let c=e.slice(2).filter(T=>T[0]==="fp_text"),l=[];for(let T of c){let k=T[2].valueOf(),C=$e(T,"at"),E=$e(T,"layer"),N=$e(T,"uuid"),I=$e(T,"effects");l.push({fp_text_type:"user",text:k,at:C,layer:E,uuid:N,effects:I})}let u=[],p=e.slice(2).filter(T=>T[0]==="fp_line");for(let T of p){let k=$e(T,"start"),C=$e(T,"end"),E=$e(T,"stroke"),N=$e(T,"layer"),I=$e(T,"uuid");u.push({start:k,end:C,stroke:E,layer:N,uuid:I})}let f=[],y=e.slice(2).filter(T=>T[0]==="fp_arc");for(let T of y){let k=$e(T,"start"),C=$e(T,"mid"),E=$e(T,"end"),N=$e(T,"stroke"),I=$e(T,"layer"),A=$e(T,"uuid");!k||!E||!C||!N||!I||f.push({start:k,mid:C,end:E,stroke:N,layer:I,uuid:A})}let g=[],x=e.slice(2).filter(T=>T[0]==="fp_circle");for(let T of x){let k=$e(T,"center"),C=$e(T,"end"),E=$e(T,"stroke"),N=$e(T,"fill"),I=$e(T,"layer"),A=$e(T,"uuid");!k||!C||!E||!I||g.push({center:k,end:C,stroke:E,fill:N,layer:I,uuid:A})}let v=[],S=e.slice(2).filter(T=>T[0]==="fp_poly");for(let T of S){let k=$e(T,"pts"),C=$e(T,"stroke"),E=$e(T,"width"),N=$e(T,"layer"),I=$e(T,"uuid"),A=$e(T,"fill"),R=C;!R&&typeof E=="number"?R={width:E,type:"solid"}:R&&typeof R=="object"&&typeof E=="number"&&R.width===void 0&&(R={...R,width:E}),v.push({pts:k,stroke:R,layer:N,uuid:I,fill:A})}let P=[];for(let T of e.slice(2)){if(T[0]!=="pad"||T[2]?.valueOf?.()!=="thru_hole")continue;let k=T[1]?.valueOf?.(),C=T[2]?.valueOf?.(),E=T[3]?.valueOf?.(),N=$e(T,"at"),I=$e(T,"drill"),A=$e(T,"size");Array.isArray(A)&&(A[0]==="size"&&(A=A.slice(1)),A={width:Number(A[0]),height:Number(A[1])});let R=$e(T,"uuid"),j=$e(T,"roundrect_rratio"),B=$e(T,"layers");Array.isArray(B)?B=B.map(U=>U.valueOf()):typeof B=="string"?B=[B]:B||(B=[]);let G={name:k,pad_type:C,pad_shape:E,at:N,drill:I,size:A,layers:B,roundrect_rratio:j,uuid:R};x9(`attempting to parse holes: ${JSON.stringify(G,null,2)}`),P.push(dit.parse(G))}return lit.parse({footprint_name:t,...i,properties:s,fp_lines:u,fp_texts:l,fp_arcs:f,fp_circles:g,pads:a,holes:P,fp_polys:v})},U1=Math.PI*2,uit=n=>{let e=n%U1;return e<0&&(e+=U1),e},oP=(n,e)=>{let t=uit(n),r=uit(e)-t;return r<0&&(r+=U1),r};function git(n,e,t){let i={x:(n.x+e.x)/2,y:(n.y+e.y)/2},r={x:(e.x+t.x)/2,y:(e.y+t.y)/2},s=-(n.x-e.x)/(n.y-e.y),o=-(e.x-t.x)/(e.y-t.y),a=(i.y-r.y+o*r.x-s*i.x)/(o-s),c=i.y+s*(a-i.x);return{x:a,y:c}}function xit(n,e){return Math.sqrt((n.x-e.x)**2+(n.y-e.y)**2)}function J_(n,e){return Math.atan2(e.y-n.y,e.x-n.x)}var S9=(n,e,t)=>{let i=git(n,e,t),r=xit(i,n),s=J_(i,n),o=J_(i,e),a=J_(i,t),c=oP(s,o),l=oP(s,a),u=l;return c>l&&(u=l-U1),Math.abs(r*u)};function P9(n,e,t,i){let r=git(n,e,t),s=xit(r,n),o=J_(r,n),a=J_(r,e),c=J_(r,t),l=oP(o,a),u=oP(o,c),p=u;l>u&&(p=u-U1);let f=[];for(let y=0;y<=i;y++){let g=o+y/i*p,x=r.x+s*Math.cos(g),v=r.y+s*Math.sin(g);f.push({x,y:v})}return f}var yl=n=>Array.isArray(n)?{x:n[0],y:n[1]}:n,b9=(n,e,t=1e-4)=>Math.abs(n.x-e.x)<t&&Math.abs(n.y-e.y)<t,C7t=n=>{let e=[],t=new Set;for(let i=0;i<n.length;i++){if(t.has(i))continue;let r=[n[i]];t.add(i);let s=n[i].end,o=!0;for(;o;){if(o=!1,r.length>1&&b9(s,r[0].start)){e.push(r);break}for(let a=0;a<n.length;a++)if(!t.has(a)){if(b9(s,n[a].start)){r.push(n[a]),t.add(a),s=n[a].end,o=!0;break}else if(b9(s,n[a].end)){n[a].type==="arc"?r.push({...n[a],reversed:!0}):r.push({...n[a],start:n[a].end,end:n[a].start}),t.add(a),s=n[a].start,o=!0;break}}if(!o){for(let a=r.length-1;a>=0;a--){let c=n.indexOf(r[a]);c!==-1&&t.delete(c)}break}}}return e},I7t=n=>{let e=[];for(let t of n)if(t.type==="line")e.push(t.start);else if(t.type==="arc"&&t.mid){let i=S9(t.start,t.mid,t.end),r=Math.max(3,Math.ceil(i)),s=P9(t.start,t.mid,t.end,r);t.reversed&&(s=s.reverse()),e.push(...s.slice(0,-1))}return e};function N7t(n){if(!Array.isArray(n))return null;let e=n.find(o=>o.layer?.toLowerCase()==="f.silks"&&(o.text?.includes("${REFERENCE}")||o.fp_text_type?.toLowerCase()==="reference"||o.text?.match(/^R\d+|C\d+|U\d+/))),t=e||n.find(o=>o.layer?.toLowerCase()==="f.fab"&&(o.text?.includes("${REFERENCE}")||o.fp_text_type?.toLowerCase()==="reference")),i=e||t;if(!i?.effects?.font?.size)return null;let[r,s]=i.effects.font.size;return s??r??1}var A7t=n=>n*Math.PI/180,v9=(n,e,t)=>{let i=A7t(t),r=Math.cos(i),s=Math.sin(i);return{x:n*r-e*s,y:n*s+e*r}},R7t=n=>{let e=[...new Map(n.map(u=>[`${u.x},${u.y}`,u])).values()];if(e.length!==4)return null;let t=e.map(u=>u.x),i=e.map(u=>u.y),r=[...new Set(t)],s=[...new Set(i)];if(r.length!==2||s.length!==2)return null;let[o,a]=r.sort((u,p)=>u-p),[c,l]=s.sort((u,p)=>u-p);return o===void 0||a===void 0||c===void 0||l===void 0?null:{x:(o+a)/2,y:(c+l)/2,width:a-o,height:l-c}},O7t=n=>{if(!n)return!1;let e=n.toLowerCase();return e!=="no"&&e!=="none"&&e!=="outline"},w9=n=>n&&Array.isArray(n)&&n.length>=3&&typeof n[2]=="number"?n[2]:0,Ur=n=>{let e=(n%360+360)%360;return e===90||e===270},K_=(0,yit.default)("kicad-mod-converter"),Ls=n=>{switch(n.toLowerCase()){case"f.cu":case"f.fab":case"f.silks":case"edge.cuts":return"top";case"b.cu":case"b.fab":case"b.silks":return"bottom"}},L7t=async n=>{let{fp_lines:e,fp_texts:t,fp_arcs:i,fp_circles:r,pads:s,properties:o,holes:a,fp_polys:c}=n,l=[];l.push({type:"source_component",source_component_id:"source_component_0",supplier_part_numbers:{}}),l.push({type:"schematic_component",schematic_component_id:"schematic_component_0",source_component_id:"source_component_0",center:{x:0,y:0},rotation:0,size:{width:0,height:0}});let u=new Set;for(let V of s)V.name&&u.add(V.name);if(a)for(let V of a)V.name&&u.add(V.name);let p=0,f=new Map;for(let V of u){let ot=`source_port_${p++}`;f.set(V,ot),l.push({type:"source_port",source_port_id:ot,source_component_id:"source_component_0",name:V,port_hints:[V]}),l.push({type:"schematic_port",schematic_port_id:`schematic_port_${p++}`,source_port_id:ot,schematic_component_id:"schematic_component_0",center:{x:0,y:0}})}let y=Number.POSITIVE_INFINITY,g=Number.NEGATIVE_INFINITY,x=Number.POSITIVE_INFINITY,v=Number.NEGATIVE_INFINITY;for(let V of s){let ot=V.at[0],nt=-V.at[1],et=V.size[0],ht=V.size[1];y=Math.min(y,ot-et/2),g=Math.max(g,ot+et/2),x=Math.min(x,nt-ht/2),v=Math.max(v,nt+ht/2)}let S="pcb_component_0";l.push({type:"pcb_component",source_component_id:"source_component_0",pcb_component_id:S,layer:"top",center:{x:0,y:0},rotation:0,width:Number.isFinite(y)?g-y:0,height:Number.isFinite(x)?v-x:0});let P=0,T=new Map;for(let V of u){let ot=`pcb_port_${P++}`,nt=f.get(V);T.set(V,ot);let et=0,ht=0,dt=["top","bottom"],St=s.find(Pt=>Pt.name===V);if(St)et=St.at[0],ht=-St.at[1],dt=St.layers?St.layers.map(Pt=>Ls(Pt)).filter(Boolean):["top","bottom"];else if(a){let Pt=a.find(ut=>ut.name===V);Pt&&(et=Pt.at[0],ht=-Pt.at[1],dt=Pt.layers?Pt.layers.map(ut=>Ls(ut)).filter(Boolean):["top","bottom"])}l.push({type:"pcb_port",pcb_port_id:ot,source_port_id:nt,pcb_component_id:S,x:et,y:ht,layers:dt})}let k=0,C=0,E=0;for(let V of s)if(V.pad_type==="smd"){let ot=w9(V.at),nt=Ur(ot)?V.size[1]:V.size[0],et=Ur(ot)?V.size[0]:V.size[1],ht=V.name?T.get(V.name):void 0;l.push({type:"pcb_smtpad",pcb_smtpad_id:`pcb_smtpad_${k++}`,shape:"rect",x:V.at[0],y:-V.at[1],width:nt,height:et,layer:Ls(V.layers?.[0]??"F.Cu"),pcb_component_id:S,port_hints:[V.name],pcb_port_id:ht})}else if(V.pad_type==="thru_hole"){if(V.pad_shape==="rect"){let ot=w9(V.at),nt=Ur(ot)?V.size[1]:V.size[0],et=Ur(ot)?V.size[0]:V.size[1],ht=V.drill?.offset?.[0]??0,dt=V.drill?.offset?.[1]??0,St=v9(ht,dt,ot),Pt=V.name?T.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${C++}`,shape:"circular_hole_with_rect_pad",hole_shape:"circle",pad_shape:"rect",x:V.at[0],y:-V.at[1],hole_offset_x:St.x,hole_offset_y:-St.y,hole_diameter:V.drill?.width,rect_pad_width:nt,rect_pad_height:et,layers:["top","bottom"],pcb_component_id:S,port_hints:[V.name],pcb_port_id:Pt})}else if(V.pad_shape==="circle"){let ot=V.name?T.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${C++}`,shape:"circle",x:V.at[0],y:-V.at[1],outer_diameter:V.size[0],hole_diameter:V.drill?.width,layers:["top","bottom"],pcb_component_id:S,port_hints:[V.name],pcb_port_id:ot})}else if(V.pad_shape==="oval"){let ot=V.name?T.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${C++}`,shape:"pill",x:V.at[0],y:-V.at[1],outer_width:V.size[0],outer_height:V.size[1],hole_width:V.drill?.width,hole_height:V.drill?.height,layers:["top","bottom"],pcb_component_id:S,port_hints:[V.name],pcb_port_id:ot})}}else V.pad_type==="np_thru_hole"&&l.push({type:"pcb_hole",pcb_hole_id:`pcb_hole_${E++}`,x:V.at[0],y:-V.at[1],hole_diameter:V.drill?.width,pcb_component_id:S});if(a)for(let V of a){let ot=V.layers?.some(pt=>pt.endsWith(".Cu")||pt==="*.Cu"),nt=w9(V.at),et=V.drill?.offset?.[0]??0,ht=V.drill?.offset?.[1]??0,dt=v9(et,ht,nt),St=V.at[0]+dt.x,Pt=-(V.at[1]+dt.y),ut=V.drill?.width??0,Y=V.size?.width??ut,q=V.roundrect_rratio??0,rt=q>0?Math.min(Ur(nt)?V.size?.height??Y:V.size?.width??Y,Ur(nt)?V.size?.width??Y:V.size?.height??Y)/2*q:0;if(ot)if(V.pad_shape==="rect"){let pt=V.name?T.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${C++}`,shape:"circular_hole_with_rect_pad",hole_shape:"circle",pad_shape:"rect",x:V.at[0],y:-V.at[1],hole_offset_x:dt.x,hole_offset_y:-dt.y,hole_diameter:ut,rect_pad_width:Ur(nt)?V.size?.height??Y:V.size?.width??Y,rect_pad_height:Ur(nt)?V.size?.width??Y:V.size?.height??Y,rect_border_radius:rt,port_hints:[V.name],layers:["top","bottom"],pcb_component_id:S,pcb_port_id:pt})}else if(V.pad_shape==="oval"){let pt=V.name?T.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${C++}`,shape:"pill",x:St,y:Pt,outer_width:Ur(nt)?V.size?.height??Y:V.size?.width??Y,outer_height:Ur(nt)?V.size?.width??Y:V.size?.height??Y,hole_width:Ur(nt)?V.drill?.height??ut:V.drill?.width??ut,hole_height:Ur(nt)?V.drill?.width??ut:V.drill?.height??ut,port_hints:[V.name],layers:["top","bottom"],pcb_component_id:S,pcb_port_id:pt})}else if(V.pad_shape==="roundrect"){let pt=V.name?T.get(V.name):void 0,yt=V.drill?.offset?.[0]??0,Z=V.drill?.offset?.[1]??0,ct=v9(yt,Z,nt),Mt=Ur(nt)?V.size?.height??Y:V.size?.width??Y,Lt=Ur(nt)?V.size?.width??Y:V.size?.height??Y;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${C++}`,shape:"circular_hole_with_rect_pad",hole_shape:"circle",pad_shape:"rect",x:St,y:Pt,hole_offset_x:ct.x,hole_offset_y:-ct.y,hole_diameter:ut,rect_pad_width:Mt,rect_pad_height:Lt,rect_border_radius:rt,port_hints:[V.name],layers:["top","bottom"],pcb_component_id:S,pcb_port_id:pt})}else{let pt=V.name?T.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${C++}`,shape:"circle",x:St,y:Pt,outer_diameter:Y,hole_diameter:ut,port_hints:[V.name],layers:["top","bottom"],pcb_component_id:S,pcb_port_id:pt})}else l.push({type:"pcb_hole",pcb_hole_id:`pcb_hole_${E++}`,x:St,y:Pt,hole_diameter:Y,hole_shape:"circle",pcb_component_id:S})}let N=[];for(let V of e)V.layer.toLowerCase()==="edge.cuts"&&N.push({type:"line",start:{x:V.start[0],y:V.start[1]},end:{x:V.end[0],y:V.end[1]},strokeWidth:V.stroke.width});for(let V of i)V.layer.toLowerCase()==="edge.cuts"&&N.push({type:"arc",start:{x:V.start[0],y:V.start[1]},mid:{x:V.mid[0],y:V.mid[1]},end:{x:V.end[0],y:V.end[1]},strokeWidth:V.stroke.width});let I=C7t(N),A=0;for(let V of I){let ot=I7t(V);ot.length>=3&&l.push({type:"pcb_cutout",pcb_cutout_id:`pcb_cutout_${A++}`,shape:"polygon",points:ot.map(nt=>({x:nt.x,y:-nt.y})),pcb_component_id:S})}let R=0,j=0,B=0,G=0;for(let V of e){let ot=[{x:V.start[0],y:-V.start[1]},{x:V.end[0],y:-V.end[1]}],nt=V.layer.toLowerCase();nt==="f.cu"?l.push({type:"pcb_trace",pcb_trace_id:`pcb_trace_${R++}`,pcb_component_id:S,layer:Ls(V.layer),route:ot,thickness:V.stroke.width}):nt==="f.silks"?l.push({type:"pcb_silkscreen_path",pcb_silkscreen_path_id:`pcb_silkscreen_path_${j++}`,pcb_component_id:S,layer:"top",route:ot,stroke_width:V.stroke.width}):nt==="edge.cuts"?K_("Skipping Edge.Cuts fp_line (converted to pcb_cutout)",V.layer):nt==="f.fab"?l.push({type:"pcb_fabrication_note_path",fabrication_note_path_id:`fabrication_note_path_${B++}`,pcb_component_id:S,layer:"top",route:ot,stroke_width:V.stroke.width,port_hints:[]}):nt.startsWith("user.")?l.push({type:"pcb_note_line",pcb_note_line_id:`pcb_note_line_${G++}`,pcb_component_id:S,x1:V.start[0],y1:-V.start[1],x2:V.end[0],y2:-V.end[1],stroke_width:V.stroke.width}):K_("Unhandled layer for fp_line",V.layer)}if(c)for(let V of c){let ot=[],nt=Pt=>{!Number.isFinite(Pt.x)||!Number.isFinite(Pt.y)||ot.push(Pt)};for(let Pt of V.pts){if(Array.isArray(Pt)){nt({x:Pt[0],y:-Pt[1]});continue}if(Pt&&typeof Pt=="object"&&"kind"in Pt){if(Pt.kind==="arc"){let ut=yl(Pt.start),Y=yl(Pt.mid),q=yl(Pt.end),rt=S9(ut,Y,q),pt=Math.max(8,Math.ceil(rt)),yt=Math.max(2,Math.ceil(rt/.1)),Z=P9(ut,Y,q,yt).map(ct=>({x:ct.x,y:-ct.y}));for(let ct of Z)nt(ct)}continue}}let et=ot,dt=et.length>2&&et[0].x===et[et.length-1].x&&et[0].y===et[et.length-1].y?et.slice(0,-1):et;if(et.length===0)continue;let St=V.stroke?.width??0;if(V.layer.endsWith(".Cu")){let Pt=R7t(dt);Pt?l.push({type:"pcb_smtpad",pcb_smtpad_id:`pcb_smtpad_${k++}`,shape:"rect",x:Pt.x,y:Pt.y,width:Pt.width,height:Pt.height,layer:Ls(V.layer),pcb_component_id:S}):O7t(V.fill)?dt.length>=3?l.push({type:"pcb_smtpad",pcb_smtpad_id:`pcb_smtpad_${k++}`,shape:"polygon",points:dt,layer:Ls(V.layer),pcb_component_id:S}):dt.length>=2&&l.push({type:"pcb_trace",pcb_trace_id:`pcb_trace_${R++}`,pcb_component_id:S,layer:Ls(V.layer),route:dt,thickness:St}):dt.length>=2&&l.push({type:"pcb_trace",pcb_trace_id:`pcb_trace_${R++}`,pcb_component_id:S,layer:Ls(V.layer),route:dt,thickness:St})}else V.layer.endsWith(".SilkS")?l.push({type:"pcb_silkscreen_path",pcb_silkscreen_path_id:`pcb_silkscreen_path_${j++}`,pcb_component_id:S,layer:Ls(V.layer),route:et,stroke_width:St}):V.layer.endsWith(".Fab")?l.push({type:"pcb_fabrication_note_path",fabrication_note_path_id:`fabrication_note_path_${B++}`,pcb_component_id:S,layer:Ls(V.layer),route:dt,stroke_width:St,port_hints:[]}):K_("Unhandled layer for fp_poly",V.layer)}let U=0;for(let V of i){let ot=V.layer.toLowerCase();if(ot==="edge.cuts"){K_("Skipping Edge.Cuts fp_arc (converted to pcb_cutout)",V.layer);continue}let nt=yl(V.start),et=yl(V.mid),ht=yl(V.end),dt=S9(nt,et,ht),St=P9(nt,et,ht,Math.ceil(dt));if(ot.startsWith("user.")){l.push({type:"pcb_note_path",pcb_note_path_id:`pcb_note_path_${U++}`,pcb_component_id:S,route:St.map(ut=>({x:ut.x,y:-ut.y})),stroke_width:V.stroke.width});continue}let Pt=Ls(V.layer);if(!Pt){K_("Unable to convert layer for fp_arc",V.layer);continue}l.push({type:"pcb_silkscreen_path",pcb_silkscreen_path_id:`pcb_silkscreen_path_${j++}`,layer:Pt,pcb_component_id:S,route:St.map(ut=>({x:ut.x,y:-ut.y})),stroke_width:V.stroke.width})}if(r)for(let V of r){let ot=V.layer.toLowerCase(),nt=yl(V.center),et=yl(V.end),ht=Math.sqrt((et.x-nt.x)**2+(et.y-nt.y)**2),dt=Math.max(16,Math.ceil(2*Math.PI*ht)),St=[];for(let Pt=0;Pt<=dt;Pt++){let ut=Pt/dt*2*Math.PI;St.push({x:nt.x+ht*Math.cos(ut),y:nt.y+ht*Math.sin(ut)})}ot.startsWith("user.")&&l.push({type:"pcb_note_path",pcb_note_path_id:`pcb_note_path_${U++}`,pcb_component_id:S,route:St.map(Pt=>({x:Pt.x,y:-Pt.y})),stroke_width:V.stroke.width})}for(let V of t){let ot=Ls(V.layer);V.layer.endsWith(".SilkS")?l.push({type:"pcb_silkscreen_text",layer:ot,font:"tscircuit2024",font_size:V.effects?.font?.size[0]??1,pcb_component_id:S,anchor_position:{x:V.at[0],y:-V.at[1]},anchor_alignment:"center",text:V.text}):V.layer.endsWith(".Fab")?l.push({type:"pcb_fabrication_note_text",layer:ot,font:"tscircuit2024",font_size:V.effects?.font?.size[0]??1,pcb_component_id:S,anchor_position:{x:V.at[0],y:-V.at[1]},anchor_alignment:"center",text:V.text}):K_("Unhandled layer for fp_text",V.layer)}let H=o.find(V=>V.key==="Reference"),Q=o.find(V=>V.key==="Value"),tt=[H,Q].filter(V=>V&&!!V.val);for(let V of tt){let ot=V.attributes.at;if(!ot)continue;let et=V.attributes.layer?.toLowerCase()?.endsWith(".fab"),ht=N7t(t);l.push({type:et?"pcb_fabrication_note_text":"pcb_silkscreen_text",layer:"top",font:"tscircuit2024",font_size:ht,pcb_component_id:S,anchor_position:{x:ot[0],y:-ot[1]},anchor_alignment:"center",text:V.val})}return l},bit=async n=>{let e=M7t(n);return await L7t(e)};var vit=async n=>{try{return(await import(n)).default}catch{console.log(`Failed to load ${n} locally, trying CDN fallback...`);try{let t=await fetch(`https://cdn.jsdelivr.net/npm/${n}/+esm`);if(!t.ok)throw new Error(`Failed to fetch ${n} from CDN: ${t.statusText}`);let i=await t.text(),r=new Blob([i],{type:"application/javascript"}),s=URL.createObjectURL(r);try{let{default:o}=await import(s);return o}finally{URL.revokeObjectURL(s)}}catch(t){throw console.error(`CDN fallback for ${n} also failed:`,t),t}}};var F7t="https://kicad-mod-cache.tscircuit.com",cP=null,wit=()=>({partsEngine:ait,spiceEngineMap:{ngspice:{simulate:async n=>{if(!cP){let e=await vit("@tscircuit/ngspice-spice-engine").catch(t=>{throw new Error("Could not load ngspice engine from local node_modules or CDN fallback.",{cause:t})});e&&(cP=await e())}if(!cP)throw new Error("Could not load ngspice engine from local node_modules or CDN fallback.");return cP.simulate(n)}}},footprintLibraryMap:{kicad:async n=>{let e=`${F7t}/${n}`,t=`${e}.circuit.json`,r=await(await fetch(t)).json(),s=Array.isArray(r)?r.filter(a=>a?.type==="pcb_silkscreen_text"?a?.text==="REF**":!0):r,o=`${e}.wrl`;return{footprintCircuitJson:s,cadModel:{wrlUrl:o,modelUnitToMmScale:2.54}}}},footprintFileParserMap:{kicad_mod:{loadFromUrl:async n=>{let e=await fetch(n).then(i=>i.text()),t=await bit(e);return{footprintCircuitJson:Array.isArray(t)?t:[t]}}}}});var k9=Ht(An(),1),M0e=(0,k9.default)("tsci:eval:execution-context");function lP(n,e={}){globalThis.React=Sit;let t=e.platform||wit(),i=e.projectConfig?{...t,...e.projectConfig}:t;i.partsEngineDisabled&&(i.partsEngine=void 0);let r=new q_({platform:i});e.name&&(r.name=e.name),e.debugNamespace&&r.enableDebug(e.debugNamespace);let s=[];return{fsMap:{},entrypoint:"",logger:{info:o=>{s.push({msg:o})},getLogs:()=>s,stringifyLogs:()=>s.map(o=>o.msg).join(`
253
+ "${t.message}"`)});if(n.view==="pcb")return e.convertCircuitJsonToPcbSvg(this.getCircuitJson());if(n.view==="schematic")return e.convertCircuitJsonToSchematicSvg(this.getCircuitJson());throw new Error(`Invalid view: ${n.view}`)}getCoreVersion(){let[n,e,t]=t7t.version.split(".").map(Number);return`${n}.${e}.${t+1}`}async preview(n){let e=typeof n=="object"?n:{previewName:n};throw new Error("project.preview is not yet implemented")}computeSchematicGlobalTransform(){return Qi()}_computePcbGlobalTransformBeforeLayout(){return Qi()}selectAll(n){return this._guessRootComponent(),this.firstChild?.selectAll(n)??[]}selectOne(n,e){return this._guessRootComponent(),this.firstChild?.selectOne(n,e)??null}emit(n,...e){if(this._eventListeners[n])for(let t of this._eventListeners[n])t(...e)}on(n,e){this._eventListeners[n]||(this._eventListeners[n]=[]),this._eventListeners[n].push(e)}removeListener(n,e){this._eventListeners[n]&&(this._eventListeners[n]=this._eventListeners[n].filter(t=>t!==e))}enableDebug(n){typeof n=="string"?r9.default.enable(n):(n===null||n===!1)&&r9.default.disable()}getClientOrigin(){return typeof window<"u"&&window.location?window.location.origin:typeof self<"u"&&self.location?self.location.origin:""}},e7t=q_,n7t=q_,i7t=n=>{let[e,t]=X_.default.useState(!0),[i,r]=X_.default.useState(null),[s,o]=X_.default.useState(),[a,c]=X_.default.useState();return X_.default.useEffect(()=>{t(!0),r(null),n&&setTimeout(()=>{try{let l=new q_;l.add(n),o(l),c(l.toJson())}catch(l){r(l)}t(!1)},1)},[n]),{isLoading:e,error:i,circuit:s,circuitJson:a}},Z_=(n,e)=>(t,i)=>{let r=[];Array.isArray(e)?r.push(...e.flat()):typeof e=="object"&&r.push(...Object.values(e).flat(),...Object.keys(e));let s=o=>{if(o?.name&&o.name!==t)throw new Error(`Component name mismatch. Hook name: ${t}, Component prop name: ${o.name}`);let a={...i,...o,name:t},c=[];for(let l of r)if(a[l]){let u=`.${t} > .${l}`,p=a[l];c.push({from:u,to:p}),delete a[l]}return(0,Id.jsxs)(Id.Fragment,{children:[(0,Id.jsx)(n,{...a}),c.map((l,u)=>(0,Id.jsx)("trace",{...l},u))]})};for(let o of r)s[o]=`.${t} > .${o}`;return s},r7t=Z_(n=>(0,Qnt.jsx)("capacitor",{...n}),MH),s7t=n=>Z_(e=>(0,tit.jsx)("chip",{pinLabels:n,...e}),n),o7t=Z_(n=>(0,eit.jsx)("diode",{...n}),VH),a7t=Z_(n=>(0,nit.jsx)("led",{...n}),HH),c7t=Z_(n=>(0,iit.jsx)("resistor",{...n}),SH),l7t=new Proxy(n=>new Proxy({},{get:(e,t)=>`.${n} > .${t}`}),{get:(n,e)=>{let t=(...i)=>{let r=i[0];return new Proxy({},{get:(s,o)=>`.${e} > .${o}`})};return new Proxy(t,{get:(i,r)=>e==="net"?`net.${r}`:e==="subcircuit"?new Proxy({},{get:(s,o)=>new Proxy({},{get:(a,c)=>`subcircuit.${r} > .${o} > .${c}`})}):`.${e} > .${r}`,apply:(i,r,s)=>e==="net"?new Proxy({},{get:(o,a)=>`net.${a}`}):new Proxy({},{get:(o,a)=>{let c=`.${e} > .${a}`;return["U","J","CN"].some(u=>e.startsWith(u))?c:new Proxy(new String(c),{get:(u,p)=>typeof p=="symbol"||p==="toString"?()=>c:`.${e} > .${a} > .${p}`})}})})}});Iet(ket);Iet({Bug:Y1});var Sit=Ht(Hs(),1);var sit=n=>{let e=n.match(/:[RC]_(\d{4})_/);if(e||(e=n.match(/:(SOIC-\d+|SOT-\d+|SOD-\d+|SSOP-\d+|TSSOP-\d+|QFP-\d+|QFN-\d+)/),e))return e[1]};var y9=n=>n.includes("cap")?n.replace(/cap/g,""):n;var oit=n=>{if(n){if(n.startsWith("kicad:")){let e=sit(n);return e?y9(e):n}return y9(n)}};var g9=new Map,Tr=async(n,e)=>{let t=new URLSearchParams({...e,json:"true"}).toString();if(g9.has(t))return g9.get(t);let r=await(await fetch(`https://jlcsearch.tscircuit.com/${n}/list?${t}`)).json();return g9.set(t,r),r},Er=n=>n?[...n].sort((e,t)=>Number(t.is_basic??!1)-Number(e.is_basic??!1)):[],ait={findPart:async({sourceComponent:n,footprinterString:e})=>{let t=oit(e);if(n.type==="source_component"&&n.ftype==="simple_resistor"){let{resistors:i}=await Tr("resistors",{resistance:n.resistance,package:t});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_capacitor"){let{capacitors:i}=await Tr("capacitors",{capacitance:n.capacitance,package:t});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_pin_header"){let i;e?.includes("_p")&&(i=Number(e.split("_p")[1]));let{headers:r}=await Tr("headers",i?{pitch:i,num_pins:n.pin_count,gender:n.gender}:{num_pins:n.pin_count,gender:n.gender});return{jlcpcb:Er(r).map(s=>`C${s.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_potentiometer"){let{potentiometers:i}=await Tr("potentiometers",{resistance:n.max_resistance,package:t});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_diode"){let{diodes:i}=await Tr("diodes",{package:t});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_chip"){let{chips:i}=await Tr("chips",{package:t});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_transistor"){let{transistors:i}=await Tr("transistors",{package:t,transistor_type:n.transistor_type});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_power_source"){let{power_sources:i}=await Tr("power_sources",{voltage:n.voltage,package:t});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_inductor"){let{inductors:i}=await Tr("inductors",{inductance:n.inductance,package:t});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_crystal"){let{crystals:i}=await Tr("crystals",{frequency:n.frequency,load_capacitance:n.load_capacitance,package:t});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_mosfet"){let{mosfets:i}=await Tr("mosfets",{package:t,mosfet_mode:n.mosfet_mode,channel_type:n.channel_type});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_resonator"){let{resonators:i}=await Tr("resonators",{frequency:n.frequency,package:t});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_switch"){let{switches:i}=await Tr("switches",{switch_type:n.type,package:t});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_led"){let{leds:i}=await Tr("leds",{package:t});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(n.type==="source_component"&&n.ftype==="simple_fuse"){let{fuses:i}=await Tr("fuses",{package:t});return{jlcpcb:Er(i).map(r=>`C${r.lcsc}`).slice(0,3)}}return{}}};var pit=Ht(cit(),1);J();var _it=Ht(An(),1),yit=Ht(An(),1),xi=h.tuple([h.coerce.number(),h.coerce.number()]),x7t=h.tuple([h.number(),h.number(),h.number()]),aP=h.union([xi,x7t]),b7t=h.object({kind:h.literal("arc"),start:xi,mid:xi,end:xi}),v7t=h.union([xi,b7t]),hit=h.object({at:aP,size:xi,layer:h.string(),layers:h.array(h.string()),roundrect_rratio:h.number(),uuid:h.string()}).partial(),w7t=h.object({key:h.string(),val:h.string(),attributes:hit}),rP=h.object({oval:h.boolean().default(!1),width:h.number().optional(),height:h.number().optional(),offset:xi.optional()}),dit=h.object({name:h.string(),pad_type:h.enum(["thru_hole","smd","np_thru_hole","connect"]),pad_shape:h.enum(["roundrect","circle","rect","oval","trapezoid","custom"]),at:aP,drill:h.union([h.number(),h.array(h.any()),rP]).transform(n=>typeof n=="number"?{oval:!1,width:n,height:n}:"oval"in n?n:n.length===2?{oval:!1,width:Number.parseFloat(n[0]),height:Number.parseFloat(n[0]),offset:xi.parse(n[1].slice(1))}:n.length===3||n.length===4?{oval:n[0]==="oval",width:Number.parseFloat(n[1]),height:Number.parseFloat(n[2]),offset:n[3]?xi.parse(n[3].slice(1)):void 0}:n).pipe(rP),size:h.union([h.array(h.number()).length(2).transform(([n,e])=>({width:n,height:e})),h.object({width:h.number(),height:h.number()})]),layers:h.array(h.string()).optional(),roundrect_rratio:h.number().optional(),uuid:h.string().optional()}),fit=h.object({name:h.string(),pad_type:h.enum(["thru_hole","smd","np_thru_hole","connect"]),pad_shape:h.enum(["roundrect","circle","rect","oval","trapezoid","custom"]),at:aP,size:xi,drill:h.union([h.number(),h.array(h.any()),rP]).transform(n=>typeof n=="number"?{oval:!1,width:n,height:n}:"oval"in n?n:n.length===2?{oval:!1,width:Number.parseFloat(n[0]),height:Number.parseFloat(n[0]),offset:xi.parse(n[1].slice(1))}:n.length===3||n.length===4?{oval:n[0]==="oval",width:Number.parseFloat(n[1]),height:Number.parseFloat(n[2]),offset:n[3]?xi.parse(n[3].slice(1)):void 0}:n).pipe(rP).optional(),layers:h.array(h.string()).optional(),roundrect_rratio:h.number().optional(),chamfer_ratio:h.number().optional(),solder_paste_margin:h.number().optional(),solder_paste_margin_ratio:h.number().optional(),clearance:h.number().optional(),zone_connection:h.union([h.literal(0).describe("Pad is not connect to zone"),h.literal(1).describe("Pad is connected to zone using thermal relief"),h.literal(2).describe("Pad is connected to zone using solid fill")]).optional(),thermal_width:h.number().optional(),thermal_gap:h.number().optional(),uuid:h.string().optional()}),mit=h.object({font:h.object({size:xi,thickness:h.number().optional()})}).partial(),S7t=h.object({fp_text_type:h.literal("user"),text:h.string(),at:aP,layer:h.string(),uuid:h.string().optional(),effects:mit.partial()}),P7t=h.object({start:xi,mid:xi,end:xi,stroke:h.object({width:h.number(),type:h.string()}),layer:h.string(),uuid:h.string().optional()}),k7t=h.object({center:xi,end:xi,stroke:h.object({width:h.number(),type:h.string()}),fill:h.string().optional(),layer:h.string(),uuid:h.string().optional()}),T7t=h.object({pts:h.array(v7t),stroke:h.object({width:h.number(),type:h.string()}).optional(),width:h.number().optional(),layer:h.string(),uuid:h.string().optional(),fill:h.string().optional()}).transform(n=>({...n,width:void 0,stroke:n.stroke??{width:n.width}})),E7t=h.object({start:xi,end:xi,stroke:h.object({width:h.number(),type:h.string()}).optional(),width:h.number().optional(),layer:h.string(),uuid:h.string().optional()}).transform(n=>({...n,width:void 0,stroke:n.stroke??{width:n.width}})),lit=h.object({footprint_name:h.string(),version:h.string().optional(),generator:h.string().optional(),generator_version:h.string().optional(),layer:h.string(),descr:h.string().default(""),tags:h.array(h.string()).optional(),properties:h.array(w7t),fp_lines:h.array(E7t),fp_texts:h.array(S7t),fp_arcs:h.array(P7t),fp_circles:h.array(k7t).optional(),fp_polys:h.array(T7t).optional(),pads:h.array(fit),holes:h.array(dit).optional()}),sP=(n,e)=>{if(e==="effects"&&Array.isArray(n)){let t={};for(let i of n)if(i[0]==="font"){let r={};for(let s of i.slice(1))s.length===2?r[s[0].valueOf()]=Number.parseFloat(s[1].valueOf()):r[s[0].valueOf()]=s.slice(1).map(o=>Number.parseFloat(o.valueOf()));t.font=r}return mit.parse(t)}if(e==="pts")return n.map(t=>{let i=t[0]?.valueOf?.()??t[0];if(i==="xy")return t.slice(1).map(r=>Number.parseFloat(r.valueOf()));if(i==="arc"){let r={kind:"arc"};for(let s of t.slice(1)){let o=s[0].valueOf();r[o]=s.slice(1).map(a=>Number.parseFloat(a.valueOf()))}return r}return t});if(e==="stroke"){let t={};for(let i of n){let r=i[0].valueOf();t[r]=sP(i.slice(1),r)}return t}return e==="at"||e==="size"||e==="start"||e==="mid"||e==="end"?(Array.isArray(n)?n:[n]).map(i=>i?.valueOf?.()??i).filter(i=>typeof i=="number"||typeof i=="string"&&/^[-+]?\d*\.?\d+(e[-+]?\d+)?$/i.test(i)).map(i=>typeof i=="number"?i:Number.parseFloat(i)):e==="tags"?n.map(t=>t.valueOf()):e==="generator_version"||e==="version"?n[0].valueOf():n.length===2?n.valueOf():e==="uuid"?Array.isArray(n)?n[0].valueOf():n.valueOf():/^[\d\.]+$/.test(n)&&!Number.isNaN(Number.parseFloat(n))?Number.parseFloat(n):Array.isArray(n)&&n.length===1?n[0].valueOf():Array.isArray(n)?n.map(t=>t.valueOf()):n},$e=(n,e)=>{for(let t of n)if(Array.isArray(t)&&t[0]===e)return sP(t.slice(1),e)},x9=(0,_it.default)("kicad-mod-converter"),M7t=n=>{let e=(0,pit.default)(n),t=e[1].valueOf(),i={},r=Object.entries(lit.shape).filter(([T,k])=>k._def.typeName==="ZodString"||T==="tags").map(([T])=>T);for(let T of e.slice(2)){if(!r.includes(T[0]))continue;let k=T[0].valueOf(),C=sP(T.slice(1),k);i[k]=C}let s=e.slice(2).filter(T=>T[0]==="property").map(T=>{let k=T[1].valueOf(),C=T[2].valueOf(),E=hit.parse(T.slice(3).reduce((N,I)=>{let A=I[0].valueOf();return N[A]=sP(I.slice(1),A),N},{}));return{key:k,val:C,attributes:E}}),o=e.slice(2).filter(T=>T[0]==="pad"),a=[];for(let T of o){let k=$e(T,"at"),C=$e(T,"size"),E=$e(T,"drill"),N=$e(T,"layers");if(Array.isArray(N)?N=N.map(j=>j.valueOf()):typeof N=="string"?N=[N]:N||(N=[]),!N.includes("F.Cu")){x9(`Skipping pad without F.Cu layer: layers=${N.join(", ")}`);continue}let I=$e(T,"roundrect_rratio"),A=$e(T,"uuid"),R={name:T[1].valueOf(),pad_type:T[2].valueOf(),pad_shape:T[3].valueOf(),at:k,drill:E,size:C,layers:N,roundrect_rratio:I,uuid:A};x9(`attempting to parse pad: ${JSON.stringify(R,null," ")}`),a.push(fit.parse(R))}let c=e.slice(2).filter(T=>T[0]==="fp_text"),l=[];for(let T of c){let k=T[2].valueOf(),C=$e(T,"at"),E=$e(T,"layer"),N=$e(T,"uuid"),I=$e(T,"effects");l.push({fp_text_type:"user",text:k,at:C,layer:E,uuid:N,effects:I})}let u=[],p=e.slice(2).filter(T=>T[0]==="fp_line");for(let T of p){let k=$e(T,"start"),C=$e(T,"end"),E=$e(T,"stroke"),N=$e(T,"layer"),I=$e(T,"uuid");u.push({start:k,end:C,stroke:E,layer:N,uuid:I})}let f=[],y=e.slice(2).filter(T=>T[0]==="fp_arc");for(let T of y){let k=$e(T,"start"),C=$e(T,"mid"),E=$e(T,"end"),N=$e(T,"stroke"),I=$e(T,"layer"),A=$e(T,"uuid");!k||!E||!C||!N||!I||f.push({start:k,mid:C,end:E,stroke:N,layer:I,uuid:A})}let g=[],x=e.slice(2).filter(T=>T[0]==="fp_circle");for(let T of x){let k=$e(T,"center"),C=$e(T,"end"),E=$e(T,"stroke"),N=$e(T,"fill"),I=$e(T,"layer"),A=$e(T,"uuid");!k||!C||!E||!I||g.push({center:k,end:C,stroke:E,fill:N,layer:I,uuid:A})}let v=[],S=e.slice(2).filter(T=>T[0]==="fp_poly");for(let T of S){let k=$e(T,"pts"),C=$e(T,"stroke"),E=$e(T,"width"),N=$e(T,"layer"),I=$e(T,"uuid"),A=$e(T,"fill"),R=C;!R&&typeof E=="number"?R={width:E,type:"solid"}:R&&typeof R=="object"&&typeof E=="number"&&R.width===void 0&&(R={...R,width:E}),v.push({pts:k,stroke:R,layer:N,uuid:I,fill:A})}let P=[];for(let T of e.slice(2)){if(T[0]!=="pad"||T[2]?.valueOf?.()!=="thru_hole")continue;let k=T[1]?.valueOf?.(),C=T[2]?.valueOf?.(),E=T[3]?.valueOf?.(),N=$e(T,"at"),I=$e(T,"drill"),A=$e(T,"size");Array.isArray(A)&&(A[0]==="size"&&(A=A.slice(1)),A={width:Number(A[0]),height:Number(A[1])});let R=$e(T,"uuid"),j=$e(T,"roundrect_rratio"),B=$e(T,"layers");Array.isArray(B)?B=B.map(U=>U.valueOf()):typeof B=="string"?B=[B]:B||(B=[]);let G={name:k,pad_type:C,pad_shape:E,at:N,drill:I,size:A,layers:B,roundrect_rratio:j,uuid:R};x9(`attempting to parse holes: ${JSON.stringify(G,null,2)}`),P.push(dit.parse(G))}return lit.parse({footprint_name:t,...i,properties:s,fp_lines:u,fp_texts:l,fp_arcs:f,fp_circles:g,pads:a,holes:P,fp_polys:v})},U1=Math.PI*2,uit=n=>{let e=n%U1;return e<0&&(e+=U1),e},oP=(n,e)=>{let t=uit(n),r=uit(e)-t;return r<0&&(r+=U1),r};function git(n,e,t){let i={x:(n.x+e.x)/2,y:(n.y+e.y)/2},r={x:(e.x+t.x)/2,y:(e.y+t.y)/2},s=-(n.x-e.x)/(n.y-e.y),o=-(e.x-t.x)/(e.y-t.y),a=(i.y-r.y+o*r.x-s*i.x)/(o-s),c=i.y+s*(a-i.x);return{x:a,y:c}}function xit(n,e){return Math.sqrt((n.x-e.x)**2+(n.y-e.y)**2)}function J_(n,e){return Math.atan2(e.y-n.y,e.x-n.x)}var S9=(n,e,t)=>{let i=git(n,e,t),r=xit(i,n),s=J_(i,n),o=J_(i,e),a=J_(i,t),c=oP(s,o),l=oP(s,a),u=l;return c>l&&(u=l-U1),Math.abs(r*u)};function P9(n,e,t,i){let r=git(n,e,t),s=xit(r,n),o=J_(r,n),a=J_(r,e),c=J_(r,t),l=oP(o,a),u=oP(o,c),p=u;l>u&&(p=u-U1);let f=[];for(let y=0;y<=i;y++){let g=o+y/i*p,x=r.x+s*Math.cos(g),v=r.y+s*Math.sin(g);f.push({x,y:v})}return f}var yl=n=>Array.isArray(n)?{x:n[0],y:n[1]}:n,b9=(n,e,t=1e-4)=>Math.abs(n.x-e.x)<t&&Math.abs(n.y-e.y)<t,C7t=n=>{let e=[],t=new Set;for(let i=0;i<n.length;i++){if(t.has(i))continue;let r=[n[i]];t.add(i);let s=n[i].end,o=!0;for(;o;){if(o=!1,r.length>1&&b9(s,r[0].start)){e.push(r);break}for(let a=0;a<n.length;a++)if(!t.has(a)){if(b9(s,n[a].start)){r.push(n[a]),t.add(a),s=n[a].end,o=!0;break}else if(b9(s,n[a].end)){n[a].type==="arc"?r.push({...n[a],reversed:!0}):r.push({...n[a],start:n[a].end,end:n[a].start}),t.add(a),s=n[a].start,o=!0;break}}if(!o){for(let a=r.length-1;a>=0;a--){let c=n.indexOf(r[a]);c!==-1&&t.delete(c)}break}}}return e},I7t=n=>{let e=[];for(let t of n)if(t.type==="line")e.push(t.start);else if(t.type==="arc"&&t.mid){let i=S9(t.start,t.mid,t.end),r=Math.max(3,Math.ceil(i)),s=P9(t.start,t.mid,t.end,r);t.reversed&&(s=s.reverse()),e.push(...s.slice(0,-1))}return e};function N7t(n){if(!Array.isArray(n))return null;let e=n.find(o=>o.layer?.toLowerCase()==="f.silks"&&(o.text?.includes("${REFERENCE}")||o.fp_text_type?.toLowerCase()==="reference"||o.text?.match(/^R\d+|C\d+|U\d+/))),t=e||n.find(o=>o.layer?.toLowerCase()==="f.fab"&&(o.text?.includes("${REFERENCE}")||o.fp_text_type?.toLowerCase()==="reference")),i=e||t;if(!i?.effects?.font?.size)return null;let[r,s]=i.effects.font.size;return s??r??1}var A7t=n=>n*Math.PI/180,v9=(n,e,t)=>{let i=A7t(t),r=Math.cos(i),s=Math.sin(i);return{x:n*r-e*s,y:n*s+e*r}},R7t=n=>{let e=[...new Map(n.map(u=>[`${u.x},${u.y}`,u])).values()];if(e.length!==4)return null;let t=e.map(u=>u.x),i=e.map(u=>u.y),r=[...new Set(t)],s=[...new Set(i)];if(r.length!==2||s.length!==2)return null;let[o,a]=r.sort((u,p)=>u-p),[c,l]=s.sort((u,p)=>u-p);return o===void 0||a===void 0||c===void 0||l===void 0?null:{x:(o+a)/2,y:(c+l)/2,width:a-o,height:l-c}},O7t=n=>{if(!n)return!1;let e=n.toLowerCase();return e!=="no"&&e!=="none"&&e!=="outline"},w9=n=>n&&Array.isArray(n)&&n.length>=3&&typeof n[2]=="number"?n[2]:0,Ur=n=>{let e=(n%360+360)%360;return e===90||e===270},K_=(0,yit.default)("kicad-mod-converter"),Ls=n=>{switch(n.toLowerCase()){case"f.cu":case"f.fab":case"f.silks":case"edge.cuts":return"top";case"b.cu":case"b.fab":case"b.silks":return"bottom"}},L7t=async n=>{let{fp_lines:e,fp_texts:t,fp_arcs:i,fp_circles:r,pads:s,properties:o,holes:a,fp_polys:c}=n,l=[];l.push({type:"source_component",source_component_id:"source_component_0",supplier_part_numbers:{}}),l.push({type:"schematic_component",schematic_component_id:"schematic_component_0",source_component_id:"source_component_0",center:{x:0,y:0},rotation:0,size:{width:0,height:0}});let u=new Set;for(let V of s)V.name&&u.add(V.name);if(a)for(let V of a)V.name&&u.add(V.name);let p=0,f=new Map;for(let V of u){let ot=`source_port_${p++}`;f.set(V,ot),l.push({type:"source_port",source_port_id:ot,source_component_id:"source_component_0",name:V,port_hints:[V]}),l.push({type:"schematic_port",schematic_port_id:`schematic_port_${p++}`,source_port_id:ot,schematic_component_id:"schematic_component_0",center:{x:0,y:0}})}let y=Number.POSITIVE_INFINITY,g=Number.NEGATIVE_INFINITY,x=Number.POSITIVE_INFINITY,v=Number.NEGATIVE_INFINITY;for(let V of s){let ot=V.at[0],nt=-V.at[1],et=V.size[0],ht=V.size[1];y=Math.min(y,ot-et/2),g=Math.max(g,ot+et/2),x=Math.min(x,nt-ht/2),v=Math.max(v,nt+ht/2)}let S="pcb_component_0";l.push({type:"pcb_component",source_component_id:"source_component_0",pcb_component_id:S,layer:"top",center:{x:0,y:0},rotation:0,width:Number.isFinite(y)?g-y:0,height:Number.isFinite(x)?v-x:0});let P=0,T=new Map;for(let V of u){let ot=`pcb_port_${P++}`,nt=f.get(V);T.set(V,ot);let et=0,ht=0,dt=["top","bottom"],St=s.find(Pt=>Pt.name===V);if(St)et=St.at[0],ht=-St.at[1],dt=St.layers?St.layers.map(Pt=>Ls(Pt)).filter(Boolean):["top","bottom"];else if(a){let Pt=a.find(ut=>ut.name===V);Pt&&(et=Pt.at[0],ht=-Pt.at[1],dt=Pt.layers?Pt.layers.map(ut=>Ls(ut)).filter(Boolean):["top","bottom"])}l.push({type:"pcb_port",pcb_port_id:ot,source_port_id:nt,pcb_component_id:S,x:et,y:ht,layers:dt})}let k=0,C=0,E=0;for(let V of s)if(V.pad_type==="smd"){let ot=w9(V.at),nt=Ur(ot)?V.size[1]:V.size[0],et=Ur(ot)?V.size[0]:V.size[1],ht=V.name?T.get(V.name):void 0;l.push({type:"pcb_smtpad",pcb_smtpad_id:`pcb_smtpad_${k++}`,shape:"rect",x:V.at[0],y:-V.at[1],width:nt,height:et,layer:Ls(V.layers?.[0]??"F.Cu"),pcb_component_id:S,port_hints:[V.name],pcb_port_id:ht})}else if(V.pad_type==="thru_hole"){if(V.pad_shape==="rect"){let ot=w9(V.at),nt=Ur(ot)?V.size[1]:V.size[0],et=Ur(ot)?V.size[0]:V.size[1],ht=V.drill?.offset?.[0]??0,dt=V.drill?.offset?.[1]??0,St=v9(ht,dt,ot),Pt=V.name?T.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${C++}`,shape:"circular_hole_with_rect_pad",hole_shape:"circle",pad_shape:"rect",x:V.at[0],y:-V.at[1],hole_offset_x:St.x,hole_offset_y:-St.y,hole_diameter:V.drill?.width,rect_pad_width:nt,rect_pad_height:et,layers:["top","bottom"],pcb_component_id:S,port_hints:[V.name],pcb_port_id:Pt})}else if(V.pad_shape==="circle"){let ot=V.name?T.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${C++}`,shape:"circle",x:V.at[0],y:-V.at[1],outer_diameter:V.size[0],hole_diameter:V.drill?.width,layers:["top","bottom"],pcb_component_id:S,port_hints:[V.name],pcb_port_id:ot})}else if(V.pad_shape==="oval"){let ot=V.name?T.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${C++}`,shape:"pill",x:V.at[0],y:-V.at[1],outer_width:V.size[0],outer_height:V.size[1],hole_width:V.drill?.width,hole_height:V.drill?.height,layers:["top","bottom"],pcb_component_id:S,port_hints:[V.name],pcb_port_id:ot})}}else V.pad_type==="np_thru_hole"&&l.push({type:"pcb_hole",pcb_hole_id:`pcb_hole_${E++}`,x:V.at[0],y:-V.at[1],hole_diameter:V.drill?.width,pcb_component_id:S});if(a)for(let V of a){let ot=V.layers?.some(pt=>pt.endsWith(".Cu")||pt==="*.Cu"),nt=w9(V.at),et=V.drill?.offset?.[0]??0,ht=V.drill?.offset?.[1]??0,dt=v9(et,ht,nt),St=V.at[0]+dt.x,Pt=-(V.at[1]+dt.y),ut=V.drill?.width??0,Y=V.size?.width??ut,q=V.roundrect_rratio??0,rt=q>0?Math.min(Ur(nt)?V.size?.height??Y:V.size?.width??Y,Ur(nt)?V.size?.width??Y:V.size?.height??Y)/2*q:0;if(ot)if(V.pad_shape==="rect"){let pt=V.name?T.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${C++}`,shape:"circular_hole_with_rect_pad",hole_shape:"circle",pad_shape:"rect",x:V.at[0],y:-V.at[1],hole_offset_x:dt.x,hole_offset_y:-dt.y,hole_diameter:ut,rect_pad_width:Ur(nt)?V.size?.height??Y:V.size?.width??Y,rect_pad_height:Ur(nt)?V.size?.width??Y:V.size?.height??Y,rect_border_radius:rt,port_hints:[V.name],layers:["top","bottom"],pcb_component_id:S,pcb_port_id:pt})}else if(V.pad_shape==="oval"){let pt=V.name?T.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${C++}`,shape:"pill",x:St,y:Pt,outer_width:Ur(nt)?V.size?.height??Y:V.size?.width??Y,outer_height:Ur(nt)?V.size?.width??Y:V.size?.height??Y,hole_width:Ur(nt)?V.drill?.height??ut:V.drill?.width??ut,hole_height:Ur(nt)?V.drill?.width??ut:V.drill?.height??ut,port_hints:[V.name],layers:["top","bottom"],pcb_component_id:S,pcb_port_id:pt})}else if(V.pad_shape==="roundrect"){let pt=V.name?T.get(V.name):void 0,yt=V.drill?.offset?.[0]??0,Z=V.drill?.offset?.[1]??0,ct=v9(yt,Z,nt),Mt=Ur(nt)?V.size?.height??Y:V.size?.width??Y,Lt=Ur(nt)?V.size?.width??Y:V.size?.height??Y;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${C++}`,shape:"circular_hole_with_rect_pad",hole_shape:"circle",pad_shape:"rect",x:St,y:Pt,hole_offset_x:ct.x,hole_offset_y:-ct.y,hole_diameter:ut,rect_pad_width:Mt,rect_pad_height:Lt,rect_border_radius:rt,port_hints:[V.name],layers:["top","bottom"],pcb_component_id:S,pcb_port_id:pt})}else{let pt=V.name?T.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${C++}`,shape:"circle",x:St,y:Pt,outer_diameter:Y,hole_diameter:ut,port_hints:[V.name],layers:["top","bottom"],pcb_component_id:S,pcb_port_id:pt})}else l.push({type:"pcb_hole",pcb_hole_id:`pcb_hole_${E++}`,x:St,y:Pt,hole_diameter:Y,hole_shape:"circle",pcb_component_id:S})}let N=[];for(let V of e)V.layer.toLowerCase()==="edge.cuts"&&N.push({type:"line",start:{x:V.start[0],y:V.start[1]},end:{x:V.end[0],y:V.end[1]},strokeWidth:V.stroke.width});for(let V of i)V.layer.toLowerCase()==="edge.cuts"&&N.push({type:"arc",start:{x:V.start[0],y:V.start[1]},mid:{x:V.mid[0],y:V.mid[1]},end:{x:V.end[0],y:V.end[1]},strokeWidth:V.stroke.width});let I=C7t(N),A=0;for(let V of I){let ot=I7t(V);ot.length>=3&&l.push({type:"pcb_cutout",pcb_cutout_id:`pcb_cutout_${A++}`,shape:"polygon",points:ot.map(nt=>({x:nt.x,y:-nt.y})),pcb_component_id:S})}let R=0,j=0,B=0,G=0;for(let V of e){let ot=[{x:V.start[0],y:-V.start[1]},{x:V.end[0],y:-V.end[1]}],nt=V.layer.toLowerCase();nt==="f.cu"?l.push({type:"pcb_trace",pcb_trace_id:`pcb_trace_${R++}`,pcb_component_id:S,layer:Ls(V.layer),route:ot,thickness:V.stroke.width}):nt==="f.silks"?l.push({type:"pcb_silkscreen_path",pcb_silkscreen_path_id:`pcb_silkscreen_path_${j++}`,pcb_component_id:S,layer:"top",route:ot,stroke_width:V.stroke.width}):nt==="edge.cuts"?K_("Skipping Edge.Cuts fp_line (converted to pcb_cutout)",V.layer):nt==="f.fab"?l.push({type:"pcb_fabrication_note_path",fabrication_note_path_id:`fabrication_note_path_${B++}`,pcb_component_id:S,layer:"top",route:ot,stroke_width:V.stroke.width,port_hints:[]}):nt.startsWith("user.")?l.push({type:"pcb_note_line",pcb_note_line_id:`pcb_note_line_${G++}`,pcb_component_id:S,x1:V.start[0],y1:-V.start[1],x2:V.end[0],y2:-V.end[1],stroke_width:V.stroke.width}):K_("Unhandled layer for fp_line",V.layer)}if(c)for(let V of c){let ot=[],nt=Pt=>{!Number.isFinite(Pt.x)||!Number.isFinite(Pt.y)||ot.push(Pt)};for(let Pt of V.pts){if(Array.isArray(Pt)){nt({x:Pt[0],y:-Pt[1]});continue}if(Pt&&typeof Pt=="object"&&"kind"in Pt){if(Pt.kind==="arc"){let ut=yl(Pt.start),Y=yl(Pt.mid),q=yl(Pt.end),rt=S9(ut,Y,q),pt=Math.max(8,Math.ceil(rt)),yt=Math.max(2,Math.ceil(rt/.1)),Z=P9(ut,Y,q,yt).map(ct=>({x:ct.x,y:-ct.y}));for(let ct of Z)nt(ct)}continue}}let et=ot,dt=et.length>2&&et[0].x===et[et.length-1].x&&et[0].y===et[et.length-1].y?et.slice(0,-1):et;if(et.length===0)continue;let St=V.stroke?.width??0;if(V.layer.endsWith(".Cu")){let Pt=R7t(dt);Pt?l.push({type:"pcb_smtpad",pcb_smtpad_id:`pcb_smtpad_${k++}`,shape:"rect",x:Pt.x,y:Pt.y,width:Pt.width,height:Pt.height,layer:Ls(V.layer),pcb_component_id:S}):O7t(V.fill)?dt.length>=3?l.push({type:"pcb_smtpad",pcb_smtpad_id:`pcb_smtpad_${k++}`,shape:"polygon",points:dt,layer:Ls(V.layer),pcb_component_id:S}):dt.length>=2&&l.push({type:"pcb_trace",pcb_trace_id:`pcb_trace_${R++}`,pcb_component_id:S,layer:Ls(V.layer),route:dt,thickness:St}):dt.length>=2&&l.push({type:"pcb_trace",pcb_trace_id:`pcb_trace_${R++}`,pcb_component_id:S,layer:Ls(V.layer),route:dt,thickness:St})}else V.layer.endsWith(".SilkS")?l.push({type:"pcb_silkscreen_path",pcb_silkscreen_path_id:`pcb_silkscreen_path_${j++}`,pcb_component_id:S,layer:Ls(V.layer),route:et,stroke_width:St}):V.layer.endsWith(".Fab")?l.push({type:"pcb_fabrication_note_path",fabrication_note_path_id:`fabrication_note_path_${B++}`,pcb_component_id:S,layer:Ls(V.layer),route:dt,stroke_width:St,port_hints:[]}):K_("Unhandled layer for fp_poly",V.layer)}let U=0;for(let V of i){let ot=V.layer.toLowerCase();if(ot==="edge.cuts"){K_("Skipping Edge.Cuts fp_arc (converted to pcb_cutout)",V.layer);continue}let nt=yl(V.start),et=yl(V.mid),ht=yl(V.end),dt=S9(nt,et,ht),St=P9(nt,et,ht,Math.ceil(dt));if(ot.startsWith("user.")){l.push({type:"pcb_note_path",pcb_note_path_id:`pcb_note_path_${U++}`,pcb_component_id:S,route:St.map(ut=>({x:ut.x,y:-ut.y})),stroke_width:V.stroke.width});continue}let Pt=Ls(V.layer);if(!Pt){K_("Unable to convert layer for fp_arc",V.layer);continue}l.push({type:"pcb_silkscreen_path",pcb_silkscreen_path_id:`pcb_silkscreen_path_${j++}`,layer:Pt,pcb_component_id:S,route:St.map(ut=>({x:ut.x,y:-ut.y})),stroke_width:V.stroke.width})}if(r)for(let V of r){let ot=V.layer.toLowerCase(),nt=yl(V.center),et=yl(V.end),ht=Math.sqrt((et.x-nt.x)**2+(et.y-nt.y)**2),dt=Math.max(16,Math.ceil(2*Math.PI*ht)),St=[];for(let Pt=0;Pt<=dt;Pt++){let ut=Pt/dt*2*Math.PI;St.push({x:nt.x+ht*Math.cos(ut),y:nt.y+ht*Math.sin(ut)})}ot.startsWith("user.")&&l.push({type:"pcb_note_path",pcb_note_path_id:`pcb_note_path_${U++}`,pcb_component_id:S,route:St.map(Pt=>({x:Pt.x,y:-Pt.y})),stroke_width:V.stroke.width})}for(let V of t){let ot=Ls(V.layer);V.layer.endsWith(".SilkS")?l.push({type:"pcb_silkscreen_text",layer:ot,font:"tscircuit2024",font_size:V.effects?.font?.size[0]??1,pcb_component_id:S,anchor_position:{x:V.at[0],y:-V.at[1]},anchor_alignment:"center",text:V.text}):V.layer.endsWith(".Fab")?l.push({type:"pcb_fabrication_note_text",layer:ot,font:"tscircuit2024",font_size:V.effects?.font?.size[0]??1,pcb_component_id:S,anchor_position:{x:V.at[0],y:-V.at[1]},anchor_alignment:"center",text:V.text}):K_("Unhandled layer for fp_text",V.layer)}let H=o.find(V=>V.key==="Reference"),Q=o.find(V=>V.key==="Value"),tt=[H,Q].filter(V=>V&&!!V.val);for(let V of tt){let ot=V.attributes.at;if(!ot)continue;let et=V.attributes.layer?.toLowerCase()?.endsWith(".fab"),ht=N7t(t);l.push({type:et?"pcb_fabrication_note_text":"pcb_silkscreen_text",layer:"top",font:"tscircuit2024",font_size:ht,pcb_component_id:S,anchor_position:{x:ot[0],y:-ot[1]},anchor_alignment:"center",text:V.val})}return l},bit=async n=>{let e=M7t(n);return await L7t(e)};var vit=async n=>{try{return(await import(n)).default}catch{console.log(`Failed to load ${n} locally, trying CDN fallback...`);try{let t=await fetch(`https://cdn.jsdelivr.net/npm/${n}/+esm`);if(!t.ok)throw new Error(`Failed to fetch ${n} from CDN: ${t.statusText}`);let i=await t.text(),r=new Blob([i],{type:"application/javascript"}),s=URL.createObjectURL(r);try{let{default:o}=await import(s);return o}finally{URL.revokeObjectURL(s)}}catch(t){throw console.error(`CDN fallback for ${n} also failed:`,t),t}}};var F7t="https://kicad-mod-cache.tscircuit.com",cP=null,wit=()=>({partsEngine:ait,spiceEngineMap:{ngspice:{simulate:async n=>{if(!cP){let e=await vit("@tscircuit/ngspice-spice-engine").catch(t=>{throw new Error("Could not load ngspice engine from local node_modules or CDN fallback.",{cause:t})});e&&(cP=await e())}if(!cP)throw new Error("Could not load ngspice engine from local node_modules or CDN fallback.");return cP.simulate(n)}}},footprintLibraryMap:{kicad:async n=>{let e=`${F7t}/${n}`,t=`${e}.circuit.json`,r=await(await fetch(t)).json(),s=Array.isArray(r)?r.filter(a=>a?.type==="pcb_silkscreen_text"?a?.text==="REF**":!0):r,o=`${e}.wrl`;return{footprintCircuitJson:s,cadModel:{wrlUrl:o,modelUnitToMmScale:2.54}}}},footprintFileParserMap:{kicad_mod:{loadFromUrl:async n=>{let e=await fetch(n).then(i=>i.text()),t=await bit(e);return{footprintCircuitJson:Array.isArray(t)?t:[t]}}}}});var k9=Ht(An(),1),C0e=(0,k9.default)("tsci:eval:execution-context");function lP(n,e={}){globalThis.React=Sit;let t=e.platform||wit(),i=e.projectConfig?{...t,...e.projectConfig}:t;i.partsEngineDisabled&&(i.partsEngine=void 0);let r=new q_({platform:i});e.name&&(r.name=e.name),e.debugNamespace&&r.enableDebug(e.debugNamespace);let s=[];return{fsMap:{},entrypoint:"",logger:{info:o=>{s.push({msg:o})},getLogs:()=>s,stringifyLogs:()=>s.map(o=>o.msg).join(`
254
254
  `)},preSuppliedImports:{"@tscircuit/core":nP,tscircuit:nP,"@tscircuit/math-utils":h4,react:Sit,debug:k9.default,"@tscircuit/props":{}},circuit:r,tsConfig:null,importStack:[],currentlyImporting:new Set,...n}}function gl(n){let e=n;return e=e.replace(/\\/g,"/"),e=e.trim(),e.startsWith("./")&&(e=e.slice(2)),e.startsWith("/")&&(e=e.slice(1)),e}function Pit(n){let e={};for(let[t,i]of Object.entries(n))e[gl(t)]=i;return e}function ao(n){if(!n)return".";let t=n.replace(/\\/g,"/").replace(/\/+$/,"");return t.indexOf("/")===-1?".":t.substring(0,t.lastIndexOf("/"))||"/"}function uP(n,e){if(n.startsWith("../")){let t=ao(e);return uP(n.slice(3),t)}return n.startsWith("./")?uP(n.slice(2),e):n.startsWith("/")?n.slice(1):`${e}/${n}`}function V1(n){if(Array.isArray(n))return null;let e=n["tsconfig.json"];if(!e)return null;try{let t=e.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g,"");return JSON.parse(t)}catch(t){throw new Error(`Failed to parse tsconfig.json: ${t.message}`)}}function kit(n){let{importPath:e,normalizedFilePathMap:t,extensions:i,tsConfig:r}=n,s=r?.compilerOptions?.paths;if(!s)return null;let o=r?.compilerOptions?.baseUrl||".",a=l=>{let u=gl(l);if(t.has(u))return t.get(u);for(let p of i){let f=`${u}.${p}`;if(t.has(f))return t.get(f)}return null};for(let[l,u]of Object.entries(s))if(l.includes("*")){let[f,y]=l.split("*");if(!e.startsWith(f)||!e.endsWith(y||""))continue;let g=e.slice(f.length,e.length-(y?y.length:0));for(let x of u){let v=x.replace("*",g),S=o&&!v.startsWith("./")&&!v.startsWith("/")?`${o}/${v}`:v,P=a(S);if(P)return P}}else{if(e!==l)continue;for(let f of u){let y=o&&!f.startsWith("./")&&!f.startsWith("/")?`${o}/${f}`:f,g=a(y);if(g)return g}}let c=T9({importPath:e,normalizedFilePathMap:t,extensions:i,tsConfig:r});return c||null}function T9(n){let{importPath:e,normalizedFilePathMap:t,extensions:i,tsConfig:r}=n,s=r?.compilerOptions?.baseUrl;if(!s)return null;let o=`${s}/${e}`,a=gl(o);if(t.has(a))return t.get(a);for(let c of i){let l=`${a}.${c}`;if(t.has(l))return t.get(l)}return null}function Tit(n,e){let t=e?.compilerOptions?.paths;if(!t)return!1;for(let[i]of Object.entries(t))if(i.includes("*")){let[s,o]=i.split("*");if(n.startsWith(s)&&n.endsWith(o||""))return!0}else if(n===i)return!0;return!1}var G1=(n,e,t,i={})=>{let r=t?uP(n,t):n,s=new Set(Array.isArray(e)?e:Object.keys(e));if(s.has(r))return r;let o=new Map;for(let u of s)o.set(gl(u),u);let a=gl(r);if(o.has(a))return o.get(a);let c=["tsx","ts","json","js","jsx","obj","gltf","glb"];for(let u of c){let p=`${a}.${u}`;if(o.has(p))return o.get(p)}let l=i.tsConfig??null;if(!n.startsWith("./")&&!n.startsWith("../")){let u=kit({importPath:n,normalizedFilePathMap:o,extensions:c,tsConfig:l});if(u)return u;let p=T9({importPath:n,normalizedFilePathMap:o,extensions:c,tsConfig:l});if(p)return p}if(!n.startsWith("./")&&!n.startsWith("../")){let u=gl(n);if(o.has(u))return o.get(u);for(let p of c){let f=`${u}.${p}`;if(o.has(f))return o.get(f)}}return null},pP=(n,e,t,i={})=>{let r=G1(n,e,t,i);if(!r)throw new Error(`File not found "${n}", available paths:
255
255
 
256
256
  ${Object.keys(e).join(", ")}`);return r};var hP=n=>{let e=/^\s*import\s+(?:(?:[\w\s]+,\s*)?(?:\*\s+as\s+[\w\s]+|\{[\s\w,]+\}|\w+)\s+from\s*)?['"](.+?)['"]/gm,t=[],i;for(;(i=e.exec(n))!==null;){let o=i[0];/^\s*import\s+type\b/.test(o)||t.push(i[1])}let r=/^\s*export\s+(?:type\s+)?(?:\*\s+as\s+[\w$]+|\*|\{[^}]+\})\s+from\s*['"](.+?)['"]/gm,s;for(;(s=r.exec(n))!==null;){let o=s[0];/^\s*export\s+type\b/.test(o)||t.push(s[1])}return t};function Nd(n,e,t){globalThis.__tscircuit_require=r=>{let s=G1(r,e,t),o=s&&e[s];if(!e[r]&&!o)throw new Error(`Import "${r}" not found ${t?`in "${t}"`:""}`);let a=e[r]||e[s];return new Proxy(a,{get(c,l){if(!(l in c)){if(l==="default")return c.default!==void 0?c.default:c.__esModule?void 0:typeof c=="function"||typeof c=="object"?c:void 0;if(l==="__esModule")return!0;throw new Error(`Component "${String(l)}" is not exported by "${r}"`)}return c[l]}})};let i=`