@tscircuit/runframe 0.0.314 → 0.0.316

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.
@@ -13362,4 +13362,4 @@ ${n.slice(0,2e3)}
13362
13362
  ${n.stack}`),t.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:r,componentDisplayName:this.getString(),phase:t.phase,error:n.toString()})})}_emitRenderLifecycleEvent(r,e){_tn(`${r}:${e} ${this.getString()}`);const t=`renderable:renderLifecycle:${r}:${e}`,n={renderId:this._renderId,componentDisplayName:this.getString(),type:t};"root"in this&&this.root&&(this.root.emit(t,n),this.root.emit("renderable:renderLifecycle:anyEvent",{...n,type:t}))}getString(){return this.constructor.name}_hasIncompleteAsyncEffects(){return this._asyncEffects.some(r=>!r.complete)}getCurrentRenderPhase(){return this._currentRenderPhase}getRenderGraph(){return{id:this._renderId,currentPhase:this._currentRenderPhase,renderPhaseStates:this.renderPhaseStates,shouldBeRemoved:this.shouldBeRemoved,children:this.children.map(r=>r.getRenderGraph())}}runRenderCycle(){for(const r of Sb)this.runRenderPhaseForChildren(r),this.runRenderPhase(r)}runRenderPhase(r){var a,o,s;this._currentRenderPhase=r;const e=this.renderPhaseStates[r],t=e.initialized,n=e.dirty;if(!t&&this.shouldBeRemoved)return;if(this.shouldBeRemoved&&t){this._emitRenderLifecycleEvent(r,"start"),(a=this==null?void 0:this[`remove${r}`])==null||a.call(this),e.initialized=!1,e.dirty=!1,this._emitRenderLifecycleEvent(r,"end");return}const i=Sb.indexOf(r)-1;if(i>=0){const l=Sb[i];if(this._asyncEffects.filter(u=>u.phase===l).some(u=>!u.complete))return}if(this._emitRenderLifecycleEvent(r,"start"),t){n&&((o=this==null?void 0:this[`update${r}`])==null||o.call(this),e.dirty=!1),this._emitRenderLifecycleEvent(r,"end");return}e.dirty=!1,(s=this==null?void 0:this[`doInitial${r}`])==null||s.call(this),e.initialized=!0,this._emitRenderLifecycleEvent(r,"end")}runRenderPhaseForChildren(r){for(const e of this.children)e.runRenderPhaseForChildren(r),e.runRenderPhase(r)}renderError(r){throw typeof r=="string"?new Error(r):new Error(JSON.stringify(r,null,2))}},bF={},qHe=r=>{const e=Object.fromEntries(Object.entries(r).map(([t,n])=>[t.toLowerCase(),n]));Object.assign(bF,r),Object.assign(bF,e)};function btn(r,e){const t=r;return t.__tsci={...e},r}var $He={supportsMutation:!0,createInstance(r,e){const t=bF[r];if(!t)throw Object.keys(bF).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 (not registered in @tscircuit/core catalogue): "${r}" See CREATING_NEW_COMPONENTS.md`);return btn(new t(e),{})},createTextInstance(){return{}},appendInitialChild(r,e){r.add(e)},appendChild(r,e){r.add(e)},appendChildToContainer(r,e){r.add(e)},finalizeInitialChildren(){return!1},prepareUpdate(){return null},shouldSetTextContent(){return!1},getRootHostContext(){return{}},getChildHostContext(){return{}},prepareForCommit(){return null},resetAfterCommit(){},commitMount(){},commitUpdate(){},removeChild(){},clearContainer(){},supportsPersistence:!1,getPublicInstance(r){return r},preparePortalMount(r){throw new Error("Function not implemented.")},scheduleTimeout(r,e){throw new Error("Function not implemented.")},cancelTimeout(r){throw new Error("Function not implemented.")},noTimeout:void 0,isPrimaryRenderer:!1,getInstanceFromNode(r){throw new Error("Function not implemented.")},beforeActiveInstanceBlur(){throw new Error("Function not implemented.")},afterActiveInstanceBlur(){throw new Error("Function not implemented.")},prepareScopeUpdate:(r,e)=>{throw new Error("Function not implemented.")},getInstanceFromScope:r=>{throw new Error("Function not implemented.")},detachDeletedInstance:r=>{throw new Error("Function not implemented.")},getCurrentEventPriority:()=>$7.DefaultEventPriority,getCurrentUpdatePriority:()=>$7.DefaultEventPriority,resolveUpdatePriority:()=>$7.DefaultEventPriority,setCurrentUpdatePriority:()=>{},maySuspendCommit:()=>!1,supportsHydration:!1},_7;Cp.version.startsWith("19.")?_7=vde($He):_7=xde($He);var Stn=r=>{const e={children:[],props:{name:"$root"},add(a){a.parent=this,this.children.push(a)},computePcbGlobalTransform(){return w9()}},t=[],n=_7.createContainer(e,0,null,!1,null,"tsci",a=>{console.log("Error in createContainer"),console.error(a),t.push(a)},null);if(Cp.version.startsWith("19.")?(_7.updateContainerSync(r,n,null,()=>{}),_7.flushSyncWork()):_7.updateContainer(r,n,null,()=>{}),t.length>0)throw t[0];const i=_7.getPublicRootInstance(n);return i||e.children[0]},lA=(r,e)=>{if(typeof r=="number")return r;if(r.startsWith("pin"))return Number(r.slice(3));if(!e)throw new Error(`No pin labels provided and pin number or label is not a number: "${r}"`);for(const t in e)if((Array.isArray(e[t])?e[t]:[e[t]]).includes(r))return Number(t.replace("pin",""));throw new Error(`No pin labels provided and pin number or label is not a number: "${r}"`)},Etn=(r,e)=>{if(!r)return;const t={},n={};for(const[i,a]of Object.entries(r)){const o=lA(i,e);n[o]={...n[o],...a}}for(const[i,a]of Object.entries(n)){const o=`pin${i}`;t[o]={bottom_margin:a.bottomMargin,left_margin:a.leftMargin,right_margin:a.rightMargin,top_margin:a.topMargin}}return t},wtn=r=>{if(r){if("leftSide"in r||"rightSide"in r||"topSide"in r||"bottomSide"in r)return{left_side:r.leftSide,right_side:r.rightSide,top_side:r.topSide,bottom_side:r.bottomSide};if("leftPinCount"in r||"rightPinCount"in r||"topPinCount"in r||"bottomPinCount"in r)return{left_size:r.leftPinCount,right_size:r.rightPinCount,top_size:r.topPinCount,bottom_size:r.bottomPinCount};if("leftSize"in r||"rightSize"in r||"topSize"in r||"bottomSize"in r)return{left_size:r.leftSize,right_size:r.rightSize,top_size:r.topSize,bottom_size:r.bottomSize}}},Ttn=class extends Error{constructor(r,e,t){let n;const a=Object.keys(t).filter(o=>o!=="_errors").map(o=>t[o]._errors[0]?`${o} (${t[o]._errors[0]})`:`${o} (${JSON.stringify(t[o])})`).join(", ");"name"in e?n=`Invalid props for ${r} "${e.name}": ${a}`:"footprint"in e&&typeof e.footprint=="string"?n=`Invalid props for ${r} (unnamed ${e.footprint} component): ${a}`:n=`Invalid props for ${r} (unnamed): ${a}`,super(n),this.componentName=r,this.originalProps=e,this.formattedError=t}};function Ble(r,e){const t=e.match(/^#(\w+)/);if(t)return r.props.id===t[1];const n=e.match(/^\.(\w+)/);if(n)return r.isMatchingNameOrAlias(n[1]);let[i,...a]=e.split(/(?=[#.[])/);return i==="pin"&&(i="port"),i&&i!=="*"&&r.lowercaseComponentName!==i.toLowerCase()?!1:a.every(o=>{if(o.startsWith("#"))return r.props.id===o.slice(1);if(o.startsWith("."))return r.isMatchingNameOrAlias(o.slice(1));const s=o.match(/\[(\w+)=['"]?(.+?)['"]?\]/);if(!s)return!0;const[,l,c]=s;return r.props[l].toString()===c})}var cA=lg("tscircuit:primitive-component:selectAll"),X_=class extends GHe{constructor(e){super(e);dt(this,"parent",null);dt(this,"children");dt(this,"childrenPendingRemoval");dt(this,"props");dt(this,"_parsedProps");dt(this,"externallyAddedAliases");dt(this,"isPrimitiveContainer",!1);dt(this,"source_group_id",null);dt(this,"source_component_id",null);dt(this,"schematic_component_id",null);dt(this,"pcb_component_id",null);dt(this,"cad_component_id",null);this.children=[],this.childrenPendingRemoval=[],this.props=e??{},this.externallyAddedAliases=[];const t=this.config.zodProps.safeParse(e??{});if(t.success)this._parsedProps=t.data;else throw new Ttn(this.lowercaseComponentName,this.props,t.error.format())}get config(){return{componentName:"",zodProps:z.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}}get lowercaseComponentName(){return this.componentName.toLowerCase()}get isSubcircuit(){var e;return!!this.props.subcircuit||this.lowercaseComponentName==="group"&&((e=this==null?void 0:this.parent)==null?void 0:e.isRoot)}get isGroup(){return this.lowercaseComponentName==="group"}setProps(e){var i,a;const t=this.config.zodProps.parse({...this.props,...e}),n=this.props;this.props=t,this._parsedProps=this.config.zodProps.parse(e),this.onPropsChange({oldProps:n,newProps:t,changedProps:Object.keys(e)}),(a=(i=this.parent)==null?void 0:i.onChildChanged)==null||a.call(i,this)}computePcbPropsTransform(){const{_parsedProps:e}=this;return Lu($f(e.pcbX??0,e.pcbY??0),w5((e.pcbRotation??0)*Math.PI/180))}_computePcbGlobalTransformBeforeLayout(){var n,i,a;const{_parsedProps:e}=this,t=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if(t&&this.props.pcbX===void 0&&this.props.pcbY===void 0)return Lu(((n=this.parent)==null?void 0:n._computePcbGlobalTransformBeforeLayout())??w9(),Lu($f(t.x,t.y),w5((e.pcbRotation??0)*Math.PI/180)));if(this.isPcbPrimitive){const o=this.getPrimitiveContainer();if(o){const s=o._parsedProps.layer==="bottom",l=o._getGlobalPcbPositionBeforeLayout();if(s)return Lu($f(l.x,l.y),LT(),$f(-l.x,-l.y)),Lu(((i=this.parent)==null?void 0:i._computePcbGlobalTransformBeforeLayout())??w9(),LT(),this.computePcbPropsTransform())}}return Lu(((a=this.parent)==null?void 0:a._computePcbGlobalTransformBeforeLayout())??w9(),this.computePcbPropsTransform())}getPrimitiveContainer(){var e,t;return this.isPrimitiveContainer?this:((t=(e=this.parent)==null?void 0:e.getPrimitiveContainer)==null?void 0:t.call(e))??null}_getPcbCircuitJsonBounds(){return{center:{x:0,y:0},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getPcbPrimitiveFlippedHelpers(){const e=this.getPrimitiveContainer(),t=e?e._parsedProps.layer==="bottom":!1;return{isFlipped:t,maybeFlipLayer:i=>t?i==="top"?"bottom":"top":i}}_setPositionFromLayout(e){throw new Error(`_setPositionFromLayout not implemented for ${this.componentName}`)}computeSchematicPropsTransform(){const{_parsedProps:e}=this;return Lu($f(e.schX??0,e.schY??0))}computeSchematicGlobalTransform(){var t,n;const e=this._getSchematicGlobalManualPlacementTransform(this);return e||Lu(((n=(t=this.parent)==null?void 0:t.computeSchematicGlobalTransform)==null?void 0:n.call(t))??w9(),this.computeSchematicPropsTransform())}_getSchematicSymbolName(){const{_parsedProps:e}=this,t=this.config.schematicSymbolName;let n=e.schRotation;if(n===void 0&&(n=0),n=n%360,n<0&&(n+=360),e.schRotation!==void 0&&n%90!==0)throw new Error(`Schematic rotation ${e.schRotation} is not supported for ${this.componentName}`);const i=`${t}_horz`,a=`${t}_vert`,o=`${t}_up`,s=`${t}_down`,l=`${t}_left`,c=`${t}_right`;if(c in bb&&n===0)return c;if(o in bb&&n===90)return o;if(l in bb&&n===180)return l;if(s in bb&&n===270)return s;if(i in bb&&(n===0||n===180))return i;if(a in bb&&(n===90||n===270))return a;if(t in bb)return t}_getSchematicSymbolNameOrThrow(){const e=this._getSchematicSymbolName();if(!e)throw new Error(`No schematic symbol found (given: "${this.config.schematicSymbolName}")`);return e}getSchematicSymbol(){const e=this._getSchematicSymbolName();return e?bb[e]??null:null}_getPcbManualPlacementForComponent(e){var a;if(!this.isSubcircuit)return null;const t=this.props.layout,n=this.props.manualEdits;if(!t&&!n)return null;const i=((a=t==null?void 0:t.manual_pcb_placement_config)==null?void 0:a.positions)||(n==null?void 0:n.pcb_placements);if(!i)return null;for(const o of i)if(t&&Ble(e,o.selector)||e.props.name===o.selector)return Fr(this._computePcbGlobalTransformBeforeLayout(),o.center);return null}_getSchematicGlobalManualPlacementTransform(e){var n,i;const t=(n=this.getSubcircuit())==null?void 0:n._parsedProps.manualEdits;if(!t)return null;for(const a of t.schematic_placements??[])if((Ble(e,a.selector)||e.props.name===a.selector)&&a.relative_to==="group_center")return Lu(((i=this.parent)==null?void 0:i._computePcbGlobalTransformBeforeLayout())??w9(),$f(a.center.x,a.center.y));return null}_getGlobalPcbPositionBeforeLayout(){return Fr(this._computePcbGlobalTransformBeforeLayout(),{x:0,y:0})}_getGlobalSchematicPositionBeforeLayout(){return Fr(this.computeSchematicGlobalTransform(),{x:0,y:0})}get root(){var e;return((e=this.parent)==null?void 0:e.root)??null}onAddToParent(e){this.parent=e}onPropsChange(e){}onChildChanged(e){var t,n;(n=(t=this.parent)==null?void 0:t.onChildChanged)==null||n.call(t,e)}add(e){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(const t of e)this.add(t)}remove(e){this.children=this.children.filter(t=>t!==e),this.childrenPendingRemoval.push(e),e.shouldBeRemoved=!0}getSubcircuitSelector(){const e=this._parsedProps.name,t=e?`${this.lowercaseComponentName}.${e}`:this.lowercaseComponentName;return!this.parent||this.parent.isSubcircuit?t:`${this.parent.getSubcircuitSelector()} > ${t}`}getFullPathSelector(){var i,a;const e=this._parsedProps.name,t=e?`${this.lowercaseComponentName}.${e}`:this.lowercaseComponentName,n=(a=(i=this.parent)==null?void 0:i.getFullPathSelector)==null?void 0:a.call(i);return n?`${n} > ${t}`:t}getNameAndAliases(){return[this._parsedProps.name,...this._parsedProps.portHints??[]].filter(Boolean)}isMatchingNameOrAlias(e){return this.getNameAndAliases().includes(e)}isMatchingAnyOf(e){return this.getNameAndAliases().some(t=>e.map(n=>n.toString()).includes(t))}getPcbSize(){throw new Error(`getPcbSize not implemented for ${this.componentName}`)}doesSelectorMatch(e){const t=[this.componentName,this.lowercaseComponentName],n=[this._parsedProps.name].filter(Boolean),i=e.trim().split(/\> /)[0],a=i[0];return i.length>1?!1:!!(e==="*"||e[0]==="#"&&e.slice(1)===this.props.id||e[0]==="."&&n.includes(e.slice(1))||/^[a-zA-Z0-9_]/.test(a)&&t.includes(a))}getSubcircuit(){var t,n;if(this.isSubcircuit)return this;const e=(n=(t=this.parent)==null?void 0:t.getSubcircuit)==null?void 0:n.call(t);if(!e)throw new Error("Component is not inside an opaque group (no board?)");return e}getGroup(){var e,t;return this.isGroup?this:((t=(e=this.parent)==null?void 0:e.getGroup)==null?void 0:t.call(e))??null}selectAll(e){cA(`selectAll: "${e}"`);const t=e.trim().split(/\s+/);let n=t[0]===">"?this.children:this.getSelectableDescendants(),i=[],a=!1,o=-1;for(const s of t)if(o++,cA(`
13363
13363
 
13364
13364
  iteration: ${o}`),cA(`part: "${t[o]}"`),cA(`currentSearch: [${n.map(l=>l.getString()).join(",")}]`),cA(`currentResults: [${i.map(l=>l.getString()).join(",")}]`),s===">")a=!0;else{const l=n.filter(u=>Ble(u,s));n=l.flatMap(u=>a?u.children:u.getSelectableDescendants()),i=l,a=!1}return i}selectOne(e,t){var i;let n=(i=t==null?void 0:t.type)==null?void 0:i.toLowerCase();return t!=null&&t.port&&(n="port"),n?this.selectAll(e).find(a=>a.lowercaseComponentName===n)??null:t!=null&&t.pcbPrimitive?this.selectAll(e).find(a=>a.isPcbPrimitive)??null:t!=null&&t.schematicPrimitive?this.selectAll(e).find(a=>a.isSchematicPrimitive)??null:this.selectAll(e)[0]??null}getAvailablePcbLayers(){var e,t;if(this.isPcbPrimitive){const{maybeFlipLayer:n}=this._getPcbPrimitiveFlippedHelpers();return"layer"in this._parsedProps||this.componentName==="SmtPad"?[n(this._parsedProps.layer??"top")]:"layers"in this._parsedProps?this._parsedProps.layers:this.componentName==="PlatedHole"?((t=(e=this.root)==null?void 0:e._getBoard())==null?void 0:t.allLayers)??["top","bottom"]:[]}return[]}getDescendants(){const e=[];for(const t of this.children)e.push(t),e.push(...t.getDescendants());return e}getSelectableDescendants(){const e=[];for(const t of this.children)t.isSubcircuit?e.push(t):(e.push(t),e.push(...t.getSelectableDescendants()));return e}_getPinCount(){return 0}_getSchematicBoxDimensions(){return null}renderError(e){var t;if(typeof e=="string")return super.renderError(e);(t=this.root)==null||t.db.pcb_placement_error.insert(e)}getString(){var i,a;const{lowercaseComponentName:e,_parsedProps:t,parent:n}=this;return(t==null?void 0:t.pinNumber)!==void 0&&((i=n==null?void 0:n.props)!=null&&i.name)&&(t!=null&&t.name)?`<${e}#${this._renderId}(pin:${t.pinNumber} .${n==null?void 0:n.props.name}>.${t.name}) />`:(a=n==null?void 0:n.props)!=null&&a.name&&(t!=null&&t.name)?`<${e}#${this._renderId}(.${n==null?void 0:n.props.name}>.${t==null?void 0:t.name}) />`:t!=null&&t.from&&(t!=null&&t.to)?`<${e}#${this._renderId}(from:${t.from} to:${t==null?void 0:t.to}) />`:t!=null&&t.name?`<${e}#${this._renderId} name=".${t==null?void 0:t.name}" />`:t!=null&&t.portHints?`<${e}#${this._renderId}(${t.portHints.map(o=>`.${o}`).join(", ")}) />`:`<${e}#${this._renderId} />`}get[Symbol.toStringTag](){return this.getString()}[Symbol.for("nodejs.util.inspect.custom")](){return this.getString()}};function YHe(r){const e=[];for(let t=0;t<r.length-1;t++)e.push([r[t],r[t+1]]);return e}var Mtn=z.object({name:z.string()}),XHe=class extends X_{constructor(){super(...arguments);dt(this,"source_net_id")}get config(){return{componentName:"Net",zodProps:Mtn}}getPortSelector(){return`net.${this.props.name}`}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_net.insert({name:t.name,member_source_group_ids:[]});this.source_net_id=n.source_net_id}doInitialSourceParentAttachment(){const e=this.getSubcircuit();if(!e)return;const{db:t}=this.root;t.source_net.update(this.source_net_id,{subcircuit_id:e.subcircuit_id})}getAllConnectedPorts(){const e=this.getSubcircuit().selectAll("port"),t=[];for(const n of e){const i=n._getDirectlyConnectedTraces();for(const a of i)if(a._isExplicitlyConnectedToNet(this)){t.push(n);break}}return t}_getAllDirectlyConnectedTraces(){const e=this.getSubcircuit().selectAll("trace"),t=[];for(const n of e)n._isExplicitlyConnectedToNet(this)&&t.push(n);return t}doInitialPcbRouteNetIslands(){var o;if((o=this.root)!=null&&o.pcbDisabled||this.getSubcircuit()._parsedProps.routingDisabled||this.getSubcircuit()._getAutorouterConfig().groupMode!=="sequential-trace")return;const{db:e}=this.root,{_parsedProps:t}=this,n=this._getAllDirectlyConnectedTraces().filter(s=>{var l;return(((l=s._portsRoutedOnPcb)==null?void 0:l.length)??0)>0}),i=[];for(const s of n){const l=s._portsRoutedOnPcb,c=i.find(u=>l.some(f=>u.ports.includes(f)));if(!c){i.push({ports:[...l],traces:[s]});continue}c.traces.push(s),c.ports.push(...l)}if(i.length===0)return;const a=YHe(i);for(const[s,l]of a){const c=s.ports.map(P=>P._getGlobalPcbPositionBeforeLayout()),u=l.ports.map(P=>P._getGlobalPcbPositionBeforeLayout());let f=1/0,m=[-1,-1];for(let P=0;P<c.length;P++){const O=c[P];for(let F=0;F<u.length;F++){const $=u[F],Z=Math.sqrt((O.x-$.x)**2+(O.y-$.y)**2);Z<f&&(f=Z,m=[P,F])}}const g=s.ports[m[0]],x=l.ports[m[1]],M=e.toArray().filter(P=>P.type==="pcb_smtpad"||P.type==="pcb_trace"||P.type==="pcb_plated_hole"||P.type==="pcb_hole"||P.type==="source_port"||P.type==="pcb_port"),{solution:T}=Xme(M.concat([{type:"source_trace",source_trace_id:"__net_trace_tmp",connected_source_port_ids:[g.source_port_id,x.source_port_id]}])),w=T[0];if(!w){this.renderError({pcb_trace_error_id:"",pcb_trace_id:"__net_trace_tmp",pcb_component_ids:[g.pcb_component_id,x.pcb_component_id].filter(Boolean),pcb_port_ids:[g.pcb_port_id,x.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(w)}}renderError(e){var t;if(typeof e=="string")return super.renderError(e);(t=this.root)==null||t.db.pcb_trace_error.insert(e)}},WHe=(r,e)=>{for(const t of e)if(typeof t=="string"&&t.startsWith("net.")){const n=r.getSubcircuit();if(!n.selectOne(t)){const i=new XHe({name:t.split("net.")[1]});n.add(i)}}},jle=class extends X_{constructor(){super(...arguments);dt(this,"pcb_smtpad_id",null);dt(this,"matchedPort",null);dt(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SmtPad",zodProps:ken}}getPcbSize(){const{_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};throw new Error(`getPcbSize for shape "${e.shape}" not implemented for ${this.componentName}`)}doInitialPortMatching(){var t;const e=(t=this.getPrimitiveContainer())==null?void 0:t.selectAll("port");if(this.props.portHints){for(const n of e)if(n.isMatchingAnyOf(this.props.portHints)){this.matchedPort=n,n.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){var m,g,x,M,T,w,P,O,F;if((m=this.root)!=null&&m.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this;if(!t.portHints)return;const n=this.getPrimitiveContainer(),i=this.getSubcircuit(),a=this._getGlobalPcbPositionBeforeLayout();n==null||n._getGlobalPcbPositionBeforeLayout();const o=DT(this._computePcbGlobalTransformBeforeLayout()),s=Math.abs(o.rotation.angle*(180/Math.PI)-90)%180<.01,{maybeFlipLayer:l}=this._getPcbPrimitiveFlippedHelpers(),c=(n==null?void 0:n._parsedProps.pcbRotation)??0;let u=null;const f=((g=this.parent)==null?void 0:g.pcb_component_id)??((x=this.getPrimitiveContainer())==null?void 0:x.pcb_component_id);t.shape==="circle"?(u=e.pcb_smtpad.insert({pcb_component_id:f,pcb_port_id:(M=this.matchedPort)==null?void 0:M.pcb_port_id,layer:l(t.layer??"top"),shape:"circle",radius:t.radius,port_hints:t.portHints.map($=>$.toString()),x:a.x,y:a.y,subcircuit_id:(i==null?void 0:i.subcircuit_id)??void 0}),e.pcb_solder_paste.insert({layer:u.layer,shape:"circle",radius:u.radius*.7,x:u.x,y:u.y,pcb_component_id:u.pcb_component_id,pcb_smtpad_id:u.pcb_smtpad_id,subcircuit_id:(i==null?void 0:i.subcircuit_id)??void 0,pcb_group_id:((T=this.getGroup())==null?void 0:T.pcb_group_id)??void 0})):t.shape==="rect"&&(u=c===0||s?e.pcb_smtpad.insert({pcb_component_id:f,pcb_port_id:(w=this.matchedPort)==null?void 0:w.pcb_port_id,layer:l(t.layer??"top"),shape:"rect",width:s?t.height:t.width,height:s?t.width:t.height,port_hints:t.portHints.map($=>$.toString()),x:a.x,y:a.y,subcircuit_id:(i==null?void 0:i.subcircuit_id)??void 0,pcb_group_id:((P=this.getGroup())==null?void 0:P.pcb_group_id)??void 0}):e.pcb_smtpad.insert({pcb_component_id:f,layer:t.layer??"top",shape:"rotated_rect",width:t.width,height:t.height,x:a.x,y:a.y,ccw_rotation:c,port_hints:t.portHints.map($=>$.toString()),subcircuit_id:(i==null?void 0:i.subcircuit_id)??void 0,pcb_group_id:((O=this.getGroup())==null?void 0:O.pcb_group_id)??void 0}),u.shape==="rect"&&e.pcb_solder_paste.insert({layer:u.layer,shape:"rect",width:u.width*.7,height:u.height*.7,x:u.x,y:u.y,pcb_component_id:u.pcb_component_id,pcb_smtpad_id:u.pcb_smtpad_id,subcircuit_id:(i==null?void 0:i.subcircuit_id)??void 0,pcb_group_id:((F=this.getGroup())==null?void 0:F.pcb_group_id)??void 0})),u&&(this.pcb_smtpad_id=u.pcb_smtpad_id)}doInitialPcbPortAttachment(){var t,n;if((t=this.root)!=null&&t.pcbDisabled)return;const{db:e}=this.root;e.pcb_smtpad.update(this.pcb_smtpad_id,{pcb_port_id:(n=this.matchedPort)==null?void 0:n.pcb_port_id})}_getPcbCircuitJsonBounds(){const{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"){const n=t.ccw_rotation*Math.PI/180,i=Math.cos(n),a=Math.sin(n),o=t.width/2,s=t.height/2,l=Math.abs(o*i)+Math.abs(s*a),c=Math.abs(o*a)+Math.abs(s*i);return{center:{x:t.x,y:t.y},bounds:{left:t.x-l,right:t.x+l,top:t.y-c,bottom:t.y+c},width:l*2,height:c*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};throw new Error(`circuitJson bounds calculation not implemented for shape "${t.shape}"`)}_setPositionFromLayout(e){var i;const{db:t}=this.root;t.pcb_smtpad.update(this.pcb_smtpad_id,{x:e.x,y:e.y});const n=t.pcb_solder_paste.list().find(a=>a.pcb_smtpad_id===this.pcb_smtpad_id);t.pcb_solder_paste.update(n==null?void 0:n.pcb_solder_paste_id,{x:e.x,y:e.y}),(i=this.matchedPort)==null||i._setPositionFromLayout(e)}},ZHe=class extends X_{constructor(){super(...arguments);dt(this,"pcb_silkscreen_path_id",null);dt(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenPath",zodProps:ctn}}doInitialPcbPrimitiveRender(){var l,c,u;if((l=this.root)!=null&&l.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,{maybeFlipLayer:n}=this._getPcbPrimitiveFlippedHelpers(),i=n(t.layer??"top");if(i!=="top"&&i!=="bottom")throw new Error(`Invalid layer "${i}" for SilkscreenPath. Must be "top" or "bottom".`);const a=this._computePcbGlobalTransformBeforeLayout(),o=this.getSubcircuit(),s=e.pcb_silkscreen_path.insert({pcb_component_id:(c=this.parent)==null?void 0:c.pcb_component_id,layer:i,route:t.route.map(f=>{const m=Fr(a,{x:f.x,y:f.y});return{...f,x:m.x,y:m.y}}),stroke_width:t.strokeWidth??.1,subcircuit_id:(o==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((u=this.getGroup())==null?void 0:u.pcb_group_id)??void 0});this.pcb_silkscreen_path_id=s.pcb_silkscreen_path_id}getPcbSize(){const{_parsedProps:e}=this;if(!e.route||e.route.length===0)return{width:0,height:0};let t=1/0,n=-1/0,i=1/0,a=-1/0;for(const o of e.route)t=Math.min(t,o.x),n=Math.max(n,o.x),i=Math.min(i,o.y),a=Math.max(a,o.y);return{width:n-t,height:a-i}}},QHe=class extends X_{constructor(){super(...arguments);dt(this,"pcb_plated_hole_id",null);dt(this,"matchedPort",null);dt(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PlatedHole",zodProps:Sen}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){const{_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};throw new Error(`getPcbSize for shape "${e.shape}" not implemented for ${this.componentName}`)}_getPcbCircuitJsonBounds(){const{db:e}=this.root,t=e.pcb_plated_hole.get(this.pcb_plated_hole_id),n=this.getPcbSize();return{center:{x:t.x,y:t.y},bounds:{left:t.x-n.width/2,top:t.y+n.height/2,right:t.x+n.width/2,bottom:t.y-n.height/2},width:n.width,height:n.height}}_setPositionFromLayout(e){var n;const{db:t}=this.root;t.pcb_plated_hole.update(this.pcb_plated_hole_id,{x:e.x,y:e.y}),(n=this.matchedPort)==null||n._setPositionFromLayout(e)}doInitialPortMatching(){var t;const e=(t=this.getPrimitiveContainer())==null?void 0:t.selectAll("port");if(this.props.portHints){for(const n of e)if(n.isMatchingAnyOf(this.props.portHints)){this.matchedPort=n,n.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){var o,s,l,c,u,f,m;if((o=this.root)!=null&&o.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=this._getGlobalPcbPositionBeforeLayout(),i=((s=this.parent)==null?void 0:s.pcb_component_id)??((l=this.getPrimitiveContainer())==null?void 0:l.pcb_component_id),a=this.getSubcircuit();if(t.shape==="circle"){const g=e.pcb_plated_hole.insert({pcb_component_id:i,pcb_port_id:(c=this.matchedPort)==null?void 0:c.pcb_port_id,outer_diameter:t.outerDiameter,hole_diameter:t.holeDiameter,shape:"circle",port_hints:this.getNameAndAliases(),x:n.x,y:n.y,layers:["top","bottom"],subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((u=this.getGroup())==null?void 0:u.pcb_group_id)??void 0});this.pcb_plated_hole_id=g.pcb_plated_hole_id}else if(t.shape==="pill"||t.shape==="oval"){const g=e.pcb_plated_hole.insert({pcb_component_id:i,pcb_port_id:(f=this.matchedPort)==null?void 0:f.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:n.x,y:n.y,layers:["top","bottom"],subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((m=this.getGroup())==null?void 0:m.pcb_group_id)??void 0});this.pcb_plated_hole_id=g.pcb_plated_hole_id}}doInitialPcbPortAttachment(){var t,n;if((t=this.root)!=null&&t.pcbDisabled)return;const{db:e}=this.root;e.pcb_plated_hole.update(this.pcb_plated_hole_id,{pcb_port_id:(n=this.matchedPort)==null?void 0:n.pcb_port_id})}},Hle=class extends X_{constructor(){super(...arguments);dt(this,"pcb_keepout_id",null);dt(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Keepout",zodProps:otn}}doInitialPcbPrimitiveRender(){var l,c,u;if((l=this.root)!=null&&l.pcbDisabled)return;const e=this.getSubcircuit(),{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),a=DT(this._computePcbGlobalTransformBeforeLayout()),o=Math.abs(a.rotation.angle*(180/Math.PI)-90)%180<.01;let s=null;n.shape==="circle"?s=t.pcb_keepout.insert({layers:["top"],shape:"circle",radius:n.radius,center:{x:i.x,y:i.y},subcircuit_id:(e==null?void 0:e.subcircuit_id)??void 0,pcb_group_id:((c=e==null?void 0:e.getGroup())==null?void 0:c.pcb_group_id)??void 0}):n.shape==="rect"&&(s=t.pcb_keepout.insert({layers:["top"],shape:"rect",...o?{width:n.height,height:n.width}:{width:n.width,height:n.height},center:{x:i.x,y:i.y},subcircuit_id:(e==null?void 0:e.subcircuit_id)??void 0,pcb_group_id:((u=e==null?void 0:e.getGroup())==null?void 0:u.pcb_group_id)??void 0})),s&&(this.pcb_keepout_id=s.pcb_keepout_id)}},KHe=class extends X_{constructor(){super(...arguments);dt(this,"pcb_hole_id",null);dt(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Hole",zodProps:Ben}}getPcbSize(){const{_parsedProps:e}=this;return{width:e.diameter,height:e.diameter}}doInitialPcbPrimitiveRender(){var o,s;if((o=this.root)!=null&&o.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=this.getSubcircuit(),i=this._getGlobalPcbPositionBeforeLayout(),a=e.pcb_hole.insert({hole_shape:"circle",hole_diameter:t.diameter,x:i.x,y:i.y,subcircuit_id:(n==null?void 0:n.subcircuit_id)??void 0,pcb_group_id:((s=n==null?void 0:n.getGroup())==null?void 0:s.pcb_group_id)??void 0});this.pcb_hole_id=a.pcb_hole_id}_getPcbCircuitJsonBounds(){const{db:e}=this.root,t=e.pcb_hole.get(this.pcb_hole_id),n=this.getPcbSize();return{center:{x:t.x,y:t.y},bounds:{left:t.x-n.width/2,top:t.y-n.height/2,right:t.x+n.width/2,bottom:t.y+n.height/2},width:n.width,height:n.height}}_setPositionFromLayout(e){const{db:t}=this.root;t.pcb_hole.update(this.pcb_hole_id,{x:e.x,y:e.y})}},JHe=class extends X_{constructor(){super(...arguments);dt(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenText",zodProps:ltn}}doInitialPcbPrimitiveRender(){var s,l;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=this.getPrimitiveContainer(),i=this._getGlobalPcbPositionBeforeLayout(),{maybeFlipLayer:a}=this._getPcbPrimitiveFlippedHelpers(),o=this.getSubcircuit();e.pcb_silkscreen_text.insert({anchor_alignment:t.anchorAlignment,anchor_position:{x:i.x,y:i.y},font:t.font??"tscircuit2024",font_size:t.fontSize??1,layer:a(t.layer??"top"),text:t.text??"",ccw_rotation:t.pcbRotation,pcb_component_id:n.pcb_component_id,subcircuit_id:(o==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((l=this.getGroup())==null?void 0:l.pcb_group_id)??void 0})}getPcbSize(){const{_parsedProps:e}=this,t=e.fontSize??1,i=(e.text??"").length*t,a=t;return{width:i*t,height:a*t}}},Ctn=({componentName:r,componentRotation:e},t)=>{const n=[];for(const i of t)if(i.type==="pcb_smtpad"&&i.shape==="rect")n.push(new jle({pcbX:i.x,pcbY:i.y,layer:i.layer,shape:"rect",height:i.height,width:i.width,portHints:i.port_hints}));else if(i.type==="pcb_smtpad"&&i.shape==="circle")n.push(new jle({pcbX:i.x,pcbY:i.y,layer:i.layer,shape:"circle",radius:i.radius,portHints:i.port_hints}));else if(i.type==="pcb_silkscreen_path")n.push(new ZHe({layer:i.layer,route:i.route,strokeWidth:i.stroke_width}));else if(i.type==="pcb_plated_hole"&&i.shape==="circle")i.shape==="circle"&&n.push(new QHe({pcbX:i.x,pcbY:i.y,shape:"circle",holeDiameter:i.hole_diameter,outerDiameter:i.outer_diameter,portHints:i.port_hints}));else if(i.type==="pcb_keepout"&&i.shape==="circle")n.push(new Hle({pcbX:i.center.x,pcbY:i.center.y,shape:"circle",radius:i.radius}));else if(i.type==="pcb_keepout"&&i.shape==="rect")n.push(new Hle({pcbX:i.center.x,pcbY:i.center.y,shape:"rect",width:i.width,height:i.height}));else if(i.type==="pcb_hole"&&i.hole_shape==="circle")n.push(new KHe({pcbX:i.x,pcbY:i.y,diameter:i.hole_diameter}));else if(i.type==="pcb_silkscreen_text"){let a=e?parseInt(e):0;const o=(a%360+360)%360;a=o>90&&o<=270?(o+180)%360:o,n.push(new JHe({anchorAlignment:"center",text:r,fontSize:i.font_size+.2,pcbX:isNaN(i.anchor_position.x)?0:i.anchor_position.x,pcbY:i.anchor_position.y,pcbRotation:a??0}))}return n};function eVe(r){let e=1/0,t=1/0,n=-1/0,i=-1/0;for(const s of r)if(s.isPcbPrimitive&&!s.componentName.startsWith("Silkscreen")){const{x:l,y:c}=s._getGlobalPcbPositionBeforeLayout(),{width:u,height:f}=s.getPcbSize();e=Math.min(e,l-u/2),t=Math.min(t,c-f/2),n=Math.max(n,l+u/2),i=Math.max(i,c+f/2)}else if(s.componentName==="Footprint"){const l=eVe(s.children);e=Math.min(e,l.minX),t=Math.min(t,l.minY),n=Math.max(n,l.maxX),i=Math.max(i,l.maxY)}let a=n-e,o=i-t;return a<0&&(a=0),o<0&&(o=0),{minX:e,minY:t,maxX:n,maxY:i,width:a,height:o}}function Rtn(r,e){const t=e.x-r.x,n=e.y-r.y;return Math.abs(t)>Math.abs(n)?t>=0?"right":"left":n>=0?"up":"down"}var Atn=r=>{if(r.length<=1)return!0;const e=r.map(a=>{const o=a._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 a=0;a<e.length;a++)for(let o=a+1;o<e.length;o++){const s=e[a],l=e[o];t[a][o]=t[o][a]=!(s.right<l.left||s.left>l.right||s.bottom>l.top||s.top<l.bottom)}const n=new Set,i=a=>{n.add(a);for(let o=0;o<e.length;o++)t[a][o]&&!n.has(o)&&i(o)};return i(0),n.size===e.length},Ptn=r=>{if(r.length===0)throw new Error("Cannot get center of empty PCB primitives array");const e=r.map(i=>i._getPcbCircuitJsonBounds().center).filter(Boolean),t=e.reduce((i,a)=>i+a.x,0),n=e.reduce((i,a)=>i+a.y,0);return{x:t/e.length,y:n/e.length}},Ntn=z.object({name:z.string().optional(),pinNumber:z.number().optional(),aliases:z.array(z.string()).optional()}),OS=class extends X_{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);dt(this,"source_port_id",null);dt(this,"pcb_port_id",null);dt(this,"schematic_port_id",null);dt(this,"schematicSymbolPortDef",null);dt(this,"matchedComponents");dt(this,"facingDirection",null);dt(this,"originDescription",null);t.originDescription&&(this.originDescription=t.originDescription),this.matchedComponents=[]}get config(){return{componentName:"Port",zodProps:Ntn}}_getGlobalPcbPositionBeforeLayout(){const e=this.matchedComponents.find(n=>n.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==null?void 0:e._getGlobalPcbPositionBeforeLayout())??{x:0,y:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_port_id)return super._getPcbCircuitJsonBounds();const{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(){const e=this.parent;if(!e||!e._getInternallyConnectedPins)return[];const t=e._getInternallyConnectedPins();for(const n of t)if(n.some(i=>i===this))return n;return[]}_hasSchematicPort(){var n,i;if((n=this.parent)==null?void 0:n.getSchematicSymbol())return!!(this.schematicSymbolPortDef||this._getPortsInternallyConnectedToThisPort().some(o=>o.schematicSymbolPortDef));const t=(i=this==null?void 0:this.parent)==null?void 0:i._getSchematicBoxDimensions();return!!(t&&this.props.pinNumber!==void 0&&t.getPortPositionByPinNumber(this.props.pinNumber))}_getGlobalSchematicPositionBeforeLayout(){var n,i,a;const e=(n=this.parent)==null?void 0:n.getSchematicSymbol();if(e){let o=this.schematicSymbolPortDef;if(!o&&(o=((i=this._getPortsInternallyConnectedToThisPort().find(l=>l.schematicSymbolPortDef))==null?void 0:i.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?`);const s=Lu(this.parent.computeSchematicGlobalTransform(),$f(-e.center.x,-e.center.y));return Fr(s,o)}const t=(a=this==null?void 0:this.parent)==null?void 0:a._getSchematicBoxDimensions();if(t&&this.props.pinNumber!==void 0){const o=t.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 Fr(this.parent.computeSchematicGlobalTransform(),o)}throw new Error(`Couldn't find position for schematic_port for port ${this.getString()}`)}_getGlobalSchematicPositionAfterLayout(){const{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`);const 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(){const{_parsedProps:e}=this;return Array.from(new Set([...e.aliases??[],...e.name?[e.name]:[],...typeof e.pinNumber=="number"?[`pin${e.pinNumber}`,e.pinNumber.toString()]:[],...this.externallyAddedAliases??[]]))}isMatchingPort(e){return this.isMatchingAnyOf(e.getNameAndAliases())}getPortSelector(){var e;return`.${(e=this.parent)==null?void 0:e.props.name} > port.${this.props.name}`}getAvailablePcbLayers(){return Array.from(new Set(this.matchedComponents.flatMap(e=>e.getAvailablePcbLayers())))}_getDirectlyConnectedTraces(){return this.getSubcircuit().selectAll("trace").filter(n=>n._isExplicitlyConnectedToPort(this))}doInitialSourceRender(){var a,o;const{db:e}=this.root,{_parsedProps:t}=this,n=this.getNameAndAliases(),i=e.source_port.insert({name:t.name,pin_number:t.pinNumber,port_hints:n,source_component_id:(a=this.parent)==null?void 0:a.source_component_id,subcircuit_id:(o=this.getSubcircuit())==null?void 0:o.subcircuit_id});this.source_port_id=i.source_port_id}doInitialSourceParentAttachment(){var t,n,i,a,o;const{db:e}=this.root;if(!((t=this.parent)!=null&&t.source_component_id))throw new Error(`${this.getString()} has no parent source component (parent: ${(n=this.parent)==null?void 0:n.getString()})`);e.source_port.update(this.source_port_id,{source_component_id:(i=this.parent)==null?void 0:i.source_component_id,subcircuit_id:(a=this.getSubcircuit())==null?void 0:a.subcircuit_id}),this.source_component_id=(o=this.parent)==null?void 0:o.source_component_id}doInitialPcbPortRender(){var a,o,s,l,c;if((a=this.root)!=null&&a.pcbDisabled)return;const{db:e}=this.root,{matchedComponents:t}=this;if(!((o=this.parent)!=null&&o.pcb_component_id))throw new Error(`${this.getString()} has no parent pcb component, cannot render pcb_port (parent: ${(s=this.parent)==null?void 0:s.getString()})`);const n=t.filter(u=>u.isPcbPrimitive);if(n.length===0)return;let i=null;if(n.length===1&&(i=n[0]._getPcbCircuitJsonBounds().center),n.length>1){if(!Atn(n))throw new Error(`${this.getString()} has multiple non-overlapping pcb matches, unclear how to place pcb_port: ${n.map(u=>u.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)`);i=Ptn(n)}if(i){const u=this.getSubcircuit(),f=e.pcb_port.insert({pcb_component_id:(l=this.parent)==null?void 0:l.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:(u==null?void 0:u.subcircuit_id)??void 0,pcb_group_id:((c=this.getGroup())==null?void 0:c.pcb_group_id)??void 0,...i,source_port_id:this.source_port_id});this.pcb_port_id=f.pcb_port_id}else{const u=n[0];throw new Error(`${u.getString()} does not have a center or _getGlobalPcbPositionBeforeLayout method (needed for pcb_port placement)`)}}doInitialSchematicPortRender(){var f;const{db:e}=this.root,{_parsedProps:t}=this,n=this.getPrimitiveContainer();if(!n||!this._hasSchematicPort())return;const i=n._getGlobalSchematicPositionBeforeLayout(),a=this._getGlobalSchematicPositionBeforeLayout();let o=null;const s=n._getSchematicBoxDimensions();s&&t.pinNumber!==void 0&&(o=s.getPortPositionByPinNumber(t.pinNumber)),this.getSubcircuit().props._schDebugObjectsEnabled&&e.schematic_debug_object.insert({shape:"rect",center:a,size:{width:.1,height:.1},label:"obstacle"}),o!=null&&o.side?this.facingDirection={left:"left",right:"right",top:"up",bottom:"down"}[o.side]:this.facingDirection=Rtn(i,a);const l=e.source_port.get(this.source_port_id);let c;for(const m of(l==null?void 0:l.port_hints)??[])m.match(/^(pin)?\d+$/)||(c=m);const u=e.schematic_port.insert({schematic_component_id:(f=this.parent)==null?void 0:f.schematic_component_id,center:a,source_port_id:this.source_port_id,facing_direction:this.facingDirection,distance_from_component_edge:.4,side_of_component:o==null?void 0:o.side,pin_number:t.pinNumber,true_ccw_index:o==null?void 0:o.trueIndex,display_pin_label:c});this.schematic_port_id=u.schematic_port_id}_setPositionFromLayout(e){const{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)}},tVe=r=>{const e=r.find(t=>/^(pin)?\d+$/.test(t));return e?Number.parseInt(e.replace(/^pin/,"")):null};function uA(r,e){var a;const t=tVe(r);if(!t)return null;const i=[...r.filter(o=>o.toString()!==t.toString()&&o!==`pin${t}`),...((a=e==null?void 0:e.additionalAliases)==null?void 0:a[`pin${t}`])??[]];return new OS({pinNumber:t,aliases:i})}var Dtn=r=>{for(const e of["leftSide","rightSide","topSide","bottomSide"])if(e in r&&typeof r[e]=="number")throw new Error(`A number was specified for "${e}", you probably meant to use "size" not "side"`);return"leftSide"in r||"rightSide"in r||"topSide"in r||"bottomSide"in r},Ltn=r=>{var a,o,s,l;if(Dtn(r))return{leftSize:((a=r.leftSide)==null?void 0:a.pins.length)??0,rightSize:((o=r.rightSide)==null?void 0:o.pins.length)??0,topSize:((s=r.topSide)==null?void 0:s.pins.length)??0,bottomSize:((l=r.bottomSide)==null?void 0:l.pins.length)??0};const{leftSize:e=0,rightSize:t=0,topSize:n=0,bottomSize:i=0}=r;return{leftSize:e,rightSize:t,topSize:n,bottomSize:i}};function nVe(r){return r.leftSide!==void 0}var Otn=r=>{var T,w,P,O,F,$,Z,Q;const e=r.portDistanceFromEdge??.4;let t=r.schPortArrangement?Ltn(r.schPortArrangement):null;const n={left:0,right:0,top:0,bottom:0};let i=r.pinCount??null;if(i===null)if(t)i=t.leftSize+t.rightSize+t.topSize;else throw new Error("Could not determine pin count for the schematic box");if(i&&!t){const ee=Math.floor(i/2);t={leftSize:i-ee,rightSize:ee,topSize:0,bottomSize:0}}t||(t={leftSize:0,rightSize:0,topSize:0,bottomSize:0});const a=({side:ee,sideIndex:ie,truePinIndex:J})=>{var De,Ee,Pe,Te;if(!r.schPortArrangement||!nVe(r.schPortArrangement))return J+1;const de={left:"top-to-bottom",bottom:"left-to-right",right:"bottom-to-top",top:"right-to-left"}[ee],he=((Ee=(De=r.schPortArrangement)==null?void 0:De[`${ee}Side`])==null?void 0:Ee.direction)??de,_e=(Te=(Pe=r.schPortArrangement)==null?void 0:Pe[`${ee}Side`])==null?void 0:Te.pins;let Ce=ie;return he!==de&&(Ce=_e.length-ie-1),lA(_e[Ce],r.pinLabels)},o=[];let s=0,l=0;for(let ee=0;ee<t.leftSize;ee++){const ie=a({side:"left",sideIndex:ee,truePinIndex:l}),J=((T=r.numericSchPinStyle)==null?void 0:T[`pin${ie}`])??((w=r.numericSchPinStyle)==null?void 0:w[ie]);J!=null&&J.topMargin&&(s+=J.topMargin),o.push({trueIndex:l,pinNumber:ie,side:"left",distanceFromOrthogonalEdge:s}),J!=null&&J.bottomMargin&&(s+=J.bottomMargin),ee===t.leftSize-1?n.left=s:s+=r.schPinSpacing,l++}s=0;for(let ee=0;ee<t.bottomSize;ee++){const ie=a({side:"bottom",sideIndex:ee,truePinIndex:l}),J=((P=r.numericSchPinStyle)==null?void 0:P[`pin${ie}`])??((O=r.numericSchPinStyle)==null?void 0:O[ie]);J!=null&&J.leftMargin&&(s+=J.leftMargin),o.push({trueIndex:l,pinNumber:ie,side:"bottom",distanceFromOrthogonalEdge:s}),J!=null&&J.rightMargin&&(s+=J.rightMargin),ee===t.bottomSize-1?n.bottom=s:s+=r.schPinSpacing,l++}s=0;for(let ee=0;ee<t.rightSize;ee++){const ie=a({side:"right",sideIndex:ee,truePinIndex:l}),J=((F=r.numericSchPinStyle)==null?void 0:F[`pin${ie}`])??(($=r.numericSchPinStyle)==null?void 0:$[ie]);J!=null&&J.bottomMargin&&(s+=J.bottomMargin),o.push({trueIndex:l,pinNumber:ie,side:"right",distanceFromOrthogonalEdge:s}),J!=null&&J.topMargin&&(s+=J.topMargin),ee===t.rightSize-1?n.right=s:s+=r.schPinSpacing,l++}s=0;for(let ee=0;ee<t.topSize;ee++){const ie=a({side:"top",sideIndex:ee,truePinIndex:l}),J=((Z=r.numericSchPinStyle)==null?void 0:Z[`pin${ie}`])??((Q=r.numericSchPinStyle)==null?void 0:Q[ie]);J!=null&&J.rightMargin&&(s+=J.rightMargin),o.push({trueIndex:l,pinNumber:ie,side:"top",distanceFromOrthogonalEdge:s}),J!=null&&J.leftMargin&&(s+=J.leftMargin),ee===t.topSize-1?n.top=s:s+=r.schPinSpacing,l++}let c=r.schWidth;c||(c=Math.max(n.top+r.schPinSpacing*2,n.bottom+r.schPinSpacing*2));const u=r.pinLabels?Math.max(...Object.values(r.pinLabels).map(ee=>ee.length*.1)):0,f=u>0?1.1:0;c=Math.max(c,u+f);let m=r.schHeight;m||(m=Math.max(n.left+r.schPinSpacing*2,n.right+r.schPinSpacing*2));const g={left:{x:-c/2-e,y:n.left/2},bottom:{x:-n.bottom/2,y:-m/2-e},right:{x:c/2+e,y:-n.right/2},top:{x:n.top/2,y:m/2+e}},x={left:{x:0,y:-1},right:{x:0,y:1},top:{x:-1,y:0},bottom:{x:1,y:0}},M=o.map(ee=>{const{distanceFromOrthogonalEdge:ie,side:J}=ee,de=g[J],he=x[J];return{x:de.x+ie*he.x,y:de.y+ie*he.y,...ee}});return{getPortPositionByPinNumber(ee){const ie=M.find(J=>J.pinNumber.toString()===ee.toString());return ie||null},getSize(){return{width:c,height:m}},getSizeIncludingPins(){return{width:c+(t.leftSize||t.rightSize?.4:0),height:m+(t.topSize||t.bottomSize?.4:0)}},pinCount:i}},ztn=lg("tscircuit:core:footprint"),Utn=class extends X_{get config(){return{componentName:"Footprint",zodProps:Hen}}doInitialPcbFootprintLayout(){var f,m,g,x,M;if((f=this.root)!=null&&f.pcbDisabled)return;const r=this.children.filter(T=>T.componentName==="Constraint");if(r.length===0)return;const{isFlipped:e}=this._getPcbPrimitiveFlippedHelpers(),t=T=>e&&"left"in T&&"right"in T?{...T,left:T.right,right:T.left}:T,n=r.flatMap(T=>T._getAllReferencedComponents().componentsWithSelectors).map(({component:T,selector:w,componentSelector:P,edge:O})=>({component:T,selector:w,componentSelector:P,edge:O,bounds:T._getPcbCircuitJsonBounds()}));if(n.some(T=>T.edge))throw new Error("edge constraints not implemented yet for footprint layout, contributions welcome!");function i(T){return n.find(({selector:w})=>w===T)}const a=new o1e,o={};function s(T){return T in o||(o[T]=new CN(T),a.addEditVariable(o[T],qg.weak)),o[T]}for(const{selector:T,bounds:w}of n){const P=s(`${T}_x`),O=s(`${T}_y`);a.suggestValue(P,w.center.x),a.suggestValue(O,w.center.y)}for(const T of r){const w=T._parsedProps;if("xDist"in w){const{xDist:P,left:O,right:F,edgeToEdge:$,centerToCenter:Z}=t(w),Q=s(`${O}_x`),ee=s(`${F}_x`),ie=(m=i(O))==null?void 0:m.bounds,J=(g=i(F))==null?void 0:g.bounds;if(Z){const de=new cg(ee,[-1,Q]);a.addConstraint(new h3(de,Fx.Eq,w.xDist,qg.required))}else if($){const de=new cg(ee,-J.width/2,[-1,Q],-ie.width/2);a.addConstraint(new h3(de,Fx.Eq,w.xDist,qg.required))}}else if("yDist"in w){const{yDist:P,top:O,bottom:F,edgeToEdge:$,centerToCenter:Z}=w,Q=s(`${O}_y`),ee=s(`${F}_y`),ie=(x=i(O))==null?void 0:x.bounds,J=(M=i(F))==null?void 0:M.bounds;if(Z){const de=new cg(Q,[-1,ee]);a.addConstraint(new h3(de,Fx.Eq,w.yDist,qg.required))}else if($){const de=new cg(Q,ie.height/2,[-1,ee],-J.height/2);a.addConstraint(new h3(de,Fx.Eq,w.yDist,qg.required))}}else if("sameY"in w){const{for:P}=w;if(P.length<2)continue;const O=P.map($=>s(`${$}_y`)),F=new cg(...O.slice(1));a.addConstraint(new h3(F,Fx.Eq,O[0],qg.required))}else if("sameX"in w){const{for:P}=w;if(P.length<2)continue;const O=P.map($=>s(`${$}_x`)),F=new cg(...O.slice(1));a.addConstraint(new h3(F,Fx.Eq,O[0],qg.required))}}a.updateVariables(),ztn.enabled&&(console.log("Solution to layout constraints:"),console.table(Object.entries(o).map(([T,w])=>({var:T,val:w.value()}))));const l={left:1/0,right:-1/0,top:-1/0,bottom:1/0};for(const{selector:T,bounds:{width:w,height:P}}of n){const O=s(`${T}_x`),F=s(`${T}_y`),$=O.value()-w/2,Z=O.value()+w/2,Q=F.value()+P/2,ee=F.value()-P/2;l.left=Math.min(l.left,$),l.right=Math.max(l.right,Z),l.top=Math.max(l.top,Q),l.bottom=Math.min(l.bottom,ee)}const c={x:-(l.right+l.left)/2,y:-(l.top+l.bottom)/2},u=this.getPrimitiveContainer()._getGlobalPcbPositionBeforeLayout();c.x+=u.x,c.y+=u.y;for(const{component:T,selector:w}of n){const P=s(`${w}_x`),O=s(`${w}_y`);T._setPositionFromLayout({x:P.value()+c.x,y:O.value()+c.y})}}},ktn=(r,e)=>{if(!r)return;const t={};for(const[n,i]of Object.entries(r)){const a=lA(n,e),o={leftMargin:i.marginLeft??i.leftMargin,rightMargin:i.marginRight??i.rightMargin,topMargin:i.marginTop??i.topMargin,bottomMargin:i.marginBottom??i.bottomMargin};t[`pin${a}`]={...t[`pin${a}`],...o}}return t},rVe=class{constructor({input:r}){dt(this,"input");this.input=r}solveAndMapToTraces(){const r=[];for(const e of this.input.connections){if(e.pointsToConnect.length!==2)continue;const[t,n]=e.pointsToConnect,i={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:n.x,y:n.y,layer:"top",width:.1}]};r.push(i)}return r}},Itn=r=>{const e=Math.min(...r.map(a=>a.center.x)),t=Math.max(...r.map(a=>a.center.x)),n=Math.min(...r.map(a=>a.center.y)),i=Math.max(...r.map(a=>a.center.y));return{minX:e,maxX:t,minY:n,maxY:i}},iVe=["top","bottom","inner1","inner2"],SF=(r,e=[])=>{var s;const t=[];if(e.length===0){const l=r[0].layers;for(const c of l)t.push(...SF(r.slice(1),[c]));return t}if(r.length===0)return[];const n=r[0],i=n.via||n.optional_via,a=e[e.length-1];if(r.length===1){const l=n;return l.layers&&i?l.layers.map(c=>({layer_path:[...e,c]})):(s=l.layers)!=null&&s.includes(a)?[{layer_path:[...e,a]}]:[]}if(!i)return n.layers&&!n.layers.includes(a)?[]:SF(r.slice(1),e.concat([a]));const o=(n.optional_via?iVe:iVe.filter(l=>l!==a)).filter(l=>{var c;return!n.layers||((c=n.layers)==null?void 0:c.includes(l))});for(const l of o)t.push(...SF(r.slice(1),e.concat(l)));return t};function aVe(r){const e={x:r.to.x-r.from.x,y:r.to.y-r.from.y},t=Math.abs(e.x),n=Math.abs(e.y);return t>n?e.x>0?"right":"left":e.y>0?"down":"up"}function Bw(r,e){return Math.hypot(r.x-e.x,r.y-e.y)}var Ftn=r=>{if(r.length===1)return r[0];if(r.some(l=>l.length===0))throw new Error("Cannot merge routes with zero length");const e=[],t=r[0][0],n=r[0][r[0].length-1],i=r[1][0],a=r[1][r[1].length-1],o=Math.min(Bw(t,i),Bw(t,a)),s=Math.min(Bw(n,i),Bw(n,a));o<s?e.push(...r[0].reverse()):e.push(...r[0]);for(let l=1;l<r.length;l++){const c=e[e.length-1],u=r[l],f=u[0],m=u[u.length-1],g=Bw(c,f),x=Bw(c,m);g<x?e.push(...u):e.push(...u.reverse())}for(let l=1;l<e.length-1;l++){const c=e[l-1],u=e[l];c.route_type==="wire"&&u.route_type==="wire"&&c.layer!==u.layer&&e.splice(l,0,{x:c.x,y:c.y,from_layer:c.layer,to_layer:u.layer,route_type:"via"})}return e},Btn=(r,e)=>{const t="_getGlobalPcbPositionBeforeLayout"in r?r._getGlobalPcbPositionBeforeLayout():r,n="_getGlobalPcbPositionBeforeLayout"in e?e._getGlobalPcbPositionBeforeLayout():e;return Math.sqrt((t.x-n.x)**2+(t.y-n.y)**2)};function jtn(r,e){if(e.length===0)throw new Error("No candidates given to getClosest method");let t=e[0],n=1/0;for(const i of e){const a=Btn(r,i);a<n&&(t=i,n=a)}return t}var Htn=(r,e)=>{let t=0;t+=r.length??0,t+=e.filter(n=>n.is_crossing).length;for(let n=1;n<e.length;n++){const i=e[n-1],a=e[n],o=Math.abs(i.from.x-i.to.x)<.01,s=Math.abs(a.from.x-a.to.x)<.01;o!==s&&t++}return t},Vle=r=>({up:"bottom",down:"top",left:"right",right:"left"})[r]??null,Gle=({firstEdge:r,firstEdgePort:e,firstDominantDirection:t,lastEdge:n,lastEdgePort:i,lastDominantDirection:a})=>{if(r&&e)return Gle({lastEdge:{from:r.to,to:r.from},lastEdgePort:e,lastDominantDirection:t}).reverse().map(s=>({from:s.to,to:s.from}));let o=[];if(n&&i){const s={x:n.to.x,y:n.to.y};a==="left"||a==="right"?(s.x=i.position.x,o.push({from:n.to,to:{...s}}),o.push({from:s,to:{...i.position}})):(s.y=i.position.y,o.push({from:n.to,to:{...s}}),o.push({from:s,to:{...i.position}}))}return o=o.filter(s=>sA(s.from,s.to)>.01),o};function Vtn(r){try{return[r(),null]}catch(e){return[null,e]}}function Gtn(r){let e=0;for(let t=0;t<r.length;t++){const n=r[t];if(n.route_type==="wire"){const i=r[t+1];if(i){const a=i.x-n.x,o=i.y-n.y;e+=Math.sqrt(a*a+o*o)}}else n.route_type==="via"&&(e+=1.6)}return e}var qtn=r=>{var s,l;const e={left:{x:-.5,y:0},up:{x:.5,y:.5},right:{x:.5,y:0},down:{x:0,y:-.5}}[r.facingDirection],t=(s=r.parent)!=null&&s.config.shouldRenderAsSchematicBox?3:1,n=(l=r.parent)!=null&&l.config.shouldRenderAsSchematicBox&&(r.facingDirection==="left"||r.facingDirection==="right")?3:1,i=e.x,a=e.y,o=r.facingDirection==="up"?.5:0;return{schBoxVertOffset:t,schBoxHorzOffset:n,horzPortDirection:i,vertPortDirectionOffset:a,handleUp:o}},EF=({port:r,anchorPos:e,schDisplayLabel:t,source_trace_id:n},{db:i})=>{const a=qtn(r);i.schematic_net_label.insert({anchor_side:"top",center:{x:e.x+a.horzPortDirection*a.schBoxHorzOffset,y:e.y+a.vertPortDirectionOffset*a.schBoxVertOffset},source_net_id:r.source_port_id,text:t,anchor_position:{x:e.x+a.horzPortDirection*a.schBoxHorzOffset,y:e.y+a.vertPortDirectionOffset*a.schBoxVertOffset},symbol_name:"ground_horz"}),i.schematic_trace.insert({edges:[{from:{x:e.x,y:e.y},to:{x:e.x,y:e.y+a.handleUp*a.schBoxVertOffset}},{from:{x:e.x,y:e.y},to:{x:e.x+a.horzPortDirection*a.schBoxHorzOffset,y:e.y+a.vertPortDirectionOffset*a.schBoxVertOffset}}],junctions:[{x:e.x+a.horzPortDirection*a.schBoxHorzOffset,y:e.y+a.vertPortDirectionOffset*a.schBoxVertOffset}],source_trace_id:n})},qle=({db:r,source_trace_id:e,sameNetOnly:t,differentNetOnly:n})=>{!t&&!n&&(n=!0);const i=r.source_trace.get(e),a=[];for(const o of r.schematic_trace.list()){if(o.source_trace_id===e)continue;const s=r.source_trace.get(o.source_trace_id),l=(s==null?void 0:s.subcircuit_connectivity_map_key)===i.subcircuit_connectivity_map_key;n&&l||t&&!l||a.push(o)}return a},$tn=({edges:r,otherEdges:e})=>{const t=[...r];for(let n=0;n<t.length;n++){if(n>2e3)throw new Error("Over 2000 iterations spent inside createSchematicTraceCrossingSegments, you have triggered an infinite loop, please report this!");const i=t[n],a=Math.abs(i.from.x-i.to.x)<.01?"vertical":i.from.y===i.to.y?"horizontal":"not-orthogonal";if(a==="not-orthogonal")continue;const o=[];for(const M of e){const T=M.from.x===M.to.x?"vertical":M.from.y===M.to.y?"horizontal":"not-orthogonal";if(T==="not-orthogonal"||a===T)continue;if(jHe([i.from,i.to],[M.from,M.to],{lineThickness:.01})){const P=a==="vertical"?i.from.x:M.from.x,O=a==="vertical"?M.from.y:i.from.y,F={x:P,y:O};o.push({otherEdge:M,crossingPoint:F,distanceFromEdgeFrom:sA(i.from,F)})}}if(o.length===0)continue;let s=o[0];for(const M of o)M.distanceFromEdgeFrom<s.distanceFromEdgeFrom&&(s=M);const l=s.crossingPoint,c=.075;if(l.x===i.from.x&&l.y===i.from.y)continue;const u=htn(i.from,l),f={x:l.x-u.x*c/2,y:l.y-u.y*c/2},m={x:l.x+u.x*c/2,y:l.y+u.y*c/2},g=sA(m,i.to)<c,x=[{from:i.from,to:f},{from:f,to:m,is_crossing:!0},{from:m,to:i.to}];t.splice(n,1,...x),n+=x.length-2,g&&n++}return t},Ytn=(r,e)=>{if(r.from.x===r.to.x&&e.from.x===e.to.x)return null;if(r.from.x===r.to.x){const u=r.from.x,f=(e.to.y-e.from.y)/(e.to.x-e.from.x),m=e.from.y-f*e.from.x,g=f*u+m;return u>=Math.min(e.from.x,e.to.x)&&u<=Math.max(e.from.x,e.to.x)&&g>=Math.min(e.from.y,e.to.y)&&g<=Math.max(e.from.y,e.to.y)?{x:u,y:g}:null}if(e.from.x===e.to.x){const u=e.from.x,f=(r.to.y-r.from.y)/(r.to.x-r.from.x),m=r.from.y-f*r.from.x,g=f*u+m;return u>=Math.min(r.from.x,r.to.x)&&u<=Math.max(r.from.x,r.to.x)&&g>=Math.min(r.from.y,r.to.y)&&g<=Math.max(r.from.y,r.to.y)?{x:u,y:g}:null}const t=(r.to.y-r.from.y)/(r.to.x-r.from.x),n=r.from.y-t*r.from.x,i=(e.to.y-e.from.y)/(e.to.x-e.from.x),a=e.from.y-i*e.from.x;if(t===i)return null;const o=(a-n)/(t-i),s=t*o+n,l=o>=Math.min(r.from.x,r.to.x)&&o<=Math.max(r.from.x,r.to.x)&&s>=Math.min(r.from.y,r.to.y)&&s<=Math.max(r.from.y,r.to.y),c=o>=Math.min(e.from.x,e.to.x)&&o<=Math.max(e.from.x,e.to.x)&&s>=Math.min(e.from.y,e.to.y)&&s<=Math.max(e.from.y,e.to.y);return l&&c?{x:o,y:s}:null},Xtn=({edges:r,db:e,source_trace_id:t})=>{const n=qle({db:e,source_trace_id:t,sameNetOnly:!0}).flatMap(i=>i.edges);for(const i of r)for(const a of n){const o=Ytn(i,a);if(o)return`${o.x}${o.y}`,[{x:o.x,y:o.y}]}return[]},Wtn=(r,{db:e})=>{const t=r.map(n=>{const i=e.source_port.get(n.source_port_id);if(!(i!=null&&i.source_component_id))return null;const a=e.source_component.get(i.source_component_id);return(a==null?void 0:a.ftype)==="simple_capacitor"?a.max_decoupling_trace_length:null}).filter(n=>n!==null);if(t.length!==0)return Math.min(...t)},Ztn=r=>{var a;const e=r.root.db,t=r._findConnectedPorts().ports??[],n=new Set(t.map(o=>o.schematic_port_id)),i=[];for(const o of e.toArray()){if(o.type==="schematic_component"){const s=!!o.symbol_name,l=o.size.width>o.size.height?"horz":"vert";i.push({type:"rect",layers:["top"],center:o.center,width:o.size.width+(s&&l==="horz"?-.5:0),height:o.size.height+(s&&l==="vert"?-.5:0),connectedTo:[]})}if(o.type==="schematic_port"){if(n.has(o.schematic_port_id))continue;const s=o.facing_direction?mtn(o.facing_direction):{x:0,y:0};i.push({type:"rect",layers:["top"],center:{x:o.center.x-s.x*.1,y:o.center.y-s.y*.1},width:.1+Math.abs(s.x)*.3,height:.1+Math.abs(s.y)*.3,connectedTo:[]})}o.type==="schematic_text"&&i.push({type:"rect",layers:["top"],center:o.position,width:(((a=o.text)==null?void 0:a.length)??0)*.1,height:.2,connectedTo:[]}),o.type==="schematic_box"&&i.push({type:"rect",layers:["top"],center:{x:o.x,y:o.y},width:o.width,height:o.height,connectedTo:[]})}return i};function Qtn({ports:r,nets:e}){var t,n,i;if(r.length>=2)return`${(t=r[0])==null?void 0:t.selector} to ${(n=r[1])==null?void 0:n.selector}`;if(r.length===1&&e.length===1)return`${(i=r[0])==null?void 0:i.selector} to net.${e[0]._parsedProps.name}`}var Ktn=({edges:r,db:e,source_trace_id:t})=>{e.source_trace.get(t);const n=qle({db:e,source_trace_id:t,differentNetOnly:!0}).flatMap(a=>a.edges),i=a=>{const{from:o,to:s}=a;return o.x===s.x?"vertical":"horizontal"};for(const a of r){const o=i(a),s=()=>n.find(c=>i(c)===o&&jHe([a.from,a.to],[c.from,c.to],{lineThickness:.05}));let l=s();for(;l;)o==="horizontal"?(a.from.y+=.1,a.to.y+=.1):(a.from.x+=.1,a.to.x+=.1),l=s()}},Jtn=(r,{db:e})=>{const t=e.pcb_board.list()[0];if(t.outline){const l=t.outline,c=(u,f)=>{let m=!1;for(let g=0,x=f.length-1;g<f.length;x=g++){const M=f[g].x,T=f[g].y,w=f[x].x,P=f[x].y;T>u.y!=P>u.y&&u.x<(w-M)*(u.y-T)/(P-T)+M&&(m=!m)}return m};return r.some(u=>!c(u,l))}const n=t.width,i=t.height,a=t.center.x,o=t.center.y;return r.some(l=>l.x<a-n/2||l.y<o-i/2||l.x>a+n/2||l.y>o+i/2)},wF=r=>({...r._getGlobalPcbPositionAfterLayout(),layers:r.getAvailablePcbLayers()}),x7=class extends X_{constructor(e){super(e);dt(this,"source_trace_id",null);dt(this,"pcb_trace_id",null);dt(this,"schematic_trace_id",null);dt(this,"_portsRoutedOnPcb");dt(this,"subcircuit_connectivity_map_key",null);this._portsRoutedOnPcb=[]}get config(){return{zodProps:jen,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(){const{db:e}=this.root,{_parsedProps:t,parent:n}=this;if(!n)throw new Error("Trace has no parent");const a=this.getTracePortPathSelectors().map(o=>({selector:o,port:this.getSubcircuit().selectOne(o,{type:"port"})??null}));for(const{selector:o,port:s}of a)if(!s){const l=o.replace(/\>.*$/,""),c=this.getSubcircuit().selectOne(l);c?this.renderError(`Could not find port for selector "${o}" (did you forget to include the pin name?)
13365
- searched component ${c.getString()}, which has ports: ${c.children.filter(u=>u.componentName==="Port").map(u=>`${u.getString()}(${u.getNameAndAliases().join(",")})`).join(" & ")}`):this.renderError(`Could not find port for selector "${o}"`)}return a.some(o=>!o.port)?{allPortsFound:!1}:{allPortsFound:!0,portsWithSelectors:a,ports:a.map(({port:o})=>o)}}_findConnectedNets(){const e=this.getTracePathNetSelectors().map(n=>({selector:n,net:this.getSubcircuit().selectOne(n,{type:"net"})})),t=e.filter(n=>!n.net);return t.length>0&&this.renderError(`Could not find net for selector "${t[0].selector}" inside ${this}`),{netsWithSelectors:e,nets:e.map(n=>n.net)}}_getAllTracesConnectedToSameNet(){const e=this.getSubcircuit().selectAll("trace"),t=this._findConnectedNets().nets,n=this._findConnectedPorts().ports??[];return e.filter(i=>{if(i===this)return!1;const a=i._findConnectedNets().nets,o=i._findConnectedPorts().ports??[];return a.some(s=>t.includes(s))||o.some(s=>n.includes(s))})}_isExplicitlyConnectedToPort(e){const{allPortsFound:t,portsWithSelectors:n}=this._findConnectedPorts();return t?n.map(a=>a.port).includes(e):!1}_isExplicitlyConnectedToNet(e){return this._findConnectedNets().nets.includes(e)}doInitialCreateNetsFromProps(){WHe(this,this.getTracePathNetSelectors())}doInitialSourceTraceRender(){var c;const{db:e}=this.root,{_parsedProps:t,parent:n}=this;if(!n){this.renderError("Trace has no parent");return}const{allPortsFound:i,portsWithSelectors:a}=this._findConnectedPorts();if(!i)return;const o=this._findConnectedNets().nets,s=Qtn({ports:a,nets:o}),l=e.source_trace.insert({connected_source_port_ids:a.map(u=>u.port.source_port_id),connected_source_net_ids:o.map(u=>u.source_net_id),subcircuit_id:(c=this.getSubcircuit())==null?void 0:c.subcircuit_id,max_length:Wtn(a.map(u=>u.port),{db:e})??t.maxLength,display_name:s,min_trace_thickness:t.thickness});this.source_trace_id=l.source_trace_id}_insertErrorIfTraceIsOutsideBoard(e,t){const{db:n}=this.root;Jtn(e,{db:n})&&n.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(a=>a.pcb_port_id)})}doInitialPcbTraceRender(){var ee,ie,J,de;if((ee=this.root)!=null&&ee.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t,parent:n}=this,i=this.getSubcircuit();if(!n)throw new Error("Trace has no parent");if(i._parsedProps.routingDisabled)return;const a=(ie=i._parsedProps.pcbRouteCache)==null?void 0:ie.pcbTraces;if(a){const he=e.pcb_trace.insert({route:a.flatMap(_e=>_e.route),source_trace_id:this.source_trace_id,subcircuit_id:(i==null?void 0:i.subcircuit_id)??void 0,pcb_group_id:((J=this.getGroup())==null?void 0:J.pcb_group_id)??void 0});this.pcb_trace_id=he.pcb_trace_id;return}if(!i._shouldUseTraceByTraceRouting())return;const{allPortsFound:o,ports:s}=this._findConnectedPorts();if(!o)return;const l=[];for(const he of s)he._hasMatchedPcbPrimitive()||l.push(he);if(l.length>0){e.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:this.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, ${this} wasn't routed. Missing ports: ${l.map(he=>he.getString()).join(", ")}`,pcb_trace_id:this.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:l.map(he=>he.pcb_port_id).filter(Boolean)});return}const c=this._findConnectedNets().netsWithSelectors;if(s.length===0&&c.length===2){this.renderError("Trace connects two nets, we haven't implemented a way to route this yet");return}else if(s.length===1&&c.length===1){const he=s[0],Ce=c[0].net.getAllConnectedPorts().filter(Ee=>Ee!==he);if(Ce.length===0){console.log("Nothing to connect this port to, the net is empty. TODO should emit a warning!");return}const De=jtn(he,Ce);s.push(De)}else if(s.length>1&&c.length>=1){this.renderError("Trace has more than one port and one or more nets, we don't currently support this type of complex trace routing");return}const u=s.flatMap(he=>he.matchedComponents.filter(_e=>_e.componentName==="TraceHint")),f=(this._parsedProps.pcbRouteHints??[]).concat(u.flatMap(he=>he.getPcbRouteHints()));if(s.length>2){this.renderError(`Trace has more than two ports (${s.map(he=>he.getString()).join(", ")}), routing between more than two ports for a single trace is not implemented`);return}if(this.getSubcircuit().selectAll("trace").filter(he=>he.renderPhaseStates.PcbTraceRender.initialized).some(he=>he._portsRoutedOnPcb.length===s.length&&he._portsRoutedOnPcb.every(_e=>s.includes(_e))))return;let x=[];f.length===0?x=[wF(s[0]),wF(s[1])]:x=[wF(s[0]),...f,wF(s[1])];const M=SF(x),T=kT(this.root.db.toArray()),[w,P]=Vtn(()=>EN(this.root.db.toArray()));if(P){this.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:this.pcb_trace_id,message:`Error getting obstacles for autorouting: ${P.message}`,source_trace_id:this.source_trace_id,center:{x:0,y:0},pcb_port_ids:s.map(he=>he.pcb_port_id),pcb_trace_id:this.pcb_trace_id,pcb_component_ids:[]});return}for(const he of w)if(he.connectedTo.length>0){const Ce=T.getNetConnectedToId(he.connectedTo[0]);Ce&&he.connectedTo.push(Ce)}let O=[];if(M.length===0)O=x;else{const he=M[0].layer_path;O=x.map((_e,Ce)=>_e.via?{..._e,via_to_layer:he[Ce]}:{..._e,layers:[he[Ce]]})}O[0].pcb_port_id=s[0].pcb_port_id,O[O.length-1].pcb_port_id=s[1].pcb_port_id;const F=[];for(const[he,_e]of YHe(O)){const Ce="via_to_layer"in he?he.via_to_layer:null,De=2,Ee="layers"in he&&he.layers.length===1?he.layers[0]:Ce??"top",Pe="layers"in _e&&_e.layers.length===1?_e.layers[0]:Ce??"top",Te="pcb_port_id"in he?he.pcb_port_id:null,Ie="pcb_port_id"in _e?_e.pcb_port_id:null,ze=this.getSubcircuit()._parsedProps.minTraceWidth??.16,He=new SN({OBSTACLE_MARGIN:ze*2,isRemovePathLoopsEnabled:!0,optimizeWithGoalBoxes:!!(Te&&Ie),connMap:T,input:{obstacles:w,minTraceWidth:ze,connections:[{name:this.source_trace_id,pointsToConnect:[{...he,layer:Ee,pcb_port_id:Te},{..._e,layer:Pe,pcb_port_id:Ie}]}],layerCount:2,bounds:{minX:Math.min(he.x,_e.x)-De,maxX:Math.max(he.x,_e.x)+De,minY:Math.min(he.y,_e.y)-De,maxY:Math.max(he.y,_e.y)+De}}});let Ue=null;try{Ue=He.solveAndMapToTraces()}catch(ht){this.renderError({type:"pcb_trace_error",pcb_trace_error_id:this.source_trace_id,error_type:"pcb_trace_error",message:`error solving route: ${ht.message}`,source_trace_id:this.pcb_trace_id,center:{x:(he.x+_e.x)/2,y:(he.y+_e.y)/2},pcb_port_ids:s.map(Tt=>Tt.pcb_port_id),pcb_trace_id:this.pcb_trace_id,pcb_component_ids:s.map(Tt=>Tt.pcb_component_id)})}if(!Ue)return;if(Ue.length===0){this.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:this.pcb_trace_id,message:`Could not find a route for ${this}`,source_trace_id:this.source_trace_id,center:{x:(he.x+_e.x)/2,y:(he.y+_e.y)/2},pcb_port_ids:s.map(ht=>ht.pcb_port_id),pcb_trace_id:this.pcb_trace_id,pcb_component_ids:s.map(ht=>ht.pcb_component_id)});return}const[at]=Ue;Ce&&(at.route=at.route.map(ht=>(ht.route_type==="wire"&&!ht.layer&&(ht.layer=Ce),ht))),Te&&at.route[0].route_type==="wire"&&(at.route[0].start_pcb_port_id=Te);const tt=at.route[at.route.length-1];Ie&&tt.route_type==="wire"&&(tt.end_pcb_port_id=Ie),F.push(at.route)}const $=Ftn(F),Z=Gtn($),Q=e.pcb_trace.insert({route:$,source_trace_id:this.source_trace_id,subcircuit_id:(de=this.getSubcircuit())==null?void 0:de.subcircuit_id,trace_length:Z});this._portsRoutedOnPcb=s,this.pcb_trace_id=Q.pcb_trace_id;for(const he of $)he.route_type==="via"&&e.pcb_via.insert({pcb_trace_id:Q.pcb_trace_id,x:he.x,y:he.y,hole_diameter:.3,outer_diameter:.6,layers:[he.from_layer,he.to_layer],from_layer:he.from_layer,to_layer:he.to_layer});this._insertErrorIfTraceIsOutsideBoard($,s)}_doInitialSchematicTraceRenderWithDisplayLabel(){var F,$,Z,Q;if((F=this.root)!=null&&F.schematicDisabled)return;const{db:e}=this.root,{_parsedProps:t,parent:n}=this;if(!n)throw new Error("Trace has no parent");const{allPortsFound:i,portsWithSelectors:a}=this._findConnectedPorts();if(!i)return;const o=a.map(({port:ee})=>({port:ee,position:ee._getGlobalSchematicPositionAfterLayout(),schematic_port_id:ee.schematic_port_id,facingDirection:ee.facingDirection}));if(o.length<2)throw new Error("Expected at least two ports in portsWithPosition.");let s,l;const c=o[0].position,u=o[0].port;if("path"in this.props){if(this.props.path.length!==2)throw new Error("Invalid 'path': Must contain exactly two elements.");[s,l]=this.props.path}else{if(!("from"in this.props&&"to"in this.props))throw new Error("Missing 'from' or 'to' properties in props.");s=this.props.from,l=this.props.to}if(!u.source_port_id)throw new Error(`Missing source_port_id for the 'from' port (${s}).`);const f=o[1].position,m=o[1].port;if(!m.source_port_id)throw new Error(`Missing source_port_id for the 'to' port (${l}).`);const g=e.schematic_net_label.list().find(ee=>ee.source_net_id===u.source_port_id),x=e.schematic_net_label.list().find(ee=>ee.source_net_id===m.source_port_id),[M,T]=a.map(({port:ee})=>ee),P=(($=M.parent)==null?void 0:$.config.shouldRenderAsSchematicBox)?`${(Z=M==null?void 0:M.parent)==null?void 0:Z.props.name}_${M==null?void 0:M.props.name}`:`${(Q=T==null?void 0:T.parent)==null?void 0:Q.props.name}_${T==null?void 0:T.props.name}`,O=this.props.schDisplayLabel??P;if(g&&g.text!==O&&(g.text=`${O} / ${g.text}`),x&&(x==null?void 0:x.text)!==O&&(x.text=`${O} / ${x.text}`),O!=null&&O.toLocaleLowerCase().includes("gnd")||O!=null&&O.toLocaleLowerCase().includes("ground")){!g&&!x?(EF({port:u,anchorPos:c,schDisplayLabel:this.props.schDisplayLabel,source_trace_id:this.source_trace_id},{db:e}),EF({port:m,anchorPos:f,schDisplayLabel:this.props.schDisplayLabel,source_trace_id:this.source_trace_id},{db:e})):g?x||EF({port:m,anchorPos:f,schDisplayLabel:this.props.schDisplayLabel,source_trace_id:this.source_trace_id},{db:e}):EF({port:u,anchorPos:c,schDisplayLabel:this.props.schDisplayLabel,source_trace_id:this.source_trace_id},{db:e});return}x||e.schematic_net_label.insert({text:this.props.schDisplayLabel??P,source_net_id:m.source_port_id,anchor_position:f,center:f,anchor_side:Vle(m.facingDirection)??"bottom"}),g||e.schematic_net_label.insert({text:this.props.schDisplayLabel??P,source_net_id:u.source_port_id,anchor_position:c,center:c,anchor_side:Vle(u.facingDirection)??"bottom"})}_isSymbolToChipConnection(){const{allPortsFound:e,ports:t}=this._findConnectedPorts();if(!e||t.length!==2)return!1;const[n,i]=t;if(!(n!=null&&n.parent)||!(i!=null&&i.parent))return!1;const a=n.parent.config.shouldRenderAsSchematicBox,o=i.parent.config.shouldRenderAsSchematicBox;return a&&!o||!a&&o}_isSymbolToSymbolConnection(){const{allPortsFound:e,ports:t}=this._findConnectedPorts();if(!e||t.length!==2)return!1;const[n,i]=t;if(!(n!=null&&n.parent)||!(i!=null&&i.parent))return!1;const a=!n.parent.config.shouldRenderAsSchematicBox,o=!i.parent.config.shouldRenderAsSchematicBox;return a&&o}_isChipToChipConnection(){const{allPortsFound:e,ports:t}=this._findConnectedPorts();if(!e||t.length!==2)return!1;const[n,i]=t;if(!(n!=null&&n.parent)||!(i!=null&&i.parent))return!1;const a=n.parent.config.shouldRenderAsSchematicBox,o=i.parent.config.shouldRenderAsSchematicBox;return a&&o}doInitialSchematicTraceRender(){var _e;if((_e=this.root)!=null&&_e.schematicDisabled)return;const{db:e}=this.root,{_parsedProps:t,parent:n}=this;if(!n)throw new Error("Trace has no parent");const{allPortsFound:i,portsWithSelectors:a}=this._findConnectedPorts(),{netsWithSelectors:o}=this._findConnectedNets();if(!i)return;if(this.props.schDisplayLabel&&("from"in this.props&&"to"in this.props||"path"in this.props)){this._doInitialSchematicTraceRenderWithDisplayLabel();return}const s={name:this.source_trace_id,pointsToConnect:[]},l=Ztn(this),c=a.map(({port:Ce})=>({port:Ce,position:Ce._getGlobalSchematicPositionAfterLayout(),schematic_port_id:Ce.schematic_port_id??void 0,facingDirection:Ce.facingDirection}));if(c.length===1&&o.length===1){const Ce=o[0].net,{port:De,position:Ee}=c[0];e.schematic_net_label.insert({text:Ce._parsedProps.name,source_net_id:Ce.source_net_id,anchor_position:Ee,center:Ee,anchor_side:Vle(De.facingDirection)??"bottom"});return}if(c.length<2)return;s.pointsToConnect=c.map(({position:Ce})=>({...Ce,layer:"top"}));const f=Itn(l),m=2,g={minTraceWidth:.1,obstacles:l,connections:[s],bounds:{minX:f.minX-m,maxX:f.maxX+m,minY:f.minY-m,maxY:f.maxY+m},layerCount:1};let x=SN,M=!1;this.getSubcircuit().props._schDirectLineRoutingEnabled&&(x=rVe,M=!0);let w=new x({input:g,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(w.length===0){if(this._isSymbolToChipConnection()||this._isSymbolToSymbolConnection()||this._isChipToChipConnection()){this._doInitialSchematicTraceRenderWithDisplayLabel();return}w=new rVe({input:g}).solveAndMapToTraces(),M=!0}const[{route:P}]=w;let O=[];for(let Ce=0;Ce<P.length-1;Ce++)O.push({from:P[Ce],to:P[Ce+1]});const F=this.source_trace_id;let $=[];if(!M){Ktn({edges:O,db:e,source_trace_id:F});const Ce=qle({db:e,source_trace_id:F,differentNetOnly:!0}).flatMap(De=>De.edges);O=$tn({edges:O,otherEdges:Ce}),$=Xtn({edges:O,db:e,source_trace_id:this.source_trace_id})}const Z=O[O.length-1],Q=c[c.length-1],ee=aVe(Z);O.push(...Gle({lastEdge:Z,lastEdgePort:Q,lastDominantDirection:ee}));const ie=O[0],J=c[0],de=aVe(ie);if(O.unshift(...Gle({firstEdge:ie,firstEdgePort:J,firstDominantDirection:de})),!this.source_trace_id)throw new Error("Missing source_trace_id for schematic trace insertion.");if(this.getSubcircuit()._parsedProps.schTraceAutoLabelEnabled&&Htn($,O)>=5&&(this._isSymbolToChipConnection()||this._isSymbolToSymbolConnection()||this._isChipToChipConnection())){this._doInitialSchematicTraceRenderWithDisplayLabel();return}const he=e.schematic_trace.insert({source_trace_id:this.source_trace_id,edges:O,junctions:$});this.schematic_trace_id=he.schematic_trace_id}},enn=lg("tscircuit:core"),tnn=z.object({x:LS,y:LS,z:LS}),Zx=class extends X_{constructor(e){super(e);dt(this,"reactSubtrees",[]);dt(this,"_impliedFootprint");dt(this,"isPrimitiveContainer",!0);dt(this,"_asyncSupplierPartNumbers");dt(this,"pcb_missing_footprint_error_id");this._addChildrenFromStringFootprint(),this.initPorts()}get defaultInternallyConnectedPinNames(){return[]}get internallyConnectedPinNames(){return this._parsedProps.internallyConnectedPins??this.defaultInternallyConnectedPinNames}initPorts(e={}){var o,s,l,c,u,f,m,g,x,M;if((o=this.root)!=null&&o.schematicDisabled)return;const{config:t}=this,n=[],i=this._getSchematicPortArrangement();if(i&&!this._parsedProps.pinLabels){for(const P in i){const O=i[P].pins;if(Array.isArray(O))for(const F of O){const $=lA(F,this._parsedProps.pinLabels);n.push(new OS({pinNumber:$,aliases:((s=e.additionalAliases)==null?void 0:s[`pin${$}`])??[]},{originDescription:`schPortArrangement:${P}`}))}}const T=["left","right","top","bottom"];let w=1;for(const P of T){const O=i[`${P}Size`];for(let F=0;F<O;F++)n.push(new OS({pinNumber:w++,aliases:((l=e.additionalAliases)==null?void 0:l[`pin${w}`])??[]},{originDescription:`schPortArrangement:${P}`}))}}const a=this._parsedProps.pinLabels;if(a)for(let[T,w]of Object.entries(a)){T=T.replace("pin","");let P=n.find($=>$._parsedProps.pinNumber===Number(T));const O=Array.isArray(w)?w[0]:w,F=Array.isArray(w)?w.slice(1):[];P?(P.externallyAddedAliases.push(O,...F),P.props.name=O):(P=new OS({pinNumber:parseInt(T),name:O,aliases:[...F,...((c=e.additionalAliases)==null?void 0:c[`pin${parseInt(T)}`])??[]]},{originDescription:`pinLabels:pin${T}`}),n.push(P))}if(t.schematicSymbolName){const T=bb[this._getSchematicSymbolNameOrThrow()];if(!T)return;for(const w of T.ports){const P=tVe(w.labels);if(!P)continue;const O=n.find(F=>F._parsedProps.pinNumber===Number(P));if(O)O.schematicSymbolPortDef=w;else{const F=uA(w.labels.concat(((u=e.additionalAliases)==null?void 0:u[`pin${P}`])??[]));F&&(F.originDescription=`schematicSymbol:labels[0]:${w.labels[0]}`,F.schematicSymbolPortDef=w,n.push(F))}}this.addAll(n)}if(!this._getSchematicPortArrangement()){const T=this.getPortsFromFootprint(e);for(const w of T)n.some(P=>P.isMatchingAnyOf(w.getNameAndAliases()))||n.push(w)}for(let T=1;T<=(e.pinCount??this._getPinCount());T++){if(!i||n.find(P=>P._parsedProps.pinNumber===T))continue;let w=[...((f=i.leftSide)==null?void 0:f.pins)??[],...((m=i.rightSide)==null?void 0:m.pins)??[],...((g=i.topSide)==null?void 0:g.pins)??[],...((x=i.bottomSide)==null?void 0:x.pins)??[]].map(P=>lA(P,this._parsedProps.pinLabels));["leftSize","rightSize","topSize","bottomSize","leftPinCount","rightPinCount","topPinCount","bottomPinCount"].some(P=>P in i)&&(w=Array.from({length:this._getPinCount()},(P,O)=>O+1)),w.includes(T)&&n.push(new OS({pinNumber:T,aliases:((M=e.additionalAliases)==null?void 0:M[`pin${T}`])??[]},{originDescription:`notOtherwiseAddedButDeducedFromPinCount:${T}`}))}n.length>0&&this.addAll(n)}_getImpliedFootprintString(){return null}_addChildrenFromStringFootprint(){var i;const{name:e,pcbRotation:t}=this.props;let{footprint:n}=this.props;if(n??(n=(i=this._getImpliedFootprintString)==null?void 0:i.call(this)),!!n&&typeof n=="string"){const a=sP.string(n).soup(),o=Ctn({componentName:e,componentRotation:t},a);this.addAll(o)}}get portMap(){return new Proxy({},{get:(e,t)=>{const n=this.children.find(i=>i.componentName==="Port"&&i.isMatchingNameOrAlias(t));if(!n)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 n}})}getInstanceForReactElement(e){for(const t of this.reactSubtrees)if(t.element===e)return t.component;return null}doInitialSourceRender(){const e=this.config.sourceFtype;if(!e)return;const{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:e,name:n.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers});this.source_component_id=i.source_component_id}doInitialSchematicComponentRender(){var n;if((n=this.root)!=null&&n.schematicDisabled)return;const{schematicSymbolName:e}=this.config;if(e)return this._doInitialSchematicComponentRenderWithSymbol();if(this._getSchematicBoxDimensions())return this._doInitialSchematicComponentRenderWithSchematicBoxDimensions()}_getSchematicSymbolDisplayValue(){}_getInternallyConnectedPins(){if(this.internallyConnectedPinNames.length===0)return[];const e=[];for(const t of this.internallyConnectedPinNames){const n=[];for(const i of t)n.push(this.portMap[i]);e.push(n)}return e}_doInitialSchematicComponentRenderWithSymbol(){var o;if((o=this.root)!=null&&o.schematicDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=this._getSchematicSymbolNameOrThrow(),i=bb[n],a=this._getGlobalSchematicPositionBeforeLayout();if(i){const s=e.schematic_component.insert({center:a,size:i.size,source_component_id:this.source_component_id,symbol_name:n,symbol_display_value:this._getSchematicSymbolDisplayValue()});this.schematic_component_id=s.schematic_component_id}}_doInitialSchematicComponentRenderWithSchematicBoxDimensions(){var f;if((f=this.root)!=null&&f.schematicDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=this._getSchematicBoxDimensions(),i={};if(Array.isArray(t.pinLabels))t.pinLabels.forEach((m,g)=>{i[String(g+1)]=m});else for(const[m,g]of Object.entries(t.pinLabels??{}))i[m]=Array.isArray(g)?g[0]:g;const a=this._getGlobalSchematicPositionBeforeLayout(),o=this._getSchematicPortArrangement(),s=e.schematic_component.insert({center:a,rotation:t.schRotation??0,size:n.getSize(),port_arrangement:wtn(o),pin_spacing:t.schPinSpacing??.2,pin_styles:Etn(t.schPinStyle,t.pinLabels),port_labels:i,source_component_id:this.source_component_id}),l=(o==null?void 0:o.topSide)!==void 0||(o==null?void 0:o.bottomSide)!==void 0,c=n==null?void 0:n.getSize().width,u=n==null?void 0:n.getSize().height;e.schematic_text.insert({text:t.manufacturerPartNumber??"",schematic_component_id:s.schematic_component_id,anchor:"left",rotation:0,position:{x:l?a.x+(c??0)/2+.1:a.x-(c??0)/2,y:l?a.y+(u??0)/2+.35:a.y-(u??0)/2-.13},color:"#006464"}),e.schematic_text.insert({text:t.name??"",schematic_component_id:s.schematic_component_id,anchor:"left",rotation:0,position:{x:l?a.x+(c??0)/2+.1:a.x-(c??0)/2,y:l?a.y+(u??0)/2+.55:a.y+(u??0)/2+.13},color:"#006464"}),this.schematic_component_id=s.schematic_component_id}doInitialPcbComponentRender(){var o;if((o=this.root)!=null&&o.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=this.getSubcircuit(),i=e.pcb_component.insert({center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,layer:t.layer??"top",rotation:t.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:n.subcircuit_id??void 0});if(!t.footprint&&!this.isGroup){const s=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=s.pcb_missing_footprint_error_id}this.pcb_component_id=i.pcb_component_id;const a=this.getSubcircuit()._getPcbManualPlacementForComponent(this);this.props.pcbX!==void 0&&this.props.pcbY!==void 0&&a&&this.renderError({type:"pcb_manual_edit_conflict_error",message:`${this.getString()} has both manual placement and explicit 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})}doInitialPcbComponentSizeCalculation(){var a;if((a=this.root)!=null&&a.pcbDisabled||!this.pcb_component_id)return;const{db:e}=this.root,{_parsedProps:t}=this,n=eVe(this.children);if(n.width===0||n.height===0)return;const i={x:(n.minX+n.maxX)/2,y:(n.minY+n.maxY)/2};e.pcb_component.update(this.pcb_component_id,{center:i,width:n.width,height:n.height})}_renderReactSubtree(e){return{element:e,component:Stn(e)}}doInitialInitializePortsFromChildren(){this.initPorts()}doInitialReactSubtreesRender(){if(wt.isValidElement(this.props.footprint)){if(this.reactSubtrees.some(t=>t.element===this.props.footprint))return;const e=this._renderReactSubtree(this.props.footprint);this.reactSubtrees.push(e),this.add(e.component)}}_hasExistingPortExactly(e){return this.children.filter(n=>n.componentName==="Port").some(n=>{const i=e.getNameAndAliases(),a=n.getNameAndAliases();return i.length===a.length&&i.every(o=>a.includes(o))})}add(e){let t;if(wt.isValidElement(e)){const n=this._renderReactSubtree(e);this.reactSubtrees.push(n),t=n.component}else t=e;if(t.componentName==="Port"){if(this._hasExistingPortExactly(t))return;const i=this.children.filter(a=>a.componentName==="Port").find(a=>a.isMatchingAnyOf(t.getNameAndAliases()));i&&enn(`Similar ports added. Port 1: ${i}, Port 2: ${t}`)}super.add(t)}getPortsFromFootprint(e){let{footprint:t}=this.props;if((!t||wt.isValidElement(t))&&(t=this.children.find(i=>i.componentName==="Footprint")),typeof t=="string"){const i=sP.string(t).soup(),a=[];for(const o of i)if("port_hints"in o&&o.port_hints){const s=uA(o.port_hints,e);if(!s)continue;s.originDescription=`footprint:string:${t}:port_hints[0]:${o.port_hints[0]}`,a.push(s)}return a}if(!wt.isValidElement(t)&&t&&t.componentName==="Footprint"){const i=t;let a=1;const o=[];for(const s of i.children){if(!s.props.portHints)continue;let l=s.props.portHints;l.some(f=>f.startsWith("pin"))||(l=[...l,`pin${a}`]),a++;const u=uA(l);u&&(u.originDescription=`footprint:${t}`,o.push(u))}return o}const n=[];if(!t){for(const i of this.children)if(i.props.portHints&&i.isPcbPrimitive){const a=uA(i.props.portHints);a&&n.push(a)}}return n}getPortsFromSchematicSymbol(){var i;if((i=this.root)!=null&&i.schematicDisabled)return[];const{config:e}=this;if(!e.schematicSymbolName)return[];const t=bb[e.schematicSymbolName];if(!t)return[];const n=[];for(const a of t.ports){const o=uA(a.labels);o&&(o.schematicSymbolPortDef=a,n.push(o))}return n}doInitialCreateNetsFromProps(){this._createNetsFromProps(this._getNetsFromConnectionsProp())}_getNetsFromConnectionsProp(){const{_parsedProps:e}=this,t=[];if(e.connections)for(const[n,i]of Object.entries(e.connections)){const a=Array.isArray(i)?i:[i];for(const o of a)t.push(o)}return t}_createNetsFromProps(e){WHe(this,e)}_getPcbCircuitJsonBounds(){const{db:e}=this.root;if(!this.pcb_component_id)return super._getPcbCircuitJsonBounds();const 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(){const e=this._getSchematicPortArrangement();if(!e)return 0;if(!nVe(e))return(e.leftSize??e.leftPinCount??0)+(e.rightSize??e.rightPinCount??0)+(e.topSize??e.topPinCount??0)+(e.bottomSize??e.bottomPinCount??0);const{leftSide:n,rightSide:i,topSide:a,bottomSide:o}=e;return Math.max(...(n==null?void 0:n.pins)??[],...(i==null?void 0:i.pins)??[],...(a==null?void 0:a.pins)??[],...(o==null?void 0:o.pins)??[])}_getPinCount(){return this._getSchematicPortArrangement()?this._getPinCountFromSchematicPortArrangement():this.getPortsFromFootprint().length}_getSchematicPortArrangement(){return this._parsedProps.schPinArrangement??this._parsedProps.schPortArrangement}_getSchematicBoxDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;const{_parsedProps:e}=this,t=this._getPinCount(),n=e.schPinSpacing??.2;return Otn({schWidth:e.schWidth,schHeight:e.schHeight,schPinSpacing:n,numericSchPinStyle:ktn(e.schPinStyle,e.pinLabels),pinCount:t,schPortArrangement:this._getSchematicPortArrangement(),pinLabels:e.pinLabels})}doInitialCadModelRender(){var c;const{db:e}=this.root,{boardThickness:t=0}=((c=this.root)==null?void 0:c._getBoard())??{},n=this._parsedProps.cadModel;if(!this.pcb_component_id||!n&&!this.props.footprint)return;const i=this._getPcbCircuitJsonBounds(),a=e.pcb_component.get(this.pcb_component_id);if(typeof n=="string")throw new Error("String cadModel not yet implemented");const o=tnn.parse({x:0,y:0,z:typeof(n==null?void 0:n.rotationOffset)=="number"?n.rotationOffset:0,...typeof(n==null?void 0:n.rotationOffset)=="object"?n.rotationOffset??{}:{}}),s=dI.parse({x:0,y:0,z:0,...typeof(n==null?void 0:n.positionOffset)=="object"?n.positionOffset:{}}),l=this.props.layer==="bottom"?"bottom":"top";e.cad_component.insert({position:{x:i.center.x+s.x,y:i.center.y+s.y,z:(l==="bottom"?-t/2:t/2)+s.z},rotation:{x:o.x,y:(l==="top"?0:180)+o.y,z:((a==null?void 0:a.rotation)??0)+(l==="bottom"?180:0)+o.z},pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,model_stl_url:"stlUrl"in(n??{})?this._addCachebustToModelUrl(n.stlUrl):void 0,model_obj_url:"objUrl"in(n??{})?this._addCachebustToModelUrl(n.objUrl):void 0,model_jscad:"jscad"in(n??{})?n.jscad:void 0,footprinter_string:typeof this.props.footprint=="string"&&!n?this.props.footprint:void 0})}_addCachebustToModelUrl(e){var n;if(!e||!e.includes("modelcdn.tscircuit.com"))return e;const t=((n=this.root)==null?void 0:n.getClientOrigin())??"";return`${e}${e.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(t)}`}doInitialPartsEngineRender(){const e=this.getInheritedProperty("partsEngine");if(!e)return;const{db:t}=this.root,n=t.source_component.get(this.source_component_id);if(!n||n.supplier_part_numbers)return;let i;this.props.footprint&&typeof this.props.footprint=="string"&&(i=this.props.footprint);const a=e.findPart({sourceComponent:n,footprinterString:i});if(!(a instanceof Promise)){t.source_component.update(this.source_component_id,{supplier_part_numbers:a});return}this._queueAsyncEffect("get-supplier-part-numbers",async()=>{this._asyncSupplierPartNumbers=await a,this._markDirty("PartsEngineRender")})}updatePartsEngineRender(){const{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}}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}_createTracesFromConnectionsProp(){const{_parsedProps:e}=this;if(e.connections)for(const[t,n]of Object.entries(e.connections)){const i=Array.isArray(n)?n:[n];for(const a of i)this.add(new x7({from:`${this.getSubcircuitSelector()} > port.${t}`,to:a}))}}},nnn=class{constructor(r,e={}){dt(this,"input");dt(this,"isRouting",!1);dt(this,"solver");dt(this,"eventHandlers",{complete:[],error:[],progress:[]});dt(this,"cycleCount",0);dt(this,"stepDelay");dt(this,"timeoutId");this.input=r;const{capacityDepth:t,targetMinCapacity:n,stepDelay:i=0}=e;this.solver=new H1e(r,{capacityDepth:t,targetMinCapacity:n}),this.stepDelay=i}start(){this.isRouting||(this.isRouting=!0,this.cycleCount=0,this.runCycleAndQueueNextCycle())}runCycleAndQueueNextCycle(){var r;if(this.isRouting)try{if(this.solver.solved||this.solver.failed){this.solver.failed?this.emitEvent({type:"error",error:new Error(this.solver.error||"Routing failed")}):this.emitEvent({type:"complete",traces:this.solver.getOutputSimpleRouteJson().traces||[]}),this.isRouting=!1;return}const e=Date.now(),t=this.solver.iterations;for(;Date.now()-e<250&&!this.solver.failed&&!this.solver.solved;)this.solver.step();const n=(this.solver.iterations-t)/(Date.now()-e)*1e3;this.cycleCount++;const i=((r=this.solver)==null?void 0:r.preview())||void 0,a=this.solver.progress;this.emitEvent({type:"progress",steps:this.cycleCount,iterationsPerSecond:n,progress:a,phase:this.solver.getCurrentPhase(),debugGraphics:i}),this.stepDelay>0?this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),this.stepDelay):this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),0)}catch(e){this.emitEvent({type:"error",error:e instanceof Error?e:new Error(String(e))}),this.isRouting=!1}}stop(){this.isRouting&&(this.isRouting=!1,this.timeoutId!==void 0&&(clearTimeout(this.timeoutId),this.timeoutId=void 0))}on(r,e){r==="complete"?this.eventHandlers.complete.push(e):r==="error"?this.eventHandlers.error.push(e):r==="progress"&&this.eventHandlers.progress.push(e)}emitEvent(r){if(r.type==="complete")for(const e of this.eventHandlers.complete)e(r);else if(r.type==="error")for(const e of this.eventHandlers.error)e(r);else if(r.type==="progress")for(const e of this.eventHandlers.progress)e(r)}solveSync(){if(this.solver.solve(),this.solver.failed)throw new Error(this.solver.error||"Routing failed");return this.solver.getOutputSimpleRouteJson().traces||[]}},oVe=class extends X_{constructor(){super(...arguments);dt(this,"matchedPort",null)}get config(){return{componentName:"TraceHint",zodProps:ptn}}doInitialPortMatching(){const{db:e}=this.root,{_parsedProps:t,parent:n}=this;if(!n)return;if(n.componentName==="Trace"){this.renderError(`Port inference inside trace is not yet supported (${this})`);return}if(!n)throw new Error("TraceHint has no parent");if(!t.for){this.renderError(`TraceHint has no for property (${this})`);return}const i=n.selectOne(t.for,{type:"port"});i||this.renderError(`${this} could not find port for selector "${t.for}"`),this.matchedPort=i,i.registerMatch(this)}getPcbRouteHints(){const{_parsedProps:e}=this,t=e.offset?[e.offset]:e.offsets;if(!t)return[];const n=this._computePcbGlobalTransformBeforeLayout();return t.map(i=>({...Fr(n,i),via:i.via,to_layer:i.to_layer,trace_width:i.trace_width}))}doInitialPcbTraceHintRender(){var n,i,a;if((n=this.root)!=null&&n.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this;e.pcb_trace_hint.insert({pcb_component_id:(i=this.matchedPort)==null?void 0:i.pcb_component_id,pcb_port_id:(a=this.matchedPort)==null?void 0:a.pcb_port_id,route:this.getPcbRouteHints()})}},rnn=(r,e)=>{const t=r.source_group.list(),n=[],i=a=>{const o=t.filter(s=>s.parent_subcircuit_id===a);for(const s of o)s.subcircuit_id&&(n.push(s.subcircuit_id),i(s.subcircuit_id))};return i(e),n},sVe=({db:r,circuitJson:e,subcircuit_id:t,minTraceWidth:n=.1})=>{if(!r&&e&&(r=wv(e)),!r)throw new Error("db or circuitJson is required");const i=t?new Set([t]):null;if(t){const x=rnn(r,t);for(const M of x)i.add(M)}const a=(e??r.toArray()).filter(x=>!t||"subcircuit_id"in x&&i.has(x.subcircuit_id)),o=r.pcb_board.list()[0];r=wv(a);const s=kT(a),l=EN([...r.pcb_component.list(),...r.pcb_smtpad.list(),...r.pcb_plated_hole.list(),...r.pcb_hole.list(),...r.pcb_via.list()].filter(x=>!t||(i==null?void 0:i.has(x.subcircuit_id))),s);for(const x of l){const M=x.connectedTo.flatMap(T=>s.getIdsConnectedToNet(T));x.connectedTo.push(...M)}const c=l.flatMap(x=>[{x:x.center.x-x.width/2,y:x.center.y-x.height/2},{x:x.center.x+x.width/2,y:x.center.y+x.height/2}]);let u;o?u={minX:o.center.x-o.width/2,maxX:o.center.x+o.width/2,minY:o.center.y-o.height/2,maxY:o.center.y+o.height/2}:u={minX:Math.min(...c.map(x=>x.x))-1,maxX:Math.max(...c.map(x=>x.x))+1,minY:Math.min(...c.map(x=>x.y))-1,maxY:Math.max(...c.map(x=>x.y))+1};const f=r.source_trace.list().map(x=>{const M=x.connected_source_port_ids.map(T=>{const w=r.source_port.get(T),P=r.pcb_port.getWhere({source_port_id:T});return{...w,...P}});return M.length<2?null:{name:x.source_trace_id??s.getNetConnectedToId(x.source_trace_id)??"",source_trace_id:x.source_trace_id,pointsToConnect:M.map(T=>{var w;return{x:T.x,y:T.y,layer:((w=T.layers)==null?void 0:w[0])??"top"}})}}).filter(x=>x!==null),m=r.source_net.list().filter(x=>!t||(i==null?void 0:i.has(x.subcircuit_id))),g=[];for(const x of m){const M=r.source_trace.list().filter(T=>{var w;return(w=T.connected_source_net_ids)==null?void 0:w.includes(x.source_net_id)});g.push({name:x.source_net_id??s.getNetConnectedToId(x.source_net_id),pointsToConnect:M.flatMap(T=>r.pcb_port.list().filter(P=>T.connected_source_port_ids.includes(P.source_port_id)).map(P=>{var O;return{x:P.x,y:P.y,layer:((O=P.layers)==null?void 0:O[0])??"top",pcb_port_id:P.pcb_port_id}}))})}return{simpleRouteJson:{bounds:u,obstacles:l,connections:[...f,...g],layerCount:2,minTraceWidth:n},connMap:s}},$le=class extends Zx{constructor(){super(...arguments);dt(this,"pcb_group_id",null);dt(this,"subcircuit_id",null);dt(this,"_hasStartedAsyncAutorouting",!1);dt(this,"_asyncAutoroutingResult",null)}get config(){return{zodProps:yen,componentName:"Group"}}doInitialSourceRender(){const{db:e}=this.root,t=e.source_group.insert({name:this._parsedProps.name,is_subcircuit:this.isSubcircuit});this.subcircuit_id=`subcircuit_${t.source_group_id}`,this.source_group_id=t.source_group_id,e.source_group.update(t.source_group_id,{subcircuit_id:this.subcircuit_id})}doInitialSourceParentAttachment(){var n,i,a;const{db:e}=this.root;if(!this.isSubcircuit)return;const t=(a=(i=(n=this.parent)==null?void 0:n.getSubcircuit)==null?void 0:i.call(n))==null?void 0:a.subcircuit_id;t&&e.source_group.update(this.source_group_id,{parent_subcircuit_id:t})}doInitialPcbComponentRender(){var i;if((i=this.root)!=null&&i.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=e.pcb_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id,name:this._parsedProps.name,center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,pcb_component_ids:[],source_group_id:this.source_group_id});this.pcb_group_id=n.pcb_group_id}doInitialCreateTraceHintsFromProps(){var a;const{_parsedProps:e}=this,{db:t}=this.root,n=e;if(!this.isSubcircuit)return;const i=(a=n.layout)==null?void 0:a.manual_trace_hints;if(i)for(const o of i)this.add(new oVe({for:o.pcb_port_selector,offsets:o.offsets}))}doInitialSourceAddConnectivityMapKey(){if(!this.isSubcircuit)return;const{db:e}=this.root,t=this.selectAll("trace"),n=new UT({});n.addConnections(t.map(i=>{const a=e.source_trace.get(i.source_trace_id);return a?[a.source_trace_id,...a.connected_source_port_ids,...a.connected_source_net_ids]:null}).filter(i=>i!==null));for(const i of t){if(!i.source_trace_id)continue;const a=n.getNetConnectedToId(i.source_trace_id);if(!a)continue;const{name:o}=this._parsedProps;i.subcircuit_connectivity_map_key=`${o??`unnamedsubcircuit${this._renderId}`}_${a}`,e.source_trace.update(i.source_trace_id,{subcircuit_connectivity_map_key:i.subcircuit_connectivity_map_key})}}_areChildSubcircuitsRouted(){const e=this.selectAll("group").filter(t=>t.isSubcircuit);for(const t of e)if(t._shouldRouteAsync()&&!t._asyncAutoroutingResult)return!1;return!0}_shouldRouteAsync(){const e=this._getAutorouterConfig();return e.groupMode==="sequential-trace"?!1:!!(e.local&&e.groupMode==="subcircuit"||!e.local)}_hasTracesToRoute(){const e=lg("tscircuit:core:_hasTracesToRoute"),t=this.selectAll("trace");return e(`[${this.getString()}] has ${t.length} traces to route`),t.length>0}async _runEffectMakeHttpAutoroutingRequest(){var c,u,f,m;const{db:e}=this.root,t=lg("tscircuit:core:_runEffectMakeHttpAutoroutingRequest");this._parsedProps;const n=this._getAutorouterConfig(),i=n.serverUrl,a=n.serverMode,o=(g,x)=>{var M;return t("fetching",g),x.headers&&(x.headers["Tscircuit-Core-Version"]=(M=this.root)==null?void 0:M.getCoreVersion()),fetch(g,x)},s=this.root.db.toArray().filter(g=>g.type.startsWith("source_")||g.type.startsWith("pcb_"));if(a==="solve-endpoint"){if(((c=this.props.autorouter)==null?void 0:c.inputFormat)==="simplified"){const{autorouting_result:x}=await o(`${i}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_simple_route_json:sVe({db:e,minTraceWidth:((u=this.props.autorouter)==null?void 0:u.minTraceWidth)??.15,subcircuit_id:this.subcircuit_id}).simpleRouteJson,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(M=>M.json());this._asyncAutoroutingResult=x,this._markDirty("PcbTraceRender");return}const{autorouting_result:g}=await o(`${i}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_circuit_json:s,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(x=>x.json());this._asyncAutoroutingResult=g,this._markDirty("PcbTraceRender");return}const{autorouting_job:l}=await o(`${i}/autorouting/jobs/create`,{method:"POST",body:JSON.stringify({input_circuit_json:s,provider:"freerouting",autostart:!0,display_name:(f=this.root)==null?void 0:f.name,subcircuit_id:this.subcircuit_id,server_cache_enabled:n.serverCacheEnabled}),headers:{"Content-Type":"application/json"}}).then(g=>g.json());for(;;){const{autorouting_job:g}=await o(`${i}/autorouting/jobs/get`,{method:"POST",body:JSON.stringify({autorouting_job_id:l.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(x=>x.json());if(g.is_finished){const{autorouting_job_output:x}=await o(`${i}/autorouting/jobs/get_output`,{method:"POST",body:JSON.stringify({autorouting_job_id:l.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(M=>M.json());this._asyncAutoroutingResult={output_pcb_traces:x.output_pcb_traces},this._markDirty("PcbTraceRender");break}if(g.has_error)throw e.pcb_autorouting_error.insert({pcb_error_id:l.autorouting_job_id,message:((m=g.error)==null?void 0:m.message)??JSON.stringify(g.error)}),new Error(`Autorouting job failed: ${JSON.stringify(g.error)}`);await new Promise(x=>setTimeout(x,100))}}async _runLocalAutorouting(){var s,l,c,u,f;const{db:e}=this.root;this._parsedProps;const t=lg("tscircuit:core:_runLocalAutorouting");t(`[${this.getString()}] starting local autorouting`);const n=this._getAutorouterConfig(),{simpleRouteJson:i}=sVe({db:e,minTraceWidth:((s=this.props.autorouter)==null?void 0:s.minTraceWidth)??.15,subcircuit_id:this.subcircuit_id});(l=this.root)==null||l.emit("autorouting:start",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),simpleRouteJson:i});let a;n.algorithmFn?a=await n.algorithmFn(i):a=new nnn(i,{capacityDepth:(c=this.props.autorouter)==null?void 0:c.capacityDepth,targetMinCapacity:(u=this.props.autorouter)==null?void 0:u.targetMinCapacity});const o=new Promise((m,g)=>{a.on("complete",x=>{t(`[${this.getString()}] local autorouting complete`),m(x.traces)}),a.on("error",x=>{t(`[${this.getString()}] local autorouting error: ${x.error.message}`),g(x.error)})});a.on("progress",m=>{var g;(g=this.root)==null||g.emit("autorouting:progress",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),...m})}),a.start();try{const m=await o;this._asyncAutoroutingResult={output_pcb_traces:m},this._markDirty("PcbTraceRender")}catch(m){const{db:g}=this.root;throw g.pcb_autorouting_error.insert({pcb_error_id:`pcb_autorouter_error_subcircuit_${this.subcircuit_id}`,message:m instanceof Error?m.message:String(m)}),(f=this.root)==null||f.emit("autorouting:error",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),error:{message:m instanceof Error?m.message:String(m)},simpleRouteJson:i}),m}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(){var t;const e=lg("tscircuit:core:doInitialPcbTraceRender");if(this.isSubcircuit&&!((t=this.root)!=null&&t.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()}}updatePcbTraceRender(){var n;const e=lg("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;const{db:t}=this.root;if(this._asyncAutoroutingResult.output_simple_route_json){e(`[${this.getString()}] updating PCB traces from simple route json (${(n=this._asyncAutoroutingResult.output_simple_route_json.traces)==null?void 0:n.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(){const{db:e}=this.root,{traces:t}=this._asyncAutoroutingResult.output_simple_route_json;if(t)for(const n of t)e.pcb_trace.insert({subcircuit_id:this.subcircuit_id,route:n.route})}_updatePcbTraceRenderFromPcbTraces(){const{output_pcb_traces:e}=this._asyncAutoroutingResult;if(!e)return;const{db:t}=this.root;for(const n of e)if(n.type==="pcb_trace"){if(n.subcircuit_id=this.subcircuit_id,n.connection_name){const i=n.connection_name;n.source_trace_id=i}t.pcb_trace.insert(n)}for(const n of e)if(n.type!=="pcb_via"&&n.type==="pcb_trace")for(const i of n.route)i.route_type==="via"&&t.pcb_via.insert({pcb_trace_id:n.pcb_trace_id,x:i.x,y:i.y,hole_diameter:.3,outer_diameter:.6,layers:[i.from_layer,i.to_layer],from_layer:i.from_layer,to_layer:i.to_layer})}doInitialSchematicLayout(){if(!this.isSubcircuit||!this._parsedProps.schAutoLayoutEnabled)return;const{db:t}=this.root,n=this.getDescendants(),i=[];for(const s of n)if("schematic_component_id"in s){const l=t.schematic_component.get(s.schematic_component_id);if(l){const c=t.schematic_port.list().filter(u=>u.schematic_component_id===l.schematic_component_id);i.push(...c)}}const a=d1e(t.toArray()),o=m1e(a);f1e(t.toArray(),o)}_getAutorouterConfig(){const e={serverUrl:"https://registry-api.tscircuit.com",serverMode:"job",serverCacheEnabled:!0},t=this._parsedProps.autorouter??this.getInheritedProperty("autorouter");return typeof t=="object"?{local:!(t.serverUrl||t.serverMode||t.serverCacheEnabled),...e,...t}:t==="auto-local"?{local:!0,groupMode:"subcircuit"}:t==="sequential-trace"?{local:!0,groupMode:"sequential-trace"}:t==="subcircuit"?{local:!0,groupMode:"subcircuit"}:t==="auto-cloud"?{local:!1,groupMode:"subcircuit",serverUrl:e.serverUrl,serverMode:e.serverMode,serverCacheEnabled:!0}:{local:!0,groupMode:"subcircuit"}}_shouldUseTraceByTraceRouting(){return this._getAutorouterConfig().groupMode==="sequential-trace"}doInitialPcbDesignRuleChecks(){var t;if((t=this.root)!=null&&t.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;const{db:e}=this.root;if(this.isSubcircuit){const n=new Map;for(const i of this.children)if(!i.isSubcircuit&&i._parsedProps.name){const a=n.get(i._parsedProps.name)||[];a.push(i),n.set(i._parsedProps.name,a)}for(const[i,a]of n.entries())a.length>1&&e.pcb_trace_error.insert({error_type:"pcb_trace_error",message:`Multiple components found with name "${i}" in subcircuit "${this._parsedProps.name||"unnamed"}". Component names must be unique within a subcircuit.`,source_trace_id:"",pcb_trace_id:"",pcb_component_ids:a.map(o=>o.pcb_component_id).filter(Boolean),pcb_port_ids:[]})}}},inn=class extends $le{constructor(){super(...arguments);dt(this,"pcb_board_id",null)}get isSubcircuit(){return!0}get config(){return{componentName:"Board",zodProps:kHe}}get boardThickness(){const{_parsedProps:e}=this;return 1.4}get allLayers(){return["top","bottom","inner1","inner2"]}doInitialPcbBoardAutoSize(){var g;if((g=this.root)!=null&&g.pcbDisabled||!this.pcb_board_id)return;const{db:e}=this.root,{_parsedProps:t}=this;if(t.width&&t.height)return;let n=1/0,i=1/0,a=-1/0,o=-1/0;const s=e.pcb_component.list();let l=!1;for(const x of s){const{width:M,height:T,center:w}=x;M===0||T===0||(l=!0,n=Math.min(n,w.x-M/2),i=Math.min(i,w.y-T/2),a=Math.max(a,w.x+M/2),o=Math.max(o,w.y+T/2))}const c=2,u=l?a-n+c*2:0,f=l?o-i+c*2:0,m={x:l?(n+a)/2+(t.outlineOffsetX??0):t.outlineOffsetX??0,y:l?(i+o)/2+(t.outlineOffsetY??0):t.outlineOffsetY??0};e.pcb_board.update(this.pcb_board_id,{width:u,height:f,center:m})}doInitialPcbComponentRender(){var o,s;if((o=this.root)!=null&&o.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this;let n=t.width??0,i=t.height??0;if(t.outline){const l=t.outline.map(x=>x.x),c=t.outline.map(x=>x.y),u=Math.min(...l),f=Math.max(...l),m=Math.min(...c),g=Math.max(...c);n=f-u,i=g-m}const a=e.pcb_board.insert({center:{x:(t.pcbX??0)+(t.outlineOffsetX??0),y:(t.pcbY??0)+(t.outlineOffsetY??0)},thickness:this.boardThickness,num_layers:this.allLayers.length,width:n,height:i,outline:(s=t.outline)==null?void 0:s.map(l=>({x:l.x+(t.outlineOffsetX??0),y:l.y+(t.outlineOffsetY??0)}))});this.pcb_board_id=a.pcb_board_id}removePcbComponentRender(){const{db:e}=this.root;this.pcb_board_id&&(e.pcb_board.delete(this.pcb_board_id),this.pcb_board_id=null)}_computePcbGlobalTransformBeforeLayout(){return w9()}doInitialPcbDesignRuleChecks(){var n;if((n=this.root)!=null&&n.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;const{db:e}=this.root;super.doInitialPcbDesignRuleChecks();const t=Q1e(e.toArray());for(const i of t)e.pcb_trace_error.insert(i)}},ann=new Proxy({},{get:(r,e)=>e}),fA=ann,onn=class extends Zx{get config(){return{componentName:"Capacitor",schematicSymbolName:this.props.polarized?"capacitor_polarized":this.props.symbolName??"capacitor",zodProps:Cen,sourceFtype:fA.simple_capacitor}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){const r=`${e8(this._parsedProps.capacitance)}F`;return this._parsedProps.schShowRatings&&this._parsedProps.maxVoltageRating?`${r}/${e8(this._parsedProps.maxVoltageRating)}V`:r}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.decouplingFor,this.props.decouplingTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.decouplingFor&&this.props.decouplingTo&&(this.add(new x7({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.decouplingFor})),this.add(new x7({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.decouplingTo})))}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({ftype:"simple_capacitor",name:e.name,manufacturer_part_number:e.manufacturerPartNumber??e.mfn,supplier_part_numbers:e.supplierPartNumbers,capacitance:e.capacitance,max_voltage_rating:e.maxVoltageRating,max_decoupling_trace_length:e.maxDecouplingTraceLength,display_capacitance:this._getSchematicSymbolDisplayValue()});this.source_component_id=t.source_component_id}},lVe=class extends Zx{constructor(){super(...arguments);dt(this,"schematicBoxDimensions",null)}get config(){return{componentName:"Chip",zodProps:IHe,shouldRenderAsSchematicBox:!0}}doInitialSchematicComponentRender(){const{_parsedProps:e}=this;(e==null?void 0:e.noSchematicRepresentation)!==!0&&super.doInitialSchematicComponentRender()}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_chip",name:t.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers});this.source_component_id=n.source_component_id}doInitialPcbComponentRender(){var i;if((i=this.root)!=null&&i.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=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});this.pcb_component_id=n.pcb_component_id}doInitialCreateTracesFromProps(){const{_parsedProps:e}=this;if(e.externallyConnectedPins)for(const[t,n]of e.externallyConnectedPins)this.add(new x7({from:`${this.getSubcircuitSelector()} > port.${t}`,to:`${this.getSubcircuitSelector()} > port.${n}`}));this._createTracesFromConnectionsProp()}},snn=class extends Zx{constructor(){super(...arguments);dt(this,"pos",this.portMap.pin1);dt(this,"anode",this.portMap.pin1);dt(this,"neg",this.portMap.pin2);dt(this,"cathode",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"diode",componentName:"Diode",zodProps:etn,sourceFtype:"simple_diode"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}},lnn=class extends Zx{constructor(){super(...arguments);dt(this,"schematicDimensions",null)}get config(){return{componentName:"Jumper",zodProps:ben,shouldRenderAsSchematicBox:!0}}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_chip",name:t.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers});this.source_component_id=n.source_component_id}doInitialPcbComponentRender(){var i;if((i=this.root)!=null&&i.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=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});this.pcb_component_id=n.pcb_component_id}},cnn=class extends Zx{constructor(){super(...arguments);dt(this,"pos",this.portMap.pin1);dt(this,"anode",this.portMap.pin1);dt(this,"neg",this.portMap.pin2);dt(this,"cathode",this.portMap.pin2)}get config(){return{componentName:"Led",schematicSymbolName:this.props.symbolName??"led",zodProps:ttn,sourceFtype:"simple_diode"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}},unn=class extends Zx{constructor(){super(...arguments);dt(this,"pos",this.portMap.pin1);dt(this,"positive",this.portMap.pin1);dt(this,"neg",this.portMap.pin2);dt(this,"negative",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"power_factor_meter_horz",componentName:"PowerSource",zodProps:stn,sourceFtype:"simple_power_source"}}initPorts(){this.add(new OS({name:"pin1",pinNumber:1,aliases:["positive","pos"]})),this.add(new OS({name:"pin2",pinNumber:2,aliases:["negative","neg"]}))}},fnn=class extends Zx{get config(){return{componentName:"Resistor",schematicSymbolName:this.props.symbolName??"boxresistor",zodProps:Een,sourceFtype:"simple_resistor"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return`${e8(this._parsedProps.resistance)}Ω`}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.pullupFor,this.props.pullupTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.pullupFor&&this.props.pullupTo&&(this.add(new x7({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pullupFor})),this.add(new x7({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pullupTo})))}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({ftype:"simple_resistor",name:e.name,manufacturer_part_number:e.manufacturerPartNumber??e.mfn,supplier_part_numbers:e.supplierPartNumbers,resistance:e.resistance,display_resistance:this._getSchematicSymbolDisplayValue()});this.source_component_id=t.source_component_id}},dnn=["leftedge","rightedge","topedge","bottomedge","center"],pnn=class extends X_{get config(){return{componentName:"Constraint",zodProps:Den}}constructor(r){if(super(r),("xdist"in r||"ydist"in r)&&!("edgeToEdge"in r)&&!("centerToCenter"in r))throw new Error(`edgeToEdge, centerToCenter must be set for xDist or yDist for ${this}`);if("for"in r&&r.for.length<2)throw new Error(`"for" must have at least two selectors for ${this}`)}_getAllReferencedComponents(){const r=[],e=this.getPrimitiveContainer();function t(n){const i=n.split(" ").pop(),a=dnn.includes(i)?i:void 0,o=a?n.replace(` ${a}`,""):n,s=e.selectOne(o,{pcbPrimitive:!0});s&&r.push({selector:n,component:s,componentSelector:o,edge:a})}for(const n of["left","right","top","bottom"])n in this._parsedProps&&t(this._parsedProps[n]);if("for"in this._parsedProps)for(const n of this._parsedProps.for)t(n);return{componentsWithSelectors:r}}},hnn=class extends X_{constructor(){super(...arguments);dt(this,"fabrication_note_path_id",null)}get config(){return{componentName:"FabricationNotePath",zodProps:itn}}doInitialPcbPrimitiveRender(){var s,l;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:e}=this.root,t=this.getSubcircuit(),{_parsedProps:n}=this,i=n.layer??"top";if(i!=="top"&&i!=="bottom")throw new Error(`Invalid layer "${i}" for SilkscreenPath. Must be "top" or "bottom".`);const a=this._computePcbGlobalTransformBeforeLayout(),o=e.pcb_fabrication_note_path.insert({pcb_component_id:(l=this.parent)==null?void 0:l.pcb_component_id,layer:i,color:n.color,route:n.route.map(c=>{const u=Fr(a,{x:c.x,y:c.y});return{...c,x:u.x,y:u.y}}),stroke_width:n.strokeWidth??.1,subcircuit_id:(t==null?void 0:t.subcircuit_id)??void 0});this.fabrication_note_path_id=o.pcb_fabrication_note_path_id}},mnn=class extends X_{get config(){return{componentName:"FabricationNoteText",zodProps:rtn}}doInitialPcbPrimitiveRender(){var i,a;if((i=this.root)!=null&&i.pcbDisabled)return;const{db:r}=this.root,{_parsedProps:e}=this,t=this.getPrimitiveContainer(),n=this.getSubcircuit();r.pcb_fabrication_note_text.insert({anchor_alignment:e.anchorAlignment,anchor_position:{x:e.pcbX??0,y:e.pcbY??0},font:e.font??"tscircuit2024",font_size:e.fontSize??1,layer:"top",color:e.color,text:e.text??"",pcb_component_id:t.pcb_component_id,subcircuit_id:(n==null?void 0:n.subcircuit_id)??void 0,pcb_group_id:((a=this.getGroup())==null?void 0:a.pcb_group_id)??void 0})}},vnn=class extends $le{constructor(r){super({...r,subcircuit:!0})}},ynn=class extends X_{constructor(){super(...arguments);dt(this,"source_net_alias_id")}get config(){return{componentName:"NetAlias",zodProps:$en}}doInitialSchematicComponentRender(){var a;if((a=this.root)!=null&&a.schematicDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n={x:t.schX??0,y:t.schY??0},i=e.schematic_net_label.insert({text:t.net,source_net_id:t.net,anchor_position:n,center:n,anchor_side:"bottom"});this.source_net_alias_id=i.source_net_id}},gnn=class extends X_{constructor(){super(...arguments);dt(this,"pcb_silkscreen_circle_id",null);dt(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenCircle",zodProps:dtn}}doInitialPcbPrimitiveRender(){var s,l,c;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,{maybeFlipLayer:n}=this._getPcbPrimitiveFlippedHelpers(),i=n(t.layer??"top");if(i!=="top"&&i!=="bottom")throw new Error(`Invalid layer "${i}" for SilkscreenCircle. Must be "top" or "bottom".`);this._computePcbGlobalTransformBeforeLayout();const a=this.getSubcircuit(),o=e.pcb_silkscreen_circle.insert({pcb_component_id:(l=this.parent)==null?void 0:l.pcb_component_id,layer:i,center:{x:t.pcbX??0,y:t.pcbY??0},radius:t.radius,subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((c=this.getGroup())==null?void 0:c.pcb_group_id)??void 0,stroke_width:t.strokeWidth??.1});this.pcb_silkscreen_circle_id=o.pcb_silkscreen_circle_id}getPcbSize(){const{_parsedProps:e}=this,t=e.radius*2;return{width:t,height:t}}},_nn=class extends X_{constructor(){super(...arguments);dt(this,"pcb_silkscreen_rect_id",null);dt(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenRect",zodProps:ftn}}doInitialPcbPrimitiveRender(){var s,l,c;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,{maybeFlipLayer:n}=this._getPcbPrimitiveFlippedHelpers(),i=n(t.layer??"top");if(i!=="top"&&i!=="bottom")throw new Error(`Invalid layer "${i}" for SilkscreenRect. Must be "top" or "bottom".`);const a=this.getSubcircuit(),o=e.pcb_silkscreen_rect.insert({pcb_component_id:(l=this.parent)==null?void 0:l.pcb_component_id,layer:i,center:{x:t.pcbX??0,y:t.pcbY??0},width:t.width,height:t.height,subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((c=this==null?void 0:this.getGroup())==null?void 0:c.pcb_group_id)??void 0,stroke_width:t.strokeWidth??.1});this.pcb_silkscreen_rect_id=o.pcb_silkscreen_rect_id}getPcbSize(){const{_parsedProps:e}=this;return{width:e.width,height:e.height}}},xnn=class extends X_{constructor(){super(...arguments);dt(this,"pcb_silkscreen_line_id",null);dt(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenLine",zodProps:utn}}doInitialPcbPrimitiveRender(){var s,l,c;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,{maybeFlipLayer:n}=this._getPcbPrimitiveFlippedHelpers(),i=n(t.layer??"top");if(i!=="top"&&i!=="bottom")throw new Error(`Invalid layer "${i}" for SilkscreenLine. Must be "top" or "bottom".`);const a=this.getSubcircuit(),o=e.pcb_silkscreen_line.insert({pcb_component_id:(l=this.parent)==null?void 0:l.pcb_component_id,layer:i,x1:t.x1,y1:t.y1,x2:t.x2,y2:t.y2,stroke_width:t.strokeWidth??.1,subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((c=a==null?void 0:a.getGroup())==null?void 0:c.pcb_group_id)??void 0});this.pcb_silkscreen_line_id=o.pcb_silkscreen_line_id}getPcbSize(){const{_parsedProps:e}=this,t=Math.abs(e.x2-e.x1),n=Math.abs(e.y2-e.y1);return{width:t,height:n}}},bnn=class extends X_{constructor(){super(...arguments);dt(this,"pcb_via_id",null);dt(this,"matchedPort",null);dt(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Via",zodProps:atn}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){const{_parsedProps:e}=this;return{width:e.outerDiameter,height:e.outerDiameter}}_getPcbCircuitJsonBounds(){const{db:e}=this.root,t=e.pcb_via.get(this.pcb_via_id),n=this.getPcbSize();return{center:{x:t.x,y:t.y},bounds:{left:t.x-n.width/2,top:t.y-n.height/2,right:t.x+n.width/2,bottom:t.y+n.height/2},width:n.width,height:n.height}}_setPositionFromLayout(e){const{db:t}=this.root;t.pcb_via.update(this.pcb_via_id,{x:e.x,y:e.y})}doInitialPcbPrimitiveRender(){var o,s;if((o=this.root)!=null&&o.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=this._getGlobalPcbPositionBeforeLayout(),i=this.getSubcircuit(),a=e.pcb_via.insert({x:n.x,y:n.y,hole_diameter:t.holeDiameter,outer_diameter:t.outerDiameter,layers:["bottom","top"],from_layer:t.fromLayer||"bottom",to_layer:t.toLayer||"top",subcircuit_id:(i==null?void 0:i.subcircuit_id)??void 0,pcb_group_id:((s=this.getGroup())==null?void 0:s.pcb_group_id)??void 0});this.pcb_via_id=a.pcb_via_id}},Snn=class extends Zx{get config(){return{componentName:"Battery",schematicSymbolName:this.props.symbolName??"battery",zodProps:Gen,sourceFtype:"simple_power_source"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({name:e.name,ftype:"simple_power_source",capacity:e.capacity,supplier_part_numbers:e.supplierPartNumbers});this.source_component_id=t.source_component_id}},Enn=class extends Zx{get config(){return{componentName:"PinHeader",zodProps:qen,shouldRenderAsSchematicBox:!0}}_getImpliedFootprintString(){var i;const r=this._parsedProps.pinCount??((i=this._parsedProps.pinLabels)==null?void 0:i.length)??0,e=this._parsedProps.holeDiameter,t=this._parsedProps.platedDiameter,n=this._parsedProps.pitch;return r>0&&n?!e&&!t?`pinrow${r}_p${n}`:`pinrow${r}_p${n}_id${e}_od${t}`:null}initPorts(){var e,t;const r=this._parsedProps.pinCount??((e=this._parsedProps.pinLabels)==null?void 0:e.length)??1;for(let n=1;n<=r;n++)this.add(new OS({name:`pin${n}`,pinNumber:n,aliases:[(t=this._parsedProps.pinLabels)==null?void 0:t[n-1]].filter(Boolean)}))}_getSchematicPortArrangement(){const r=this._parsedProps.pinCount??1,e=this._parsedProps.facingDirection??"right";return{leftSize:e==="left"?r:0,rightSize:e==="right"?r:0}}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({ftype:"simple_pin_header",name:e.name,supplier_part_numbers:e.supplierPartNumbers,pin_count:e.pinCount,gender:e.gender});this.source_component_id=t.source_component_id}};function wnn(r){switch(r){case"two_ground_pins":return"crystal_4pin";case"ground_pin":return"resonator";case"no_ground":return"crystal";default:return"crystal"}}var Tnn=class extends Zx{get config(){return{componentName:"Resonator",schematicSymbolName:this.props.symbolName??wnn(this.props.pinVariant),zodProps:Men,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({ftype:"simple_resonator",name:e.name,frequency:e.frequency,load_capacitance:e.loadCapacitance,supplier_part_numbers:e.supplierPartNumbers,pin_variant:e.pinVariant||"no_ground"});this.source_component_id=t.source_component_id}},Mnn=class extends Zx{get config(){return{componentName:"Inductor",schematicSymbolName:this.props.symbolName??"inductor",zodProps:Zen,sourceFtype:fA.simple_inductor}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({name:e.name,ftype:fA.simple_inductor,inductance:e.inductance,supplier_part_numbers:e.supplierPartNumbers});this.source_component_id=t.source_component_id}};function Cnn(r){switch(r){case"three_pin":return"potentiometer3";case"two_pin":return"potentiometer2";default:return"potentiometer2"}}var Rnn=class extends Zx{get config(){return{componentName:"Potentiometer",schematicSymbolName:this.props.symbolName??Cnn(this.props.pinVariant),zodProps:wen,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({ftype:"simple_potentiometer",name:e.name,max_resistance:e.maxResistance,pin_variant:e.pinVariant||"two_pin"});this.source_component_id=t.source_component_id}},Ann=class extends Zx{get config(){return{componentName:"PushButton",schematicSymbolName:this.props.symbolName??"push_button_normally_open_momentary",zodProps:Yen,sourceFtype:fA.simple_push_button}}get defaultInternallyConnectedPinNames(){return[["pin1","pin4"],["pin2","pin3"]]}initPorts(){super.initPorts({pinCount:4,additionalAliases:{pin1:["side1"],pin3:["side2"]}})}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({name:e.name,ftype:fA.simple_push_button,supplier_part_numbers:e.supplierPartNumbers});this.source_component_id=t.source_component_id}},Pnn=class extends Zx{get config(){return{schematicSymbolName:this.props.symbolName??(this.props.pinVariant==="four_pin"?"crystal_4pin":"crystal"),componentName:"Crystal",zodProps:Ten,sourceFtype:"simple_crystal"}}initPorts(){const r=this.props.pinVariant==="four_pin"?{pin1:["left1","1"],pin2:["top1","2","gnd1"],pin3:["right1","3"],pin4:["bottom1","4","gnd2"]}:{pin1:["pos","left"],pin2:["neg","right"]};super.initPorts({additionalAliases:r})}_getSchematicSymbolDisplayValue(){return`${e8(this._parsedProps.frequency)}Hz`}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({name:e.name,ftype:"simple_crystal",frequency:e.frequency,load_capacitance:e.loadCapacitance,pin_variant:e.pinVariant||"two_pin"});this.source_component_id=t.source_component_id}},Nnn=class extends Zx{constructor(){super(...arguments);dt(this,"emitter",this.portMap.pin1);dt(this,"collector",this.portMap.pin2);dt(this,"base",this.portMap.pin3)}get config(){return{componentName:"Transistor",schematicSymbolName:this.props.type==="npn"?"npn_bipolar_transistor":"pnp_bipolar_transistor",zodProps:Xen,sourceFtype:"simple_transistor",shouldRenderAsSchematicBox:!1}}initPorts(){super.initPorts({pinCount:3,additionalAliases:{pin1:["emitter","e"],pin2:["collector","c"],pin3:["base","b"]}})}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_transistor",name:t.name,transistor_type:t.type});this.source_component_id=n.source_component_id}},Dnn=class extends Zx{get config(){const r=this.props.mosfetMode==="depletion"?"d":"e";return{componentName:"Mosfet",schematicSymbolName:`${this.props.channelType}_channel_${r}_mosfet_transistor`,zodProps:Wen,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({ftype:"simple_mosfet",name:e.name,mosfet_mode:e.mosfetMode,channel_type:e.channelType});this.source_component_id=t.source_component_id}},Lnn=class extends Zx{_getSwitchType(){const{spst:r,spdt:e,dpst:t,dpdt:n,type:i}=this._parsedProps??{};return n?"dpdt":r?"spst":e?"spdt":t?"dpst":i??"spst"}get config(){const r=this._getSwitchType(),{isNormallyClosed:e}=this._parsedProps??{};return{componentName:"Switch",schematicSymbolName:{spst:e?"spst_normally_closed_switch":"SPST_switch",spdt:e?"spdt_normally_closed_switch":"SPDT_switch",dpst:e?"dpst_normally_closed_switch":"dpst_switch",dpdt:e?"dpdt_normally_closed_switch":"dpdt_switch"}[r]??"SPST_switch",zodProps:ntn,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({ftype:"simple_switch",name:e.name,switch_type:e.type,is_normally_closed:e.isNormallyClosed??!1});this.source_component_id=t.source_component_id}};new Proxy({},{get:(r,e)=>{const t=(...n)=>(n[0],new Proxy({},{get:(i,a)=>`.${e} > .${a}`}));return new Proxy(t,{get:(n,i)=>e==="net"?`net.${i}`:e==="subcircuit"?new Proxy({},{get:(a,o)=>new Proxy({},{get:(s,l)=>`subcircuit.${i} > .${o} > .${l}`})}):`.${e} > .${i}`,apply:(n,i,a)=>new Proxy({},{get:(o,s)=>`.${e} > .${s}`})})}}),qHe(VHe),qHe({Bug:lVe});const cVe=r=>`hsl(${Sb.indexOf(r)*137.5%360}, 70%, 50%)`,Onn=({phaseTimings:r})=>{if(!r)return null;const e=Object.values(r).reduce((t,n)=>t+n,0);return ft.jsxs("div",{className:"rf-space-y-2 rf-w-full rf-px-4",children:[ft.jsx("div",{className:"rf-relative rf-h-8 rf-flex rf-rounded-sm",children:Sb.map(t=>{const n=r[t]||0,i=n/e*100;return ft.jsx("div",{className:"rf-group/bar rf-relative rf-overflow-visible",style:{width:`${i}%`,backgroundColor:cVe(t)},children:ft.jsxs("div",{className:"rf-opacity-0 group-hover/bar:rf-opacity-100 rf-transition-opacity rf-absolute rf-bottom-full rf-left-1/2 rf-transform -rf-translate-x-1/2 rf-mb-2 rf-px-2 rf-py-1 rf-text-xs rf-whitespace-nowrap rf-rounded rf-bg-gray-900 rf-text-white rf-pointer-events-none",children:[t,": ",n.toFixed(1),"ms"]})},t)})}),ft.jsxs("div",{className:"rf-text-xs rf-text-gray-500",children:["Total: ",e.toFixed(2),"ms"]})]})},znn=({renderLog:r})=>{const[e,t]=wt.useState("chronological");if(!r)return ft.jsx("div",{className:"rf-p-4 rf-bg-gray-100 rf-rounded-md",children:"No render log, make sure this tab is open when you render (TODO add a rerender button here)"});const n=Object.entries((r==null?void 0:r.phaseTimings)??{});e==="chronological"?n.sort((a,o)=>Sb.indexOf(a[0])-Sb.indexOf(o[0])):n.sort((a,o)=>o[1]-a[1]);const i=n.reduce((a,[o,s])=>a+s,0);return ft.jsxs("div",{className:"rf-bg-white",children:[ft.jsxs("div",{className:"rf-flex rf-justify-between rf-items-center",children:[ft.jsx("div",{children:"Render Logs"}),ft.jsxs("div",{className:"rf-mb-4 rf-pr-2 rf-flex rf-text-xs rf-items-center",children:[ft.jsx("div",{className:"rf-mr-2",children:"Sort by:"}),ft.jsxs("select",{value:e,onChange:a=>t(a.target.value),className:"rf-px-2 rf-py-1 rf-border rf-rounded rf-text-xs",children:[ft.jsx("option",{value:"chronological",children:"Phase Order"}),ft.jsx("option",{value:"longest",children:"Duration"})]})]})]}),ft.jsx(Onn,{phaseTimings:r.phaseTimings}),ft.jsxs("table",{className:"rf-w-full rf-text-xs",children:[ft.jsx("thead",{children:ft.jsxs("tr",{children:[ft.jsx("th",{className:"rf-text-left rf-p-2",children:"Phase Order"}),ft.jsx("th",{className:"rf-text-left rf-p-2",children:"Phase"}),ft.jsx("th",{className:"rf-text-left rf-p-2",children:"Duration (ms)"})]})}),ft.jsx("tbody",{children:n.map(([a,o])=>ft.jsxs("tr",{children:[ft.jsx("td",{className:"rf-p-2",children:Sb.indexOf(a)}),ft.jsx("td",{className:"rf-p-2",children:a}),ft.jsx("td",{className:"rf-p-2",children:ft.jsx("div",{className:"rf-w-8",children:ft.jsx("div",{className:"rf-h-2 rf-rounded-sm",style:{backgroundColor:cVe(a),width:`${o/i*100}%`}})})}),ft.jsx("td",{className:"rf-p-2",children:ft.jsxs("div",{className:"rf-flex w-full",children:[ft.jsxs("span",{className:"rf-flex-grow",children:[o,"ms"]}),ft.jsxs("span",{className:"rf-text-gray-500 rf-pr-2",children:[(o/i*100).toFixed(1),"%"]})]})})]},a))})]})]})},Unn="0.0.313",knn=["assembly","bom","circuit_json","errors","render_log"],Inn=({code:r,onRunClicked:e=void 0,errorMessage:t,circuitJson:n,autoroutingGraphics:i,showRightHeaderContent:a=!0,showCodeTab:o=!1,codeTabContent:s,showJsonTab:l=!0,showRenderLogTab:c=!0,onActiveTabChange:u,renderLog:f,showImportAndFormatButtons:m=!0,className:g,headerClassName:x,leftHeaderContent:M,readOnly:T,isStreaming:w,autoroutingLog:P,onReportAutoroutingLog:O,isRunningCode:F,hasCodeChangedSinceLastRun:$,onEditEvent:Z,editEvents:Q,defaultActiveTab:ee,autoRotate3dViewerDisabled:ie,showSchematicDebugGrid:J=!1,showToggleFullScreen:de=!0,defaultToFullScreen:he=!1})=>{var Ie;K$t();const[_e,Ce]=wt.useState(ee??"pcb"),[De,Ee]=wt.useState(he),Pe=wt.useCallback(ze=>{Ce(ze),u==null||u(ze)},[u]),Te=()=>{Ee(!De)};return wt.useEffect(()=>{t&&Pe("errors")},[t]),wt.useEffect(()=>{(_e==="code"||_e==="errors")&&n&&!t&&Pe(ee??"pcb")},[n]),ft.jsx("div",{className:jy("flex flex-col relative rf-overflow-x-hidden",g),children:ft.jsx("div",{className:jy("rf-md:sticky rf-md:top-2",De&&"rf-fixed rf-top-0 rf-left-0 rf-w-full rf-bg-white"),children:ft.jsxs(pYe,{value:_e,onValueChange:Pe,className:"rf-flex-grow rf-flex rf-flex-col",children:[ft.jsxs("div",{className:jy("rf-flex rf-items-center rf-gap-2 rf-p-2 rf-pb-0",x),children:[M,M&&ft.jsx("div",{className:"rf-flex-grow"}),!M&&F&&ft.jsx(LLe,{className:"rf-w-4 rf-h-4 rf-animate-spin"}),!M&&ft.jsx("div",{className:"rf-flex-grow"}),f&&f.progress!==1&&ft.jsxs("div",{className:"rf-flex rf-items-center rf-gap-2",children:[f.lastRenderEvent&&ft.jsx("div",{className:"rf-text-xs rf-text-gray-500",children:(Ie=f.lastRenderEvent)==null?void 0:Ie.type.split("renderable:renderLifecycle:")[1].split(":")[0]}),ft.jsx("div",{className:"rf-w-4 rf-h-4 rf-bg-blue-500 rf-opacity-50 rf-rounded-full rf-text-white",children:ft.jsx(LLe,{className:"rf-w-4 rf-h-4 rf-animate-spin"})}),ft.jsxs("div",{className:"rf-text-xs rf-font-bold rf-text-gray-700 rf-tabular-nums",children:[((f.progress??0)*100).toFixed(1),"%"]})]}),a&&ft.jsxs(Kue,{children:[o&&ft.jsx(O7,{value:"code",children:"Code"}),ft.jsxs(O7,{value:"pcb",className:"rf-whitespace-nowrap",children:[n&&ft.jsx("span",{className:jy("rf-inline-flex rf-items-center rf-justify-center rf-w-2 rf-h-2 rf-mr-1 rf-text-xs rf-font-bold rf-text-white rf-rounded-full",$?"rf-bg-gray-500":"rf-bg-blue-500")}),"PCB"]}),ft.jsxs(O7,{value:"schematic",className:"rf-whitespace-nowrap",children:[n&&ft.jsx("span",{className:jy("rf-inline-flex rf-items-center rf-justify-center rf-w-2 rf-h-2 rf-mr-1 rf-text-xs rf-font-bold rf-text-white rf-rounded-full",$?"rf-bg-gray-500":"rf-bg-blue-500")}),"Schematic"]}),ft.jsxs(O7,{value:"cad",children:[n&&ft.jsx("span",{className:jy("inline-flex items-center justify-center w-2 h-2 mr-1 text-xs font-bold text-white rounded-full",$?"rf-bg-gray-500":"rf-bg-blue-500")}),"3D"]}),!["pcb","cad","schematic"].includes(_e)&&ft.jsx(O7,{value:_e,children:Que(_e)}),ft.jsxs(Vze,{children:[ft.jsx(Gze,{asChild:!0,children:ft.jsxs("div",{className:"rf-whitespace-nowrap rf-p-2 rf-mr-1 rf-cursor-pointer rf-relative",children:[ft.jsx(CUt,{className:"rf-w-4 rf-h-4"}),t&&ft.jsx("span",{className:"rf-inline-flex rf-absolute rf-top-[6px] rf-right-[4px] rf-items-center rf-justify-center rf-w-1 rf-h-1 rf-ml-2 rf-text-[8px] rf-font-bold rf-text-white rf-bg-red-500 rf-rounded-full"})]})}),ft.jsxs(iae,{className:"rf-*:text-xs",children:[knn.map(ze=>ft.jsxs(ok,{onSelect:()=>Pe(ze),children:[_e!==ze&&ft.jsx(DLe,{className:"rf-w-3 rf-h-3 rf-opacity-30"}),_e===ze&&ft.jsx(NLe,{className:"rf-w-3 rf-h-3"}),ft.jsx("div",{className:"rf-pr-2",children:Que(ze)}),ze==="errors"&&t&&ft.jsx("span",{className:"rf-inline-flex rf-items-center rf-justify-center rf-w-3 rf-h-3 rf-ml-2 rf-text-[8px] rf-font-bold rf-text-white rf-bg-red-500 rf-rounded-full",children:"1"})]},ze)),ft.jsx(ok,{disabled:!0,className:"rf-opacity-60 rf-cursor-default rf-select-none",children:ft.jsxs("div",{className:"rf-pr-2 rf-text-xs rf-text-gray-500",children:["@tscircuit/runframe@",Unn.split(".").map((ze,He)=>He===2?parseInt(ze)+1:ze).join(".")]})})]})]})]}),de&&ft.jsx(R8,{onClick:Te,variant:"ghost",children:De?ft.jsx(AUt,{size:16}):ft.jsx(RUt,{size:16})})]}),o&&ft.jsx(o4,{value:"code",className:"rf-flex-grow rf-overflow-hidden",children:ft.jsx("div",{className:"rf-h-full",children:s})}),ft.jsx(o4,{value:"pcb",children:ft.jsx("div",{className:jy("rf-overflow-hidden",De?"rf-h-[calc(100vh-52px)]":"rf-h-[620px]"),children:ft.jsx(Rw,{fallbackRender:({error:ze})=>ft.jsx("div",{className:"rf-mt-4 rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200",children:ft.jsxs("div",{className:"rf-p-4",children:[ft.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-3",children:"Error loading PCB viewer"}),ft.jsx("p",{className:"rf-text-xs rf-font-mono rf-whitespace-pre-wrap rf-text-red-600 rf-mt-2",children:(ze==null?void 0:ze.message)||"An unknown error occurred"})]})}),children:n?ft.jsx(Z$t,{focusOnHover:!1,circuitJson:n,debugGraphics:i,containerClassName:jy("rf-h-full rf-w-full",De?"rf-min-h-[calc(100vh-240px)]":"rf-min-h-[620px]"),onEditEventsChanged:ze=>{Z&&ze.forEach(He=>Z(He))}}):ft.jsx(g7,{onRunClicked:e})})})}),ft.jsx(o4,{value:"assembly",children:ft.jsx("div",{className:jy("rf-overflow-auto",De?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:ft.jsx(Rw,{fallback:ft.jsx("div",{children:"Error loading Assembly"}),children:n?ft.jsx(q$t,{circuitJson:n,containerStyle:{height:"100%"},editingEnabled:!0,debugGrid:!0}):ft.jsx(g7,{onRunClicked:e})})})}),ft.jsx(o4,{value:"schematic",children:ft.jsx("div",{className:jy("rf-overflow-auto",De?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:ft.jsx(Rw,{fallbackRender:({error:ze})=>ft.jsx("div",{className:"rf-mt-4 rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200",children:ft.jsxs("div",{className:"rf-p-4",children:[ft.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-3",children:"Error loading Schematic"}),ft.jsx("p",{className:"rf-text-xs rf-font-mono rf-whitespace-pre-wrap rf-text-red-600 rf-mt-2",children:(ze==null?void 0:ze.message)||"An unknown error occurred"})]})}),children:n?ft.jsx(H$t,{circuitJson:n,containerStyle:{height:"100%"},editingEnabled:!0,onEditEvent:ze=>Z==null?void 0:Z(ze),editEvents:Q,debugGrid:J}):ft.jsx(g7,{onRunClicked:e})})})}),ft.jsx(o4,{value:"cad",children:ft.jsx("div",{className:jy("rf-overflow-auto",De?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:ft.jsx(Rw,{FallbackComponent:hUt,children:n?ft.jsx(JNt,{soup:n,autoRotateDisabled:ie}):ft.jsx(g7,{onRunClicked:e})})})}),ft.jsx(o4,{value:"bom",children:ft.jsx("div",{className:jy("rf-overflow-auto",De?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:ft.jsx(Rw,{fallbackRender:({error:ze})=>ft.jsx("div",{className:"rf-mt-4 rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200",children:ft.jsxs("div",{className:"rf-p-4",children:[ft.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-3",children:"Error loading Bill of Materials"}),ft.jsx("p",{className:"rf-text-xs rf-font-mono rf-whitespace-pre-wrap rf-text-red-600 rf-mt-2",children:(ze==null?void 0:ze.message)||"An unknown error occurred"})]})}),children:n?ft.jsx(W$t,{circuitJson:n}):ft.jsx(g7,{onRunClicked:e})})})}),ft.jsx(o4,{value:"circuit_json",children:ft.jsx("div",{className:jy("rf-overflow-auto",De?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:ft.jsx(Rw,{fallback:ft.jsx("div",{children:"Error loading JSON viewer"}),children:n?ft.jsx(Y$t,{elements:n}):ft.jsx(g7,{onRunClicked:e})})})}),ft.jsx(o4,{value:"errors",children:ft.jsx("div",{className:jy("rf-overflow-auto",De?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:n||t?ft.jsx(MBt,{code:r,errorMessage:t,autoroutingLog:P,onReportAutoroutingLog:O}):ft.jsx(g7,{onRunClicked:e})})}),c&&ft.jsx(o4,{value:"render_log",children:ft.jsx(znn,{renderLog:f})})]})})})};_ue.createRoot(document.getElementById("root")).render(ft.jsx(Inn,{defaultActiveTab:"cad",autoRotate3dViewerDisabled:!0,showRightHeaderContent:!1,circuitJson:window.CIRCUIT_JSON||{},...window.CIRCUIT_JSON_PREVIEW_PROPS||{}}))});
13365
+ searched component ${c.getString()}, which has ports: ${c.children.filter(u=>u.componentName==="Port").map(u=>`${u.getString()}(${u.getNameAndAliases().join(",")})`).join(" & ")}`):this.renderError(`Could not find port for selector "${o}"`)}return a.some(o=>!o.port)?{allPortsFound:!1}:{allPortsFound:!0,portsWithSelectors:a,ports:a.map(({port:o})=>o)}}_findConnectedNets(){const e=this.getTracePathNetSelectors().map(n=>({selector:n,net:this.getSubcircuit().selectOne(n,{type:"net"})})),t=e.filter(n=>!n.net);return t.length>0&&this.renderError(`Could not find net for selector "${t[0].selector}" inside ${this}`),{netsWithSelectors:e,nets:e.map(n=>n.net)}}_getAllTracesConnectedToSameNet(){const e=this.getSubcircuit().selectAll("trace"),t=this._findConnectedNets().nets,n=this._findConnectedPorts().ports??[];return e.filter(i=>{if(i===this)return!1;const a=i._findConnectedNets().nets,o=i._findConnectedPorts().ports??[];return a.some(s=>t.includes(s))||o.some(s=>n.includes(s))})}_isExplicitlyConnectedToPort(e){const{allPortsFound:t,portsWithSelectors:n}=this._findConnectedPorts();return t?n.map(a=>a.port).includes(e):!1}_isExplicitlyConnectedToNet(e){return this._findConnectedNets().nets.includes(e)}doInitialCreateNetsFromProps(){WHe(this,this.getTracePathNetSelectors())}doInitialSourceTraceRender(){var c;const{db:e}=this.root,{_parsedProps:t,parent:n}=this;if(!n){this.renderError("Trace has no parent");return}const{allPortsFound:i,portsWithSelectors:a}=this._findConnectedPorts();if(!i)return;const o=this._findConnectedNets().nets,s=Qtn({ports:a,nets:o}),l=e.source_trace.insert({connected_source_port_ids:a.map(u=>u.port.source_port_id),connected_source_net_ids:o.map(u=>u.source_net_id),subcircuit_id:(c=this.getSubcircuit())==null?void 0:c.subcircuit_id,max_length:Wtn(a.map(u=>u.port),{db:e})??t.maxLength,display_name:s,min_trace_thickness:t.thickness});this.source_trace_id=l.source_trace_id}_insertErrorIfTraceIsOutsideBoard(e,t){const{db:n}=this.root;Jtn(e,{db:n})&&n.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(a=>a.pcb_port_id)})}doInitialPcbTraceRender(){var ee,ie,J,de;if((ee=this.root)!=null&&ee.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t,parent:n}=this,i=this.getSubcircuit();if(!n)throw new Error("Trace has no parent");if(i._parsedProps.routingDisabled)return;const a=(ie=i._parsedProps.pcbRouteCache)==null?void 0:ie.pcbTraces;if(a){const he=e.pcb_trace.insert({route:a.flatMap(_e=>_e.route),source_trace_id:this.source_trace_id,subcircuit_id:(i==null?void 0:i.subcircuit_id)??void 0,pcb_group_id:((J=this.getGroup())==null?void 0:J.pcb_group_id)??void 0});this.pcb_trace_id=he.pcb_trace_id;return}if(!i._shouldUseTraceByTraceRouting())return;const{allPortsFound:o,ports:s}=this._findConnectedPorts();if(!o)return;const l=[];for(const he of s)he._hasMatchedPcbPrimitive()||l.push(he);if(l.length>0){e.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:this.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, ${this} wasn't routed. Missing ports: ${l.map(he=>he.getString()).join(", ")}`,pcb_trace_id:this.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:l.map(he=>he.pcb_port_id).filter(Boolean)});return}const c=this._findConnectedNets().netsWithSelectors;if(s.length===0&&c.length===2){this.renderError("Trace connects two nets, we haven't implemented a way to route this yet");return}else if(s.length===1&&c.length===1){const he=s[0],Ce=c[0].net.getAllConnectedPorts().filter(Ee=>Ee!==he);if(Ce.length===0){console.log("Nothing to connect this port to, the net is empty. TODO should emit a warning!");return}const De=jtn(he,Ce);s.push(De)}else if(s.length>1&&c.length>=1){this.renderError("Trace has more than one port and one or more nets, we don't currently support this type of complex trace routing");return}const u=s.flatMap(he=>he.matchedComponents.filter(_e=>_e.componentName==="TraceHint")),f=(this._parsedProps.pcbRouteHints??[]).concat(u.flatMap(he=>he.getPcbRouteHints()));if(s.length>2){this.renderError(`Trace has more than two ports (${s.map(he=>he.getString()).join(", ")}), routing between more than two ports for a single trace is not implemented`);return}if(this.getSubcircuit().selectAll("trace").filter(he=>he.renderPhaseStates.PcbTraceRender.initialized).some(he=>he._portsRoutedOnPcb.length===s.length&&he._portsRoutedOnPcb.every(_e=>s.includes(_e))))return;let x=[];f.length===0?x=[wF(s[0]),wF(s[1])]:x=[wF(s[0]),...f,wF(s[1])];const M=SF(x),T=kT(this.root.db.toArray()),[w,P]=Vtn(()=>EN(this.root.db.toArray()));if(P){this.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:this.pcb_trace_id,message:`Error getting obstacles for autorouting: ${P.message}`,source_trace_id:this.source_trace_id,center:{x:0,y:0},pcb_port_ids:s.map(he=>he.pcb_port_id),pcb_trace_id:this.pcb_trace_id,pcb_component_ids:[]});return}for(const he of w)if(he.connectedTo.length>0){const Ce=T.getNetConnectedToId(he.connectedTo[0]);Ce&&he.connectedTo.push(Ce)}let O=[];if(M.length===0)O=x;else{const he=M[0].layer_path;O=x.map((_e,Ce)=>_e.via?{..._e,via_to_layer:he[Ce]}:{..._e,layers:[he[Ce]]})}O[0].pcb_port_id=s[0].pcb_port_id,O[O.length-1].pcb_port_id=s[1].pcb_port_id;const F=[];for(const[he,_e]of YHe(O)){const Ce="via_to_layer"in he?he.via_to_layer:null,De=2,Ee="layers"in he&&he.layers.length===1?he.layers[0]:Ce??"top",Pe="layers"in _e&&_e.layers.length===1?_e.layers[0]:Ce??"top",Te="pcb_port_id"in he?he.pcb_port_id:null,Ie="pcb_port_id"in _e?_e.pcb_port_id:null,ze=this.getSubcircuit()._parsedProps.minTraceWidth??.16,He=new SN({OBSTACLE_MARGIN:ze*2,isRemovePathLoopsEnabled:!0,optimizeWithGoalBoxes:!!(Te&&Ie),connMap:T,input:{obstacles:w,minTraceWidth:ze,connections:[{name:this.source_trace_id,pointsToConnect:[{...he,layer:Ee,pcb_port_id:Te},{..._e,layer:Pe,pcb_port_id:Ie}]}],layerCount:2,bounds:{minX:Math.min(he.x,_e.x)-De,maxX:Math.max(he.x,_e.x)+De,minY:Math.min(he.y,_e.y)-De,maxY:Math.max(he.y,_e.y)+De}}});let Ue=null;try{Ue=He.solveAndMapToTraces()}catch(ht){this.renderError({type:"pcb_trace_error",pcb_trace_error_id:this.source_trace_id,error_type:"pcb_trace_error",message:`error solving route: ${ht.message}`,source_trace_id:this.pcb_trace_id,center:{x:(he.x+_e.x)/2,y:(he.y+_e.y)/2},pcb_port_ids:s.map(Tt=>Tt.pcb_port_id),pcb_trace_id:this.pcb_trace_id,pcb_component_ids:s.map(Tt=>Tt.pcb_component_id)})}if(!Ue)return;if(Ue.length===0){this.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:this.pcb_trace_id,message:`Could not find a route for ${this}`,source_trace_id:this.source_trace_id,center:{x:(he.x+_e.x)/2,y:(he.y+_e.y)/2},pcb_port_ids:s.map(ht=>ht.pcb_port_id),pcb_trace_id:this.pcb_trace_id,pcb_component_ids:s.map(ht=>ht.pcb_component_id)});return}const[at]=Ue;Ce&&(at.route=at.route.map(ht=>(ht.route_type==="wire"&&!ht.layer&&(ht.layer=Ce),ht))),Te&&at.route[0].route_type==="wire"&&(at.route[0].start_pcb_port_id=Te);const tt=at.route[at.route.length-1];Ie&&tt.route_type==="wire"&&(tt.end_pcb_port_id=Ie),F.push(at.route)}const $=Ftn(F),Z=Gtn($),Q=e.pcb_trace.insert({route:$,source_trace_id:this.source_trace_id,subcircuit_id:(de=this.getSubcircuit())==null?void 0:de.subcircuit_id,trace_length:Z});this._portsRoutedOnPcb=s,this.pcb_trace_id=Q.pcb_trace_id;for(const he of $)he.route_type==="via"&&e.pcb_via.insert({pcb_trace_id:Q.pcb_trace_id,x:he.x,y:he.y,hole_diameter:.3,outer_diameter:.6,layers:[he.from_layer,he.to_layer],from_layer:he.from_layer,to_layer:he.to_layer});this._insertErrorIfTraceIsOutsideBoard($,s)}_doInitialSchematicTraceRenderWithDisplayLabel(){var F,$,Z,Q;if((F=this.root)!=null&&F.schematicDisabled)return;const{db:e}=this.root,{_parsedProps:t,parent:n}=this;if(!n)throw new Error("Trace has no parent");const{allPortsFound:i,portsWithSelectors:a}=this._findConnectedPorts();if(!i)return;const o=a.map(({port:ee})=>({port:ee,position:ee._getGlobalSchematicPositionAfterLayout(),schematic_port_id:ee.schematic_port_id,facingDirection:ee.facingDirection}));if(o.length<2)throw new Error("Expected at least two ports in portsWithPosition.");let s,l;const c=o[0].position,u=o[0].port;if("path"in this.props){if(this.props.path.length!==2)throw new Error("Invalid 'path': Must contain exactly two elements.");[s,l]=this.props.path}else{if(!("from"in this.props&&"to"in this.props))throw new Error("Missing 'from' or 'to' properties in props.");s=this.props.from,l=this.props.to}if(!u.source_port_id)throw new Error(`Missing source_port_id for the 'from' port (${s}).`);const f=o[1].position,m=o[1].port;if(!m.source_port_id)throw new Error(`Missing source_port_id for the 'to' port (${l}).`);const g=e.schematic_net_label.list().find(ee=>ee.source_net_id===u.source_port_id),x=e.schematic_net_label.list().find(ee=>ee.source_net_id===m.source_port_id),[M,T]=a.map(({port:ee})=>ee),P=(($=M.parent)==null?void 0:$.config.shouldRenderAsSchematicBox)?`${(Z=M==null?void 0:M.parent)==null?void 0:Z.props.name}_${M==null?void 0:M.props.name}`:`${(Q=T==null?void 0:T.parent)==null?void 0:Q.props.name}_${T==null?void 0:T.props.name}`,O=this.props.schDisplayLabel??P;if(g&&g.text!==O&&(g.text=`${O} / ${g.text}`),x&&(x==null?void 0:x.text)!==O&&(x.text=`${O} / ${x.text}`),O!=null&&O.toLocaleLowerCase().includes("gnd")||O!=null&&O.toLocaleLowerCase().includes("ground")){!g&&!x?(EF({port:u,anchorPos:c,schDisplayLabel:this.props.schDisplayLabel,source_trace_id:this.source_trace_id},{db:e}),EF({port:m,anchorPos:f,schDisplayLabel:this.props.schDisplayLabel,source_trace_id:this.source_trace_id},{db:e})):g?x||EF({port:m,anchorPos:f,schDisplayLabel:this.props.schDisplayLabel,source_trace_id:this.source_trace_id},{db:e}):EF({port:u,anchorPos:c,schDisplayLabel:this.props.schDisplayLabel,source_trace_id:this.source_trace_id},{db:e});return}x||e.schematic_net_label.insert({text:this.props.schDisplayLabel??P,source_net_id:m.source_port_id,anchor_position:f,center:f,anchor_side:Vle(m.facingDirection)??"bottom"}),g||e.schematic_net_label.insert({text:this.props.schDisplayLabel??P,source_net_id:u.source_port_id,anchor_position:c,center:c,anchor_side:Vle(u.facingDirection)??"bottom"})}_isSymbolToChipConnection(){const{allPortsFound:e,ports:t}=this._findConnectedPorts();if(!e||t.length!==2)return!1;const[n,i]=t;if(!(n!=null&&n.parent)||!(i!=null&&i.parent))return!1;const a=n.parent.config.shouldRenderAsSchematicBox,o=i.parent.config.shouldRenderAsSchematicBox;return a&&!o||!a&&o}_isSymbolToSymbolConnection(){const{allPortsFound:e,ports:t}=this._findConnectedPorts();if(!e||t.length!==2)return!1;const[n,i]=t;if(!(n!=null&&n.parent)||!(i!=null&&i.parent))return!1;const a=!n.parent.config.shouldRenderAsSchematicBox,o=!i.parent.config.shouldRenderAsSchematicBox;return a&&o}_isChipToChipConnection(){const{allPortsFound:e,ports:t}=this._findConnectedPorts();if(!e||t.length!==2)return!1;const[n,i]=t;if(!(n!=null&&n.parent)||!(i!=null&&i.parent))return!1;const a=n.parent.config.shouldRenderAsSchematicBox,o=i.parent.config.shouldRenderAsSchematicBox;return a&&o}doInitialSchematicTraceRender(){var _e;if((_e=this.root)!=null&&_e.schematicDisabled)return;const{db:e}=this.root,{_parsedProps:t,parent:n}=this;if(!n)throw new Error("Trace has no parent");const{allPortsFound:i,portsWithSelectors:a}=this._findConnectedPorts(),{netsWithSelectors:o}=this._findConnectedNets();if(!i)return;if(this.props.schDisplayLabel&&("from"in this.props&&"to"in this.props||"path"in this.props)){this._doInitialSchematicTraceRenderWithDisplayLabel();return}const s={name:this.source_trace_id,pointsToConnect:[]},l=Ztn(this),c=a.map(({port:Ce})=>({port:Ce,position:Ce._getGlobalSchematicPositionAfterLayout(),schematic_port_id:Ce.schematic_port_id??void 0,facingDirection:Ce.facingDirection}));if(c.length===1&&o.length===1){const Ce=o[0].net,{port:De,position:Ee}=c[0];e.schematic_net_label.insert({text:Ce._parsedProps.name,source_net_id:Ce.source_net_id,anchor_position:Ee,center:Ee,anchor_side:Vle(De.facingDirection)??"bottom"});return}if(c.length<2)return;s.pointsToConnect=c.map(({position:Ce})=>({...Ce,layer:"top"}));const f=Itn(l),m=2,g={minTraceWidth:.1,obstacles:l,connections:[s],bounds:{minX:f.minX-m,maxX:f.maxX+m,minY:f.minY-m,maxY:f.maxY+m},layerCount:1};let x=SN,M=!1;this.getSubcircuit().props._schDirectLineRoutingEnabled&&(x=rVe,M=!0);let w=new x({input:g,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(w.length===0){if(this._isSymbolToChipConnection()||this._isSymbolToSymbolConnection()||this._isChipToChipConnection()){this._doInitialSchematicTraceRenderWithDisplayLabel();return}w=new rVe({input:g}).solveAndMapToTraces(),M=!0}const[{route:P}]=w;let O=[];for(let Ce=0;Ce<P.length-1;Ce++)O.push({from:P[Ce],to:P[Ce+1]});const F=this.source_trace_id;let $=[];if(!M){Ktn({edges:O,db:e,source_trace_id:F});const Ce=qle({db:e,source_trace_id:F,differentNetOnly:!0}).flatMap(De=>De.edges);O=$tn({edges:O,otherEdges:Ce}),$=Xtn({edges:O,db:e,source_trace_id:this.source_trace_id})}const Z=O[O.length-1],Q=c[c.length-1],ee=aVe(Z);O.push(...Gle({lastEdge:Z,lastEdgePort:Q,lastDominantDirection:ee}));const ie=O[0],J=c[0],de=aVe(ie);if(O.unshift(...Gle({firstEdge:ie,firstEdgePort:J,firstDominantDirection:de})),!this.source_trace_id)throw new Error("Missing source_trace_id for schematic trace insertion.");if(this.getSubcircuit()._parsedProps.schTraceAutoLabelEnabled&&Htn($,O)>=5&&(this._isSymbolToChipConnection()||this._isSymbolToSymbolConnection()||this._isChipToChipConnection())){this._doInitialSchematicTraceRenderWithDisplayLabel();return}const he=e.schematic_trace.insert({source_trace_id:this.source_trace_id,edges:O,junctions:$});this.schematic_trace_id=he.schematic_trace_id}},enn=lg("tscircuit:core"),tnn=z.object({x:LS,y:LS,z:LS}),Zx=class extends X_{constructor(e){super(e);dt(this,"reactSubtrees",[]);dt(this,"_impliedFootprint");dt(this,"isPrimitiveContainer",!0);dt(this,"_asyncSupplierPartNumbers");dt(this,"pcb_missing_footprint_error_id");this._addChildrenFromStringFootprint(),this.initPorts()}get defaultInternallyConnectedPinNames(){return[]}get internallyConnectedPinNames(){return this._parsedProps.internallyConnectedPins??this.defaultInternallyConnectedPinNames}initPorts(e={}){var o,s,l,c,u,f,m,g,x,M;if((o=this.root)!=null&&o.schematicDisabled)return;const{config:t}=this,n=[],i=this._getSchematicPortArrangement();if(i&&!this._parsedProps.pinLabels){for(const P in i){const O=i[P].pins;if(Array.isArray(O))for(const F of O){const $=lA(F,this._parsedProps.pinLabels);n.push(new OS({pinNumber:$,aliases:((s=e.additionalAliases)==null?void 0:s[`pin${$}`])??[]},{originDescription:`schPortArrangement:${P}`}))}}const T=["left","right","top","bottom"];let w=1;for(const P of T){const O=i[`${P}Size`];for(let F=0;F<O;F++)n.push(new OS({pinNumber:w++,aliases:((l=e.additionalAliases)==null?void 0:l[`pin${w}`])??[]},{originDescription:`schPortArrangement:${P}`}))}}const a=this._parsedProps.pinLabels;if(a)for(let[T,w]of Object.entries(a)){T=T.replace("pin","");let P=n.find($=>$._parsedProps.pinNumber===Number(T));const O=Array.isArray(w)?w[0]:w,F=Array.isArray(w)?w.slice(1):[];P?(P.externallyAddedAliases.push(O,...F),P.props.name=O):(P=new OS({pinNumber:parseInt(T),name:O,aliases:[...F,...((c=e.additionalAliases)==null?void 0:c[`pin${parseInt(T)}`])??[]]},{originDescription:`pinLabels:pin${T}`}),n.push(P))}if(t.schematicSymbolName){const T=bb[this._getSchematicSymbolNameOrThrow()];if(!T)return;for(const w of T.ports){const P=tVe(w.labels);if(!P)continue;const O=n.find(F=>F._parsedProps.pinNumber===Number(P));if(O)O.schematicSymbolPortDef=w;else{const F=uA(w.labels.concat(((u=e.additionalAliases)==null?void 0:u[`pin${P}`])??[]));F&&(F.originDescription=`schematicSymbol:labels[0]:${w.labels[0]}`,F.schematicSymbolPortDef=w,n.push(F))}}this.addAll(n)}if(!this._getSchematicPortArrangement()){const T=this.getPortsFromFootprint(e);for(const w of T)n.some(P=>P.isMatchingAnyOf(w.getNameAndAliases()))||n.push(w)}for(let T=1;T<=(e.pinCount??this._getPinCount());T++){if(!i||n.find(P=>P._parsedProps.pinNumber===T))continue;let w=[...((f=i.leftSide)==null?void 0:f.pins)??[],...((m=i.rightSide)==null?void 0:m.pins)??[],...((g=i.topSide)==null?void 0:g.pins)??[],...((x=i.bottomSide)==null?void 0:x.pins)??[]].map(P=>lA(P,this._parsedProps.pinLabels));["leftSize","rightSize","topSize","bottomSize","leftPinCount","rightPinCount","topPinCount","bottomPinCount"].some(P=>P in i)&&(w=Array.from({length:this._getPinCount()},(P,O)=>O+1)),w.includes(T)&&n.push(new OS({pinNumber:T,aliases:((M=e.additionalAliases)==null?void 0:M[`pin${T}`])??[]},{originDescription:`notOtherwiseAddedButDeducedFromPinCount:${T}`}))}n.length>0&&this.addAll(n)}_getImpliedFootprintString(){return null}_addChildrenFromStringFootprint(){var i;const{name:e,pcbRotation:t}=this.props;let{footprint:n}=this.props;if(n??(n=(i=this._getImpliedFootprintString)==null?void 0:i.call(this)),!!n&&typeof n=="string"){const a=sP.string(n).soup(),o=Ctn({componentName:e,componentRotation:t},a);this.addAll(o)}}get portMap(){return new Proxy({},{get:(e,t)=>{const n=this.children.find(i=>i.componentName==="Port"&&i.isMatchingNameOrAlias(t));if(!n)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 n}})}getInstanceForReactElement(e){for(const t of this.reactSubtrees)if(t.element===e)return t.component;return null}doInitialSourceRender(){const e=this.config.sourceFtype;if(!e)return;const{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:e,name:n.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers});this.source_component_id=i.source_component_id}doInitialSchematicComponentRender(){var n;if((n=this.root)!=null&&n.schematicDisabled)return;const{schematicSymbolName:e}=this.config;if(e)return this._doInitialSchematicComponentRenderWithSymbol();if(this._getSchematicBoxDimensions())return this._doInitialSchematicComponentRenderWithSchematicBoxDimensions()}_getSchematicSymbolDisplayValue(){}_getInternallyConnectedPins(){if(this.internallyConnectedPinNames.length===0)return[];const e=[];for(const t of this.internallyConnectedPinNames){const n=[];for(const i of t)n.push(this.portMap[i]);e.push(n)}return e}_doInitialSchematicComponentRenderWithSymbol(){var o;if((o=this.root)!=null&&o.schematicDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=this._getSchematicSymbolNameOrThrow(),i=bb[n],a=this._getGlobalSchematicPositionBeforeLayout();if(i){const s=e.schematic_component.insert({center:a,size:i.size,source_component_id:this.source_component_id,symbol_name:n,symbol_display_value:this._getSchematicSymbolDisplayValue()});this.schematic_component_id=s.schematic_component_id}}_doInitialSchematicComponentRenderWithSchematicBoxDimensions(){var f;if((f=this.root)!=null&&f.schematicDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=this._getSchematicBoxDimensions(),i={};if(Array.isArray(t.pinLabels))t.pinLabels.forEach((m,g)=>{i[String(g+1)]=m});else for(const[m,g]of Object.entries(t.pinLabels??{}))i[m]=Array.isArray(g)?g[0]:g;const a=this._getGlobalSchematicPositionBeforeLayout(),o=this._getSchematicPortArrangement(),s=e.schematic_component.insert({center:a,rotation:t.schRotation??0,size:n.getSize(),port_arrangement:wtn(o),pin_spacing:t.schPinSpacing??.2,pin_styles:Etn(t.schPinStyle,t.pinLabels),port_labels:i,source_component_id:this.source_component_id}),l=(o==null?void 0:o.topSide)!==void 0||(o==null?void 0:o.bottomSide)!==void 0,c=n==null?void 0:n.getSize().width,u=n==null?void 0:n.getSize().height;e.schematic_text.insert({text:t.manufacturerPartNumber??"",schematic_component_id:s.schematic_component_id,anchor:"left",rotation:0,position:{x:l?a.x+(c??0)/2+.1:a.x-(c??0)/2,y:l?a.y+(u??0)/2+.35:a.y-(u??0)/2-.13},color:"#006464"}),e.schematic_text.insert({text:t.name??"",schematic_component_id:s.schematic_component_id,anchor:"left",rotation:0,position:{x:l?a.x+(c??0)/2+.1:a.x-(c??0)/2,y:l?a.y+(u??0)/2+.55:a.y+(u??0)/2+.13},color:"#006464"}),this.schematic_component_id=s.schematic_component_id}doInitialPcbComponentRender(){var o;if((o=this.root)!=null&&o.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=this.getSubcircuit(),i=e.pcb_component.insert({center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,layer:t.layer??"top",rotation:t.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:n.subcircuit_id??void 0});if(!t.footprint&&!this.isGroup){const s=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=s.pcb_missing_footprint_error_id}this.pcb_component_id=i.pcb_component_id;const a=this.getSubcircuit()._getPcbManualPlacementForComponent(this);this.props.pcbX!==void 0&&this.props.pcbY!==void 0&&a&&this.renderError({type:"pcb_manual_edit_conflict_error",message:`${this.getString()} has both manual placement and explicit 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})}doInitialPcbComponentSizeCalculation(){var a;if((a=this.root)!=null&&a.pcbDisabled||!this.pcb_component_id)return;const{db:e}=this.root,{_parsedProps:t}=this,n=eVe(this.children);if(n.width===0||n.height===0)return;const i={x:(n.minX+n.maxX)/2,y:(n.minY+n.maxY)/2};e.pcb_component.update(this.pcb_component_id,{center:i,width:n.width,height:n.height})}_renderReactSubtree(e){return{element:e,component:Stn(e)}}doInitialInitializePortsFromChildren(){this.initPorts()}doInitialReactSubtreesRender(){if(wt.isValidElement(this.props.footprint)){if(this.reactSubtrees.some(t=>t.element===this.props.footprint))return;const e=this._renderReactSubtree(this.props.footprint);this.reactSubtrees.push(e),this.add(e.component)}}_hasExistingPortExactly(e){return this.children.filter(n=>n.componentName==="Port").some(n=>{const i=e.getNameAndAliases(),a=n.getNameAndAliases();return i.length===a.length&&i.every(o=>a.includes(o))})}add(e){let t;if(wt.isValidElement(e)){const n=this._renderReactSubtree(e);this.reactSubtrees.push(n),t=n.component}else t=e;if(t.componentName==="Port"){if(this._hasExistingPortExactly(t))return;const i=this.children.filter(a=>a.componentName==="Port").find(a=>a.isMatchingAnyOf(t.getNameAndAliases()));i&&enn(`Similar ports added. Port 1: ${i}, Port 2: ${t}`)}super.add(t)}getPortsFromFootprint(e){let{footprint:t}=this.props;if((!t||wt.isValidElement(t))&&(t=this.children.find(i=>i.componentName==="Footprint")),typeof t=="string"){const i=sP.string(t).soup(),a=[];for(const o of i)if("port_hints"in o&&o.port_hints){const s=uA(o.port_hints,e);if(!s)continue;s.originDescription=`footprint:string:${t}:port_hints[0]:${o.port_hints[0]}`,a.push(s)}return a}if(!wt.isValidElement(t)&&t&&t.componentName==="Footprint"){const i=t;let a=1;const o=[];for(const s of i.children){if(!s.props.portHints)continue;let l=s.props.portHints;l.some(f=>f.startsWith("pin"))||(l=[...l,`pin${a}`]),a++;const u=uA(l);u&&(u.originDescription=`footprint:${t}`,o.push(u))}return o}const n=[];if(!t){for(const i of this.children)if(i.props.portHints&&i.isPcbPrimitive){const a=uA(i.props.portHints);a&&n.push(a)}}return n}getPortsFromSchematicSymbol(){var i;if((i=this.root)!=null&&i.schematicDisabled)return[];const{config:e}=this;if(!e.schematicSymbolName)return[];const t=bb[e.schematicSymbolName];if(!t)return[];const n=[];for(const a of t.ports){const o=uA(a.labels);o&&(o.schematicSymbolPortDef=a,n.push(o))}return n}doInitialCreateNetsFromProps(){this._createNetsFromProps(this._getNetsFromConnectionsProp())}_getNetsFromConnectionsProp(){const{_parsedProps:e}=this,t=[];if(e.connections)for(const[n,i]of Object.entries(e.connections)){const a=Array.isArray(i)?i:[i];for(const o of a)t.push(o)}return t}_createNetsFromProps(e){WHe(this,e)}_getPcbCircuitJsonBounds(){const{db:e}=this.root;if(!this.pcb_component_id)return super._getPcbCircuitJsonBounds();const 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(){const e=this._getSchematicPortArrangement();if(!e)return 0;if(!nVe(e))return(e.leftSize??e.leftPinCount??0)+(e.rightSize??e.rightPinCount??0)+(e.topSize??e.topPinCount??0)+(e.bottomSize??e.bottomPinCount??0);const{leftSide:n,rightSide:i,topSide:a,bottomSide:o}=e;return Math.max(...(n==null?void 0:n.pins)??[],...(i==null?void 0:i.pins)??[],...(a==null?void 0:a.pins)??[],...(o==null?void 0:o.pins)??[])}_getPinCount(){return this._getSchematicPortArrangement()?this._getPinCountFromSchematicPortArrangement():this.getPortsFromFootprint().length}_getSchematicPortArrangement(){return this._parsedProps.schPinArrangement??this._parsedProps.schPortArrangement}_getSchematicBoxDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;const{_parsedProps:e}=this,t=this._getPinCount(),n=e.schPinSpacing??.2;return Otn({schWidth:e.schWidth,schHeight:e.schHeight,schPinSpacing:n,numericSchPinStyle:ktn(e.schPinStyle,e.pinLabels),pinCount:t,schPortArrangement:this._getSchematicPortArrangement(),pinLabels:e.pinLabels})}doInitialCadModelRender(){var c;const{db:e}=this.root,{boardThickness:t=0}=((c=this.root)==null?void 0:c._getBoard())??{},n=this._parsedProps.cadModel;if(!this.pcb_component_id||!n&&!this.props.footprint)return;const i=this._getPcbCircuitJsonBounds(),a=e.pcb_component.get(this.pcb_component_id);if(typeof n=="string")throw new Error("String cadModel not yet implemented");const o=tnn.parse({x:0,y:0,z:typeof(n==null?void 0:n.rotationOffset)=="number"?n.rotationOffset:0,...typeof(n==null?void 0:n.rotationOffset)=="object"?n.rotationOffset??{}:{}}),s=dI.parse({x:0,y:0,z:0,...typeof(n==null?void 0:n.positionOffset)=="object"?n.positionOffset:{}}),l=this.props.layer==="bottom"?"bottom":"top";e.cad_component.insert({position:{x:i.center.x+s.x,y:i.center.y+s.y,z:(l==="bottom"?-t/2:t/2)+s.z},rotation:{x:o.x,y:(l==="top"?0:180)+o.y,z:((a==null?void 0:a.rotation)??0)+(l==="bottom"?180:0)+o.z},pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,model_stl_url:"stlUrl"in(n??{})?this._addCachebustToModelUrl(n.stlUrl):void 0,model_obj_url:"objUrl"in(n??{})?this._addCachebustToModelUrl(n.objUrl):void 0,model_jscad:"jscad"in(n??{})?n.jscad:void 0,footprinter_string:typeof this.props.footprint=="string"&&!n?this.props.footprint:void 0})}_addCachebustToModelUrl(e){var n;if(!e||!e.includes("modelcdn.tscircuit.com"))return e;const t=((n=this.root)==null?void 0:n.getClientOrigin())??"";return`${e}${e.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(t)}`}doInitialPartsEngineRender(){const e=this.getInheritedProperty("partsEngine");if(!e)return;const{db:t}=this.root,n=t.source_component.get(this.source_component_id);if(!n||n.supplier_part_numbers)return;let i;this.props.footprint&&typeof this.props.footprint=="string"&&(i=this.props.footprint);const a=e.findPart({sourceComponent:n,footprinterString:i});if(!(a instanceof Promise)){t.source_component.update(this.source_component_id,{supplier_part_numbers:a});return}this._queueAsyncEffect("get-supplier-part-numbers",async()=>{this._asyncSupplierPartNumbers=await a,this._markDirty("PartsEngineRender")})}updatePartsEngineRender(){const{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}}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}_createTracesFromConnectionsProp(){const{_parsedProps:e}=this;if(e.connections)for(const[t,n]of Object.entries(e.connections)){const i=Array.isArray(n)?n:[n];for(const a of i)this.add(new x7({from:`${this.getSubcircuitSelector()} > port.${t}`,to:a}))}}},nnn=class{constructor(r,e={}){dt(this,"input");dt(this,"isRouting",!1);dt(this,"solver");dt(this,"eventHandlers",{complete:[],error:[],progress:[]});dt(this,"cycleCount",0);dt(this,"stepDelay");dt(this,"timeoutId");this.input=r;const{capacityDepth:t,targetMinCapacity:n,stepDelay:i=0}=e;this.solver=new H1e(r,{capacityDepth:t,targetMinCapacity:n}),this.stepDelay=i}start(){this.isRouting||(this.isRouting=!0,this.cycleCount=0,this.runCycleAndQueueNextCycle())}runCycleAndQueueNextCycle(){var r;if(this.isRouting)try{if(this.solver.solved||this.solver.failed){this.solver.failed?this.emitEvent({type:"error",error:new Error(this.solver.error||"Routing failed")}):this.emitEvent({type:"complete",traces:this.solver.getOutputSimpleRouteJson().traces||[]}),this.isRouting=!1;return}const e=Date.now(),t=this.solver.iterations;for(;Date.now()-e<250&&!this.solver.failed&&!this.solver.solved;)this.solver.step();const n=(this.solver.iterations-t)/(Date.now()-e)*1e3;this.cycleCount++;const i=((r=this.solver)==null?void 0:r.preview())||void 0,a=this.solver.progress;this.emitEvent({type:"progress",steps:this.cycleCount,iterationsPerSecond:n,progress:a,phase:this.solver.getCurrentPhase(),debugGraphics:i}),this.stepDelay>0?this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),this.stepDelay):this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),0)}catch(e){this.emitEvent({type:"error",error:e instanceof Error?e:new Error(String(e))}),this.isRouting=!1}}stop(){this.isRouting&&(this.isRouting=!1,this.timeoutId!==void 0&&(clearTimeout(this.timeoutId),this.timeoutId=void 0))}on(r,e){r==="complete"?this.eventHandlers.complete.push(e):r==="error"?this.eventHandlers.error.push(e):r==="progress"&&this.eventHandlers.progress.push(e)}emitEvent(r){if(r.type==="complete")for(const e of this.eventHandlers.complete)e(r);else if(r.type==="error")for(const e of this.eventHandlers.error)e(r);else if(r.type==="progress")for(const e of this.eventHandlers.progress)e(r)}solveSync(){if(this.solver.solve(),this.solver.failed)throw new Error(this.solver.error||"Routing failed");return this.solver.getOutputSimpleRouteJson().traces||[]}},oVe=class extends X_{constructor(){super(...arguments);dt(this,"matchedPort",null)}get config(){return{componentName:"TraceHint",zodProps:ptn}}doInitialPortMatching(){const{db:e}=this.root,{_parsedProps:t,parent:n}=this;if(!n)return;if(n.componentName==="Trace"){this.renderError(`Port inference inside trace is not yet supported (${this})`);return}if(!n)throw new Error("TraceHint has no parent");if(!t.for){this.renderError(`TraceHint has no for property (${this})`);return}const i=n.selectOne(t.for,{type:"port"});i||this.renderError(`${this} could not find port for selector "${t.for}"`),this.matchedPort=i,i.registerMatch(this)}getPcbRouteHints(){const{_parsedProps:e}=this,t=e.offset?[e.offset]:e.offsets;if(!t)return[];const n=this._computePcbGlobalTransformBeforeLayout();return t.map(i=>({...Fr(n,i),via:i.via,to_layer:i.to_layer,trace_width:i.trace_width}))}doInitialPcbTraceHintRender(){var n,i,a;if((n=this.root)!=null&&n.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this;e.pcb_trace_hint.insert({pcb_component_id:(i=this.matchedPort)==null?void 0:i.pcb_component_id,pcb_port_id:(a=this.matchedPort)==null?void 0:a.pcb_port_id,route:this.getPcbRouteHints()})}},rnn=(r,e)=>{const t=r.source_group.list(),n=[],i=a=>{const o=t.filter(s=>s.parent_subcircuit_id===a);for(const s of o)s.subcircuit_id&&(n.push(s.subcircuit_id),i(s.subcircuit_id))};return i(e),n},sVe=({db:r,circuitJson:e,subcircuit_id:t,minTraceWidth:n=.1})=>{if(!r&&e&&(r=wv(e)),!r)throw new Error("db or circuitJson is required");const i=t?new Set([t]):null;if(t){const x=rnn(r,t);for(const M of x)i.add(M)}const a=(e??r.toArray()).filter(x=>!t||"subcircuit_id"in x&&i.has(x.subcircuit_id)),o=r.pcb_board.list()[0];r=wv(a);const s=kT(a),l=EN([...r.pcb_component.list(),...r.pcb_smtpad.list(),...r.pcb_plated_hole.list(),...r.pcb_hole.list(),...r.pcb_via.list()].filter(x=>!t||(i==null?void 0:i.has(x.subcircuit_id))),s);for(const x of l){const M=x.connectedTo.flatMap(T=>s.getIdsConnectedToNet(T));x.connectedTo.push(...M)}const c=l.flatMap(x=>[{x:x.center.x-x.width/2,y:x.center.y-x.height/2},{x:x.center.x+x.width/2,y:x.center.y+x.height/2}]);let u;o?u={minX:o.center.x-o.width/2,maxX:o.center.x+o.width/2,minY:o.center.y-o.height/2,maxY:o.center.y+o.height/2}:u={minX:Math.min(...c.map(x=>x.x))-1,maxX:Math.max(...c.map(x=>x.x))+1,minY:Math.min(...c.map(x=>x.y))-1,maxY:Math.max(...c.map(x=>x.y))+1};const f=r.source_trace.list().map(x=>{const M=x.connected_source_port_ids.map(T=>{const w=r.source_port.get(T),P=r.pcb_port.getWhere({source_port_id:T});return{...w,...P}});return M.length<2?null:{name:x.source_trace_id??s.getNetConnectedToId(x.source_trace_id)??"",source_trace_id:x.source_trace_id,pointsToConnect:M.map(T=>{var w;return{x:T.x,y:T.y,layer:((w=T.layers)==null?void 0:w[0])??"top"}})}}).filter(x=>x!==null),m=r.source_net.list().filter(x=>!t||(i==null?void 0:i.has(x.subcircuit_id))),g=[];for(const x of m){const M=r.source_trace.list().filter(T=>{var w;return(w=T.connected_source_net_ids)==null?void 0:w.includes(x.source_net_id)});g.push({name:x.source_net_id??s.getNetConnectedToId(x.source_net_id),pointsToConnect:M.flatMap(T=>r.pcb_port.list().filter(P=>T.connected_source_port_ids.includes(P.source_port_id)).map(P=>{var O;return{x:P.x,y:P.y,layer:((O=P.layers)==null?void 0:O[0])??"top",pcb_port_id:P.pcb_port_id}}))})}return{simpleRouteJson:{bounds:u,obstacles:l,connections:[...f,...g],layerCount:2,minTraceWidth:n},connMap:s}},$le=class extends Zx{constructor(){super(...arguments);dt(this,"pcb_group_id",null);dt(this,"subcircuit_id",null);dt(this,"_hasStartedAsyncAutorouting",!1);dt(this,"_asyncAutoroutingResult",null)}get config(){return{zodProps:yen,componentName:"Group"}}doInitialSourceRender(){const{db:e}=this.root,t=e.source_group.insert({name:this._parsedProps.name,is_subcircuit:this.isSubcircuit});this.subcircuit_id=`subcircuit_${t.source_group_id}`,this.source_group_id=t.source_group_id,e.source_group.update(t.source_group_id,{subcircuit_id:this.subcircuit_id})}doInitialSourceParentAttachment(){var n,i,a;const{db:e}=this.root;if(!this.isSubcircuit)return;const t=(a=(i=(n=this.parent)==null?void 0:n.getSubcircuit)==null?void 0:i.call(n))==null?void 0:a.subcircuit_id;t&&e.source_group.update(this.source_group_id,{parent_subcircuit_id:t})}doInitialPcbComponentRender(){var i;if((i=this.root)!=null&&i.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=e.pcb_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id,name:this._parsedProps.name,center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,pcb_component_ids:[],source_group_id:this.source_group_id});this.pcb_group_id=n.pcb_group_id}doInitialCreateTraceHintsFromProps(){var a;const{_parsedProps:e}=this,{db:t}=this.root,n=e;if(!this.isSubcircuit)return;const i=(a=n.layout)==null?void 0:a.manual_trace_hints;if(i)for(const o of i)this.add(new oVe({for:o.pcb_port_selector,offsets:o.offsets}))}doInitialSourceAddConnectivityMapKey(){if(!this.isSubcircuit)return;const{db:e}=this.root,t=this.selectAll("trace"),n=new UT({});n.addConnections(t.map(i=>{const a=e.source_trace.get(i.source_trace_id);return a?[a.source_trace_id,...a.connected_source_port_ids,...a.connected_source_net_ids]:null}).filter(i=>i!==null));for(const i of t){if(!i.source_trace_id)continue;const a=n.getNetConnectedToId(i.source_trace_id);if(!a)continue;const{name:o}=this._parsedProps;i.subcircuit_connectivity_map_key=`${o??`unnamedsubcircuit${this._renderId}`}_${a}`,e.source_trace.update(i.source_trace_id,{subcircuit_connectivity_map_key:i.subcircuit_connectivity_map_key})}}_areChildSubcircuitsRouted(){const e=this.selectAll("group").filter(t=>t.isSubcircuit);for(const t of e)if(t._shouldRouteAsync()&&!t._asyncAutoroutingResult)return!1;return!0}_shouldRouteAsync(){const e=this._getAutorouterConfig();return e.groupMode==="sequential-trace"?!1:!!(e.local&&e.groupMode==="subcircuit"||!e.local)}_hasTracesToRoute(){const e=lg("tscircuit:core:_hasTracesToRoute"),t=this.selectAll("trace");return e(`[${this.getString()}] has ${t.length} traces to route`),t.length>0}async _runEffectMakeHttpAutoroutingRequest(){var c,u,f,m;const{db:e}=this.root,t=lg("tscircuit:core:_runEffectMakeHttpAutoroutingRequest");this._parsedProps;const n=this._getAutorouterConfig(),i=n.serverUrl,a=n.serverMode,o=(g,x)=>{var M;return t("fetching",g),x.headers&&(x.headers["Tscircuit-Core-Version"]=(M=this.root)==null?void 0:M.getCoreVersion()),fetch(g,x)},s=this.root.db.toArray().filter(g=>g.type.startsWith("source_")||g.type.startsWith("pcb_"));if(a==="solve-endpoint"){if(((c=this.props.autorouter)==null?void 0:c.inputFormat)==="simplified"){const{autorouting_result:x}=await o(`${i}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_simple_route_json:sVe({db:e,minTraceWidth:((u=this.props.autorouter)==null?void 0:u.minTraceWidth)??.15,subcircuit_id:this.subcircuit_id}).simpleRouteJson,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(M=>M.json());this._asyncAutoroutingResult=x,this._markDirty("PcbTraceRender");return}const{autorouting_result:g}=await o(`${i}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_circuit_json:s,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(x=>x.json());this._asyncAutoroutingResult=g,this._markDirty("PcbTraceRender");return}const{autorouting_job:l}=await o(`${i}/autorouting/jobs/create`,{method:"POST",body:JSON.stringify({input_circuit_json:s,provider:"freerouting",autostart:!0,display_name:(f=this.root)==null?void 0:f.name,subcircuit_id:this.subcircuit_id,server_cache_enabled:n.serverCacheEnabled}),headers:{"Content-Type":"application/json"}}).then(g=>g.json());for(;;){const{autorouting_job:g}=await o(`${i}/autorouting/jobs/get`,{method:"POST",body:JSON.stringify({autorouting_job_id:l.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(x=>x.json());if(g.is_finished){const{autorouting_job_output:x}=await o(`${i}/autorouting/jobs/get_output`,{method:"POST",body:JSON.stringify({autorouting_job_id:l.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(M=>M.json());this._asyncAutoroutingResult={output_pcb_traces:x.output_pcb_traces},this._markDirty("PcbTraceRender");break}if(g.has_error)throw e.pcb_autorouting_error.insert({pcb_error_id:l.autorouting_job_id,message:((m=g.error)==null?void 0:m.message)??JSON.stringify(g.error)}),new Error(`Autorouting job failed: ${JSON.stringify(g.error)}`);await new Promise(x=>setTimeout(x,100))}}async _runLocalAutorouting(){var s,l,c,u,f;const{db:e}=this.root;this._parsedProps;const t=lg("tscircuit:core:_runLocalAutorouting");t(`[${this.getString()}] starting local autorouting`);const n=this._getAutorouterConfig(),{simpleRouteJson:i}=sVe({db:e,minTraceWidth:((s=this.props.autorouter)==null?void 0:s.minTraceWidth)??.15,subcircuit_id:this.subcircuit_id});(l=this.root)==null||l.emit("autorouting:start",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),simpleRouteJson:i});let a;n.algorithmFn?a=await n.algorithmFn(i):a=new nnn(i,{capacityDepth:(c=this.props.autorouter)==null?void 0:c.capacityDepth,targetMinCapacity:(u=this.props.autorouter)==null?void 0:u.targetMinCapacity});const o=new Promise((m,g)=>{a.on("complete",x=>{t(`[${this.getString()}] local autorouting complete`),m(x.traces)}),a.on("error",x=>{t(`[${this.getString()}] local autorouting error: ${x.error.message}`),g(x.error)})});a.on("progress",m=>{var g;(g=this.root)==null||g.emit("autorouting:progress",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),...m})}),a.start();try{const m=await o;this._asyncAutoroutingResult={output_pcb_traces:m},this._markDirty("PcbTraceRender")}catch(m){const{db:g}=this.root;throw g.pcb_autorouting_error.insert({pcb_error_id:`pcb_autorouter_error_subcircuit_${this.subcircuit_id}`,message:m instanceof Error?m.message:String(m)}),(f=this.root)==null||f.emit("autorouting:error",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),error:{message:m instanceof Error?m.message:String(m)},simpleRouteJson:i}),m}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(){var t;const e=lg("tscircuit:core:doInitialPcbTraceRender");if(this.isSubcircuit&&!((t=this.root)!=null&&t.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()}}updatePcbTraceRender(){var n;const e=lg("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;const{db:t}=this.root;if(this._asyncAutoroutingResult.output_simple_route_json){e(`[${this.getString()}] updating PCB traces from simple route json (${(n=this._asyncAutoroutingResult.output_simple_route_json.traces)==null?void 0:n.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(){const{db:e}=this.root,{traces:t}=this._asyncAutoroutingResult.output_simple_route_json;if(t)for(const n of t)e.pcb_trace.insert({subcircuit_id:this.subcircuit_id,route:n.route})}_updatePcbTraceRenderFromPcbTraces(){const{output_pcb_traces:e}=this._asyncAutoroutingResult;if(!e)return;const{db:t}=this.root;for(const n of e)if(n.type==="pcb_trace"){if(n.subcircuit_id=this.subcircuit_id,n.connection_name){const i=n.connection_name;n.source_trace_id=i}t.pcb_trace.insert(n)}for(const n of e)if(n.type!=="pcb_via"&&n.type==="pcb_trace")for(const i of n.route)i.route_type==="via"&&t.pcb_via.insert({pcb_trace_id:n.pcb_trace_id,x:i.x,y:i.y,hole_diameter:.3,outer_diameter:.6,layers:[i.from_layer,i.to_layer],from_layer:i.from_layer,to_layer:i.to_layer})}doInitialSchematicLayout(){if(!this.isSubcircuit||!this._parsedProps.schAutoLayoutEnabled)return;const{db:t}=this.root,n=this.getDescendants(),i=[];for(const s of n)if("schematic_component_id"in s){const l=t.schematic_component.get(s.schematic_component_id);if(l){const c=t.schematic_port.list().filter(u=>u.schematic_component_id===l.schematic_component_id);i.push(...c)}}const a=d1e(t.toArray()),o=m1e(a);f1e(t.toArray(),o)}_getAutorouterConfig(){const e={serverUrl:"https://registry-api.tscircuit.com",serverMode:"job",serverCacheEnabled:!0},t=this._parsedProps.autorouter??this.getInheritedProperty("autorouter");return typeof t=="object"?{local:!(t.serverUrl||t.serverMode||t.serverCacheEnabled),...e,...t}:t==="auto-local"?{local:!0,groupMode:"subcircuit"}:t==="sequential-trace"?{local:!0,groupMode:"sequential-trace"}:t==="subcircuit"?{local:!0,groupMode:"subcircuit"}:t==="auto-cloud"?{local:!1,groupMode:"subcircuit",serverUrl:e.serverUrl,serverMode:e.serverMode,serverCacheEnabled:!0}:{local:!0,groupMode:"subcircuit"}}_shouldUseTraceByTraceRouting(){return this._getAutorouterConfig().groupMode==="sequential-trace"}doInitialPcbDesignRuleChecks(){var t;if((t=this.root)!=null&&t.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;const{db:e}=this.root;if(this.isSubcircuit){const n=new Map;for(const i of this.children)if(!i.isSubcircuit&&i._parsedProps.name){const a=n.get(i._parsedProps.name)||[];a.push(i),n.set(i._parsedProps.name,a)}for(const[i,a]of n.entries())a.length>1&&e.pcb_trace_error.insert({error_type:"pcb_trace_error",message:`Multiple components found with name "${i}" in subcircuit "${this._parsedProps.name||"unnamed"}". Component names must be unique within a subcircuit.`,source_trace_id:"",pcb_trace_id:"",pcb_component_ids:a.map(o=>o.pcb_component_id).filter(Boolean),pcb_port_ids:[]})}}},inn=class extends $le{constructor(){super(...arguments);dt(this,"pcb_board_id",null)}get isSubcircuit(){return!0}get config(){return{componentName:"Board",zodProps:kHe}}get boardThickness(){const{_parsedProps:e}=this;return 1.4}get allLayers(){return["top","bottom","inner1","inner2"]}doInitialPcbBoardAutoSize(){var g;if((g=this.root)!=null&&g.pcbDisabled||!this.pcb_board_id)return;const{db:e}=this.root,{_parsedProps:t}=this;if(t.width&&t.height)return;let n=1/0,i=1/0,a=-1/0,o=-1/0;const s=e.pcb_component.list();let l=!1;for(const x of s){const{width:M,height:T,center:w}=x;M===0||T===0||(l=!0,n=Math.min(n,w.x-M/2),i=Math.min(i,w.y-T/2),a=Math.max(a,w.x+M/2),o=Math.max(o,w.y+T/2))}const c=2,u=l?a-n+c*2:0,f=l?o-i+c*2:0,m={x:l?(n+a)/2+(t.outlineOffsetX??0):t.outlineOffsetX??0,y:l?(i+o)/2+(t.outlineOffsetY??0):t.outlineOffsetY??0};e.pcb_board.update(this.pcb_board_id,{width:u,height:f,center:m})}doInitialPcbComponentRender(){var o,s;if((o=this.root)!=null&&o.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this;let n=t.width??0,i=t.height??0;if(t.outline){const l=t.outline.map(x=>x.x),c=t.outline.map(x=>x.y),u=Math.min(...l),f=Math.max(...l),m=Math.min(...c),g=Math.max(...c);n=f-u,i=g-m}const a=e.pcb_board.insert({center:{x:(t.pcbX??0)+(t.outlineOffsetX??0),y:(t.pcbY??0)+(t.outlineOffsetY??0)},thickness:this.boardThickness,num_layers:this.allLayers.length,width:n,height:i,outline:(s=t.outline)==null?void 0:s.map(l=>({x:l.x+(t.outlineOffsetX??0),y:l.y+(t.outlineOffsetY??0)}))});this.pcb_board_id=a.pcb_board_id}removePcbComponentRender(){const{db:e}=this.root;this.pcb_board_id&&(e.pcb_board.delete(this.pcb_board_id),this.pcb_board_id=null)}_computePcbGlobalTransformBeforeLayout(){return w9()}doInitialPcbDesignRuleChecks(){var n;if((n=this.root)!=null&&n.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;const{db:e}=this.root;super.doInitialPcbDesignRuleChecks();const t=Q1e(e.toArray());for(const i of t)e.pcb_trace_error.insert(i)}},ann=new Proxy({},{get:(r,e)=>e}),fA=ann,onn=class extends Zx{get config(){return{componentName:"Capacitor",schematicSymbolName:this.props.polarized?"capacitor_polarized":this.props.symbolName??"capacitor",zodProps:Cen,sourceFtype:fA.simple_capacitor}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){const r=`${e8(this._parsedProps.capacitance)}F`;return this._parsedProps.schShowRatings&&this._parsedProps.maxVoltageRating?`${r}/${e8(this._parsedProps.maxVoltageRating)}V`:r}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.decouplingFor,this.props.decouplingTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.decouplingFor&&this.props.decouplingTo&&(this.add(new x7({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.decouplingFor})),this.add(new x7({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.decouplingTo})))}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({ftype:"simple_capacitor",name:e.name,manufacturer_part_number:e.manufacturerPartNumber??e.mfn,supplier_part_numbers:e.supplierPartNumbers,capacitance:e.capacitance,max_voltage_rating:e.maxVoltageRating,max_decoupling_trace_length:e.maxDecouplingTraceLength,display_capacitance:this._getSchematicSymbolDisplayValue()});this.source_component_id=t.source_component_id}},lVe=class extends Zx{constructor(){super(...arguments);dt(this,"schematicBoxDimensions",null)}get config(){return{componentName:"Chip",zodProps:IHe,shouldRenderAsSchematicBox:!0}}doInitialSchematicComponentRender(){const{_parsedProps:e}=this;(e==null?void 0:e.noSchematicRepresentation)!==!0&&super.doInitialSchematicComponentRender()}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_chip",name:t.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers});this.source_component_id=n.source_component_id}doInitialPcbComponentRender(){var i;if((i=this.root)!=null&&i.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=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});this.pcb_component_id=n.pcb_component_id}doInitialCreateTracesFromProps(){const{_parsedProps:e}=this;if(e.externallyConnectedPins)for(const[t,n]of e.externallyConnectedPins)this.add(new x7({from:`${this.getSubcircuitSelector()} > port.${t}`,to:`${this.getSubcircuitSelector()} > port.${n}`}));this._createTracesFromConnectionsProp()}},snn=class extends Zx{constructor(){super(...arguments);dt(this,"pos",this.portMap.pin1);dt(this,"anode",this.portMap.pin1);dt(this,"neg",this.portMap.pin2);dt(this,"cathode",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"diode",componentName:"Diode",zodProps:etn,sourceFtype:"simple_diode"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}},lnn=class extends Zx{constructor(){super(...arguments);dt(this,"schematicDimensions",null)}get config(){return{componentName:"Jumper",zodProps:ben,shouldRenderAsSchematicBox:!0}}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_chip",name:t.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers});this.source_component_id=n.source_component_id}doInitialPcbComponentRender(){var i;if((i=this.root)!=null&&i.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=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});this.pcb_component_id=n.pcb_component_id}},cnn=class extends Zx{constructor(){super(...arguments);dt(this,"pos",this.portMap.pin1);dt(this,"anode",this.portMap.pin1);dt(this,"neg",this.portMap.pin2);dt(this,"cathode",this.portMap.pin2)}get config(){return{componentName:"Led",schematicSymbolName:this.props.symbolName??"led",zodProps:ttn,sourceFtype:"simple_diode"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}},unn=class extends Zx{constructor(){super(...arguments);dt(this,"pos",this.portMap.pin1);dt(this,"positive",this.portMap.pin1);dt(this,"neg",this.portMap.pin2);dt(this,"negative",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"power_factor_meter_horz",componentName:"PowerSource",zodProps:stn,sourceFtype:"simple_power_source"}}initPorts(){this.add(new OS({name:"pin1",pinNumber:1,aliases:["positive","pos"]})),this.add(new OS({name:"pin2",pinNumber:2,aliases:["negative","neg"]}))}},fnn=class extends Zx{get config(){return{componentName:"Resistor",schematicSymbolName:this.props.symbolName??"boxresistor",zodProps:Een,sourceFtype:"simple_resistor"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return`${e8(this._parsedProps.resistance)}Ω`}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.pullupFor,this.props.pullupTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.pullupFor&&this.props.pullupTo&&(this.add(new x7({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pullupFor})),this.add(new x7({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pullupTo})))}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({ftype:"simple_resistor",name:e.name,manufacturer_part_number:e.manufacturerPartNumber??e.mfn,supplier_part_numbers:e.supplierPartNumbers,resistance:e.resistance,display_resistance:this._getSchematicSymbolDisplayValue()});this.source_component_id=t.source_component_id}},dnn=["leftedge","rightedge","topedge","bottomedge","center"],pnn=class extends X_{get config(){return{componentName:"Constraint",zodProps:Den}}constructor(r){if(super(r),("xdist"in r||"ydist"in r)&&!("edgeToEdge"in r)&&!("centerToCenter"in r))throw new Error(`edgeToEdge, centerToCenter must be set for xDist or yDist for ${this}`);if("for"in r&&r.for.length<2)throw new Error(`"for" must have at least two selectors for ${this}`)}_getAllReferencedComponents(){const r=[],e=this.getPrimitiveContainer();function t(n){const i=n.split(" ").pop(),a=dnn.includes(i)?i:void 0,o=a?n.replace(` ${a}`,""):n,s=e.selectOne(o,{pcbPrimitive:!0});s&&r.push({selector:n,component:s,componentSelector:o,edge:a})}for(const n of["left","right","top","bottom"])n in this._parsedProps&&t(this._parsedProps[n]);if("for"in this._parsedProps)for(const n of this._parsedProps.for)t(n);return{componentsWithSelectors:r}}},hnn=class extends X_{constructor(){super(...arguments);dt(this,"fabrication_note_path_id",null)}get config(){return{componentName:"FabricationNotePath",zodProps:itn}}doInitialPcbPrimitiveRender(){var s,l;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:e}=this.root,t=this.getSubcircuit(),{_parsedProps:n}=this,i=n.layer??"top";if(i!=="top"&&i!=="bottom")throw new Error(`Invalid layer "${i}" for SilkscreenPath. Must be "top" or "bottom".`);const a=this._computePcbGlobalTransformBeforeLayout(),o=e.pcb_fabrication_note_path.insert({pcb_component_id:(l=this.parent)==null?void 0:l.pcb_component_id,layer:i,color:n.color,route:n.route.map(c=>{const u=Fr(a,{x:c.x,y:c.y});return{...c,x:u.x,y:u.y}}),stroke_width:n.strokeWidth??.1,subcircuit_id:(t==null?void 0:t.subcircuit_id)??void 0});this.fabrication_note_path_id=o.pcb_fabrication_note_path_id}},mnn=class extends X_{get config(){return{componentName:"FabricationNoteText",zodProps:rtn}}doInitialPcbPrimitiveRender(){var i,a;if((i=this.root)!=null&&i.pcbDisabled)return;const{db:r}=this.root,{_parsedProps:e}=this,t=this.getPrimitiveContainer(),n=this.getSubcircuit();r.pcb_fabrication_note_text.insert({anchor_alignment:e.anchorAlignment,anchor_position:{x:e.pcbX??0,y:e.pcbY??0},font:e.font??"tscircuit2024",font_size:e.fontSize??1,layer:"top",color:e.color,text:e.text??"",pcb_component_id:t.pcb_component_id,subcircuit_id:(n==null?void 0:n.subcircuit_id)??void 0,pcb_group_id:((a=this.getGroup())==null?void 0:a.pcb_group_id)??void 0})}},vnn=class extends $le{constructor(r){super({...r,subcircuit:!0})}},ynn=class extends X_{constructor(){super(...arguments);dt(this,"source_net_alias_id")}get config(){return{componentName:"NetAlias",zodProps:$en}}doInitialSchematicComponentRender(){var a;if((a=this.root)!=null&&a.schematicDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n={x:t.schX??0,y:t.schY??0},i=e.schematic_net_label.insert({text:t.net,source_net_id:t.net,anchor_position:n,center:n,anchor_side:"bottom"});this.source_net_alias_id=i.source_net_id}},gnn=class extends X_{constructor(){super(...arguments);dt(this,"pcb_silkscreen_circle_id",null);dt(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenCircle",zodProps:dtn}}doInitialPcbPrimitiveRender(){var s,l,c;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,{maybeFlipLayer:n}=this._getPcbPrimitiveFlippedHelpers(),i=n(t.layer??"top");if(i!=="top"&&i!=="bottom")throw new Error(`Invalid layer "${i}" for SilkscreenCircle. Must be "top" or "bottom".`);this._computePcbGlobalTransformBeforeLayout();const a=this.getSubcircuit(),o=e.pcb_silkscreen_circle.insert({pcb_component_id:(l=this.parent)==null?void 0:l.pcb_component_id,layer:i,center:{x:t.pcbX??0,y:t.pcbY??0},radius:t.radius,subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((c=this.getGroup())==null?void 0:c.pcb_group_id)??void 0,stroke_width:t.strokeWidth??.1});this.pcb_silkscreen_circle_id=o.pcb_silkscreen_circle_id}getPcbSize(){const{_parsedProps:e}=this,t=e.radius*2;return{width:t,height:t}}},_nn=class extends X_{constructor(){super(...arguments);dt(this,"pcb_silkscreen_rect_id",null);dt(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenRect",zodProps:ftn}}doInitialPcbPrimitiveRender(){var s,l,c;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,{maybeFlipLayer:n}=this._getPcbPrimitiveFlippedHelpers(),i=n(t.layer??"top");if(i!=="top"&&i!=="bottom")throw new Error(`Invalid layer "${i}" for SilkscreenRect. Must be "top" or "bottom".`);const a=this.getSubcircuit(),o=e.pcb_silkscreen_rect.insert({pcb_component_id:(l=this.parent)==null?void 0:l.pcb_component_id,layer:i,center:{x:t.pcbX??0,y:t.pcbY??0},width:t.width,height:t.height,subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((c=this==null?void 0:this.getGroup())==null?void 0:c.pcb_group_id)??void 0,stroke_width:t.strokeWidth??.1});this.pcb_silkscreen_rect_id=o.pcb_silkscreen_rect_id}getPcbSize(){const{_parsedProps:e}=this;return{width:e.width,height:e.height}}},xnn=class extends X_{constructor(){super(...arguments);dt(this,"pcb_silkscreen_line_id",null);dt(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenLine",zodProps:utn}}doInitialPcbPrimitiveRender(){var s,l,c;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,{maybeFlipLayer:n}=this._getPcbPrimitiveFlippedHelpers(),i=n(t.layer??"top");if(i!=="top"&&i!=="bottom")throw new Error(`Invalid layer "${i}" for SilkscreenLine. Must be "top" or "bottom".`);const a=this.getSubcircuit(),o=e.pcb_silkscreen_line.insert({pcb_component_id:(l=this.parent)==null?void 0:l.pcb_component_id,layer:i,x1:t.x1,y1:t.y1,x2:t.x2,y2:t.y2,stroke_width:t.strokeWidth??.1,subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((c=a==null?void 0:a.getGroup())==null?void 0:c.pcb_group_id)??void 0});this.pcb_silkscreen_line_id=o.pcb_silkscreen_line_id}getPcbSize(){const{_parsedProps:e}=this,t=Math.abs(e.x2-e.x1),n=Math.abs(e.y2-e.y1);return{width:t,height:n}}},bnn=class extends X_{constructor(){super(...arguments);dt(this,"pcb_via_id",null);dt(this,"matchedPort",null);dt(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Via",zodProps:atn}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){const{_parsedProps:e}=this;return{width:e.outerDiameter,height:e.outerDiameter}}_getPcbCircuitJsonBounds(){const{db:e}=this.root,t=e.pcb_via.get(this.pcb_via_id),n=this.getPcbSize();return{center:{x:t.x,y:t.y},bounds:{left:t.x-n.width/2,top:t.y-n.height/2,right:t.x+n.width/2,bottom:t.y+n.height/2},width:n.width,height:n.height}}_setPositionFromLayout(e){const{db:t}=this.root;t.pcb_via.update(this.pcb_via_id,{x:e.x,y:e.y})}doInitialPcbPrimitiveRender(){var o,s;if((o=this.root)!=null&&o.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=this._getGlobalPcbPositionBeforeLayout(),i=this.getSubcircuit(),a=e.pcb_via.insert({x:n.x,y:n.y,hole_diameter:t.holeDiameter,outer_diameter:t.outerDiameter,layers:["bottom","top"],from_layer:t.fromLayer||"bottom",to_layer:t.toLayer||"top",subcircuit_id:(i==null?void 0:i.subcircuit_id)??void 0,pcb_group_id:((s=this.getGroup())==null?void 0:s.pcb_group_id)??void 0});this.pcb_via_id=a.pcb_via_id}},Snn=class extends Zx{get config(){return{componentName:"Battery",schematicSymbolName:this.props.symbolName??"battery",zodProps:Gen,sourceFtype:"simple_power_source"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({name:e.name,ftype:"simple_power_source",capacity:e.capacity,supplier_part_numbers:e.supplierPartNumbers});this.source_component_id=t.source_component_id}},Enn=class extends Zx{get config(){return{componentName:"PinHeader",zodProps:qen,shouldRenderAsSchematicBox:!0}}_getImpliedFootprintString(){var i;const r=this._parsedProps.pinCount??((i=this._parsedProps.pinLabels)==null?void 0:i.length)??0,e=this._parsedProps.holeDiameter,t=this._parsedProps.platedDiameter,n=this._parsedProps.pitch;return r>0&&n?!e&&!t?`pinrow${r}_p${n}`:`pinrow${r}_p${n}_id${e}_od${t}`:null}initPorts(){var e,t;const r=this._parsedProps.pinCount??((e=this._parsedProps.pinLabels)==null?void 0:e.length)??1;for(let n=1;n<=r;n++)this.add(new OS({name:`pin${n}`,pinNumber:n,aliases:[(t=this._parsedProps.pinLabels)==null?void 0:t[n-1]].filter(Boolean)}))}_getSchematicPortArrangement(){const r=this._parsedProps.pinCount??1,e=this._parsedProps.facingDirection??"right";return{leftSize:e==="left"?r:0,rightSize:e==="right"?r:0}}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({ftype:"simple_pin_header",name:e.name,supplier_part_numbers:e.supplierPartNumbers,pin_count:e.pinCount,gender:e.gender});this.source_component_id=t.source_component_id}};function wnn(r){switch(r){case"two_ground_pins":return"crystal_4pin";case"ground_pin":return"resonator";case"no_ground":return"crystal";default:return"crystal"}}var Tnn=class extends Zx{get config(){return{componentName:"Resonator",schematicSymbolName:this.props.symbolName??wnn(this.props.pinVariant),zodProps:Men,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({ftype:"simple_resonator",name:e.name,frequency:e.frequency,load_capacitance:e.loadCapacitance,supplier_part_numbers:e.supplierPartNumbers,pin_variant:e.pinVariant||"no_ground"});this.source_component_id=t.source_component_id}},Mnn=class extends Zx{get config(){return{componentName:"Inductor",schematicSymbolName:this.props.symbolName??"inductor",zodProps:Zen,sourceFtype:fA.simple_inductor}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({name:e.name,ftype:fA.simple_inductor,inductance:e.inductance,supplier_part_numbers:e.supplierPartNumbers});this.source_component_id=t.source_component_id}};function Cnn(r){switch(r){case"three_pin":return"potentiometer3";case"two_pin":return"potentiometer2";default:return"potentiometer2"}}var Rnn=class extends Zx{get config(){return{componentName:"Potentiometer",schematicSymbolName:this.props.symbolName??Cnn(this.props.pinVariant),zodProps:wen,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({ftype:"simple_potentiometer",name:e.name,max_resistance:e.maxResistance,pin_variant:e.pinVariant||"two_pin"});this.source_component_id=t.source_component_id}},Ann=class extends Zx{get config(){return{componentName:"PushButton",schematicSymbolName:this.props.symbolName??"push_button_normally_open_momentary",zodProps:Yen,sourceFtype:fA.simple_push_button}}get defaultInternallyConnectedPinNames(){return[["pin1","pin4"],["pin2","pin3"]]}initPorts(){super.initPorts({pinCount:4,additionalAliases:{pin1:["side1"],pin3:["side2"]}})}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({name:e.name,ftype:fA.simple_push_button,supplier_part_numbers:e.supplierPartNumbers});this.source_component_id=t.source_component_id}},Pnn=class extends Zx{get config(){return{schematicSymbolName:this.props.symbolName??(this.props.pinVariant==="four_pin"?"crystal_4pin":"crystal"),componentName:"Crystal",zodProps:Ten,sourceFtype:"simple_crystal"}}initPorts(){const r=this.props.pinVariant==="four_pin"?{pin1:["left1","1"],pin2:["top1","2","gnd1"],pin3:["right1","3"],pin4:["bottom1","4","gnd2"]}:{pin1:["pos","left"],pin2:["neg","right"]};super.initPorts({additionalAliases:r})}_getSchematicSymbolDisplayValue(){return`${e8(this._parsedProps.frequency)}Hz`}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({name:e.name,ftype:"simple_crystal",frequency:e.frequency,load_capacitance:e.loadCapacitance,pin_variant:e.pinVariant||"two_pin"});this.source_component_id=t.source_component_id}},Nnn=class extends Zx{constructor(){super(...arguments);dt(this,"emitter",this.portMap.pin1);dt(this,"collector",this.portMap.pin2);dt(this,"base",this.portMap.pin3)}get config(){return{componentName:"Transistor",schematicSymbolName:this.props.type==="npn"?"npn_bipolar_transistor":"pnp_bipolar_transistor",zodProps:Xen,sourceFtype:"simple_transistor",shouldRenderAsSchematicBox:!1}}initPorts(){super.initPorts({pinCount:3,additionalAliases:{pin1:["emitter","e"],pin2:["collector","c"],pin3:["base","b"]}})}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_transistor",name:t.name,transistor_type:t.type});this.source_component_id=n.source_component_id}},Dnn=class extends Zx{get config(){const r=this.props.mosfetMode==="depletion"?"d":"e";return{componentName:"Mosfet",schematicSymbolName:`${this.props.channelType}_channel_${r}_mosfet_transistor`,zodProps:Wen,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({ftype:"simple_mosfet",name:e.name,mosfet_mode:e.mosfetMode,channel_type:e.channelType});this.source_component_id=t.source_component_id}},Lnn=class extends Zx{_getSwitchType(){const{spst:r,spdt:e,dpst:t,dpdt:n,type:i}=this._parsedProps??{};return n?"dpdt":r?"spst":e?"spdt":t?"dpst":i??"spst"}get config(){const r=this._getSwitchType(),{isNormallyClosed:e}=this._parsedProps??{};return{componentName:"Switch",schematicSymbolName:{spst:e?"spst_normally_closed_switch":"SPST_switch",spdt:e?"spdt_normally_closed_switch":"SPDT_switch",dpst:e?"dpst_normally_closed_switch":"dpst_switch",dpdt:e?"dpdt_normally_closed_switch":"dpdt_switch"}[r]??"SPST_switch",zodProps:ntn,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({ftype:"simple_switch",name:e.name,switch_type:e.type,is_normally_closed:e.isNormallyClosed??!1});this.source_component_id=t.source_component_id}};new Proxy({},{get:(r,e)=>{const t=(...n)=>(n[0],new Proxy({},{get:(i,a)=>`.${e} > .${a}`}));return new Proxy(t,{get:(n,i)=>e==="net"?`net.${i}`:e==="subcircuit"?new Proxy({},{get:(a,o)=>new Proxy({},{get:(s,l)=>`subcircuit.${i} > .${o} > .${l}`})}):`.${e} > .${i}`,apply:(n,i,a)=>new Proxy({},{get:(o,s)=>`.${e} > .${s}`})})}}),qHe(VHe),qHe({Bug:lVe});const cVe=r=>`hsl(${Sb.indexOf(r)*137.5%360}, 70%, 50%)`,Onn=({phaseTimings:r})=>{if(!r)return null;const e=Object.values(r).reduce((t,n)=>t+n,0);return ft.jsxs("div",{className:"rf-space-y-2 rf-w-full rf-px-4",children:[ft.jsx("div",{className:"rf-relative rf-h-8 rf-flex rf-rounded-sm",children:Sb.map(t=>{const n=r[t]||0,i=n/e*100;return ft.jsx("div",{className:"rf-group/bar rf-relative rf-overflow-visible",style:{width:`${i}%`,backgroundColor:cVe(t)},children:ft.jsxs("div",{className:"rf-opacity-0 group-hover/bar:rf-opacity-100 rf-transition-opacity rf-absolute rf-bottom-full rf-left-1/2 rf-transform -rf-translate-x-1/2 rf-mb-2 rf-px-2 rf-py-1 rf-text-xs rf-whitespace-nowrap rf-rounded rf-bg-gray-900 rf-text-white rf-pointer-events-none",children:[t,": ",n.toFixed(1),"ms"]})},t)})}),ft.jsxs("div",{className:"rf-text-xs rf-text-gray-500",children:["Total: ",e.toFixed(2),"ms"]})]})},znn=({renderLog:r})=>{const[e,t]=wt.useState("chronological");if(!r)return ft.jsx("div",{className:"rf-p-4 rf-bg-gray-100 rf-rounded-md",children:"No render log, make sure this tab is open when you render (TODO add a rerender button here)"});const n=Object.entries((r==null?void 0:r.phaseTimings)??{});e==="chronological"?n.sort((a,o)=>Sb.indexOf(a[0])-Sb.indexOf(o[0])):n.sort((a,o)=>o[1]-a[1]);const i=n.reduce((a,[o,s])=>a+s,0);return ft.jsxs("div",{className:"rf-bg-white",children:[ft.jsxs("div",{className:"rf-flex rf-justify-between rf-items-center",children:[ft.jsx("div",{children:"Render Logs"}),ft.jsxs("div",{className:"rf-mb-4 rf-pr-2 rf-flex rf-text-xs rf-items-center",children:[ft.jsx("div",{className:"rf-mr-2",children:"Sort by:"}),ft.jsxs("select",{value:e,onChange:a=>t(a.target.value),className:"rf-px-2 rf-py-1 rf-border rf-rounded rf-text-xs",children:[ft.jsx("option",{value:"chronological",children:"Phase Order"}),ft.jsx("option",{value:"longest",children:"Duration"})]})]})]}),ft.jsx(Onn,{phaseTimings:r.phaseTimings}),ft.jsxs("table",{className:"rf-w-full rf-text-xs",children:[ft.jsx("thead",{children:ft.jsxs("tr",{children:[ft.jsx("th",{className:"rf-text-left rf-p-2",children:"Phase Order"}),ft.jsx("th",{className:"rf-text-left rf-p-2",children:"Phase"}),ft.jsx("th",{className:"rf-text-left rf-p-2",children:"Duration (ms)"})]})}),ft.jsx("tbody",{children:n.map(([a,o])=>ft.jsxs("tr",{children:[ft.jsx("td",{className:"rf-p-2",children:Sb.indexOf(a)}),ft.jsx("td",{className:"rf-p-2",children:a}),ft.jsx("td",{className:"rf-p-2",children:ft.jsx("div",{className:"rf-w-8",children:ft.jsx("div",{className:"rf-h-2 rf-rounded-sm",style:{backgroundColor:cVe(a),width:`${o/i*100}%`}})})}),ft.jsx("td",{className:"rf-p-2",children:ft.jsxs("div",{className:"rf-flex w-full",children:[ft.jsxs("span",{className:"rf-flex-grow",children:[o,"ms"]}),ft.jsxs("span",{className:"rf-text-gray-500 rf-pr-2",children:[(o/i*100).toFixed(1),"%"]})]})})]},a))})]})]})},Unn="0.0.315",knn=["assembly","bom","circuit_json","errors","render_log"],Inn=({code:r,onRunClicked:e=void 0,errorMessage:t,circuitJson:n,autoroutingGraphics:i,showRightHeaderContent:a=!0,showCodeTab:o=!1,codeTabContent:s,showJsonTab:l=!0,showRenderLogTab:c=!0,onActiveTabChange:u,renderLog:f,showImportAndFormatButtons:m=!0,className:g,headerClassName:x,leftHeaderContent:M,readOnly:T,isStreaming:w,autoroutingLog:P,onReportAutoroutingLog:O,isRunningCode:F,hasCodeChangedSinceLastRun:$,onEditEvent:Z,editEvents:Q,defaultActiveTab:ee,autoRotate3dViewerDisabled:ie,showSchematicDebugGrid:J=!1,showToggleFullScreen:de=!0,defaultToFullScreen:he=!1})=>{var Ie;K$t();const[_e,Ce]=wt.useState(ee??"pcb"),[De,Ee]=wt.useState(he),Pe=wt.useCallback(ze=>{Ce(ze),u==null||u(ze)},[u]),Te=()=>{Ee(!De)};return wt.useEffect(()=>{t&&Pe("errors")},[t]),wt.useEffect(()=>{(_e==="code"||_e==="errors")&&n&&!t&&Pe(ee??"pcb")},[n]),ft.jsx("div",{className:jy("flex flex-col relative rf-overflow-x-hidden",g),children:ft.jsx("div",{className:jy("rf-md:sticky rf-md:top-2",De&&"rf-fixed rf-top-0 rf-left-0 rf-w-full rf-bg-white"),children:ft.jsxs(pYe,{value:_e,onValueChange:Pe,className:"rf-flex-grow rf-flex rf-flex-col",children:[ft.jsxs("div",{className:jy("rf-flex rf-items-center rf-gap-2 rf-p-2 rf-pb-0",x),children:[M,M&&ft.jsx("div",{className:"rf-flex-grow"}),!M&&F&&ft.jsx(LLe,{className:"rf-w-4 rf-h-4 rf-animate-spin"}),!M&&ft.jsx("div",{className:"rf-flex-grow"}),f&&f.progress!==1&&ft.jsxs("div",{className:"rf-flex rf-items-center rf-gap-2",children:[f.lastRenderEvent&&ft.jsx("div",{className:"rf-text-xs rf-text-gray-500",children:(Ie=f.lastRenderEvent)==null?void 0:Ie.type.split("renderable:renderLifecycle:")[1].split(":")[0]}),ft.jsx("div",{className:"rf-w-4 rf-h-4 rf-bg-blue-500 rf-opacity-50 rf-rounded-full rf-text-white",children:ft.jsx(LLe,{className:"rf-w-4 rf-h-4 rf-animate-spin"})}),ft.jsxs("div",{className:"rf-text-xs rf-font-bold rf-text-gray-700 rf-tabular-nums",children:[((f.progress??0)*100).toFixed(1),"%"]})]}),a&&ft.jsxs(Kue,{children:[o&&ft.jsx(O7,{value:"code",children:"Code"}),ft.jsxs(O7,{value:"pcb",className:"rf-whitespace-nowrap",children:[n&&ft.jsx("span",{className:jy("rf-inline-flex rf-items-center rf-justify-center rf-w-2 rf-h-2 rf-mr-1 rf-text-xs rf-font-bold rf-text-white rf-rounded-full",$?"rf-bg-gray-500":"rf-bg-blue-500")}),"PCB"]}),ft.jsxs(O7,{value:"schematic",className:"rf-whitespace-nowrap",children:[n&&ft.jsx("span",{className:jy("rf-inline-flex rf-items-center rf-justify-center rf-w-2 rf-h-2 rf-mr-1 rf-text-xs rf-font-bold rf-text-white rf-rounded-full",$?"rf-bg-gray-500":"rf-bg-blue-500")}),"Schematic"]}),ft.jsxs(O7,{value:"cad",children:[n&&ft.jsx("span",{className:jy("inline-flex items-center justify-center w-2 h-2 mr-1 text-xs font-bold text-white rounded-full",$?"rf-bg-gray-500":"rf-bg-blue-500")}),"3D"]}),!["pcb","cad","schematic"].includes(_e)&&ft.jsx(O7,{value:_e,children:Que(_e)}),ft.jsxs(Vze,{children:[ft.jsx(Gze,{asChild:!0,children:ft.jsxs("div",{className:"rf-whitespace-nowrap rf-p-2 rf-mr-1 rf-cursor-pointer rf-relative",children:[ft.jsx(CUt,{className:"rf-w-4 rf-h-4"}),t&&ft.jsx("span",{className:"rf-inline-flex rf-absolute rf-top-[6px] rf-right-[4px] rf-items-center rf-justify-center rf-w-1 rf-h-1 rf-ml-2 rf-text-[8px] rf-font-bold rf-text-white rf-bg-red-500 rf-rounded-full"})]})}),ft.jsxs(iae,{className:"rf-*:text-xs",children:[knn.map(ze=>ft.jsxs(ok,{onSelect:()=>Pe(ze),children:[_e!==ze&&ft.jsx(DLe,{className:"rf-w-3 rf-h-3 rf-opacity-30"}),_e===ze&&ft.jsx(NLe,{className:"rf-w-3 rf-h-3"}),ft.jsx("div",{className:"rf-pr-2",children:Que(ze)}),ze==="errors"&&t&&ft.jsx("span",{className:"rf-inline-flex rf-items-center rf-justify-center rf-w-3 rf-h-3 rf-ml-2 rf-text-[8px] rf-font-bold rf-text-white rf-bg-red-500 rf-rounded-full",children:"1"})]},ze)),ft.jsx(ok,{disabled:!0,className:"rf-opacity-60 rf-cursor-default rf-select-none",children:ft.jsxs("div",{className:"rf-pr-2 rf-text-xs rf-text-gray-500",children:["@tscircuit/runframe@",Unn.split(".").map((ze,He)=>He===2?parseInt(ze)+1:ze).join(".")]})})]})]})]}),de&&ft.jsx(R8,{onClick:Te,variant:"ghost",children:De?ft.jsx(AUt,{size:16}):ft.jsx(RUt,{size:16})})]}),o&&ft.jsx(o4,{value:"code",className:"rf-flex-grow rf-overflow-hidden",children:ft.jsx("div",{className:"rf-h-full",children:s})}),ft.jsx(o4,{value:"pcb",children:ft.jsx("div",{className:jy("rf-overflow-hidden",De?"rf-h-[calc(100vh-52px)]":"rf-h-[620px]"),children:ft.jsx(Rw,{fallbackRender:({error:ze})=>ft.jsx("div",{className:"rf-mt-4 rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200",children:ft.jsxs("div",{className:"rf-p-4",children:[ft.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-3",children:"Error loading PCB viewer"}),ft.jsx("p",{className:"rf-text-xs rf-font-mono rf-whitespace-pre-wrap rf-text-red-600 rf-mt-2",children:(ze==null?void 0:ze.message)||"An unknown error occurred"})]})}),children:n?ft.jsx(Z$t,{focusOnHover:!1,circuitJson:n,debugGraphics:i,containerClassName:jy("rf-h-full rf-w-full",De?"rf-min-h-[calc(100vh-240px)]":"rf-min-h-[620px]"),onEditEventsChanged:ze=>{Z&&ze.forEach(He=>Z(He))}}):ft.jsx(g7,{onRunClicked:e})})})}),ft.jsx(o4,{value:"assembly",children:ft.jsx("div",{className:jy("rf-overflow-auto",De?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:ft.jsx(Rw,{fallback:ft.jsx("div",{children:"Error loading Assembly"}),children:n?ft.jsx(q$t,{circuitJson:n,containerStyle:{height:"100%"},editingEnabled:!0,debugGrid:!0}):ft.jsx(g7,{onRunClicked:e})})})}),ft.jsx(o4,{value:"schematic",children:ft.jsx("div",{className:jy("rf-overflow-auto",De?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:ft.jsx(Rw,{fallbackRender:({error:ze})=>ft.jsx("div",{className:"rf-mt-4 rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200",children:ft.jsxs("div",{className:"rf-p-4",children:[ft.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-3",children:"Error loading Schematic"}),ft.jsx("p",{className:"rf-text-xs rf-font-mono rf-whitespace-pre-wrap rf-text-red-600 rf-mt-2",children:(ze==null?void 0:ze.message)||"An unknown error occurred"})]})}),children:n?ft.jsx(H$t,{circuitJson:n,containerStyle:{height:"100%"},editingEnabled:!0,onEditEvent:ze=>Z==null?void 0:Z(ze),editEvents:Q,debugGrid:J}):ft.jsx(g7,{onRunClicked:e})})})}),ft.jsx(o4,{value:"cad",children:ft.jsx("div",{className:jy("rf-overflow-auto",De?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:ft.jsx(Rw,{FallbackComponent:hUt,children:n?ft.jsx(JNt,{soup:n,autoRotateDisabled:ie}):ft.jsx(g7,{onRunClicked:e})})})}),ft.jsx(o4,{value:"bom",children:ft.jsx("div",{className:jy("rf-overflow-auto",De?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:ft.jsx(Rw,{fallbackRender:({error:ze})=>ft.jsx("div",{className:"rf-mt-4 rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200",children:ft.jsxs("div",{className:"rf-p-4",children:[ft.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-3",children:"Error loading Bill of Materials"}),ft.jsx("p",{className:"rf-text-xs rf-font-mono rf-whitespace-pre-wrap rf-text-red-600 rf-mt-2",children:(ze==null?void 0:ze.message)||"An unknown error occurred"})]})}),children:n?ft.jsx(W$t,{circuitJson:n}):ft.jsx(g7,{onRunClicked:e})})})}),ft.jsx(o4,{value:"circuit_json",children:ft.jsx("div",{className:jy("rf-overflow-auto",De?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:ft.jsx(Rw,{fallback:ft.jsx("div",{children:"Error loading JSON viewer"}),children:n?ft.jsx(Y$t,{elements:n}):ft.jsx(g7,{onRunClicked:e})})})}),ft.jsx(o4,{value:"errors",children:ft.jsx("div",{className:jy("rf-overflow-auto",De?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:n||t?ft.jsx(MBt,{code:r,errorMessage:t,autoroutingLog:P,onReportAutoroutingLog:O}):ft.jsx(g7,{onRunClicked:e})})}),c&&ft.jsx(o4,{value:"render_log",children:ft.jsx(znn,{renderLog:f})})]})})})};_ue.createRoot(document.getElementById("root")).render(ft.jsx(Inn,{defaultActiveTab:"cad",autoRotate3dViewerDisabled:!0,showRightHeaderContent:!1,circuitJson:window.CIRCUIT_JSON||{},...window.CIRCUIT_JSON_PREVIEW_PROPS||{}}))});