tscircuit 0.0.1085 → 0.0.1086-libonly

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -595,10 +595,10 @@ ${pin._facingDirection??getPinDirection2(pin,chip)}`,x:pin.x,y:pin.y,color:getCo
595
595
  `)},SpiceNetlist=class{constructor(title="Circuit Netlist"){__publicField(this,"title");__publicField(this,"components");__publicField(this,"nodes");__publicField(this,"controls");__publicField(this,"subcircuits");__publicField(this,"models");__publicField(this,"tranCommand");__publicField(this,"printStatements");this.title=title,this.components=[],this.nodes=new Set,this.controls=[],this.subcircuits=[],this.models=new Map,this.tranCommand=null,this.printStatements=[]}addComponent(component){this.components.push(component);for(let node of component.nodes)this.nodes.add(node)}addSubcircuit(subcircuit){this.subcircuits.find(s4=>s4.name===subcircuit.name)||this.subcircuits.push(subcircuit)}toSpiceString(){return convertSpiceNetlistToString(this)}},SpiceComponent=class{constructor(name,command,nodes){__publicField(this,"name");__publicField(this,"command");__publicField(this,"nodes");this.name=name,this.command=command,this.nodes=nodes}toSpiceString(){return this.command.toSpiceString()}},ResistorCommand=class{constructor(props){__publicField(this,"commandName","resistor");__publicField(this,"props");this.props=props}toSpiceString(){let{name,positiveNode,negativeNode,model,value}=this.props,spiceString=`R${name} ${positiveNode} ${negativeNode}`;return model&&(spiceString+=` ${model}`),spiceString+=` ${value}`,spiceString}},CapacitorCommand=class{constructor(props){__publicField(this,"commandName","capacitor");__publicField(this,"props");this.props=props}toSpiceString(){let{name,positiveNode,negativeNode,modelName,value,initialCondition}=this.props,spiceString=`C${name} ${positiveNode} ${negativeNode}`;return modelName&&(spiceString+=` ${modelName}`),spiceString+=` ${value}`,initialCondition&&(spiceString+=` IC=${initialCondition}`),spiceString}},VoltageSourceCommand=class{constructor(props){__publicField(this,"commandName","voltage_source");__publicField(this,"props");this.props=props}toSpiceString(){let{name,positiveNode,negativeNode,value,acMagnitude,acPhase}=this.props,spiceString=`V${name} ${positiveNode} ${negativeNode}`;return value&&(spiceString+=` ${value}`),acMagnitude&&(spiceString+=` AC ${acMagnitude}`,acPhase&&(spiceString+=` ${acPhase}`)),spiceString}},BJTCommand=class{constructor(props){__publicField(this,"commandName","bjt");__publicField(this,"props");this.props=props}toSpiceString(){let{name,collector,base,emitter,substrate,model,area}=this.props,spiceString=`Q${name} ${collector} ${base} ${emitter}`;return substrate&&(spiceString+=` ${substrate}`),spiceString+=` ${model}`,area&&(spiceString+=` ${area}`),spiceString}},DiodeCommand=class{constructor(props){__publicField(this,"commandName","diode");__publicField(this,"props");this.props=props}toSpiceString(){let{name,positiveNode,negativeNode,model,area}=this.props,spiceString=`D${name} ${positiveNode} ${negativeNode} ${model}`;return area&&(spiceString+=` ${area}`),spiceString}},InductorCommand=class{constructor(props){__publicField(this,"commandName","inductor");__publicField(this,"props");this.props=props}toSpiceString(){let{name,positiveNode,negativeNode,model,value,initialCondition}=this.props,spiceString=`L${name} ${positiveNode} ${negativeNode}`;return model&&(spiceString+=` ${model}`),spiceString+=` ${value}`,initialCondition&&(spiceString+=` IC=${initialCondition}`),spiceString}},MOSFETCommand=class{constructor(props){__publicField(this,"commandName","mosfet");__publicField(this,"props");this.props=props}toSpiceString(){let{name,drain,gate,source,substrate,model,length:length3,width,drainArea,sourceArea,drainPerimeter,sourcePerimeter,drainResistance,sourceResistance}=this.props,spiceString=`M${name} ${drain} ${gate} ${source} ${substrate} ${model}`;return Object.entries({L:length3,W:width,AD:drainArea,AS:sourceArea,PD:drainPerimeter,PS:sourcePerimeter,NRD:drainResistance,NRS:sourceResistance}).forEach(([key,value])=>{value&&(spiceString+=` ${key}=${value}`)}),spiceString}},VoltageControlledSwitchCommand=class{constructor(props){__publicField(this,"commandName","voltage_controlled_switch");__publicField(this,"props");this.props=props}toSpiceString(){let{name,positiveNode,negativeNode,positiveControl,negativeControl,model}=this.props;return`S${name} ${positiveNode} ${negativeNode} ${positiveControl} ${negativeControl} ${model}`}};function circuitJsonToSpice(circuitJson){let netlist=new SpiceNetlist("* Circuit JSON to SPICE Netlist"),sourceComponents=su2(circuitJson).source_component.list(),sourcePorts=su2(circuitJson).source_port.list(),sourceTraces=su2(circuitJson).source_trace.list(),simulationProbes=circuitJson.filter(elm=>elm.type==="simulation_voltage_probe"),simulationSwitches=circuitJson.filter(element=>element.type==="simulation_switch").map(element=>element),simulationSwitchMap=new Map;for(let simSwitch of simulationSwitches)simSwitch.source_component_id&&simulationSwitchMap.set(simSwitch.source_component_id,simSwitch);let connMap=getSourcePortConnectivityMapFromCircuitJson(circuitJson),nodeMap=new Map,netToNodeName=new Map,nodeCounter=1,probeNames=new Set;if(simulationProbes.length>0)for(let probe of simulationProbes)probe.name&&probeNames.add(probe.name);let numericProbeNames=[...probeNames].map(name=>/^N(\d+)$/i.exec(name)).filter(m3=>m3!==null).map(m3=>parseInt(m3[1],10));numericProbeNames.length>0&&(nodeCounter=Math.max(...numericProbeNames)+1);let groundNets=new Set,gndSourceNetIds=new Set(su2(circuitJson).source_net.list().filter(sn3=>sn3.name?.toLowerCase().includes("gnd")).map(sn3=>sn3.source_net_id));if(gndSourceNetIds.size>0){for(let trace of su2(circuitJson).source_trace.list())if(trace.connected_source_port_ids.length>0&&trace.connected_source_net_ids.some(netId=>gndSourceNetIds.has(netId))){let aPortOnGnd=trace.connected_source_port_ids[0],gndNet=connMap.getNetConnectedToId(aPortOnGnd);gndNet&&groundNets.add(gndNet)}}let groundPorts=sourcePorts.filter(p4=>p4.name?.toLowerCase()==="gnd");for(let groundPort of groundPorts){let groundNet=connMap.getNetConnectedToId(groundPort.source_port_id);groundNet&&groundNets.add(groundNet)}for(let simSource of su2(circuitJson).simulation_voltage_source.list()){let neg_port_id=simSource.negative_source_port_id??simSource.terminal2_source_port_id;if(neg_port_id){let gnd_net=connMap.getNetConnectedToId(neg_port_id);gnd_net&&groundNets.add(gnd_net)}}for(let groundNet of groundNets)netToNodeName.set(groundNet,"0");if(simulationProbes.length>0)for(let probe of simulationProbes){if(!probe.name||probe.reference_input_source_port_id||probe.reference_input_source_net_id)continue;let net,signal_port_id=probe.signal_input_source_port_id,signal_net_id=probe.signal_input_source_net_id;if(signal_port_id)net=connMap.getNetConnectedToId(signal_port_id);else if(signal_net_id){let trace=sourceTraces.find(t6=>t6.connected_source_net_ids.includes(signal_net_id));if(trace&&trace.connected_source_port_ids.length>0){let portId=trace.connected_source_port_ids[0];net=connMap.getNetConnectedToId(portId)}}net?netToNodeName.has(net)||netToNodeName.set(net,probe.name):signal_port_id&&probe.name&&nodeMap.set(signal_port_id,probe.name)}for(let port of sourcePorts){let portId=port.source_port_id,net=connMap.getNetConnectedToId(portId);net&&(netToNodeName.has(net)||netToNodeName.set(net,`N${nodeCounter++}`),nodeMap.set(portId,netToNodeName.get(net)))}for(let port of sourcePorts){let portId=port.source_port_id;nodeMap.has(portId)||nodeMap.set(portId,`N${nodeCounter++}`)}for(let component of sourceComponents){if(component.type!=="source_component")continue;let componentPorts=su2(circuitJson).source_port.list({source_component_id:component.source_component_id}).sort((a3,b3)=>(a3.pin_number??0)-(b3.pin_number??0)),nodes=componentPorts.map(port=>nodeMap.get(port.source_port_id)||"0");if("ftype"in component){let spiceComponent=null;switch(component.ftype){case"simple_resistor":{if("resistance"in component&&"name"in component){let resistorCmd=new ResistorCommand({name:component.name,positiveNode:nodes[0]||"0",negativeNode:nodes[1]||"0",value:formatResistance(component.resistance)});spiceComponent=new SpiceComponent(component.name,resistorCmd,nodes)}break}case"simple_switch":{let sanitizedBase=sanitizeIdentifier(component.name??component.source_component_id,"SW"),positiveNode=nodes[0]||"0",negativeNode=nodes[1]||"0",controlNode=`NCTRL_${sanitizedBase}`,modelName=`SW_${sanitizedBase}`,associatedSimulationSwitch=simulationSwitchMap.get(component.source_component_id),controlValue=buildSimulationSwitchControlValue(associatedSimulationSwitch),switchCmd=new VoltageControlledSwitchCommand({name:sanitizedBase,positiveNode,negativeNode,positiveControl:controlNode,negativeControl:"0",model:modelName});spiceComponent=new SpiceComponent(sanitizedBase,switchCmd,[positiveNode,negativeNode,controlNode,"0"]),netlist.models.has(modelName)||netlist.models.set(modelName,`.MODEL ${modelName} SW(Ron=0.1 Roff=1e9 Vt=2.5 Vh=0.1)`);let controlSourceName=`CTRL_${sanitizedBase}`,controlSourceCmd=new VoltageSourceCommand({name:controlSourceName,positiveNode:controlNode,negativeNode:"0",value:controlValue}),controlComponent=new SpiceComponent(controlSourceName,controlSourceCmd,[controlNode,"0"]);netlist.addComponent(controlComponent);break}case"simple_capacitor":{if("capacitance"in component&&"name"in component){let capacitorCmd=new CapacitorCommand({name:component.name,positiveNode:nodes[0]||"0",negativeNode:nodes[1]||"0",value:formatCapacitance(component.capacitance)});spiceComponent=new SpiceComponent(component.name,capacitorCmd,nodes)}break}case"simple_diode":{if("name"in component){let anodePort=componentPorts.find(p4=>p4.name?.toLowerCase()==="anode"||p4.port_hints?.includes("anode")),cathodePort=componentPorts.find(p4=>p4.name?.toLowerCase()==="cathode"||p4.port_hints?.includes("cathode")),positiveNode=nodeMap.get(anodePort?.source_port_id??"")||"0",negativeNode=nodeMap.get(cathodePort?.source_port_id??"")||"0",modelName="D",diodeCmd=new DiodeCommand({name:component.name,positiveNode,negativeNode,model:modelName});netlist.models.set(modelName,`.MODEL ${modelName} D`),spiceComponent=new SpiceComponent(component.name,diodeCmd,[positiveNode,negativeNode])}break}case"simple_inductor":{if("inductance"in component&&"name"in component){let inductorCmd=new InductorCommand({name:component.name,positiveNode:nodes[0]||"0",negativeNode:nodes[1]||"0",value:formatInductance(component.inductance)});spiceComponent=new SpiceComponent(component.name,inductorCmd,nodes)}break}case"simple_mosfet":{if("name"in component){let drainPort=componentPorts.find(p4=>p4.name?.toLowerCase()==="drain"||p4.port_hints?.includes("drain")),gatePort=componentPorts.find(p4=>p4.name?.toLowerCase()==="gate"||p4.port_hints?.includes("gate")),sourcePort=componentPorts.find(p4=>p4.name?.toLowerCase()==="source"||p4.port_hints?.includes("source")),drainNode=nodeMap.get(drainPort?.source_port_id??"")||"0",gateNode=nodeMap.get(gatePort?.source_port_id??"")||"0",sourceNode=nodeMap.get(sourcePort?.source_port_id??"")||"0",substrateNode=sourceNode,channel_type=component.channel_type??"n",mosfet_mode=component.mosfet_mode??"enhancement",modelType=`${channel_type.toUpperCase()}MOS`,modelName=`${modelType}_${mosfet_mode.toUpperCase()}`;if(!netlist.models.has(modelName))if(mosfet_mode==="enhancement"){let vto=channel_type==="p"?-1:1;netlist.models.set(modelName,`.MODEL ${modelName} ${modelType} (VTO=${vto} KP=0.1)`)}else netlist.models.set(modelName,`.MODEL ${modelName} ${modelType} (KP=0.1)`);let mosfetCmd=new MOSFETCommand({name:component.name,drain:drainNode,gate:gateNode,source:sourceNode,substrate:substrateNode,model:modelName});spiceComponent=new SpiceComponent(component.name,mosfetCmd,[drainNode,gateNode,sourceNode])}break}case"simple_transistor":{if("name"in component){let collectorPort=componentPorts.find(p4=>p4.name?.toLowerCase()==="collector"||p4.port_hints?.includes("collector")),basePort=componentPorts.find(p4=>p4.name?.toLowerCase()==="base"||p4.port_hints?.includes("base")),emitterPort=componentPorts.find(p4=>p4.name?.toLowerCase()==="emitter"||p4.port_hints?.includes("emitter"));if(!collectorPort||!basePort||!emitterPort)throw new Error(`Transistor ${component.name} is missing required ports (collector, base, emitter)`);let collectorNode=nodeMap.get(collectorPort.source_port_id)||"0",baseNode=nodeMap.get(basePort.source_port_id)||"0",emitterNode=nodeMap.get(emitterPort.source_port_id)||"0",transistor_type=component.transistor_type??"npn",modelName=transistor_type.toUpperCase();netlist.models.has(modelName)||netlist.models.set(modelName,`.MODEL ${modelName} ${transistor_type.toUpperCase()}`);let bjtCmd=new BJTCommand({name:component.name,collector:collectorNode,base:baseNode,emitter:emitterNode,model:modelName});spiceComponent=new SpiceComponent(component.name,bjtCmd,[collectorNode,baseNode,emitterNode])}break}}spiceComponent&&netlist.addComponent(spiceComponent)}}let simulationVoltageSources=su2(circuitJson).simulation_voltage_source.list();for(let simSource of simulationVoltageSources)if(simSource.type==="simulation_voltage_source")if(simSource.is_dc_source===!1){if("terminal1_source_port_id"in simSource&&"terminal2_source_port_id"in simSource&&simSource.terminal1_source_port_id&&simSource.terminal2_source_port_id){let positiveNode=nodeMap.get(simSource.terminal1_source_port_id)||"0",negativeNode=nodeMap.get(simSource.terminal2_source_port_id)||"0",value="",wave_shape2=simSource.wave_shape;if(wave_shape2==="sinewave"){let v_peak=simSource.voltage??0,freq=simSource.frequency??0,delay=0,damping_factor=0,phase=simSource.phase??0;freq>0?value=`SIN(0 ${v_peak} ${freq} ${delay} ${damping_factor} ${phase})`:value=`DC ${simSource.voltage??0}`}else if(wave_shape2==="square"){let v_pulsed=simSource.voltage??0,freq=simSource.frequency??0,period_from_freq=freq===0?1/0:1/freq,period=simSource.period??period_from_freq,duty_cycle=simSource.duty_cycle??.5,pulse_width=period*duty_cycle;value=`PULSE(0 ${v_pulsed} 0 1n 1n ${pulse_width} ${period})`}else simSource.voltage!==void 0&&(value=`DC ${simSource.voltage}`);if(value){let voltageSourceCmd=new VoltageSourceCommand({name:simSource.simulation_voltage_source_id,positiveNode,negativeNode,value}),spiceComponent=new SpiceComponent(simSource.simulation_voltage_source_id,voltageSourceCmd,[positiveNode,negativeNode]);netlist.addComponent(spiceComponent)}}}else{let positivePortId=simSource.positive_source_port_id??simSource.terminal1_source_port_id,negativePortId=simSource.negative_source_port_id??simSource.terminal2_source_port_id;if(positivePortId&&negativePortId&&"voltage"in simSource&&simSource.voltage!==void 0){let positiveNode=nodeMap.get(positivePortId)||"0",negativeNode=nodeMap.get(negativePortId)||"0",voltageSourceCmd=new VoltageSourceCommand({name:simSource.simulation_voltage_source_id,positiveNode,negativeNode,value:`DC ${simSource.voltage}`}),spiceComponent=new SpiceComponent(simSource.simulation_voltage_source_id,voltageSourceCmd,[positiveNode,negativeNode]);netlist.addComponent(spiceComponent)}}let simExperiment=circuitJson.find(elm=>elm.type==="simulation_experiment");if(simExperiment){if(simulationProbes.length>0){let nodesToProbe=new Set,getPortIdFromNetId=netId=>sourceTraces.find(t6=>t6.connected_source_net_ids.includes(netId))?.connected_source_port_ids[0];for(let probe of simulationProbes){let signalPortId=probe.signal_input_source_port_id;if(!signalPortId){let signalNetId=probe.signal_input_source_net_id;signalNetId&&(signalPortId=getPortIdFromNetId(signalNetId))}if(!signalPortId)continue;let signalNodeName=nodeMap.get(signalPortId);if(!signalNodeName)continue;let referencePortId=probe.reference_input_source_port_id;if(!referencePortId&&probe.reference_input_source_net_id&&(referencePortId=getPortIdFromNetId(probe.reference_input_source_net_id)),referencePortId){let referenceNodeName=nodeMap.get(referencePortId);referenceNodeName&&referenceNodeName!=="0"?nodesToProbe.add(`V(${signalNodeName},${referenceNodeName})`):signalNodeName!=="0"&&nodesToProbe.add(`V(${signalNodeName})`)}else signalNodeName!=="0"&&nodesToProbe.add(`V(${signalNodeName})`)}nodesToProbe.size>0&&simExperiment.experiment_type?.includes("transient")&&netlist.printStatements.push(`.PRINT TRAN ${[...nodesToProbe].join(" ")}`)}let timePerStep=simExperiment.time_per_step,endTime=simExperiment.end_time_ms,startTimeMs=simExperiment.start_time_ms;if(timePerStep&&endTime){let startTime=(startTimeMs??0)/1e3,tranCmd=`.tran ${formatNumberForSpice(timePerStep/1e3)} ${formatNumberForSpice(endTime/1e3)}`;startTime>0&&(tranCmd+=` ${formatNumberForSpice(startTime)}`),tranCmd+=" UIC",netlist.tranCommand=tranCmd}}return netlist}function formatResistance(resistance2){return resistance2>=1e6?`${resistance2/1e6}MEG`:resistance2>=1e3?`${resistance2/1e3}K`:resistance2.toString()}function formatCapacitance(capacitance2){return capacitance2>=.001?`${capacitance2*1e3}M`:capacitance2>=1e-6?`${capacitance2*1e6}U`:capacitance2>=1e-9?`${capacitance2*1e9}N`:capacitance2>=1e-12?`${capacitance2*1e12}P`:capacitance2.toString()}function formatInductance(inductance2){return inductance2>=1?inductance2.toString():inductance2>=.001?`${inductance2*1e3}m`:inductance2>=1e-6?`${inductance2*1e6}u`:inductance2>=1e-9?`${inductance2*1e9}n`:inductance2>=1e-12?`${inductance2*1e12}p`:inductance2.toString()}function sanitizeIdentifier(value,prefix){if(!value)return prefix;let sanitized=value.replace(/[^A-Za-z0-9_]/g,"_");return sanitized?/^[0-9]/.test(sanitized)?`${prefix}_${sanitized}`:sanitized:prefix}function buildSimulationSwitchControlValue(simulationSwitch){if(!simulationSwitch)return"DC 0";let startsClosed=simulationSwitch.starts_closed??!1,closesAt=simulationSwitch.closes_at??0,opensAt=simulationSwitch.opens_at,switchingFrequency=simulationSwitch.switching_frequency,[initialVoltage,pulsedVoltage]=startsClosed?[5,0]:[0,5];if(switchingFrequency&&switchingFrequency>0){let period=1/switchingFrequency,widthFromOpenClose=opensAt&&opensAt>closesAt?Math.min(opensAt-closesAt,period):0,pulseWidth=widthFromOpenClose>0?widthFromOpenClose:Math.max(period/2,1e-9);return`PULSE(${formatNumberForSpice(initialVoltage)} ${formatNumberForSpice(pulsedVoltage)} ${formatNumberForSpice(closesAt)} 1n 1n ${formatNumberForSpice(pulseWidth)} ${formatNumberForSpice(period)})`}if(opensAt!==void 0&&opensAt>closesAt){let pulseWidth=Math.max(opensAt-closesAt,1e-9),period=closesAt+pulseWidth*2;return`PULSE(${formatNumberForSpice(initialVoltage)} ${formatNumberForSpice(pulsedVoltage)} ${formatNumberForSpice(closesAt)} 1n 1n ${formatNumberForSpice(pulseWidth)} ${formatNumberForSpice(period)})`}if(closesAt>0){let period=closesAt*2,pulseWidth=Math.max(period/2,1e-9);return`PULSE(${formatNumberForSpice(initialVoltage)} ${formatNumberForSpice(pulsedVoltage)} ${formatNumberForSpice(closesAt)} 1n 1n ${formatNumberForSpice(pulseWidth)} ${formatNumberForSpice(period)})`}return`DC ${startsClosed?5:0}`}function formatNumberForSpice(value){if(!Number.isFinite(value))return`${value}`;if(value===0)return"0";let absValue=Math.abs(value);return absValue>=1e3||absValue<=.001?Number(value.toExponential(6)).toString():Number(value.toPrecision(6)).toString()}var import_debug17=__toESM(require_browser(),1);var EPS5=1e-15,NodeIndex=class{constructor(){__publicField(this,"map");__publicField(this,"rev");this.map=new Map([["0",0]]),this.rev=["0"]}getOrCreate(name){let origName=String(name),key=origName.toUpperCase();if(this.map.has(key))return this.map.get(key);let idx=this.rev.length;return this.map.set(key,idx),this.rev.push(origName),idx}get(name){return this.map.get(String(name).toUpperCase())}count(){return this.rev.length}matrixIndexOfNode(nodeId){return nodeId===0?-1:nodeId-1}};function parseNumberWithUnits(raw){if(raw==null)return NaN;let s4=String(raw).trim();if(s4==="")return NaN;if(/^[+-]?\d*\.?\d+(?:[eE][+-]?\d+)?$/.test(s4))return parseFloat(s4);let unitMul={t:1e12,g:1e9,meg:1e6,k:1e3,m:.001,u:1e-6,n:1e-9,p:1e-12,f:1e-15},m3=s4.match(/^([+-]?\d*\.?\d+(?:[eE][+-]?\d+)?)([a-zA-Z]+)$/);if(!m3)return parseFloat(s4);let[,numberPart,suffixPart]=m3;if(numberPart==null)return parseFloat(s4);let val=parseFloat(numberPart),suf=(suffixPart??"").toLowerCase();return suf=suf.replace(/(ohm|v|a|s|h|f)$/g,""),suf==="meg"?val*unitMul.meg:suf.length===1&&suf in unitMul?val*unitMul[suf]:val}function parsePulseArgs(token){let parts=token.trim().replace(/^pulse\s*\(/i,"(").replace(/^\(/,"").replace(/\)$/,"").trim().split(/[\s,]+/).filter(x3=>x3.length);if(parts.length<7)throw new Error("PULSE(...) requires 7 or 8 args");let vals=parts.map(value=>parseNumberWithUnits(value));if(vals.some(v4=>Number.isNaN(v4)))throw new Error("Invalid PULSE() numeric value");return{v1:vals[0],v2:vals[1],td:vals[2],tr:vals[3],tf:vals[4],ton:vals[5],period:vals[6],ncycles:parts[7]!=null?vals[7]:1/0}}function parsePwlArgs(token){let parts=token.trim().replace(/^pwl\s*\(/i,"(").replace(/^\(/,"").replace(/\)$/,"").trim().split(/[\s,]+/).filter(x3=>x3.length);if(parts.length===0||parts.length%2!==0)throw new Error("PWL(...) requires an even number of time/value pairs");let pairs3=[];for(let i3=0;i3<parts.length;i3+=2){let t6=parseNumberWithUnits(parts[i3]),v4=parseNumberWithUnits(parts[i3+1]);if(Number.isNaN(t6)||Number.isNaN(v4))throw new Error("Invalid PWL() numeric value");pairs3.push({t:t6,v:v4})}return pairs3}function pulseValue(p4,t6){if(t6<p4.td)return p4.v1;let tt3=t6-p4.td,cyclesDone=Math.floor(tt3/p4.period);if(cyclesDone>=p4.ncycles)return p4.v1;let tc=tt3-cyclesDone*p4.period;if(tc<p4.tr){let a3=tc/Math.max(p4.tr,EPS5);return p4.v1+(p4.v2-p4.v1)*a3}if(tc<p4.tr+p4.ton)return p4.v2;if(tc<p4.tr+p4.ton+p4.tf){let a3=(tc-(p4.tr+p4.ton))/Math.max(p4.tf,EPS5);return p4.v2+(p4.v1-p4.v2)*a3}return p4.v1}function pwlValue(pairs3,t6){if(pairs3.length===0)return 0;if(t6<=pairs3[0].t)return pairs3[0].v;for(let i3=1;i3<pairs3.length;i3++){let prev=pairs3[i3-1],curr=pairs3[i3];if(t6<=curr.t){let dt2=Math.max(curr.t-prev.t,EPS5),a3=(t6-prev.t)/dt2;return prev.v+(curr.v-prev.v)*a3}}return pairs3[pairs3.length-1].v}function smartTokens(line2){let re3=/"[^"]*"|\w+\s*\([^)]*\)|\([^()]*\)|\S+/g,out=[],m3;for(;(m3=re3.exec(line2))!==null;)out.push(m3[0]);return out}function requireToken(tokens,index,context){let token=tokens[index];if(token==null)throw new Error(context);return token}function parseNetlist(text){let vswitchModels=new Map,diodeModels=new Map,ckt={nodes:new NodeIndex,R:[],C:[],L:[],V:[],S:[],D:[],analyses:{ac:null,tran:null},probes:{tran:[]},skipped:[],models:{vswitch:vswitchModels,diode:diodeModels}},lines=text.split(/\r?\n/),seenTitle=!1;for(let raw of lines){let line2=raw.trim();if(!line2||/^\*/.test(line2))continue;if(/^\s*\.end\b/i.test(line2))break;line2=line2.replace(/\/\/.*$/,""),line2=line2.replace(/;.*$/,"");let tokens=smartTokens(line2);if(tokens.length===0)continue;let first=tokens[0];if(first.length===0)continue;if(!seenTitle&&!/^[rclvgsmiqd]\w*$/i.test(first)&&!/^\./.test(first)){seenTitle=!0;continue}if(/^\./.test(first)){let dir=first.toLowerCase();if(dir===".ac"){let mode=requireToken(tokens,1,".ac missing mode").toLowerCase();if(mode!=="dec"&&mode!=="lin")throw new Error(".ac supports 'dec' or 'lin'");let N4=parseInt(requireToken(tokens,2,".ac missing point count"),10),f12=parseNumberWithUnits(requireToken(tokens,3,".ac missing start frequency")),f2=parseNumberWithUnits(requireToken(tokens,4,".ac missing stop frequency"));ckt.analyses.ac={mode,N:N4,f1:f12,f2}}else if(dir===".tran"){let dt2=parseNumberWithUnits(requireToken(tokens,1,".tran missing timestep")),tstop=parseNumberWithUnits(requireToken(tokens,2,".tran missing stop time"));ckt.analyses.tran={dt:dt2,tstop}}else if(dir===".print")if(requireToken(tokens,1,".print missing analysis type").toLowerCase()==="tran"){let probeTokens=tokens.slice(2);for(let token of probeTokens){let match2=token.match(/^v\(([^)]+)\)$/i);if(match2&&match2[1]){let nodeName2=match2[1];ckt.probes.tran.some(p4=>p4.toUpperCase()===nodeName2.toUpperCase())||ckt.probes.tran.push(nodeName2)}}}else ckt.skipped.push(line2);else if(dir===".model"){let nameToken=requireToken(tokens,1,".model missing name"),type=requireToken(tokens,2,".model missing type"),paramsStr="";if(type.includes("(")){let idx=type.indexOf("(");paramsStr=type.slice(idx+1),type=type.slice(0,idx)}if(!paramsStr)paramsStr=tokens.slice(3).join(" ").replace(/^\(/,"").replace(/\)$/,"");else{let rest=tokens.slice(3).join(" ").replace(/\)$/,"");paramsStr=`${paramsStr} ${rest}`.trim()}paramsStr=paramsStr.replace(/^\(/,"").replace(/\)$/,"").trim();let typeLower=type.toLowerCase();if(typeLower==="vswitch"||typeLower==="sw"){let model={name:nameToken,Ron:1,Roff:1e12,Von:0,Voff:0},vt3,vh2;if(paramsStr.length>0){let assignments=paramsStr.split(/[\s,]+/).filter(Boolean);for(let assignment of assignments){let[keyRaw,valueRaw]=assignment.split("=");if(!keyRaw||valueRaw==null)continue;let key=keyRaw.toLowerCase(),value=parseNumberWithUnits(valueRaw);Number.isNaN(value)||(key==="ron"?model.Ron=value:key==="roff"?model.Roff=value:key==="von"?model.Von=value:key==="voff"?model.Voff=value:key==="vt"?vt3=value:key==="vh"&&(vh2=value))}}if(vt3!==void 0){let Vh2=vh2??0;model.Von=vt3+Vh2/2,model.Voff=vt3-Vh2/2}vswitchModels.set(nameToken.toLowerCase(),model)}else if(typeLower==="d"){let model={name:nameToken,Is:1e-14,N:1};if(paramsStr.length>0){let assignments=paramsStr.split(/[\s,]+/).filter(Boolean);for(let assignment of assignments){let[keyRaw,valueRaw]=assignment.split("=");if(!keyRaw||valueRaw==null)continue;let key=keyRaw.toLowerCase(),value=parseNumberWithUnits(valueRaw);Number.isNaN(value)||(key==="is"?model.Is=value:key==="n"&&(model.N=value))}}diodeModels.set(nameToken.toLowerCase(),model)}else ckt.skipped.push(line2)}else ckt.skipped.push(line2);continue}let typeChar=first.charAt(0).toLowerCase(),name=first;try{if(typeChar==="r"){let n12=ckt.nodes.getOrCreate(requireToken(tokens,1,"Resistor missing node")),n22=ckt.nodes.getOrCreate(requireToken(tokens,2,"Resistor missing node")),val=parseNumberWithUnits(requireToken(tokens,3,"Resistor missing value"));ckt.R.push({name,n1:n12,n2:n22,R:val})}else if(typeChar==="c"){let n12=ckt.nodes.getOrCreate(requireToken(tokens,1,"Capacitor missing node")),n22=ckt.nodes.getOrCreate(requireToken(tokens,2,"Capacitor missing node")),val=parseNumberWithUnits(requireToken(tokens,3,"Capacitor missing value"));ckt.C.push({name,n1:n12,n2:n22,C:val,vPrev:0})}else if(typeChar==="l"){let n12=ckt.nodes.getOrCreate(requireToken(tokens,1,"Inductor missing node")),n22=ckt.nodes.getOrCreate(requireToken(tokens,2,"Inductor missing node")),val=parseNumberWithUnits(requireToken(tokens,3,"Inductor missing value"));ckt.L.push({name,n1:n12,n2:n22,L:val,iPrev:0})}else if(typeChar==="v"){let n12=ckt.nodes.getOrCreate(requireToken(tokens,1,"Voltage source missing node")),n22=ckt.nodes.getOrCreate(requireToken(tokens,2,"Voltage source missing node")),spec={dc:0,acMag:0,acPhaseDeg:0,waveform:null,index:-1},i3=3;for(i3<tokens.length&&!/^[a-zA-Z]/.test(tokens[i3])&&(spec.dc=parseNumberWithUnits(tokens[i3]),i3++);i3<tokens.length;){let key=tokens[i3].toLowerCase();if(key==="dc"){let valueToken=requireToken(tokens,i3+1,"DC value missing");spec.dc=parseNumberWithUnits(valueToken),i3+=2}else if(key==="ac"){let magToken=requireToken(tokens,i3+1,"AC magnitude missing");spec.acMag=parseNumberWithUnits(magToken);let phaseToken=tokens[i3+2];phaseToken!=null&&/^[+-]?\d/.test(phaseToken)?(spec.acPhaseDeg=parseNumberWithUnits(phaseToken),i3+=3):i3+=2}else if(key.startsWith("pulse")){let argToken=key.includes("(")?key:requireToken(tokens,i3+1,"PULSE() missing arguments");if(!argToken||!/\(.*\)/.test(argToken))throw new Error("Malformed PULSE() specification");let p4=parsePulseArgs(argToken);spec.waveform=t6=>pulseValue(p4,t6),i3+=key.includes("(")?1:2}else if(key.startsWith("pwl")){let argToken=key.includes("(")?key:requireToken(tokens,i3+1,"PWL() missing arguments");if(!argToken||!/\(.*\)/.test(argToken))throw new Error("Malformed PWL() specification");let pairs3=parsePwlArgs(argToken);spec.waveform=t6=>pwlValue(pairs3,t6),i3+=key.includes("(")?1:2}else/^\(.*\)$/.test(key),i3++}ckt.V.push({name,n1:n12,n2:n22,dc:spec.dc,acMag:spec.acMag,acPhaseDeg:spec.acPhaseDeg,waveform:spec.waveform,index:spec.index??-1})}else if(typeChar==="s"){let n12=ckt.nodes.getOrCreate(requireToken(tokens,1,"Switch missing node")),n22=ckt.nodes.getOrCreate(requireToken(tokens,2,"Switch missing node")),ncPos=ckt.nodes.getOrCreate(requireToken(tokens,3,"Switch missing control node")),ncNeg=ckt.nodes.getOrCreate(requireToken(tokens,4,"Switch missing control node")),modelName=requireToken(tokens,5,"Switch missing model");ckt.S.push({name,n1:n12,n2:n22,ncPos,ncNeg,modelName:modelName.toLowerCase(),model:null,isOn:!1})}else if(typeChar==="d")if(tokens.length===4){let nPlus=ckt.nodes.getOrCreate(requireToken(tokens,1,"Diode missing node")),nMinus=ckt.nodes.getOrCreate(requireToken(tokens,2,"Diode missing node")),modelName=requireToken(tokens,3,"Diode missing model");ckt.D.push({name,nPlus,nMinus,modelName:modelName.toLowerCase(),model:null,vdPrev:0})}else ckt.skipped.push(line2);else ckt.skipped.push(line2)}catch(err){throw err instanceof Error?new Error(`Parse error on line: "${line2}"
596
596
  ${err.message}`):err}}let nNodes=ckt.nodes.count()-1;for(let i3=0;i3<ckt.V.length;i3++){let vs3=ckt.V[i3];vs3&&(vs3.index=nNodes+i3)}for(let sw of ckt.S){let model=vswitchModels.get(sw.modelName);if(!model)throw new Error(`Unknown .model ${sw.modelName} referenced by switch ${sw.name}`);sw.model=model,sw.isOn=!1}for(let d2 of ckt.D){let model=diodeModels.get(d2.modelName);if(!model)throw new Error(`Unknown .model ${d2.modelName} referenced by diode ${d2.name}`);d2.model=model}return ckt}var Complex=class _Complex{constructor(re3=0,im2=0){__publicField(this,"re");__publicField(this,"im");this.re=re3,this.im=im2}static from(re3,im2=0){return new _Complex(re3,im2)}static fromPolar(mag,deg=0){let ph2=deg*Math.PI/180;return new _Complex(mag*Math.cos(ph2),mag*Math.sin(ph2))}clone(){return new _Complex(this.re,this.im)}add(b3){return new _Complex(this.re+b3.re,this.im+b3.im)}sub(b3){return new _Complex(this.re-b3.re,this.im-b3.im)}mul(b3){return new _Complex(this.re*b3.re-this.im*b3.im,this.re*b3.im+this.im*b3.re)}div(b3){let d2=b3.re*b3.re+b3.im*b3.im;if(d2<EPS5)throw new Error("Complex divide by ~0");return new _Complex((this.re*b3.re+this.im*b3.im)/d2,(this.im*b3.re-this.re*b3.im)/d2)}inv(){let d2=this.re*this.re+this.im*this.im;if(d2<EPS5)throw new Error("Complex invert by ~0");return new _Complex(this.re/d2,-this.im/d2)}abs(){return Math.hypot(this.re,this.im)}phaseDeg(){return Math.atan2(this.im,this.re)*180/Math.PI}};function solveComplex(A4,b3){let n3=A4.length;for(let i3=0;i3<n3;i3++){let row=A4[i3],bi3=b3[i3];if(!row||!bi3)throw new Error("Matrix dimensions mismatch");let copy=row.map(z5=>z5.clone());copy.push(bi3.clone()),A4[i3]=copy}for(let k4=0;k4<n3;k4++){let imax=k4,pivotRow=A4[k4];if(!pivotRow)throw new Error("Matrix row missing");let vmax=pivotRow[k4]?.abs()??0;for(let i3=k4+1;i3<n3;i3++){let row=A4[i3];if(!row)throw new Error("Matrix row missing");let v4=row[k4]?.abs()??0;v4>vmax&&(vmax=v4,imax=i3)}if(vmax<EPS5)throw new Error("Singular matrix (complex)");if(imax!==k4){let tmp=A4[k4];A4[k4]=A4[imax],A4[imax]=tmp}let pivotRowUpdated=A4[k4];if(!pivotRowUpdated)throw new Error("Pivot row missing");let pivot=pivotRowUpdated[k4];if(!pivot)throw new Error("Zero pivot encountered");for(let i3=k4+1;i3<n3;i3++){let row=A4[i3];if(!row)throw new Error("Matrix row missing");let entry=row[k4];if(!entry)continue;let f2=entry.div(pivot);if(!(f2.abs()<EPS5))for(let j3=k4;j3<=n3;j3++){let target=row[j3],source=pivotRowUpdated[j3];!target||!source||(row[j3]=target.sub(f2.mul(source)))}}}let x3=new Array(n3);for(let i3=n3-1;i3>=0;i3--){let row=A4[i3];if(!row)throw new Error("Matrix row missing");let s4=row[n3];if(!s4)throw new Error("Augmented column missing");for(let j3=i3+1;j3<n3;j3++){let coeff=row[j3],sol=x3[j3];!coeff||!sol||(s4=s4.sub(coeff.mul(sol)))}let pivot=row[i3];if(!pivot)throw new Error("Zero pivot on back-substitution");x3[i3]=s4.div(pivot)}return x3}function logspace(f12,f2,pointsPerDecade){if(f12<=0||f2<=0)throw new Error(".ac frequencies must be > 0");f2<f12&&([f12,f2]=[f2,f12]);let decades=Math.log10(f2/f12),n3=Math.max(1,Math.ceil(decades*pointsPerDecade)),arr=[];for(let i3=0;i3<=n3;i3++)arr.push(f12*Math.pow(10,i3/pointsPerDecade));let last=arr[arr.length-1];return(last==null||last<f2*(1-EPS5))&&arr.push(f2),arr}function stampAdmittanceComplex(A4,nidx,n12,n22,Y4){let i12=nidx.matrixIndexOfNode(n12),i22=nidx.matrixIndexOfNode(n22);if(i12>=0){let row1=A4[i12];if(!row1)throw new Error("Matrix row missing while stamping");row1[i12]=row1[i12]?.add(Y4)??Y4}if(i22>=0){let row2=A4[i22];if(!row2)throw new Error("Matrix row missing while stamping");row2[i22]=row2[i22]?.add(Y4)??Y4}if(i12>=0&&i22>=0){let row1=A4[i12],row2=A4[i22];if(!row1||!row2)throw new Error("Matrix row missing while stamping");row1[i22]=row1[i22]?.sub(Y4)??Complex.from(0,0).sub(Y4),row2[i12]=row2[i12]?.sub(Y4)??Complex.from(0,0).sub(Y4)}}function stampVoltageSourceComplex(A4,b3,nidx,source,voltage2){let i12=nidx.matrixIndexOfNode(source.n1),i22=nidx.matrixIndexOfNode(source.n2),j3=source.index,one=Complex.from(1,0),negOne=Complex.from(-1,0);if(i12>=0){let row1=A4[i12];if(!row1)throw new Error("Matrix row missing while stamping voltage source");row1[j3]=row1[j3]?.add(one)??one}if(i22>=0){let row2=A4[i22];if(!row2)throw new Error("Matrix row missing while stamping voltage source");row2[j3]=row2[j3]?.sub(one)??negOne}let branchRow=A4[j3];if(!branchRow)throw new Error("Branch row missing while stamping voltage source");i12>=0&&(branchRow[i12]=branchRow[i12]?.add(one)??one),i22>=0&&(branchRow[i22]=branchRow[i22]?.sub(one)??negOne),b3[j3]=(b3[j3]??Complex.from(0,0)).add(voltage2)}function buildFrequencyArray(params){let{mode,N:N4,f1:f12,f2}=params;if(mode==="dec")return logspace(f12,f2,N4);let arr=[],npts=Math.max(2,N4),step=(f2-f12)/(npts-1);for(let i3=0;i3<npts;i3++)arr.push(f12+i3*step);return arr}function buildLinearSystemForAC(ckt,f2,Nvar){let A4=Array.from({length:Nvar},()=>Array.from({length:Nvar},()=>Complex.from(0,0))),b3=Array.from({length:Nvar},()=>Complex.from(0,0)),twoPi=2*Math.PI;for(let r4 of ckt.R){if(r4.R<=0)throw new Error(`R ${r4.name} must be > 0`);let Y4=Complex.from(1/r4.R,0);stampAdmittanceComplex(A4,ckt.nodes,r4.n1,r4.n2,Y4)}for(let c3 of ckt.C){let Y4=Complex.from(0,twoPi*f2*c3.C);stampAdmittanceComplex(A4,ckt.nodes,c3.n1,c3.n2,Y4)}for(let l3 of ckt.L){let denom=Complex.from(0,twoPi*f2*l3.L),Y4=denom.abs()<EPS5?Complex.from(0,0):Complex.from(1,0).div(denom);stampAdmittanceComplex(A4,ckt.nodes,l3.n1,l3.n2,Y4)}for(let vs3 of ckt.V){let Vph=Complex.fromPolar(vs3.acMag||0,vs3.acPhaseDeg||0);stampVoltageSourceComplex(A4,b3,ckt.nodes,vs3,Vph)}return{A:A4,b:b3}}function simulateAC(ckt){var _a359,_b2,_c2,_d2;if(!ckt.analyses.ac)return null;let{mode,N:N4,f1:f12,f2}=ckt.analyses.ac,nNodeVars=ckt.nodes.count()-1,nVsrc=ckt.V.length,Nvar=nNodeVars+nVsrc,freqs=buildFrequencyArray({mode,N:N4,f1:f12,f2}),nodeVoltages={};ckt.nodes.rev.forEach((name,id)=>{id!==0&&(nodeVoltages[name]=[])});let elementCurrents={},twoPi=2*Math.PI;for(let f4 of freqs){let{A:A4,b:b3}=buildLinearSystemForAC(ckt,f4,Nvar),x3=solveComplex(A4,b3);for(let id=1;id<ckt.nodes.count();id++){let idx=id-1,nodeName2=ckt.nodes.rev[id];if(!nodeName2)continue;let series=nodeVoltages[nodeName2];series&&series.push(x3[idx]??Complex.from(0,0))}for(let r4 of ckt.R){let v12=r4.n1===0?Complex.from(0,0):x3[r4.n1-1]??Complex.from(0,0),v22=r4.n2===0?Complex.from(0,0):x3[r4.n2-1]??Complex.from(0,0),i3=Complex.from(1/r4.R,0).mul(v12.sub(v22));(elementCurrents[_a359=r4.name]||(elementCurrents[_a359]=[])).push(i3)}for(let c3 of ckt.C){let v12=c3.n1===0?Complex.from(0,0):x3[c3.n1-1]??Complex.from(0,0),v22=c3.n2===0?Complex.from(0,0):x3[c3.n2-1]??Complex.from(0,0),i3=Complex.from(0,twoPi*f4*c3.C).mul(v12.sub(v22));(elementCurrents[_b2=c3.name]||(elementCurrents[_b2]=[])).push(i3)}for(let l3 of ckt.L){let v12=l3.n1===0?Complex.from(0,0):x3[l3.n1-1]??Complex.from(0,0),v22=l3.n2===0?Complex.from(0,0):x3[l3.n2-1]??Complex.from(0,0),denom=Complex.from(0,twoPi*f4*l3.L),i3=(denom.abs()<EPS5?Complex.from(0,0):Complex.from(1,0).div(denom)).mul(v12.sub(v22));(elementCurrents[_c2=l3.name]||(elementCurrents[_c2]=[])).push(i3)}for(let vs3 of ckt.V){let i3=x3[vs3.index]??Complex.from(0,0);(elementCurrents[_d2=vs3.name]||(elementCurrents[_d2]=[])).push(i3)}}return{freqs,nodeVoltages,elementCurrents}}var VT_300K=.02585;function solveReal(A4,b3){let n3=A4.length;for(let i3=0;i3<n3;i3++){let row=A4[i3],bi3=b3[i3];if(!row||bi3==null)throw new Error("Matrix dimensions mismatch");let copy=row.slice();copy.push(bi3),A4[i3]=copy}for(let k4=0;k4<n3;k4++){let imax=k4,pivotRow=A4[k4];if(!pivotRow)throw new Error("Matrix row missing");let vmax=Math.abs(pivotRow[k4]??0);for(let i3=k4+1;i3<n3;i3++){let row=A4[i3];if(!row)throw new Error("Matrix row missing");let v4=Math.abs(row[k4]??0);v4>vmax&&(vmax=v4,imax=i3)}if(vmax<EPS5)throw new Error("Singular matrix (real)");if(imax!==k4){let tmp=A4[k4];A4[k4]=A4[imax],A4[imax]=tmp}let pivotRowUpdated=A4[k4];if(!pivotRowUpdated)throw new Error("Pivot row missing");let pivot=pivotRowUpdated[k4];if(pivot==null)throw new Error("Zero pivot encountered");for(let i3=k4+1;i3<n3;i3++){let row=A4[i3];if(!row)throw new Error("Matrix row missing");let entry=row[k4];if(entry==null)continue;let f2=entry/pivot;if(!(Math.abs(f2)<EPS5))for(let j3=k4;j3<=n3;j3++){let target=row[j3],source=pivotRowUpdated[j3];target==null||source==null||(row[j3]=target-f2*source)}}}let x3=new Array(n3).fill(0);for(let i3=n3-1;i3>=0;i3--){let row=A4[i3];if(!row)throw new Error("Matrix row missing");let s4=row[n3];if(s4==null)throw new Error("Augmented column missing");for(let j3=i3+1;j3<n3;j3++){let coeff=row[j3],sol=x3[j3];coeff==null||sol==null||(s4-=coeff*sol)}let pivot=row[i3];if(pivot==null)throw new Error("Zero pivot on back-substitution");x3[i3]=s4/pivot}return x3}function stampAdmittanceReal(A4,nidx,n12,n22,Y4){let i12=nidx.matrixIndexOfNode(n12),i22=nidx.matrixIndexOfNode(n22);if(i12>=0){let row1=A4[i12];if(!row1)throw new Error("Matrix row missing while stamping");row1[i12]=(row1[i12]??0)+Y4}if(i22>=0){let row2=A4[i22];if(!row2)throw new Error("Matrix row missing while stamping");row2[i22]=(row2[i22]??0)+Y4}if(i12>=0&&i22>=0){let row1=A4[i12],row2=A4[i22];if(!row1||!row2)throw new Error("Matrix row missing while stamping");row1[i22]=(row1[i22]??0)-Y4,row2[i12]=(row2[i12]??0)-Y4}}function stampCurrentReal(b3,nidx,nPlus,nMinus,current2){let iPlus=nidx.matrixIndexOfNode(nPlus),iMinus=nidx.matrixIndexOfNode(nMinus);iPlus>=0&&(b3[iPlus]=(b3[iPlus]??0)-current2),iMinus>=0&&(b3[iMinus]=(b3[iMinus]??0)+current2)}function stampVoltageSourceReal(A4,b3,nidx,source,voltage2){let i12=nidx.matrixIndexOfNode(source.n1),i22=nidx.matrixIndexOfNode(source.n2),j3=source.index;if(i12>=0){let row1=A4[i12];if(!row1)throw new Error("Matrix row missing while stamping voltage source");row1[j3]=(row1[j3]??0)+1}if(i22>=0){let row2=A4[i22];if(!row2)throw new Error("Matrix row missing while stamping voltage source");row2[j3]=(row2[j3]??0)-1}let branchRow=A4[j3];if(!branchRow)throw new Error("Branch row missing while stamping voltage source");i12>=0&&(branchRow[i12]=(branchRow[i12]??0)+1),i22>=0&&(branchRow[i22]=(branchRow[i22]??0)-1),b3[j3]=(b3[j3]??0)+voltage2}function computeEffectiveTimeStep(dtRequested,tstop){let dtEff=dtRequested>EPS5?dtRequested:Math.max(tstop/1e3,EPS5),steps=Math.max(1,Math.ceil(tstop/Math.max(dtEff,EPS5)));return{dt:steps>0?tstop/steps:tstop,steps}}function stampAllElementsAtTime(A4,b3,ckt,t6,dt2,x3,iter){for(let r4 of ckt.R){let G4=1/r4.R;stampAdmittanceReal(A4,ckt.nodes,r4.n1,r4.n2,G4)}for(let c3 of ckt.C){let Gc2=c3.C/Math.max(dt2,EPS5);stampAdmittanceReal(A4,ckt.nodes,c3.n1,c3.n2,Gc2);let Ieq=-Gc2*c3.vPrev;stampCurrentReal(b3,ckt.nodes,c3.n1,c3.n2,Ieq)}for(let l3 of ckt.L){let Gl=Math.max(dt2,EPS5)/l3.L;stampAdmittanceReal(A4,ckt.nodes,l3.n1,l3.n2,Gl),stampCurrentReal(b3,ckt.nodes,l3.n1,l3.n2,l3.iPrev)}for(let sw of ckt.S){let model=sw.model;if(!model)continue;let Rvalue=sw.isOn?model.Ron:model.Roff,G4=1/Math.max(Math.abs(Rvalue),EPS5);stampAdmittanceReal(A4,ckt.nodes,sw.n1,sw.n2,G4)}for(let vs3 of ckt.V){let Vt3=vs3.waveform?vs3.waveform(t6):vs3.dc||0;stampVoltageSourceReal(A4,b3,ckt.nodes,vs3,Vt3)}for(let d2 of ckt.D){let model=d2.model;if(!model)continue;let{nPlus,nMinus}=d2,vp_idx=ckt.nodes.matrixIndexOfNode(nPlus),vn_idx=ckt.nodes.matrixIndexOfNode(nMinus),v_plus_prev_iter=nPlus===0?0:x3[vp_idx]??0,v_minus_prev_iter=nMinus===0?0:x3[vn_idx]??0,vd_prev_iter=v_plus_prev_iter-v_minus_prev_iter,vd2=iter===0?d2.vdPrev:vd_prev_iter,v_thermal=model.N*VT_300K,vd_limited=vd2;vd2>.8&&(vd_limited=.8),vd2<-1&&(vd_limited=-1);let exp_val=Math.exp(vd_limited/v_thermal),id=model.Is*(exp_val-1),gd2=Math.max(model.Is/v_thermal*exp_val,1e-12),ieq=id-gd2*vd_limited;stampAdmittanceReal(A4,ckt.nodes,nPlus,nMinus,gd2),stampCurrentReal(b3,ckt.nodes,nPlus,nMinus,ieq)}}function updateSwitchStatesFromSolution(ckt,x3){let switched=!1;for(let sw of ckt.S){let model=sw.model;if(!model)continue;let vp2=sw.ncPos===0?0:x3[sw.ncPos-1]??0,vn3=sw.ncNeg===0?0:x3[sw.ncNeg-1]??0,vctrl=vp2-vn3,nextState=sw.isOn;sw.isOn?vctrl<model.Voff&&(nextState=!1):vctrl>model.Von&&(nextState=!0),nextState!==sw.isOn&&(sw.isOn=nextState,switched=!0)}return switched}function simulateTRAN(ckt){var _a359,_b2,_c2,_d2,_e3,_f2;if(!ckt.analyses.tran)return null;let{dt:dtRequested,tstop}=ckt.analyses.tran,{dt:dt2,steps}=computeEffectiveTimeStep(dtRequested,tstop),nNodeVars=ckt.nodes.count()-1,nVsrc=ckt.V.length,Nvar=nNodeVars+nVsrc,times=[],nodeVoltages={};ckt.nodes.rev.forEach((name,id)=>{id!==0&&(nodeVoltages[name]=[])});let elementCurrents={},t6=0;for(let step=0;step<=steps;step++,t6=step*dt2){times.push(t6);let x3=new Array(Nvar).fill(0);for(let iter=0;iter<20;iter++){let A4=Array.from({length:Nvar},()=>new Array(Nvar).fill(0)),b3=new Array(Nvar).fill(0);if(stampAllElementsAtTime(A4,b3,ckt,t6,dt2,x3,iter),x3=solveReal(A4,b3),!updateSwitchStatesFromSolution(ckt,x3)||iter===19)break}for(let id=1;id<ckt.nodes.count();id++){let idx=id-1,nodeName2=ckt.nodes.rev[id];if(!nodeName2)continue;let series=nodeVoltages[nodeName2];series&&series.push(x3[idx]??0)}for(let r4 of ckt.R){let v12=r4.n1===0?0:x3[r4.n1-1]??0,v22=r4.n2===0?0:x3[r4.n2-1]??0,i3=(v12-v22)/r4.R;(elementCurrents[_a359=r4.name]||(elementCurrents[_a359]=[])).push(i3)}for(let c3 of ckt.C){let v12=c3.n1===0?0:x3[c3.n1-1]??0,v22=c3.n2===0?0:x3[c3.n2-1]??0,i3=c3.C*(v12-v22-c3.vPrev)/Math.max(dt2,EPS5);(elementCurrents[_b2=c3.name]||(elementCurrents[_b2]=[])).push(i3)}for(let l3 of ckt.L){let v12=l3.n1===0?0:x3[l3.n1-1]??0,v22=l3.n2===0?0:x3[l3.n2-1]??0,i3=Math.max(dt2,EPS5)/l3.L*(v12-v22)+l3.iPrev;(elementCurrents[_c2=l3.name]||(elementCurrents[_c2]=[])).push(i3)}for(let vs3 of ckt.V){let i3=x3[vs3.index]??0;(elementCurrents[_d2=vs3.name]||(elementCurrents[_d2]=[])).push(i3)}for(let sw of ckt.S){let model=sw.model;if(!model)continue;let v12=sw.n1===0?0:x3[sw.n1-1]??0,v22=sw.n2===0?0:x3[sw.n2-1]??0,Rvalue=sw.isOn?model.Ron:model.Roff,Rclamped=Math.max(Math.abs(Rvalue),EPS5),i3=(v12-v22)/Rclamped;(elementCurrents[_e3=sw.name]||(elementCurrents[_e3]=[])).push(i3)}for(let d2 of ckt.D){if(!d2.model)continue;let{nPlus,nMinus,model}=d2,v12=nPlus===0?0:x3[nPlus-1]??0,v22=nMinus===0?0:x3[nMinus-1]??0,vd2=v12-v22,v_thermal=model.N*VT_300K,exp_val=Math.exp(vd2/v_thermal),id=model.Is*(exp_val-1);(elementCurrents[_f2=d2.name]||(elementCurrents[_f2]=[])).push(id)}for(let c3 of ckt.C){let v12=c3.n1===0?0:x3[c3.n1-1]??0,v22=c3.n2===0?0:x3[c3.n2-1]??0;c3.vPrev=v12-v22}for(let l3 of ckt.L){let v12=l3.n1===0?0:x3[l3.n1-1]??0,v22=l3.n2===0?0:x3[l3.n2-1]??0,Gl=Math.max(dt2,EPS5)/l3.L;l3.iPrev=Gl*(v12-v22)+l3.iPrev}for(let d2 of ckt.D){let v12=d2.nPlus===0?0:x3[d2.nPlus-1]??0,v22=d2.nMinus===0?0:x3[d2.nMinus-1]??0;d2.vdPrev=v12-v22}}if(ckt.probes.tran.length>0){let probedVoltages={},upperProbes=ckt.probes.tran.map(p4=>p4.toUpperCase());for(let nodeName2 in nodeVoltages)upperProbes.includes(nodeName2.toUpperCase())&&(probedVoltages[nodeName2]=nodeVoltages[nodeName2]);return{times,nodeVoltages:probedVoltages,elementCurrents}}return{times,nodeVoltages,elementCurrents}}function simulate(netlistText){let circuit=parseNetlist(netlistText),ac2=simulateAC(circuit),tran=simulateTRAN(circuit);return{circuit,ac:ac2,tran}}function spiceyTranToVGraphs(tranResult,ckt,simulation_experiment_id){if(!tranResult||!ckt.analyses.tran)return[];let{dt:dt2,tstop}=ckt.analyses.tran,{times,nodeVoltages}=tranResult,graphs=[];for(let nodeName2 in nodeVoltages){let voltage_levels=nodeVoltages[nodeName2];graphs.push({type:"simulation_transient_voltage_graph",simulation_transient_voltage_graph_id:`stvg_${simulation_experiment_id}_${nodeName2}`,simulation_experiment_id,timestamps_ms:times.map(t6=>t6*1e3),voltage_levels,time_per_step:dt2*1e3,start_time_ms:0,end_time_ms:tstop*1e3,name:`${nodeName2}`})}return graphs}init_dist6();var SI_PREFIXES=[{value:1e12,symbol:"T"},{value:1e9,symbol:"G"},{value:1e6,symbol:"M"},{value:1e3,symbol:"k"},{value:1,symbol:""},{value:.001,symbol:"m"},{value:1e-6,symbol:"\xB5"},{value:1e-9,symbol:"n"},{value:1e-12,symbol:"p"}];function formatSiUnit(value){if(value==null)return"";if(value===0)return"0";let absValue=Math.abs(value),prefix=SI_PREFIXES.find(p4=>{let scaled2=absValue/p4.value;return scaled2>=1&&scaled2<1e3})||SI_PREFIXES[SI_PREFIXES.length-1],formatted=(value/prefix.value).toPrecision(3);return formatted.includes(".")&&!/\.0+$/.test(formatted)&&(formatted=formatted.replace(/0+$/,"")),formatted=formatted.replace(/\.0+$/,""),`${formatted}${prefix.symbol}`}init_dist6();init_dist();init_dist4();init_dist6();init_dist4();init_dist6();init_dist6();init_dist();init_dist6();init_dist6();init_src();init_dist6();init_dist4();init_dist6();init_dist4();init_dist6();init_dist6();init_dist4();init_dist6();function distance7(x12,y12,x22,y22){return Math.sqrt((x22-x12)**2+(y22-y12)**2)}var addStartAndEndPortIdsIfMissing=soup=>{let pcbPorts=soup.filter(item=>item.type==="pcb_port"),pcbSmtPads=soup.filter(item=>item.type==="pcb_smtpad"),pcbTraces=soup.filter(item=>item.type==="pcb_trace");function findPortIdOverlappingPoint(point6,options={}){let traceWidth=options.traceWidth||0,directPort=pcbPorts.find(port=>distance7(port.x,port.y,point6.x,point6.y)<.01);if(directPort)return directPort.pcb_port_id;if(options.isFirstOrLastPoint){let smtPad=pcbSmtPads.find(pad2=>{if(pad2.shape==="rect")return Math.abs(point6.x-pad2.x)<pad2.width/2+traceWidth/2&&Math.abs(point6.y-pad2.y)<pad2.height/2+traceWidth/2;if(pad2.shape==="circle")return distance7(point6.x,point6.y,pad2.x,pad2.y)<pad2.radius});if(smtPad)return smtPad.pcb_port_id??null}return null}for(let trace of pcbTraces)for(let index=0;index<trace.route.length;index++){let segment2=trace.route[index],isFirstOrLastPoint=index===0||index===trace.route.length-1;if(segment2.route_type==="wire"){if(!segment2.start_pcb_port_id&&index===0){let startPortId=findPortIdOverlappingPoint(segment2,{isFirstOrLastPoint,traceWidth:segment2.width});startPortId&&(segment2.start_pcb_port_id=startPortId)}if(!segment2.end_pcb_port_id&&index===trace.route.length-1){let endPortId=findPortIdOverlappingPoint(segment2,{isFirstOrLastPoint,traceWidth:segment2.width});endPortId&&(segment2.end_pcb_port_id=endPortId)}}}};function checkEachPcbPortConnectedToPcbTraces(circuitJson){addStartAndEndPortIdsIfMissing(circuitJson);let sourceTraces=circuitJson.filter(item=>item.type==="source_trace"),pcbPorts=circuitJson.filter(item=>item.type==="pcb_port"),errors=[],connectivityMap=getFullConnectivityMapFromCircuitJson(circuitJson),sourcePortToPcbPort=new Map;for(let pcbPort of pcbPorts)sourcePortToPcbPort.set(pcbPort.source_port_id,pcbPort);for(let sourceTrace of sourceTraces){let connectedSourcePortIds=sourceTrace.connected_source_port_ids;if(connectedSourcePortIds.length<2)continue;let pcbPortsInTrace=[],missingPcbPorts=[];for(let sourcePortId of connectedSourcePortIds){let pcbPort=sourcePortToPcbPort.get(sourcePortId);pcbPort?pcbPortsInTrace.push(pcbPort):missingPcbPorts.push(sourcePortId)}if(pcbPortsInTrace.length<2)continue;let firstPcbPort=pcbPortsInTrace[0],referenceNetId=connectivityMap.getNetConnectedToId(firstPcbPort.pcb_port_id);connectivityMap.getIdsConnectedToNet(referenceNetId).filter(id=>circuitJson.some(element=>element.type==="pcb_trace"&&("pcb_trace_id"in element&&element.pcb_trace_id===id||"route_id"in element&&element.route_id===id))).length===0&&new Set(pcbPortsInTrace.map(p4=>p4.pcb_component_id)).size>1&&errors.push({type:"pcb_port_not_connected_error",message:`pcb_port_not_connected_error: Pcb ports [${pcbPortsInTrace.map(p4=>p4.pcb_port_id).join(", ")}] are not connected together through the same net.`,error_type:"pcb_port_not_connected_error",pcb_port_ids:pcbPortsInTrace.map(p4=>p4.pcb_port_id),pcb_component_ids:pcbPortsInTrace.map(p4=>p4.pcb_component_id).filter(id=>id!==void 0),pcb_port_not_connected_error_id:`pcb_port_not_connected_error_trace_${sourceTrace.source_trace_id}`})}return errors}var SpatialObjectIndex=class{constructor({objects,getBounds:getBounds3,getId,CELL_SIZE}){__publicField(this,"buckets");__publicField(this,"objectsById");__publicField(this,"getBounds");__publicField(this,"getId");__publicField(this,"CELL_SIZE",.4);__publicField(this,"_idCounter",0);this.buckets=new Map,this.objectsById=new Map,this.getBounds=getBounds3,this.getId=getId??(()=>this._getNextId()),this.CELL_SIZE=CELL_SIZE??this.CELL_SIZE;for(let obj of objects)this.addObject(obj)}_getNextId(){return`${this._idCounter++}`}addObject(obj){let bounds=this.getBounds(obj),spatialIndexId=this.getId(obj),objWithId={...obj,spatialIndexId};this.objectsById.set(spatialIndexId,objWithId);let minBucketX=Math.floor(bounds.minX/this.CELL_SIZE),minBucketY=Math.floor(bounds.minY/this.CELL_SIZE),maxBucketX=Math.floor(bounds.maxX/this.CELL_SIZE),maxBucketY=Math.floor(bounds.maxY/this.CELL_SIZE);for(let bx2=minBucketX;bx2<=maxBucketX;bx2++)for(let by2=minBucketY;by2<=maxBucketY;by2++){let bucketKey=`${bx2}x${by2}`,bucket=this.buckets.get(bucketKey);bucket?bucket.push(objWithId):this.buckets.set(bucketKey,[objWithId])}}removeObject(id){let obj=this.objectsById.get(id);if(!obj)return!1;this.objectsById.delete(id);let bounds=this.getBounds(obj),minBucketX=Math.floor(bounds.minX/this.CELL_SIZE),minBucketY=Math.floor(bounds.minY/this.CELL_SIZE),maxBucketX=Math.floor(bounds.maxX/this.CELL_SIZE),maxBucketY=Math.floor(bounds.maxY/this.CELL_SIZE);for(let bx2=minBucketX;bx2<=maxBucketX;bx2++)for(let by2=minBucketY;by2<=maxBucketY;by2++){let bucketKey=`${bx2}x${by2}`,bucket=this.buckets.get(bucketKey);if(bucket){let index=bucket.findIndex(item=>item.spatialIndexId===id);index!==-1&&(bucket.splice(index,1),bucket.length===0&&this.buckets.delete(bucketKey))}}return!0}getBucketKey(x3,y3){return`${Math.floor(x3/this.CELL_SIZE)}x${Math.floor(y3/this.CELL_SIZE)}`}getObjectsInBounds(bounds,margin=0){let objects=[],addedIds=new Set,minBucketX=Math.floor((bounds.minX-margin)/this.CELL_SIZE),minBucketY=Math.floor((bounds.minY-margin)/this.CELL_SIZE),maxBucketX=Math.floor((bounds.maxX+margin)/this.CELL_SIZE),maxBucketY=Math.floor((bounds.maxY+margin)/this.CELL_SIZE);for(let bx2=minBucketX;bx2<=maxBucketX;bx2++)for(let by2=minBucketY;by2<=maxBucketY;by2++){let bucketKey=`${bx2}x${by2}`,bucket=this.buckets.get(bucketKey)||[];for(let obj of bucket){let id=obj.spatialIndexId;addedIds.has(id)||(addedIds.add(id),objects.push(obj))}}return objects}},getCollidableBounds=collidable=>collidable.type==="pcb_trace_segment"?{minX:Math.min(collidable.x1,collidable.x2),minY:Math.min(collidable.y1,collidable.y2),maxX:Math.max(collidable.x1,collidable.x2),maxY:Math.max(collidable.y1,collidable.y2)}:getBoundsOfPcbElements([collidable]),DEFAULT_TRACE_MARGIN=.1,DEFAULT_TRACE_THICKNESS=.15;var DEFAULT_SAME_NET_VIA_MARGIN=.2,DEFAULT_DIFFERENT_NET_VIA_MARGIN=.3,EPSILON=.005;function getPcbPortIdsConnectedToTrace(trace){let connectedPcbPorts=new Set;for(let segment2 of trace.route)segment2.route_type==="wire"&&(segment2.start_pcb_port_id&&connectedPcbPorts.add(segment2.start_pcb_port_id),segment2.end_pcb_port_id&&connectedPcbPorts.add(segment2.end_pcb_port_id));return Array.from(connectedPcbPorts)}function getPcbPortIdsConnectedToTraces(traces){let connectedPorts=new Set;for(let trace of traces)for(let portId of getPcbPortIdsConnectedToTrace(trace))connectedPorts.add(portId);return Array.from(connectedPorts)}var getClosestPointBetweenSegments=(segmentA,segmentB)=>{let a12={x:segmentA.x1,y:segmentA.y1},a22={x:segmentA.x2,y:segmentA.y2},b12={x:segmentB.x1,y:segmentB.y1},b22={x:segmentB.x2,y:segmentB.y2},va2={x:a22.x-a12.x,y:a22.y-a12.y},vb2={x:b22.x-b12.x,y:b22.y-b12.y},lenSqrA=va2.x*va2.x+va2.y*va2.y,lenSqrB=vb2.x*vb2.x+vb2.y*vb2.y;if(lenSqrA===0||lenSqrB===0){if(lenSqrA===0&&lenSqrB===0)return{x:(a12.x+b12.x)/2,y:(a12.y+b12.y)/2};if(lenSqrA===0){let t22=clamp4(((a12.x-b12.x)*vb2.x+(a12.y-b12.y)*vb2.y)/lenSqrB,0,1),closestOnB2={x:b12.x+t22*vb2.x,y:b12.y+t22*vb2.y};return{x:(a12.x+closestOnB2.x)/2,y:(a12.y+closestOnB2.y)/2}}let t6=clamp4(((b12.x-a12.x)*va2.x+(b12.y-a12.y)*va2.y)/lenSqrA,0,1),closestOnA2={x:a12.x+t6*va2.x,y:a12.y+t6*va2.y};return{x:(closestOnA2.x+b12.x)/2,y:(closestOnA2.y+b12.y)/2}}let w4={x:a12.x-b12.x,y:a12.y-b12.y},dotAA=va2.x*va2.x+va2.y*va2.y,dotAB=va2.x*vb2.x+va2.y*vb2.y,dotAW=va2.x*w4.x+va2.y*w4.y,dotBB=vb2.x*vb2.x+vb2.y*vb2.y,dotBW=vb2.x*w4.x+vb2.y*w4.y,denominator=dotAA*dotBB-dotAB*dotAB;if(denominator<1e-10)return closestPointsParallelSegments(a12,a22,b12,b22,va2,vb2,lenSqrA,lenSqrB);let tA=(dotAB*dotBW-dotBB*dotAW)/denominator,tB=(dotAA*dotBW-dotAB*dotAW)/denominator;tA=clamp4(tA,0,1),tB=clamp4(tB,0,1),tB=(tA*dotAB+dotBW)/dotBB,tB=clamp4(tB,0,1),tA=(tB*dotAB-dotAW)/dotAA,tA=clamp4(tA,0,1);let closestOnA={x:a12.x+tA*va2.x,y:a12.y+tA*va2.y},closestOnB={x:b12.x+tB*vb2.x,y:b12.y+tB*vb2.y},dx2=closestOnA.x-closestOnB.x,dy2=closestOnA.y-closestOnB.y,distance52=Math.sqrt(dx2*dx2+dy2*dy2);return{x:(closestOnA.x+closestOnB.x)/2,y:(closestOnA.y+closestOnB.y)/2}},closestPointsParallelSegments=(a12,a22,b12,b22,va2,vb2,lenSqrA,lenSqrB)=>{let tA=((b12.x-a12.x)*va2.x+(b12.y-a12.y)*va2.y)/lenSqrA;tA=clamp4(tA,0,1);let pointOnA1={x:a12.x+tA*va2.x,y:a12.y+tA*va2.y},tA2=((b22.x-a12.x)*va2.x+(b22.y-a12.y)*va2.y)/lenSqrA;tA2=clamp4(tA2,0,1);let pointOnA2={x:a12.x+tA2*va2.x,y:a12.y+tA2*va2.y},tB=((a12.x-b12.x)*vb2.x+(a12.y-b12.y)*vb2.y)/lenSqrB;tB=clamp4(tB,0,1);let pointOnB1={x:b12.x+tB*vb2.x,y:b12.y+tB*vb2.y},tB2=((a22.x-b12.x)*vb2.x+(a22.y-b12.y)*vb2.y)/lenSqrB;tB2=clamp4(tB2,0,1);let pointOnB2={x:b12.x+tB2*vb2.x,y:b12.y+tB2*vb2.y},closestPair=[{pointA:pointOnA1,pointB:b12,distance:Math.sqrt((pointOnA1.x-b12.x)**2+(pointOnA1.y-b12.y)**2)},{pointA:pointOnA2,pointB:b22,distance:Math.sqrt((pointOnA2.x-b22.x)**2+(pointOnA2.y-b22.y)**2)},{pointA:a12,pointB:pointOnB1,distance:Math.sqrt((a12.x-pointOnB1.x)**2+(a12.y-pointOnB1.y)**2)},{pointA:a22,pointB:pointOnB2,distance:Math.sqrt((a22.x-pointOnB2.x)**2+(a22.y-pointOnB2.y)**2)}].reduce((closest,current2)=>current2.distance<closest.distance?current2:closest);return{x:(closestPair.pointA.x+closestPair.pointB.x)/2,y:(closestPair.pointA.y+closestPair.pointB.y)/2}},clamp4=(value,min,max)=>Math.max(min,Math.min(max,value)),getRadiusOfCircuitJsonElement=obj=>{if(obj.type==="pcb_via"||obj.type==="pcb_plated_hole"&&obj.shape==="circle")return obj.outer_diameter/2;if(obj.type==="pcb_hole"&&obj.hole_shape==="circle")return obj.hole_diameter/2;if(obj.type==="pcb_smtpad"&&obj.shape==="circle")return obj.radius;throw new Error(`Could not determine radius of element: ${JSON.stringify(obj)}`)},getClosestPointBetweenSegmentAndBounds=(segment2,bounds)=>{let p12={x:segment2.x1,y:segment2.y1},p22={x:segment2.x2,y:segment2.y2},minX=bounds.minX,minY=bounds.minY,maxX=bounds.maxX,maxY=bounds.maxY;if(p12.x===p22.x&&p12.y===p22.y){let closestX=Math.max(minX,Math.min(maxX,p12.x)),closestY=Math.max(minY,Math.min(maxY,p12.y));return closestX===p12.x&&closestY===p12.y?{x:p12.x,y:p12.y}:{x:closestX,y:closestY}}let dx2=p22.x-p12.x,dy2=p22.y-p12.y,tMinX=dx2!==0?(minX-p12.x)/dx2:Number.NEGATIVE_INFINITY,tMaxX=dx2!==0?(maxX-p12.x)/dx2:Number.POSITIVE_INFINITY,tMinY=dy2!==0?(minY-p12.y)/dy2:Number.NEGATIVE_INFINITY,tMaxY=dy2!==0?(maxY-p12.y)/dy2:Number.POSITIVE_INFINITY,tEnter=Math.max(Math.min(tMinX,tMaxX),Math.min(tMinY,tMaxY)),tExit=Math.min(Math.max(tMinX,tMaxX),Math.max(tMinY,tMaxY));if(tEnter<=tExit&&tExit>=0&&tEnter<=1){let t6=Math.max(0,Math.min(1,tEnter));return{x:p12.x+t6*dx2,y:p12.y+t6*dy2}}let closestToP1={x:Math.max(minX,Math.min(maxX,p12.x)),y:Math.max(minY,Math.min(maxY,p12.y))},closestToP2={x:Math.max(minX,Math.min(maxX,p22.x)),y:Math.max(minY,Math.min(maxY,p22.y))},distToP1Squared=(closestToP1.x-p12.x)**2+(closestToP1.y-p12.y)**2,distToP2Squared=(closestToP2.x-p22.x)**2+(closestToP2.y-p22.y)**2,edges=[{start:{x:minX,y:minY},end:{x:maxX,y:minY}},{start:{x:maxX,y:minY},end:{x:maxX,y:maxY}},{start:{x:maxX,y:maxY},end:{x:minX,y:maxY}},{start:{x:minX,y:maxY},end:{x:minX,y:minY}}],minDistance=Math.min(distToP1Squared,distToP2Squared),closestPoint=distToP1Squared<=distToP2Squared?closestToP1:closestToP2,clamp22=(value,min,max)=>Math.max(min,Math.min(max,value));for(let edge of edges){let va2={x:p22.x-p12.x,y:p22.y-p12.y},vb2={x:edge.end.x-edge.start.x,y:edge.end.y-edge.start.y},w4={x:p12.x-edge.start.x,y:p12.y-edge.start.y},dotAA=va2.x*va2.x+va2.y*va2.y,dotAB=va2.x*vb2.x+va2.y*vb2.y,dotAW=va2.x*w4.x+va2.y*w4.y,dotBB=vb2.x*vb2.x+vb2.y*vb2.y,dotBW=vb2.x*w4.x+vb2.y*w4.y,denominator=dotAA*dotBB-dotAB*dotAB;if(Math.abs(denominator)<1e-10)continue;let tA=(dotAB*dotBW-dotBB*dotAW)/denominator,tB=(dotAA*dotBW-dotAB*dotAW)/denominator;tA=clamp22(tA,0,1),tB=clamp22(tB,0,1);let closestOnSegment={x:p12.x+tA*va2.x,y:p12.y+tA*va2.y},closestOnEdge={x:edge.start.x+tB*vb2.x,y:edge.start.y+tB*vb2.y},dx22=closestOnSegment.x-closestOnEdge.x,dy22=closestOnSegment.y-closestOnEdge.y,distSquared=dx22*dx22+dy22*dy22;distSquared<minDistance&&(minDistance=distSquared,closestPoint={x:(closestOnSegment.x+closestOnEdge.x)/2,y:(closestOnSegment.y+closestOnEdge.y)/2})}return closestPoint};function getLayersOfPcbElement(obj){return obj.type==="pcb_trace_segment"?[obj.layer]:obj.type==="pcb_smtpad"?[obj.layer]:obj.type==="pcb_plated_hole"?Array.isArray(obj.layers)?obj.layers:[...all_layers]:obj.type==="pcb_hole"?[...all_layers]:obj.type==="pcb_via"?Array.isArray(obj.layers)?obj.layers:[...all_layers]:obj.type==="pcb_keepout"?Array.isArray(obj.layers)?obj.layers:[]:[]}function checkEachPcbTraceNonOverlapping(circuitJson,{connMap}={}){let errors=[];connMap??(connMap=getFullConnectivityMapFromCircuitJson(circuitJson));let pcbTraceSegments=cju_default(circuitJson).pcb_trace.list().flatMap(pcbTrace=>{let segments=[];for(let i3=0;i3<pcbTrace.route.length-1;i3++){let p12=pcbTrace.route[i3],p22=pcbTrace.route[i3+1];p12.route_type==="wire"&&p22.route_type==="wire"&&p12.layer===p22.layer&&segments.push({type:"pcb_trace_segment",pcb_trace_id:pcbTrace.pcb_trace_id,_pcbTrace:pcbTrace,thickness:"width"in p12?p12.width:"width"in p22?p22.width:DEFAULT_TRACE_THICKNESS,layer:p12.layer,x1:p12.x,y1:p12.y,x2:p22.x,y2:p22.y})}return segments}),pcbSmtPads=cju_default(circuitJson).pcb_smtpad.list(),pcbPlatedHoles=cju_default(circuitJson).pcb_plated_hole.list(),pcbHoles=cju_default(circuitJson).pcb_hole.list(),pcbVias=cju_default(circuitJson).pcb_via.list(),pcbKeepouts=cju_default(circuitJson).pcb_keepout.list(),allObjects=[...pcbTraceSegments,...pcbSmtPads,...pcbPlatedHoles,...pcbHoles,...pcbVias,...pcbKeepouts],spatialIndex=new SpatialObjectIndex({objects:allObjects,getBounds:getCollidableBounds}),getReadableName=id=>getReadableNameForElement(circuitJson,id),errorIds=new Set;for(let segmentA of pcbTraceSegments){let requiredMargin=DEFAULT_TRACE_MARGIN,bounds=getCollidableBounds(segmentA),nearbyObjects=spatialIndex.getObjectsInBounds(bounds,requiredMargin+segmentA.thickness/2);if(!(segmentA.x1===segmentA.x2&&segmentA.y1===segmentA.y2))for(let obj of nearbyObjects){if(!getLayersOfPcbElement(obj).includes(segmentA.layer))continue;if(obj.type==="pcb_trace_segment"){let segmentB=obj;if(segmentA.layer!==segmentB.layer||connMap.areIdsConnected(segmentA.pcb_trace_id,segmentB.pcb_trace_id))continue;let gap2=segmentToSegmentMinDistance({x:segmentA.x1,y:segmentA.y1},{x:segmentA.x2,y:segmentA.y2},{x:segmentB.x1,y:segmentB.y1},{x:segmentB.x2,y:segmentB.y2})-segmentA.thickness/2-segmentB.thickness/2;if(gap2>DEFAULT_TRACE_MARGIN-EPSILON)continue;let pcb_trace_error_id=`overlap_${segmentA.pcb_trace_id}_${segmentB.pcb_trace_id}`,pcb_trace_error_id_reverse=`overlap_${segmentB.pcb_trace_id}_${segmentA.pcb_trace_id}`;if(errorIds.has(pcb_trace_error_id)||errorIds.has(pcb_trace_error_id_reverse))continue;errorIds.add(pcb_trace_error_id),errors.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${getReadableName(segmentA.pcb_trace_id)} overlaps with ${getReadableName(segmentB.pcb_trace_id)} ${gap2<0?"(accidental contact)":`(gap: ${gap2.toFixed(3)}mm)`}`,pcb_trace_id:segmentA.pcb_trace_id,source_trace_id:"",pcb_trace_error_id,pcb_component_ids:[],center:getClosestPointBetweenSegments(segmentA,segmentB),pcb_port_ids:getPcbPortIdsConnectedToTraces([segmentA._pcbTrace,segmentB._pcbTrace])});continue}let primaryObjId=getPrimaryId(obj);if(connMap.areIdsConnected(segmentA.pcb_trace_id,"pcb_trace_id"in obj?obj.pcb_trace_id:primaryObjId))continue;if(obj.type==="pcb_via"||obj.type==="pcb_plated_hole"&&obj.shape==="circle"||obj.type==="pcb_hole"||obj.type==="pcb_smtpad"&&obj.shape==="circle"){let radius=getRadiusOfCircuitJsonElement(obj),gap2=segmentToCircleMinDistance({x:segmentA.x1,y:segmentA.y1},{x:segmentA.x2,y:segmentA.y2},{x:obj.x,y:obj.y,radius})-segmentA.thickness/2;if(gap2>DEFAULT_TRACE_MARGIN-EPSILON)continue;let pcb_trace_error_id=`overlap_${segmentA.pcb_trace_id}_${primaryObjId}`;if(errorIds.has(pcb_trace_error_id))continue;errorIds.add(pcb_trace_error_id),errors.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${getReadableName(segmentA.pcb_trace_id)} overlaps with ${obj.type} "${getReadableName(getPrimaryId(obj))}" ${gap2<0?"(accidental contact)":`(gap: ${gap2.toFixed(3)}mm)`}`,pcb_trace_id:segmentA.pcb_trace_id,center:getClosestPointBetweenSegmentAndBounds(segmentA,getCollidableBounds(obj)),source_trace_id:"",pcb_trace_error_id,pcb_component_ids:["pcb_component_id"in obj?obj.pcb_component_id:void 0].filter(Boolean),pcb_port_ids:[...getPcbPortIdsConnectedToTraces([segmentA._pcbTrace]),"pcb_port_id"in obj?obj.pcb_port_id:void 0].filter(Boolean)})}let gap=segmentToBoundsMinDistance({x:segmentA.x1,y:segmentA.y1},{x:segmentA.x2,y:segmentA.y2},getCollidableBounds(obj))-segmentA.thickness/2;if(gap+EPSILON<requiredMargin){let pcb_trace_error_id=`overlap_${segmentA.pcb_trace_id}_${primaryObjId}`;if(errorIds.has(pcb_trace_error_id))continue;errorIds.add(pcb_trace_error_id),errors.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${getReadableName(segmentA.pcb_trace_id)} overlaps with ${obj.type} "${getReadableName(getPrimaryId(obj))}" ${gap<0?"(accidental contact)":`(gap: ${gap.toFixed(3)}mm)`}`,pcb_trace_id:segmentA.pcb_trace_id,source_trace_id:"",pcb_trace_error_id,pcb_component_ids:["pcb_component_id"in obj?obj.pcb_component_id:void 0].filter(Boolean),center:getClosestPointBetweenSegmentAndBounds(segmentA,getCollidableBounds(obj)),pcb_port_ids:[...getPcbPortIdsConnectedToTraces([segmentA._pcbTrace]),"pcb_port_id"in obj?obj.pcb_port_id:void 0].filter(Boolean)})}}}return errors}function isPolygonCCW(poly){return poly.area()>=0}function rectanglePolygon({center:center2,size:size2,rotationDeg=0}){let cx2=center2.x,cy2=center2.y,hw=size2.width/2,hh=size2.height/2,corners=[new Point$3(cx2-hw,cy2-hh),new Point$3(cx2+hw,cy2-hh),new Point$3(cx2+hw,cy2+hh),new Point$3(cx2-hw,cy2+hh)],poly=new Polygon$1(corners);if(rotationDeg){let matrix2=rotateDEG2(rotationDeg,cx2,cy2),rotatedCorners=corners.map(pt3=>{let p4=applyToPoint2(matrix2,{x:pt3.x,y:pt3.y});return new Point$3(p4.x,p4.y)});poly=new Polygon$1(rotatedCorners)}return isPolygonCCW(poly)||poly.reverse(),poly}function boardToPolygon({board}){if(board.outline&&board.outline.length>0){let points=board.outline.map(p4=>new Point$3(p4.x,p4.y)),poly=new Polygon$1(points);return isPolygonCCW(poly)||poly.reverse(),poly}return board.center&&typeof board.width=="number"&&typeof board.height=="number"?rectanglePolygon({center:board.center,size:{width:board.width,height:board.height},rotationDeg:0}):null}function getComponentName({circuitJson,component}){if(component.source_component_id){let sourceComponent=circuitJson.find(el2=>el2.type==="source_component"&&el2.source_component_id===component.source_component_id);if(sourceComponent&&"name"in sourceComponent&&sourceComponent.name)return sourceComponent.name}return getReadableNameForElement(circuitJson,component.pcb_component_id)||"Unknown"}function computeOverlapDistance(compPoly,boardPoly,componentCenter,componentWidth,componentHeight,rotationDeg){let centerPoint=new Point$3(componentCenter.x,componentCenter.y);if(!boardPoly.contains(centerPoint)){let dist=boardPoly.distanceTo(centerPoint);return Array.isArray(dist)?dist[0]:Number(dist)||0}let hw=componentWidth/2,hh=componentHeight/2,corners=[{x:componentCenter.x-hw,y:componentCenter.y-hh},{x:componentCenter.x+hw,y:componentCenter.y-hh},{x:componentCenter.x+hw,y:componentCenter.y+hh},{x:componentCenter.x-hw,y:componentCenter.y+hh}],midpoints=[];for(let i3=0;i3<4;i3++){let next2=(i3+1)%4;midpoints.push({x:(corners[i3].x+corners[next2].x)/2,y:(corners[i3].y+corners[next2].y)/2})}let matrix2=rotateDEG2(rotationDeg,componentCenter.x,componentCenter.y),rotatePoint5=pt3=>{let p4=applyToPoint2(matrix2,pt3);return new Point$3(p4.x,p4.y)},rotatedPoints=corners.concat(midpoints).map(rotatePoint5),maxDistance=0;for(let pt3 of rotatedPoints)if(!boardPoly.contains(pt3)){let dist=boardPoly.distanceTo(pt3),d2=Array.isArray(dist)?dist[0]:Number(dist)||0;d2>maxDistance&&(maxDistance=d2)}if(maxDistance>0)return maxDistance;try{let intersection=BooleanOperations.intersect(compPoly,boardPoly),intersectionArea=0;intersection?Array.isArray(intersection)?intersectionArea=intersection.reduce((sum,p4)=>sum+(typeof p4.area=="function"?p4.area():0),0):typeof intersection.area=="function"?intersectionArea=intersection.area():intersectionArea=0:intersectionArea=0;let compArea=compPoly.area();if(intersectionArea>0&&intersectionArea<compArea){let overlapRatio=1-intersectionArea/compArea,compWidth=Math.abs(componentWidth),compHeight=Math.abs(componentHeight);return Math.min(compWidth,compHeight)*overlapRatio}else return .1}catch{return .1}}function checkPcbComponentsOutOfBoard(circuitJson){let board=circuitJson.find(el2=>el2.type==="pcb_board");if(!board)return[];let boardPoly=boardToPolygon({board});if(!boardPoly)return[];let components=circuitJson.filter(el2=>el2.type==="pcb_component");if(components.length===0)return[];let errors=[];for(let c3 of components){if(!c3.center||typeof c3.width!="number"||typeof c3.height!="number"||c3.width<=0||c3.height<=0)continue;let compPoly=rectanglePolygon({center:c3.center,size:{width:c3.width,height:c3.height},rotationDeg:c3.rotation||0});if(compPoly.area()===0||boardPoly.contains(compPoly))continue;let overlapDistance=computeOverlapDistance(compPoly,boardPoly,c3.center,c3.width,c3.height,c3.rotation||0),compName=getComponentName({circuitJson,component:c3}),overlapDistanceMm=Math.round(overlapDistance*100)/100;errors.push({type:"pcb_component_outside_board_error",error_type:"pcb_component_outside_board_error",pcb_component_outside_board_error_id:`pcb_component_outside_board_${c3.pcb_component_id}`,message:`Component ${compName} (${c3.pcb_component_id}) extends outside board boundaries by ${overlapDistanceMm}mm`,pcb_component_id:c3.pcb_component_id,pcb_board_id:board.pcb_board_id,component_center:c3.center,component_bounds:{min_x:compPoly.box.xmin,max_x:compPoly.box.xmax,min_y:compPoly.box.ymin,max_y:compPoly.box.ymax},subcircuit_id:c3.subcircuit_id,source_component_id:c3.source_component_id})}return errors}function distance22(a3,b3){return Math.hypot(a3.x-b3.x,a3.y-b3.y)}function checkSameNetViaSpacing(circuitJson,{connMap,minSpacing=DEFAULT_SAME_NET_VIA_MARGIN}={}){let vias=circuitJson.filter(el2=>el2.type==="pcb_via");if(vias.length<2)return[];connMap??(connMap=getFullConnectivityMapFromCircuitJson(circuitJson));let errors=[],reported=new Set;for(let i3=0;i3<vias.length;i3++)for(let j3=i3+1;j3<vias.length;j3++){let viaA=vias[i3],viaB=vias[j3];if(!connMap.areIdsConnected(viaA.pcb_via_id,viaB.pcb_via_id))continue;let gap=distance22(viaA,viaB)-viaA.outer_diameter/2-viaB.outer_diameter/2;if(gap+EPSILON>=minSpacing)continue;let pairId=[viaA.pcb_via_id,viaB.pcb_via_id].sort().join("_");reported.has(pairId)||(reported.add(pairId),errors.push({type:"pcb_via_clearance_error",pcb_error_id:`same_net_vias_close_${pairId}`,message:`Vias ${getReadableNameForElement(circuitJson,viaA.pcb_via_id)} and ${getReadableNameForElement(circuitJson,viaB.pcb_via_id)} are too close together (gap: ${gap.toFixed(3)}mm)`,error_type:"pcb_via_clearance_error",pcb_via_ids:[viaA.pcb_via_id,viaB.pcb_via_id],minimum_clearance:minSpacing,actual_clearance:gap,pcb_center:{x:(viaA.x+viaB.x)/2,y:(viaA.y+viaB.y)/2}}))}return errors}function distance32(a3,b3){return Math.hypot(a3.x-b3.x,a3.y-b3.y)}function checkDifferentNetViaSpacing(circuitJson,{connMap,minSpacing=DEFAULT_DIFFERENT_NET_VIA_MARGIN}={}){let vias=circuitJson.filter(el2=>el2.type==="pcb_via");if(vias.length<2)return[];connMap??(connMap=getFullConnectivityMapFromCircuitJson(circuitJson));let errors=[],reported=new Set;for(let i3=0;i3<vias.length;i3++)for(let j3=i3+1;j3<vias.length;j3++){let viaA=vias[i3],viaB=vias[j3];if(connMap.areIdsConnected(viaA.pcb_via_id,viaB.pcb_via_id))continue;let gap=distance32(viaA,viaB)-viaA.outer_diameter/2-viaB.outer_diameter/2;if(gap+EPSILON>=minSpacing)continue;let pairId=[viaA.pcb_via_id,viaB.pcb_via_id].sort().join("_");reported.has(pairId)||(reported.add(pairId),errors.push({type:"pcb_via_clearance_error",pcb_error_id:`different_net_vias_close_${pairId}`,message:`Vias ${getReadableNameForElement(circuitJson,viaA.pcb_via_id)} and ${getReadableNameForElement(circuitJson,viaB.pcb_via_id)} from different nets are too close together (gap: ${gap.toFixed(3)}mm)`,error_type:"pcb_via_clearance_error",pcb_via_ids:[viaA.pcb_via_id,viaB.pcb_via_id],minimum_clearance:minSpacing,actual_clearance:gap,pcb_center:{x:(viaA.x+viaB.x)/2,y:(viaA.y+viaB.y)/2}}))}return errors}var DEFAULT_BOARD_MARGIN=.2;function getBoardPolygonPoints(board){if(board.outline&&board.outline.length>0)return board.outline.map(p4=>({x:p4.x,y:p4.y}));if(board.center&&typeof board.width=="number"&&typeof board.height=="number"){let cx2=board.center.x,cy2=board.center.y,hw=board.width/2,hh=board.height/2;return[{x:cx2-hw,y:cy2-hh},{x:cx2+hw,y:cy2-hh},{x:cx2+hw,y:cy2+hh},{x:cx2-hw,y:cy2+hh}]}return null}function checkPcbTracesOutOfBoard(circuitJson,config={}){let errors=[],margin=config.margin??DEFAULT_BOARD_MARGIN,board=circuitJson.find(el2=>el2.type==="pcb_board");if(!board)return errors;let boardPoints=getBoardPolygonPoints(board);if(!boardPoints)return errors;let pcbTraces=cju_default(circuitJson).pcb_trace.list();for(let trace of pcbTraces)if(!(trace.route.length<2))for(let i3=0;i3<trace.route.length-1;i3++){let p12=trace.route[i3],p22=trace.route[i3+1];if(p12.route_type!=="wire"||p22.route_type!=="wire")continue;let traceWidth="width"in p12?p12.width:"width"in p22?p22.width:.1,segmentStart={x:p12.x,y:p12.y},segmentEnd={x:p22.x,y:p22.y},minDistance=1/0;for(let j3=0;j3<boardPoints.length;j3++){let edgeStart=boardPoints[j3],edgeEnd=boardPoints[(j3+1)%boardPoints.length],distance52=segmentToSegmentMinDistance(segmentStart,segmentEnd,edgeStart,edgeEnd);distance52<minDistance&&(minDistance=distance52)}let minimumDistance=traceWidth/2+margin;if(minDistance<minimumDistance){let error={type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:`trace_too_close_to_board_${trace.pcb_trace_id}_segment_${i3}`,message:`Trace too close to board edge (${minDistance.toFixed(3)}mm < ${minimumDistance.toFixed(3)}mm required, margin: ${margin}mm)`,pcb_trace_id:trace.pcb_trace_id,source_trace_id:trace.source_trace_id||"",center:{x:(segmentStart.x+segmentEnd.x)/2,y:(segmentStart.y+segmentEnd.y)/2},pcb_component_ids:[],pcb_port_ids:[]};errors.push(error)}}return errors}function doPcbElementsOverlap(elem1,elem2){let bounds1=getBoundsOfPcbElements([elem1]),bounds2=getBoundsOfPcbElements([elem2]);return doBoundsOverlap(bounds1,bounds2)}function checkPcbComponentOverlap(circuitJson){let errors=[],connMap=getFullConnectivityMapFromCircuitJson(circuitJson),smtPads=cju_default(circuitJson).pcb_smtpad.list(),platedHoles=cju_default(circuitJson).pcb_plated_hole.list(),holes=cju_default(circuitJson).pcb_hole.list(),componentMap=new Map;for(let pad2 of smtPads){let componentId=pad2.pcb_component_id||`standalone_pad_${getPrimaryId(pad2)}`;componentMap.has(componentId)||componentMap.set(componentId,{component_id:componentId,elements:[],bounds:{minX:0,minY:0,maxX:0,maxY:0}}),componentMap.get(componentId).elements.push(pad2)}for(let hole of platedHoles){let componentId=hole.pcb_component_id||`standalone_plated_hole_${getPrimaryId(hole)}`;componentMap.has(componentId)||componentMap.set(componentId,{component_id:componentId,elements:[],bounds:{minX:0,minY:0,maxX:0,maxY:0}}),componentMap.get(componentId).elements.push(hole)}for(let hole of holes){let componentId=`standalone_hole_${getPrimaryId(hole)}`;componentMap.set(componentId,{component_id:componentId,elements:[hole],bounds:{minX:0,minY:0,maxX:0,maxY:0}})}for(let[componentId,componentData]of componentMap)componentData.elements.length>0&&(componentData.bounds=getBoundsOfPcbElements(componentData.elements));let componentsWithElements=Array.from(componentMap.values());for(let i3=0;i3<componentsWithElements.length;i3++)for(let j3=i3+1;j3<componentsWithElements.length;j3++){let comp1=componentsWithElements[i3],comp2=componentsWithElements[j3];if(doBoundsOverlap(comp1.bounds,comp2.bounds))for(let elem1 of comp1.elements)for(let elem2 of comp2.elements){let id1=getPrimaryId(elem1),id2=getPrimaryId(elem2);if(!(elem1.type==="pcb_smtpad"&&elem2.type==="pcb_smtpad"&&connMap.areIdsConnected(id1,id2))&&doPcbElementsOverlap(elem1,elem2)){let error={type:"pcb_footprint_overlap_error",pcb_error_id:`pcb_footprint_overlap_${id1}_${id2}`,error_type:"pcb_footprint_overlap_error",message:`PCB component ${elem1.type} "${id1}" overlaps with ${elem2.type} "${id2}"`};(elem1.type==="pcb_smtpad"||elem2.type==="pcb_smtpad")&&(error.pcb_smtpad_ids=[],elem1.type==="pcb_smtpad"&&error.pcb_smtpad_ids.push(id1),elem2.type==="pcb_smtpad"&&error.pcb_smtpad_ids.push(id2)),(elem1.type==="pcb_plated_hole"||elem2.type==="pcb_plated_hole")&&(error.pcb_plated_hole_ids=[],elem1.type==="pcb_plated_hole"&&error.pcb_plated_hole_ids.push(id1),elem2.type==="pcb_plated_hole"&&error.pcb_plated_hole_ids.push(id2)),(elem1.type==="pcb_hole"||elem2.type==="pcb_hole")&&(error.pcb_hole_ids=[],elem1.type==="pcb_hole"&&error.pcb_hole_ids.push(id1),elem2.type==="pcb_hole"&&error.pcb_hole_ids.push(id2)),errors.push(error)}}}return errors}function checkPinMustBeConnected(circuitJson){let errors=[],sourceComponents=circuitJson.filter(el2=>"source_component_id"in el2&&(el2.type==="source_component"||el2.type.startsWith("source_simple_"))),sourcePorts=circuitJson.filter(el2=>el2.type==="source_port"),sourceTraces=circuitJson.filter(el2=>el2.type==="source_trace"),connectedPortIds=new Set;for(let trace of sourceTraces)for(let portId of trace.connected_source_port_ids??[])connectedPortIds.add(portId);let componentInternalConnections=new Map;for(let component of sourceComponents)"internally_connected_source_port_ids"in component&&component.internally_connected_source_port_ids&&componentInternalConnections.set(component.source_component_id,component.internally_connected_source_port_ids);for(let internalGroups of componentInternalConnections.values())for(let group of internalGroups)if(group.some(portId=>connectedPortIds.has(portId)))for(let portId of group)connectedPortIds.add(portId);for(let port of sourcePorts)if(port.must_be_connected===!0&&!connectedPortIds.has(port.source_port_id)){let componentName=sourceComponents.find(c3=>c3.source_component_id===port.source_component_id)?.name??"Unknown";errors.push({type:"source_pin_must_be_connected_error",source_pin_must_be_connected_error_id:`source_pin_must_be_connected_error_${port.source_port_id}`,error_type:"source_pin_must_be_connected_error",message:`Port ${port.name} on ${componentName} must be connected but is floating`,source_component_id:port.source_component_id??"",source_port_id:port.source_port_id,subcircuit_id:port.subcircuit_id})}return errors}init_dist();init_dist();init_dist5();init_dist();init_dist2();init_dist();init_dist6();var import_react4=__toESM(require_react(),1);var import_debug18=__toESM(require_browser(),1),import_react5=__toESM(require_react(),1),import_react6=__toESM(require_react(),1);var import_jsx_runtime=__toESM(require_jsx_runtime(),1);var import_jsx_runtime2=__toESM(require_jsx_runtime(),1),import_jsx_runtime3=__toESM(require_jsx_runtime(),1);var import_jsx_runtime4=__toESM(require_jsx_runtime(),1);var import_jsx_runtime5=__toESM(require_jsx_runtime(),1);var import_jsx_runtime6=__toESM(require_jsx_runtime(),1),import_react7=__toESM(require_react(),1);var __defProp4=Object.defineProperty,__export3=(target,all)=>{for(var name in all)__defProp4(target,name,{get:all[name],enumerable:!0})},components_exports={};__export3(components_exports,{AnalogSimulation:()=>AnalogSimulation,Battery:()=>Battery,Board:()=>Board,Breakout:()=>Breakout,BreakoutPoint:()=>BreakoutPoint,CadAssembly:()=>CadAssembly,CadModel:()=>CadModel,Capacitor:()=>Capacitor,Chip:()=>Chip,Constraint:()=>Constraint3,CopperPour:()=>CopperPour,CopperText:()=>CopperText,Crystal:()=>Crystal,Cutout:()=>Cutout,Diode:()=>Diode,FabricationNoteDimension:()=>FabricationNoteDimension,FabricationNotePath:()=>FabricationNotePath,FabricationNoteRect:()=>FabricationNoteRect,FabricationNoteText:()=>FabricationNoteText,Fiducial:()=>Fiducial,Footprint:()=>Footprint,Fuse:()=>Fuse,Group:()=>Group6,Hole:()=>Hole,Inductor:()=>Inductor,Interconnect:()=>Interconnect,Jumper:()=>Jumper,Keepout:()=>Keepout,Led:()=>Led,Mosfet:()=>Mosfet,Net:()=>Net,NetLabel:()=>NetLabel,NormalComponent:()=>NormalComponent3,Panel:()=>Panel,PcbNoteDimension:()=>PcbNoteDimension,PcbNoteLine:()=>PcbNoteLine,PcbNotePath:()=>PcbNotePath,PcbNoteRect:()=>PcbNoteRect,PcbNoteText:()=>PcbNoteText,PcbTrace:()=>PcbTrace,PinHeader:()=>PinHeader,Pinout:()=>Pinout,PlatedHole:()=>PlatedHole,Port:()=>Port,Potentiometer:()=>Potentiometer,PowerSource:()=>PowerSource,PrimitiveComponent:()=>PrimitiveComponent2,PushButton:()=>PushButton,Renderable:()=>Renderable,Resistor:()=>Resistor,Resonator:()=>Resonator,SchematicArc:()=>SchematicArc,SchematicBox:()=>SchematicBox,SchematicCell:()=>SchematicCell,SchematicCircle:()=>SchematicCircle,SchematicLine:()=>SchematicLine,SchematicRect:()=>SchematicRect,SchematicRow:()=>SchematicRow,SchematicTable:()=>SchematicTable,SchematicText:()=>SchematicText,SilkscreenCircle:()=>SilkscreenCircle,SilkscreenLine:()=>SilkscreenLine,SilkscreenPath:()=>SilkscreenPath,SilkscreenRect:()=>SilkscreenRect,SilkscreenText:()=>SilkscreenText,SmtPad:()=>SmtPad,SolderJumper:()=>SolderJumper,Subcircuit:()=>Subcircuit,Switch:()=>Switch,Symbol:()=>SymbolComponent,TestPoint:()=>TestPoint,Trace:()=>Trace3,TraceHint:()=>TraceHint,Transistor:()=>Transistor,Via:()=>Via,VoltageProbe:()=>VoltageProbe,VoltageSource:()=>VoltageSource});var debug5=(0,import_debug6.default)("tscircuit:renderable"),orderedRenderPhases=["ReactSubtreesRender","InflateSubcircuitCircuitJson","SourceNameDuplicateComponentRemoval","PcbFootprintStringRender","InitializePortsFromChildren","CreateNetsFromProps","AssignFallbackProps","CreateTracesFromProps","CreateTracesFromNetLabels","CreateTraceHintsFromProps","SourceGroupRender","AssignNameToUnnamedComponents","SourceRender","SourceParentAttachment","PortMatching","OptimizeSelectorCache","SourceTraceRender","SourceAddConnectivityMapKey","SourceDesignRuleChecks","SimulationRender","SchematicComponentRender","SchematicPortRender","SchematicPrimitiveRender","SchematicComponentSizeCalculation","SchematicLayout","SchematicTraceRender","SchematicReplaceNetLabelsWithSymbols","PcbComponentRender","PcbPrimitiveRender","PcbFootprintLayout","PcbPortRender","PcbPortAttachment","PcbComponentSizeCalculation","PcbComponentAnchorAlignment","PcbLayout","PcbBoardAutoSize","PanelLayout","PcbTraceHintRender","PcbManualTraceRender","PcbTraceRender","PcbRouteNetIslands","PcbCopperPourRender","PcbDesignRuleChecks","SilkscreenOverlapAdjustment","CadModelRender","PartsEngineRender","SimulationSpiceEngineRender"],asyncPhaseDependencies={PcbFootprintLayout:["PcbFootprintStringRender"],PcbComponentSizeCalculation:["PcbFootprintStringRender"],PcbLayout:["PcbFootprintStringRender"],PcbBoardAutoSize:["PcbFootprintStringRender"],PcbTraceHintRender:["PcbFootprintStringRender"],PcbManualTraceRender:["PcbFootprintStringRender"],PcbCopperPourRender:["PcbFootprintStringRender","PcbTraceRender","PcbRouteNetIslands"],PcbTraceRender:["PcbFootprintStringRender"],PcbRouteNetIslands:["PcbFootprintStringRender"],PcbDesignRuleChecks:["PcbFootprintStringRender"],SilkscreenOverlapAdjustment:["PcbFootprintStringRender"],CadModelRender:["PcbFootprintStringRender"],PartsEngineRender:["PcbFootprintStringRender"],PcbComponentAnchorAlignment:["PcbFootprintStringRender"]},globalRenderCounter=0,Renderable=class _Renderable{constructor(props){__publicField(this,"renderPhaseStates");__publicField(this,"shouldBeRemoved",!1);__publicField(this,"children");__publicField(this,"isPcbPrimitive",!1);__publicField(this,"isSchematicPrimitive",!1);__publicField(this,"_renderId");__publicField(this,"_currentRenderPhase",null);__publicField(this,"_asyncEffects",[]);__publicField(this,"parent",null);this._renderId=`${globalRenderCounter++}`,this.children=[],this.renderPhaseStates={};for(let phase of orderedRenderPhases)this.renderPhaseStates[phase]={initialized:!1,dirty:!1}}_markDirty(phase){this.renderPhaseStates[phase].dirty=!0;let phaseIndex=orderedRenderPhases.indexOf(phase);for(let i3=phaseIndex+1;i3<orderedRenderPhases.length;i3++)this.renderPhaseStates[orderedRenderPhases[i3]].dirty=!0;this.parent?._markDirty&&this.parent._markDirty(phase)}_queueAsyncEffect(effectName,effect){let asyncEffect={promise:effect(),phase:this._currentRenderPhase,effectName,complete:!1};this._asyncEffects.push(asyncEffect),"root"in this&&this.root&&this.root.emit("asyncEffect:start",{effectName,componentDisplayName:this.getString(),phase:asyncEffect.phase}),asyncEffect.promise.then(()=>{asyncEffect.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName,componentDisplayName:this.getString(),phase:asyncEffect.phase})}).catch(error=>{console.error(`Async effect error in ${asyncEffect.phase} "${effectName}":
597
597
  ${error.stack}`),asyncEffect.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName,componentDisplayName:this.getString(),phase:asyncEffect.phase,error:error.toString()})})}_emitRenderLifecycleEvent(phase,startOrEnd){debug5(`${phase}:${startOrEnd} ${this.getString()}`);let granular_event_type=`renderable:renderLifecycle:${phase}:${startOrEnd}`,eventPayload={renderId:this._renderId,componentDisplayName:this.getString(),type:granular_event_type};"root"in this&&this.root&&(this.root.emit(granular_event_type,eventPayload),this.root.emit("renderable:renderLifecycle:anyEvent",{...eventPayload,type:granular_event_type}))}getString(){return this.constructor.name}_hasIncompleteAsyncEffects(){return this._asyncEffects.some(effect=>!effect.complete)?!0:this.children.some(child=>typeof child._hasIncompleteAsyncEffects=="function"?child._hasIncompleteAsyncEffects():!1)}_hasIncompleteAsyncEffectsInSubtreeForPhase(phase){for(let e4 of this._asyncEffects)if(!e4.complete&&e4.phase===phase)return!0;for(let child of this.children)if(child._hasIncompleteAsyncEffectsInSubtreeForPhase(phase))return!0;return!1}getCurrentRenderPhase(){return this._currentRenderPhase}getRenderGraph(){return{id:this._renderId,currentPhase:this._currentRenderPhase,renderPhaseStates:this.renderPhaseStates,shouldBeRemoved:this.shouldBeRemoved,children:this.children.map(child=>child.getRenderGraph())}}getTopLevelRenderable(){let current2=this;for(;current2.parent&&current2.parent instanceof _Renderable;)current2=current2.parent;return current2}runRenderCycle(){for(let renderPhase of orderedRenderPhases)this.runRenderPhaseForChildren(renderPhase),this.runRenderPhase(renderPhase)}runRenderPhase(phase){this._currentRenderPhase=phase;let phaseState=this.renderPhaseStates[phase],isInitialized=phaseState.initialized,isDirty2=phaseState.dirty;if(!isInitialized&&this.shouldBeRemoved)return;if(this.shouldBeRemoved&&isInitialized){this._emitRenderLifecycleEvent(phase,"start"),this?.[`remove${phase}`]?.(),phaseState.initialized=!1,phaseState.dirty=!1,this._emitRenderLifecycleEvent(phase,"end");return}let prevPhaseIndex=orderedRenderPhases.indexOf(phase)-1;if(prevPhaseIndex>=0){let prevPhase=orderedRenderPhases[prevPhaseIndex];if(this._asyncEffects.filter(e4=>e4.phase===prevPhase).some(e4=>!e4.complete))return}let deps=asyncPhaseDependencies[phase]||[];if(deps.length>0){let root=this.getTopLevelRenderable();for(let depPhase of deps)if(root._hasIncompleteAsyncEffectsInSubtreeForPhase(depPhase))return}if(this._emitRenderLifecycleEvent(phase,"start"),isInitialized){isDirty2&&(this?.[`update${phase}`]?.(),phaseState.dirty=!1),this._emitRenderLifecycleEvent(phase,"end");return}phaseState.dirty=!1,this?.[`doInitial${phase}`]?.(),phaseState.initialized=!0,this._emitRenderLifecycleEvent(phase,"end")}runRenderPhaseForChildren(phase){for(let child of this.children)child.runRenderPhaseForChildren(phase),child.runRenderPhase(phase)}renderError(message){throw typeof message=="string"?new Error(message):new Error(JSON.stringify(message,null,2))}},catalogue={},extendCatalogue=objects=>{let altKeys=Object.fromEntries(Object.entries(objects).map(([key,v4])=>[key.toLowerCase(),v4]));Object.assign(catalogue,objects),Object.assign(catalogue,altKeys)},InvalidProps=class extends Error{constructor(componentName,originalProps,formattedError){let message,propsWithError=Object.keys(formattedError).filter(k4=>k4!=="_errors"),invalidPinLabelMessages=[],pinLabels=originalProps.pinLabels;if(pinLabels)for(let[pin,labelOrLabels]of Object.entries(pinLabels)){let labels=Array.isArray(labelOrLabels)?labelOrLabels:[labelOrLabels];for(let label of labels)typeof label=="string"&&(label.startsWith(" ")||label.endsWith(" "))&&invalidPinLabelMessages.push(`pinLabels.${pin} ("${label}" has leading or trailing spaces)`)}let propMessage=propsWithError.map(k4=>k4==="pinLabels"&&invalidPinLabelMessages.length>0?invalidPinLabelMessages.join(", "):formattedError[k4]._errors[0]?`${k4} (${formattedError[k4]._errors[0]})`:`${k4} (${JSON.stringify(formattedError[k4])})`).join(", ");"name"in originalProps?message=`Invalid props for ${componentName} "${originalProps.name}": ${propMessage}`:"footprint"in originalProps&&typeof originalProps.footprint=="string"?message=`Invalid props for ${componentName} (unnamed ${originalProps.footprint} component): ${propMessage}`:message=`Invalid props for ${componentName} (unnamed): ${propMessage}`,super(message),this.componentName=componentName,this.originalProps=originalProps,this.formattedError=formattedError}};function isMatchingSelector(component,selector){let idMatch=selector.match(/^#(\w+)/);if(idMatch)return component.props.id===idMatch[1];let classMatch=selector.match(/^\.(\w+)/);if(classMatch)return component.isMatchingNameOrAlias(classMatch[1]);let[type,...conditions]=selector.split(/(?=[#.[])/);return type==="pin"&&(type="port"),type&&type!=="*"&&component.lowercaseComponentName!==type.toLowerCase()?!1:conditions.every(condition=>{if(condition.startsWith("#"))return component.props.id===condition.slice(1);if(condition.startsWith("."))return component.isMatchingNameOrAlias(condition.slice(1));let match2=condition.match(/\[(\w+)=['"]?(.+?)['"]?\]/);if(!match2)return!0;let[,prop,value]=match2;return component.props[prop].toString()===value})}var defaultUnits={mm:1};function evaluateCalcString(input2,options){let{knownVariables,units:userUnits}=options,units={...defaultUnits,...userUnits??{}},expr=extractExpression(input2),tokens=tokenize2(expr,units);return parseExpression(tokens,knownVariables)}function extractExpression(raw){let trimmed=raw.trim();if(!trimmed.toLowerCase().startsWith("calc"))return trimmed;let match2=trimmed.match(/^calc\s*\((.*)\)$/is);if(!match2)throw new Error(`Invalid calc() expression: "${raw}"`);return match2[1].trim()}function tokenize2(expr,units){let tokens=[],i3=0,isDigit=ch2=>ch2>="0"&&ch2<="9",isIdentStart=ch2=>ch2>="A"&&ch2<="Z"||ch2>="a"&&ch2<="z"||ch2==="_",isIdentChar=ch2=>isIdentStart(ch2)||isDigit(ch2)||ch2===".";for(;i3<expr.length;){let ch2=expr[i3];if(ch2===" "||ch2===" "||ch2===`
598
- `||ch2==="\r"){i3++;continue}if(isDigit(ch2)||ch2==="."&&i3+1<expr.length&&isDigit(expr[i3+1])){let start=i3;for(i3++;i3<expr.length;){let c3=expr[i3];if(isDigit(c3)||c3===".")i3++;else break}let numberText=expr.slice(start,i3),num=Number(numberText);if(Number.isNaN(num))throw new Error(`Invalid number: "${numberText}"`);let unitStart=i3;for(;i3<expr.length&&/[A-Za-z]/.test(expr[i3]);)i3++;if(i3>unitStart){let unitText=expr.slice(unitStart,i3),factor=units[unitText];if(factor==null)throw new Error(`Unknown unit: "${unitText}"`);num*=factor}tokens.push({type:"number",value:num});continue}if(isIdentStart(ch2)){let start=i3;for(i3++;i3<expr.length&&isIdentChar(expr[i3]);)i3++;let ident=expr.slice(start,i3);tokens.push({type:"identifier",value:ident});continue}if(ch2==="("||ch2===")"){tokens.push({type:"paren",value:ch2}),i3++;continue}if(ch2==="+"||ch2==="-"||ch2==="*"||ch2==="/"){tokens.push({type:"operator",value:ch2}),i3++;continue}throw new Error(`Unexpected character "${ch2}" in expression "${expr}"`)}return tokens}function parseExpression(tokens,vars){let index=0,peek=()=>tokens[index],consume=()=>tokens[index++],parsePrimary=()=>{let token=peek();if(!token)throw new Error("Unexpected end of expression");if(token.type==="number")return consume(),token.value;if(token.type==="identifier"){consume();let value=vars[token.value];if(value==null)throw new Error(`Unknown variable: "${token.value}"`);return value}if(token.type==="paren"&&token.value==="("){consume();let value=parseExpr(),next2=peek();if(!next2||next2.type!=="paren"||next2.value!==")")throw new Error('Expected ")"');return consume(),value}throw new Error(`Unexpected token "${token.value}"`)},parseFactor=()=>{let token=peek();if(token&&token.type==="operator"&&(token.value==="+"||token.value==="-")){consume();let value=parseFactor();return token.value==="+"?value:-value}return parsePrimary()},parseTerm=()=>{let value=parseFactor();for(;;){let token=peek();if(!token||token.type!=="operator"||token.value!=="*"&&token.value!=="/")break;consume();let rhs=parseFactor();token.value==="*"?value*=rhs:value/=rhs}return value},parseExpr=()=>{let value=parseTerm();for(;;){let token=peek();if(!token||token.type!=="operator"||token.value!=="+"&&token.value!=="-")break;consume();let rhs=parseTerm();token.value==="+"?value+=rhs:value-=rhs}return value},result=parseExpr();if(index<tokens.length){let leftover=tokens.slice(index).map(t6=>"value"in t6?t6.value:"?").join(" ");throw new Error(`Unexpected tokens at end of expression: ${leftover}`)}return result}var cssSelectPrimitiveComponentAdapter={isTag:node=>!0,getParent:node=>node.parent,getChildren:node=>node.children,getName:node=>node.lowercaseComponentName,getAttributeValue:(node,name)=>{if(name==="class"&&"getNameAndAliases"in node)return node.getNameAndAliases().join(" ");if(name==="name"&&node._parsedProps?.name)return node._parsedProps.name;if(node._parsedProps&&name in node._parsedProps){let value=node._parsedProps[name];return typeof value=="string"?value:value!=null?String(value):null}if(name in node){let value=node[name];return typeof value=="string"?value:value!=null?String(value):null}let reverseMap=node._attributeLowerToCamelNameMap;if(reverseMap){let camelCaseName=reverseMap[name];if(camelCaseName&&camelCaseName in node){let value=node[camelCaseName];return typeof value=="string"?value:value!=null?String(value):null}}return null},hasAttrib:(node,name)=>{if(name==="class")return!!node._parsedProps?.name;if(node._parsedProps&&name in node._parsedProps||name in node)return!0;let reverseMap=node._attributeLowerToCamelNameMap;if(reverseMap){let camelCaseName=reverseMap[name];if(camelCaseName&&camelCaseName in node)return!0}return!1},getSiblings:node=>node.parent?node.parent.children:[],prevElementSibling:node=>{if(!node.parent)return null;let siblings=node.parent.children,idx=siblings.indexOf(node);return idx>0?siblings[idx-1]:null},getText:()=>"",removeSubsets:nodes=>nodes.filter((node,i3)=>!nodes.some((other,j3)=>i3!==j3&&other!==node&&other.getDescendants().includes(node))),existsOne:(test,nodes)=>nodes.some(test),findAll:(test,nodes)=>{let result=[],recurse=node=>{test(node)&&result.push(node);for(let child of node.children)recurse(child)};for(let node of nodes)recurse(node);return result},findOne:(test,nodes)=>{for(let node of nodes){if(test(node))return node;let children=node.children;if(children.length>0){let result=cssSelectPrimitiveComponentAdapter.findOne(test,children);if(result)return result}}return null},equals:(a3,b3)=>a3._renderId===b3._renderId,isHovered:elem=>!1,isVisited:elem=>!1,isActive:elem=>!1},cssSelectPrimitiveComponentAdapterWithoutSubcircuits={...cssSelectPrimitiveComponentAdapter,getChildren:node=>node.children.filter(c3=>!c3.isSubcircuit)},cssSelectPrimitiveComponentAdapterOnlySubcircuits={...cssSelectPrimitiveComponentAdapter,getChildren:node=>node.children.filter(c3=>c3.isSubcircuit)},buildPlusMinusNetErrorMessage=(selector,component)=>{let netName=selector.split("net.")[1]?.split(/[ >]/)[0]??selector;return`Net names cannot contain "+" or "-" (component "${component?.componentName??"Unknown component"}" received "${netName}" via "${selector}"). Try using underscores instead, e.g. VCC_P`},preprocessSelector=(selector,component)=>{if(/net\.[^\s>]*\./.test(selector))throw new Error('Net names cannot contain a period, try using "sel.net..." to autocomplete with conventional net names, e.g. V3_3');if(/net\.[^\s>]*[+-]/.test(selector))throw new Error(buildPlusMinusNetErrorMessage(selector,component));if(/net\.[0-9]/.test(selector)){let match2=selector.match(/net\.([^ >]+)/),netName=match2?match2[1]:"";throw new Error(`Net name "${netName}" cannot start with a number, try using a prefix like "VBUS1"`)}return selector.replace(/ pin(?=[\d.])/g," port").replace(/ subcircuit\./g," group[isSubcircuit=true]").replace(/([^ ])\>([^ ])/g,"$1 > $2").replace(/(^|[ >])(?!pin\.)(?!port\.)(?!net\.)([A-Z][A-Za-z0-9_-]*)\.([A-Za-z0-9_-]+)/g,(_4,sep,name,pin)=>{let pinPart=/^\d+$/.test(pin)?`pin${pin}`:pin;return`${sep}.${name} > .${pinPart}`}).trim()},cssSelectOptionsInsideSubcircuit={adapter:cssSelectPrimitiveComponentAdapterWithoutSubcircuits,cacheResults:!0},PrimitiveComponent2=class extends Renderable{constructor(props){super(props);__publicField(this,"parent",null);__publicField(this,"children");__publicField(this,"childrenPendingRemoval");__publicField(this,"props");__publicField(this,"_parsedProps");__publicField(this,"externallyAddedAliases");__publicField(this,"isPrimitiveContainer",!1);__publicField(this,"canHaveTextChildren",!1);__publicField(this,"source_group_id",null);__publicField(this,"source_component_id",null);__publicField(this,"schematic_component_id",null);__publicField(this,"pcb_component_id",null);__publicField(this,"cad_component_id",null);__publicField(this,"fallbackUnassignedName");__publicField(this,"_cachedSelectAllQueries",new Map);__publicField(this,"_cachedSelectOneQueries",new Map);this.children=[],this.childrenPendingRemoval=[],this.props=props??{},this.externallyAddedAliases=[];let parsePropsResult=("partial"in this.config.zodProps?this.config.zodProps.partial({name:!0}):this.config.zodProps).safeParse(props??{});if(parsePropsResult.success)this._parsedProps=parsePropsResult.data;else throw new InvalidProps(this.lowercaseComponentName,this.props,parsePropsResult.error.format())}get config(){return{componentName:"",zodProps:external_exports.object({}).passthrough()}}get componentName(){return this.config.componentName}getInheritedProperty(propertyName){let current2=this;for(;current2;){if(current2._parsedProps&&propertyName in current2._parsedProps)return current2._parsedProps[propertyName];current2=current2.parent}if(this.root?.platform&&propertyName in this.root.platform)return this.root.platform[propertyName]}getInheritedMergedProperty(propertyName){let parentPropertyObject=this.parent?.getInheritedMergedProperty?.(propertyName),myPropertyObject=this._parsedProps?.[propertyName];return{...parentPropertyObject,...myPropertyObject}}get lowercaseComponentName(){return this.componentName.toLowerCase()}get isSubcircuit(){return!!this.props.subcircuit||this.lowercaseComponentName==="group"&&this?.parent?.isRoot}get isGroup(){return this.lowercaseComponentName==="group"}get name(){return this._parsedProps.name??this.fallbackUnassignedName}setProps(props){let newProps=this.config.zodProps.parse({...this.props,...props}),oldProps=this.props;this.props=newProps,this._parsedProps=this.config.zodProps.parse(props),this.onPropsChange({oldProps,newProps,changedProps:Object.keys(props)}),this.parent?.onChildChanged?.(this)}_getPcbRotationBeforeLayout(){let{pcbRotation}=this.props;return typeof pcbRotation=="string"?parseFloat(pcbRotation):pcbRotation??null}getResolvedPcbPositionProp(){return{pcbX:this._resolvePcbCoordinate(this._parsedProps.pcbX,"pcbX"),pcbY:this._resolvePcbCoordinate(this._parsedProps.pcbY,"pcbY")}}_resolvePcbCoordinate(rawValue,axis,options={}){if(rawValue==null)return 0;if(typeof rawValue=="number")return rawValue;if(typeof rawValue!="string")throw new Error(`Invalid ${axis} value for ${this.componentName}: ${String(rawValue)}`);let allowBoardVariables=options.allowBoardVariables??this._isNormalComponent===!0,includesBoardVariable=rawValue.includes("board."),knownVariables={};if(allowBoardVariables){let board=this._getBoard(),boardVariables=board?._getBoardCalcVariables()??{};if(includesBoardVariable&&!board)throw new Error(`Cannot resolve ${axis} for ${this.componentName}: no board found for board.* variables`);if(includesBoardVariable&&board&&Object.keys(boardVariables).length===0)throw new Error("Cannot do calculations based on board size when the board is auto-sized");Object.assign(knownVariables,boardVariables)}try{return evaluateCalcString(rawValue,{knownVariables})}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`Invalid ${axis} value for ${this.componentName}: ${message}`)}}computePcbPropsTransform(){let rotation4=this._getPcbRotationBeforeLayout()??0,{pcbX,pcbY}=this.getResolvedPcbPositionProp();return compose(translate(pcbX,pcbY),rotate(rotation4*Math.PI/180))}_computePcbGlobalTransformBeforeLayout(){let manualPlacement=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if(manualPlacement&&this.props.pcbX===void 0&&this.props.pcbY===void 0){let rotation4=this._getPcbRotationBeforeLayout()??0;return compose(this.parent?._computePcbGlobalTransformBeforeLayout()??identity(),compose(translate(manualPlacement.x,manualPlacement.y),rotate(rotation4*Math.PI/180)))}if(this.isPcbPrimitive){let primitiveContainer=this.getPrimitiveContainer();if(primitiveContainer&&primitiveContainer._parsedProps.layer==="bottom")return compose(this.parent?._computePcbGlobalTransformBeforeLayout()??identity(),flipY(),this.computePcbPropsTransform())}return compose(this.parent?._computePcbGlobalTransformBeforeLayout()??identity(),this.computePcbPropsTransform())}getPrimitiveContainer(){return this.isPrimitiveContainer?this:this.parent?.getPrimitiveContainer?.()??null}getParentNormalComponent(){let current2=this.parent;for(;current2;){if(current2.isPrimitiveContainer&&current2.doInitialPcbComponentRender)return current2;current2=current2.parent}return null}_getPcbCircuitJsonBounds(){return{center:{x:0,y:0},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getPcbPrimitiveFlippedHelpers(){let container=this.getPrimitiveContainer(),isFlipped=container?container._parsedProps.layer==="bottom":!1;return{isFlipped,maybeFlipLayer:layer=>isFlipped?layer==="top"?"bottom":"top":layer}}_setPositionFromLayout(newCenter){throw new Error(`_setPositionFromLayout not implemented for ${this.componentName}`)}computeSchematicPropsTransform(){let{_parsedProps:props}=this;return compose(translate(props.schX??0,props.schY??0))}computeSchematicGlobalTransform(){let manualPlacementTransform=this._getSchematicGlobalManualPlacementTransform(this);return manualPlacementTransform||compose(this.parent?.computeSchematicGlobalTransform?.()??identity(),this.computeSchematicPropsTransform())}_getSchematicSymbolName(){let{_parsedProps:props}=this,base_symbol_name=this.config.schematicSymbolName,orientationRotationMap={horizontal:0,pos_left:0,neg_right:0,pos_right:180,neg_left:180,pos_top:270,neg_bottom:90,vertical:270,pos_bottom:90,neg_top:90},normalizedRotation=props.schOrientation!==void 0?orientationRotationMap[props.schOrientation]:props.schRotation;if(normalizedRotation===void 0&&(normalizedRotation=0),normalizedRotation=normalizedRotation%360,normalizedRotation<0&&(normalizedRotation+=360),props.schRotation!==void 0&&normalizedRotation%90!==0)throw new Error(`Schematic rotation ${props.schRotation} is not supported for ${this.componentName}`);let symbol_name_horz=`${base_symbol_name}_horz`,symbol_name_vert=`${base_symbol_name}_vert`,symbol_name_up=`${base_symbol_name}_up`,symbol_name_down=`${base_symbol_name}_down`,symbol_name_left=`${base_symbol_name}_left`,symbol_name_right=`${base_symbol_name}_right`;if(symbol_name_right in ef&&normalizedRotation===0)return symbol_name_right;if(symbol_name_up in ef&&normalizedRotation===90)return symbol_name_up;if(symbol_name_left in ef&&normalizedRotation===180)return symbol_name_left;if(symbol_name_down in ef&&normalizedRotation===270)return symbol_name_down;if(symbol_name_horz in ef&&(normalizedRotation===0||normalizedRotation===180))return symbol_name_horz;if(symbol_name_vert in ef&&(normalizedRotation===90||normalizedRotation===270))return symbol_name_vert;if(base_symbol_name in ef)return base_symbol_name}_getSchematicSymbolNameOrThrow(){let symbol_name=this._getSchematicSymbolName();if(!symbol_name)throw new Error(`No schematic symbol found (given: "${this.config.schematicSymbolName}")`);return symbol_name}getSchematicSymbol(){let symbol_name=this._getSchematicSymbolName();return symbol_name?ef[symbol_name]??null:null}_getPcbManualPlacementForComponent(component){if(!this.isSubcircuit)return null;let manualEdits=this.props.manualEdits;if(!manualEdits)return null;let placementConfigPositions=manualEdits?.pcb_placements;if(!placementConfigPositions)return null;for(let position2 of placementConfigPositions)if(isMatchingSelector(component,position2.selector)||component.props.name===position2.selector)return applyToPoint(this._computePcbGlobalTransformBeforeLayout(),position2.center);return null}_getSchematicManualPlacementForComponent(component){if(!this.isSubcircuit)return null;let manualEdits=this.props.manualEdits;if(!manualEdits)return null;let placementConfigPositions=manualEdits.schematic_placements;if(!placementConfigPositions)return null;for(let position2 of placementConfigPositions)if(isMatchingSelector(component,position2.selector)||component.props.name===position2.selector)return applyToPoint(this.computeSchematicGlobalTransform(),position2.center);return null}_getSchematicGlobalManualPlacementTransform(component){let manualEdits=this.getSubcircuit()?._parsedProps.manualEdits;if(!manualEdits)return null;for(let position2 of manualEdits.schematic_placements??[])if((isMatchingSelector(component,position2.selector)||component.props.name===position2.selector)&&position2.relative_to==="group_center")return compose(this.parent?._computePcbGlobalTransformBeforeLayout()??identity(),translate(position2.center.x,position2.center.y));return null}_getGlobalPcbPositionBeforeLayout(){return applyToPoint(this._computePcbGlobalTransformBeforeLayout(),{x:0,y:0})}_getGlobalSchematicPositionBeforeLayout(){return applyToPoint(this.computeSchematicGlobalTransform(),{x:0,y:0})}_getBoard(){let current2=this;for(;current2;){let maybePrimitive=current2;if(maybePrimitive.componentName==="Board")return maybePrimitive;current2=current2.parent??null}return this.root?._getBoard()}get root(){return this.parent?.root??null}onAddToParent(parent){this.parent=parent}onPropsChange(params){}onChildChanged(child){this.parent?.onChildChanged?.(child)}add(component){let textContent2=component.__text;if(typeof textContent2=="string"){if(this.canHaveTextChildren||textContent2.trim()==="")return;throw new Error(`Invalid JSX Element: Expected a React component but received text "${textContent2}"`)}if(Object.keys(component).length!==0){if(component.lowercaseComponentName==="panel")throw new Error("<panel> must be a root-level element");if(!component.onAddToParent)throw new Error(`Invalid JSX Element: Expected a React component but received "${JSON.stringify(component)}"`);component.onAddToParent(this),component.parent=this,this.children.push(component)}}addAll(components){for(let component of components)this.add(component)}remove(component){this.children=this.children.filter(c3=>c3!==component),this.childrenPendingRemoval.push(component),component.shouldBeRemoved=!0}getSubcircuitSelector(){let name=this.name,endPart=name?`${this.lowercaseComponentName}.${name}`:this.lowercaseComponentName;return!this.parent||this.parent.isSubcircuit?endPart:`${this.parent.getSubcircuitSelector()} > ${endPart}`}getFullPathSelector(){let name=this.name,endPart=name?`${this.lowercaseComponentName}.${name}`:this.lowercaseComponentName,parentSelector=this.parent?.getFullPathSelector?.();return parentSelector?`${parentSelector} > ${endPart}`:endPart}getNameAndAliases(){return[this.name,...this._parsedProps.portHints??[]].filter(Boolean)}isMatchingNameOrAlias(name){return this.getNameAndAliases().includes(name)}isMatchingAnyOf(aliases2){return this.getNameAndAliases().some(a3=>aliases2.map(a22=>a22.toString()).includes(a3))}getPcbSize(){throw new Error(`getPcbSize not implemented for ${this.componentName}`)}doesSelectorMatch(selector){let myTypeNames=[this.componentName,this.lowercaseComponentName],myClassNames=[this.name].filter(Boolean),parts=selector.trim().split(/\> /)[0],firstPart=parts[0];return parts.length>1?!1:!!(selector==="*"||selector[0]==="#"&&selector.slice(1)===this.props.id||selector[0]==="."&&myClassNames.includes(selector.slice(1))||/^[a-zA-Z0-9_]/.test(firstPart)&&myTypeNames.includes(firstPart))}getSubcircuit(){if(this.isSubcircuit)return this;let group=this.parent?.getSubcircuit?.();if(!group)throw new Error("Component is not inside an opaque group (no board?)");return group}getGroup(){return this.isGroup?this:this.parent?.getGroup?.()??null}doInitialAssignNameToUnnamedComponents(){this._parsedProps.name||(this.fallbackUnassignedName=this.getSubcircuit().getNextAvailableName(this))}doInitialOptimizeSelectorCache(){if(!this.isSubcircuit)return;let ports=this.selectAll("port");for(let port of ports){let parentAliases=(port.getParentNormalComponent?.()??port.parent)?.getNameAndAliases(),portAliases=port.getNameAndAliases();if(parentAliases)for(let parentAlias of parentAliases)for(let portAlias of portAliases){let selectors=[`.${parentAlias} > .${portAlias}`,`.${parentAlias} .${portAlias}`];for(let selector of selectors){let ar2=this._cachedSelectAllQueries.get(selector);ar2?ar2.push(port):this._cachedSelectAllQueries.set(selector,[port])}}}for(let[selector,ports2]of this._cachedSelectAllQueries.entries())ports2.length===1&&this._cachedSelectOneQueries.set(selector,ports2[0])}selectAll(selectorRaw){if(this._cachedSelectAllQueries.has(selectorRaw))return this._cachedSelectAllQueries.get(selectorRaw);let selector=preprocessSelector(selectorRaw,this),result=selectAll(selector,this,cssSelectOptionsInsideSubcircuit);if(result.length>0)return this._cachedSelectAllQueries.set(selectorRaw,result),result;let[firstpart,...rest]=selector.split(" "),subcircuit=selectOne(firstpart,this,{adapter:cssSelectPrimitiveComponentAdapterOnlySubcircuits});if(!subcircuit)return[];let result2=subcircuit.selectAll(rest.join(" "));return this._cachedSelectAllQueries.set(selectorRaw,result2),result2}selectOne(selectorRaw,options){if(this._cachedSelectOneQueries.has(selectorRaw))return this._cachedSelectOneQueries.get(selectorRaw);let selector=preprocessSelector(selectorRaw,this);options?.port&&(options.type="port");let result=null;if(options?.type&&(result=selectAll(selector,this,cssSelectOptionsInsideSubcircuit).find(n3=>n3.lowercaseComponentName===options.type)),result??(result=selectOne(selector,this,cssSelectOptionsInsideSubcircuit)),result)return this._cachedSelectOneQueries.set(selectorRaw,result),result;let[firstpart,...rest]=selector.split(" "),subcircuit=selectOne(firstpart,this,{adapter:cssSelectPrimitiveComponentAdapterOnlySubcircuits});return subcircuit?(result=subcircuit.selectOne(rest.join(" "),options),this._cachedSelectOneQueries.set(selectorRaw,result),result):null}getAvailablePcbLayers(){if(this.isPcbPrimitive){let{maybeFlipLayer}=this._getPcbPrimitiveFlippedHelpers();return"layer"in this._parsedProps||this.componentName==="SmtPad"?[maybeFlipLayer(this._parsedProps.layer??"top")]:"layers"in this._parsedProps?this._parsedProps.layers:this.componentName==="PlatedHole"?[...this.root?._getBoard()?.allLayers??["top","bottom"]]:[]}return[]}getDescendants(){let descendants=[];for(let child of this.children)descendants.push(child),descendants.push(...child.getDescendants());return descendants}getSelectableDescendants(){let descendants=[];for(let child of this.children)child.isSubcircuit?descendants.push(child):(descendants.push(child),descendants.push(...child.getSelectableDescendants()));return descendants}_getPinCount(){return 0}_getSchematicBoxDimensions(){return null}_getSchematicBoxComponentDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;let{_parsedProps:props}=this;return{schWidth:props.schWidth,schHeight:props.schHeight}}renderError(message){if(typeof message=="string")return super.renderError(message);switch(message.type){case"pcb_placement_error":this.root?.db.pcb_placement_error.insert(message);break;case"pcb_via_clearance_error":this.root?.db.pcb_via_clearance_error.insert(message);break;case"pcb_trace_error":this.root?.db.pcb_trace_error.insert(message);break;case"pcb_manual_edit_conflict_warning":this.root?.db.pcb_manual_edit_conflict_warning.insert(message);break;default:this.root?.db.pcb_placement_error.insert(message)}}getString(){let{lowercaseComponentName:cname,_parsedProps:props,parent}=this;return props?.pinNumber!==void 0&&parent?.props?.name&&props?.name?`<${cname}#${this._renderId}(pin:${props.pinNumber} .${parent?.props.name}>.${props.name}) />`:parent?.props?.name&&props?.name?`<${cname}#${this._renderId}(.${parent?.props.name}>.${props?.name}) />`:props?.from&&props?.to?`<${cname}#${this._renderId}(from:${props.from} to:${props?.to}) />`:props?.name?`<${cname}#${this._renderId} name=".${props?.name}" />`:props?.portHints?`<${cname}#${this._renderId}(${props.portHints.map(ph2=>`.${ph2}`).join(", ")}) />`:`<${cname}#${this._renderId} />`}get[Symbol.toStringTag](){return this.getString()}[Symbol.for("nodejs.util.inspect.custom")](){return this.getString()}},ErrorPlaceholderComponent=class extends PrimitiveComponent2{constructor(props,error){super(props);let resolveCoordinate=(value,axis)=>{if(typeof value=="number")return value;if(typeof value=="string")try{return this._resolvePcbCoordinate(value,axis,{allowBoardVariables:!1})}catch{return 0}return 0};this._parsedProps={...props,error,type:props.type||"unknown",component_name:props.name,error_type:"source_failed_to_create_component_error",message:error instanceof Error?error.message:String(error),pcbX:resolveCoordinate(props.pcbX,"pcbX"),pcbY:resolveCoordinate(props.pcbY,"pcbY"),schX:props.schX,schY:props.schY}}get config(){return{componentName:"ErrorPlaceholder",zodProps:external_exports.object({}).passthrough()}}doInitialSourceRender(){if(this.root?.db){let pcbPosition2=this._getGlobalPcbPositionBeforeLayout(),schematicPosition=this._getGlobalSchematicPositionBeforeLayout();this.root.db.source_failed_to_create_component_error.insert({component_name:this._parsedProps.component_name,error_type:"source_failed_to_create_component_error",message:`Could not create ${this._parsedProps.componentType??"component"}${this._parsedProps.name?` "${this._parsedProps.name}"`:""}. ${this._parsedProps.error?.formattedError?._errors?.join("; ")||this._parsedProps.message}`,pcb_center:pcbPosition2,schematic_center:schematicPosition})}}};function createErrorPlaceholderComponent(props,error){return new ErrorPlaceholderComponent(props,error)}function prepare(object,state2){let instance=object;return instance.__tsci={...state2},object}var hostConfig={supportsMutation:!0,createInstance(type,props){let target=catalogue[type];if(!target)throw Object.keys(catalogue).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 "${type}". No element with this name is registered in the @tscircuit/core catalogue. Check for typos or see https://docs.tscircuit.com/category/built-in-elements for a list of valid components. To add your own component, see docs/CREATING_NEW_COMPONENTS.md`);try{return prepare(new target(props),{})}catch(error){return createErrorPlaceholderComponent({...props,componentType:type},error)}},createTextInstance(text){return{__text:text}},appendInitialChild(parentInstance,child){parentInstance.add(child)},appendChild(parentInstance,child){parentInstance.add(child)},appendChildToContainer(container,child){container.add(child)},finalizeInitialChildren(){return!1},prepareUpdate(){return null},shouldSetTextContent(){return!1},getRootHostContext(){return{}},getChildHostContext(){return{}},prepareForCommit(){return null},resetAfterCommit(){},commitMount(){},commitUpdate(){},removeChild(){},clearContainer(){},supportsPersistence:!1,getPublicInstance(instance){return instance},preparePortalMount(containerInfo){throw new Error("Function not implemented.")},scheduleTimeout(fn3,delay){throw new Error("Function not implemented.")},cancelTimeout(id){throw new Error("Function not implemented.")},noTimeout:void 0,isPrimaryRenderer:!1,getInstanceFromNode(node){throw new Error("Function not implemented.")},beforeActiveInstanceBlur(){throw new Error("Function not implemented.")},afterActiveInstanceBlur(){throw new Error("Function not implemented.")},prepareScopeUpdate:(scopeInstance,instance)=>{throw new Error("Function not implemented.")},getInstanceFromScope:scopeInstance=>{throw new Error("Function not implemented.")},detachDeletedInstance:node=>{throw new Error("Function not implemented.")},getCurrentEventPriority:()=>import_constants.DefaultEventPriority,getCurrentUpdatePriority:()=>import_constants.DefaultEventPriority,resolveUpdatePriority:()=>import_constants.DefaultEventPriority,setCurrentUpdatePriority:()=>{},maySuspendCommit:()=>!1,supportsHydration:!1},reconciler=(0,import_react_reconciler.default)(hostConfig),createInstanceFromReactElement=reactElm=>{let rootContainer={children:[],props:{name:"$root"},add(instance){instance.parent=this,this.children.push(instance)},computePcbGlobalTransform(){return identity()}},containerErrors=[],container=reconciler.createContainer(rootContainer,0,null,!1,null,"tsci",error=>{console.log("Error in createContainer"),console.error(error),containerErrors.push(error)},null);if(reconciler.updateContainerSync(reactElm,container,null,()=>{}),reconciler.flushSyncWork(),containerErrors.length>0)throw containerErrors[0];let rootInstance=reconciler.getPublicRootInstance(container);return rootInstance||rootContainer.children[0]},parsePinNumberFromLabelsOrThrow=(pinNumberOrLabel,pinLabels)=>{if(typeof pinNumberOrLabel=="number")return pinNumberOrLabel;if(pinNumberOrLabel.startsWith("pin"))return Number(pinNumberOrLabel.slice(3));if(!pinLabels)throw new Error(`No pin labels provided and pin number or label is not a number: "${pinNumberOrLabel}"`);for(let pinNumberKey in pinLabels)if((Array.isArray(pinLabels[pinNumberKey])?pinLabels[pinNumberKey]:[pinLabels[pinNumberKey]]).includes(pinNumberOrLabel))return Number(pinNumberKey.replace("pin",""));throw new Error(`No pin labels provided and pin number or label is not a number: "${pinNumberOrLabel}"`)},underscorifyPinStyles=(pinStyles,pinLabels)=>{if(!pinStyles)return;let underscorePinStyles={},mergedStyles={};for(let[pinNameOrLabel,pinStyle]of Object.entries(pinStyles)){let pinNumber=parsePinNumberFromLabelsOrThrow(pinNameOrLabel,pinLabels);mergedStyles[pinNumber]={...mergedStyles[pinNumber],...pinStyle}}for(let[pinNumber,pinStyle]of Object.entries(mergedStyles)){let pinKey=`pin${pinNumber}`;underscorePinStyles[pinKey]={bottom_margin:pinStyle.bottomMargin,left_margin:pinStyle.leftMargin,right_margin:pinStyle.rightMargin,top_margin:pinStyle.topMargin}}return underscorePinStyles},underscorifyPortArrangement=portArrangement=>{if(portArrangement){if("leftSide"in portArrangement||"rightSide"in portArrangement||"topSide"in portArrangement||"bottomSide"in portArrangement)return{left_side:portArrangement.leftSide,right_side:portArrangement.rightSide,top_side:portArrangement.topSide,bottom_side:portArrangement.bottomSide};if("leftPinCount"in portArrangement||"rightPinCount"in portArrangement||"topPinCount"in portArrangement||"bottomPinCount"in portArrangement)return{left_size:portArrangement.leftPinCount,right_size:portArrangement.rightPinCount,top_size:portArrangement.topPinCount,bottom_size:portArrangement.bottomPinCount};if("leftSize"in portArrangement||"rightSize"in portArrangement||"topSize"in portArrangement||"bottomSize"in portArrangement)return{left_size:portArrangement.leftSize,right_size:portArrangement.rightSize,top_size:portArrangement.topSize,bottom_size:portArrangement.bottomSize}}};function pairs2(arr){let result=[];for(let i3=0;i3<arr.length-1;i3++)result.push([arr[i3],arr[i3+1]]);return result}var netProps2=external_exports.object({name:external_exports.string().refine(val=>!/[+-]/.test(val),val=>({message:`Net names cannot contain "+" or "-" (component "Net" received "${val}"). Try using underscores instead, e.g. VCC_P`}))}),Net=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"source_net_id");__publicField(this,"subcircuit_connectivity_map_key",null)}get config(){return{componentName:"Net",zodProps:netProps2}}getPortSelector(){return`net.${this.props.name}`}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,isGround=props.name.startsWith("GND"),isPositiveVoltageSource=props.name.startsWith("V"),net=db.source_net.insert({name:props.name,member_source_group_ids:[],is_ground:isGround,is_power:isPositiveVoltageSource,is_positive_voltage_source:isPositiveVoltageSource});this.source_net_id=net.source_net_id}doInitialSourceParentAttachment(){let subcircuit=this.getSubcircuit();if(!subcircuit)return;let{db}=this.root;db.source_net.update(this.source_net_id,{subcircuit_id:subcircuit.subcircuit_id})}getAllConnectedPorts(){let allPorts=this.getSubcircuit().selectAll("port"),connectedPorts=[];for(let port of allPorts){let traces=port._getDirectlyConnectedTraces();for(let trace of traces)if(trace._isExplicitlyConnectedToNet(this)){connectedPorts.push(port);break}}return connectedPorts}_getAllDirectlyConnectedTraces(){let allTraces=this.getSubcircuit().selectAll("trace"),connectedTraces=[];for(let trace of allTraces)trace._isExplicitlyConnectedToNet(this)&&connectedTraces.push(trace);return connectedTraces}doInitialPcbRouteNetIslands(){if(this.root?.pcbDisabled||this.getSubcircuit()._parsedProps.routingDisabled||this.getSubcircuit()._getAutorouterConfig().groupMode!=="sequential-trace")return;let{db}=this.root,{_parsedProps:props}=this,traces=this._getAllDirectlyConnectedTraces().filter(trace=>(trace._portsRoutedOnPcb?.length??0)>0),islands=[];for(let trace of traces){let tracePorts=trace._portsRoutedOnPcb,traceIsland=islands.find(island=>tracePorts.some(port=>island.ports.includes(port)));if(!traceIsland){islands.push({ports:[...tracePorts],traces:[trace]});continue}traceIsland.traces.push(trace),traceIsland.ports.push(...tracePorts)}if(islands.length===0)return;let islandPairs=pairs2(islands);for(let[A4,B4]of islandPairs){let Apositions=A4.ports.map(port=>port._getGlobalPcbPositionBeforeLayout()),Bpositions=B4.ports.map(port=>port._getGlobalPcbPositionBeforeLayout()),closestDist=1/0,closestPair=[-1,-1];for(let i3=0;i3<Apositions.length;i3++){let Apos=Apositions[i3];for(let j3=0;j3<Bpositions.length;j3++){let Bpos=Bpositions[j3],dist=Math.sqrt((Apos.x-Bpos.x)**2+(Apos.y-Bpos.y)**2);dist<closestDist&&(closestDist=dist,closestPair=[i3,j3])}}let Aport=A4.ports[closestPair[0]],Bport=B4.ports[closestPair[1]],pcbElements=db.toArray().filter(elm=>elm.type==="pcb_smtpad"||elm.type==="pcb_trace"||elm.type==="pcb_plated_hole"||elm.type==="pcb_hole"||elm.type==="source_port"||elm.type==="pcb_port"),{solution}=autoroute2(pcbElements.concat([{type:"source_trace",source_trace_id:"__net_trace_tmp",connected_source_port_ids:[Aport.source_port_id,Bport.source_port_id]}])),trace=solution[0];if(!trace){this.renderError({pcb_trace_error_id:"",pcb_trace_id:"__net_trace_tmp",pcb_component_ids:[Aport.pcb_component_id,Bport.pcb_component_id].filter(Boolean),pcb_port_ids:[Aport.pcb_port_id,Bport.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}db.pcb_trace.insert(trace)}}renderError(message){if(typeof message=="string")return super.renderError(message);this.root?.db.pcb_trace_error.insert(message)}},createNetsFromProps=(component,props)=>{for(let prop of props)if(typeof prop=="string"&&prop.startsWith("net.")){if(/net\.[^\s>]*\./.test(prop))throw new Error('Net names cannot contain a period, try using "sel.net..." to autocomplete with conventional net names, e.g. V3_3');if(/net\.[^\s>]*[+-]/.test(prop)){let netName=prop.split("net.")[1],message=`Net names cannot contain "+" or "-" (component "${component.componentName}" received "${netName}" via "${prop}"). Try using underscores instead, e.g. VCC_P`;throw new Error(message)}if(/net\.[0-9]/.test(prop)){let netName=prop.split("net.")[1];throw new Error(`Net name "${netName}" cannot start with a number, try using a prefix like "VBUS1"`)}let subcircuit=component.getSubcircuit();if(!subcircuit.selectOne(prop)){let net=new Net({name:prop.split("net.")[1]});subcircuit.add(net)}}},SmtPad=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"pcb_smtpad_id",null);__publicField(this,"matchedPort",null);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SmtPad",zodProps:smtPadProps}}getPcbSize(){let{_parsedProps:props}=this;if(props.shape==="circle")return{width:props.radius*2,height:props.radius*2};if(props.shape==="rect")return{width:props.width,height:props.height};if(props.shape==="rotated_rect"){let angleRad=(props.ccwRotation??0)*Math.PI/180,cosAngle=Math.cos(angleRad),sinAngle=Math.sin(angleRad),width=Math.abs(props.width*cosAngle)+Math.abs(props.height*sinAngle),height=Math.abs(props.width*sinAngle)+Math.abs(props.height*cosAngle);return{width,height}}if(props.shape==="polygon"){let points=props.points,xs3=points.map(p4=>p4.x),ys3=points.map(p4=>p4.y),minX=Math.min(...xs3),maxX=Math.max(...xs3),minY=Math.min(...ys3),maxY=Math.max(...ys3);return{width:maxX-minX,height:maxY-minY}}if(props.shape==="pill")return{width:props.width,height:props.height};throw new Error(`getPcbSize for shape "${props.shape}" not implemented for ${this.componentName}`)}doInitialPortMatching(){let parentPorts=this.getPrimitiveContainer()?.selectAll("port");if(this.props.portHints){for(let port of parentPorts)if(port.isMatchingAnyOf(this.props.portHints)){this.matchedPort=port,port.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,isCoveredWithSolderMask=props.coveredWithSolderMask??!1,shouldCreateSolderPaste=!isCoveredWithSolderMask,soldermaskMargin=props.solderMaskMargin,subcircuit=this.getSubcircuit(),position2=this._getGlobalPcbPositionBeforeLayout(),globalTransform=this._computePcbGlobalTransformBeforeLayout(),normalizedRotationDegrees=(decomposeTSR(this._computePcbGlobalTransformBeforeLayout()).rotation.angle*180/Math.PI%360+360)%360,rotationTolerance=.01,isAxisAligned=Math.abs(normalizedRotationDegrees)<rotationTolerance||Math.abs(normalizedRotationDegrees-180)<rotationTolerance||Math.abs(normalizedRotationDegrees-360)<rotationTolerance,isRotated90Degrees=Math.abs(normalizedRotationDegrees-90)<rotationTolerance||Math.abs(normalizedRotationDegrees-270)<rotationTolerance,finalRotationDegrees=Math.abs(normalizedRotationDegrees-360)<rotationTolerance?0:normalizedRotationDegrees,transformRotationBeforeFlip=finalRotationDegrees,{maybeFlipLayer,isFlipped}=this._getPcbPrimitiveFlippedHelpers();isFlipped&&(finalRotationDegrees=(360-finalRotationDegrees+360)%360);let portHints2=props.portHints?.map(ph2=>ph2.toString())??[],pcb_smtpad2=null,pcb_component_id=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id;if(props.shape==="circle")pcb_smtpad2=db.pcb_smtpad.insert({pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,layer:maybeFlipLayer(props.layer??"top"),shape:"circle",radius:props.radius,port_hints:portHints2,is_covered_with_solder_mask:isCoveredWithSolderMask,soldermask_margin:soldermaskMargin,x:position2.x,y:position2.y,subcircuit_id:subcircuit?.subcircuit_id??void 0}),shouldCreateSolderPaste&&db.pcb_solder_paste.insert({layer:pcb_smtpad2.layer,shape:"circle",radius:pcb_smtpad2.radius*.7,x:pcb_smtpad2.x,y:pcb_smtpad2.y,pcb_component_id:pcb_smtpad2.pcb_component_id,pcb_smtpad_id:pcb_smtpad2.pcb_smtpad_id,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});else if(props.shape==="rect")!isAxisAligned&&!isRotated90Degrees?pcb_smtpad2=db.pcb_smtpad.insert({pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,layer:maybeFlipLayer(props.layer??"top"),shape:"rotated_rect",width:props.width,height:props.height,corner_radius:props.cornerRadius??void 0,x:position2.x,y:position2.y,ccw_rotation:finalRotationDegrees,port_hints:portHints2,is_covered_with_solder_mask:isCoveredWithSolderMask,soldermask_margin:soldermaskMargin,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):pcb_smtpad2=db.pcb_smtpad.insert({pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,layer:maybeFlipLayer(props.layer??"top"),shape:"rect",width:isRotated90Degrees?props.height:props.width,height:isRotated90Degrees?props.width:props.height,corner_radius:props.cornerRadius??void 0,port_hints:portHints2,is_covered_with_solder_mask:isCoveredWithSolderMask,soldermask_margin:soldermaskMargin,x:position2.x,y:position2.y,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),shouldCreateSolderPaste&&(pcb_smtpad2.shape==="rect"?db.pcb_solder_paste.insert({layer:maybeFlipLayer(props.layer??"top"),shape:"rect",width:pcb_smtpad2.width*.7,height:pcb_smtpad2.height*.7,x:pcb_smtpad2.x,y:pcb_smtpad2.y,pcb_component_id:pcb_smtpad2.pcb_component_id,pcb_smtpad_id:pcb_smtpad2.pcb_smtpad_id,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):pcb_smtpad2.shape==="rotated_rect"&&db.pcb_solder_paste.insert({layer:maybeFlipLayer(props.layer??"top"),shape:"rotated_rect",width:pcb_smtpad2.width*.7,height:pcb_smtpad2.height*.7,x:pcb_smtpad2.x,y:pcb_smtpad2.y,ccw_rotation:pcb_smtpad2.ccw_rotation,pcb_component_id:pcb_smtpad2.pcb_component_id,pcb_smtpad_id:pcb_smtpad2.pcb_smtpad_id,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}));else if(props.shape==="rotated_rect"){let baseRotation=props.ccwRotation??0,combinedRotationBeforeFlip=(transformRotationBeforeFlip+baseRotation+360)%360,padRotation=isFlipped?(360-combinedRotationBeforeFlip+360)%360:combinedRotationBeforeFlip;pcb_smtpad2=db.pcb_smtpad.insert({pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,layer:maybeFlipLayer(props.layer??"top"),shape:"rotated_rect",width:props.width,height:props.height,corner_radius:props.cornerRadius??void 0,x:position2.x,y:position2.y,ccw_rotation:padRotation,port_hints:portHints2,is_covered_with_solder_mask:isCoveredWithSolderMask,soldermask_margin:soldermaskMargin,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),shouldCreateSolderPaste&&db.pcb_solder_paste.insert({layer:maybeFlipLayer(props.layer??"top"),shape:"rotated_rect",width:pcb_smtpad2.width*.7,height:pcb_smtpad2.height*.7,x:position2.x,y:position2.y,ccw_rotation:padRotation,pcb_component_id,pcb_smtpad_id:pcb_smtpad2.pcb_smtpad_id,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(props.shape==="polygon"){let transformedPoints=props.points.map(point23=>{let transformed=applyToPoint(globalTransform,{x:distance.parse(point23.x),y:distance.parse(point23.y)});return{x:transformed.x,y:transformed.y}});pcb_smtpad2=db.pcb_smtpad.insert({pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,layer:maybeFlipLayer(props.layer??"top"),shape:"polygon",points:transformedPoints,port_hints:portHints2,is_covered_with_solder_mask:isCoveredWithSolderMask,soldermask_margin:soldermaskMargin,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else props.shape==="pill"&&(pcb_smtpad2=db.pcb_smtpad.insert({pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,layer:maybeFlipLayer(props.layer??"top"),shape:"pill",x:position2.x,y:position2.y,radius:props.radius,height:props.height,width:props.width,port_hints:portHints2,is_covered_with_solder_mask:isCoveredWithSolderMask,soldermask_margin:soldermaskMargin,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}));pcb_smtpad2&&(this.pcb_smtpad_id=pcb_smtpad2.pcb_smtpad_id)}doInitialPcbPortAttachment(){if(this.root?.pcbDisabled)return;let{db}=this.root;db.pcb_smtpad.update(this.pcb_smtpad_id,{pcb_port_id:this.matchedPort?.pcb_port_id})}_getPcbCircuitJsonBounds(){let{db}=this.root,smtpad2=db.pcb_smtpad.get(this.pcb_smtpad_id);if(smtpad2.shape==="rect")return{center:{x:smtpad2.x,y:smtpad2.y},bounds:{left:smtpad2.x-smtpad2.width/2,top:smtpad2.y+smtpad2.height/2,right:smtpad2.x+smtpad2.width/2,bottom:smtpad2.y-smtpad2.height/2},width:smtpad2.width,height:smtpad2.height};if(smtpad2.shape==="rotated_rect"){let angleRad=smtpad2.ccw_rotation*Math.PI/180,cosAngle=Math.cos(angleRad),sinAngle=Math.sin(angleRad),w22=smtpad2.width/2,h22=smtpad2.height/2,xExtent=Math.abs(w22*cosAngle)+Math.abs(h22*sinAngle),yExtent=Math.abs(w22*sinAngle)+Math.abs(h22*cosAngle);return{center:{x:smtpad2.x,y:smtpad2.y},bounds:{left:smtpad2.x-xExtent,right:smtpad2.x+xExtent,top:smtpad2.y-yExtent,bottom:smtpad2.y+yExtent},width:xExtent*2,height:yExtent*2}}if(smtpad2.shape==="circle")return{center:{x:smtpad2.x,y:smtpad2.y},bounds:{left:smtpad2.x-smtpad2.radius,top:smtpad2.y-smtpad2.radius,right:smtpad2.x+smtpad2.radius,bottom:smtpad2.y+smtpad2.radius},width:smtpad2.radius*2,height:smtpad2.radius*2};if(smtpad2.shape==="polygon"){let points=smtpad2.points,xs3=points.map(p4=>p4.x),ys3=points.map(p4=>p4.y),minX=Math.min(...xs3),maxX=Math.max(...xs3),minY=Math.min(...ys3),maxY=Math.max(...ys3);return{center:{x:(minX+maxX)/2,y:(minY+maxY)/2},bounds:{left:minX,top:maxY,right:maxX,bottom:minY},width:maxX-minX,height:maxY-minY}}if(smtpad2.shape==="pill"){let halfWidth=smtpad2.width/2,halfHeight=smtpad2.height/2;return{center:{x:smtpad2.x,y:smtpad2.y},bounds:{left:smtpad2.x-halfWidth,top:smtpad2.y-halfHeight,right:smtpad2.x+halfWidth,bottom:smtpad2.y+halfHeight},width:smtpad2.width,height:smtpad2.height}}throw new Error(`circuitJson bounds calculation not implemented for shape "${smtpad2.shape}"`)}_setPositionFromLayout(newCenter){let{db}=this.root;db.pcb_smtpad.update(this.pcb_smtpad_id,{x:newCenter.x,y:newCenter.y});let solderPaste=db.pcb_solder_paste.list().find(elm=>elm.pcb_smtpad_id===this.pcb_smtpad_id);solderPaste&&db.pcb_solder_paste.update(solderPaste.pcb_solder_paste_id,{x:newCenter.x,y:newCenter.y}),this.matchedPort?._setPositionFromLayout(newCenter)}},SilkscreenPath=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"pcb_silkscreen_path_id",null);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenPath",zodProps:silkscreenPathProps}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,{maybeFlipLayer}=this._getPcbPrimitiveFlippedHelpers(),layer=maybeFlipLayer(props.layer??"top");if(layer!=="top"&&layer!=="bottom")throw new Error(`Invalid layer "${layer}" for SilkscreenPath. Must be "top" or "bottom".`);let transform5=this._computePcbGlobalTransformBeforeLayout(),subcircuit=this.getSubcircuit(),pcb_component_id=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,pcb_silkscreen_path2=db.pcb_silkscreen_path.insert({pcb_component_id,layer,route:props.route.map(p4=>{let transformedPosition=applyToPoint(transform5,{x:p4.x,y:p4.y});return{...p4,x:transformedPosition.x,y:transformedPosition.y}}),stroke_width:props.strokeWidth??.1,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_path_id=pcb_silkscreen_path2.pcb_silkscreen_path_id}_setPositionFromLayout(newCenter){let{db}=this.root,{_parsedProps:props}=this,currentPath=db.pcb_silkscreen_path.get(this.pcb_silkscreen_path_id);if(!currentPath)return;let currentCenterX=0,currentCenterY=0;for(let point23 of currentPath.route)currentCenterX+=point23.x,currentCenterY+=point23.y;currentCenterX/=currentPath.route.length,currentCenterY/=currentPath.route.length;let offsetX=newCenter.x-currentCenterX,offsetY=newCenter.y-currentCenterY,newRoute=currentPath.route.map(point23=>({...point23,x:point23.x+offsetX,y:point23.y+offsetY}));db.pcb_silkscreen_path.update(this.pcb_silkscreen_path_id,{route:newRoute})}getPcbSize(){let{_parsedProps:props}=this;if(!props.route||props.route.length===0)return{width:0,height:0};let minX=1/0,maxX=-1/0,minY=1/0,maxY=-1/0;for(let point23 of props.route)minX=Math.min(minX,point23.x),maxX=Math.max(maxX,point23.x),minY=Math.min(minY,point23.y),maxY=Math.max(maxY,point23.y);return{width:maxX-minX,height:maxY-minY}}},pcbTraceProps2=external_exports.object({route:external_exports.array(pcb_trace_route_point),source_trace_id:external_exports.string().optional()}),PcbTrace=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"pcb_trace_id",null);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbTrace",zodProps:pcbTraceProps2}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,container=this.getPrimitiveContainer(),subcircuit=this.getSubcircuit(),{maybeFlipLayer}=this._getPcbPrimitiveFlippedHelpers(),parentTransform=this._computePcbGlobalTransformBeforeLayout(),transformedRoute=props.route.map(point23=>{let{x:x3,y:y3,...restOfPoint}=point23,transformedPoint=applyToPoint(parentTransform,{x:x3,y:y3});return point23.route_type==="wire"&&point23.layer?{...transformedPoint,...restOfPoint,layer:maybeFlipLayer(point23.layer)}:{...transformedPoint,...restOfPoint}}),pcb_trace2=db.pcb_trace.insert({pcb_component_id:container.pcb_component_id,source_trace_id:props.source_trace_id,route:transformedRoute,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_trace_id=pcb_trace2.pcb_trace_id}getPcbSize(){let{_parsedProps:props}=this;if(!props.route||props.route.length===0)return{width:0,height:0};let minX=1/0,maxX=-1/0,minY=1/0,maxY=-1/0;for(let point23 of props.route)minX=Math.min(minX,point23.x),maxX=Math.max(maxX,point23.x),minY=Math.min(minY,point23.y),maxY=Math.max(maxY,point23.y),point23.route_type==="wire"&&(minX=Math.min(minX,point23.x-point23.width/2),maxX=Math.max(maxX,point23.x+point23.width/2),minY=Math.min(minY,point23.y-point23.width/2),maxY=Math.max(maxY,point23.y+point23.width/2));return minX===1/0||maxX===-1/0||minY===1/0||maxY===-1/0?{width:0,height:0}:{width:maxX-minX,height:maxY-minY}}},PlatedHole=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"pcb_plated_hole_id",null);__publicField(this,"matchedPort",null);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PlatedHole",zodProps:platedHoleProps}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){let{_parsedProps:props}=this;if(props.shape==="circle")return{width:props.outerDiameter,height:props.outerDiameter};if(props.shape==="oval"||props.shape==="pill")return{width:props.outerWidth,height:props.outerHeight};if(props.shape==="circular_hole_with_rect_pad")return{width:props.rectPadWidth,height:props.rectPadHeight};if(props.shape==="pill_hole_with_rect_pad")return{width:props.rectPadWidth,height:props.rectPadHeight};if(props.shape==="hole_with_polygon_pad"){if(!props.padOutline||props.padOutline.length===0)throw new Error("padOutline is required for hole_with_polygon_pad shape");let xs3=props.padOutline.map(p4=>typeof p4.x=="number"?p4.x:parseFloat(String(p4.x))),ys3=props.padOutline.map(p4=>typeof p4.y=="number"?p4.y:parseFloat(String(p4.y))),minX=Math.min(...xs3),maxX=Math.max(...xs3),minY=Math.min(...ys3),maxY=Math.max(...ys3);return{width:maxX-minX,height:maxY-minY}}throw new Error(`getPcbSize for shape "${props.shape}" not implemented for ${this.componentName}`)}_getPcbCircuitJsonBounds(){let{db}=this.root,platedHole=db.pcb_plated_hole.get(this.pcb_plated_hole_id),size2=this.getPcbSize();return{center:{x:platedHole.x,y:platedHole.y},bounds:{left:platedHole.x-size2.width/2,top:platedHole.y+size2.height/2,right:platedHole.x+size2.width/2,bottom:platedHole.y-size2.height/2},width:size2.width,height:size2.height}}_setPositionFromLayout(newCenter){let{db}=this.root;db.pcb_plated_hole.update(this.pcb_plated_hole_id,{x:newCenter.x,y:newCenter.y}),this.matchedPort?._setPositionFromLayout(newCenter)}doInitialPortMatching(){let parentPorts=this.getPrimitiveContainer()?.selectAll("port");if(this.props.portHints){for(let port of parentPorts)if(port.isMatchingAnyOf(this.props.portHints)){this.matchedPort=port,port.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,position2=this._getGlobalPcbPositionBeforeLayout(),pcb_component_id=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,subcircuit=this.getSubcircuit(),soldermaskMargin=props.solderMaskMargin,isCoveredWithSolderMask=props.coveredWithSolderMask??!1;if(props.shape==="circle"){let pcb_plated_hole2=db.pcb_plated_hole.insert({pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,outer_diameter:props.outerDiameter,hole_diameter:props.holeDiameter,shape:"circle",port_hints:this.getNameAndAliases(),x:position2.x,y:position2.y,layers:["top","bottom"],soldermask_margin:soldermaskMargin,is_covered_with_solder_mask:isCoveredWithSolderMask,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=pcb_plated_hole2.pcb_plated_hole_id,db.pcb_solder_paste.insert({layer:"top",shape:"circle",radius:props.outerDiameter/2,x:position2.x,y:position2.y,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),db.pcb_solder_paste.insert({layer:"bottom",shape:"circle",radius:props.outerDiameter/2,x:position2.x,y:position2.y,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(props.shape==="pill"&&props.rectPad){let pcb_plated_hole2=db.pcb_plated_hole.insert({pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:props.outerWidth,outer_height:props.outerHeight,hole_width:props.holeWidth,hole_height:props.holeHeight,shape:"rotated_pill_hole_with_rect_pad",type:"pcb_plated_hole",port_hints:this.getNameAndAliases(),pcb_plated_hole_id:this.pcb_plated_hole_id,x:position2.x,y:position2.y,layers:["top","bottom"],soldermask_margin:soldermaskMargin,is_covered_with_solder_mask:isCoveredWithSolderMask,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_shape:"rotated_pill",pad_shape:"rect",hole_ccw_rotation:props.pcbRotation??0,rect_ccw_rotation:props.pcbRotation??0,rect_pad_width:props.outerWidth,rect_pad_height:props.outerHeight,hole_offset_x:props.holeOffsetX,hole_offset_y:props.holeOffsetY});this.pcb_plated_hole_id=pcb_plated_hole2.pcb_plated_hole_id}else if(props.shape==="pill"||props.shape==="oval"){let pcb_plated_hole2=db.pcb_plated_hole.insert({pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:props.outerWidth,outer_height:props.outerHeight,hole_width:props.holeWidth,hole_height:props.holeHeight,shape:props.shape,port_hints:this.getNameAndAliases(),x:position2.x,y:position2.y,layers:["top","bottom"],soldermask_margin:soldermaskMargin,is_covered_with_solder_mask:isCoveredWithSolderMask,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,ccw_rotation:props.pcbRotation??0});this.pcb_plated_hole_id=pcb_plated_hole2.pcb_plated_hole_id,db.pcb_solder_paste.insert({layer:"top",shape:props.shape,width:props.outerWidth,height:props.outerHeight,x:position2.x,y:position2.y,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),db.pcb_solder_paste.insert({layer:"bottom",shape:props.shape,width:props.outerWidth,height:props.outerHeight,x:position2.x,y:position2.y,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(props.shape==="circular_hole_with_rect_pad"){let pcb_plated_hole2=db.pcb_plated_hole.insert({pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,hole_diameter:props.holeDiameter,rect_pad_width:props.rectPadWidth,rect_pad_height:props.rectPadHeight,shape:"circular_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:position2.x,y:position2.y,layers:["top","bottom"],soldermask_margin:soldermaskMargin,is_covered_with_solder_mask:isCoveredWithSolderMask,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_offset_x:props.holeOffsetX,hole_offset_y:props.holeOffsetY,rect_border_radius:props.rectBorderRadius??0});this.pcb_plated_hole_id=pcb_plated_hole2.pcb_plated_hole_id}else if(props.shape==="pill_hole_with_rect_pad"){let pcb_plated_hole2=db.pcb_plated_hole.insert({pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,hole_width:props.holeWidth,hole_height:props.holeHeight,rect_pad_width:props.rectPadWidth,rect_pad_height:props.rectPadHeight,hole_offset_x:props.holeOffsetX,hole_offset_y:props.holeOffsetY,shape:"pill_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:position2.x,y:position2.y,layers:["top","bottom"],soldermask_margin:soldermaskMargin,is_covered_with_solder_mask:isCoveredWithSolderMask,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=pcb_plated_hole2.pcb_plated_hole_id}else if(props.shape==="hole_with_polygon_pad"){let padOutline=(props.padOutline||[]).map(point23=>{let x3=typeof point23.x=="number"?point23.x:parseFloat(String(point23.x)),y3=typeof point23.y=="number"?point23.y:parseFloat(String(point23.y));return{x:x3,y:y3}}),pcb_plated_hole2=db.pcb_plated_hole.insert({pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,shape:"hole_with_polygon_pad",hole_shape:props.holeShape||"circle",hole_diameter:props.holeDiameter,hole_width:props.holeWidth,hole_height:props.holeHeight,pad_outline:padOutline,hole_offset_x:typeof props.holeOffsetX=="number"?props.holeOffsetX:parseFloat(String(props.holeOffsetX||0)),hole_offset_y:typeof props.holeOffsetY=="number"?props.holeOffsetY:parseFloat(String(props.holeOffsetY||0)),port_hints:this.getNameAndAliases(),x:position2.x,y:position2.y,layers:["top","bottom"],soldermask_margin:soldermaskMargin,is_covered_with_solder_mask:isCoveredWithSolderMask,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=pcb_plated_hole2.pcb_plated_hole_id}}doInitialPcbPortAttachment(){if(this.root?.pcbDisabled)return;let{db}=this.root;db.pcb_plated_hole.update(this.pcb_plated_hole_id,{pcb_port_id:this.matchedPort?.pcb_port_id})}},Keepout=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"pcb_keepout_id",null);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Keepout",zodProps:pcbKeepoutProps}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let subcircuit=this.getSubcircuit(),{db}=this.root,{_parsedProps:props}=this,position2=this._getGlobalPcbPositionBeforeLayout(),decomposedMat=decomposeTSR(this._computePcbGlobalTransformBeforeLayout()),isRotated90=Math.abs(decomposedMat.rotation.angle*(180/Math.PI)-90)%180<.01,pcb_keepout2=null;props.shape==="circle"?pcb_keepout2=db.pcb_keepout.insert({layers:["top"],shape:"circle",radius:props.radius,center:{x:position2.x,y:position2.y},subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:subcircuit?.getGroup()?.pcb_group_id??void 0}):props.shape==="rect"&&(pcb_keepout2=db.pcb_keepout.insert({layers:["top"],shape:"rect",...isRotated90?{width:props.height,height:props.width}:{width:props.width,height:props.height},center:{x:position2.x,y:position2.y},subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:subcircuit?.getGroup()?.pcb_group_id??void 0})),pcb_keepout2&&(this.pcb_keepout_id=pcb_keepout2.pcb_keepout_id)}},Hole=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"pcb_hole_id",null);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Hole",zodProps:holeProps}}getPcbSize(){let{_parsedProps:props}=this,isPill=props.shape==="pill",isRect=props.shape==="rect";return isPill?{width:props.width,height:props.height}:isRect?{width:props.width,height:props.height}:{width:props.diameter,height:props.diameter}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,subcircuit=this.getSubcircuit(),position2=this._getGlobalPcbPositionBeforeLayout(),soldermaskMargin=props.solderMaskMargin,isCoveredWithSolderMask=props.coveredWithSolderMask??!1,pcb_component_id=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id;if(props.shape==="pill")if(props.pcbRotation&&props.pcbRotation!==0){let inserted_hole=db.pcb_hole.insert({pcb_component_id,type:"pcb_hole",hole_shape:"rotated_pill",hole_width:props.width,hole_height:props.height,x:position2.x,y:position2.y,ccw_rotation:props.pcbRotation,soldermask_margin:soldermaskMargin,is_covered_with_solder_mask:isCoveredWithSolderMask,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:subcircuit?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=inserted_hole.pcb_hole_id}else{let inserted_hole=db.pcb_hole.insert({pcb_component_id,type:"pcb_hole",hole_shape:"pill",hole_width:props.width,hole_height:props.height,x:position2.x,y:position2.y,soldermask_margin:soldermaskMargin,is_covered_with_solder_mask:isCoveredWithSolderMask,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:subcircuit?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=inserted_hole.pcb_hole_id}else if(props.shape==="rect"){let inserted_hole=db.pcb_hole.insert({pcb_component_id,type:"pcb_hole",hole_shape:"rect",hole_width:props.width,hole_height:props.height,x:position2.x,y:position2.y,soldermask_margin:soldermaskMargin,is_covered_with_solder_mask:isCoveredWithSolderMask,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:subcircuit?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=inserted_hole.pcb_hole_id}else{let inserted_hole=db.pcb_hole.insert({pcb_component_id,type:"pcb_hole",hole_shape:"circle",hole_diameter:props.diameter,x:position2.x,y:position2.y,soldermask_margin:soldermaskMargin,is_covered_with_solder_mask:isCoveredWithSolderMask,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:subcircuit?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=inserted_hole.pcb_hole_id}}_getPcbCircuitJsonBounds(){let{db}=this.root,hole=db.pcb_hole.get(this.pcb_hole_id),size2=this.getPcbSize();return{center:{x:hole.x,y:hole.y},bounds:{left:hole.x-size2.width/2,top:hole.y-size2.height/2,right:hole.x+size2.width/2,bottom:hole.y+size2.height/2},width:size2.width,height:size2.height}}_setPositionFromLayout(newCenter){let{db}=this.root;db.pcb_hole.update(this.pcb_hole_id,{x:newCenter.x,y:newCenter.y})}};function normalizeTextForCircuitJson(text){return text.replace(/\\n/g,`
599
- `)}var SilkscreenText=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenText",zodProps:silkscreenTextProps}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,container=this.getPrimitiveContainer(),position2=this._getGlobalPcbPositionBeforeLayout(),{maybeFlipLayer,isFlipped}=this._getPcbPrimitiveFlippedHelpers(),subcircuit=this.getSubcircuit(),rotation4=0;if(props.pcbRotation!==void 0&&props.pcbRotation!==0)rotation4=props.pcbRotation;else{let globalTransform=this._computePcbGlobalTransformBeforeLayout();rotation4=decomposeTSR(globalTransform).rotation.angle*180/Math.PI}isFlipped&&(rotation4=(rotation4+180)%360);let uniqueLayers=new Set(props.layers);props.layer&&uniqueLayers.add(props.layer);let targetLayers=uniqueLayers.size>0?Array.from(uniqueLayers):["top"],fontSize=props.fontSize??this.getInheritedProperty("pcbStyle")?.silkscreenFontSize??1;for(let layer of targetLayers)db.pcb_silkscreen_text.insert({anchor_alignment:props.anchorAlignment,anchor_position:{x:position2.x,y:position2.y},font:props.font??"tscircuit2024",font_size:fontSize,layer:maybeFlipLayer(layer),text:normalizeTextForCircuitJson(props.text??""),ccw_rotation:rotation4,pcb_component_id:container.pcb_component_id,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}getPcbSize(){let{_parsedProps:props}=this,fontSize=props.fontSize??this.getInheritedProperty("pcbStyle")?.silkscreenFontSize??1,textWidth=(props.text??"").length*fontSize,textHeight=fontSize;return{width:textWidth*fontSize,height:textHeight*fontSize}}},Cutout=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"pcb_cutout_id",null);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Cutout",zodProps:cutoutProps}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,subcircuit=this.getSubcircuit(),pcb_group_id=this.getGroup()?.pcb_group_id??void 0,globalPosition=this._getGlobalPcbPositionBeforeLayout(),parentRotation=this.getPrimitiveContainer()?._parsedProps.pcbRotation??0,inserted_pcb_cutout;if(props.shape==="rect"){let rotationDeg=typeof parentRotation=="string"?parseInt(parentRotation.replace("deg",""),10):parentRotation,isRotated90=Math.abs(rotationDeg%180)===90,rectData={shape:"rect",center:globalPosition,width:isRotated90?props.height:props.width,height:isRotated90?props.width:props.height,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id};inserted_pcb_cutout=db.pcb_cutout.insert(rectData)}else if(props.shape==="circle"){let circleData={shape:"circle",center:globalPosition,radius:props.radius,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id};inserted_pcb_cutout=db.pcb_cutout.insert(circleData)}else if(props.shape==="polygon"){let transform5=this._computePcbGlobalTransformBeforeLayout(),polygonData={shape:"polygon",points:props.points.map(p4=>applyToPoint(transform5,p4)),subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id};inserted_pcb_cutout=db.pcb_cutout.insert(polygonData)}inserted_pcb_cutout&&(this.pcb_cutout_id=inserted_pcb_cutout.pcb_cutout_id)}getPcbSize(){let{_parsedProps:props}=this;if(props.shape==="rect")return{width:props.width,height:props.height};if(props.shape==="circle")return{width:props.radius*2,height:props.radius*2};if(props.shape==="polygon"){if(props.points.length===0)return{width:0,height:0};let minX=1/0,maxX=-1/0,minY=1/0,maxY=-1/0;for(let point23 of props.points)minX=Math.min(minX,point23.x),maxX=Math.max(maxX,point23.x),minY=Math.min(minY,point23.y),maxY=Math.max(maxY,point23.y);return{width:maxX-minX,height:maxY-minY}}return{width:0,height:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_cutout_id)return super._getPcbCircuitJsonBounds();let{db}=this.root,cutout=db.pcb_cutout.get(this.pcb_cutout_id);if(!cutout)return super._getPcbCircuitJsonBounds();if(cutout.shape==="rect")return{center:cutout.center,bounds:{left:cutout.center.x-cutout.width/2,top:cutout.center.y+cutout.height/2,right:cutout.center.x+cutout.width/2,bottom:cutout.center.y-cutout.height/2},width:cutout.width,height:cutout.height};if(cutout.shape==="circle")return{center:cutout.center,bounds:{left:cutout.center.x-cutout.radius,top:cutout.center.y+cutout.radius,right:cutout.center.x+cutout.radius,bottom:cutout.center.y-cutout.radius},width:cutout.radius*2,height:cutout.radius*2};if(cutout.shape==="polygon"){if(cutout.points.length===0)return super._getPcbCircuitJsonBounds();let minX=1/0,maxX=-1/0,minY=1/0,maxY=-1/0;for(let point23 of cutout.points)minX=Math.min(minX,point23.x),maxX=Math.max(maxX,point23.x),minY=Math.min(minY,point23.y),maxY=Math.max(maxY,point23.y);return{center:{x:(minX+maxX)/2,y:(minY+maxY)/2},bounds:{left:minX,top:maxY,right:maxX,bottom:minY},width:maxX-minX,height:maxY-minY}}return super._getPcbCircuitJsonBounds()}_setPositionFromLayout(newCenter){if(!this.pcb_cutout_id)return;let{db}=this.root,cutout=db.pcb_cutout.get(this.pcb_cutout_id);if(cutout){if(cutout.shape==="rect"||cutout.shape==="circle")db.pcb_cutout.update(this.pcb_cutout_id,{...cutout,center:newCenter});else if(cutout.shape==="polygon"){let oldCenter=this._getPcbCircuitJsonBounds().center,dx2=newCenter.x-oldCenter.x,dy2=newCenter.y-oldCenter.y,newPoints=cutout.points.map(p4=>({x:p4.x+dx2,y:p4.y+dy2}));db.pcb_cutout.update(this.pcb_cutout_id,{...cutout,points:newPoints})}}}},createPinrowSilkscreenText=({elm,pinLabels,layer,readableRotation,anchorAlignment})=>{let pinNum=elm.text.replace(/[{}]/g,"").toLowerCase(),label=pinNum;if(Array.isArray(pinLabels)){let index=parseInt(pinNum.replace(/[^\d]/g,""),10)-1;label=String(pinLabels[index]??pinNum)}else typeof pinLabels=="object"&&(label=String(pinLabels[pinNum]??pinNum));return new SilkscreenText({anchorAlignment:anchorAlignment||"center",text:label??pinNum,layer:layer||"top",fontSize:elm.font_size+.2,pcbX:isNaN(elm.anchor_position.x)?0:elm.anchor_position.x,pcbY:elm.anchor_position.y,pcbRotation:readableRotation??0})},calculateCcwRotation=(componentRotationStr,elementCcwRotation)=>{let componentAngle=parseInt(componentRotationStr||"0",10),totalRotation;return elementCcwRotation!=null?totalRotation=elementCcwRotation-componentAngle:totalRotation=componentAngle,(totalRotation%360+360)%360},createComponentsFromCircuitJson=({componentName,componentRotation,footprinterString,pinLabels,pcbPinLabels},circuitJson)=>{let components=[];for(let elm of circuitJson)if(elm.type==="pcb_smtpad"&&elm.shape==="rect")components.push(new SmtPad({pcbX:elm.x,pcbY:elm.y,layer:elm.layer,shape:"rect",height:elm.height,width:elm.width,portHints:elm.port_hints,rectBorderRadius:elm.rect_border_radius}));else if(elm.type==="pcb_smtpad"&&elm.shape==="circle")components.push(new SmtPad({pcbX:elm.x,pcbY:elm.y,layer:elm.layer,shape:"circle",radius:elm.radius,portHints:elm.port_hints}));else if(elm.type==="pcb_smtpad"&&elm.shape==="pill")components.push(new SmtPad({shape:"pill",height:elm.height,width:elm.width,radius:elm.radius,portHints:elm.port_hints,pcbX:elm.x,pcbY:elm.y,layer:elm.layer}));else if(elm.type==="pcb_silkscreen_path")components.push(new SilkscreenPath({layer:elm.layer,route:elm.route,strokeWidth:elm.stroke_width}));else if(elm.type==="pcb_plated_hole")elm.shape==="circle"?components.push(new PlatedHole({pcbX:elm.x,pcbY:elm.y,shape:"circle",holeDiameter:elm.hole_diameter,outerDiameter:elm.outer_diameter,portHints:elm.port_hints})):elm.shape==="circular_hole_with_rect_pad"?components.push(new PlatedHole({pcbX:elm.x,pcbY:elm.y,shape:"circular_hole_with_rect_pad",holeDiameter:elm.hole_diameter,rectPadHeight:elm.rect_pad_height,rectPadWidth:elm.rect_pad_width,portHints:elm.port_hints,rectBorderRadius:elm.rect_border_radius,holeOffsetX:elm.hole_offset_x,holeOffsetY:elm.hole_offset_y})):elm.shape==="pill"||elm.shape==="oval"?components.push(new PlatedHole({pcbX:elm.x,pcbY:elm.y,shape:elm.shape,holeWidth:elm.hole_width,holeHeight:elm.hole_height,outerWidth:elm.outer_width,outerHeight:elm.outer_height,portHints:elm.port_hints})):elm.shape==="pill_hole_with_rect_pad"?components.push(new PlatedHole({pcbX:elm.x,pcbY:elm.y,shape:"pill_hole_with_rect_pad",holeShape:"pill",padShape:"rect",holeWidth:elm.hole_width,holeHeight:elm.hole_height,rectPadWidth:elm.rect_pad_width,rectPadHeight:elm.rect_pad_height,portHints:elm.port_hints,holeOffsetX:elm.hole_offset_x,holeOffsetY:elm.hole_offset_y})):elm.shape==="hole_with_polygon_pad"&&components.push(new PlatedHole({pcbX:elm.x,pcbY:elm.y,shape:"hole_with_polygon_pad",holeShape:elm.hole_shape||"circle",holeDiameter:elm.hole_diameter,holeWidth:elm.hole_width,holeHeight:elm.hole_height,padOutline:elm.pad_outline||[],holeOffsetX:elm.hole_offset_x,holeOffsetY:elm.hole_offset_y,portHints:elm.port_hints}));else if(elm.type==="pcb_keepout"&&elm.shape==="circle")components.push(new Keepout({pcbX:elm.center.x,pcbY:elm.center.y,shape:"circle",radius:elm.radius}));else if(elm.type==="pcb_keepout"&&elm.shape==="rect")components.push(new Keepout({pcbX:elm.center.x,pcbY:elm.center.y,shape:"rect",width:elm.width,height:elm.height}));else if(elm.type==="pcb_hole"&&elm.hole_shape==="circle")components.push(new Hole({pcbX:elm.x,pcbY:elm.y,diameter:elm.hole_diameter}));else if(elm.type==="pcb_hole"&&elm.hole_shape==="rect")components.push(new Hole({pcbX:elm.x,pcbY:elm.y,shape:"rect",width:elm.hole_width,height:elm.hole_height}));else if(elm.type==="pcb_hole"&&elm.hole_shape==="pill")components.push(new Hole({pcbX:elm.x,pcbY:elm.y,shape:"pill",width:elm.hole_width,height:elm.hole_height}));else if(elm.type==="pcb_hole"&&elm.hole_shape==="rotated_pill")components.push(new Hole({pcbX:elm.x,pcbY:elm.y,shape:"pill",width:elm.hole_width,height:elm.hole_height,pcbRotation:elm.ccw_rotation}));else if(elm.type==="pcb_cutout")elm.shape==="rect"?components.push(new Cutout({pcbX:elm.center.x,pcbY:elm.center.y,shape:"rect",width:elm.width,height:elm.height})):elm.shape==="circle"?components.push(new Cutout({pcbX:elm.center.x,pcbY:elm.center.y,shape:"circle",radius:elm.radius})):elm.shape==="polygon"&&components.push(new Cutout({shape:"polygon",points:elm.points}));else if(elm.type==="pcb_silkscreen_text"){let ccwRotation=calculateCcwRotation(componentRotation,elm.ccw_rotation);footprinterString?.includes("pinrow")&&elm.text.includes("PIN")?components.push(createPinrowSilkscreenText({elm,pinLabels:pcbPinLabels??pinLabels??{},layer:elm.layer,readableRotation:ccwRotation,anchorAlignment:elm.anchor_alignment})):components.push(new SilkscreenText({anchorAlignment:elm.anchor_alignment||"center",text:componentName||elm.text,fontSize:elm.font_size+.2,pcbX:Number.isNaN(elm.anchor_position.x)?0:elm.anchor_position.x,pcbY:elm.anchor_position.y,pcbRotation:ccwRotation??0}))}else elm.type==="pcb_trace"&&components.push(new PcbTrace({route:elm.route}));return components};function getBoundsOfPcbComponents(components){let minX=1/0,minY=1/0,maxX=-1/0,maxY=-1/0,hasValidComponents=!1;for(let child of components)if(child.isPcbPrimitive&&!child.componentName.startsWith("Silkscreen")){let{x:x3,y:y3}=child._getGlobalPcbPositionBeforeLayout(),{width:width2,height:height2}=child.getPcbSize();minX=Math.min(minX,x3-width2/2),minY=Math.min(minY,y3-height2/2),maxX=Math.max(maxX,x3+width2/2),maxY=Math.max(maxY,y3+height2/2),hasValidComponents=!0}else if(child.children.length>0){let childBounds=getBoundsOfPcbComponents(child.children);(childBounds.width>0||childBounds.height>0)&&(minX=Math.min(minX,childBounds.minX),minY=Math.min(minY,childBounds.minY),maxX=Math.max(maxX,childBounds.maxX),maxY=Math.max(maxY,childBounds.maxY),hasValidComponents=!0)}if(!hasValidComponents)return{minX:0,minY:0,maxX:0,maxY:0,width:0,height:0};let width=maxX-minX,height=maxY-minY;return width<0&&(width=0),height<0&&(height=0),{minX,minY,maxX,maxY,width,height}}function normalizeAngle(angle){let normalized=angle%360;return normalized<0?normalized+360:normalized}function isAngleBetween(angle,start,end,direction2){return direction2==="counterclockwise"?end>=start?angle>=start&&angle<=end:angle>=start||angle<=end:end<=start?angle<=start&&angle>=end:angle<=start||angle>=end}function getArcBounds(elm){let center2=elm.center,radius=elm.radius,startAngle=elm.start_angle_degrees,endAngle=elm.end_angle_degrees,direction2=elm.direction??"counterclockwise";if(!center2||typeof center2.x!="number"||typeof center2.y!="number"||typeof radius!="number"||typeof startAngle!="number"||typeof endAngle!="number")return null;let start=normalizeAngle(startAngle),end=normalizeAngle(endAngle),consideredAngles=new Set([start,end]),cardinalAngles=[0,90,180,270];for(let cardinal of cardinalAngles)isAngleBetween(cardinal,start,end,direction2)&&consideredAngles.add(cardinal);let minX=1/0,minY=1/0,maxX=-1/0,maxY=-1/0;for(let angle of consideredAngles){let radians=angle*Math.PI/180,x3=center2.x+radius*Math.cos(radians),y3=center2.y+radius*Math.sin(radians);minX=Math.min(minX,x3),maxX=Math.max(maxX,x3),minY=Math.min(minY,y3),maxY=Math.max(maxY,y3)}return!Number.isFinite(minX)||!Number.isFinite(minY)?null:{minX,maxX,minY,maxY}}function getBoundsForSchematic(db){let minX=1/0,minY=1/0,maxX=-1/0,maxY=-1/0;for(let elm of db){let cx2,cy2,w4,h3;if(elm.type==="schematic_component")cx2=elm.center?.x,cy2=elm.center?.y,w4=elm.size?.width,h3=elm.size?.height;else if(elm.type==="schematic_box")cx2=elm.x,cy2=elm.y,w4=elm.width,h3=elm.height;else if(elm.type==="schematic_port")cx2=elm.center?.x,cy2=elm.center?.y,w4=.2,h3=.2;else if(elm.type==="schematic_text")cx2=elm.position?.x,cy2=elm.position?.y,w4=(elm.text?.length??0)*.1,h3=.2;else if(elm.type==="schematic_line"){let x12=elm.x1??0,y12=elm.y1??0,x22=elm.x2??0,y22=elm.y2??0;cx2=(x12+x22)/2,cy2=(y12+y22)/2,w4=Math.abs(x22-x12),h3=Math.abs(y22-y12)}else if(elm.type==="schematic_rect")cx2=elm.center?.x,cy2=elm.center?.y,w4=elm.width,h3=elm.height;else if(elm.type==="schematic_circle"){cx2=elm.center?.x,cy2=elm.center?.y;let radius=elm.radius;typeof radius=="number"&&(w4=radius*2,h3=radius*2)}else if(elm.type==="schematic_arc"){let bounds=getArcBounds(elm);bounds&&(minX=Math.min(minX,bounds.minX),maxX=Math.max(maxX,bounds.maxX),minY=Math.min(minY,bounds.minY),maxY=Math.max(maxY,bounds.maxY));continue}typeof cx2=="number"&&typeof cy2=="number"&&typeof w4=="number"&&typeof h3=="number"&&(minX=Math.min(minX,cx2-w4/2),maxX=Math.max(maxX,cx2+w4/2),minY=Math.min(minY,cy2-h3/2),maxY=Math.max(maxY,cy2+h3/2))}return{minX,maxX,minY,maxY}}function getRelativeDirection(pointA,pointB){let dx2=pointB.x-pointA.x,dy2=pointB.y-pointA.y;return Math.abs(dx2)>Math.abs(dy2)?dx2>=0?"right":"left":dy2>=0?"up":"down"}var areAllPcbPrimitivesOverlapping=pcbPrimitives=>{if(pcbPrimitives.length<=1)return!0;let bounds=pcbPrimitives.map(p4=>{let circuitBounds=p4._getPcbCircuitJsonBounds();return{left:circuitBounds.bounds.left,right:circuitBounds.bounds.right,top:circuitBounds.bounds.top,bottom:circuitBounds.bounds.bottom}}),overlaps=Array(bounds.length).fill(!1).map(()=>Array(bounds.length).fill(!1));for(let i3=0;i3<bounds.length;i3++)for(let j3=i3+1;j3<bounds.length;j3++){let a3=bounds[i3],b3=bounds[j3];overlaps[i3][j3]=overlaps[j3][i3]=!(a3.right<b3.left||a3.left>b3.right||a3.bottom>b3.top||a3.top<b3.bottom)}let visited=new Set,dfs=node=>{visited.add(node);for(let i3=0;i3<bounds.length;i3++)overlaps[node][i3]&&!visited.has(i3)&&dfs(i3)};return dfs(0),visited.size===bounds.length},getCenterOfPcbPrimitives=pcbPrimitives=>{if(pcbPrimitives.length===0)throw new Error("Cannot get center of empty PCB primitives array");let positions=pcbPrimitives.map(p4=>p4._getPcbCircuitJsonBounds().center).filter(Boolean),sumX=positions.reduce((sum,pos)=>sum+pos.x,0),sumY=positions.reduce((sum,pos)=>sum+pos.y,0);return{x:sumX/positions.length,y:sumY/positions.length}},portProps2=external_exports.object({name:external_exports.string().optional(),pinNumber:external_exports.number().optional(),aliases:external_exports.array(external_exports.string()).optional(),layer:external_exports.string().optional(),layers:external_exports.array(external_exports.string()).optional(),schX:external_exports.number().optional(),schY:external_exports.number().optional(),direction:external_exports.enum(["up","down","left","right"]).optional(),connectsTo:external_exports.union([external_exports.string(),external_exports.array(external_exports.string())]).optional()}),Port=class extends PrimitiveComponent2{constructor(props,opts={}){if(!props.name&&props.pinNumber!==void 0&&(props.name=`pin${props.pinNumber}`),!props.name)throw new Error("Port must have a name or a pinNumber");super(props);__publicField(this,"source_port_id",null);__publicField(this,"pcb_port_id",null);__publicField(this,"schematic_port_id",null);__publicField(this,"schematicSymbolPortDef",null);__publicField(this,"matchedComponents");__publicField(this,"facingDirection",null);__publicField(this,"originDescription",null);opts.originDescription&&(this.originDescription=opts.originDescription),this.matchedComponents=[]}get config(){return{componentName:"Port",zodProps:portProps2}}isGroupPort(){return this.parent?.componentName==="Group"}isComponentPort(){return!this.isGroupPort()}_getConnectedPortsFromConnectsTo(){let{_parsedProps:props}=this,connectsTo=props.connectsTo;if(!connectsTo)return[];let connectedPorts=[],connectsToArray=Array.isArray(connectsTo)?connectsTo:[connectsTo];for(let connection of connectsToArray){let port=this.getSubcircuit().selectOne(connection,{type:"port"});port&&connectedPorts.push(port)}return connectedPorts}_isBoardPinoutFromAttributes(){let parent=this.parent;if(parent?._parsedProps?.pinAttributes){let pinAttributes=parent._parsedProps.pinAttributes;for(let alias of this.getNameAndAliases())if(pinAttributes[alias]?.includeInBoardPinout)return!0}}_getGlobalPcbPositionBeforeLayout(){let matchedPcbElm=this.matchedComponents.find(c3=>c3.isPcbPrimitive),parentComponent=this.parent;if(parentComponent&&!parentComponent.props.footprint)throw new Error(`${parentComponent.componentName} "${parentComponent.props.name}" does not have a footprint. Add a footprint prop, e.g. <${parentComponent.componentName.toLowerCase()} footprint="..." />`);if(!matchedPcbElm)throw new Error(`Port ${this} has no matching PCB primitives. This often means the footprint's pads lack matching port hints.`);return matchedPcbElm?._getGlobalPcbPositionBeforeLayout()??{x:0,y:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_port_id)return super._getPcbCircuitJsonBounds();let{db}=this.root,pcb_port2=db.pcb_port.get(this.pcb_port_id);return{center:{x:pcb_port2.x,y:pcb_port2.y},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getGlobalPcbPositionAfterLayout(){return this._getPcbCircuitJsonBounds().center}_getPortsInternallyConnectedToThisPort(){let parent=this.parent;if(!parent||!parent._getInternallyConnectedPins)return[];let internallyConnectedPorts=parent._getInternallyConnectedPins();for(let ports of internallyConnectedPorts)if(ports.some(port=>port===this))return ports;return[]}_hasSchematicPort(){let{schX,schY}=this._parsedProps;if(schX!==void 0&&schY!==void 0)return!0;let parentNormalComponent=this.getParentNormalComponent();if(parentNormalComponent?.getSchematicSymbol())return!!(this.schematicSymbolPortDef||this._getPortsInternallyConnectedToThisPort().some(p4=>p4.schematicSymbolPortDef));let parentBoxDim=parentNormalComponent?._getSchematicBoxDimensions();return!!(parentBoxDim&&this.props.pinNumber!==void 0&&parentBoxDim.getPortPositionByPinNumber(this.props.pinNumber))}_getGlobalSchematicPositionBeforeLayout(){let{schX,schY}=this._parsedProps;if(schX!==void 0&&schY!==void 0)return{x:schX,y:schY};let parentNormalComponent=this.getParentNormalComponent(),symbol=parentNormalComponent?.getSchematicSymbol();if(symbol){let schematicSymbolPortDef=this.schematicSymbolPortDef;if(!schematicSymbolPortDef&&(schematicSymbolPortDef=this._getPortsInternallyConnectedToThisPort().find(p4=>p4.schematicSymbolPortDef)?.schematicSymbolPortDef??null,!schematicSymbolPortDef))throw new Error(`Couldn't find schematicSymbolPortDef for port ${this.getString()}, searched internally connected ports and none had a schematicSymbolPortDef. Why are we trying to get the schematic position of this port?`);let transform5=compose(parentNormalComponent.computeSchematicGlobalTransform(),translate(-symbol.center.x,-symbol.center.y));return applyToPoint(transform5,schematicSymbolPortDef)}let parentBoxDim=parentNormalComponent?._getSchematicBoxDimensions();if(parentBoxDim&&this.props.pinNumber!==void 0){let localPortPosition=parentBoxDim.getPortPositionByPinNumber(this.props.pinNumber);if(!localPortPosition)throw new Error(`Couldn't find position for schematic_port for port ${this.getString()} inside of the schematic box`);return applyToPoint(parentNormalComponent.computeSchematicGlobalTransform(),localPortPosition)}throw new Error(`Couldn't find position for schematic_port for port ${this.getString()}`)}_getGlobalSchematicPositionAfterLayout(){let{db}=this.root;if(!this.schematic_port_id)throw new Error(`Can't get schematic port position after layout for "${this.getString()}", no schematic_port_id`);let schematic_port2=db.schematic_port.get(this.schematic_port_id);if(!schematic_port2)throw new Error(`Schematic port not found when trying to get post-layout position: ${this.schematic_port_id}`);return schematic_port2.center}registerMatch(component){this.matchedComponents.push(component)}getNameAndAliases(){let{_parsedProps:props}=this;return Array.from(new Set([...props.name?[props.name]:[],...props.aliases??[],...typeof props.pinNumber=="number"?[`pin${props.pinNumber}`,props.pinNumber.toString()]:[],...this.externallyAddedAliases??[]]))}_getMatchingPinAttributes(){let pinAttributes=this.parent?._parsedProps?.pinAttributes;if(!pinAttributes)return[];let matches=[];for(let alias of this.getNameAndAliases()){let attributes2=pinAttributes[alias];attributes2&&matches.push(attributes2)}return matches}_shouldIncludeInBoardPinout(){return this._getMatchingPinAttributes().some(attributes2=>attributes2.includeInBoardPinout===!0)}isMatchingPort(port){return this.isMatchingAnyOf(port.getNameAndAliases())}getPortSelector(){return`.${(this.getParentNormalComponent()??this.parent)?.props.name} > port.${this.props.name}`}getAvailablePcbLayers(){let{layer,layers}=this._parsedProps;return layers||(layer?[layer]:Array.from(new Set(this.matchedComponents.flatMap(c3=>c3.getAvailablePcbLayers()))))}_getDirectlyConnectedTraces(){return this.getSubcircuit().selectAll("trace").filter(trace=>!trace._couldNotFindPort).filter(trace=>trace._isExplicitlyConnectedToPort(this))}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,port_hints=this.getNameAndAliases(),parentNormalComponent=this.getParentNormalComponent(),source_component_id=(this.parent?.source_component_id?this.parent:parentNormalComponent)?.source_component_id??null,pinAttributes=this._getMatchingPinAttributes(),portAttributesFromParent={};for(let attributes2 of pinAttributes)attributes2.mustBeConnected!==void 0&&(portAttributesFromParent.must_be_connected=attributes2.mustBeConnected);let source_port2=db.source_port.insert({name:props.name,pin_number:props.pinNumber,port_hints,source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id,...portAttributesFromParent});this.source_port_id=source_port2.source_port_id}doInitialSourceParentAttachment(){let{db}=this.root,parentNormalComponent=this.getParentNormalComponent(),parentWithSourceId=this.parent?.source_component_id?this.parent:parentNormalComponent;if(this.isGroupPort()){db.source_port.update(this.source_port_id,{source_component_id:null,subcircuit_id:this.getSubcircuit()?.subcircuit_id});return}if(!parentWithSourceId?.source_component_id)throw new Error(`${this.getString()} has no parent source component (parent: ${this.parent?.getString()})`);db.source_port.update(this.source_port_id,{source_component_id:parentWithSourceId.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id}),this.source_component_id=parentWithSourceId.source_component_id}doInitialPcbPortRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{matchedComponents}=this;if(this.isGroupPort()){let connectedPorts=this._getConnectedPortsFromConnectsTo();if(connectedPorts.length===0)return;let connectedPort=connectedPorts[0];if(!connectedPort.pcb_port_id)return;let connectedPcbPort=db.pcb_port.get(connectedPort.pcb_port_id),matchCenter2={x:connectedPcbPort.x,y:connectedPcbPort.y},subcircuit=this.getSubcircuit(),pcb_port2=db.pcb_port.insert({pcb_component_id:void 0,layers:connectedPort.getAvailablePcbLayers(),subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...matchCenter2,source_port_id:this.source_port_id,is_board_pinout:!1});this.pcb_port_id=pcb_port2.pcb_port_id;return}let parentNormalComponent=this.getParentNormalComponent(),parentWithPcbComponentId=this.parent?.pcb_component_id?this.parent:parentNormalComponent;if(!parentWithPcbComponentId?.pcb_component_id)throw new Error(`${this.getString()} has no parent pcb component, cannot render pcb_port (parent: ${this.parent?.getString()}, parentNormalComponent: ${parentNormalComponent?.getString()})`);let pcbMatches=matchedComponents.filter(c3=>c3.isPcbPrimitive);if(pcbMatches.length===0)return;let matchCenter=null;if(pcbMatches.length===1&&(matchCenter=pcbMatches[0]._getPcbCircuitJsonBounds().center),pcbMatches.length>1){if(!areAllPcbPrimitivesOverlapping(pcbMatches))throw new Error(`${this.getString()} has multiple non-overlapping pcb matches, unclear how to place pcb_port: ${pcbMatches.map(c3=>c3.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)`);matchCenter=getCenterOfPcbPrimitives(pcbMatches)}if(matchCenter){let subcircuit=this.getSubcircuit(),isBoardPinout=this._shouldIncludeInBoardPinout(),pcb_port2=db.pcb_port.insert({pcb_component_id:parentWithPcbComponentId.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...isBoardPinout?{is_board_pinout:!0}:{},...matchCenter,source_port_id:this.source_port_id,is_board_pinout:this._isBoardPinoutFromAttributes()});this.pcb_port_id=pcb_port2.pcb_port_id}else{let pcbMatch=pcbMatches[0];throw new Error(`${pcbMatch.getString()} does not have a center or _getGlobalPcbPositionBeforeLayout method (needed for pcb_port placement)`)}}updatePcbPortRender(){if(this.root?.pcbDisabled)return;let{db}=this.root;if(this.pcb_port_id)return;if(this.isGroupPort()){let connectedPorts=this._getConnectedPortsFromConnectsTo();if(connectedPorts.length===0)return;let connectedPort=connectedPorts[0];if(!connectedPort.pcb_port_id)return;let connectedPcbPort=db.pcb_port.get(connectedPort.pcb_port_id),matchCenter2={x:connectedPcbPort.x,y:connectedPcbPort.y},subcircuit2=this.getSubcircuit(),pcb_port22=db.pcb_port.insert({pcb_component_id:void 0,layers:connectedPort.getAvailablePcbLayers(),subcircuit_id:subcircuit2?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...matchCenter2,source_port_id:this.source_port_id,is_board_pinout:!1});this.pcb_port_id=pcb_port22.pcb_port_id;return}let pcbMatches=this.matchedComponents.filter(c3=>c3.isPcbPrimitive);if(pcbMatches.length===0)return;let matchCenter=null;if(pcbMatches.length===1&&(matchCenter=pcbMatches[0]._getPcbCircuitJsonBounds().center),pcbMatches.length>1)try{areAllPcbPrimitivesOverlapping(pcbMatches)&&(matchCenter=getCenterOfPcbPrimitives(pcbMatches))}catch{}if(!matchCenter)return;let parentNormalComponent=this.getParentNormalComponent(),parentWithPcbComponentId=this.parent?.pcb_component_id?this.parent:parentNormalComponent,subcircuit=this.getSubcircuit(),isBoardPinout=this._shouldIncludeInBoardPinout(),pcb_port2=db.pcb_port.insert({pcb_component_id:parentWithPcbComponentId?.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...isBoardPinout?{is_board_pinout:!0}:{},...matchCenter,source_port_id:this.source_port_id,is_board_pinout:this._isBoardPinoutFromAttributes()});this.pcb_port_id=pcb_port2.pcb_port_id}_getBestDisplayPinLabel(){let{db}=this.root,sourcePort=db.source_port.get(this.source_port_id),labelHints=[];for(let portHint of sourcePort?.port_hints??[])portHint.match(/^(pin)?\d+$/)||portHint.match(/^(left|right)/)&&!sourcePort?.name.match(/^(left|right)/)||labelHints.push(portHint);if(this.getParentNormalComponent()?.props?.showPinAliases&&labelHints.length>0)return labelHints.join("/");if(labelHints.length>0)return labelHints[0]}doInitialSchematicPortRender(){let{db}=this.root,{_parsedProps:props}=this,{schX,schY}=props,container=schX!==void 0&&schY!==void 0?this.getParentNormalComponent():this.getPrimitiveContainer();if(!container||!this._hasSchematicPort())return;let containerCenter=container._getGlobalSchematicPositionBeforeLayout(),portCenter=this._getGlobalSchematicPositionBeforeLayout(),localPortInfo=null,containerDims=container._getSchematicBoxDimensions();containerDims&&props.pinNumber!==void 0&&(localPortInfo=containerDims.getPortPositionByPinNumber(props.pinNumber)),this.getSubcircuit().props._schDebugObjectsEnabled&&db.schematic_debug_object.insert({shape:"rect",center:portCenter,size:{width:.1,height:.1},label:"obstacle"}),localPortInfo?.side?this.facingDirection={left:"left",right:"right",top:"up",bottom:"down"}[localPortInfo.side]:this.facingDirection=getRelativeDirection(containerCenter,portCenter);let bestDisplayPinLabel=this._getBestDisplayPinLabel(),schematicPortInsertProps={type:"schematic_port",schematic_component_id:this.getParentNormalComponent()?.schematic_component_id,center:portCenter,source_port_id:this.source_port_id,facing_direction:this.facingDirection,distance_from_component_edge:.4,side_of_component:localPortInfo?.side,pin_number:props.pinNumber,true_ccw_index:localPortInfo?.trueIndex,display_pin_label:bestDisplayPinLabel,is_connected:!1};for(let attributes2 of this._getMatchingPinAttributes())attributes2.requiresPower&&(schematicPortInsertProps.has_input_arrow=!0),attributes2.providesPower&&(schematicPortInsertProps.has_output_arrow=!0);let schematic_port2=db.schematic_port.insert(schematicPortInsertProps);this.schematic_port_id=schematic_port2.schematic_port_id}_getSubcircuitConnectivityKey(){return this.root?.db.source_port.get(this.source_port_id)?.subcircuit_connectivity_map_key}_setPositionFromLayout(newCenter){let{db}=this.root;this.pcb_port_id&&db.pcb_port.update(this.pcb_port_id,{x:newCenter.x,y:newCenter.y})}_hasMatchedPcbPrimitive(){return this.matchedComponents.some(c3=>c3.isPcbPrimitive)}_getNetLabelText(){return`${this.parent?.props.name}_${this.props.name}`}},getPinNumberFromLabels=labels=>{let pinNumber=labels.find(p4=>/^(pin)?\d+$/.test(p4));return pinNumber?Number.parseInt(pinNumber.replace(/^pin/,"")):null};function getPortFromHints(hints,opts){let pinNumber=getPinNumberFromLabels(hints);if(!pinNumber)return null;let aliases2=[...hints.filter(p4=>p4.toString()!==pinNumber.toString()&&p4!==`pin${pinNumber}`),...opts?.additionalAliases?.[`pin${pinNumber}`]??[]];return new Port({pinNumber,aliases:aliases2})}var hasExplicitPinMapping=pa2=>{for(let side of["leftSide","rightSide","topSide","bottomSide"])if(side in pa2&&typeof pa2[side]=="number")throw new Error(`A number was specified for "${side}", you probably meant to use "size" not "side"`);return"leftSide"in pa2||"rightSide"in pa2||"topSide"in pa2||"bottomSide"in pa2},getSizeOfSidesFromPortArrangement=pa2=>{if(hasExplicitPinMapping(pa2))return{leftSize:pa2.leftSide?.pins.length??0,rightSize:pa2.rightSide?.pins.length??0,topSize:pa2.topSide?.pins.length??0,bottomSize:pa2.bottomSide?.pins.length??0};let{leftSize=0,rightSize=0,topSize=0,bottomSize=0}=pa2;return{leftSize,rightSize,topSize,bottomSize}},DEFAULT_SCHEMATIC_BOX_PADDING_MM=.4;function isExplicitPinMappingArrangement(arrangement){let a3=arrangement;return a3.leftSide!==void 0||a3.rightSide!==void 0||a3.topSide!==void 0||a3.bottomSide!==void 0}var getAllDimensionsForSchematicBox=params=>{let portDistanceFromEdge=params.portDistanceFromEdge??.4,sidePinCounts=params.schPortArrangement?getSizeOfSidesFromPortArrangement(params.schPortArrangement):null,sideLengths={left:0,right:0,top:0,bottom:0},pinCount=params.pinCount??null;if(pinCount===null)if(sidePinCounts)pinCount=sidePinCounts.leftSize+sidePinCounts.rightSize+sidePinCounts.topSize;else throw new Error("Could not determine pin count for the schematic box");if(pinCount&&!sidePinCounts){let rightSize=Math.floor(pinCount/2);sidePinCounts={leftSize:pinCount-rightSize,rightSize,topSize:0,bottomSize:0}}sidePinCounts||(sidePinCounts={leftSize:0,rightSize:0,topSize:0,bottomSize:0});let getPinNumberUsingSideIndex=({side,sideIndex,truePinIndex:truePinIndex2})=>{if(!params.schPortArrangement||!isExplicitPinMappingArrangement(params.schPortArrangement))return truePinIndex2+1;let normalCcwDirection={left:"top-to-bottom",bottom:"left-to-right",right:"bottom-to-top",top:"right-to-left"}[side],directionAlongSide=params.schPortArrangement?.[`${side}Side`]?.direction??normalCcwDirection,pinsDefinitionForSide=params.schPortArrangement?.[`${side}Side`]?.pins,sideIndexWithDirectionCorrection=sideIndex;return directionAlongSide!==normalCcwDirection&&(sideIndexWithDirectionCorrection=pinsDefinitionForSide.length-sideIndex-1),parsePinNumberFromLabelsOrThrow(pinsDefinitionForSide[sideIndexWithDirectionCorrection],params.pinLabels)},orderedTruePorts=[],currentDistanceFromEdge=0,truePinIndex=0;for(let sideIndex=0;sideIndex<sidePinCounts.leftSize;sideIndex++){let pinNumber=getPinNumberUsingSideIndex({side:"left",sideIndex,truePinIndex}),pinStyle=params.numericSchPinStyle?.[`pin${pinNumber}`]??params.numericSchPinStyle?.[pinNumber];pinStyle?.topMargin&&(currentDistanceFromEdge+=pinStyle.topMargin),orderedTruePorts.push({trueIndex:truePinIndex,pinNumber,side:"left",distanceFromOrthogonalEdge:currentDistanceFromEdge}),pinStyle?.bottomMargin&&(currentDistanceFromEdge+=pinStyle.bottomMargin),sideIndex===sidePinCounts.leftSize-1?sideLengths.left=currentDistanceFromEdge:currentDistanceFromEdge+=params.schPinSpacing,truePinIndex++}currentDistanceFromEdge=0;for(let sideIndex=0;sideIndex<sidePinCounts.bottomSize;sideIndex++){let pinNumber=getPinNumberUsingSideIndex({side:"bottom",sideIndex,truePinIndex}),pinStyle=params.numericSchPinStyle?.[`pin${pinNumber}`]??params.numericSchPinStyle?.[pinNumber];pinStyle?.leftMargin&&(currentDistanceFromEdge+=pinStyle.leftMargin),orderedTruePorts.push({trueIndex:truePinIndex,pinNumber,side:"bottom",distanceFromOrthogonalEdge:currentDistanceFromEdge}),pinStyle?.rightMargin&&(currentDistanceFromEdge+=pinStyle.rightMargin),sideIndex===sidePinCounts.bottomSize-1?sideLengths.bottom=currentDistanceFromEdge:currentDistanceFromEdge+=params.schPinSpacing,truePinIndex++}currentDistanceFromEdge=0;for(let sideIndex=0;sideIndex<sidePinCounts.rightSize;sideIndex++){let pinNumber=getPinNumberUsingSideIndex({side:"right",sideIndex,truePinIndex}),pinStyle=params.numericSchPinStyle?.[`pin${pinNumber}`]??params.numericSchPinStyle?.[pinNumber];pinStyle?.bottomMargin&&(currentDistanceFromEdge+=pinStyle.bottomMargin),orderedTruePorts.push({trueIndex:truePinIndex,pinNumber,side:"right",distanceFromOrthogonalEdge:currentDistanceFromEdge}),pinStyle?.topMargin&&(currentDistanceFromEdge+=pinStyle.topMargin),sideIndex===sidePinCounts.rightSize-1?sideLengths.right=currentDistanceFromEdge:currentDistanceFromEdge+=params.schPinSpacing,truePinIndex++}currentDistanceFromEdge=0;for(let sideIndex=0;sideIndex<sidePinCounts.topSize;sideIndex++){let pinNumber=getPinNumberUsingSideIndex({side:"top",sideIndex,truePinIndex}),pinStyle=params.numericSchPinStyle?.[`pin${pinNumber}`]??params.numericSchPinStyle?.[pinNumber];pinStyle?.rightMargin&&(currentDistanceFromEdge+=pinStyle.rightMargin),orderedTruePorts.push({trueIndex:truePinIndex,pinNumber,side:"top",distanceFromOrthogonalEdge:currentDistanceFromEdge}),pinStyle?.leftMargin&&(currentDistanceFromEdge+=pinStyle.leftMargin),sideIndex===sidePinCounts.topSize-1?sideLengths.top=currentDistanceFromEdge:currentDistanceFromEdge+=params.schPinSpacing,truePinIndex++}let resolvedSchWidth=params.schWidth;if(resolvedSchWidth===void 0){resolvedSchWidth=Math.max(sideLengths.top+DEFAULT_SCHEMATIC_BOX_PADDING_MM,sideLengths.bottom+DEFAULT_SCHEMATIC_BOX_PADDING_MM),params.pinLabels&&orderedTruePorts.filter(p4=>p4.side==="left"||p4.side==="right").some(p4=>params.pinLabels?.[`pin${p4.pinNumber}`]||params.pinLabels?.[p4.pinNumber])&&(resolvedSchWidth=Math.max(resolvedSchWidth,.5));let labelWidth=params.pinLabels?Math.max(...Object.values(params.pinLabels).map(label=>label.length*.1)):0,LABEL_PADDING=labelWidth>0?1.1:0;resolvedSchWidth=Math.max(resolvedSchWidth,labelWidth+LABEL_PADDING)}let schHeight=params.schHeight;schHeight||(schHeight=Math.max(sideLengths.left+DEFAULT_SCHEMATIC_BOX_PADDING_MM,sideLengths.right+DEFAULT_SCHEMATIC_BOX_PADDING_MM));let trueEdgePositions={left:{x:-resolvedSchWidth/2-portDistanceFromEdge,y:sideLengths.left/2},bottom:{x:-sideLengths.bottom/2,y:-schHeight/2-portDistanceFromEdge},right:{x:resolvedSchWidth/2+portDistanceFromEdge,y:-sideLengths.right/2},top:{x:sideLengths.top/2,y:schHeight/2+portDistanceFromEdge}},trueEdgeTraversalDirections={left:{x:0,y:-1},right:{x:0,y:1},top:{x:-1,y:0},bottom:{x:1,y:0}},truePortsWithPositions=orderedTruePorts.map(p4=>{let{distanceFromOrthogonalEdge,side}=p4,edgePos=trueEdgePositions[side],edgeDir=trueEdgeTraversalDirections[side];return{x:edgePos.x+distanceFromOrthogonalEdge*edgeDir.x,y:edgePos.y+distanceFromOrthogonalEdge*edgeDir.y,...p4}});return{getPortPositionByPinNumber(pinNumber){let port=truePortsWithPositions.find(p4=>p4.pinNumber.toString()===pinNumber.toString());return port||null},getSize(){return{width:resolvedSchWidth,height:schHeight}},getSizeIncludingPins(){return{width:resolvedSchWidth+(sidePinCounts.leftSize||sidePinCounts.rightSize?.4:0),height:schHeight+(sidePinCounts.topSize||sidePinCounts.bottomSize?.4:0)}},pinCount}},debug22=(0,import_debug8.default)("tscircuit:core:footprint"),Footprint=class extends PrimitiveComponent2{get config(){return{componentName:"Footprint",zodProps:footprintProps}}doInitialPcbFootprintLayout(){if(this.root?.pcbDisabled)return;let constraints=this.children.filter(child=>child.componentName==="Constraint");if(constraints.length===0)return;let{isFlipped}=this._getPcbPrimitiveFlippedHelpers(),maybeFlipLeftRight=props=>isFlipped&&"left"in props&&"right"in props?{...props,left:props.right,right:props.left}:props,involvedComponents=constraints.flatMap(constraint=>constraint._getAllReferencedComponents().componentsWithSelectors).map(({component,selector,componentSelector,edge})=>({component,selector,componentSelector,edge,bounds:component._getPcbCircuitJsonBounds()}));if(involvedComponents.some(c3=>c3.edge))throw new Error("edge constraints not implemented yet for footprint layout, contributions welcome!");function getComponentDetails(selector){return involvedComponents.find(({selector:s4})=>s4===selector)}let solver=new Solver,kVars={};function getKVar(name){return name in kVars||(kVars[name]=new Variable(name),solver.addEditVariable(kVars[name],Strength.weak)),kVars[name]}for(let{selector,bounds:bounds2}of involvedComponents){let kvx=getKVar(`${selector}_x`),kvy=getKVar(`${selector}_y`);solver.suggestValue(kvx,bounds2.center.x),solver.suggestValue(kvy,bounds2.center.y)}for(let constraint of constraints){let props=constraint._parsedProps;if("xDist"in props){let{xDist,left,right,edgeToEdge,centerToCenter}=maybeFlipLeftRight(props),leftVar=getKVar(`${left}_x`),rightVar=getKVar(`${right}_x`),leftBounds=getComponentDetails(left)?.bounds,rightBounds=getComponentDetails(right)?.bounds;if(centerToCenter){let expr=new Expression(rightVar,[-1,leftVar]);solver.addConstraint(new Constraint(expr,Operator.Eq,props.xDist,Strength.required))}else if(edgeToEdge){let expr=new Expression(rightVar,-rightBounds.width/2,[-1,leftVar],-leftBounds.width/2);solver.addConstraint(new Constraint(expr,Operator.Eq,props.xDist,Strength.required))}}else if("yDist"in props){let{yDist,top,bottom,edgeToEdge,centerToCenter}=props,topVar=getKVar(`${top}_y`),bottomVar=getKVar(`${bottom}_y`),topBounds=getComponentDetails(top)?.bounds,bottomBounds=getComponentDetails(bottom)?.bounds;if(centerToCenter){let expr=new Expression(topVar,[-1,bottomVar]);solver.addConstraint(new Constraint(expr,Operator.Eq,props.yDist,Strength.required))}else if(edgeToEdge){let expr=new Expression(topVar,topBounds.height/2,[-1,bottomVar],-bottomBounds.height/2);solver.addConstraint(new Constraint(expr,Operator.Eq,props.yDist,Strength.required))}}else if("sameY"in props){let{for:selectors}=props;if(selectors.length<2)continue;let vars=selectors.map(selector=>getKVar(`${selector}_y`)),expr=new Expression(...vars.slice(1));solver.addConstraint(new Constraint(expr,Operator.Eq,vars[0],Strength.required))}else if("sameX"in props){let{for:selectors}=props;if(selectors.length<2)continue;let vars=selectors.map(selector=>getKVar(`${selector}_x`)),expr=new Expression(...vars.slice(1));solver.addConstraint(new Constraint(expr,Operator.Eq,vars[0],Strength.required))}}solver.updateVariables(),debug22.enabled&&(console.log("Solution to layout constraints:"),console.table(Object.entries(kVars).map(([key,kvar])=>({var:key,val:kvar.value()}))));let bounds={left:1/0,right:-1/0,top:-1/0,bottom:1/0};for(let{selector,bounds:{width,height}}of involvedComponents){let kvx=getKVar(`${selector}_x`),kvy=getKVar(`${selector}_y`),newLeft=kvx.value()-width/2,newRight=kvx.value()+width/2,newTop=kvy.value()+height/2,newBottom=kvy.value()-height/2;bounds.left=Math.min(bounds.left,newLeft),bounds.right=Math.max(bounds.right,newRight),bounds.top=Math.max(bounds.top,newTop),bounds.bottom=Math.min(bounds.bottom,newBottom)}let globalOffset={x:-(bounds.right+bounds.left)/2,y:-(bounds.top+bounds.bottom)/2},containerPos=this.getPrimitiveContainer()._getGlobalPcbPositionBeforeLayout();globalOffset.x+=containerPos.x,globalOffset.y+=containerPos.y;for(let{component,selector}of involvedComponents){let kvx=getKVar(`${selector}_x`),kvy=getKVar(`${selector}_y`);component._setPositionFromLayout({x:kvx.value()+globalOffset.x,y:kvy.value()+globalOffset.y})}}},getFileExtension=filename=>{if(!filename)return null;let fragmentMatch=filename.match(/#ext=(\w+)$/);if(fragmentMatch)return fragmentMatch[1].toLowerCase();let sanitized=filename.split("?")[0].split("#")[0],lastSegment=sanitized.split("/").pop()??sanitized;return lastSegment.includes(".")?lastSegment.split(".").pop()?.toLowerCase()??null:null},joinUrlPath=(base,path)=>{let trimmedBase=base.replace(/\/+$/,""),trimmedPath=path.replace(/^\/+/,"");return`${trimmedBase}/${trimmedPath}`},constructAssetUrl=(targetUrl,baseUrl)=>{if(!baseUrl||!targetUrl.startsWith("/"))return targetUrl;try{let baseUrlObj=new URL(baseUrl);return baseUrlObj.pathname!=="/"&&targetUrl.startsWith(baseUrlObj.pathname)?new URL(targetUrl,baseUrlObj.origin).toString():joinUrlPath(baseUrl,targetUrl)}catch{return targetUrl}},rotation2=external_exports.union([external_exports.number(),external_exports.string()]),rotation3=external_exports.object({x:rotation2,y:rotation2,z:rotation2}),CadModel=class extends PrimitiveComponent2{get config(){return{componentName:"CadModel",zodProps:cadmodelProps}}doInitialCadModelRender(){let parent=this._findParentWithPcbComponent();if(!parent||!parent.pcb_component_id)return;let{db}=this.root,{boardThickness=0}=this.root?._getBoard()??{},bounds=parent._getPcbCircuitJsonBounds(),pcb_component2=db.pcb_component.get(parent.pcb_component_id),props=this._parsedProps;if(!props||typeof props.modelUrl!="string"&&typeof props.stepUrl!="string")return;let parentTransform=parent._computePcbGlobalTransformBeforeLayout(),accumulatedRotation=decomposeTSR(parentTransform).rotation.angle*180/Math.PI,rotationOffset=rotation3.parse({x:0,y:0,z:0});if(typeof props.rotationOffset=="number")rotationOffset.z=Number(props.rotationOffset);else if(typeof props.rotationOffset=="object"){let parsed=rotation3.parse(props.rotationOffset);rotationOffset.x=Number(parsed.x),rotationOffset.y=Number(parsed.y),rotationOffset.z=Number(parsed.z)}let{pcbX,pcbY}=this.getResolvedPcbPositionProp(),positionOffset=point32.parse({x:pcbX,y:pcbY,z:props.pcbZ??0,...typeof props.positionOffset=="object"?props.positionOffset:{}}),zOffsetFromSurface=props.zOffsetFromSurface!==void 0?distance.parse(props.zOffsetFromSurface):0,layer=parent.props.layer==="bottom"?"bottom":"top",ext=props.modelUrl?getFileExtension(props.modelUrl):void 0,modelUrlWithoutExtFragment=props.modelUrl?.replace(/#ext=\w+$/,""),urlProps={};if(ext==="stl"?urlProps.model_stl_url=this._addCachebustToModelUrl(modelUrlWithoutExtFragment):ext==="obj"?urlProps.model_obj_url=this._addCachebustToModelUrl(modelUrlWithoutExtFragment):ext==="gltf"?urlProps.model_gltf_url=this._addCachebustToModelUrl(modelUrlWithoutExtFragment):ext==="glb"?urlProps.model_glb_url=this._addCachebustToModelUrl(modelUrlWithoutExtFragment):ext==="step"||ext==="stp"?urlProps.model_step_url=this._addCachebustToModelUrl(modelUrlWithoutExtFragment):ext==="wrl"||ext==="vrml"?urlProps.model_wrl_url=this._addCachebustToModelUrl(modelUrlWithoutExtFragment):urlProps.model_stl_url=this._addCachebustToModelUrl(modelUrlWithoutExtFragment),props.stepUrl){let transformed=this._addCachebustToModelUrl(props.stepUrl);transformed&&(urlProps.model_step_url=transformed)}let cad=db.cad_component.insert({position:{x:bounds.center.x+Number(positionOffset.x),y:bounds.center.y+Number(positionOffset.y),z:(layer==="bottom"?-boardThickness/2:boardThickness/2)+(layer==="bottom"?-zOffsetFromSurface:zOffsetFromSurface)+Number(positionOffset.z)},rotation:{x:Number(rotationOffset.x),y:(layer==="top"?0:180)+Number(rotationOffset.y),z:layer==="bottom"?-(accumulatedRotation+Number(rotationOffset.z))+180:accumulatedRotation+Number(rotationOffset.z)},pcb_component_id:parent.pcb_component_id,source_component_id:parent.source_component_id,model_unit_to_mm_scale_factor:typeof props.modelUnitToMmScale=="number"?props.modelUnitToMmScale:void 0,show_as_translucent_model:parent._parsedProps.showAsTranslucentModel,...urlProps});this.cad_component_id=cad.cad_component_id}_findParentWithPcbComponent(){let p4=this.parent;for(;p4&&!p4.pcb_component_id;)p4=p4.parent;return p4}_addCachebustToModelUrl(url){if(!url)return url;let baseUrl=this.root?.platform?.projectBaseUrl,transformedUrl=constructAssetUrl(url,baseUrl);if(!transformedUrl.includes("modelcdn.tscircuit.com"))return transformedUrl;let origin=this.root?.getClientOrigin()??"";return`${transformedUrl}${transformedUrl.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(origin)}`}},CadAssembly=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"CadAssembly",zodProps:cadassemblyProps}}},getNumericSchPinStyle=(pinStyles,pinLabels)=>{if(!pinStyles)return;let numericPinStyles={};for(let[pinNameOrLabel,pinStyle]of Object.entries(pinStyles)){let pinNumber=parsePinNumberFromLabelsOrThrow(pinNameOrLabel,pinLabels),pinStyleWithSideFirst={leftMargin:pinStyle.marginLeft??pinStyle.leftMargin,rightMargin:pinStyle.marginRight??pinStyle.rightMargin,topMargin:pinStyle.marginTop??pinStyle.topMargin,bottomMargin:pinStyle.marginBottom??pinStyle.bottomMargin};numericPinStyles[`pin${pinNumber}`]={...numericPinStyles[`pin${pinNumber}`],...pinStyleWithSideFirst}}return numericPinStyles},DirectLineRouter=class{constructor({input:input2}){__publicField(this,"input");this.input=input2}solveAndMapToTraces(){let traces=[];for(let connection of this.input.connections){if(connection.pointsToConnect.length!==2)continue;let[start,end]=connection.pointsToConnect,trace={type:"pcb_trace",pcb_trace_id:"",connection_name:connection.name,route:[{route_type:"wire",x:start.x,y:start.y,layer:"top",width:.1},{route_type:"wire",x:end.x,y:end.y,layer:"top",width:.1}]};traces.push(trace)}return traces}},computeObstacleBounds=obstacles=>{let minX=Math.min(...obstacles.map(o3=>o3.center.x)),maxX=Math.max(...obstacles.map(o3=>o3.center.x)),minY=Math.min(...obstacles.map(o3=>o3.center.y)),maxY=Math.max(...obstacles.map(o3=>o3.center.y));return{minX,maxX,minY,maxY}},LAYER_SELECTION_PREFERENCE=["top","bottom","inner1","inner2"],findPossibleTraceLayerCombinations=(hints,layer_path=[])=>{let candidates=[];if(layer_path.length===0){let starting_layers=hints[0].layers;for(let layer of starting_layers)candidates.push(...findPossibleTraceLayerCombinations(hints.slice(1),[layer]));return candidates}if(hints.length===0)return[];let current_hint=hints[0],is_possibly_via=current_hint.via||current_hint.optional_via,last_layer=layer_path[layer_path.length-1];if(hints.length===1){let last_hint=current_hint;return last_hint.layers&&is_possibly_via?last_hint.layers.map(layer=>({layer_path:[...layer_path,layer]})):last_hint.layers?.includes(last_layer)?[{layer_path:[...layer_path,last_layer]}]:[]}if(!is_possibly_via)return current_hint.layers&&!current_hint.layers.includes(last_layer)?[]:findPossibleTraceLayerCombinations(hints.slice(1),layer_path.concat([last_layer]));let candidate_next_layers=(current_hint.optional_via?LAYER_SELECTION_PREFERENCE:LAYER_SELECTION_PREFERENCE.filter(layer=>layer!==last_layer)).filter(layer=>!current_hint.layers||current_hint.layers?.includes(layer));for(let candidate_next_layer of candidate_next_layers)candidates.push(...findPossibleTraceLayerCombinations(hints.slice(1),layer_path.concat(candidate_next_layer)));return candidates};function getDominantDirection(edge){let delta={x:edge.to.x-edge.from.x,y:edge.to.y-edge.from.y},absX=Math.abs(delta.x),absY=Math.abs(delta.y);return absX>absY?delta.x>0?"right":"left":delta.y>0?"down":"up"}function pdist(a3,b3){return Math.hypot(a3.x-b3.x,a3.y-b3.y)}var mergeRoutes=routes=>{if(routes.length===1)return routes[0];if(routes.some(r4=>r4.length===0))throw new Error("Cannot merge routes with zero length");let merged=[],first_route_fp=routes[0][0],first_route_lp=routes[0][routes[0].length-1],second_route_fp=routes[1][0],second_route_lp=routes[1][routes[1].length-1],best_reverse_dist=Math.min(pdist(first_route_fp,second_route_fp),pdist(first_route_fp,second_route_lp)),best_normal_dist=Math.min(pdist(first_route_lp,second_route_fp),pdist(first_route_lp,second_route_lp));best_reverse_dist<best_normal_dist?merged.push(...routes[0].reverse()):merged.push(...routes[0]);for(let i3=1;i3<routes.length;i3++){let last_merged_point=merged[merged.length-1],next_route=routes[i3],next_first_point=next_route[0],next_last_point=next_route[next_route.length-1],distance_to_first=pdist(last_merged_point,next_first_point),distance_to_last=pdist(last_merged_point,next_last_point);distance_to_first<distance_to_last?merged.push(...next_route):merged.push(...next_route.reverse())}for(let i3=1;i3<merged.length-1;i3++){let lastPoint=merged[i3-1],currentPoint=merged[i3];lastPoint.route_type==="wire"&&currentPoint.route_type==="wire"&&lastPoint.layer!==currentPoint.layer&&merged.splice(i3,0,{x:lastPoint.x,y:lastPoint.y,from_layer:lastPoint.layer,to_layer:currentPoint.layer,route_type:"via"})}return merged},getDistance=(a3,b3)=>{let aPos="_getGlobalPcbPositionBeforeLayout"in a3?a3._getGlobalPcbPositionBeforeLayout():a3,bPos="_getGlobalPcbPositionBeforeLayout"in b3?b3._getGlobalPcbPositionBeforeLayout():b3;return Math.sqrt((aPos.x-bPos.x)**2+(aPos.y-bPos.y)**2)};function getClosest(point23,candidates){if(candidates.length===0)throw new Error("No candidates given to getClosest method");let closest=candidates[0],closestDist=1/0;for(let candidate of candidates){let dist=getDistance(point23,candidate);dist<closestDist&&(closest=candidate,closestDist=dist)}return closest}var countComplexElements=(junctions,edges)=>{let count=0;count+=junctions.length??0,count+=edges.filter(edge=>edge.is_crossing).length;for(let i3=1;i3<edges.length;i3++){let prev=edges[i3-1],curr=edges[i3],prevVertical=Math.abs(prev.from.x-prev.to.x)<.01,currVertical=Math.abs(curr.from.x-curr.to.x)<.01;prevVertical!==currVertical&&count++}return count},getEnteringEdgeFromDirection=direction2=>({up:"bottom",down:"top",left:"right",right:"left"})[direction2]??null,getStubEdges=({firstEdge,firstEdgePort,firstDominantDirection,lastEdge,lastEdgePort,lastDominantDirection})=>{if(firstEdge&&firstEdgePort)return getStubEdges({lastEdge:{from:firstEdge.to,to:firstEdge.from},lastEdgePort:firstEdgePort,lastDominantDirection:firstDominantDirection}).reverse().map(e4=>({from:e4.to,to:e4.from}));let edges=[];if(lastEdge&&lastEdgePort){let intermediatePoint={x:lastEdge.to.x,y:lastEdge.to.y};lastDominantDirection==="left"||lastDominantDirection==="right"?(intermediatePoint.x=lastEdgePort.position.x,edges.push({from:lastEdge.to,to:{...intermediatePoint}}),edges.push({from:intermediatePoint,to:{...lastEdgePort.position}})):(intermediatePoint.y=lastEdgePort.position.y,edges.push({from:lastEdge.to,to:{...intermediatePoint}}),edges.push({from:intermediatePoint,to:{...lastEdgePort.position}}))}return edges=edges.filter(e4=>distance4(e4.from,e4.to)>.01),edges};function tryNow(fn3){try{return[fn3(),null]}catch(e4){return[null,e4]}}var getMaxLengthFromConnectedCapacitors=(ports,{db})=>{let capacitorMaxLengths=ports.map(port=>{let sourcePort=db.source_port.get(port.source_port_id);if(!sourcePort?.source_component_id)return null;let sourceComponent=db.source_component.get(sourcePort.source_component_id);return sourceComponent?.ftype==="simple_capacitor"?sourceComponent.max_decoupling_trace_length:null}).filter(length7=>length7!==null);if(capacitorMaxLengths.length!==0)return Math.min(...capacitorMaxLengths)};function getTraceDisplayName({ports,nets}){if(ports.length>=2)return`${ports[0]?.selector} to ${ports[1]?.selector}`;if(ports.length===1&&nets.length===1)return`${ports[0]?.selector} to net.${nets[0]._parsedProps.name}`}var isRouteOutsideBoard=(mergedRoute,{db})=>{let pcbBoard=db.pcb_board.list()[0];if(pcbBoard.outline){let boardOutline=pcbBoard.outline,isInsidePolygon=(point23,polygon2)=>{let inside2=!1;for(let i3=0,j3=polygon2.length-1;i3<polygon2.length;j3=i3++){let xi3=polygon2[i3].x,yi3=polygon2[i3].y,xj=polygon2[j3].x,yj=polygon2[j3].y;yi3>point23.y!=yj>point23.y&&point23.x<(xj-xi3)*(point23.y-yi3)/(yj-yi3)+xi3&&(inside2=!inside2)}return inside2};return mergedRoute.some(point23=>!isInsidePolygon(point23,boardOutline))}let boardWidth=pcbBoard.width,boardHeight=pcbBoard.height,boardCenterX=pcbBoard.center.x,boardCenterY=pcbBoard.center.y;return mergedRoute.some(point23=>point23.x<boardCenterX-boardWidth/2||point23.y<boardCenterY-boardHeight/2||point23.x>boardCenterX+boardWidth/2||point23.y>boardCenterY+boardHeight/2)},isCloseTo2=(a3,b3)=>Math.abs(a3-b3)<1e-4,getObstaclesFromRoute2=(route,source_trace_id,{viaDiameter=.5}={})=>{let obstacles=[];for(let i3=0;i3<route.length-1;i3++){let[start,end]=[route[i3],route[i3+1]],prev=i3-1>=0?route[i3-1]:null,isHorz=isCloseTo2(start.y,end.y),isVert=isCloseTo2(start.x,end.x);if(!isHorz&&!isVert)throw new Error(`getObstaclesFromTrace currently only supports horizontal and vertical traces (not diagonals) Conflicting trace: ${source_trace_id}, start: (${start.x}, ${start.y}), end: (${end.x}, ${end.y})`);let obstacle={type:"rect",layers:[start.layer],center:{x:(start.x+end.x)/2,y:(start.y+end.y)/2},width:isHorz?Math.abs(start.x-end.x):.1,height:isVert?Math.abs(start.y-end.y):.1,connectedTo:[source_trace_id]};if(obstacles.push(obstacle),prev&&prev.layer===start.layer&&start.layer!==end.layer){let via={type:"rect",layers:[start.layer,end.layer],center:{x:start.x,y:start.y},connectedTo:[source_trace_id],width:viaDiameter,height:viaDiameter};obstacles.push(via)}}return obstacles};function generateApproximatingRects2(rotatedRect,numRects=4){let{center:center2,width,height,rotation:rotation4}=rotatedRect,rects=[],angleRad=rotation4*Math.PI/180,cosAngle=Math.cos(angleRad),sinAngle=Math.sin(angleRad),normalizedRotation=(rotation4%360+360)%360;if(height<=width?normalizedRotation>=45&&normalizedRotation<135||normalizedRotation>=225&&normalizedRotation<315:normalizedRotation>=135&&normalizedRotation<225||normalizedRotation>=315||normalizedRotation<45){let sliceWidth=width/numRects;for(let i3=0;i3<numRects;i3++){let x3=(i3-numRects/2+.5)*sliceWidth,rotatedX=-x3*cosAngle,rotatedY=-x3*sinAngle,coverageWidth=sliceWidth*1.1,coverageHeight=Math.abs(height*cosAngle)+Math.abs(sliceWidth*sinAngle);rects.push({center:{x:center2.x+rotatedX,y:center2.y+rotatedY},width:coverageWidth,height:coverageHeight})}}else{let sliceHeight=height/numRects;for(let i3=0;i3<numRects;i3++){let y3=(i3-numRects/2+.5)*sliceHeight,rotatedX=-y3*sinAngle,rotatedY=y3*cosAngle,coverageWidth=Math.abs(width*cosAngle)+Math.abs(sliceHeight*sinAngle),coverageHeight=sliceHeight*1.1;rects.push({center:{x:center2.x+rotatedX,y:center2.y+rotatedY},width:coverageWidth,height:coverageHeight})}}return rects}function fillPolygonWithRects(polygon2,options={}){if(polygon2.length<3)return[];let{rectHeight=.1}=options,rects=[],yCoords=polygon2.map(p4=>p4.y),minY=Math.min(...yCoords),maxY=Math.max(...yCoords);for(let y3=minY;y3<maxY;y3+=rectHeight){let scanlineY=y3+rectHeight/2,intersections=[];for(let i3=0;i3<polygon2.length;i3++){let p12=polygon2[i3],p22=polygon2[(i3+1)%polygon2.length];if(p12.y<=scanlineY&&p22.y>scanlineY||p22.y<=scanlineY&&p12.y>scanlineY){let x3=(scanlineY-p12.y)*(p22.x-p12.x)/(p22.y-p12.y)+p12.x;intersections.push(x3)}}intersections.sort((a3,b3)=>a3-b3);for(let i3=0;i3<intersections.length;i3+=2)if(i3+1<intersections.length){let x12=intersections[i3],width=intersections[i3+1]-x12;width>1e-6&&rects.push({center:{x:x12+width/2,y:scanlineY},width,height:rectHeight})}}return rects}function fillCircleWithRects(circle2,options={}){let{center:center2,radius}=circle2,{rectHeight=.1}=options,rects=[],numSlices=Math.ceil(radius*2/rectHeight);for(let i3=0;i3<numSlices;i3++){let y3=center2.y-radius+(i3+.5)*rectHeight,dy2=y3-center2.y,halfWidth=Math.sqrt(radius*radius-dy2*dy2);halfWidth>0&&rects.push({center:{x:center2.x,y:y3},width:halfWidth*2,height:rectHeight})}return rects}var EVERY_LAYER2=["top","inner1","inner2","bottom"],getObstaclesFromCircuitJson2=(soup,connMap)=>{let withNetId=idList=>connMap?idList.concat(idList.map(id=>connMap?.getNetConnectedToId(id)).filter(Boolean)):idList,obstacles=[];for(let element of soup)if(element.type==="pcb_smtpad"){if(element.shape==="circle")obstacles.push({type:"oval",layers:[element.layer],center:{x:element.x,y:element.y},width:element.radius*2,height:element.radius*2,connectedTo:withNetId([element.pcb_smtpad_id])});else if(element.shape==="rect")obstacles.push({type:"rect",layers:[element.layer],center:{x:element.x,y:element.y},width:element.width,height:element.height,connectedTo:withNetId([element.pcb_smtpad_id])});else if(element.shape==="rotated_rect"){let rotatedRect={center:{x:element.x,y:element.y},width:element.width,height:element.height,rotation:element.ccw_rotation},approximatingRects=generateApproximatingRects2(rotatedRect);for(let rect of approximatingRects)obstacles.push({type:"rect",layers:[element.layer],center:rect.center,width:rect.width,height:rect.height,connectedTo:withNetId([element.pcb_smtpad_id])})}}else if(element.type==="pcb_keepout")element.shape==="circle"?obstacles.push({type:"oval",layers:element.layers,center:{x:element.center.x,y:element.center.y},width:element.radius*2,height:element.radius*2,connectedTo:[]}):element.shape==="rect"&&obstacles.push({type:"rect",layers:element.layers,center:{x:element.center.x,y:element.center.y},width:element.width,height:element.height,connectedTo:[]});else if(element.type==="pcb_cutout"){if(element.shape==="rect")obstacles.push({type:"rect",layers:EVERY_LAYER2,center:{x:element.center.x,y:element.center.y},width:element.width,height:element.height,connectedTo:[]});else if(element.shape==="circle"){let approximatingRects=fillCircleWithRects({center:element.center,radius:element.radius},{rectHeight:.6});for(let rect of approximatingRects)obstacles.push({type:"rect",layers:EVERY_LAYER2,center:rect.center,width:rect.width,height:rect.height,connectedTo:[]})}else if(element.shape==="polygon"){let approximatingRects=fillPolygonWithRects(element.points,{rectHeight:.6});for(let rect of approximatingRects)obstacles.push({type:"rect",layers:EVERY_LAYER2,center:rect.center,width:rect.width,height:rect.height,connectedTo:[]})}}else if(element.type==="pcb_hole")element.hole_shape==="oval"?obstacles.push({type:"oval",center:{x:element.x,y:element.y},width:element.hole_width,height:element.hole_height,connectedTo:[]}):element.hole_shape==="rect"?obstacles.push({type:"rect",layers:EVERY_LAYER2,center:{x:element.x,y:element.y},width:element.hole_width,height:element.hole_height,connectedTo:[]}):element.hole_shape==="square"?obstacles.push({type:"rect",layers:EVERY_LAYER2,center:{x:element.x,y:element.y},width:element.hole_diameter,height:element.hole_diameter,connectedTo:[]}):(element.hole_shape==="round"||element.hole_shape==="circle")&&obstacles.push({type:"rect",layers:EVERY_LAYER2,center:{x:element.x,y:element.y},width:element.hole_diameter,height:element.hole_diameter,connectedTo:[]});else if(element.type==="pcb_plated_hole"){if(element.shape==="circle")obstacles.push({type:"oval",layers:EVERY_LAYER2,center:{x:element.x,y:element.y},width:element.outer_diameter,height:element.outer_diameter,connectedTo:withNetId([element.pcb_plated_hole_id])});else if(element.shape==="circular_hole_with_rect_pad")obstacles.push({type:"rect",layers:EVERY_LAYER2,center:{x:element.x,y:element.y},width:element.rect_pad_width,height:element.rect_pad_height,connectedTo:withNetId([element.pcb_plated_hole_id])});else if(element.shape==="oval"||element.shape==="pill")obstacles.push({type:"oval",layers:EVERY_LAYER2,center:{x:element.x,y:element.y},width:element.outer_width,height:element.outer_height,connectedTo:withNetId([element.pcb_plated_hole_id])});else if(element.shape==="hole_with_polygon_pad"&&"pad_outline"in element&&element.pad_outline&&element.pad_outline.length>0){let xs3=element.pad_outline.map(p4=>element.x+p4.x),ys3=element.pad_outline.map(p4=>element.y+p4.y),minX=Math.min(...xs3),maxX=Math.max(...xs3),minY=Math.min(...ys3),maxY=Math.max(...ys3),centerX=(minX+maxX)/2,centerY=(minY+maxY)/2;obstacles.push({type:"rect",layers:EVERY_LAYER2,center:{x:centerX,y:centerY},width:maxX-minX,height:maxY-minY,connectedTo:withNetId([element.pcb_plated_hole_id])})}}else if(element.type==="pcb_trace"){let traceObstacles=getObstaclesFromRoute2(element.route.map(rp2=>({x:rp2.x,y:rp2.y,layer:"layer"in rp2?rp2.layer:rp2.from_layer})),element.source_trace_id);obstacles.push(...traceObstacles)}else if(element.type==="pcb_via"){let netIsAssignable=!!(element.net_is_assignable??element.netIsAssignable);obstacles.push({type:"rect",layers:element.layers,center:{x:element.x,y:element.y},connectedTo:[],width:element.outer_diameter,height:element.outer_diameter,netIsAssignable:netIsAssignable||void 0})}return obstacles},computeSchematicNetLabelCenter=({anchor_position,anchor_side,text,font_size=.18})=>{let charWidth=.1*(font_size/.18),width=text.length*charWidth,height=font_size,center2={...anchor_position};switch(anchor_side){case"right":center2.x-=width/2;break;case"left":center2.x+=width/2;break;case"top":center2.y-=height/2;break;case"bottom":center2.y+=height/2;break}return center2},getOtherSchematicTraces=({db,source_trace_id,sameNetOnly,differentNetOnly})=>{!sameNetOnly&&!differentNetOnly&&(differentNetOnly=!0);let mySourceTrace=db.source_trace.get(source_trace_id),traces=[];for(let otherSchematicTrace of db.schematic_trace.list()){if(otherSchematicTrace.source_trace_id===source_trace_id)continue;let isSameNet=db.source_trace.get(otherSchematicTrace.source_trace_id)?.subcircuit_connectivity_map_key===mySourceTrace.subcircuit_connectivity_map_key;differentNetOnly&&isSameNet||sameNetOnly&&!isSameNet||traces.push(otherSchematicTrace)}return traces},createSchematicTraceCrossingSegments=({edges:inputEdges,otherEdges})=>{let edges=[...inputEdges];for(let i3=0;i3<edges.length;i3++){if(i3>2e3)throw new Error("Over 2000 iterations spent inside createSchematicTraceCrossingSegments, you have triggered an infinite loop, please report this!");let edge=edges[i3],edgeOrientation=Math.abs(edge.from.x-edge.to.x)<.01?"vertical":edge.from.y===edge.to.y?"horizontal":"not-orthogonal";if(edgeOrientation==="not-orthogonal")continue;let otherEdgesIntersections=[];for(let otherEdge of otherEdges){let otherOrientation=otherEdge.from.x===otherEdge.to.x?"vertical":otherEdge.from.y===otherEdge.to.y?"horizontal":"not-orthogonal";if(otherOrientation==="not-orthogonal"||edgeOrientation===otherOrientation)continue;if(doesLineIntersectLine2([edge.from,edge.to],[otherEdge.from,otherEdge.to],{lineThickness:.01})){let intersectX=edgeOrientation==="vertical"?edge.from.x:otherEdge.from.x,intersectY=edgeOrientation==="vertical"?otherEdge.from.y:edge.from.y,crossingPoint2={x:intersectX,y:intersectY};otherEdgesIntersections.push({otherEdge,crossingPoint:crossingPoint2,distanceFromEdgeFrom:distance4(edge.from,crossingPoint2)})}}if(otherEdgesIntersections.length===0)continue;let closestIntersection=otherEdgesIntersections[0];for(let intersection of otherEdgesIntersections)intersection.distanceFromEdgeFrom<closestIntersection.distanceFromEdgeFrom&&(closestIntersection=intersection);let crossingPoint=closestIntersection.crossingPoint,crossingSegmentLength=.075;if(crossingPoint.x===edge.from.x&&crossingPoint.y===edge.from.y)continue;let crossingUnitVec=getUnitVectorFromPointAToB2(edge.from,crossingPoint),beforeCrossing={x:crossingPoint.x-crossingUnitVec.x*crossingSegmentLength/2,y:crossingPoint.y-crossingUnitVec.y*crossingSegmentLength/2},afterCrossing={x:crossingPoint.x+crossingUnitVec.x*crossingSegmentLength/2,y:crossingPoint.y+crossingUnitVec.y*crossingSegmentLength/2},overshot=distance4(afterCrossing,edge.to)<crossingSegmentLength,newEdges=[{from:edge.from,to:beforeCrossing},{from:beforeCrossing,to:afterCrossing,is_crossing:!0},{from:afterCrossing,to:edge.to}];edges.splice(i3,1,...newEdges),i3+=newEdges.length-2,overshot&&i3++}return edges},TOLERANCE=.001,isPointWithinEdge=(point23,edge)=>{let minX=Math.min(edge.from.x,edge.to.x),maxX=Math.max(edge.from.x,edge.to.x),minY=Math.min(edge.from.y,edge.to.y),maxY=Math.max(edge.from.y,edge.to.y);return point23.x>=minX&&point23.x<=maxX&&point23.y>=minY&&point23.y<=maxY},getEdgeOrientation=edge=>{let isVertical3=Math.abs(edge.from.x-edge.to.x)<TOLERANCE,isHorizontal2=Math.abs(edge.from.y-edge.to.y)<TOLERANCE;return isVertical3?"vertical":isHorizontal2?"horizontal":"diagonal"},getIntersectionPoint=(edge1,edge2)=>{let orientation1=getEdgeOrientation(edge1),orientation22=getEdgeOrientation(edge2);if(orientation1===orientation22)return null;if(orientation1==="vertical"&&orientation22==="horizontal"||orientation1==="horizontal"&&orientation22==="vertical"){let verticalEdge=orientation1==="vertical"?edge1:edge2,horizontalEdge=orientation1==="horizontal"?edge1:edge2,x22=verticalEdge.from.x,y22=horizontalEdge.from.y,intersection2={x:x22,y:y22};return isPointWithinEdge(intersection2,edge1)&&isPointWithinEdge(intersection2,edge2)?intersection2:null}if(orientation1==="vertical"||orientation22==="vertical"){let verticalEdge=orientation1==="vertical"?edge1:edge2,diagonalEdge=orientation1==="vertical"?edge2:edge1,x22=verticalEdge.from.x,m3=(diagonalEdge.to.y-diagonalEdge.from.y)/(diagonalEdge.to.x-diagonalEdge.from.x),b3=diagonalEdge.from.y-m3*diagonalEdge.from.x,y22=m3*x22+b3,intersection2={x:x22,y:y22};return isPointWithinEdge(intersection2,edge1)&&isPointWithinEdge(intersection2,edge2)?intersection2:null}let m12=(edge1.to.y-edge1.from.y)/(edge1.to.x-edge1.from.x),b12=edge1.from.y-m12*edge1.from.x,m22=(edge2.to.y-edge2.from.y)/(edge2.to.x-edge2.from.x),b22=edge2.from.y-m22*edge2.from.x;if(Math.abs(m12-m22)<TOLERANCE)return null;let x3=(b22-b12)/(m12-m22),y3=m12*x3+b12,intersection={x:x3,y:y3};return isPointWithinEdge(intersection,edge1)&&isPointWithinEdge(intersection,edge2)?intersection:null},createSchematicTraceJunctions=({edges:myEdges,db,source_trace_id})=>{let otherEdges=getOtherSchematicTraces({db,source_trace_id,sameNetOnly:!0}).flatMap(t6=>t6.edges),junctions=new Map;for(let myEdge of myEdges)for(let otherEdge of otherEdges){let intersection=getIntersectionPoint(myEdge,otherEdge);if(intersection){let key=`${intersection.x.toFixed(6)},${intersection.y.toFixed(6)}`;junctions.has(key)||junctions.set(key,intersection)}}return Array.from(junctions.values())};function getObstaclesFromBounds(bounds,opts={}){let{minX,maxX,minY,maxY}=bounds,PADDING=opts.padding??1;if(!isFinite(minX)||!isFinite(maxX)||!isFinite(minY)||!isFinite(maxY))return[];let left=minX-PADDING,right=maxX+PADDING,top=maxY+PADDING,bottom=minY-PADDING,thickness=.01;return[{type:"rect",layers:["top"],center:{x:(left+right)/2,y:top},width:right-left,height:thickness,connectedTo:[]},{type:"rect",layers:["top"],center:{x:(left+right)/2,y:bottom},width:right-left,height:thickness,connectedTo:[]},{type:"rect",layers:["top"],center:{x:left,y:(top+bottom)/2},width:thickness,height:top-bottom,connectedTo:[]},{type:"rect",layers:["top"],center:{x:right,y:(top+bottom)/2},width:thickness,height:top-bottom,connectedTo:[]}]}var getSchematicObstaclesForTrace=trace=>{let db=trace.root.db,connectedPorts=trace._findConnectedPorts().ports??[],connectedPortIds=new Set(connectedPorts.map(p4=>p4.schematic_port_id)),obstacles=[];for(let elm of db.toArray()){if(elm.type==="schematic_component"){let isSymbol3=!!elm.symbol_name,dominateAxis=elm.size.width>elm.size.height?"horz":"vert";obstacles.push({type:"rect",layers:["top"],center:elm.center,width:elm.size.width+(isSymbol3&&dominateAxis==="horz"?-.5:0),height:elm.size.height+(isSymbol3&&dominateAxis==="vert"?-.5:0),connectedTo:[]})}if(elm.type==="schematic_port"){if(connectedPortIds.has(elm.schematic_port_id))continue;let dirVec=elm.facing_direction?getUnitVectorFromDirection2(elm.facing_direction):{x:0,y:0};obstacles.push({type:"rect",layers:["top"],center:{x:elm.center.x-dirVec.x*.1,y:elm.center.y-dirVec.y*.1},width:.1+Math.abs(dirVec.x)*.3,height:.1+Math.abs(dirVec.y)*.3,connectedTo:[]})}elm.type==="schematic_text"&&obstacles.push({type:"rect",layers:["top"],center:elm.position,width:(elm.text?.length??0)*.1,height:.2,connectedTo:[]}),elm.type==="schematic_box"&&obstacles.push({type:"rect",layers:["top"],center:{x:elm.x,y:elm.y},width:elm.width,height:elm.height,connectedTo:[]})}let bounds=getBoundsForSchematic(db.toArray());return obstacles.push(...getObstaclesFromBounds(bounds,{padding:1})),obstacles},pushEdgesOfSchematicTraceToPreventOverlap=({edges,db,source_trace_id})=>{let mySourceTrace=db.source_trace.get(source_trace_id),otherEdges=getOtherSchematicTraces({db,source_trace_id,differentNetOnly:!0}).flatMap(t6=>t6.edges),edgeOrientation=edge=>{let{from,to:to2}=edge;return from.x===to2.x?"vertical":"horizontal"};for(let mySegment of edges){let mySegmentOrientation=edgeOrientation(mySegment),findOverlappingParallelSegment=()=>otherEdges.find(otherEdge=>edgeOrientation(otherEdge)===mySegmentOrientation&&doesLineIntersectLine2([mySegment.from,mySegment.to],[otherEdge.from,otherEdge.to],{lineThickness:.05})),overlappingParallelSegmentFromOtherTrace=findOverlappingParallelSegment();for(;overlappingParallelSegmentFromOtherTrace;)mySegmentOrientation==="horizontal"?(mySegment.from.y+=.1,mySegment.to.y+=.1):(mySegment.from.x+=.1,mySegment.to.x+=.1),overlappingParallelSegmentFromOtherTrace=findOverlappingParallelSegment()}},convertFacingDirectionToElbowDirection=facingDirection=>{switch(facingDirection){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:}},autorouterVersion=package_default.version??"unknown",AutorouterError=class extends Error{constructor(message){super(`${message} (capacity-autorouter@${autorouterVersion})`),this.name="AutorouterError"}},TraceConnectionError=class extends Error{constructor(errorData){super(errorData.message),this.errorData=errorData,this.name="TraceConnectionError"}},Trace_doInitialSchematicTraceRender=trace=>{if(trace.root?._featureMspSchematicTraceRouting||trace._couldNotFindPort||trace.root?.schematicDisabled)return;let{db}=trace.root,{_parsedProps:props,parent}=trace;if(!parent)throw new Error("Trace has no parent");let allPortsFound,connectedPorts;try{let result=trace._findConnectedPorts();allPortsFound=result.allPortsFound,connectedPorts=result.portsWithSelectors??[]}catch(error){if(error instanceof TraceConnectionError){db.source_trace_not_connected_error.insert({...error.errorData,error_type:"source_trace_not_connected_error"});return}throw error}let{netsWithSelectors}=trace._findConnectedNets();if(!allPortsFound)return;let portPairKey=connectedPorts.map(p4=>p4.port.schematic_port_id).sort().join(","),board=trace.root?._getBoard();if(board?._connectedSchematicPortPairs&&board._connectedSchematicPortPairs.has(portPairKey))return;let connection={name:trace.source_trace_id,pointsToConnect:[]},obstacles=getSchematicObstaclesForTrace(trace),portsWithPosition=connectedPorts.filter(({port})=>port.schematic_port_id!==null).map(({port})=>({port,position:port._getGlobalSchematicPositionAfterLayout(),schematic_port_id:port.schematic_port_id??void 0,facingDirection:port.facingDirection}));if(portsWithPosition.length===1&&netsWithSelectors.length===1){let net=netsWithSelectors[0].net,{port,position:anchorPos}=portsWithPosition[0],connectedNetLabel=trace.getSubcircuit().selectAll("netlabel").find(nl2=>{let conn=nl2._parsedProps.connection??nl2._parsedProps.connectsTo;return conn?Array.isArray(conn)?conn.some(selector=>trace.getSubcircuit().selectOne(selector,{port:!0})===port):trace.getSubcircuit().selectOne(conn,{port:!0})===port:!1});if(!connectedNetLabel){let dbNetLabel=db.schematic_net_label.getWhere({source_trace_id:trace.source_trace_id});dbNetLabel&&(connectedNetLabel=dbNetLabel)}if(connectedNetLabel){let labelPos="_getGlobalSchematicPositionBeforeLayout"in connectedNetLabel?connectedNetLabel._getGlobalSchematicPositionBeforeLayout():connectedNetLabel.anchor_position,edges2=[];anchorPos.x===labelPos.x||anchorPos.y===labelPos.y?edges2.push({from:anchorPos,to:labelPos}):(edges2.push({from:anchorPos,to:{x:labelPos.x,y:anchorPos.y}}),edges2.push({from:{x:labelPos.x,y:anchorPos.y},to:labelPos}));let dbTrace2=db.schematic_trace.insert({source_trace_id:trace.source_trace_id,edges:edges2,junctions:[],subcircuit_connectivity_map_key:trace.subcircuit_connectivity_map_key??void 0});trace.schematic_trace_id=dbTrace2.schematic_trace_id;return}if(trace.props.schDisplayLabel){let side2=getEnteringEdgeFromDirection(port.facingDirection)??"bottom";db.schematic_net_label.insert({text:trace.props.schDisplayLabel,source_net_id:net.source_net_id,anchor_position:anchorPos,center:computeSchematicNetLabelCenter({anchor_position:anchorPos,anchor_side:side2,text:trace.props.schDisplayLabel}),anchor_side:side2});return}let side=getEnteringEdgeFromDirection(port.facingDirection)??"bottom",netLabel=db.schematic_net_label.insert({text:net._parsedProps.name,source_net_id:net.source_net_id,anchor_position:anchorPos,center:computeSchematicNetLabelCenter({anchor_position:anchorPos,anchor_side:side,text:net._parsedProps.name}),anchor_side:side});return}if(trace.props.schDisplayLabel&&("from"in trace.props&&"to"in trace.props||"path"in trace.props)){trace._doInitialSchematicTraceRenderWithDisplayLabel();return}if(portsWithPosition.length<2)return;let edges=(()=>{let elbowEdges=[];for(let i3=0;i3<portsWithPosition.length-1;i3++){let start=portsWithPosition[i3],end=portsWithPosition[i3+1],path=calculateElbow({x:start.position.x,y:start.position.y,facingDirection:convertFacingDirectionToElbowDirection(start.facingDirection)},{x:end.position.x,y:end.position.y,facingDirection:convertFacingDirectionToElbowDirection(end.facingDirection)});for(let j3=0;j3<path.length-1;j3++)elbowEdges.push({from:path[j3],to:path[j3+1]})}let doesSegmentIntersectRect2=(edge,rect)=>{let halfW=rect.width/2,halfH=rect.height/2,left=rect.center.x-halfW,right=rect.center.x+halfW,top=rect.center.y-halfH,bottom=rect.center.y+halfH,inRect=p4=>p4.x>=left&&p4.x<=right&&p4.y>=top&&p4.y<=bottom;return inRect(edge.from)||inRect(edge.to)?!0:[[{x:left,y:top},{x:right,y:top}],[{x:right,y:top},{x:right,y:bottom}],[{x:right,y:bottom},{x:left,y:bottom}],[{x:left,y:bottom},{x:left,y:top}]].some(r4=>doesLineIntersectLine2([edge.from,edge.to],r4,{lineThickness:0}))};for(let edge of elbowEdges)for(let obstacle of obstacles)if(doesSegmentIntersectRect2(edge,obstacle))return null;return elbowEdges})();edges&&edges.length===0&&(edges=null),connection.pointsToConnect=portsWithPosition.map(({position:position2})=>({...position2,layer:"top"}));let bounds=computeObstacleBounds(obstacles),BOUNDS_MARGIN=2,simpleRouteJsonInput={minTraceWidth:.1,obstacles,connections:[connection],bounds:{minX:bounds.minX-BOUNDS_MARGIN,maxX:bounds.maxX+BOUNDS_MARGIN,minY:bounds.minY-BOUNDS_MARGIN,maxY:bounds.maxY+BOUNDS_MARGIN},layerCount:1},Autorouter=MultilayerIjump,skipOtherTraceInteraction=!1;if(trace.getSubcircuit().props._schDirectLineRoutingEnabled&&(Autorouter=DirectLineRouter,skipOtherTraceInteraction=!0),!edges){let results=new Autorouter({input:simpleRouteJsonInput,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(results.length===0){if(trace._isSymbolToChipConnection()||trace._isSymbolToSymbolConnection()||trace._isChipToChipConnection()){trace._doInitialSchematicTraceRenderWithDisplayLabel();return}results=new DirectLineRouter({input:simpleRouteJsonInput}).solveAndMapToTraces(),skipOtherTraceInteraction=!0}let[{route}]=results;edges=[];for(let i3=0;i3<route.length-1;i3++)edges.push({from:route[i3],to:route[i3+1]})}let source_trace_id=trace.source_trace_id,junctions=[];if(!skipOtherTraceInteraction){pushEdgesOfSchematicTraceToPreventOverlap({edges,db,source_trace_id});let otherEdges=getOtherSchematicTraces({db,source_trace_id,differentNetOnly:!0}).flatMap(t6=>t6.edges);edges=createSchematicTraceCrossingSegments({edges,otherEdges}),junctions=createSchematicTraceJunctions({edges,db,source_trace_id:trace.source_trace_id})}if(!edges||edges.length===0)return;let lastEdge=edges[edges.length-1],lastEdgePort=portsWithPosition[portsWithPosition.length-1],lastDominantDirection=getDominantDirection(lastEdge);edges.push(...getStubEdges({lastEdge,lastEdgePort,lastDominantDirection}));let firstEdge=edges[0],firstEdgePort=portsWithPosition[0],firstDominantDirection=getDominantDirection(firstEdge);if(edges.unshift(...getStubEdges({firstEdge,firstEdgePort,firstDominantDirection})),!trace.source_trace_id)throw new Error("Missing source_trace_id for schematic trace insertion.");if(trace.getSubcircuit()._parsedProps.schTraceAutoLabelEnabled&&countComplexElements(junctions,edges)>=5&&(trace._isSymbolToChipConnection()||trace._isSymbolToSymbolConnection()||trace._isChipToChipConnection())){trace._doInitialSchematicTraceRenderWithDisplayLabel();return}let dbTrace=db.schematic_trace.insert({source_trace_id:trace.source_trace_id,edges,junctions,subcircuit_connectivity_map_key:trace.subcircuit_connectivity_map_key??void 0});trace.schematic_trace_id=dbTrace.schematic_trace_id;for(let{port}of connectedPorts)port.schematic_port_id&&db.schematic_port.update(port.schematic_port_id,{is_connected:!0});board?._connectedSchematicPortPairs&&board._connectedSchematicPortPairs.add(portPairKey)};function getTraceLength(route){let totalLength=0;for(let i3=0;i3<route.length;i3++){let point23=route[i3];if(point23.route_type==="wire"){let nextPoint=route[i3+1];if(nextPoint){let dx2=nextPoint.x-point23.x,dy2=nextPoint.y-point23.y;totalLength+=Math.sqrt(dx2*dx2+dy2*dy2)}}else point23.route_type==="via"&&(totalLength+=1.6)}return totalLength}var DEFAULT_VIA_HOLE_DIAMETER=.3,DEFAULT_VIA_PAD_DIAMETER=.6,parseDistance=(value,fallback)=>{if(value===void 0)return fallback;if(typeof value=="number")return value;let parsed=parseFloat(value);return Number.isFinite(parsed)?parsed:fallback},getViaDiameterDefaults=pcbStyle2=>({holeDiameter:parseDistance(pcbStyle2?.viaHoleDiameter,DEFAULT_VIA_HOLE_DIAMETER),padDiameter:parseDistance(pcbStyle2?.viaPadDiameter,DEFAULT_VIA_PAD_DIAMETER)}),getViaDiameterDefaultsWithOverrides=(overrides,pcbStyle2)=>{let defaults=getViaDiameterDefaults(pcbStyle2);return{holeDiameter:overrides.holeDiameter??defaults.holeDiameter,padDiameter:overrides.padDiameter??defaults.padDiameter}},portToObjective=port=>({...port._getGlobalPcbPositionAfterLayout(),layers:port.getAvailablePcbLayers()}),SHOULD_USE_SINGLE_LAYER_ROUTING=!1;function Trace_doInitialPcbTraceRender(trace){if(trace.root?.pcbDisabled)return;let{db}=trace.root,{_parsedProps:props,parent}=trace,subcircuit=trace.getSubcircuit();if(!parent)throw new Error("Trace has no parent");if(subcircuit._parsedProps.routingDisabled)return;let cachedRoute=subcircuit._parsedProps.pcbRouteCache?.pcbTraces;if(cachedRoute){let pcb_trace22=db.pcb_trace.insert({route:cachedRoute.flatMap(trace2=>trace2.route),source_trace_id:trace.source_trace_id,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:trace.getGroup()?.pcb_group_id??void 0});trace.pcb_trace_id=pcb_trace22.pcb_trace_id;return}if(props.pcbPath&&props.pcbPath.length>0||props.pcbStraightLine||!subcircuit._shouldUseTraceByTraceRouting())return;let{allPortsFound,ports}=trace._findConnectedPorts(),portsConnectedOnPcbViaNet=[];if(!allPortsFound)return;let portsWithoutMatchedPcbPrimitive=[];for(let port of ports)port._hasMatchedPcbPrimitive()||portsWithoutMatchedPcbPrimitive.push(port);if(portsWithoutMatchedPcbPrimitive.length>0){db.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:trace.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, ${trace} wasn't routed. Missing ports: ${portsWithoutMatchedPcbPrimitive.map(p4=>p4.getString()).join(", ")}`,pcb_trace_id:trace.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:portsWithoutMatchedPcbPrimitive.map(p4=>p4.pcb_port_id).filter(Boolean)});return}let nets=trace._findConnectedNets().netsWithSelectors;if(ports.length===0&&nets.length===2){trace.renderError("Trace connects two nets, we haven't implemented a way to route this yet");return}else if(ports.length===1&&nets.length===1){let port=ports[0],otherPortsInNet=nets[0].net.getAllConnectedPorts().filter(p4=>p4!==port);if(otherPortsInNet.length===0){console.log("Nothing to connect this port to, the net is empty. TODO should emit a warning!");return}let closestPortInNet=getClosest(port,otherPortsInNet);portsConnectedOnPcbViaNet.push(closestPortInNet),ports.push(closestPortInNet)}else if(ports.length>1&&nets.length>=1){trace.renderError("Trace has more than one port and one or more nets, we don't currently support this type of complex trace routing");return}let hints=ports.flatMap(port=>port.matchedComponents.filter(c3=>c3.componentName==="TraceHint")),pcbRouteHints=(trace._parsedProps.pcbRouteHints??[]).concat(hints.flatMap(h3=>h3.getPcbRouteHints()));if(ports.length>2){trace.renderError(`Trace has more than two ports (${ports.map(p4=>p4.getString()).join(", ")}), routing between more than two ports for a single trace is not implemented`);return}if(trace.getSubcircuit().selectAll("trace").filter(trace2=>trace2.renderPhaseStates.PcbTraceRender.initialized).some(trace2=>trace2._portsRoutedOnPcb.length===ports.length&&trace2._portsRoutedOnPcb.every(portRoutedByOtherTrace=>ports.includes(portRoutedByOtherTrace))))return;let orderedRouteObjectives=[];pcbRouteHints.length===0?orderedRouteObjectives=[portToObjective(ports[0]),portToObjective(ports[1])]:orderedRouteObjectives=[portToObjective(ports[0]),...pcbRouteHints,portToObjective(ports[1])];let candidateLayerCombinations=findPossibleTraceLayerCombinations(orderedRouteObjectives);if(SHOULD_USE_SINGLE_LAYER_ROUTING&&candidateLayerCombinations.length===0){trace.renderError(`Could not find a common layer (using hints) for trace ${trace.getString()}`);return}let connMap=getFullConnectivityMapFromCircuitJson(trace.root.db.toArray()),[obstacles,errGettingObstacles]=tryNow(()=>getObstaclesFromCircuitJson2(trace.root.db.toArray()));if(errGettingObstacles){trace.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:trace.pcb_trace_id,message:`Error getting obstacles for autorouting: ${errGettingObstacles.message}`,source_trace_id:trace.source_trace_id,center:{x:0,y:0},pcb_port_ids:ports.map(p4=>p4.pcb_port_id),pcb_trace_id:trace.pcb_trace_id,pcb_component_ids:[]});return}for(let obstacle of obstacles)if(obstacle.connectedTo.length>0){let netId=connMap.getNetConnectedToId(obstacle.connectedTo[0]);netId&&obstacle.connectedTo.push(netId)}let orderedRoutePoints=[];if(candidateLayerCombinations.length===0)orderedRoutePoints=orderedRouteObjectives;else{let candidateLayerSelections=candidateLayerCombinations[0].layer_path;orderedRoutePoints=orderedRouteObjectives.map((t6,idx)=>t6.via?{...t6,via_to_layer:candidateLayerSelections[idx]}:{...t6,layers:[candidateLayerSelections[idx]]})}orderedRoutePoints[0].pcb_port_id=ports[0].pcb_port_id,orderedRoutePoints[orderedRoutePoints.length-1].pcb_port_id=ports[1].pcb_port_id;let routes=[];for(let[a3,b3]of pairs2(orderedRoutePoints)){let dominantLayer="via_to_layer"in a3?a3.via_to_layer:null,BOUNDS_MARGIN=2,aLayer="layers"in a3&&a3.layers.length===1?a3.layers[0]:dominantLayer??"top",bLayer="layers"in b3&&b3.layers.length===1?b3.layers[0]:dominantLayer??"top",pcbPortA="pcb_port_id"in a3?a3.pcb_port_id:null,pcbPortB="pcb_port_id"in b3?b3.pcb_port_id:null,minTraceWidth=trace._getExplicitTraceThickness()??trace.getSubcircuit()._parsedProps.minTraceWidth??.16,ijump=new MultilayerIjump({OBSTACLE_MARGIN:minTraceWidth*2,isRemovePathLoopsEnabled:!0,optimizeWithGoalBoxes:!!(pcbPortA&&pcbPortB),connMap,input:{obstacles,minTraceWidth,connections:[{name:trace.source_trace_id,pointsToConnect:[{...a3,layer:aLayer,pcb_port_id:pcbPortA},{...b3,layer:bLayer,pcb_port_id:pcbPortB}]}],layerCount:trace.getSubcircuit()._getSubcircuitLayerCount(),bounds:{minX:Math.min(a3.x,b3.x)-BOUNDS_MARGIN,maxX:Math.max(a3.x,b3.x)+BOUNDS_MARGIN,minY:Math.min(a3.y,b3.y)-BOUNDS_MARGIN,maxY:Math.max(a3.y,b3.y)+BOUNDS_MARGIN}}}),traces=null;try{traces=ijump.solveAndMapToTraces()}catch(e4){trace.renderError({type:"pcb_trace_error",pcb_trace_error_id:trace.source_trace_id,error_type:"pcb_trace_error",message:`error solving route: ${e4.message}`,source_trace_id:trace.pcb_trace_id,center:{x:(a3.x+b3.x)/2,y:(a3.y+b3.y)/2},pcb_port_ids:ports.map(p4=>p4.pcb_port_id),pcb_trace_id:trace.pcb_trace_id,pcb_component_ids:ports.map(p4=>p4.pcb_component_id)})}if(!traces)return;if(traces.length===0){trace.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:trace.pcb_trace_id,message:`Could not find a route for ${trace}`,source_trace_id:trace.source_trace_id,center:{x:(a3.x+b3.x)/2,y:(a3.y+b3.y)/2},pcb_port_ids:ports.map(p4=>p4.pcb_port_id),pcb_trace_id:trace.pcb_trace_id,pcb_component_ids:ports.map(p4=>p4.pcb_component_id)});return}let[autoroutedTrace]=traces;dominantLayer&&(autoroutedTrace.route=autoroutedTrace.route.map(p4=>(p4.route_type==="wire"&&!p4.layer&&(p4.layer=dominantLayer),p4))),pcbPortA&&autoroutedTrace.route[0].route_type==="wire"&&(autoroutedTrace.route[0].start_pcb_port_id=pcbPortA);let lastRoutePoint=autoroutedTrace.route[autoroutedTrace.route.length-1];pcbPortB&&lastRoutePoint.route_type==="wire"&&(lastRoutePoint.end_pcb_port_id=pcbPortB),routes.push(autoroutedTrace.route)}let mergedRoute=mergeRoutes(routes),traceLength=getTraceLength(mergedRoute),pcbStyle2=trace.getInheritedMergedProperty("pcbStyle"),{holeDiameter,padDiameter}=getViaDiameterDefaults(pcbStyle2),pcb_trace2=db.pcb_trace.insert({route:mergedRoute,source_trace_id:trace.source_trace_id,subcircuit_id:trace.getSubcircuit()?.subcircuit_id,trace_length:traceLength});trace._portsRoutedOnPcb=ports,trace.pcb_trace_id=pcb_trace2.pcb_trace_id;for(let point23 of mergedRoute)point23.route_type==="via"&&db.pcb_via.insert({pcb_trace_id:pcb_trace2.pcb_trace_id,x:point23.x,y:point23.y,hole_diameter:holeDiameter,outer_diameter:padDiameter,layers:[point23.from_layer,point23.to_layer],from_layer:point23.from_layer,to_layer:point23.to_layer});trace._insertErrorIfTraceIsOutsideBoard(mergedRoute,ports)}function computeLineRectIntersection(params){let{lineStart,lineEnd,rectCenter,rectWidth,rectHeight}=params,left=rectCenter.x-rectWidth/2,right=rectCenter.x+rectWidth/2,top=rectCenter.y+rectHeight/2,bottom=rectCenter.y-rectHeight/2,dx2=lineEnd.x-lineStart.x,dy2=lineEnd.y-lineStart.y,intersections=[];if(dx2!==0){let t6=(left-lineStart.x)/dx2;if(t6>=0&&t6<=1){let y3=lineStart.y+t6*dy2;y3>=bottom&&y3<=top&&intersections.push({x:left,y:y3,t:t6})}}if(dx2!==0){let t6=(right-lineStart.x)/dx2;if(t6>=0&&t6<=1){let y3=lineStart.y+t6*dy2;y3>=bottom&&y3<=top&&intersections.push({x:right,y:y3,t:t6})}}if(dy2!==0){let t6=(bottom-lineStart.y)/dy2;if(t6>=0&&t6<=1){let x3=lineStart.x+t6*dx2;x3>=left&&x3<=right&&intersections.push({x:x3,y:bottom,t:t6})}}if(dy2!==0){let t6=(top-lineStart.y)/dy2;if(t6>=0&&t6<=1){let x3=lineStart.x+t6*dx2;x3>=left&&x3<=right&&intersections.push({x:x3,y:top,t:t6})}}return intersections.length===0?null:(intersections.sort((a3,b3)=>a3.t-b3.t),{x:intersections[0].x,y:intersections[0].y})}function computeLineCircleIntersection(params){let{lineStart,lineEnd,circleCenter,circleRadius}=params,x12=lineStart.x-circleCenter.x,y12=lineStart.y-circleCenter.y,x22=lineEnd.x-circleCenter.x,y22=lineEnd.y-circleCenter.y,dx2=x22-x12,dy2=y22-y12,a3=dx2*dx2+dy2*dy2,b3=2*(x12*dx2+y12*dy2),c3=x12*x12+y12*y12-circleRadius*circleRadius,discriminant=b3*b3-4*a3*c3;if(discriminant<0)return null;let sqrtDisc=Math.sqrt(discriminant),t12=(-b3-sqrtDisc)/(2*a3),t22=(-b3+sqrtDisc)/(2*a3),t6=null;return t12>=0&&t12<=1?t6=t12:t22>=0&&t22<=1&&(t6=t22),t6===null?null:{x:lineStart.x+t6*dx2,y:lineStart.y+t6*dy2}}function clipTraceEndAtPad(params){let{traceStart,traceEnd,traceWidth,port}=params,pcbPrimitive=port.matchedComponents.find(c3=>c3.isPcbPrimitive);if(!pcbPrimitive)return traceEnd;let padBounds=pcbPrimitive._getPcbCircuitJsonBounds(),padWidth=padBounds.width,padHeight=padBounds.height,padCenter=padBounds.center,smallestPadDimension=Math.min(padWidth,padHeight);if(traceWidth<=smallestPadDimension/2)return traceEnd;let clippedPoint=null;if(pcbPrimitive.componentName==="SmtPad"){let smtPad=pcbPrimitive,padShape=smtPad._parsedProps.shape;if(padShape==="circle"){let radius=smtPad._parsedProps.radius;clippedPoint=computeLineCircleIntersection({lineStart:traceStart,lineEnd:traceEnd,circleCenter:padCenter,circleRadius:radius})}else(padShape==="rect"||padShape==="rotated_rect"||padShape==="pill"||padShape==="polygon")&&(clippedPoint=computeLineRectIntersection({lineStart:traceStart,lineEnd:traceEnd,rectCenter:padCenter,rectWidth:padWidth,rectHeight:padHeight}))}else if(pcbPrimitive.componentName==="PlatedHole"){let platedHole=pcbPrimitive;if(platedHole._parsedProps.shape==="circle"){let outerDiameter=platedHole._parsedProps.outerDiameter;clippedPoint=computeLineCircleIntersection({lineStart:traceStart,lineEnd:traceEnd,circleCenter:padCenter,circleRadius:outerDiameter/2})}else clippedPoint=computeLineRectIntersection({lineStart:traceStart,lineEnd:traceEnd,rectCenter:padCenter,rectWidth:padWidth,rectHeight:padHeight})}return clippedPoint??traceEnd}function Trace_doInitialPcbManualTraceRender(trace){if(trace.root?.pcbDisabled)return;let{db}=trace.root,{_parsedProps:props}=trace,subcircuit=trace.getSubcircuit(),hasPcbPath=props.pcbPath!==void 0,wantsStraightLine=!!props.pcbStraightLine;if(!hasPcbPath&&!wantsStraightLine)return;let{allPortsFound,ports,portsWithSelectors}=trace._findConnectedPorts();if(!allPortsFound)return;let portsWithoutMatchedPcbPrimitive=[];for(let port of ports)port._hasMatchedPcbPrimitive()||portsWithoutMatchedPcbPrimitive.push(port);if(portsWithoutMatchedPcbPrimitive.length>0){db.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:trace.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, ${trace} wasn't routed. Missing ports: ${portsWithoutMatchedPcbPrimitive.map(p4=>p4.getString()).join(", ")}`,pcb_trace_id:trace.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:portsWithoutMatchedPcbPrimitive.map(p4=>p4.pcb_port_id).filter(Boolean)});return}let width=trace._getExplicitTraceThickness()??trace.getSubcircuit()._parsedProps.minTraceWidth??.16;if(wantsStraightLine&&!hasPcbPath){if(!ports||ports.length<2){trace.renderError("pcbStraightLine requires exactly two connected ports");return}let[startPort,endPort]=ports,startLayers=startPort.getAvailablePcbLayers(),endLayers=endPort.getAvailablePcbLayers(),layer2=startLayers.find(layer3=>endLayers.includes(layer3))??startLayers[0]??endLayers[0]??"top",startPos=startPort._getGlobalPcbPositionAfterLayout(),endPos=endPort._getGlobalPcbPositionAfterLayout(),clippedStartPos=clipTraceEndAtPad({traceStart:endPos,traceEnd:startPos,traceWidth:width,port:startPort}),clippedEndPos=clipTraceEndAtPad({traceStart:startPos,traceEnd:endPos,traceWidth:width,port:endPort}),route2=[{route_type:"wire",x:clippedStartPos.x,y:clippedStartPos.y,width,layer:layer2,start_pcb_port_id:startPort.pcb_port_id},{route_type:"wire",x:clippedEndPos.x,y:clippedEndPos.y,width,layer:layer2,end_pcb_port_id:endPort.pcb_port_id}],traceLength2=getTraceLength(route2),pcb_trace22=db.pcb_trace.insert({route:route2,source_trace_id:trace.source_trace_id,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:trace.getGroup()?.pcb_group_id??void 0,trace_length:traceLength2});trace._portsRoutedOnPcb=ports,trace.pcb_trace_id=pcb_trace22.pcb_trace_id,trace._insertErrorIfTraceIsOutsideBoard(route2,ports);return}if(!props.pcbPath)return;let anchorPort;props.pcbPathRelativeTo&&(anchorPort=portsWithSelectors.find(p4=>p4.selector===props.pcbPathRelativeTo)?.port,anchorPort||(anchorPort=trace.getSubcircuit().selectOne(props.pcbPathRelativeTo))),anchorPort||(anchorPort=ports[0]);let otherPort=ports.find(p4=>p4!==anchorPort)??ports[1],layer=anchorPort.getAvailablePcbLayers()[0]||"top",anchorPos=anchorPort._getGlobalPcbPositionAfterLayout(),otherPos=otherPort._getGlobalPcbPositionAfterLayout(),route=[];route.push({route_type:"wire",x:anchorPos.x,y:anchorPos.y,width,layer,start_pcb_port_id:anchorPort.pcb_port_id});let transform5=anchorPort?._computePcbGlobalTransformBeforeLayout?.()||identity();for(let pt3 of props.pcbPath){let coordinates,isGlobalPosition=!1;if(typeof pt3=="string"){let resolvedPort=trace.getSubcircuit().selectOne(pt3,{type:"port"});if(!resolvedPort){db.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:trace.source_trace_id,message:`Could not resolve pcbPath selector "${pt3}" for ${trace}`,pcb_trace_id:trace.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:[]});continue}let portPos=resolvedPort._getGlobalPcbPositionAfterLayout();coordinates={x:portPos.x,y:portPos.y},isGlobalPosition=!0}else coordinates={x:pt3.x,y:pt3.y},isGlobalPosition=!1;let finalCoordinates=isGlobalPosition?coordinates:applyToPoint(transform5,coordinates);route.push({route_type:"wire",x:finalCoordinates.x,y:finalCoordinates.y,width,layer})}route.push({route_type:"wire",x:otherPos.x,y:otherPos.y,width,layer,end_pcb_port_id:otherPort.pcb_port_id});let traceLength=getTraceLength(route),pcb_trace2=db.pcb_trace.insert({route,source_trace_id:trace.source_trace_id,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:trace.getGroup()?.pcb_group_id??void 0,trace_length:traceLength});trace._portsRoutedOnPcb=ports,trace.pcb_trace_id=pcb_trace2.pcb_trace_id,trace._insertErrorIfTraceIsOutsideBoard(route,ports)}function Trace__doInitialSchematicTraceRenderWithDisplayLabel(trace){if(trace.root?.schematicDisabled)return;let{db}=trace.root,{_parsedProps:props,parent}=trace;if(!parent)throw new Error("Trace has no parent");let{allPortsFound,portsWithSelectors:connectedPorts}=trace._findConnectedPorts();if(!allPortsFound)return;let portsWithPosition=connectedPorts.map(({port})=>({port,position:port._getGlobalSchematicPositionAfterLayout(),schematic_port_id:port.schematic_port_id,facingDirection:port.facingDirection}));if(portsWithPosition.length<2)throw new Error("Expected at least two ports in portsWithPosition.");let fromPortName,toPortName,fromAnchorPos=portsWithPosition[0].position,fromPort=portsWithPosition[0].port;if("path"in trace.props){if(trace.props.path.length!==2)throw new Error("Invalid 'path': Must contain exactly two elements.");[fromPortName,toPortName]=trace.props.path}else{if(!("from"in trace.props&&"to"in trace.props))throw new Error("Missing 'from' or 'to' properties in props.");fromPortName=trace.props.from,toPortName=trace.props.to}if(!fromPort.source_port_id)throw new Error(`Missing source_port_id for the 'from' port (${fromPortName}).`);let toAnchorPos=portsWithPosition[1].position,toPort=portsWithPosition[1].port;if(!toPort.source_port_id)throw new Error(`Missing source_port_id for the 'to' port (${toPortName}).`);let existingFromNetLabel=db.schematic_net_label.list().find(label=>label.source_net_id===fromPort.source_port_id),existingToNetLabel=db.schematic_net_label.list().find(label=>label.source_net_id===toPort.source_port_id),[firstPort,secondPort]=connectedPorts.map(({port})=>port),pinFullName=firstPort.parent?.config.shouldRenderAsSchematicBox?`${firstPort?.parent?.props.name}_${firstPort?.props.name}`:`${secondPort?.parent?.props.name}_${secondPort?.props.name}`,netLabelText=trace.props.schDisplayLabel??pinFullName;if(existingFromNetLabel&&existingFromNetLabel.text!==netLabelText&&(existingFromNetLabel.text=`${netLabelText} / ${existingFromNetLabel.text}`),existingToNetLabel&&existingToNetLabel?.text!==netLabelText&&(existingToNetLabel.text=`${netLabelText} / ${existingToNetLabel.text}`),!existingToNetLabel){let toSide=getEnteringEdgeFromDirection(toPort.facingDirection)??"bottom";db.schematic_net_label.insert({text:trace.props.schDisplayLabel??pinFullName,source_net_id:toPort.source_port_id,anchor_position:toAnchorPos,center:computeSchematicNetLabelCenter({anchor_position:toAnchorPos,anchor_side:toSide,text:trace.props.schDisplayLabel??pinFullName}),anchor_side:toSide})}if(!existingFromNetLabel){let fromSide=getEnteringEdgeFromDirection(fromPort.facingDirection)??"bottom";db.schematic_net_label.insert({text:trace.props.schDisplayLabel??pinFullName,source_net_id:fromPort.source_port_id,anchor_position:fromAnchorPos,center:computeSchematicNetLabelCenter({anchor_position:fromAnchorPos,anchor_side:fromSide,text:trace.props.schDisplayLabel??pinFullName}),anchor_side:fromSide})}}function Trace__findConnectedPorts(trace){let{_parsedProps:props,parent}=trace;if(!parent)throw new Error("Trace has no parent");let portsWithSelectors=trace.getTracePortPathSelectors().map(selector=>({selector,port:trace.getSubcircuit().selectOne(selector,{type:"port"})??null}));for(let{selector,port}of portsWithSelectors)if(!port){let parentSelector,portToken,dotIndex=selector.lastIndexOf(".");if(dotIndex!==-1&&dotIndex>selector.lastIndexOf(" "))parentSelector=selector.slice(0,dotIndex),portToken=selector.slice(dotIndex+1);else{let match2=selector.match(/^(.*[ >])?([^ >]+)$/);parentSelector=match2?.[1]?.trim()??"",portToken=match2?.[2]??selector}let targetComponent=parentSelector?trace.getSubcircuit().selectOne(parentSelector):null;if(!targetComponent&&parentSelector&&!/[.#\[]/.test(parentSelector)&&(targetComponent=trace.getSubcircuit().selectOne(`.${parentSelector}`)),!targetComponent){let errorMessage2=parentSelector?`Could not find port for selector "${selector}". Component "${parentSelector}" not found`:`Could not find port for selector "${selector}"`,subcircuit2=trace.getSubcircuit(),sourceGroup2=subcircuit2.getGroup();throw new TraceConnectionError({error_type:"source_trace_not_connected_error",message:errorMessage2,subcircuit_id:subcircuit2.subcircuit_id??void 0,source_group_id:sourceGroup2?.source_group_id??void 0,source_trace_id:trace.source_trace_id??void 0,selectors_not_found:[selector]})}let ports=targetComponent.children.filter(c3=>c3.componentName==="Port"),portLabel=portToken.includes(".")?portToken.split(".").pop()??"":portToken,portNames=ports.flatMap(c3=>c3.getNameAndAliases()),hasCustomLabels=portNames.some(n3=>!/^(pin\d+|\d+)$/.test(n3)),labelList=Array.from(new Set(portNames)).join(", "),detail;ports.length===0?detail="It has no ports":hasCustomLabels?detail=`It has [${labelList}]`:detail=`It has ${ports.length} pins and no pinLabels (consider adding pinLabels)`;let errorMessage=`Could not find port for selector "${selector}". Component "${targetComponent.props.name??parentSelector}" found, but does not have pin "${portLabel}". ${detail}`,subcircuit=trace.getSubcircuit(),sourceGroup=subcircuit.getGroup();throw new TraceConnectionError({error_type:"source_trace_not_connected_error",message:errorMessage,subcircuit_id:subcircuit.subcircuit_id??void 0,source_group_id:sourceGroup?.source_group_id??void 0,source_trace_id:trace.source_trace_id??void 0,selectors_not_found:[selector]})}return portsWithSelectors.some(p4=>!p4.port)?{allPortsFound:!1}:{allPortsFound:!0,portsWithSelectors,ports:portsWithSelectors.map(({port})=>port)}}var Trace3=class extends PrimitiveComponent2{constructor(props){super(props);__publicField(this,"source_trace_id",null);__publicField(this,"pcb_trace_id",null);__publicField(this,"schematic_trace_id",null);__publicField(this,"_portsRoutedOnPcb");__publicField(this,"subcircuit_connectivity_map_key",null);__publicField(this,"_traceConnectionHash",null);__publicField(this,"_couldNotFindPort");this._portsRoutedOnPcb=[]}_getExplicitTraceThickness(){return this._parsedProps.thickness??this._parsedProps.width}get config(){return{zodProps:traceProps,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(p4=>typeof p4=="string"?p4:p4.getPortSelector()):[]}getTracePortPathSelectors(){return this._getTracePortOrNetSelectorListFromProps().filter(selector=>!selector.includes("net."))}getTracePathNetSelectors(){return this._getTracePortOrNetSelectorListFromProps().filter(selector=>selector.includes("net."))}_findConnectedPorts(){return Trace__findConnectedPorts(this)}_resolveNet(selector){let direct=this.getSubcircuit().selectOne(selector,{type:"net"});if(direct)return direct;let match2=selector.match(/^net\.(.+)$/),netName=match2?match2[1]:null;if(!netName)return null;let board=this.root?._getBoard();return board?board.getDescendants().find(d2=>d2.componentName==="Net"&&d2._parsedProps.name===netName)||null:(this.renderError(`Could not find a <board> ancestor for ${this}, so net "${selector}" cannot be resolved`),null)}_findConnectedNets(){let netsWithSelectors=this.getTracePathNetSelectors().map(selector=>({selector,net:this._resolveNet(selector)})),undefinedNets=netsWithSelectors.filter(n3=>!n3.net);return undefinedNets.length>0&&this.renderError(`Could not find net for selector "${undefinedNets[0].selector}" inside ${this}`),{netsWithSelectors,nets:netsWithSelectors.map(n3=>n3.net)}}_getAllTracesConnectedToSameNet(){let traces=this.getSubcircuit().selectAll("trace"),myNets=this._findConnectedNets().nets,myPorts=this._findConnectedPorts().ports??[];return traces.filter(t6=>{if(t6===this)return!1;let tNets=t6._findConnectedNets().nets,tPorts=t6._findConnectedPorts().ports??[];return tNets.some(n3=>myNets.includes(n3))||tPorts.some(p4=>myPorts.includes(p4))})}_isExplicitlyConnectedToPort(port){let{allPortsFound,portsWithSelectors:portsWithMetadata}=this._findConnectedPorts();return allPortsFound?portsWithMetadata.map(p4=>p4.port).includes(port):!1}_isExplicitlyConnectedToNet(net){return this._findConnectedNets().nets.includes(net)}doInitialCreateNetsFromProps(){createNetsFromProps(this,this.getTracePathNetSelectors())}_computeTraceConnectionHash(){let{allPortsFound,ports}=this._findConnectedPorts();return!allPortsFound||!ports?null:[...ports].sort((a3,b3)=>(a3.pcb_port_id||"").localeCompare(b3.pcb_port_id||"")).map(p4=>p4.pcb_port_id).join(",")}doInitialSourceTraceRender(){let{db}=this.root,{_parsedProps:props,parent}=this;if(!parent){this.renderError("Trace has no parent");return}let allPortsFound,ports;try{let result=this._findConnectedPorts();allPortsFound=result.allPortsFound,ports=result.portsWithSelectors??[]}catch(error){if(error instanceof TraceConnectionError){db.source_trace_not_connected_error.insert({...error.errorData,error_type:"source_trace_not_connected_error"}),this._couldNotFindPort=!0;return}throw error}if(!allPortsFound)return;this._traceConnectionHash=this._computeTraceConnectionHash();let existingTrace=db.source_trace.list().find(t6=>t6.subcircuit_connectivity_map_key===this.subcircuit_connectivity_map_key&&t6.connected_source_port_ids.sort().join(",")===this._traceConnectionHash);if(existingTrace){this.source_trace_id=existingTrace.source_trace_id;return}let nets=this._findConnectedNets().nets,displayName=getTraceDisplayName({ports,nets}),trace=db.source_trace.insert({connected_source_port_ids:ports.map(p4=>p4.port.source_port_id),connected_source_net_ids:nets.map(n3=>n3.source_net_id),subcircuit_id:this.getSubcircuit()?.subcircuit_id,max_length:getMaxLengthFromConnectedCapacitors(ports.map(p4=>p4.port),{db})??props.maxLength,display_name:displayName,min_trace_thickness:this._getExplicitTraceThickness()});this.source_trace_id=trace.source_trace_id}_insertErrorIfTraceIsOutsideBoard(mergedRoute,ports){let{db}=this.root;isRouteOutsideBoard(mergedRoute,{db})&&db.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:ports.map(p4=>p4.pcb_port_id)})}doInitialPcbManualTraceRender(){Trace_doInitialPcbManualTraceRender(this)}doInitialPcbTraceRender(){Trace_doInitialPcbTraceRender(this)}_doInitialSchematicTraceRenderWithDisplayLabel(){Trace__doInitialSchematicTraceRenderWithDisplayLabel(this)}_isSymbolToChipConnection(){let{allPortsFound,ports}=this._findConnectedPorts();if(!allPortsFound||ports.length!==2)return!1;let[port1,port2]=ports;if(!port1?.parent||!port2?.parent)return!1;let isPort1Chip=port1.parent.config.shouldRenderAsSchematicBox,isPort2Chip=port2.parent.config.shouldRenderAsSchematicBox;return isPort1Chip&&!isPort2Chip||!isPort1Chip&&isPort2Chip}_isSymbolToSymbolConnection(){let{allPortsFound,ports}=this._findConnectedPorts();if(!allPortsFound||ports.length!==2)return!1;let[port1,port2]=ports;if(!port1?.parent||!port2?.parent)return!1;let isPort1Symbol=!port1.parent.config.shouldRenderAsSchematicBox,isPort2Symbol=!port2.parent.config.shouldRenderAsSchematicBox;return isPort1Symbol&&isPort2Symbol}_isChipToChipConnection(){let{allPortsFound,ports}=this._findConnectedPorts();if(!allPortsFound||ports.length!==2)return!1;let[port1,port2]=ports;if(!port1?.parent||!port2?.parent)return!1;let isPort1Chip=port1.parent.config.shouldRenderAsSchematicBox,isPort2Chip=port2.parent.config.shouldRenderAsSchematicBox;return isPort1Chip&&isPort2Chip}doInitialSchematicTraceRender(){Trace_doInitialSchematicTraceRender(this)}},NormalComponent__getMinimumFlexContainerSize=component=>{let{db}=component.root;if(component.pcb_component_id){let pcbComponent=db.pcb_component.get(component.pcb_component_id);return pcbComponent?{width:pcbComponent.width,height:pcbComponent.height}:null}if(component.pcb_group_id){let pcbGroup=db.pcb_group.get(component.pcb_group_id);if(!pcbGroup)return null;if(pcbGroup.outline&&pcbGroup.outline.length>0){let bounds=getBoundsFromPoints(pcbGroup.outline);return bounds?{width:bounds.maxX-bounds.minX,height:bounds.maxY-bounds.minY}:null}return{width:pcbGroup.width??0,height:pcbGroup.height??0}}return null},NormalComponent__repositionOnPcb=(component,position2)=>{let{db}=component.root,allCircuitJson=db.toArray();if(component.pcb_component_id){repositionPcbComponentTo(allCircuitJson,component.pcb_component_id,position2);return}if(component.source_group_id){repositionPcbGroupTo(allCircuitJson,component.source_group_id,position2);return}throw new Error(`Cannot reposition component ${component.getString()}: no pcb_component_id or source_group_id`)},NormalComponent_doInitialSourceDesignRuleChecks=component=>{let{db}=component.root;if(!component.source_component_id)return;let ports=component.selectAll("port"),traces=db.source_trace.list(),connected=new Set;for(let trace of traces)for(let id of trace.connected_source_port_ids)connected.add(id);let internalGroups=component._getInternallyConnectedPins();for(let group of internalGroups)if(group.some(p4=>p4.source_port_id&&connected.has(p4.source_port_id)))for(let p4 of group)p4.source_port_id&&connected.add(p4.source_port_id);for(let port of ports)port.source_port_id&&shouldCheckPortForMissingTrace(component,port)&&(connected.has(port.source_port_id)||db.source_pin_missing_trace_warning.insert({message:`Port ${port.getNameAndAliases()[0]} on ${component.props.name} is missing a trace`,source_component_id:component.source_component_id,source_port_id:port.source_port_id,subcircuit_id:component.getSubcircuit().subcircuit_id??void 0,warning_type:"source_pin_missing_trace_warning"}))},shouldCheckPortForMissingTrace=(component,port)=>{if(component.config.componentName==="Chip"){let pinAttributes=component.props.pinAttributes;if(!pinAttributes)return!1;for(let alias of port.getNameAndAliases()){let attrs=pinAttributes[alias];if(attrs?.requiresPower||attrs?.requiresGround||attrs?.requiresVoltage!==void 0)return!0}return!1}return!0};function getPcbTextBounds(text){let fontSize=text.font_size,textWidth=text.text.length*fontSize*.6,textHeight=fontSize,anchorAlignment=text.anchor_alignment||"center",centerX=text.anchor_position.x,centerY=text.anchor_position.y;switch(anchorAlignment){case"top_left":centerX=text.anchor_position.x+textWidth/2,centerY=text.anchor_position.y+textHeight/2;break;case"top_center":centerX=text.anchor_position.x,centerY=text.anchor_position.y+textHeight/2;break;case"top_right":centerX=text.anchor_position.x-textWidth/2,centerY=text.anchor_position.y+textHeight/2;break;case"center_left":centerX=text.anchor_position.x+textWidth/2,centerY=text.anchor_position.y;break;case"center":centerX=text.anchor_position.x,centerY=text.anchor_position.y;break;case"center_right":centerX=text.anchor_position.x-textWidth/2,centerY=text.anchor_position.y;break;case"bottom_left":centerX=text.anchor_position.x+textWidth/2,centerY=text.anchor_position.y-textHeight/2;break;case"bottom_center":centerX=text.anchor_position.x,centerY=text.anchor_position.y-textHeight/2;break;case"bottom_right":centerX=text.anchor_position.x-textWidth/2,centerY=text.anchor_position.y-textHeight/2;break;default:centerX=text.anchor_position.x,centerY=text.anchor_position.y;break}return{x:centerX-textWidth/2,y:centerY-textHeight/2,width:textWidth,height:textHeight}}function NormalComponent_doInitialSilkscreenOverlapAdjustment(component){if(!component._adjustSilkscreenTextAutomatically||component.root?.pcbDisabled||!component.pcb_component_id)return;let{db}=component.root,componentCenter=component._getPcbCircuitJsonBounds().center,silkscreenTexts=db.pcb_silkscreen_text.list({pcb_component_id:component.pcb_component_id}).filter(text=>text.text===component.name);if(silkscreenTexts.length===0)return;let obstacleBounds=component.getSubcircuit().selectAll("[_isNormalComponent=true]").filter(comp=>comp!==component&&comp.pcb_component_id).map(comp=>{let bounds=comp._getPcbCircuitJsonBounds(),box2={center:bounds.center,width:bounds.width,height:bounds.height};return getBoundingBox2(box2)});for(let silkscreenText of silkscreenTexts){let currentPosition=silkscreenText.anchor_position,textBounds=getPcbTextBounds(silkscreenText),textBox={center:{x:textBounds.x+textBounds.width/2,y:textBounds.y+textBounds.height/2},width:textBounds.width,height:textBounds.height},textBoundsBox=getBoundingBox2(textBox);if(!obstacleBounds.some(obstacle=>doBoundsOverlap(textBoundsBox,obstacle)))continue;let flippedX=2*componentCenter.x-currentPosition.x,flippedY=2*componentCenter.y-currentPosition.y,flippedTextBox={center:{x:flippedX,y:flippedY},width:textBounds.width,height:textBounds.height},flippedTextBounds=getBoundingBox2(flippedTextBox);obstacleBounds.some(obstacle=>doBoundsOverlap(flippedTextBounds,obstacle))||db.pcb_silkscreen_text.update(silkscreenText.pcb_silkscreen_text_id,{anchor_position:{x:flippedX,y:flippedY}})}}function filterPinLabels(pinLabels){if(!pinLabels)return{validPinLabels:pinLabels,invalidPinLabelsMessages:[]};let validPinLabels={},invalidPinLabelsMessages=[];for(let[pin,labelOrLabels]of Object.entries(pinLabels)){let labels=Array.isArray(labelOrLabels)?labelOrLabels.slice():[labelOrLabels],validLabels=[];for(let label of labels)isValidPinLabel(pin,label)?validLabels.push(label):invalidPinLabelsMessages.push(`Invalid pin label: ${pin} = '${label}' - excluding from component. Please use a valid pin label.`);validLabels.length>0&&(validPinLabels[pin]=Array.isArray(labelOrLabels)?validLabels:validLabels[0])}return{validPinLabels:Object.keys(validPinLabels).length>0?validPinLabels:void 0,invalidPinLabelsMessages}}function isValidPinLabel(pin,label){try{let testProps={name:"test",footprint:"test",pinLabels:{[pin]:label}};return chipProps.safeParse(testProps).success}catch{return!1}}var isHttpUrl=s4=>s4.startsWith("http://")||s4.startsWith("https://"),parseLibraryFootprintRef=s4=>{if(isHttpUrl(s4))return null;let idx=s4.indexOf(":");if(idx<=0)return null;let footprintLib=s4.slice(0,idx),footprintName=s4.slice(idx+1);return!footprintLib||!footprintName?null:{footprintLib,footprintName}},isStaticAssetPath=s4=>s4.startsWith("/"),resolveStaticFileImportDebug=(0,import_debug9.default)("tscircuit:core:resolveStaticFileImport");async function resolveStaticFileImport(path,platform){if(!path)return path;let resolver=platform?.resolveProjectStaticFileImportUrl;if(resolver&&path.startsWith("/"))try{let resolved=await resolver(path);if(resolved)return resolved}catch(error){resolveStaticFileImportDebug("failed to resolve static file via platform resolver",error)}return constructAssetUrl(path,platform?.projectBaseUrl)}function NormalComponent_doInitialPcbFootprintStringRender(component,queueAsyncEffect){let{footprint}=component.props;if(footprint??(footprint=component._getImpliedFootprintString?.()),!footprint)return;let{pcbRotation,pinLabels,pcbPinLabels}=component.props,fileExtension=getFileExtension(String(footprint)),footprintParser=fileExtension?component.root?.platform?.footprintFileParserMap?.[fileExtension]:null;if(typeof footprint=="string"&&(isHttpUrl(footprint)||isStaticAssetPath(footprint))&&footprintParser){if(component._hasStartedFootprintUrlLoad)return;component._hasStartedFootprintUrlLoad=!0,queueAsyncEffect("load-footprint-from-platform-file-parser",async()=>{let footprintUrl=isHttpUrl(footprint)?footprint:await resolveStaticFileImport(footprint,component.root?.platform);try{let result=await footprintParser.loadFromUrl(footprintUrl),fpComponents=createComponentsFromCircuitJson({componentName:component.name,componentRotation:pcbRotation,footprinterString:footprintUrl,pinLabels,pcbPinLabels},result.footprintCircuitJson);component.addAll(fpComponents),component._markDirty("InitializePortsFromChildren")}catch(err){let db=component.root?.db;if(db&&component.source_component_id&&component.pcb_component_id){let subcircuit=component.getSubcircuit(),errorMsg=`${component.getString()} failed to load footprint "${footprintUrl}": `+(err instanceof Error?err.message:String(err)),errorObj=external_footprint_load_error.parse({type:"external_footprint_load_error",message:errorMsg,pcb_component_id:component.pcb_component_id,source_component_id:component.source_component_id,subcircuit_id:subcircuit.subcircuit_id??void 0,pcb_group_id:component.getGroup()?.pcb_group_id??void 0,footprinter_string:footprintUrl});db.external_footprint_load_error.insert(errorObj)}throw err}});return}if(typeof footprint=="string"&&isHttpUrl(footprint)){if(component._hasStartedFootprintUrlLoad)return;component._hasStartedFootprintUrlLoad=!0;let url=footprint;queueAsyncEffect("load-footprint-url",async()=>{try{let res2=await fetch(url);if(!res2.ok)throw new Error(`Failed to fetch footprint: ${res2.status}`);let soup=await res2.json(),fpComponents=createComponentsFromCircuitJson({componentName:component.name,componentRotation:pcbRotation,footprinterString:url,pinLabels,pcbPinLabels},soup);component.addAll(fpComponents),component._markDirty("InitializePortsFromChildren")}catch(err){let db=component.root?.db;if(db&&component.source_component_id&&component.pcb_component_id){let subcircuit=component.getSubcircuit(),errorMsg=`${component.getString()} failed to load external footprint "${url}": `+(err instanceof Error?err.message:String(err)),errorObj=external_footprint_load_error.parse({type:"external_footprint_load_error",message:errorMsg,pcb_component_id:component.pcb_component_id,source_component_id:component.source_component_id,subcircuit_id:subcircuit.subcircuit_id??void 0,pcb_group_id:component.getGroup()?.pcb_group_id??void 0,footprinter_string:url});db.external_footprint_load_error.insert(errorObj)}throw err}});return}if(typeof footprint=="string"){let libRef=parseLibraryFootprintRef(footprint);if(!libRef||component._hasStartedFootprintUrlLoad)return;component._hasStartedFootprintUrlLoad=!0;let libMap=component.root?.platform?.footprintLibraryMap?.[libRef.footprintLib],resolverFn;if(typeof libMap=="function"&&(resolverFn=libMap),!resolverFn)return;let resolvedPcbStyle=component.getInheritedMergedProperty("pcbStyle");queueAsyncEffect("load-lib-footprint",async()=>{try{let result=await resolverFn(libRef.footprintName,{resolvedPcbStyle}),circuitJson=null;if(Array.isArray(result)?circuitJson=result:Array.isArray(result.footprintCircuitJson)&&(circuitJson=result.footprintCircuitJson),!circuitJson)return;let fpComponents=createComponentsFromCircuitJson({componentName:component.name,componentRotation:pcbRotation,footprinterString:footprint,pinLabels,pcbPinLabels},circuitJson);component.addAll(fpComponents),!Array.isArray(result)&&result.cadModel&&(component._asyncFootprintCadModel=result.cadModel);for(let child of component.children)child.componentName==="Port"&&child._markDirty?.("PcbPortRender");component._markDirty("InitializePortsFromChildren")}catch(err){let db=component.root?.db;if(db&&component.source_component_id&&component.pcb_component_id){let subcircuit=component.getSubcircuit(),errorMsg=`${component.getString()} failed to load external footprint "${footprint}": `+(err instanceof Error?err.message:String(err)),errorObj=external_footprint_load_error.parse({type:"external_footprint_load_error",message:errorMsg,pcb_component_id:component.pcb_component_id,source_component_id:component.source_component_id,subcircuit_id:subcircuit.subcircuit_id??void 0,pcb_group_id:component.getGroup()?.pcb_group_id??void 0,footprinter_string:footprint});db.external_footprint_load_error.insert(errorObj)}throw err}});return}if(!(0,import_react3.isValidElement)(footprint)&&footprint.componentName==="Footprint"&&component.add(footprint),Array.isArray(footprint)&&!(0,import_react3.isValidElement)(footprint)&&footprint.length>0){try{let fpComponents=createComponentsFromCircuitJson({componentName:component.name,componentRotation:pcbRotation,footprinterString:"",pinLabels,pcbPinLabels},footprint);component.addAll(fpComponents)}catch(err){let db=component.root?.db;if(db&&component.source_component_id&&component.pcb_component_id){let subcircuit=component.getSubcircuit(),errorMsg=`${component.getString()} failed to load json footprint: `+(err instanceof Error?err.message:String(err)),errorObj=circuit_json_footprint_load_error.parse({type:"circuit_json_footprint_load_error",message:errorMsg,pcb_component_id:component.pcb_component_id,source_component_id:component.source_component_id,subcircuit_id:subcircuit.subcircuit_id??void 0,pcb_group_id:component.getGroup()?.pcb_group_id??void 0});db.circuit_json_footprint_load_error.insert(errorObj)}throw err}return}}function NormalComponent_doInitialPcbComponentAnchorAlignment(component){if(component.root?.pcbDisabled||!component.pcb_component_id)return;let{pcbX,pcbY}=component._parsedProps,pcbPositionAnchor=component.props?.pcbPositionAnchor;if(!pcbPositionAnchor||pcbX===void 0&&pcbY===void 0)return;let bounds=getBoundsOfPcbComponents(component.children);if(bounds.width===0||bounds.height===0)return;let currentCenter={...{x:(bounds.minX+bounds.maxX)/2,y:(bounds.minY+bounds.maxY)/2}},anchorPos=null;if(new Set(["center","top_left","top_center","top_right","center_left","center_right","bottom_left","bottom_center","bottom_right"]).has(pcbPositionAnchor)){let b3={left:bounds.minX,right:bounds.maxX,top:bounds.minY,bottom:bounds.maxY};switch(pcbPositionAnchor){case"center":anchorPos=currentCenter;break;case"top_left":anchorPos={x:b3.left,y:b3.top};break;case"top_center":anchorPos={x:currentCenter.x,y:b3.top};break;case"top_right":anchorPos={x:b3.right,y:b3.top};break;case"center_left":anchorPos={x:b3.left,y:currentCenter.y};break;case"center_right":anchorPos={x:b3.right,y:currentCenter.y};break;case"bottom_left":anchorPos={x:b3.left,y:b3.bottom};break;case"bottom_center":anchorPos={x:currentCenter.x,y:b3.bottom};break;case"bottom_right":anchorPos={x:b3.right,y:b3.bottom};break}}else try{let port=component.portMap[pcbPositionAnchor];port&&(anchorPos=port._getGlobalPcbPositionBeforeLayout())}catch{}if(!anchorPos)return;let newCenter={...currentCenter};pcbX!==void 0&&(newCenter.x+=pcbX-anchorPos.x),pcbY!==void 0&&(newCenter.y+=pcbY-anchorPos.y),(Math.abs(newCenter.x-currentCenter.x)>1e-6||Math.abs(newCenter.y-currentCenter.y)>1e-6)&&component._repositionOnPcb(newCenter)}var debug32=(0,import_debug5.default)("tscircuit:core"),rotation32=external_exports.object({x:rotation,y:rotation,z:rotation}),NormalComponent3=class extends PrimitiveComponent2{constructor(props){let filteredProps={...props},invalidPinLabelsMessages=[];if(filteredProps.pinLabels&&!Array.isArray(filteredProps.pinLabels)){let{validPinLabels,invalidPinLabelsMessages:messages}=filterPinLabels(filteredProps.pinLabels);filteredProps.pinLabels=validPinLabels,invalidPinLabelsMessages=messages}super(filteredProps);__publicField(this,"reactSubtrees",[]);__publicField(this,"_impliedFootprint");__publicField(this,"isPrimitiveContainer",!0);__publicField(this,"_isNormalComponent",!0);__publicField(this,"_attributeLowerToCamelNameMap",{_isnormalcomponent:"_isNormalComponent"});__publicField(this,"_asyncSupplierPartNumbers");__publicField(this,"_asyncFootprintCadModel");__publicField(this,"_isCadModelChild");__publicField(this,"pcb_missing_footprint_error_id");__publicField(this,"_hasStartedFootprintUrlLoad",!1);__publicField(this,"_invalidPinLabelMessages",[]);__publicField(this,"_adjustSilkscreenTextAutomatically",!1);this._invalidPinLabelMessages=invalidPinLabelsMessages,this._addChildrenFromStringFootprint(),this.initPorts()}get defaultInternallyConnectedPinNames(){return[]}get internallyConnectedPinNames(){return(this._parsedProps.internallyConnectedPins??this.defaultInternallyConnectedPinNames).map(pinGroup=>pinGroup.map(pin=>typeof pin=="number"?`pin${pin}`:pin))}doInitialSourceNameDuplicateComponentRemoval(){if(!this.name)return;let root=this.root;if(this.getSubcircuit().selectAll(`.${this.name}`).filter(component=>component!==this&&component._isNormalComponent&&component.renderPhaseStates?.SourceNameDuplicateComponentRemoval?.initialized).length>0){let pcbPosition2=this._getGlobalPcbPositionBeforeLayout(),schematicPosition=this._getGlobalSchematicPositionBeforeLayout();root.db.source_failed_to_create_component_error.insert({component_name:this.name,error_type:"source_failed_to_create_component_error",message:`Cannot create component "${this.name}": A component with the same name already exists`,pcb_center:pcbPosition2,schematic_center:schematicPosition}),this.shouldBeRemoved=!0;let childrenToRemove=[...this.children];for(let child of childrenToRemove)this.remove(child)}}initPorts(opts={}){if(this.root?.schematicDisabled)return;let{config}=this,portsToCreate=[],schPortArrangement=this._getSchematicPortArrangement();if(schPortArrangement&&!this._parsedProps.pinLabels){for(let side in schPortArrangement){let pins=schPortArrangement[side].pins;if(Array.isArray(pins))for(let pinNumberOrLabel of pins){let pinNumber=parsePinNumberFromLabelsOrThrow(pinNumberOrLabel,this._parsedProps.pinLabels);portsToCreate.push(new Port({pinNumber,aliases:opts.additionalAliases?.[`pin${pinNumber}`]??[]},{originDescription:`schPortArrangement:${side}`}))}}let sides=["left","right","top","bottom"],pinNum=1;for(let side of sides){let size2=schPortArrangement[`${side}Size`];for(let i3=0;i3<size2;i3++)portsToCreate.push(new Port({pinNumber:pinNum++,aliases:opts.additionalAliases?.[`pin${pinNum}`]??[]},{originDescription:`schPortArrangement:${side}`}))}}let pinLabels=this._parsedProps.pinLabels;if(pinLabels)for(let[pinNumber,label]of Object.entries(pinLabels)){pinNumber=pinNumber.replace("pin","");let existingPort=portsToCreate.find(p4=>p4._parsedProps.pinNumber===Number(pinNumber)),primaryLabel=Array.isArray(label)?label[0]:label,otherLabels=Array.isArray(label)?label.slice(1):[];existingPort?(existingPort.externallyAddedAliases.push(primaryLabel,...otherLabels),existingPort.props.name=primaryLabel):(existingPort=new Port({pinNumber:parseInt(pinNumber),name:primaryLabel,aliases:[...otherLabels,...opts.additionalAliases?.[`pin${parseInt(pinNumber)}`]??[]]},{originDescription:`pinLabels:pin${pinNumber}`}),portsToCreate.push(existingPort))}if(config.schematicSymbolName&&!opts.ignoreSymbolPorts){let sym=ef[this._getSchematicSymbolNameOrThrow()];if(!sym)return;for(let symPort of sym.ports){let pinNumber=getPinNumberFromLabels(symPort.labels);if(!pinNumber)continue;let existingPort=portsToCreate.find(p4=>p4._parsedProps.pinNumber===Number(pinNumber));if(existingPort)existingPort.schematicSymbolPortDef=symPort;else{let port=getPortFromHints(symPort.labels.concat(opts.additionalAliases?.[`pin${pinNumber}`]??[]));port&&(port.originDescription=`schematicSymbol:labels[0]:${symPort.labels[0]}`,port.schematicSymbolPortDef=symPort,portsToCreate.push(port))}}this.addAll(portsToCreate)}if(!this._getSchematicPortArrangement()){let portsFromFootprint=this.getPortsFromFootprint(opts);for(let port of portsFromFootprint)portsToCreate.some(p4=>p4.isMatchingAnyOf(port.getNameAndAliases()))||portsToCreate.push(port)}let requiredPinCount=opts.pinCount??this._getPinCount()??0;for(let pn3=1;pn3<=requiredPinCount;pn3++){if(portsToCreate.find(p4=>p4._parsedProps.pinNumber===pn3))continue;if(!schPortArrangement){portsToCreate.push(new Port({pinNumber:pn3,aliases:opts.additionalAliases?.[`pin${pn3}`]??[]}));continue}let explicitlyListedPinNumbersInSchPortArrangement=[...schPortArrangement.leftSide?.pins??[],...schPortArrangement.rightSide?.pins??[],...schPortArrangement.topSide?.pins??[],...schPortArrangement.bottomSide?.pins??[]].map(pn22=>parsePinNumberFromLabelsOrThrow(pn22,this._parsedProps.pinLabels));["leftSize","rightSize","topSize","bottomSize","leftPinCount","rightPinCount","topPinCount","bottomPinCount"].some(key=>key in schPortArrangement)&&(explicitlyListedPinNumbersInSchPortArrangement=Array.from({length:this._getPinCount()},(_4,i3)=>i3+1)),explicitlyListedPinNumbersInSchPortArrangement.includes(pn3)&&portsToCreate.push(new Port({pinNumber:pn3,aliases:opts.additionalAliases?.[`pin${pn3}`]??[]},{originDescription:`notOtherwiseAddedButDeducedFromPinCount:${pn3}`}))}portsToCreate.length>0&&this.addAll(portsToCreate)}_getImpliedFootprintString(){return null}_addChildrenFromStringFootprint(){let{pcbRotation,pinLabels,pcbPinLabels}=this.props,{footprint}=this.props;if(footprint??(footprint=this._getImpliedFootprintString?.()),!!footprint&&typeof footprint=="string"){if(isHttpUrl(footprint)||isStaticAssetPath(footprint)||parseLibraryFootprintRef(footprint))return;let fpSoup=fp.string(footprint).soup(),fpComponents=createComponentsFromCircuitJson({componentName:this.name??this.componentName,componentRotation:pcbRotation,footprinterString:footprint,pinLabels,pcbPinLabels},fpSoup);this.addAll(fpComponents)}}get portMap(){return new Proxy({},{get:(target,prop)=>{let port=this.children.find(c3=>c3.componentName==="Port"&&c3.isMatchingNameOrAlias(prop));if(!port)throw new Error(`There was an issue finding the port "${prop.toString()}" inside of a ${this.componentName} component with name: "${this.props.name}". This is a bug in @tscircuit/core`);return port}})}getInstanceForReactElement(element){for(let subtree of this.reactSubtrees)if(subtree.element===element)return subtree.component;return null}doInitialSourceRender(){let ftype=this.config.sourceFtype;if(!ftype)return;let{db}=this.root,{_parsedProps:props}=this,source_component=db.source_component.insert({ftype,name:this.name,manufacturer_part_number:props.manufacturerPartNumber??props.mfn,supplier_part_numbers:props.supplierPartNumbers});this.source_component_id=source_component.source_component_id}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;let{db}=this.root;if(this._invalidPinLabelMessages?.length&&this.root?.db)for(let message of this._invalidPinLabelMessages){let property_name="pinLabels",match2=message.match(/^Invalid pin label:\s*([^=]+)=\s*'([^']+)'/);match2&&(property_name=`pinLabels['${match2[2]}']`),this.root.db.source_property_ignored_warning.insert({source_component_id:this.source_component_id,property_name,message,error_type:"source_property_ignored_warning"})}let{schematicSymbolName}=this.config,{_parsedProps:props}=this;props.symbol&&(0,import_react2.isValidElement)(props.symbol)?this._doInitialSchematicComponentRenderWithReactSymbol(props.symbol):schematicSymbolName?this._doInitialSchematicComponentRenderWithSymbol():this._getSchematicBoxDimensions()&&this._doInitialSchematicComponentRenderWithSchematicBoxDimensions();let manualPlacement=this.getSubcircuit()?._getSchematicManualPlacementForComponent(this);if(this.schematic_component_id&&(this.props.schX!==void 0||this.props.schY!==void 0)&&manualPlacement){if(!this.schematic_component_id)return;let warning=schematic_manual_edit_conflict_warning.parse({type:"schematic_manual_edit_conflict_warning",schematic_manual_edit_conflict_warning_id:`schematic_manual_edit_conflict_${this.source_component_id}`,message:`${this.getString()} has both manual placement and prop coordinates. schX and schY will be used. Remove schX/schY or clear the manual placement.`,schematic_component_id:this.schematic_component_id,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id});db.schematic_manual_edit_conflict_warning.insert(warning)}}_getSchematicSymbolDisplayValue(){}_getInternallyConnectedPins(){if(this.internallyConnectedPinNames.length===0)return[];let internallyConnectedPorts=[];for(let netPortNames of this.internallyConnectedPinNames){let ports=[];for(let portName of netPortNames)ports.push(this.portMap[portName]);internallyConnectedPorts.push(ports)}return internallyConnectedPorts}_doInitialSchematicComponentRenderWithSymbol(){if(this.root?.schematicDisabled)return;let{db}=this.root,{_parsedProps:props}=this,symbol_name=this._getSchematicSymbolNameOrThrow(),symbol=ef[symbol_name],center2=this._getGlobalSchematicPositionBeforeLayout();if(symbol){let schematic_component2=db.schematic_component.insert({center:center2,size:symbol.size,source_component_id:this.source_component_id,is_box_with_pins:!0,symbol_name,symbol_display_value:this._getSchematicSymbolDisplayValue()});this.schematic_component_id=schematic_component2.schematic_component_id}}_doInitialSchematicComponentRenderWithReactSymbol(symbolElement){if(this.root?.schematicDisabled)return;let{db}=this.root,center2=this._getGlobalSchematicPositionBeforeLayout(),schematic_component2=db.schematic_component.insert({center:center2,size:{width:0,height:0},source_component_id:this.source_component_id,symbol_display_value:this._getSchematicSymbolDisplayValue(),is_box_with_pins:!1});this.schematic_component_id=schematic_component2.schematic_component_id}_doInitialSchematicComponentRenderWithSchematicBoxDimensions(){if(this.root?.schematicDisabled)return;let{db}=this.root,{_parsedProps:props}=this,dimensions=this._getSchematicBoxDimensions(),primaryPortLabels={};if(Array.isArray(props.pinLabels))props.pinLabels.forEach((label,index)=>{primaryPortLabels[String(index+1)]=label});else for(let[port,label]of Object.entries(props.pinLabels??{}))primaryPortLabels[port]=Array.isArray(label)?label[0]:label;let center2=this._getGlobalSchematicPositionBeforeLayout(),schPortArrangement=this._getSchematicPortArrangement(),schematic_component2=db.schematic_component.insert({center:center2,rotation:props.schRotation??0,size:dimensions.getSize(),port_arrangement:underscorifyPortArrangement(schPortArrangement),pin_spacing:props.schPinSpacing??.2,pin_styles:underscorifyPinStyles(props.schPinStyle,props.pinLabels),port_labels:primaryPortLabels,source_component_id:this.source_component_id}),hasTopOrBottomPins=schPortArrangement?.topSide!==void 0||schPortArrangement?.bottomSide!==void 0,schematic_box_width=dimensions?.getSize().width,schematic_box_height=dimensions?.getSize().height,manufacturer_part_number_schematic_text=db.schematic_text.insert({text:props.manufacturerPartNumber??"",schematic_component_id:schematic_component2.schematic_component_id,anchor:"left",rotation:0,position:{x:hasTopOrBottomPins?center2.x+(schematic_box_width??0)/2+.1:center2.x-(schematic_box_width??0)/2,y:hasTopOrBottomPins?center2.y+(schematic_box_height??0)/2+.35:center2.y-(schematic_box_height??0)/2-.13},color:"#006464",font_size:.18}),component_name_text=db.schematic_text.insert({text:props.name??"",schematic_component_id:schematic_component2.schematic_component_id,anchor:"left",rotation:0,position:{x:hasTopOrBottomPins?center2.x+(schematic_box_width??0)/2+.1:center2.x-(schematic_box_width??0)/2,y:hasTopOrBottomPins?center2.y+(schematic_box_height??0)/2+.55:center2.y+(schematic_box_height??0)/2+.13},color:"#006464",font_size:.18});this.schematic_component_id=schematic_component2.schematic_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,subcircuit=this.getSubcircuit(),componentLayer=props.layer??"top";if(componentLayer!=="top"&&componentLayer!=="bottom"){let error=pcb_component_invalid_layer_error.parse({type:"pcb_component_invalid_layer_error",message:`Component cannot be placed on layer '${componentLayer}'. Components can only be placed on 'top' or 'bottom' layers.`,source_component_id:this.source_component_id,layer:componentLayer,subcircuit_id:subcircuit.subcircuit_id??void 0});db.pcb_component_invalid_layer_error.insert(error)}let globalTransform=this._computePcbGlobalTransformBeforeLayout(),accumulatedRotation=decomposeTSR(globalTransform).rotation.angle*180/Math.PI,pcb_component2=db.pcb_component.insert({center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,layer:componentLayer==="top"||componentLayer==="bottom"?componentLayer:"top",rotation:props.pcbRotation??accumulatedRotation,source_component_id:this.source_component_id,subcircuit_id:subcircuit.subcircuit_id??void 0,do_not_place:props.doNotPlace??!1,obstructs_within_bounds:props.obstructsWithinBounds??!0});if(!(props.footprint??this._getImpliedFootprintString())&&!this.isGroup){let footprint_error=db.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=footprint_error.pcb_missing_footprint_error_id}this.pcb_component_id=pcb_component2.pcb_component_id;let manualPlacement=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if((this.props.pcbX!==void 0||this.props.pcbY!==void 0)&&manualPlacement){let warning=pcb_manual_edit_conflict_warning.parse({type:"pcb_manual_edit_conflict_warning",pcb_manual_edit_conflict_warning_id:`pcb_manual_edit_conflict_${this.source_component_id}`,message:`${this.getString()} has both manual placement and prop coordinates. pcbX and pcbY will be used. Remove pcbX/pcbY or clear the manual placement.`,pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,subcircuit_id:subcircuit.subcircuit_id??void 0});db.pcb_manual_edit_conflict_warning.insert(warning)}}doInitialPcbComponentSizeCalculation(){if(this.root?.pcbDisabled||!this.pcb_component_id)return;let{db}=this.root,{_parsedProps:props}=this,bounds=getBoundsOfPcbComponents(this.children);if(bounds.width===0||bounds.height===0)return;let center2={x:(bounds.minX+bounds.maxX)/2,y:(bounds.minY+bounds.maxY)/2};db.pcb_component.update(this.pcb_component_id,{center:center2,width:bounds.width,height:bounds.height})}updatePcbComponentSizeCalculation(){this.doInitialPcbComponentSizeCalculation()}doInitialSchematicComponentSizeCalculation(){if(this.root?.schematicDisabled||!this.schematic_component_id)return;let{db}=this.root;if(!db.schematic_component.get(this.schematic_component_id))return;let schematicElements=[],collectSchematicPrimitives=children=>{for(let child of children){if(child.isSchematicPrimitive&&child.componentName==="SchematicLine"){let line2=db.schematic_line.get(child.schematic_line_id);line2&&schematicElements.push(line2)}if(child.isSchematicPrimitive&&child.componentName==="SchematicRect"){let rect=db.schematic_rect.get(child.schematic_rect_id);rect&&schematicElements.push(rect)}if(child.isSchematicPrimitive&&child.componentName==="SchematicCircle"){let circle2=db.schematic_circle.get(child.schematic_circle_id);circle2&&schematicElements.push(circle2)}if(child.isSchematicPrimitive&&child.componentName==="SchematicArc"){let arc2=db.schematic_arc.get(child.schematic_arc_id);arc2&&schematicElements.push(arc2)}if(child.isSchematicPrimitive&&child.componentName==="SchematicText"){let text=db.schematic_text.get(child.schematic_text_id);text&&schematicElements.push(text)}child.children&&child.children.length>0&&collectSchematicPrimitives(child.children)}};if(collectSchematicPrimitives(this.children),schematicElements.length===0)return;let bounds=getBoundsForSchematic(schematicElements),width=Math.abs(bounds.maxX-bounds.minX),height=Math.abs(bounds.maxY-bounds.minY);if(width===0&&height===0)return;let centerX=(bounds.minX+bounds.maxX)/2,centerY=(bounds.minY+bounds.maxY)/2;db.schematic_component.update(this.schematic_component_id,{center:{x:centerX,y:centerY},size:{width,height}})}updateSchematicComponentSizeCalculation(){this.doInitialSchematicComponentSizeCalculation()}doInitialPcbComponentAnchorAlignment(){NormalComponent_doInitialPcbComponentAnchorAlignment(this)}updatePcbComponentAnchorAlignment(){this.doInitialPcbComponentAnchorAlignment()}_renderReactSubtree(element){let component=createInstanceFromReactElement(element);return{element,component}}doInitialInitializePortsFromChildren(){this.initPorts()}doInitialReactSubtreesRender(){let fpElm=this.props.footprint;(0,import_react2.isValidElement)(fpElm)&&(this.children.some(c3=>c3.componentName==="Footprint")||this.add(fpElm));let symElm=this.props.symbol;(0,import_react2.isValidElement)(symElm)&&(this.children.some(c3=>c3.componentName==="Symbol")||this.add(symElm));let cmElm=this.props.cadModel;if((0,import_react2.isValidElement)(cmElm)){this._isCadModelChild=!0;let hasCadAssemblyChild=this.children.some(c3=>c3.componentName==="CadAssembly"),hasCadModelChild=this.children.some(c3=>c3.componentName==="CadModel");!hasCadAssemblyChild&&!hasCadModelChild&&this.add(cmElm)}}doInitialPcbFootprintStringRender(){NormalComponent_doInitialPcbFootprintStringRender(this,(name,effect)=>this._queueAsyncEffect(name,effect))}_hasExistingPortExactly(port1){return this.children.filter(c3=>c3.componentName==="Port").some(port2=>{let aliases1=port1.getNameAndAliases(),aliases2=port2.getNameAndAliases();return aliases1.length===aliases2.length&&aliases1.every(alias=>aliases2.includes(alias))})}add(componentOrElm){let component;if((0,import_react2.isValidElement)(componentOrElm)){let subtree=this._renderReactSubtree(componentOrElm);this.reactSubtrees.push(subtree),component=subtree.component}else component=componentOrElm;if(component.componentName==="Port"){if(this._hasExistingPortExactly(component))return;let conflictingPort=this.children.filter(c3=>c3.componentName==="Port").find(p4=>p4.isMatchingAnyOf(component.getNameAndAliases()));conflictingPort&&debug32(`Similar ports added. Port 1: ${conflictingPort}, Port 2: ${component}`)}super.add(component)}getPortsFromFootprint(opts){let{footprint}=this.props;if((!footprint||(0,import_react2.isValidElement)(footprint))&&(footprint=this.children.find(c3=>c3.componentName==="Footprint")),typeof footprint=="string"){if(isHttpUrl(footprint))return[];if(isStaticAssetPath(footprint))return[];if(parseLibraryFootprintRef(footprint))return[];let fpSoup=fp.string(footprint).soup(),newPorts2=[];for(let elm of fpSoup)if("port_hints"in elm&&elm.port_hints){let newPort=getPortFromHints(elm.port_hints,opts);if(!newPort)continue;newPort.originDescription=`footprint:string:${footprint}:port_hints[0]:${elm.port_hints[0]}`,newPorts2.push(newPort)}return newPorts2}if(!(0,import_react2.isValidElement)(footprint)&&footprint&&footprint.componentName==="Footprint"){let fp22=footprint,pinNumber=1,newPorts2=[];for(let fpChild of fp22.children){if(!fpChild.props.portHints)continue;let portHintsList=fpChild.props.portHints;portHintsList.some(hint=>hint.startsWith("pin"))||(portHintsList=[...portHintsList,`pin${pinNumber}`]),pinNumber++;let newPort=getPortFromHints(portHintsList);newPort&&(newPort.originDescription=`footprint:${footprint}`,newPorts2.push(newPort))}return newPorts2}let newPorts=[];if(!footprint){for(let child of this.children)if(child.props.portHints&&child.isPcbPrimitive){let port=getPortFromHints(child.props.portHints);port&&newPorts.push(port)}}return newPorts}getPortsFromSchematicSymbol(){if(this.root?.schematicDisabled)return[];let{config}=this;if(!config.schematicSymbolName)return[];let symbol=ef[config.schematicSymbolName];if(!symbol)return[];let newPorts=[];for(let symbolPort of symbol.ports){let port=getPortFromHints(symbolPort.labels);port&&(port.schematicSymbolPortDef=symbolPort,newPorts.push(port))}return newPorts}doInitialCreateNetsFromProps(){this._createNetsFromProps(this._getNetsFromConnectionsProp())}_getNetsFromConnectionsProp(){let{_parsedProps:props}=this,propsWithConnections=[];if(props.connections)for(let[pinName,target]of Object.entries(props.connections)){let targets=Array.isArray(target)?target:[target];for(let targetPath of targets)propsWithConnections.push(String(targetPath))}return propsWithConnections}_createNetsFromProps(propsWithConnections){createNetsFromProps(this,propsWithConnections)}_getPcbCircuitJsonBounds(){let{db}=this.root;if(!this.pcb_component_id)return super._getPcbCircuitJsonBounds();let pcb_component2=db.pcb_component.get(this.pcb_component_id);return{center:{x:pcb_component2.center.x,y:pcb_component2.center.y},bounds:{left:pcb_component2.center.x-pcb_component2.width/2,top:pcb_component2.center.y-pcb_component2.height/2,right:pcb_component2.center.x+pcb_component2.width/2,bottom:pcb_component2.center.y+pcb_component2.height/2},width:pcb_component2.width,height:pcb_component2.height}}_getPinCountFromSchematicPortArrangement(){let schPortArrangement=this._getSchematicPortArrangement();if(!schPortArrangement)return 0;if(!isExplicitPinMappingArrangement(schPortArrangement))return(schPortArrangement.leftSize??schPortArrangement.leftPinCount??0)+(schPortArrangement.rightSize??schPortArrangement.rightPinCount??0)+(schPortArrangement.topSize??schPortArrangement.topPinCount??0)+(schPortArrangement.bottomSize??schPortArrangement.bottomPinCount??0);let{leftSide,rightSide,topSide,bottomSide}=schPortArrangement;return Math.max(...leftSide?.pins??[],...rightSide?.pins??[],...topSide?.pins??[],...bottomSide?.pins??[])}_getPinCount(){if(this._getSchematicPortArrangement())return this._getPinCountFromSchematicPortArrangement();let portsFromFootprint=this.getPortsFromFootprint();if(portsFromFootprint.length>0)return portsFromFootprint.length;let{pinLabels}=this._parsedProps;if(pinLabels){if(Array.isArray(pinLabels))return pinLabels.length;let pinNumbers=Object.keys(pinLabels).map(k4=>k4.startsWith("pin")?parseInt(k4.slice(3)):parseInt(k4)).filter(n3=>!Number.isNaN(n3));return pinNumbers.length>0?Math.max(...pinNumbers):Object.keys(pinLabels).length}return 0}_getSchematicPortArrangement(){return this._parsedProps.schPinArrangement??this._parsedProps.schPortArrangement}_getPinLabelsFromPorts(){let ports=this.selectAll("port"),pinLabels={};for(let port of ports){let pinNumber=port.props.pinNumber;if(pinNumber!==void 0){let bestLabel=port._getBestDisplayPinLabel();bestLabel&&(pinLabels[`pin${pinNumber}`]=bestLabel)}}return pinLabels}_getSchematicBoxDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;let{_parsedProps:props}=this,pinCount=this._getPinCount(),pinSpacing=props.schPinSpacing??.2,allPinLabels={...this._getPinLabelsFromPorts(),...props.pinLabels};return getAllDimensionsForSchematicBox({schWidth:props.schWidth,schHeight:props.schHeight,schPinSpacing:pinSpacing,numericSchPinStyle:getNumericSchPinStyle(props.schPinStyle,allPinLabels),pinCount,schPortArrangement:this._getSchematicPortArrangement(),pinLabels:allPinLabels})}getFootprinterString(){return typeof this._parsedProps.footprint=="string"?this._parsedProps.footprint:null}doInitialCadModelRender(){if(this._isCadModelChild||this.props.doNotPlace)return;let{db}=this.root,{boardThickness=0}=this.root?._getBoard()??{},cadModelProp2=this._parsedProps.cadModel,cadModel=cadModelProp2===void 0?this._asyncFootprintCadModel:cadModelProp2,footprint=this.getFootprinterString()??this._getImpliedFootprintString();if(!this.pcb_component_id||!cadModel&&!footprint||cadModel===null)return;let bounds=this._getPcbCircuitJsonBounds();if(typeof cadModel=="string")throw new Error("String cadModel not yet implemented");let rotationOffset=rotation32.parse({x:0,y:0,z:typeof cadModel?.rotationOffset=="number"?cadModel.rotationOffset:0,...typeof cadModel?.rotationOffset=="object"?cadModel.rotationOffset??{}:{}}),positionOffset=point3.parse({x:0,y:0,z:0,...typeof cadModel?.positionOffset=="object"?cadModel.positionOffset:{}}),zOffsetFromSurface=cadModel&&typeof cadModel=="object"&&"zOffsetFromSurface"in cadModel&&cadModel.zOffsetFromSurface!==void 0?distance.parse(cadModel.zOffsetFromSurface):0,computedLayer=this.props.layer==="bottom"?"bottom":"top",globalTransform=this._computePcbGlobalTransformBeforeLayout(),totalRotation=decomposeTSR(globalTransform).rotation.angle*180/Math.PI,isBottomLayer=computedLayer==="bottom",rotationWithOffset=totalRotation+(rotationOffset.z??0),cadRotationZ=normalizeDegrees(rotationWithOffset),cad_model=db.cad_component.insert({position:{x:bounds.center.x+positionOffset.x,y:bounds.center.y+positionOffset.y,z:(computedLayer==="bottom"?-boardThickness/2:boardThickness/2)+(computedLayer==="bottom"?-zOffsetFromSurface:zOffsetFromSurface)+positionOffset.z},rotation:{x:rotationOffset.x,y:rotationOffset.y+(isBottomLayer?180:0),z:normalizeDegrees(isBottomLayer?-cadRotationZ:cadRotationZ)},pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,model_stl_url:"stlUrl"in(cadModel??{})?this._addCachebustToModelUrl(cadModel.stlUrl):void 0,model_obj_url:"objUrl"in(cadModel??{})?this._addCachebustToModelUrl(cadModel.objUrl):void 0,model_mtl_url:"mtlUrl"in(cadModel??{})?this._addCachebustToModelUrl(cadModel.mtlUrl):void 0,model_gltf_url:"gltfUrl"in(cadModel??{})?this._addCachebustToModelUrl(cadModel.gltfUrl):void 0,model_glb_url:"glbUrl"in(cadModel??{})?this._addCachebustToModelUrl(cadModel.glbUrl):void 0,model_step_url:"stepUrl"in(cadModel??{})?this._addCachebustToModelUrl(cadModel.stepUrl):void 0,model_wrl_url:"wrlUrl"in(cadModel??{})?this._addCachebustToModelUrl(cadModel.wrlUrl):void 0,model_jscad:"jscad"in(cadModel??{})?cadModel.jscad:void 0,model_unit_to_mm_scale_factor:typeof cadModel?.modelUnitToMmScale=="number"?cadModel.modelUnitToMmScale:void 0,footprinter_string:typeof footprint=="string"&&!cadModel?footprint:void 0,show_as_translucent_model:this._parsedProps.showAsTranslucentModel});this.cad_component_id=cad_model.cad_component_id}_addCachebustToModelUrl(url){if(!url||!url.includes("modelcdn.tscircuit.com"))return url;let origin=this.root?.getClientOrigin()??"";return`${url}${url.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(origin)}`}_getPartsEngineCacheKey(source_component,footprinterString){return JSON.stringify({ftype:source_component.ftype,name:source_component.name,manufacturer_part_number:source_component.manufacturer_part_number,footprinterString})}async _getSupplierPartNumbers(partsEngine2,source_component,footprinterString){if(this.props.doNotPlace)return{};let cacheEngine=this.root?.platform?.localCacheEngine,cacheKey=this._getPartsEngineCacheKey(source_component,footprinterString);if(cacheEngine){let cached=await cacheEngine.getItem(cacheKey);if(cached)try{return JSON.parse(cached)}catch{}}let result=await Promise.resolve(partsEngine2.findPart({sourceComponent:source_component,footprinterString}));if(typeof result=="string"){if(result.includes("<!DOCTYPE")||result.includes("<html"))throw new Error(`Failed to fetch supplier part numbers: Received HTML response instead of JSON. Response starts with: ${result.substring(0,100)}`);if(result==="Not found")return{};throw new Error(`Invalid supplier part numbers format: Expected object but got string: "${result}"`)}if(!result||Array.isArray(result)||typeof result!="object"){let actualType=result===null?"null":Array.isArray(result)?"array":typeof result;throw new Error(`Invalid supplier part numbers format: Expected object but got ${actualType}`)}let supplierPartNumbers=result;if(cacheEngine)try{await cacheEngine.setItem(cacheKey,JSON.stringify(supplierPartNumbers))}catch{}return supplierPartNumbers}doInitialPartsEngineRender(){if(this.props.doNotPlace)return;let partsEngine2=this.getInheritedProperty("partsEngine");if(!partsEngine2)return;let{db}=this.root,source_component=db.source_component.get(this.source_component_id);if(!source_component||source_component.supplier_part_numbers)return;let footprinterString;this.props.footprint&&typeof this.props.footprint=="string"&&(footprinterString=this.props.footprint);let supplierPartNumbersMaybePromise=this._getSupplierPartNumbers(partsEngine2,source_component,footprinterString);if(!(supplierPartNumbersMaybePromise instanceof Promise)){db.source_component.update(this.source_component_id,{supplier_part_numbers:supplierPartNumbersMaybePromise});return}this._queueAsyncEffect("get-supplier-part-numbers",async()=>{await supplierPartNumbersMaybePromise.then(supplierPartNumbers=>{this._asyncSupplierPartNumbers=supplierPartNumbers,this._markDirty("PartsEngineRender")}).catch(error=>{this._asyncSupplierPartNumbers={};let errorObj=unknown_error_finding_part.parse({type:"unknown_error_finding_part",message:`Failed to fetch supplier part numbers for ${this.getString()}: ${error.message}`,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id});db.unknown_error_finding_part.insert(errorObj),this._markDirty("PartsEngineRender")})})}updatePartsEngineRender(){if(this.props.doNotPlace)return;let{db}=this.root,source_component=db.source_component.get(this.source_component_id);if(source_component&&!source_component.supplier_part_numbers&&this._asyncSupplierPartNumbers){db.source_component.update(this.source_component_id,{supplier_part_numbers:this._asyncSupplierPartNumbers});return}}doInitialAssignFallbackProps(){let{_parsedProps:props}=this;props.connections&&!this.name&&(this.fallbackUnassignedName=this.getSubcircuit().getNextAvailableName(this))}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}_createTracesFromConnectionsProp(){let{_parsedProps:props}=this;if(props.connections)for(let[pinName,target]of Object.entries(props.connections)){let targets=Array.isArray(target)?target:[target];for(let targetPath of targets)this.add(new Trace3({from:`.${this.name} > .${pinName}`,to:String(targetPath)}))}}doInitialSourceDesignRuleChecks(){NormalComponent_doInitialSourceDesignRuleChecks(this)}doInitialPcbLayout(){if(this.root?.pcbDisabled||!this.pcb_component_id)return;let{db}=this.root,props=this._parsedProps;if(!(props.pcbX!==void 0||props.pcbY!==void 0))return;let sourceComponent=db.source_component.get(this.source_component_id),positionedRelativeToGroupId=sourceComponent?.source_group_id?db.pcb_group.getWhere({source_group_id:sourceComponent.source_group_id})?.pcb_group_id:void 0,positionedRelativeToBoardId=positionedRelativeToGroupId?void 0:this._getBoard()?.pcb_board_id??void 0;db.pcb_component.update(this.pcb_component_id,{position_mode:"relative_to_group_anchor",positioned_relative_to_pcb_group_id:positionedRelativeToGroupId,positioned_relative_to_pcb_board_id:positionedRelativeToBoardId,display_offset_x:props.pcbX,display_offset_y:props.pcbY})}_getMinimumFlexContainerSize(){return NormalComponent__getMinimumFlexContainerSize(this)}_repositionOnPcb(position2){return NormalComponent__repositionOnPcb(this,position2)}doInitialSilkscreenOverlapAdjustment(){return NormalComponent_doInitialSilkscreenOverlapAdjustment(this)}isRelativelyPositioned(){return this._parsedProps.pcbX!==void 0||this._parsedProps.pcbY!==void 0}},getBoardCenterFromAnchor=({boardAnchorPosition,boardAnchorAlignment,width,height})=>{let{x:ax2,y:ay2}=boardAnchorPosition,cx2=ax2,cy2=ay2;switch(boardAnchorAlignment){case"top_left":cx2=ax2+width/2,cy2=ay2-height/2;break;case"top_right":cx2=ax2-width/2,cy2=ay2-height/2;break;case"bottom_left":cx2=ax2+width/2,cy2=ay2+height/2;break;case"bottom_right":cx2=ax2-width/2,cy2=ay2+height/2;break;case"top":cx2=ax2,cy2=ay2-height/2;break;case"bottom":cx2=ax2,cy2=ay2+height/2;break;case"left":cx2=ax2+width/2,cy2=ay2;break;case"right":cx2=ax2-width/2,cy2=ay2;break;default:break}return{x:cx2,y:cy2}},SOLVERS={PackSolver2,AutoroutingPipelineSolver:pi2,AssignableViaAutoroutingPipelineSolver:wi2,CopperPourPipelineSolver},CapacityMeshAutorouter=class{constructor(input2,options={}){__publicField(this,"input");__publicField(this,"isRouting",!1);__publicField(this,"solver");__publicField(this,"eventHandlers",{complete:[],error:[],progress:[]});__publicField(this,"cycleCount",0);__publicField(this,"stepDelay");__publicField(this,"timeoutId");this.input=input2;let{capacityDepth,targetMinCapacity,stepDelay=0,useAssignableViaSolver=!1,onSolverStarted}=options,{AutoroutingPipelineSolver:AutoroutingPipelineSolver2,AssignableViaAutoroutingPipelineSolver:AssignableViaAutoroutingPipelineSolver2}=dist_exports3,solverName=useAssignableViaSolver?"AssignableViaAutoroutingPipelineSolver":"AutoroutingPipelineSolver",SolverClass=SOLVERS[solverName];this.solver=new SolverClass(input2,{capacityDepth,targetMinCapacity,cacheProvider:null}),onSolverStarted?.({solverName,solverParams:{input:input2,options:{capacityDepth,targetMinCapacity,cacheProvider:null}}}),this.stepDelay=stepDelay}start(){this.isRouting||(this.isRouting=!0,this.cycleCount=0,this.runCycleAndQueueNextCycle())}runCycleAndQueueNextCycle(){if(this.isRouting)try{if(this.solver.solved||this.solver.failed){this.solver.failed?this.emitEvent({type:"error",error:new AutorouterError(this.solver.error||"Routing failed")}):this.emitEvent({type:"complete",traces:this.solver.getOutputSimpleRouteJson().traces||[]}),this.isRouting=!1;return}let startTime=Date.now(),startIterations=this.solver.iterations;for(;Date.now()-startTime<250&&!this.solver.failed&&!this.solver.solved;)this.solver.step();let iterationsPerSecond=(this.solver.iterations-startIterations)/(Date.now()-startTime)*1e3;this.cycleCount++;let debugGraphics=this.solver?.preview()||void 0,progress=this.solver.progress;this.emitEvent({type:"progress",steps:this.cycleCount,iterationsPerSecond,progress,phase:this.solver.getCurrentPhase(),debugGraphics}),this.stepDelay>0?this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),this.stepDelay):this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),0)}catch(error){this.emitEvent({type:"error",error:error instanceof Error?new AutorouterError(error.message):new AutorouterError(String(error))}),this.isRouting=!1}}stop(){this.isRouting&&(this.isRouting=!1,this.timeoutId!==void 0&&(clearTimeout(this.timeoutId),this.timeoutId=void 0))}on(event,callback){event==="complete"?this.eventHandlers.complete.push(callback):event==="error"?this.eventHandlers.error.push(callback):event==="progress"&&this.eventHandlers.progress.push(callback)}emitEvent(event){if(event.type==="complete")for(let handler of this.eventHandlers.complete)handler(event);else if(event.type==="error")for(let handler of this.eventHandlers.error)handler(event);else if(event.type==="progress")for(let handler of this.eventHandlers.progress)handler(event)}solveSync(){if(this.solver.solve(),this.solver.failed)throw new AutorouterError(this.solver.error||"Routing failed");return this.solver.getOutputSimpleRouteJson().traces||[]}},TraceHint=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"matchedPort",null)}get config(){return{componentName:"TraceHint",zodProps:traceHintProps}}doInitialPortMatching(){let{db}=this.root,{_parsedProps:props,parent}=this;if(!parent)return;if(parent.componentName==="Trace"){this.renderError(`Port inference inside trace is not yet supported (${this})`);return}if(!parent)throw new Error("TraceHint has no parent");if(!props.for){this.renderError(`TraceHint has no for property (${this})`);return}let port=parent.selectOne(props.for,{type:"port"});port||this.renderError(`${this} could not find port for selector "${props.for}"`),this.matchedPort=port,port.registerMatch(this)}getPcbRouteHints(){let{_parsedProps:props}=this,offsets=props.offset?[props.offset]:props.offsets;if(!offsets)return[];let globalTransform=this._computePcbGlobalTransformBeforeLayout();return offsets.map(offset=>({...applyToPoint(globalTransform,offset),via:offset.via,to_layer:offset.to_layer,trace_width:offset.trace_width}))}doInitialPcbTraceHintRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this;db.pcb_trace_hint.insert({pcb_component_id:this.matchedPort?.pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,route:this.getPcbRouteHints()})}},applyPcbEditEventsToManualEditsFile=({circuitJson,editEvents,manualEditsFile})=>{let updatedManualEditsFile={...manualEditsFile,pcb_placements:[...manualEditsFile.pcb_placements??[]]};for(let editEvent of editEvents)if(editEvent.edit_event_type==="edit_pcb_component_location"){let{pcb_component_id,new_center}=editEvent,pcb_component2=su2(circuitJson).pcb_component.get(pcb_component_id);if(!pcb_component2)continue;let source_component=su2(circuitJson).source_component.get(pcb_component2.source_component_id);if(!source_component)continue;let existingPlacementIndex=updatedManualEditsFile.pcb_placements?.findIndex(p4=>p4.selector===source_component.name),newPlacement={selector:source_component.name,center:new_center,relative_to:"group_center"};existingPlacementIndex>=0?updatedManualEditsFile.pcb_placements[existingPlacementIndex]=newPlacement:updatedManualEditsFile.pcb_placements.push(newPlacement)}return updatedManualEditsFile},applySchematicEditEventsToManualEditsFile=({circuitJson,editEvents,manualEditsFile})=>{let updatedManualEditsFile={...manualEditsFile,schematic_placements:[...manualEditsFile.schematic_placements??[]]};for(let editEvent of editEvents)if(editEvent.edit_event_type==="edit_schematic_component_location"){let{schematic_component_id,new_center}=editEvent,schematic_component2=su2(circuitJson).schematic_component.get(schematic_component_id);if(!schematic_component2||!schematic_component2.source_component_id)continue;let source_component=su2(circuitJson).source_component.get(schematic_component2.source_component_id);if(!source_component)continue;let existingPlacementIndex=updatedManualEditsFile.schematic_placements?.findIndex(p4=>p4.selector===source_component.name),newPlacement={selector:source_component.name,center:new_center,relative_to:"group_center"};existingPlacementIndex>=0?updatedManualEditsFile.schematic_placements[existingPlacementIndex]=newPlacement:updatedManualEditsFile.schematic_placements.push(newPlacement)}return updatedManualEditsFile},applyEditEventsToManualEditsFile=({circuitJson,editEvents,manualEditsFile})=>{let schematicEditEvents=editEvents.filter(event=>event.edit_event_type==="edit_schematic_component_location"),pcbEditEvents=editEvents.filter(event=>event.edit_event_type==="edit_pcb_component_location"),updatedManualEditsFile=manualEditsFile;return schematicEditEvents.length>0&&(updatedManualEditsFile=applySchematicEditEventsToManualEditsFile({circuitJson,editEvents:schematicEditEvents,manualEditsFile:updatedManualEditsFile})),pcbEditEvents.length>0&&(updatedManualEditsFile=applyPcbEditEventsToManualEditsFile({circuitJson,editEvents:pcbEditEvents,manualEditsFile:updatedManualEditsFile})),updatedManualEditsFile},applyTraceHintEditEvent=(circuitJson,edit_event)=>{if(su2(circuitJson).pcb_trace_hint.get(edit_event.pcb_trace_hint_id))circuitJson=circuitJson.map(e4=>e4.pcb_trace_hint_id===edit_event.pcb_trace_hint_id?{...e4,route:edit_event.route}:e4);else{let pcbPort=su2(circuitJson).pcb_port.get(edit_event.pcb_port_id);circuitJson=circuitJson.filter(e4=>!(e4.type==="pcb_trace_hint"&&e4.pcb_port_id===edit_event.pcb_port_id)).concat([{type:"pcb_trace_hint",pcb_trace_hint_id:edit_event.pcb_trace_hint_id,route:edit_event.route,pcb_port_id:edit_event.pcb_port_id,pcb_component_id:pcbPort?.pcb_component_id}])}return circuitJson},applyEditEvents=({circuitJson,editEvents})=>{circuitJson=JSON.parse(JSON.stringify(circuitJson));for(let editEvent of editEvents)if(editEvent.edit_event_type==="edit_pcb_component_location"){let component=circuitJson.find(e4=>e4.type==="pcb_component"&&e4.pcb_component_id===editEvent.pcb_component_id);if((!component||component.center.x!==editEvent.new_center.x||component.center.y!==editEvent.new_center.y)&&editEvent.original_center){let mat=translate(editEvent.new_center.x-editEvent.original_center.x,editEvent.new_center.y-editEvent.original_center.y);circuitJson=circuitJson.map(e4=>e4.pcb_component_id!==editEvent.pcb_component_id?e4:transformPCBElement(e4,mat))}}else editEvent.edit_event_type==="edit_schematic_component_location"?circuitJson=circuitJson.map(e4=>e4.type==="schematic_component"&&e4.schematic_component_id===editEvent.schematic_component_id?{...e4,center:editEvent.new_center}:e4):editEvent.edit_event_type==="edit_pcb_trace_hint"&&(circuitJson=applyTraceHintEditEvent(circuitJson,editEvent));return circuitJson},getDescendantSubcircuitIds=(db,root_subcircuit_id)=>{let groups=db.source_group.list(),result=[],findDescendants=parentId=>{let children=groups.filter(group=>group.parent_subcircuit_id===parentId);for(let child of children)child.subcircuit_id&&(result.push(child.subcircuit_id),findDescendants(child.subcircuit_id))};return findDescendants(root_subcircuit_id),result},getSimpleRouteJsonFromCircuitJson=({db,circuitJson,subcircuit_id,minTraceWidth=.1})=>{if(!db&&circuitJson&&(db=su2(circuitJson)),!db)throw new Error("db or circuitJson is required");let traceHints=db.pcb_trace_hint.list(),relevantSubcircuitIds=subcircuit_id?new Set([subcircuit_id]):null;if(subcircuit_id){let descendantSubcircuitIds=getDescendantSubcircuitIds(db,subcircuit_id);for(let id of descendantSubcircuitIds)relevantSubcircuitIds.add(id)}let subcircuitElements=(circuitJson??db.toArray()).filter(e4=>!subcircuit_id||"subcircuit_id"in e4&&relevantSubcircuitIds.has(e4.subcircuit_id)),board=null;if(subcircuit_id){let source_group_id=subcircuit_id.replace(/^subcircuit_/,""),source_board2=db.source_board.getWhere({source_group_id});source_board2&&(board=db.pcb_board.getWhere({source_board_id:source_board2.source_board_id}))}board||(board=db.pcb_board.list()[0]),db=su2(subcircuitElements);let connMap=getFullConnectivityMapFromCircuitJson(subcircuitElements),obstacles=getObstaclesFromCircuitJson2([...db.pcb_component.list(),...db.pcb_smtpad.list(),...db.pcb_plated_hole.list(),...db.pcb_hole.list(),...db.pcb_via.list(),...db.pcb_cutout.list()].filter(e4=>!subcircuit_id||relevantSubcircuitIds?.has(e4.subcircuit_id)),connMap);for(let obstacle of obstacles){let additionalIds=obstacle.connectedTo.flatMap(id=>connMap.getIdsConnectedToNet(id));obstacle.connectedTo.push(...additionalIds)}let internalConnections=db.source_component_internal_connection.list(),sourcePortIdToInternalConnectionId=new Map;for(let ic2 of internalConnections)for(let sourcePortId of ic2.source_port_ids)sourcePortIdToInternalConnectionId.set(sourcePortId,ic2.source_component_internal_connection_id);let pcbElementIdToSourcePortId=new Map;for(let pcbPort of db.pcb_port.list())if(pcbPort.source_port_id){let smtpad2=db.pcb_smtpad.getWhere({pcb_port_id:pcbPort.pcb_port_id});smtpad2&&pcbElementIdToSourcePortId.set(smtpad2.pcb_smtpad_id,pcbPort.source_port_id);let platedHole=db.pcb_plated_hole.getWhere({pcb_port_id:pcbPort.pcb_port_id});platedHole&&pcbElementIdToSourcePortId.set(platedHole.pcb_plated_hole_id,pcbPort.source_port_id)}for(let obstacle of obstacles)for(let connectedId of obstacle.connectedTo){let sourcePortId=pcbElementIdToSourcePortId.get(connectedId);if(sourcePortId){let internalConnectionId=sourcePortIdToInternalConnectionId.get(sourcePortId);if(internalConnectionId){obstacle.offBoardConnectsTo=[internalConnectionId],obstacle.netIsAssignable=!0;break}}}let allPoints=obstacles.flatMap(o3=>[{x:o3.center.x-o3.width/2,y:o3.center.y-o3.height/2},{x:o3.center.x+o3.width/2,y:o3.center.y+o3.height/2}]).concat(board?.outline??[]),bounds;if(board&&!board.outline?bounds={minX:board.center.x-board.width/2,maxX:board.center.x+board.width/2,minY:board.center.y-board.height/2,maxY:board.center.y+board.height/2}:bounds={minX:Math.min(...allPoints.map(p4=>p4.x))-1,maxX:Math.max(...allPoints.map(p4=>p4.x))+1,minY:Math.min(...allPoints.map(p4=>p4.y))-1,maxY:Math.max(...allPoints.map(p4=>p4.y))+1},subcircuit_id){let group=db.pcb_group.getWhere({subcircuit_id});if(group?.width&&group.height){let groupBounds={minX:group.center.x-group.width/2,maxX:group.center.x+group.width/2,minY:group.center.y-group.height/2,maxY:group.center.y+group.height/2};bounds={minX:Math.min(bounds.minX,groupBounds.minX),maxX:Math.max(bounds.maxX,groupBounds.maxX),minY:Math.min(bounds.minY,groupBounds.minY),maxY:Math.max(bounds.maxY,groupBounds.maxY)}}}let routedTraceIds=new Set(db.pcb_trace.list().map(t6=>t6.source_trace_id).filter(id=>!!id)),directTraceConnections=db.source_trace.list().filter(trace=>!routedTraceIds.has(trace.source_trace_id)).map(trace=>{let connectedPorts=trace.connected_source_port_ids.map(id=>{let source_port2=db.source_port.get(id),pcb_port2=db.pcb_port.getWhere({source_port_id:id});return{...source_port2,...pcb_port2}});if(connectedPorts.length<2)return null;let[portA,portB]=connectedPorts;if(portA.x===void 0||portA.y===void 0)return console.error(`(source_port_id: ${portA.source_port_id}) for trace ${trace.source_trace_id} does not have x/y coordinates. Skipping this trace.`),null;if(portB.x===void 0||portB.y===void 0)return console.error(`(source_port_id: ${portB.source_port_id}) for trace ${trace.source_trace_id} does not have x/y coordinates. Skipping this trace.`),null;let layerA=portA.layers?.[0]??"top",layerB=portB.layers?.[0]??"top",matchingHints=traceHints.filter(hint=>hint.pcb_port_id===portA.pcb_port_id||hint.pcb_port_id===portB.pcb_port_id),hintPoints=[];for(let hint of matchingHints){let layer=db.pcb_port.get(hint.pcb_port_id)?.layers?.[0]??"top";for(let pt3 of hint.route)hintPoints.push({x:pt3.x,y:pt3.y,layer})}return{name:trace.source_trace_id??connMap.getNetConnectedToId(trace.source_trace_id)??"",source_trace_id:trace.source_trace_id,width:trace.min_trace_thickness,pointsToConnect:[{x:portA.x,y:portA.y,layer:layerA,pointId:portA.pcb_port_id,pcb_port_id:portA.pcb_port_id},...hintPoints,{x:portB.x,y:portB.y,layer:layerB,pointId:portB.pcb_port_id,pcb_port_id:portB.pcb_port_id}]}}).filter(c3=>c3!==null),directTraceConnectionsById=new Map(directTraceConnections.map(c3=>[c3.source_trace_id,c3])),source_nets=db.source_net.list().filter(e4=>!subcircuit_id||relevantSubcircuitIds?.has(e4.subcircuit_id)),connectionsFromNets=[];for(let net of source_nets){let connectedSourceTraces=db.source_trace.list().filter(st3=>st3.connected_source_net_ids?.includes(net.source_net_id));connectionsFromNets.push({name:net.source_net_id??connMap.getNetConnectedToId(net.source_net_id),pointsToConnect:connectedSourceTraces.flatMap(st3=>db.pcb_port.list().filter(p4=>st3.connected_source_port_ids.includes(p4.source_port_id)).map(p4=>({x:p4.x,y:p4.y,layer:p4.layers?.[0]??"top",pointId:p4.pcb_port_id,pcb_port_id:p4.pcb_port_id})))})}let breakoutPoints=db.pcb_breakout_point.list().filter(bp2=>!subcircuit_id||relevantSubcircuitIds?.has(bp2.subcircuit_id)),connectionsFromBreakoutPoints=[],breakoutTraceConnectionsById=new Map;for(let bp2 of breakoutPoints){let pt3={x:bp2.x,y:bp2.y,layer:"top"};if(bp2.source_trace_id){let conn=directTraceConnectionsById.get(bp2.source_trace_id)??breakoutTraceConnectionsById.get(bp2.source_trace_id);if(conn)conn.pointsToConnect.push(pt3);else{let newConn={name:bp2.source_trace_id,source_trace_id:bp2.source_trace_id,pointsToConnect:[pt3]};connectionsFromBreakoutPoints.push(newConn),breakoutTraceConnectionsById.set(bp2.source_trace_id,newConn)}}else if(bp2.source_net_id){let conn=connectionsFromNets.find(c3=>c3.name===bp2.source_net_id);conn?conn.pointsToConnect.push(pt3):connectionsFromBreakoutPoints.push({name:bp2.source_net_id,pointsToConnect:[pt3]})}else if(bp2.source_port_id){let pcb_port2=db.pcb_port.getWhere({source_port_id:bp2.source_port_id});pcb_port2&&connectionsFromBreakoutPoints.push({name:bp2.source_port_id,source_trace_id:void 0,pointsToConnect:[{x:pcb_port2.x,y:pcb_port2.y,layer:pcb_port2.layers?.[0]??"top",pointId:pcb_port2.pcb_port_id,pcb_port_id:pcb_port2.pcb_port_id},pt3]})}}let allConns=[...directTraceConnections,...connectionsFromNets,...connectionsFromBreakoutPoints],pointIdToConn=new Map;for(let conn of allConns)for(let pt3 of conn.pointsToConnect)pt3.pointId&&pointIdToConn.set(pt3.pointId,conn);let existingTraces=db.pcb_trace.list().filter(t6=>!subcircuit_id||relevantSubcircuitIds?.has(t6.subcircuit_id));for(let tr2 of existingTraces){let tracePortIds=new Set;for(let seg of tr2.route)seg.start_pcb_port_id&&tracePortIds.add(seg.start_pcb_port_id),seg.end_pcb_port_id&&tracePortIds.add(seg.end_pcb_port_id);if(tracePortIds.size<2)continue;let firstId=tracePortIds.values().next().value;if(!firstId)continue;let conn=pointIdToConn.get(firstId);conn&&[...tracePortIds].every(pid=>pointIdToConn.get(pid)===conn)&&(conn.externallyConnectedPointIds??(conn.externallyConnectedPointIds=[]),conn.externallyConnectedPointIds.push([...tracePortIds]))}return{simpleRouteJson:{bounds,obstacles,connections:allConns,layerCount:board?.num_layers??2,minTraceWidth,outline:board?.outline?.map(point23=>({...point23}))},connMap}},getPhaseTimingsFromRenderEvents=renderEvents=>{let phaseTimings={};if(!renderEvents)return phaseTimings;for(let renderPhase of orderedRenderPhases)phaseTimings[renderPhase]=0;let startEvents=new Map;for(let event of renderEvents){let[,,phase,eventType]=event.type.split(":");if(eventType==="start"){startEvents.set(`${phase}:${event.renderId}`,event);continue}if(eventType==="end"){let startEvent=startEvents.get(`${phase}:${event.renderId}`);if(startEvent){let duration=event.createdAt-startEvent.createdAt;phaseTimings[phase]=(phaseTimings[phase]||0)+duration}}}return phaseTimings},normalizePinLabels=inputPinLabels=>{let unqInputPinLabels=inputPinLabels.map(labels=>[...new Set(labels)]),result=unqInputPinLabels.map(()=>[]),desiredNumbers=unqInputPinLabels.map(()=>null);for(let i3=0;i3<unqInputPinLabels.length;i3++)for(let label of unqInputPinLabels[i3])if(/^\d+$/.test(label)){desiredNumbers[i3]=Number.parseInt(label);break}let highestPinNumber=0,alreadyAcceptedDesiredNumbers=new Set;for(let i3=0;i3<desiredNumbers.length;i3++){let desiredNumber=desiredNumbers[i3];if(desiredNumber===null||desiredNumber<1)continue;if(!alreadyAcceptedDesiredNumbers.has(desiredNumber)){alreadyAcceptedDesiredNumbers.add(desiredNumber),result[i3].push(`pin${desiredNumber}`),highestPinNumber=Math.max(highestPinNumber,desiredNumber);continue}let existingAltsForPin=0;for(let label of result[i3])label.startsWith(`pin${desiredNumber}_alt`)&&existingAltsForPin++;result[i3].push(`pin${desiredNumber}_alt${existingAltsForPin+1}`)}for(let i3=0;i3<result.length;i3++)result[i3][0]?.includes("_alt")&&(highestPinNumber++,result[i3].unshift(`pin${highestPinNumber}`));for(let i3=0;i3<result.length;i3++)result[i3].length===0&&(highestPinNumber++,result[i3].push(`pin${highestPinNumber}`));let totalLabelCounts={};for(let inputLabels of unqInputPinLabels)for(let label of inputLabels)/^\d+$/.test(label)||(totalLabelCounts[label]=(totalLabelCounts[label]??0)+1);let incrementalLabelCounts={};for(let i3=0;i3<unqInputPinLabels.length;i3++){let inputLabels=unqInputPinLabels[i3];for(let label of inputLabels)/^\d+$/.test(label)||(totalLabelCounts[label]===1?result[i3].push(label):(incrementalLabelCounts[label]=(incrementalLabelCounts[label]??0)+1,result[i3].push(`${label}${incrementalLabelCounts[label]}`)))}return result};function updateSchematicPrimitivesForLayoutShift({db,schematicComponentId,deltaX,deltaY}){let rects=db.schematic_rect.list({schematic_component_id:schematicComponentId});for(let rect of rects)rect.center.x+=deltaX,rect.center.y+=deltaY;let lines=db.schematic_line.list({schematic_component_id:schematicComponentId});for(let line2 of lines)line2.x1+=deltaX,line2.y1+=deltaY,line2.x2+=deltaX,line2.y2+=deltaY;let circles=db.schematic_circle.list({schematic_component_id:schematicComponentId});for(let circle2 of circles)circle2.center.x+=deltaX,circle2.center.y+=deltaY;let arcs=db.schematic_arc.list({schematic_component_id:schematicComponentId});for(let arc2 of arcs)arc2.center.x+=deltaX,arc2.center.y+=deltaY}var debug42=(0,import_debug11.default)("Group_doInitialSchematicLayoutMatchAdapt");function Group_doInitialSchematicLayoutMatchAdapt(group){let{db}=group.root,subtreeCircuitJson=buildSubtree(db.toArray(),{source_group_id:group.source_group_id}),bpcGraphBeforeGeneratedNetLabels=convertCircuitJsonToBpc(subtreeCircuitJson);debug42.enabled&&global?.debugGraphics&&global.debugGraphics?.push(getGraphicsForBpcGraph(bpcGraphBeforeGeneratedNetLabels,{title:`floatingBpcGraph-${group.name}`}));let floatingGraph=convertCircuitJsonToBpc(subtreeCircuitJson),floatingGraphNoNotConnected={boxes:floatingGraph.boxes,pins:floatingGraph.pins.map(p4=>({...p4,color:p4.color.replace("not_connected","normal")}))},{result:laidOutBpcGraph}=layoutSchematicGraphVariants([{variantName:"default",floatingGraph},{variantName:"noNotConnected",floatingGraph:floatingGraphNoNotConnected}],{singletonKeys:["vcc/2","gnd/2"],centerPinColors:["netlabel_center","component_center"],floatingBoxIdsWithMutablePinOffsets:new Set(floatingGraph.boxes.filter(box2=>floatingGraph.pins.filter(p4=>p4.boxId===box2.boxId).filter(bp2=>!bp2.color.includes("center")).length<=2).map(b3=>b3.boxId)),corpus:{}});debug42.enabled&&global?.debugGraphics&&global.debugGraphics?.push(getGraphicsForBpcGraph(laidOutBpcGraph,{title:`laidOutBpcGraph-${group.name}`}));let groupOffset=group._getGlobalSchematicPositionBeforeLayout();for(let box2 of laidOutBpcGraph.boxes){if(!box2.center)continue;let schematic_component2=db.schematic_component.get(box2.boxId);if(schematic_component2){let newCenter={x:box2.center.x+groupOffset.x,y:box2.center.y+groupOffset.y},ports=db.schematic_port.list({schematic_component_id:schematic_component2.schematic_component_id}),texts=db.schematic_text.list({schematic_component_id:schematic_component2.schematic_component_id}),positionDelta={x:newCenter.x-schematic_component2.center.x,y:newCenter.y-schematic_component2.center.y};for(let port of ports)port.center.x+=positionDelta.x,port.center.y+=positionDelta.y;for(let text of texts)text.position.x+=positionDelta.x,text.position.y+=positionDelta.y;updateSchematicPrimitivesForLayoutShift({db,schematicComponentId:schematic_component2.schematic_component_id,deltaX:positionDelta.x,deltaY:positionDelta.y}),schematic_component2.center=newCenter;continue}let schematic_net_label2=db.schematic_net_label.get(box2.boxId);if(schematic_net_label2){let pin=laidOutBpcGraph.pins.find(p4=>p4.boxId===box2.boxId&&p4.color==="netlabel_center");if(!pin)throw new Error(`No pin found for net label: ${box2.boxId}`);let finalCenter={x:box2.center.x+groupOffset.x,y:box2.center.y+groupOffset.y};schematic_net_label2.center=finalCenter,schematic_net_label2.anchor_position={x:finalCenter.x+pin.offset.x,y:finalCenter.y+pin.offset.y};continue}console.error(`No schematic element found for box: ${box2.boxId}. This is a bug in the matchAdapt binding with @tscircuit/core`)}}var debug52=(0,import_debug12.default)("Group_doInitialSchematicLayoutMatchpack");function facingDirectionToSide(facingDirection){switch(facingDirection){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:return"y+"}}function rotateDirection2(direction2,degrees){let directions=["right","up","left","down"],currentIndex=directions.indexOf(direction2);if(currentIndex===-1)return direction2;let steps=Math.round(degrees/90),newIndex=(currentIndex+steps)%4;return directions[newIndex<0?newIndex+4:newIndex]}function convertTreeToInputProblem(tree,db,group){let problem={chipMap:{},chipPinMap:{},netMap:{},pinStrongConnMap:{},netConnMap:{},chipGap:.6,decouplingCapsGap:.4,partitionGap:1.2};debug52(`[${group.name}] Processing ${tree.childNodes.length} child nodes for input problem`),tree.childNodes.forEach((child,index)=>{if(debug52(`[${group.name}] Processing child ${index}: nodeType=${child.nodeType}`),child.nodeType==="component"?debug52(`[${group.name}] - Component: ${child.sourceComponent?.name}`):child.nodeType==="group"&&debug52(`[${group.name}] - Group: ${child.sourceGroup?.name}`),child.nodeType==="component"&&child.sourceComponent){let chipId=child.sourceComponent.name||`chip_${index}`,schematicComponent=db.schematic_component.getWhere({source_component_id:child.sourceComponent.source_component_id});if(!schematicComponent)return;let component=group.children.find(groupChild=>groupChild.source_component_id===child.sourceComponent?.source_component_id),availableRotations=[0,90,180,270];component?._parsedProps?.schOrientation&&(availableRotations=[0]),component?._parsedProps?.schRotation!==void 0&&(availableRotations=[0]),component?._parsedProps?.facingDirection&&(availableRotations=[0]),component?._parsedProps?.schFacingDirection&&(availableRotations=[0]),component?.componentName==="Chip"&&(availableRotations=[0]);let marginLeft=component?._parsedProps?.schMarginLeft??component?._parsedProps?.schMarginX??0,marginRight=component?._parsedProps?.schMarginRight??component?._parsedProps?.schMarginX??0,marginTop=component?._parsedProps?.schMarginTop??component?._parsedProps?.schMarginY??0,marginBottom=component?._parsedProps?.schMarginBottom??component?._parsedProps?.schMarginY??0;component?.config.shouldRenderAsSchematicBox&&(marginTop+=.4,marginBottom+=.4);let marginXShift=(marginRight-marginLeft)/2,marginYShift=(marginTop-marginBottom)/2;problem.chipMap[chipId]={chipId,pins:[],size:{x:(schematicComponent.size?.width||1)+marginLeft+marginRight,y:(schematicComponent.size?.height||1)+marginTop+marginBottom},availableRotations};let ports=db.schematic_port.list({schematic_component_id:schematicComponent.schematic_component_id});for(let port of ports){let sourcePort=db.source_port.get(port.source_port_id);if(!sourcePort)continue;let pinId=`${chipId}.${sourcePort.pin_number||sourcePort.name||port.schematic_port_id}`;problem.chipMap[chipId].pins.push(pinId);let side=facingDirectionToSide(port.facing_direction);problem.chipPinMap[pinId]={pinId,offset:{x:(port.center?.x||0)-(schematicComponent.center.x||0)+marginXShift,y:(port.center?.y||0)-(schematicComponent.center.y||0)+marginYShift},side}}}else if(child.nodeType==="group"&&child.sourceGroup){let groupId=child.sourceGroup.name||`group_${index}`;debug52(`[${group.name}] Processing nested group: ${groupId}`);let schematicGroup=db.schematic_group?.getWhere?.({source_group_id:child.sourceGroup.source_group_id}),groupInstance=group.children.find(groupChild=>groupChild.source_group_id===child.sourceGroup?.source_group_id);if(debug52(`[${group.name}] Found schematic_group for ${groupId}:`,schematicGroup),schematicGroup){debug52(`[${group.name}] Treating group ${groupId} as composite chip`);let groupComponents=db.schematic_component.list({schematic_group_id:schematicGroup.schematic_group_id});debug52(`[${group.name}] Group ${groupId} has ${groupComponents.length} components:`,groupComponents.map(c3=>c3.source_component_id));let minX=1/0,maxX=-1/0,minY=1/0,maxY=-1/0,hasValidBounds=!1;for(let comp of groupComponents)if(comp.center&&comp.size){hasValidBounds=!0;let halfWidth=comp.size.width/2,halfHeight=comp.size.height/2;minX=Math.min(minX,comp.center.x-halfWidth),maxX=Math.max(maxX,comp.center.x+halfWidth),minY=Math.min(minY,comp.center.y-halfHeight),maxY=Math.max(maxY,comp.center.y+halfHeight)}let marginLeft=groupInstance?._parsedProps?.schMarginLeft??groupInstance?._parsedProps?.schMarginX??0,marginRight=groupInstance?._parsedProps?.schMarginRight??groupInstance?._parsedProps?.schMarginX??0,marginTop=groupInstance?._parsedProps?.schMarginTop??groupInstance?._parsedProps?.schMarginY??0,marginBottom=groupInstance?._parsedProps?.schMarginBottom??groupInstance?._parsedProps?.schMarginY??0,marginXShift=(marginRight-marginLeft)/2,marginYShift=(marginTop-marginBottom)/2,groupWidth=(hasValidBounds?maxX-minX:2)+marginLeft+marginRight,groupHeight=(hasValidBounds?maxY-minY:2)+marginTop+marginBottom;debug52(`[${group.name}] Group ${groupId} computed size: ${groupWidth} x ${groupHeight}`);let groupPins=[];for(let comp of groupComponents){let ports=db.schematic_port.list({schematic_component_id:comp.schematic_component_id});for(let port of ports){let sourcePort=db.source_port.get(port.source_port_id);if(!sourcePort)continue;let pinId=`${groupId}.${sourcePort.pin_number||sourcePort.name||port.schematic_port_id}`;groupPins.push(pinId);let groupCenter=schematicGroup.center||{x:0,y:0},side=facingDirectionToSide(port.facing_direction);problem.chipPinMap[pinId]={pinId,offset:{x:(port.center?.x||0)-groupCenter.x+marginXShift,y:(port.center?.y||0)-groupCenter.y+marginYShift},side}}}debug52(`[${group.name}] Group ${groupId} has ${groupPins.length} pins:`,groupPins),problem.chipMap[groupId]={chipId:groupId,pins:groupPins,size:{x:groupWidth,y:groupHeight}},debug52(`[${group.name}] Added group ${groupId} to chipMap`)}else debug52(`[${group.name}] Warning: No schematic_group found for group ${groupId}`)}}),debug52(`[${group.name}] Creating connections using connectivity keys`);let connectivityGroups=new Map;for(let[chipId,chip]of Object.entries(problem.chipMap))for(let pinId of chip.pins){let pinNumber=pinId.split(".").pop(),treeNode=tree.childNodes.find(child=>child.nodeType==="component"&&child.sourceComponent?child.sourceComponent.name===chipId:child.nodeType==="group"&&child.sourceGroup?`group_${tree.childNodes.indexOf(child)}`===chipId:!1);if(treeNode?.nodeType==="group"&&treeNode.sourceGroup){let schematicGroup=db.schematic_group?.getWhere?.({source_group_id:treeNode.sourceGroup.source_group_id});if(schematicGroup){let groupComponents=db.schematic_component.list({schematic_group_id:schematicGroup.schematic_group_id});for(let comp of groupComponents){let sourcePorts=db.source_port.list({source_component_id:comp.source_component_id});for(let sourcePort of sourcePorts){let portNumber=sourcePort.pin_number||sourcePort.name;if(String(portNumber)===String(pinNumber))if(sourcePort.subcircuit_connectivity_map_key){let connectivityKey=sourcePort.subcircuit_connectivity_map_key;connectivityGroups.has(connectivityKey)||connectivityGroups.set(connectivityKey,[]),connectivityGroups.get(connectivityKey).push(pinId),debug52(`[${group.name}] \u2713 Pin ${pinId} has connectivity key: ${connectivityKey}`)}else debug52(`[${group.name}] Pin ${pinId} has no connectivity key`)}}}}else if(treeNode?.nodeType==="component"&&treeNode.sourceComponent){let sourcePorts=db.source_port.list({source_component_id:treeNode.sourceComponent.source_component_id});for(let sourcePort of sourcePorts){let portNumber=sourcePort.pin_number||sourcePort.name;if(String(portNumber)===String(pinNumber)&&sourcePort.subcircuit_connectivity_map_key){let connectivityKey=sourcePort.subcircuit_connectivity_map_key;connectivityGroups.has(connectivityKey)||connectivityGroups.set(connectivityKey,[]),connectivityGroups.get(connectivityKey).push(pinId),debug52(`[${group.name}] Pin ${pinId} has connectivity key: ${connectivityKey}`)}}}}debug52(`[${group.name}] Found ${connectivityGroups.size} connectivity groups:`,Array.from(connectivityGroups.entries()).map(([key,pins])=>({key,pins})));for(let[connectivityKey,pins]of connectivityGroups)if(pins.length>=2){let tracesWithThisKey=db.source_trace.list().filter(trace=>trace.subcircuit_connectivity_map_key===connectivityKey),hasNetConnections=tracesWithThisKey.some(trace=>trace.connected_source_net_ids&&trace.connected_source_net_ids.length>0),hasDirectConnections=tracesWithThisKey.some(trace=>trace.connected_source_port_ids&&trace.connected_source_port_ids.length>=2);if(debug52(`[${group.name}] Connectivity ${connectivityKey}: hasNetConnections=${hasNetConnections}, hasDirectConnections=${hasDirectConnections}`),hasDirectConnections){for(let trace of tracesWithThisKey)if(trace.connected_source_port_ids&&trace.connected_source_port_ids.length>=2){let directlyConnectedPins=[];for(let portId of trace.connected_source_port_ids)for(let pinId of pins){let pinNumber=pinId.split(".").pop(),sourcePort=db.source_port.get(portId);if(sourcePort&&String(sourcePort.pin_number||sourcePort.name)===String(pinNumber)){let chipId=pinId.split(".")[0],treeNode=tree.childNodes.find(child=>child.nodeType==="component"&&child.sourceComponent?child.sourceComponent.name===chipId:child.nodeType==="group"&&child.sourceGroup?`group_${tree.childNodes.indexOf(child)}`===chipId:!1);treeNode?.nodeType==="component"&&treeNode.sourceComponent&&db.source_port.list({source_component_id:treeNode.sourceComponent.source_component_id}).some(p4=>p4.source_port_id===portId)&&directlyConnectedPins.push(pinId)}}for(let i3=0;i3<directlyConnectedPins.length;i3++)for(let j3=i3+1;j3<directlyConnectedPins.length;j3++){let pin1=directlyConnectedPins[i3],pin2=directlyConnectedPins[j3];problem.pinStrongConnMap[`${pin1}-${pin2}`]=!0,problem.pinStrongConnMap[`${pin2}-${pin1}`]=!0,debug52(`[${group.name}] Created strong connection: ${pin1} <-> ${pin2}`)}}}if(hasNetConnections){let source_net2=db.source_net.getWhere({subcircuit_connectivity_map_key:connectivityKey}),isGround=source_net2?.is_ground??!1,isPositiveVoltageSource=source_net2?.is_power??!1;problem.netMap[connectivityKey]={netId:connectivityKey,isGround,isPositiveVoltageSource};for(let pinId of pins)problem.netConnMap[`${pinId}-${connectivityKey}`]=!0;debug52(`[${group.name}] Created net ${connectivityKey} with ${pins.length} pins:`,pins)}}return problem}function Group_doInitialSchematicLayoutMatchPack(group){let{db}=group.root,tree=getCircuitJsonTree(db.toArray(),{source_group_id:group.source_group_id});if(debug52(`[${group.name}] Starting matchpack layout with ${tree.childNodes.length} children`),debug52(`[${group.name}] Tree structure:`,JSON.stringify(tree,null,2)),tree.childNodes.length<=1){debug52(`[${group.name}] Only ${tree.childNodes.length} children, skipping layout`);return}debug52("Converting circuit tree to InputProblem...");let inputProblem=convertTreeToInputProblem(tree,db,group);debug52.enabled&&group.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`matchpack-input-problem-${group.name}`,content:JSON.stringify(inputProblem,null,2)});let solver=new LayoutPipelineSolver(inputProblem);if(debug52("Starting LayoutPipelineSolver..."),debug52.enabled&&global?.debugGraphics){let initialViz=solver.visualize();global.debugGraphics.push({...initialViz,title:`matchpack-initial-${group.name}`})}if(solver.solve(),debug52(`Solver completed in ${solver.iterations} iterations`),debug52(`Solved: ${solver.solved}, Failed: ${solver.failed}`),solver.failed)throw debug52(`Solver failed with error: ${solver.error}`),new Error(`Matchpack layout solver failed: ${solver.error}`);let outputLayout=solver.getOutputLayout();if(debug52("OutputLayout:",JSON.stringify(outputLayout,null,2)),debug52("Solver completed successfully:",!solver.failed),debug52.enabled&&global?.debugGraphics){let finalViz=solver.visualize();global.debugGraphics.push({...finalViz,title:`matchpack-final-${group.name}`})}let overlaps=solver.checkForOverlaps(outputLayout);if(overlaps.length>0){debug52(`Warning: Found ${overlaps.length} overlapping components:`);for(let overlap of overlaps)debug52(` ${overlap.chip1} overlaps ${overlap.chip2} (area: ${overlap.overlapArea})`)}let groupOffset=group._getGlobalSchematicPositionBeforeLayout();debug52(`Group offset: x=${groupOffset.x}, y=${groupOffset.y}`),debug52(`Applying layout results for ${Object.keys(outputLayout.chipPlacements).length} chip placements`);for(let[chipId,placement]of Object.entries(outputLayout.chipPlacements)){debug52(`Processing placement for chip: ${chipId} at (${placement.x}, ${placement.y})`);let treeNode=tree.childNodes.find(child=>{if(child.nodeType==="component"&&child.sourceComponent){let matches=child.sourceComponent.name===chipId;return debug52(` Checking component ${child.sourceComponent.name}: matches=${matches}`),matches}if(child.nodeType==="group"&&child.sourceGroup){let groupName=child.sourceGroup.name,expectedChipId=`group_${tree.childNodes.indexOf(child)}`,matches=expectedChipId===chipId;return debug52(` Checking group ${groupName} (expected chipId: ${expectedChipId}): matches=${matches}`),matches}return!1});if(!treeNode){debug52(`Warning: No tree node found for chip: ${chipId}`),debug52("Available tree nodes:",tree.childNodes.map((child,idx)=>({type:child.nodeType,name:child.nodeType==="component"?child.sourceComponent?.name:child.sourceGroup?.name,expectedChipId:child.nodeType==="group"?`group_${idx}`:child.sourceComponent?.name})));continue}let newCenter={x:placement.x+groupOffset.x,y:placement.y+groupOffset.y};if(treeNode.nodeType==="component"&&treeNode.sourceComponent){let schematicComponent=db.schematic_component.getWhere({source_component_id:treeNode.sourceComponent.source_component_id});if(schematicComponent){debug52(`Moving component ${chipId} to (${newCenter.x}, ${newCenter.y})`);let ports=db.schematic_port.list({schematic_component_id:schematicComponent.schematic_component_id}),texts=db.schematic_text.list({schematic_component_id:schematicComponent.schematic_component_id}),positionDelta={x:newCenter.x-schematicComponent.center.x,y:newCenter.y-schematicComponent.center.y};for(let port of ports)port.center.x+=positionDelta.x,port.center.y+=positionDelta.y;for(let text of texts)text.position.x+=positionDelta.x,text.position.y+=positionDelta.y;if(updateSchematicPrimitivesForLayoutShift({db,schematicComponentId:schematicComponent.schematic_component_id,deltaX:positionDelta.x,deltaY:positionDelta.y}),schematicComponent.center=newCenter,placement.ccwRotationDegrees!==0){debug52(`Component ${chipId} has rotation: ${placement.ccwRotationDegrees}\xB0`);let angleRad=placement.ccwRotationDegrees*Math.PI/180,cos4=Math.cos(angleRad),sin4=Math.sin(angleRad);for(let port of ports){let dx2=port.center.x-newCenter.x,dy2=port.center.y-newCenter.y,rotatedDx=dx2*cos4-dy2*sin4,rotatedDy=dx2*sin4+dy2*cos4;port.center.x=newCenter.x+rotatedDx,port.center.y=newCenter.y+rotatedDy;let originalDirection=port.facing_direction||"right";port.facing_direction=rotateDirection2(originalDirection,placement.ccwRotationDegrees),port.side_of_component=(port.facing_direction==="up"?"top":port.facing_direction==="down"?"bottom":port.facing_direction)||port.side_of_component}for(let text of texts){let dx2=text.position.x-newCenter.x,dy2=text.position.y-newCenter.y,rotatedDx=dx2*cos4-dy2*sin4,rotatedDy=dx2*sin4+dy2*cos4;text.position.x=newCenter.x+rotatedDx,text.position.y=newCenter.y+rotatedDy}if(schematicComponent.symbol_name){let schematicSymbolDirection=schematicComponent.symbol_name.match(/_(right|left|up|down)$/);schematicSymbolDirection&&(schematicComponent.symbol_name=schematicComponent.symbol_name.replace(schematicSymbolDirection[0],`_${rotateDirection2(schematicSymbolDirection[1],placement.ccwRotationDegrees)}`))}}}}else if(treeNode.nodeType==="group"&&treeNode.sourceGroup){let schematicGroup=db.schematic_group?.getWhere?.({source_group_id:treeNode.sourceGroup.source_group_id});if(schematicGroup){debug52(`Moving group ${chipId} to (${newCenter.x}, ${newCenter.y}) from (${schematicGroup.center?.x}, ${schematicGroup.center?.y})`);let groupComponents=db.schematic_component.list({schematic_group_id:schematicGroup.schematic_group_id});debug52(`Group ${chipId} has ${groupComponents.length} components to move`);let oldCenter=schematicGroup.center||{x:0,y:0},positionDelta={x:newCenter.x-oldCenter.x,y:newCenter.y-oldCenter.y};debug52(`Position delta for group ${chipId}: (${positionDelta.x}, ${positionDelta.y})`);for(let component of groupComponents)if(component.center){let oldComponentCenter={...component.center};component.center.x+=positionDelta.x,component.center.y+=positionDelta.y,debug52(`Moved component ${component.source_component_id} from (${oldComponentCenter.x}, ${oldComponentCenter.y}) to (${component.center.x}, ${component.center.y})`);let ports=db.schematic_port.list({schematic_component_id:component.schematic_component_id}),texts=db.schematic_text.list({schematic_component_id:component.schematic_component_id});for(let port of ports)port.center&&(port.center.x+=positionDelta.x,port.center.y+=positionDelta.y);for(let text of texts)text.position&&(text.position.x+=positionDelta.x,text.position.y+=positionDelta.y)}schematicGroup.center=newCenter,debug52(`Updated group ${chipId} center to (${newCenter.x}, ${newCenter.y})`)}}}debug52("Matchpack layout completed successfully")}function Group_doInitialSourceAddConnectivityMapKey(group){if(!group.isSubcircuit)return;let{db}=group.root,traces=group.selectAll("trace"),vias=group.selectAll("via"),nets=group.selectAll("net"),connMap=new ConnectivityMap({});connMap.addConnections(traces.map(t6=>{let source_trace2=db.source_trace.get(t6.source_trace_id);return source_trace2?[source_trace2.source_trace_id,...source_trace2.connected_source_port_ids,...source_trace2.connected_source_net_ids]:null}).filter(c3=>c3!==null));let sourceNets=db.source_net.list().filter(net=>net.subcircuit_id===group.subcircuit_id);for(let sourceNet of sourceNets)connMap.addConnections([[sourceNet.source_net_id]]);let{name:subcircuitName}=group._parsedProps;for(let trace of traces){if(!trace.source_trace_id)continue;let connNetId=connMap.getNetConnectedToId(trace.source_trace_id);connNetId&&(trace.subcircuit_connectivity_map_key=`${subcircuitName??`unnamedsubcircuit${group._renderId}`}_${connNetId}`,db.source_trace.update(trace.source_trace_id,{subcircuit_connectivity_map_key:trace.subcircuit_connectivity_map_key}))}let allSourcePortIds=new Set;for(let trace of traces){if(!trace.source_trace_id)continue;let source_trace2=db.source_trace.get(trace.source_trace_id);if(source_trace2)for(let id of source_trace2.connected_source_port_ids)allSourcePortIds.add(id)}for(let portId of allSourcePortIds){let connNetId=connMap.getNetConnectedToId(portId);if(!connNetId)continue;let connectivityMapKey=`${subcircuitName??`unnamedsubcircuit${group._renderId}`}_${connNetId}`;db.source_port.update(portId,{subcircuit_connectivity_map_key:connectivityMapKey})}let allSourceNetIds=new Set;for(let trace of traces){if(!trace.source_trace_id)continue;let source_trace2=db.source_trace.get(trace.source_trace_id);if(source_trace2)for(let source_net_id of source_trace2.connected_source_net_ids)allSourceNetIds.add(source_net_id)}for(let sourceNet of sourceNets)allSourceNetIds.add(sourceNet.source_net_id);for(let netId of allSourceNetIds){let connNetId=connMap.getNetConnectedToId(netId);if(!connNetId)continue;let connectivityMapKey=`${subcircuitName??`unnamedsubcircuit${group._renderId}`}_${connNetId}`;db.source_net.update(netId,{subcircuit_connectivity_map_key:connectivityMapKey});let netInstance=nets.find(n3=>n3.source_net_id===netId);netInstance&&(netInstance.subcircuit_connectivity_map_key=connectivityMapKey)}for(let via of vias){let connectedNetOrTrace=via._getConnectedNetOrTrace();connectedNetOrTrace&&connectedNetOrTrace.subcircuit_connectivity_map_key&&(via.subcircuit_connectivity_map_key=connectedNetOrTrace.subcircuit_connectivity_map_key)}}function Group_doInitialSchematicLayoutGrid(group){let{db}=group.root,props=group._parsedProps,schematicChildren=group.children.filter(child=>{let isExplicitlyPositioned=child._parsedProps?.schX!==void 0||child._parsedProps?.schY!==void 0;return child.schematic_component_id&&!isExplicitlyPositioned});if(schematicChildren.length===0)return;let maxCellWidth=0,maxCellHeight=0;for(let child of schematicChildren){let schComp=db.schematic_component.get(child.schematic_component_id);schComp?.size&&(maxCellWidth=Math.max(maxCellWidth,schComp.size.width),maxCellHeight=Math.max(maxCellHeight,schComp.size.height))}maxCellWidth===0&&schematicChildren.length>0&&(maxCellWidth=1),maxCellHeight===0&&schematicChildren.length>0&&(maxCellHeight=1);let gridColsOption=props.gridCols,gridRowsOption,gridGapOption=props.gridGap,gridRowGapOption=props.gridRowGap,gridColumnGapOption=props.gridColumnGap;props.schLayout?.grid&&(gridColsOption=props.schLayout.grid.cols??gridColsOption,gridRowsOption=props.schLayout.grid.rows,gridGapOption=props.schLayout.gridGap??gridGapOption,gridRowGapOption=props.schLayout.gridRowGap??gridRowGapOption,gridColumnGapOption=props.schLayout.gridColumnGap??gridColumnGapOption);let numCols,numRows;gridColsOption!==void 0&&gridRowsOption!==void 0?(numCols=gridColsOption,numRows=gridRowsOption):gridColsOption!==void 0?(numCols=gridColsOption,numRows=Math.ceil(schematicChildren.length/numCols)):gridRowsOption!==void 0?(numRows=gridRowsOption,numCols=Math.ceil(schematicChildren.length/numRows)):(numCols=Math.ceil(Math.sqrt(schematicChildren.length)),numRows=Math.ceil(schematicChildren.length/numCols)),numCols===0&&schematicChildren.length>0&&(numCols=1),numRows===0&&schematicChildren.length>0&&(numRows=schematicChildren.length);let gridGapX,gridGapY,parseGap=val=>{if(val!==void 0)return typeof val=="number"?val:length.parse(val)};if(gridRowGapOption!==void 0||gridColumnGapOption!==void 0){let fallbackX=typeof gridGapOption=="object"&&gridGapOption!==null?gridGapOption.x:gridGapOption,fallbackY=typeof gridGapOption=="object"&&gridGapOption!==null?gridGapOption.y:gridGapOption;gridGapX=parseGap(gridColumnGapOption??fallbackX)??1,gridGapY=parseGap(gridRowGapOption??fallbackY)??1}else if(typeof gridGapOption=="number")gridGapX=gridGapOption,gridGapY=gridGapOption;else if(typeof gridGapOption=="string"){let parsed=length.parse(gridGapOption);gridGapX=parsed,gridGapY=parsed}else if(typeof gridGapOption=="object"&&gridGapOption!==null){let xRaw=gridGapOption.x,yRaw=gridGapOption.y;gridGapX=typeof xRaw=="number"?xRaw:length.parse(xRaw??"0mm"),gridGapY=typeof yRaw=="number"?yRaw:length.parse(yRaw??"0mm")}else gridGapX=1,gridGapY=1;let totalGridWidth=numCols*maxCellWidth+Math.max(0,numCols-1)*gridGapX,totalGridHeight=numRows*maxCellHeight+Math.max(0,numRows-1)*gridGapY,groupCenter=group._getGlobalSchematicPositionBeforeLayout(),firstCellCenterX=groupCenter.x-totalGridWidth/2+maxCellWidth/2,firstCellCenterY=groupCenter.y+totalGridHeight/2-maxCellHeight/2;for(let i3=0;i3<schematicChildren.length;i3++){let child=schematicChildren[i3];if(!child.schematic_component_id)continue;let row=Math.floor(i3/numCols),col=i3%numCols;if(row>=numRows||col>=numCols){console.warn(`Schematic grid layout: Child ${child.getString()} at index ${i3} (row ${row}, col ${col}) exceeds specified grid dimensions (${numRows}x${numCols}). Skipping placement.`);continue}let targetCellCenterX=firstCellCenterX+col*(maxCellWidth+gridGapX),targetCellCenterY=firstCellCenterY-row*(maxCellHeight+gridGapY),schComp=db.schematic_component.get(child.schematic_component_id);if(schComp){let oldChildCenter=schComp.center,newChildCenter={x:targetCellCenterX,y:targetCellCenterY};db.schematic_component.update(child.schematic_component_id,{center:newChildCenter});let deltaX=newChildCenter.x-oldChildCenter.x,deltaY=newChildCenter.y-oldChildCenter.y,schPorts=db.schematic_port.list({schematic_component_id:child.schematic_component_id});for(let port of schPorts)db.schematic_port.update(port.schematic_port_id,{center:{x:port.center.x+deltaX,y:port.center.y+deltaY}});let schTexts=db.schematic_text.list({schematic_component_id:child.schematic_component_id});for(let text of schTexts)db.schematic_text.update(text.schematic_text_id,{position:{x:text.position.x+deltaX,y:text.position.y+deltaY}});updateSchematicPrimitivesForLayoutShift({db,schematicComponentId:child.schematic_component_id,deltaX,deltaY})}}group.schematic_group_id&&db.schematic_group.update(group.schematic_group_id,{width:totalGridWidth,height:totalGridHeight,center:groupCenter})}var getSizeOfTreeNodeChild=(db,child)=>{let{sourceComponent,sourceGroup}=child;if(child.nodeType==="component"){let schComponent=db.schematic_component.getWhere({source_component_id:sourceComponent?.source_component_id});return schComponent?.size?{width:schComponent.size.width,height:schComponent.size.height}:null}if(child.nodeType==="group"){let schGroup=db.schematic_group.getWhere({source_group_id:sourceGroup?.source_group_id});if(schGroup?.width&&schGroup?.height)return{width:schGroup.width,height:schGroup.height};let groupComponents=db.schematic_component.list({schematic_group_id:schGroup?.schematic_group_id}),minX=1/0,maxX=-1/0,minY=1/0,maxY=-1/0;for(let comp of groupComponents)if(comp.center&&comp.size){let halfWidth=comp.size.width/2,halfHeight=comp.size.height/2;minX=Math.min(minX,comp.center.x-halfWidth),maxX=Math.max(maxX,comp.center.x+halfWidth),minY=Math.min(minY,comp.center.y-halfHeight),maxY=Math.max(maxY,comp.center.y+halfHeight)}let groupWidth=maxX-minX,groupHeight=maxY-minY;return{width:groupWidth,height:groupHeight}}return null},Group_doInitialSchematicLayoutFlex=group=>{let{db}=group.root,props=group._parsedProps,tree=getCircuitJsonTree(db.toArray(),{source_group_id:group.source_group_id}),rawJustify=props.schJustifyContent??props.justifyContent,rawAlign=props.schAlignItems??props.alignItems,rawGap=props.schFlexGap??props.schGap??props.gap,direction2=props.schFlexDirection??"row",justifyContent={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"space-between","space-between":"space-between","space-around":"space-around","space-evenly":"space-evenly",center:"center"}[rawJustify??"space-between"],alignItems={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[rawAlign??"center"];if(!justifyContent)throw new Error(`Invalid justifyContent value: "${rawJustify}"`);if(!alignItems)throw new Error(`Invalid alignItems value: "${rawAlign}"`);let rowGap=0,columnGap=0;typeof rawGap=="object"?(rowGap=rawGap.y??0,columnGap=rawGap.x??0):typeof rawGap=="number"?(rowGap=rawGap,columnGap=rawGap):typeof rawGap=="string"&&(rowGap=length.parse(rawGap),columnGap=length.parse(rawGap));let minFlexContainer,width=props.width??props.schWidth??void 0,height=props.height??props.schHeight??void 0;(width===void 0||height===void 0)&&(minFlexContainer=getMinimumFlexContainer(tree.childNodes.map(child=>getSizeOfTreeNodeChild(db,child)).filter(size2=>size2!==null),{alignItems,justifyContent,direction:direction2,rowGap,columnGap}),width=minFlexContainer.width,height=minFlexContainer.height);let flexBox=new RootFlexBox(width,height,{alignItems,justifyContent,direction:direction2,rowGap,columnGap});for(let child of tree.childNodes){let size2=getSizeOfTreeNodeChild(db,child);flexBox.addChild({metadata:child,width:size2?.width??0,height:size2?.height??0,flexBasis:size2?direction2==="row"?size2.width:size2.height:void 0})}flexBox.build();let bounds={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let child of flexBox.children)bounds.minX=Math.min(bounds.minX,child.position.x),bounds.minY=Math.min(bounds.minY,child.position.y),bounds.maxX=Math.max(bounds.maxX,child.position.x+child.size.width),bounds.maxY=Math.max(bounds.maxY,child.position.y+child.size.height);bounds.width=bounds.maxX-bounds.minX,bounds.height=bounds.maxY-bounds.minY;let offset={x:-(bounds.maxX+bounds.minX)/2,y:-(bounds.maxY+bounds.minY)/2},allCircuitJson=db.toArray();for(let child of flexBox.children){let{sourceComponent,sourceGroup}=child.metadata;if(sourceComponent){let schComponent=db.schematic_component.getWhere({source_component_id:sourceComponent.source_component_id});if(!schComponent)continue;repositionSchematicComponentTo(allCircuitJson,schComponent.schematic_component_id,{x:child.position.x+child.size.width/2+offset.x,y:child.position.y+child.size.height/2+offset.y})}if(sourceGroup){if(!db.schematic_group.getWhere({source_group_id:sourceGroup.source_group_id}))continue;repositionSchematicGroupTo(allCircuitJson,sourceGroup.source_group_id,{x:child.position.x+child.size.width/2+offset.x,y:child.position.y+child.size.height/2+offset.y})}}group.schematic_group_id&&db.schematic_group.update(group.schematic_group_id,{width:bounds.width,height:bounds.height})},MIN_GAP=1;function Group_doInitialPcbLayoutGrid(group){let{db}=group.root,props=group._parsedProps,pcbChildren=getPcbChildren(group);if(pcbChildren.length===0)return;let childDimensions=calculateChildDimensions({db,pcbChildren}),gridConfig=parseGridConfiguration(props),gridLayout=createGridLayout({props,pcbChildren,childDimensions,gridConfig}),cssGrid=createCssGrid({pcbChildren,childDimensions,gridLayout,gridConfig}),{itemCoordinates}=cssGrid.layout();positionChildren({db,group,pcbChildren,itemCoordinates,gridLayout}),updateGroupDimensions({db,group,props,gridLayout})}function getPcbChildren(group){return group.children.filter(child=>child.pcb_component_id||child.pcb_group_id)}function calculateChildDimensions(params){let{db,pcbChildren}=params,maxWidth=0,maxHeight=0;for(let child of pcbChildren){let width=0,height=0;if(child.pcb_group_id){let pcbGroup=db.pcb_group.get(child.pcb_group_id);width=pcbGroup?.width??0,height=pcbGroup?.height??0}else if(child.pcb_component_id){let pcbComp=db.pcb_component.get(child.pcb_component_id);width=pcbComp?.width??0,height=pcbComp?.height??0}maxWidth=Math.max(maxWidth,width),maxHeight=Math.max(maxHeight,height)}return{width:maxWidth,height:maxHeight}}function parseGridConfiguration(props){let cols=props.pcbGridCols??props.gridCols??props.pcbLayout?.grid?.cols,rows=props.pcbGridRows??props.pcbLayout?.grid?.rows,templateColumns=props.pcbGridTemplateColumns,templateRows=props.pcbGridTemplateRows,parseGap=gapValue=>gapValue===void 0?MIN_GAP:typeof gapValue=="number"?gapValue:length.parse(gapValue),gridGapOption=props.pcbGridGap??props.gridGap??props.pcbLayout?.gridGap,rowGapOption=props.pcbGridRowGap??props.gridRowGap??props.pcbLayout?.gridRowGap,colGapOption=props.pcbGridColumnGap??props.gridColumnGap??props.pcbLayout?.gridColumnGap,gapX=MIN_GAP,gapY=MIN_GAP;if(rowGapOption!==void 0||colGapOption!==void 0){let fallbackX=typeof gridGapOption=="object"?gridGapOption?.x:gridGapOption,fallbackY=typeof gridGapOption=="object"?gridGapOption?.y:gridGapOption;gapX=parseGap(colGapOption??fallbackX),gapY=parseGap(rowGapOption??fallbackY)}else if(typeof gridGapOption=="object"&&gridGapOption!==null)gapX=parseGap(gridGapOption.x),gapY=parseGap(gridGapOption.y);else{let gap=parseGap(gridGapOption);gapX=gap,gapY=gap}return{cols,rows,gapX,gapY,templateColumns,templateRows}}function createGridLayout(params){let{props,pcbChildren,childDimensions,gridConfig}=params;return props.pcbGridTemplateColumns||props.pcbGridTemplateRows?createTemplateBasedLayout({props,gridConfig,pcbChildren,childDimensions}):createDefaultLayout({gridConfig,pcbChildren,childDimensions})}function createTemplateBasedLayout(params){let{props,gridConfig,pcbChildren,childDimensions}=params,gridTemplateColumns=props.pcbGridTemplateColumns??"",gridTemplateRows=props.pcbGridTemplateRows??"",extractRepeatCount=template=>{let match2=template.match(/repeat\((\d+),/);return match2?parseInt(match2[1]):Math.ceil(Math.sqrt(pcbChildren.length))},numCols=props.pcbGridTemplateColumns?extractRepeatCount(gridTemplateColumns):Math.ceil(Math.sqrt(pcbChildren.length)),numRows=props.pcbGridTemplateRows?extractRepeatCount(gridTemplateRows):Math.ceil(pcbChildren.length/numCols),containerWidth=numCols*childDimensions.width+Math.max(0,numCols-1)*gridConfig.gapX,containerHeight=numRows*childDimensions.height+Math.max(0,numRows-1)*gridConfig.gapY;return{gridTemplateColumns,gridTemplateRows,containerWidth,containerHeight}}function createDefaultLayout(params){let{gridConfig,pcbChildren,childDimensions}=params,numCols,numRows;gridConfig.cols!==void 0&&gridConfig.rows!==void 0?(numCols=gridConfig.cols,numRows=gridConfig.rows):gridConfig.cols!==void 0?(numCols=gridConfig.cols,numRows=Math.ceil(pcbChildren.length/numCols)):gridConfig.rows!==void 0?(numRows=gridConfig.rows,numCols=Math.ceil(pcbChildren.length/numRows)):(numCols=Math.ceil(Math.sqrt(pcbChildren.length)),numRows=Math.ceil(pcbChildren.length/numCols)),numCols=Math.max(1,numCols),numRows=Math.max(1,numRows);let containerWidth=numCols*childDimensions.width+Math.max(0,numCols-1)*gridConfig.gapX,containerHeight=numRows*childDimensions.height+Math.max(0,numRows-1)*gridConfig.gapY,gridTemplateColumns=`repeat(${numCols}, ${childDimensions.width}px)`,gridTemplateRows=`repeat(${numRows}, ${childDimensions.height}px)`;return{gridTemplateColumns,gridTemplateRows,containerWidth,containerHeight}}function createCssGrid(params){let{pcbChildren,childDimensions,gridLayout,gridConfig}=params,gridChildren=pcbChildren.map((child,index)=>({key:child.getString()||`child-${index}`,contentWidth:childDimensions.width,contentHeight:childDimensions.height}));return new CssGrid({containerWidth:gridLayout.containerWidth,containerHeight:gridLayout.containerHeight,gridTemplateColumns:gridLayout.gridTemplateColumns,gridTemplateRows:gridLayout.gridTemplateRows,gap:[gridConfig.gapY,gridConfig.gapX],children:gridChildren})}function positionChildren(params){let{db,group,pcbChildren,itemCoordinates,gridLayout}=params,groupCenter=group._getGlobalPcbPositionBeforeLayout(),allCircuitJson=db.toArray();for(let i3=0;i3<pcbChildren.length;i3++){let child=pcbChildren[i3],childKey=child.getString()||`child-${i3}`,coordinates=itemCoordinates[childKey];if(!coordinates){console.warn(`PCB grid layout: No coordinates found for child ${childKey}`);continue}let targetX=groupCenter.x-gridLayout.containerWidth/2+coordinates.x+coordinates.width/2,targetY=groupCenter.y+gridLayout.containerHeight/2-coordinates.y-coordinates.height/2;if(child.pcb_component_id)repositionPcbComponentTo(allCircuitJson,child.pcb_component_id,{x:targetX,y:targetY});else{let groupChild=child;groupChild.pcb_group_id&&groupChild.source_group_id&&repositionPcbGroupTo(allCircuitJson,groupChild.source_group_id,{x:targetX,y:targetY})}}}function updateGroupDimensions(params){let{db,group,props,gridLayout}=params;if(group.pcb_group_id){let groupCenter=group._getGlobalPcbPositionBeforeLayout();db.pcb_group.update(group.pcb_group_id,{width:props.width??gridLayout.containerWidth,height:props.height??gridLayout.containerHeight,center:groupCenter})}}function getPresetAutoroutingConfig(autorouterConfig2){let defaults={serverUrl:"https://registry-api.tscircuit.com",serverMode:"job",serverCacheEnabled:!0};if(typeof autorouterConfig2=="object"&&!autorouterConfig2.preset)return{local:!(autorouterConfig2.serverUrl||autorouterConfig2.serverMode||autorouterConfig2.serverCacheEnabled),...defaults,...autorouterConfig2};let preset=typeof autorouterConfig2=="object"?autorouterConfig2.preset:autorouterConfig2,providedConfig=typeof autorouterConfig2=="object"?autorouterConfig2:{};switch(typeof preset=="string"?preset.replace(/_/g,"-"):preset){case"auto-local":return{local:!0,groupMode:"subcircuit"};case"sequential-trace":return{local:!0,groupMode:"sequential-trace"};case"subcircuit":return{local:!0,groupMode:"subcircuit"};case"auto-cloud":{let{preset:_preset,local:_local,groupMode:_groupMode,...rest}=providedConfig;return{local:!1,groupMode:"subcircuit",...defaults,...rest}}case"laser-prefab":{let{preset:_preset,local:_local,groupMode:_groupMode,...rest}=providedConfig;return{local:!0,groupMode:"subcircuit",preset:"laser_prefab",...rest}}default:return{local:!0,groupMode:"subcircuit"}}}var applyComponentConstraintClusters=(group,packInput)=>{let constraints=group.children.filter(c3=>c3.componentName==="Constraint"&&c3._parsedProps.pcb),clusterByRoot=new Map,parent={},find2=x3=>(parent[x3]!==x3&&(parent[x3]=find2(parent[x3])),parent[x3]),union2=(a3,b3)=>{let ra2=find2(a3),rb2=find2(b3);ra2!==rb2&&(parent[rb2]=ra2)},makeSet=x3=>{x3 in parent||(parent[x3]=x3)},getIdFromSelector=sel2=>{let name=sel2.startsWith(".")?sel2.slice(1):sel2;return group.children.find(c3=>c3.name===name)?.pcb_component_id??void 0};for(let constraint of constraints){let props=constraint._parsedProps;if("left"in props&&"right"in props){let a3=getIdFromSelector(props.left),b3=getIdFromSelector(props.right);a3&&b3&&(makeSet(a3),makeSet(b3),union2(a3,b3))}else if("top"in props&&"bottom"in props){let a3=getIdFromSelector(props.top),b3=getIdFromSelector(props.bottom);a3&&b3&&(makeSet(a3),makeSet(b3),union2(a3,b3))}else if("for"in props&&Array.isArray(props.for)){let ids=props.for.map(s4=>getIdFromSelector(s4)).filter(s4=>!!s4);for(let id of ids)makeSet(id);for(let i3=1;i3<ids.length;i3++)union2(ids[0],ids[i3])}}for(let id of Object.keys(parent)){let rootId=find2(id);clusterByRoot.has(rootId)||clusterByRoot.set(rootId,{componentIds:[],constraints:[]}),clusterByRoot.get(rootId).componentIds.push(id)}for(let constraint of constraints){let props=constraint._parsedProps,compId;if("left"in props?compId=getIdFromSelector(props.left):"top"in props?compId=getIdFromSelector(props.top):"for"in props&&(compId=getIdFromSelector(props.for[0])),!compId)continue;let root=find2(compId);clusterByRoot.get(root)?.constraints.push(constraint)}let clusterMap={},packCompById=Object.fromEntries(packInput.components.map(c3=>[c3.componentId,c3]));for(let[rootId,info]of clusterByRoot.entries()){if(info.componentIds.length<=1)continue;let solver=new Solver,kVars={},getVar=(id,axis)=>{let key=`${id}_${axis}`;return kVars[key]||(kVars[key]=new Variable(key)),kVars[key]},anchor=info.componentIds[0];solver.addConstraint(new Constraint(getVar(anchor,"x"),Operator.Eq,0,Strength.required)),solver.addConstraint(new Constraint(getVar(anchor,"y"),Operator.Eq,0,Strength.required));for(let constraint of info.constraints){let props=constraint._parsedProps;if("xDist"in props){let left=getIdFromSelector(props.left),right=getIdFromSelector(props.right);left&&right&&solver.addConstraint(new Constraint(new Expression(getVar(right,"x"),[-1,getVar(left,"x")]),Operator.Eq,props.xDist,Strength.required))}else if("yDist"in props){let top=getIdFromSelector(props.top),bottom=getIdFromSelector(props.bottom);top&&bottom&&solver.addConstraint(new Constraint(new Expression(getVar(top,"y"),[-1,getVar(bottom,"y")]),Operator.Eq,props.yDist,Strength.required))}else if("sameX"in props&&Array.isArray(props.for)){let ids=props.for.map(s4=>getIdFromSelector(s4)).filter(s4=>!!s4);if(ids.length>1){let base=getVar(ids[0],"x");for(let i3=1;i3<ids.length;i3++)solver.addConstraint(new Constraint(new Expression(getVar(ids[i3],"x"),[-1,base]),Operator.Eq,0,Strength.required))}}else if("sameY"in props&&Array.isArray(props.for)){let ids=props.for.map(s4=>getIdFromSelector(s4)).filter(s4=>!!s4);if(ids.length>1){let base=getVar(ids[0],"y");for(let i3=1;i3<ids.length;i3++)solver.addConstraint(new Constraint(new Expression(getVar(ids[i3],"y"),[-1,base]),Operator.Eq,0,Strength.required))}}}solver.updateVariables();let positions={};for(let id of info.componentIds)positions[id]={x:getVar(id,"x").value(),y:getVar(id,"y").value()};let minX=1/0,minY=1/0,maxX=-1/0,maxY=-1/0;for(let id of info.componentIds){let comp=packCompById[id],pos=positions[id];if(comp)for(let pad2 of comp.pads){let ax2=pos.x+pad2.offset.x,ay2=pos.y+pad2.offset.y;minX=Math.min(minX,ax2-pad2.size.x/2),maxX=Math.max(maxX,ax2+pad2.size.x/2),minY=Math.min(minY,ay2-pad2.size.y/2),maxY=Math.max(maxY,ay2+pad2.size.y/2)}}let clusterCenter={x:(minX+maxX)/2,y:(minY+maxY)/2},mergedPads=[],relCenters={};for(let id of info.componentIds){let comp=packCompById[id],pos=positions[id];if(comp){relCenters[id]={x:pos.x-clusterCenter.x,y:pos.y-clusterCenter.y};for(let pad2 of comp.pads)mergedPads.push({padId:pad2.padId,networkId:pad2.networkId,type:pad2.type,size:pad2.size,offset:{x:pos.x+pad2.offset.x-clusterCenter.x,y:pos.y+pad2.offset.y-clusterCenter.y}})}}packInput.components=packInput.components.filter(c3=>!info.componentIds.includes(c3.componentId)),packInput.components.push({componentId:info.componentIds[0],pads:mergedPads,availableRotationDegrees:[0]}),info.relativeCenters=relCenters,clusterMap[info.componentIds[0]]=info}return clusterMap},updateCadRotation=({db,pcbComponentId,rotationDegrees,layer})=>{if(rotationDegrees==null||!db?.cad_component?.list)return;let cadComponent=db.cad_component.getWhere({pcb_component_id:pcbComponentId});if(!cadComponent)return;let delta=layer?.toLowerCase?.()==="bottom"?-rotationDegrees:rotationDegrees,currentRotationZ=cadComponent.rotation?.z??0,nextRotation={...cadComponent.rotation??{x:0,y:0,z:0},z:normalizeDegrees(currentRotationZ+delta)};db.cad_component.update(cadComponent.cad_component_id,{rotation:nextRotation}),cadComponent.rotation=nextRotation},isDescendantGroup=(db,groupId,ancestorId)=>{if(groupId===ancestorId)return!0;let group=db.source_group.get(groupId);return!group||!group.parent_source_group_id?!1:isDescendantGroup(db,group.parent_source_group_id,ancestorId)},applyPackOutput=(group,packOutput,clusterMap)=>{let{db}=group.root;for(let packedComponent of packOutput.components){let{center:center2,componentId,ccwRotationOffset,ccwRotationDegrees}=packedComponent,cluster=clusterMap[componentId];if(cluster){let rotationDegrees2=ccwRotationDegrees??ccwRotationOffset??0,angleRad=rotationDegrees2*Math.PI/180;for(let memberId of cluster.componentIds){let rel=cluster.relativeCenters[memberId];if(!rel)continue;db.pcb_component.update(memberId,{position_mode:"packed"});let rotatedRel={x:rel.x*Math.cos(angleRad)-rel.y*Math.sin(angleRad),y:rel.x*Math.sin(angleRad)+rel.y*Math.cos(angleRad)},member=db.pcb_component.get(memberId);if(!member)continue;let originalCenter2=member.center,transformMatrix2=compose(group._computePcbGlobalTransformBeforeLayout(),translate(center2.x+rotatedRel.x,center2.y+rotatedRel.y),rotate(angleRad),translate(-originalCenter2.x,-originalCenter2.y)),related=db.toArray().filter(elm=>"pcb_component_id"in elm&&elm.pcb_component_id===memberId);transformPCBElements(related,transformMatrix2),updateCadRotation({db,pcbComponentId:memberId,rotationDegrees:rotationDegrees2,layer:member.layer})}continue}let pcbComponent=db.pcb_component.get(componentId);if(pcbComponent){db.pcb_component.update(componentId,{position_mode:"packed"});let currentGroupId=group.source_group_id,componentGroupId=db.source_component.get(pcbComponent.source_component_id)?.source_group_id;if(componentGroupId!==void 0&&!isDescendantGroup(db,componentGroupId,currentGroupId))continue;let originalCenter2=pcbComponent.center,rotationDegrees2=ccwRotationDegrees??ccwRotationOffset??0,transformMatrix2=compose(group._computePcbGlobalTransformBeforeLayout(),translate(center2.x,center2.y),rotate(rotationDegrees2*Math.PI/180),translate(-originalCenter2.x,-originalCenter2.y)),related=db.toArray().filter(elm=>"pcb_component_id"in elm&&elm.pcb_component_id===componentId);transformPCBElements(related,transformMatrix2),updateCadRotation({db,pcbComponentId:componentId,rotationDegrees:rotationDegrees2,layer:pcbComponent.layer});continue}let pcbGroup=db.pcb_group.list().find(g4=>g4.source_group_id===componentId);if(!pcbGroup)continue;let originalCenter=pcbGroup.center,rotationDegrees=ccwRotationDegrees??ccwRotationOffset??0,transformMatrix=compose(group._computePcbGlobalTransformBeforeLayout(),translate(center2.x,center2.y),rotate(rotationDegrees*Math.PI/180),translate(-originalCenter.x,-originalCenter.y)),relatedElements=db.toArray().filter(elm=>{if("source_group_id"in elm&&elm.source_group_id&&(elm.source_group_id===componentId||isDescendantGroup(db,elm.source_group_id,componentId)))return!0;if("source_component_id"in elm&&elm.source_component_id){let sourceComponent=db.source_component.get(elm.source_component_id);if(sourceComponent?.source_group_id&&(sourceComponent.source_group_id===componentId||isDescendantGroup(db,sourceComponent.source_group_id,componentId)))return!0}if("pcb_component_id"in elm&&elm.pcb_component_id){let pcbComp=db.pcb_component.get(elm.pcb_component_id);if(pcbComp?.source_component_id){let sourceComp=db.source_component.get(pcbComp.source_component_id);if(sourceComp?.source_group_id&&(sourceComp.source_group_id===componentId||isDescendantGroup(db,sourceComp.source_group_id,componentId)))return!0}}return!1});for(let elm of relatedElements)elm.type==="pcb_component"&&db.pcb_component.update(elm.pcb_component_id,{position_mode:"packed"});transformPCBElements(relatedElements,transformMatrix),db.pcb_group.update(pcbGroup.pcb_group_id,{center:center2})}},DEFAULT_MIN_GAP="1mm",debug6=(0,import_debug13.default)("Group_doInitialPcbLayoutPack"),Group_doInitialPcbLayoutPack=group=>{let{db}=group.root,{_parsedProps:props}=group;group.root?.emit("packing:start",{subcircuit_id:group.subcircuit_id,componentDisplayName:group.getString()});let{packOrderStrategy,packPlacementStrategy,gap:gapProp,pcbGap,pcbPackGap}=props,gap=pcbPackGap??pcbGap??gapProp,gapMm=length.parse(gap??DEFAULT_MIN_GAP),chipMarginsMap={},staticPcbComponentIds=new Set,collectMargins=comp=>{if(comp?.pcb_component_id&&comp?._parsedProps){let props2=comp._parsedProps,left=length.parse(props2.pcbMarginLeft??props2.pcbMarginX??0),right=length.parse(props2.pcbMarginRight??props2.pcbMarginX??0),top=length.parse(props2.pcbMarginTop??props2.pcbMarginY??0),bottom=length.parse(props2.pcbMarginBottom??props2.pcbMarginY??0);(left||right||top||bottom)&&(chipMarginsMap[comp.pcb_component_id]={left,right,top,bottom})}comp?.children&&comp.children.forEach(collectMargins)};collectMargins(group);let excludedPcbGroupIds=new Set;for(let child of group.children){let childIsGroupOrNormalComponent=child;childIsGroupOrNormalComponent._isNormalComponent&&childIsGroupOrNormalComponent.isRelativelyPositioned?.()&&(childIsGroupOrNormalComponent.pcb_component_id&&staticPcbComponentIds.add(childIsGroupOrNormalComponent.pcb_component_id),childIsGroupOrNormalComponent.pcb_group_id&&excludedPcbGroupIds.add(childIsGroupOrNormalComponent.pcb_group_id))}let isDescendantGroup2=(db2,groupId,ancestorId)=>{if(groupId===ancestorId)return!0;let group2=db2.source_group.get(groupId);return!group2||!group2.parent_source_group_id?!1:isDescendantGroup2(db2,group2.parent_source_group_id,ancestorId)};if(excludedPcbGroupIds.size>0)for(let element of db.toArray()){if(element.type!=="pcb_component")continue;let sourceComponent=db.source_component.get(element.source_component_id);if(sourceComponent?.source_group_id)for(let groupId of excludedPcbGroupIds)isDescendantGroup2(db,sourceComponent.source_group_id,groupId)&&staticPcbComponentIds.add(element.pcb_component_id)}let filteredCircuitJson=db.toArray(),bounds;if(props.width!==void 0&&props.height!==void 0){let widthMm=length.parse(props.width),heightMm=length.parse(props.height);bounds={minX:-widthMm/2,maxX:widthMm/2,minY:-heightMm/2,maxY:heightMm/2}}let packInput={...convertPackOutputToPackInput(convertCircuitJsonToPackOutput(filteredCircuitJson,{source_group_id:group.source_group_id,chipMarginsMap,staticPcbComponentIds:Array.from(staticPcbComponentIds)})),orderStrategy:packOrderStrategy??"largest_to_smallest",placementStrategy:packPlacementStrategy??"minimum_sum_squared_distance_to_network",minGap:gapMm,bounds},clusterMap=applyComponentConstraintClusters(group,packInput);debug6.enabled&&(group.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-circuitjson-${group.name}`,content:JSON.stringify(db.toArray())}),group.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-${group.name}`,content:packInput}));let packOutput;try{let solver=new PackSolver2(packInput);group.root?.emit("solver:started",{type:"solver:started",solverName:"PackSolver2",solverParams:solver.getConstructorParams(),componentName:group.getString()}),solver.solve(),packOutput={...packInput,components:solver.packedComponents}}catch(error){throw group.root?.emit("packing:error",{subcircuit_id:group.subcircuit_id,componentDisplayName:group.getString(),error:{message:error instanceof Error?error.message:String(error)}}),error}if(debug6.enabled&&global?.debugGraphics){let graphics=getGraphicsFromPackOutput(packOutput);graphics.title=`packOutput-${group.name}`,global.debugGraphics?.push(graphics)}applyPackOutput(group,packOutput,clusterMap),group.root?.emit("packing:end",{subcircuit_id:group.subcircuit_id,componentDisplayName:group.getString()})},Group_doInitialPcbLayoutFlex=group=>{let{db}=group.root,{_parsedProps:props}=group,pcbChildren=group.children.filter(c3=>c3.pcb_component_id||c3.pcb_group_id);if(pcbChildren.some(child=>{let childProps=child._parsedProps;return childProps?.pcbX!==void 0||childProps?.pcbY!==void 0}))return;let rawJustify=props.pcbJustifyContent??props.justifyContent,rawAlign=props.pcbAlignItems??props.alignItems,rawGap=props.pcbFlexGap??props.pcbGap??props.gap,direction2=props.pcbFlexDirection??"row",justifyContent={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"space-between","space-between":"space-between","space-around":"space-around","space-evenly":"space-evenly",center:"center"}[rawJustify??"space-between"],alignItems={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[rawAlign??"center"];if(!justifyContent)throw new Error(`Invalid justifyContent value: "${rawJustify}"`);if(!alignItems)throw new Error(`Invalid alignItems value: "${rawAlign}"`);let rowGap=0,columnGap=0;typeof rawGap=="object"?(rowGap=rawGap.y??0,columnGap=rawGap.x??0):typeof rawGap=="number"?(rowGap=rawGap,columnGap=rawGap):typeof rawGap=="string"&&(rowGap=length.parse(rawGap),columnGap=length.parse(rawGap));let minFlexContainer,width=props.width??props.pcbWidth??void 0,height=props.height??props.pcbHeight??void 0;(width===void 0||height===void 0)&&(minFlexContainer=getMinimumFlexContainer(pcbChildren.map(child=>child._getMinimumFlexContainerSize()).filter(size2=>size2!==null),{alignItems,justifyContent,direction:direction2,rowGap,columnGap}),width=minFlexContainer.width,height=minFlexContainer.height);let flexBox=new RootFlexBox(width,height,{alignItems,justifyContent,direction:direction2,rowGap,columnGap});for(let child of pcbChildren){let size2=child._getMinimumFlexContainerSize();flexBox.addChild({metadata:child,width:size2?.width??0,height:size2?.height??0,flexBasis:size2?direction2==="row"?size2.width:size2.height:void 0})}flexBox.build();let bounds={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let child of flexBox.children)bounds.minX=Math.min(bounds.minX,child.position.x),bounds.minY=Math.min(bounds.minY,child.position.y),bounds.maxX=Math.max(bounds.maxX,child.position.x+child.size.width),bounds.maxY=Math.max(bounds.maxY,child.position.y+child.size.height);bounds.width=bounds.maxX-bounds.minX,bounds.height=bounds.maxY-bounds.minY;let groupCenter=group._getGlobalPcbPositionBeforeLayout(),offset={x:groupCenter.x-(bounds.maxX+bounds.minX)/2,y:groupCenter.y-(bounds.maxY+bounds.minY)/2};for(let child of flexBox.children)child.metadata._repositionOnPcb({x:child.position.x+child.size.width/2+offset.x,y:child.position.y+child.size.height/2+offset.y});db.pcb_group.update(group.pcb_group_id,{width:bounds.width,height:bounds.height,center:groupCenter})};function createSchematicTraceSolverInputProblem(group){let{db}=group.root,sckToSourceNet=new Map,sckToUserNetId=new Map,allScks=new Set,displayLabelTraces=group.selectAll("trace").filter(t6=>t6._parsedProps?.schDisplayLabel),childGroups=group.selectAll("group"),allSchematicGroupIds=[group.schematic_group_id,...childGroups.map(a3=>a3.schematic_group_id)],schematicComponents=db.schematic_component.list().filter(a3=>allSchematicGroupIds.includes(a3.schematic_group_id)),chips=[],pinIdToSchematicPortId=new Map,schematicPortIdToPinId=new Map;for(let schematicComponent of schematicComponents){let chipId=schematicComponent.schematic_component_id,pins=[],sourceComponent=db.source_component.getWhere({source_component_id:schematicComponent.source_component_id}),schematicPorts=db.schematic_port.list({schematic_component_id:schematicComponent.schematic_component_id});for(let schematicPort of schematicPorts){let pinId=`${sourceComponent?.name??schematicComponent.schematic_component_id}.${schematicPort.pin_number}`;pinIdToSchematicPortId.set(pinId,schematicPort.schematic_port_id),schematicPortIdToPinId.set(schematicPort.schematic_port_id,pinId)}for(let schematicPort of schematicPorts){let pinId=schematicPortIdToPinId.get(schematicPort.schematic_port_id);pins.push({pinId,x:schematicPort.center.x,y:schematicPort.center.y})}chips.push({chipId,center:schematicComponent.center,width:schematicComponent.size.width,height:schematicComponent.size.height,pins})}let allSourceAndSchematicPortIdsInScope=new Set,schPortIdToSourcePortId=new Map,sourcePortIdToSchPortId=new Map,userNetIdToSck=new Map;for(let sc2 of schematicComponents){let ports=db.schematic_port.list({schematic_component_id:sc2.schematic_component_id});for(let sp2 of ports)allSourceAndSchematicPortIdsInScope.add(sp2.schematic_port_id),sp2.source_port_id&&(schPortIdToSourcePortId.set(sp2.schematic_port_id,sp2.source_port_id),sourcePortIdToSchPortId.set(sp2.source_port_id,sp2.schematic_port_id))}let allowedSubcircuitIds=new Set;group.subcircuit_id&&allowedSubcircuitIds.add(group.subcircuit_id);for(let cg of childGroups)cg.subcircuit_id&&allowedSubcircuitIds.add(cg.subcircuit_id);let externalNetIds=db.source_trace.list().filter(st3=>{if(st3.subcircuit_id===group.subcircuit_id)return!0;for(let source_port_id of st3.connected_source_port_ids)if(sourcePortIdToSchPortId.has(source_port_id))return!0;return!1}).flatMap(st3=>st3.connected_source_net_ids);for(let netId of externalNetIds){let net=db.source_net.get(netId);net?.subcircuit_id&&allowedSubcircuitIds.add(net.subcircuit_id)}let directConnections=[],pairKeyToSourceTraceId=new Map;for(let st3 of db.source_trace.list()){if(st3.subcircuit_id&&!allowedSubcircuitIds.has(st3.subcircuit_id))continue;let connected=(st3.connected_source_port_ids??[]).map(srcId=>sourcePortIdToSchPortId.get(srcId)).filter(sourcePortId=>!!sourcePortId&&allSourceAndSchematicPortIdsInScope.has(sourcePortId));if(connected.length>=2){let[a3,b3]=connected.slice(0,2),pairKey=[a3,b3].sort().join("::");if(!pairKeyToSourceTraceId.has(pairKey)){pairKeyToSourceTraceId.set(pairKey,st3.source_trace_id);let userNetId=st3.display_name??st3.source_trace_id;st3.subcircuit_connectivity_map_key&&(allScks.add(st3.subcircuit_connectivity_map_key),userNetIdToSck.set(userNetId,st3.subcircuit_connectivity_map_key),sckToUserNetId.set(st3.subcircuit_connectivity_map_key,userNetId)),directConnections.push({pinIds:[a3,b3].map(id=>schematicPortIdToPinId.get(id)),netId:userNetId})}}}let netConnections=[];for(let net of db.source_net.list().filter(n3=>!n3.subcircuit_id||allowedSubcircuitIds.has(n3.subcircuit_id)))net.subcircuit_connectivity_map_key&&(allScks.add(net.subcircuit_connectivity_map_key),sckToSourceNet.set(net.subcircuit_connectivity_map_key,net));let sckToPinIds=new Map;for(let[schId,srcPortId]of schPortIdToSourcePortId){let sp2=db.source_port.get(srcPortId);if(!sp2?.subcircuit_connectivity_map_key)continue;let sck=sp2.subcircuit_connectivity_map_key;allScks.add(sck),sckToPinIds.has(sck)||sckToPinIds.set(sck,[]),sckToPinIds.get(sck).push(schId)}for(let[subcircuitConnectivityKey,schematicPortIds]of sckToPinIds){let sourceNet=sckToSourceNet.get(subcircuitConnectivityKey);if(sourceNet&&schematicPortIds.length>=2){let userNetId=String(sourceNet.name||sourceNet.source_net_id||subcircuitConnectivityKey);userNetIdToSck.set(userNetId,subcircuitConnectivityKey),sckToUserNetId.set(subcircuitConnectivityKey,userNetId);let charWidth=.1*(.18/.18),netLabelWidth=Number((String(userNetId).length*charWidth).toFixed(2));netConnections.push({netId:userNetId,pinIds:schematicPortIds.map(portId=>schematicPortIdToPinId.get(portId)),netLabelWidth})}}let availableNetLabelOrientations=(()=>{let netToAllowedOrientations={},presentNetIds=new Set(netConnections.map(nc2=>nc2.netId));for(let net of db.source_net.list().filter(n3=>!n3.subcircuit_id||allowedSubcircuitIds.has(n3.subcircuit_id)))net.name&&presentNetIds.has(net.name)&&(net.is_ground||net.name.toLowerCase().startsWith("gnd")?netToAllowedOrientations[net.name]=["y-"]:net.is_power||net.name.toLowerCase().startsWith("v")?netToAllowedOrientations[net.name]=["y+"]:netToAllowedOrientations[net.name]=["x-","x+"]);return netToAllowedOrientations})();return{inputProblem:{chips,directConnections,netConnections,availableNetLabelOrientations,maxMspPairDistance:group._parsedProps.schMaxTraceDistance??2.4},pinIdToSchematicPortId,pairKeyToSourceTraceId,sckToSourceNet,sckToUserNetId,userNetIdToSck,allSourceAndSchematicPortIdsInScope,schPortIdToSourcePortId,displayLabelTraces,allScks}}var TOL=1e-6;function isHorizontalEdge(edge){let dx2=Math.abs(edge.to.x-edge.from.x),dy2=Math.abs(edge.to.y-edge.from.y);return dx2>=dy2}function length6(a3,b3){return Math.hypot(b3.x-a3.x,b3.y-a3.y)}function pointAt(a3,b3,t6){return{x:a3.x+(b3.x-a3.x)*t6,y:a3.y+(b3.y-a3.y)*t6}}function paramAlong(a3,b3,p4){let L5=length6(a3,b3);if(L5<TOL)return 0;let t6=((p4.x-a3.x)*(b3.x-a3.x)+(p4.y-a3.y)*(b3.y-a3.y))/((b3.x-a3.x)*(b3.x-a3.x)+(b3.y-a3.y)*(b3.y-a3.y));return Math.max(0,Math.min(1,t6))*L5}function cross2(ax2,ay2,bx2,by2){return ax2*by2-ay2*bx2}function segmentIntersection(p12,p22,q12,q22){let r4={x:p22.x-p12.x,y:p22.y-p12.y},s4={x:q22.x-q12.x,y:q22.y-q12.y},rxs=cross2(r4.x,r4.y,s4.x,s4.y),q_p={x:q12.x-p12.x,y:q12.y-p12.y},q_pxr=cross2(q_p.x,q_p.y,r4.x,r4.y);if(Math.abs(rxs)<TOL&&Math.abs(q_pxr)<TOL||Math.abs(rxs)<TOL&&Math.abs(q_pxr)>=TOL)return null;let t6=cross2(q_p.x,q_p.y,s4.x,s4.y)/rxs,u4=cross2(q_p.x,q_p.y,r4.x,r4.y)/rxs;return t6<-TOL||t6>1+TOL||u4<-TOL||u4>1+TOL?null:{x:p12.x+t6*r4.x,y:p12.y+t6*r4.y}}function mergeIntervals(intervals,tol=TOL){if(intervals.length===0)return intervals;intervals.sort((a3,b3)=>a3.start-b3.start);let merged=[],cur={...intervals[0]};for(let i3=1;i3<intervals.length;i3++){let nxt=intervals[i3];nxt.start<=cur.end+tol?cur.end=Math.max(cur.end,nxt.end):(merged.push(cur),cur={...nxt})}return merged.push(cur),merged}function splitEdgeByCrossings(edge,crossingDistances,crossLen){let L5=length6(edge.from,edge.to);if(L5<TOL||crossingDistances.length===0)return[edge];let half=crossLen/2,rawIntervals=crossingDistances.map(d2=>({start:Math.max(0,d2-half),end:Math.min(L5,d2+half)})).filter(iv=>iv.end-iv.start>TOL),intervals=mergeIntervals(rawIntervals),result=[],cursor=0,dir={x:edge.to.x-edge.from.x,y:edge.to.y-edge.from.y},addSeg=(d02,d12,isCrossing)=>{if(d12-d02<=TOL)return;let t02=d02/L5,t12=d12/L5;result.push({from:pointAt(edge.from,edge.to,t02),to:pointAt(edge.from,edge.to,t12),...isCrossing?{is_crossing:!0}:{}})};for(let iv of intervals)iv.start-cursor>TOL&&addSeg(cursor,iv.start,!1),addSeg(iv.start,iv.end,!0),cursor=iv.end;return L5-cursor>TOL&&addSeg(cursor,L5,!1),result.length>0?result:[edge]}function computeCrossings(traces,opts={}){let crossLen=opts.crossSegmentLength??.075,tol=opts.tolerance??TOL,crossingsByEdge=new Map,keyOf=ref=>`${ref.traceIdx}:${ref.edgeIdx}`,getEdge=ref=>traces[ref.traceIdx].edges[ref.edgeIdx];for(let ti3=0;ti3<traces.length;ti3++){let A4=traces[ti3];for(let ei3=0;ei3<A4.edges.length;ei3++){let eA=A4.edges[ei3];for(let tj=ti3;tj<traces.length;tj++){let B4=traces[tj];for(let ej=tj===ti3?ei3+1:0;ej<B4.edges.length;ej++){let eB=B4.edges[ej],P4=segmentIntersection(eA.from,eA.to,eB.from,eB.to);if(!P4)continue;let LA=length6(eA.from,eA.to),LB=length6(eB.from,eB.to);if(LA<tol||LB<tol)continue;let dA=paramAlong(eA.from,eA.to,P4),dB=paramAlong(eB.from,eB.to,P4),nearEndpointA=dA<=tol||Math.abs(LA-dA)<=tol||Number.isNaN(dA),nearEndpointB=dB<=tol||Math.abs(LB-dB)<=tol||Number.isNaN(dB);if(!nearEndpointA&&!nearEndpointB){let aIsHorizontal=isHorizontalEdge(eA),bIsHorizontal=isHorizontalEdge(eB),assignToA;if(aIsHorizontal!==bIsHorizontal)assignToA=aIsHorizontal;else{let ax2=Math.abs(eA.to.x-eA.from.x),ay2=Math.abs(eA.to.y-eA.from.y),bx2=Math.abs(eB.to.x-eB.from.x),by2=Math.abs(eB.to.y-eB.from.y),aScore=ax2-ay2,bScore=bx2-by2;assignToA=aScore===bScore?!0:aScore>bScore}let chosenKey=keyOf({traceIdx:assignToA?ti3:tj,edgeIdx:assignToA?ei3:ej}),chosenList=crossingsByEdge.get(chosenKey)??[];chosenList.push(assignToA?dA:dB),crossingsByEdge.set(chosenKey,chosenList)}}}}}let out=traces.map(t6=>({source_trace_id:t6.source_trace_id,edges:[]}));for(let ti3=0;ti3<traces.length;ti3++){let trace=traces[ti3];for(let ei3=0;ei3<trace.edges.length;ei3++){let eRefKey=keyOf({traceIdx:ti3,edgeIdx:ei3}),splittingDistances=crossingsByEdge.get(eRefKey)??[];if(splittingDistances.length===0){out[ti3].edges.push(trace.edges[ei3]);continue}let uniqueSorted=Array.from(new Set(splittingDistances.map(d2=>Number(d2.toFixed(6))))).sort((a3,b3)=>a3-b3),split=splitEdgeByCrossings(trace.edges[ei3],uniqueSorted,crossLen);out[ti3].edges.push(...split)}}return out}var TOL2=1e-6;function nearlyEqual(a3,b3,tol=TOL2){return Math.abs(a3-b3)<=tol}function pointEq(a3,b3,tol=TOL2){return nearlyEqual(a3.x,b3.x,tol)&&nearlyEqual(a3.y,b3.y,tol)}function onSegment4(p4,a3,b3,tol=TOL2){let minX=Math.min(a3.x,b3.x)-tol,maxX=Math.max(a3.x,b3.x)+tol,minY=Math.min(a3.y,b3.y)-tol,maxY=Math.max(a3.y,b3.y)+tol;return p4.x<minX||p4.x>maxX||p4.y<minY||p4.y>maxY?!1:Math.abs((b3.x-a3.x)*(p4.y-a3.y)-(b3.y-a3.y)*(p4.x-a3.x))<=tol}function dedupePoints(points,tol=TOL2){let map=new Map;for(let p4 of points){let key=`${p4.x.toFixed(6)},${p4.y.toFixed(6)}`;map.has(key)||map.set(key,p4)}return Array.from(map.values())}function edgeVec(e4){return{x:e4.to.x-e4.from.x,y:e4.to.y-e4.from.y}}function isParallel(e12,e22,tol=TOL2){let v12=edgeVec(e12),v22=edgeVec(e22),L12=Math.hypot(v12.x,v12.y),L22=Math.hypot(v22.x,v22.y);if(L12<tol||L22<tol)return!0;let cross22=v12.x*v22.y-v12.y*v22.x;return Math.abs(cross22)<=tol*L12*L22}function incidentEdgesAtPoint(trace,p4,tol=TOL2){return trace.edges.filter(e4=>pointEq(e4.from,p4,tol)||pointEq(e4.to,p4,tol))}function nearestEndpointOnTrace(trace,p4,tol=TOL2){for(let e4 of trace.edges){if(pointEq(e4.from,p4,tol))return e4.from;if(pointEq(e4.to,p4,tol))return e4.to}return null}function edgeDirectionFromPoint(e4,p4,tol=TOL2){let other=pointEq(e4.from,p4,tol)||nearlyEqual(e4.from.x,p4.x,tol)&&nearlyEqual(e4.from.y,p4.y,tol)?e4.to:e4.from,dx2=other.x-p4.x,dy2=other.y-p4.y;return Math.abs(dx2)<tol&&Math.abs(dy2)<tol?null:Math.abs(dx2)>=Math.abs(dy2)?dx2>=0?"right":"left":dy2>=0?"up":"down"}function getCornerOrientationAtPoint(trace,p4,tol=TOL2){let incident=incidentEdgesAtPoint(trace,p4,tol);if(incident.length<2)return null;let dirs=incident.map(e4=>edgeDirectionFromPoint(e4,p4,tol)),hasUp=dirs.includes("up"),hasDown=dirs.includes("down"),hasLeft=dirs.includes("left"),hasRight=dirs.includes("right"),vertical=hasUp?"up":hasDown?"down":null,horizontal=hasRight?"right":hasLeft?"left":null;return vertical&&horizontal?`${vertical}-${horizontal}`:null}function computeJunctions(traces,opts={}){let tol=opts.tolerance??TOL2,result={};for(let t6 of traces)result[t6.source_trace_id]=[];let endpointsByTrace=traces.map(t6=>{let pts=[];for(let e4 of t6.edges)pts.push(e4.from,e4.to);return dedupePoints(pts,tol)});for(let i3=0;i3<traces.length;i3++){let A4=traces[i3],AEnds=endpointsByTrace[i3];for(let j3=i3+1;j3<traces.length;j3++){let B4=traces[j3],BEnds=endpointsByTrace[j3];for(let pa2 of AEnds)for(let pb2 of BEnds)if(pointEq(pa2,pb2,tol)){let aEdgesAtP=incidentEdgesAtPoint(A4,pa2,tol),bEdgesAtP=incidentEdgesAtPoint(B4,pb2,tol),hasCorner=aEdgesAtP.some(eA=>bEdgesAtP.some(eB=>!isParallel(eA,eB,tol))),aCorner=getCornerOrientationAtPoint(A4,pa2,tol),bCorner=getCornerOrientationAtPoint(B4,pb2,tol);hasCorner&&!(aCorner!==null&&bCorner!==null&&aCorner===bCorner)&&(result[A4.source_trace_id].push(pa2),A4.source_trace_id!==B4.source_trace_id&&result[B4.source_trace_id].push(pb2))}for(let pa2 of AEnds)for(let eB of B4.edges)if(onSegment4(pa2,eB.from,eB.to,tol)){let hasCorner=incidentEdgesAtPoint(A4,pa2,tol).some(eA=>!isParallel(eA,eB,tol)),aCorner=getCornerOrientationAtPoint(A4,pa2,tol),bEndpointNearPa=nearestEndpointOnTrace(B4,pa2,tol*1e3),bCorner=bEndpointNearPa?getCornerOrientationAtPoint(B4,bEndpointNearPa,tol):null;hasCorner&&!(aCorner!==null&&bCorner!==null&&aCorner===bCorner)&&(result[A4.source_trace_id].push(pa2),A4.source_trace_id!==B4.source_trace_id&&result[B4.source_trace_id].push(pa2))}for(let pb2 of BEnds)for(let eA of A4.edges)if(onSegment4(pb2,eA.from,eA.to,tol)){let hasCorner=incidentEdgesAtPoint(B4,pb2,tol).some(eB=>!isParallel(eA,eB,tol)),bCorner=getCornerOrientationAtPoint(B4,pb2,tol),aEndpointNearPb=nearestEndpointOnTrace(A4,pb2,tol*1e3),aCorner=aEndpointNearPb?getCornerOrientationAtPoint(A4,aEndpointNearPb,tol):null;hasCorner&&!(aCorner!==null&&bCorner!==null&&aCorner===bCorner)&&(result[B4.source_trace_id].push(pb2),A4.source_trace_id!==B4.source_trace_id&&result[A4.source_trace_id].push(pb2))}}}for(let id of Object.keys(result))result[id]=dedupePoints(result[id],tol);return result}var debug7=(0,import_debug15.default)("Group_doInitialSchematicTraceRender");function applyTracesFromSolverOutput(args){let{group,solver,pinIdToSchematicPortId,userNetIdToSck}=args,{db}=group.root,traces=solver.traceCleanupSolver?.getOutput().traces??solver.traceLabelOverlapAvoidanceSolver?.getOutput().traces??solver.schematicTraceLinesSolver?.solvedTracePaths,pendingTraces=[];debug7(`Traces inside SchematicTraceSolver output: ${(traces??[]).length}`);for(let solvedTracePath of traces??[]){let points=solvedTracePath?.tracePath;if(!Array.isArray(points)||points.length<2){debug7(`Skipping trace ${solvedTracePath?.pinIds.join(",")} because it has less than 2 points`);continue}let edges=[];for(let i3=0;i3<points.length-1;i3++)edges.push({from:{x:points[i3].x,y:points[i3].y},to:{x:points[i3+1].x,y:points[i3+1].y}});let source_trace_id=null,subcircuit_connectivity_map_key;if(Array.isArray(solvedTracePath?.pins)&&solvedTracePath.pins.length===2){let pA=pinIdToSchematicPortId.get(solvedTracePath.pins[0]?.pinId),pB=pinIdToSchematicPortId.get(solvedTracePath.pins[1]?.pinId);if(pA&&pB){for(let schPid of[pA,pB])db.schematic_port.get(schPid)&&db.schematic_port.update(schPid,{is_connected:!0});subcircuit_connectivity_map_key=userNetIdToSck.get(String(solvedTracePath.userNetId))}}source_trace_id||(source_trace_id=`solver_${solvedTracePath?.mspPairId}`,subcircuit_connectivity_map_key=userNetIdToSck.get(String(solvedTracePath.userNetId))),pendingTraces.push({source_trace_id,edges,subcircuit_connectivity_map_key})}debug7(`Applying ${pendingTraces.length} traces from SchematicTraceSolver output`);let withCrossings=computeCrossings(pendingTraces.map(t6=>({source_trace_id:t6.source_trace_id,edges:t6.edges}))),junctionsById=computeJunctions(withCrossings);for(let t6 of withCrossings)db.schematic_trace.insert({source_trace_id:t6.source_trace_id,edges:t6.edges,junctions:junctionsById[t6.source_trace_id]??[],subcircuit_connectivity_map_key:pendingTraces.find(p4=>p4.source_trace_id===t6.source_trace_id)?.subcircuit_connectivity_map_key})}var oppositeSide2=input2=>{switch(input2){case"x+":return"left";case"x-":return"right";case"y+":return"bottom";case"y-":return"top";case"left":return"right";case"top":return"bottom";case"right":return"left";case"bottom":return"top"}},getNetNameFromPorts=ports=>{for(let port of ports){let traces=port._getDirectlyConnectedTraces();for(let trace of traces){let displayLabel=trace._parsedProps.schDisplayLabel;if(displayLabel)return{name:displayLabel,wasAssignedDisplayLabel:!0}}}return{name:ports.map(p4=>p4._getNetLabelText()).join("/"),wasAssignedDisplayLabel:!1}},debug8=(0,import_debug16.default)("Group_doInitialSchematicTraceRender");function applyNetLabelPlacements(args){let{group,solver,sckToSourceNet,allScks,allSourceAndSchematicPortIdsInScope,schPortIdToSourcePortId,userNetIdToSck,pinIdToSchematicPortId,schematicPortIdsWithPreExistingNetLabels,schematicPortIdsWithRoutedTraces}=args,{db}=group.root,netLabelPlacements=solver.netLabelPlacementSolver?.netLabelPlacements??solver.traceLabelOverlapAvoidanceSolver?.getOutput().netLabelPlacements??[],globalConnMap=solver.mspConnectionPairSolver.globalConnMap;for(let placement of netLabelPlacements){debug8(`processing placement: ${placement.netId}`);let placementUserNetId=globalConnMap.getIdsConnectedToNet(placement.globalConnNetId).find(id=>userNetIdToSck.get(id)),placementSck=userNetIdToSck.get(placementUserNetId),anchor_position=placement.anchorPoint,orientation4=placement.orientation,anchor_side=oppositeSide2(orientation4),sourceNet=placementSck?sckToSourceNet.get(placementSck):void 0,schPortIds=placement.pinIds.map(pinId=>pinIdToSchematicPortId.get(pinId));if(schPortIds.some(schPortId=>schematicPortIdsWithPreExistingNetLabels.has(schPortId))){debug8(`skipping net label placement for "${placement.netId}" REASON:schematic port has pre-existing net label`);continue}if(sourceNet){let text2=sourceNet.name,center22=computeSchematicNetLabelCenter({anchor_position,anchor_side,text:text2});db.schematic_net_label.insert({text:text2,anchor_position,center:center22,anchor_side,...sourceNet?.source_net_id?{source_net_id:sourceNet.source_net_id}:{}});continue}let ports=group.selectAll("port").filter(p4=>p4._getSubcircuitConnectivityKey()===placementSck),{name:text,wasAssignedDisplayLabel}=getNetNameFromPorts(ports);if(!wasAssignedDisplayLabel&&schPortIds.some(schPortId=>schematicPortIdsWithRoutedTraces.has(schPortId))){debug8(`skipping net label placement for "${placement.netId}" REASON:schematic port has routed traces and no display label`);continue}let center2=computeSchematicNetLabelCenter({anchor_position,anchor_side,text});db.schematic_net_label.insert({text,anchor_position,center:center2,anchor_side})}}var insertNetLabelsForPortsMissingTrace=({allSourceAndSchematicPortIdsInScope,group,schPortIdToSourcePortId,sckToSourceNet:connKeyToNet,pinIdToSchematicPortId,schematicPortIdsWithPreExistingNetLabels})=>{let{db}=group.root;for(let schOrSrcPortId of Array.from(allSourceAndSchematicPortIdsInScope)){let schPort=db.schematic_port.get(schOrSrcPortId);if(!schPort||schPort.is_connected)continue;let srcPortId=schPortIdToSourcePortId.get(schOrSrcPortId);if(!srcPortId)continue;let key=db.source_port.get(srcPortId)?.subcircuit_connectivity_map_key;if(!key)continue;let sourceNet=connKeyToNet.get(key);if(!sourceNet||db.schematic_net_label.list().some(nl2=>Math.abs(nl2.anchor_position.x-schPort.center.x)<.1&&Math.abs(nl2.anchor_position.y-schPort.center.y)<.1?sourceNet.source_net_id&&nl2.source_net_id?nl2.source_net_id===sourceNet.source_net_id:nl2.text===(sourceNet.name||key):!1))continue;let text=sourceNet.name||sourceNet.source_net_id||key,side=getEnteringEdgeFromDirection(schPort.facing_direction||"right")||"right",center2=computeSchematicNetLabelCenter({anchor_position:schPort.center,anchor_side:side,text});db.schematic_net_label.insert({text,anchor_position:schPort.center,center:center2,anchor_side:side,...sourceNet.source_net_id?{source_net_id:sourceNet.source_net_id}:{}})}},getSchematicPortIdsWithAssignedNetLabels=group=>{let schematicPortIdsWithNetLabels=new Set,netLabels=group.selectAll("netlabel");for(let netLabel of netLabels){let netLabelPorts=netLabel._getConnectedPorts();for(let port of netLabelPorts)port.schematic_port_id&&schematicPortIdsWithNetLabels.add(port.schematic_port_id)}return schematicPortIdsWithNetLabels},getSchematicPortIdsWithRoutedTraces=({solver,pinIdToSchematicPortId})=>{let solvedTraces=solver.schematicTraceLinesSolver.solvedTracePaths,schematicPortIdsWithRoutedTraces=new Set;for(let solvedTrace of solvedTraces)for(let pinId of solvedTrace.pinIds){let schPortId=pinIdToSchematicPortId.get(pinId);schPortId&&schematicPortIdsWithRoutedTraces.add(schPortId)}return schematicPortIdsWithRoutedTraces},debug9=(0,import_debug14.default)("Group_doInitialSchematicTraceRender"),Group_doInitialSchematicTraceRender=group=>{if(!group.root?._featureMspSchematicTraceRouting||!group.isSubcircuit||group.root?.schematicDisabled)return;let{inputProblem,pinIdToSchematicPortId,pairKeyToSourceTraceId,sckToSourceNet,allSourceAndSchematicPortIdsInScope,schPortIdToSourcePortId,displayLabelTraces,allScks,userNetIdToSck}=createSchematicTraceSolverInputProblem(group),schematicPortIdsWithPreExistingNetLabels=getSchematicPortIdsWithAssignedNetLabels(group);debug9.enabled&&group.root?.emit("debug:logOutput",{type:"debug:logOutput",name:"group-trace-render-input-problem",content:JSON.stringify(inputProblem,null,2)});let solver=new SchematicTracePipelineSolver(inputProblem);solver.solve();let schematicPortIdsWithRoutedTraces=getSchematicPortIdsWithRoutedTraces({solver,pinIdToSchematicPortId});applyTracesFromSolverOutput({group,solver,pinIdToSchematicPortId,userNetIdToSck}),applyNetLabelPlacements({group,solver,sckToSourceNet,allSourceAndSchematicPortIdsInScope,schPortIdToSourcePortId,pinIdToSchematicPortId,allScks,userNetIdToSck,schematicPortIdsWithPreExistingNetLabels,schematicPortIdsWithRoutedTraces}),insertNetLabelsForPortsMissingTrace({group,allSourceAndSchematicPortIdsInScope,schPortIdToSourcePortId,sckToSourceNet,pinIdToSchematicPortId,schematicPortIdsWithPreExistingNetLabels})},getSpiceyEngine=()=>({async simulate(spiceString){let simulation_experiment_id="spice-experiment-1",{circuit:parsedCircuit,tran}=simulate(spiceString);return{simulationResultCircuitJson:spiceyTranToVGraphs(tran,parsedCircuit,simulation_experiment_id)}}}),SIMULATION_COLOR_PALETTE=["rgb(132, 0, 0)","rgb(194, 194, 0)","rgb(194, 0, 194)","rgb(194, 0, 0)","rgb(0, 132, 132)","rgb(0, 132, 0)","rgb(0, 0, 132)","rgb(132, 132, 132)","rgb(132, 0, 132)","rgb(194, 194, 194)","rgb(132, 0, 132)","rgb(132, 0, 0)","rgb(132, 132, 0)","rgb(194, 194, 194)","rgb(0, 0, 132)","rgb(0, 132, 0)"],idToColorMap=new Map,colorIndex=0;function getSimulationColorForId(id){if(idToColorMap.has(id))return idToColorMap.get(id);let color=SIMULATION_COLOR_PALETTE[colorIndex];return colorIndex=(colorIndex+1)%SIMULATION_COLOR_PALETTE.length,idToColorMap.set(id,color),color}function resetSimulationColorState(){idToColorMap.clear(),colorIndex=0}var debug10=(0,import_debug17.default)("tscircuit:core:Group_doInitialSimulationSpiceEngineRender");function Group_doInitialSimulationSpiceEngineRender(group){if(!group.isSubcircuit)return;let{root}=group;if(!root)return;let analogSims=group.selectAll("analogsimulation");if(analogSims.length===0)return;let voltageProbes=group.selectAll("voltageprobe");resetSimulationColorState();let spiceEngineMap={...root.platform?.spiceEngineMap};spiceEngineMap.spicey||(spiceEngineMap.spicey=getSpiceyEngine());let circuitJson=root.db.toArray(),spiceString,spiceNetlist;try{spiceNetlist=circuitJsonToSpice(circuitJson),spiceString=spiceNetlist.toSpiceString(),debug10(`Generated SPICE string:
600
- ${spiceString}`)}catch(error){debug10(`Failed to convert circuit JSON to SPICE: ${error}`);return}for(let analogSim of analogSims){let engineName=analogSim._parsedProps.spiceEngine??"spicey",spiceEngine2=spiceEngineMap[engineName];if(!spiceEngine2)throw new Error(`SPICE engine "${engineName}" not found in platform config. Available engines: ${JSON.stringify(Object.keys(spiceEngineMap).filter(k4=>k4!=="spicey"))}`);let effectId=`spice-simulation-${engineName}-${analogSim.source_component_id}`;debug10(`Queueing simulation for spice engine: ${engineName} (id: ${effectId})`),group._queueAsyncEffect(effectId,async()=>{try{debug10(`Running simulation with engine: ${engineName}`);let result=await spiceEngine2.simulate(spiceString);debug10(`Simulation completed, received ${result.simulationResultCircuitJson.length} elements`);let simulationExperiment=root.db.simulation_experiment.list()[0];if(!simulationExperiment){debug10("No simulation experiment found, skipping result insertion");return}for(let element of result.simulationResultCircuitJson){if(element.type==="simulation_transient_voltage_graph"){element.simulation_experiment_id=simulationExperiment.simulation_experiment_id;let probeMatch=voltageProbes.find(p4=>p4.finalProbeName===element.name);probeMatch&&(element.color=probeMatch.color)}let elementType=element.type;elementType&&root.db[elementType]?(root.db[elementType].insert(element),debug10(`Inserted ${elementType} into database`)):(debug10(`Warning: Unknown element type ${elementType}, adding to raw db`),root.db._addElement(element))}group._markDirty("SimulationSpiceEngineRender")}catch(error){debug10(`Simulation failed for engine ${engineName}: ${error}`);let simulationExperiment=root.db.simulation_experiment.list()[0];root.db.simulation_unknown_experiment_error.insert({simulation_experiment_id:simulationExperiment?.simulation_experiment_id,error_type:"simulation_unknown_experiment_error",message:error instanceof Error?error.message:String(error)})}})}}function Group_doInitialPcbComponentAnchorAlignment(group){if(group.root?.pcbDisabled||!group.pcb_group_id)return;let pcbPositionAnchor=group._parsedProps?.pcbPositionAnchor;if(!pcbPositionAnchor)return;let targetPosition=group._getGlobalPcbPositionBeforeLayout(),{pcbX,pcbY}=group._parsedProps;if(pcbX===void 0&&pcbY===void 0)return;let{db}=group.root,pcbGroup=db.pcb_group.get(group.pcb_group_id);if(!pcbGroup)return;let width=pcbGroup.width,height=pcbGroup.height,{center:center2}=pcbGroup;if(pcbGroup.outline&&pcbGroup.outline.length>0){let bounds2=getBoundsFromPoints(pcbGroup.outline);bounds2&&(width=bounds2.maxX-bounds2.minX,height=bounds2.maxY-bounds2.minY)}if(!width||!height)return;let bounds={left:center2.x-width/2,right:center2.x+width/2,top:center2.y+height/2,bottom:center2.y-height/2},currentCenter={...center2},anchorPos=null;if(new Set(["center","top_left","top_center","top_right","center_left","center_right","bottom_left","bottom_center","bottom_right"]).has(pcbPositionAnchor))switch(pcbPositionAnchor){case"center":anchorPos=currentCenter;break;case"top_left":anchorPos={x:bounds.left,y:bounds.top};break;case"top_center":anchorPos={x:currentCenter.x,y:bounds.top};break;case"top_right":anchorPos={x:bounds.right,y:bounds.top};break;case"center_left":anchorPos={x:bounds.left,y:currentCenter.y};break;case"center_right":anchorPos={x:bounds.right,y:currentCenter.y};break;case"bottom_left":anchorPos={x:bounds.left,y:bounds.bottom};break;case"bottom_center":anchorPos={x:currentCenter.x,y:bounds.bottom};break;case"bottom_right":anchorPos={x:bounds.right,y:bounds.bottom};break}if(!anchorPos)return;let newCenter={...currentCenter};targetPosition.x!==void 0&&(newCenter.x+=targetPosition.x-anchorPos.x),targetPosition.y!==void 0&&(newCenter.y+=targetPosition.y-anchorPos.y),(Math.abs(newCenter.x-currentCenter.x)>1e-6||Math.abs(newCenter.y-currentCenter.y)>1e-6)&&(group._repositionOnPcb(newCenter),db.pcb_group.update(group.pcb_group_id,{center:newCenter})),db.pcb_group.update(group.pcb_group_id,{anchor_position:targetPosition,anchor_alignment:pcbPositionAnchor,display_offset_x:pcbX,display_offset_y:pcbY})}function computeCenterFromAnchorPosition(anchorPosition,ctx){let{width,height,pcbAnchorAlignment}=ctx;if(!pcbAnchorAlignment)return anchorPosition;let alignment=pcbAnchorAlignment;if(typeof width!="number"||typeof height!="number")return console.log("width or height is not a number"),anchorPosition;let ax2=anchorPosition.x,ay2=anchorPosition.y;switch(alignment){case"top_left":return{x:ax2+width/2,y:ay2-height/2};case"top_center":return{x:ax2,y:ay2-height/2};case"top_right":return{x:ax2-width/2,y:ay2-height/2};case"center_left":return{x:ax2+width/2,y:ay2};case"center_right":return{x:ax2-width/2,y:ay2};case"bottom_left":return{x:ax2+width/2,y:ay2+height/2};case"bottom_center":return{x:ax2,y:ay2+height/2};case"bottom_right":return{x:ax2-width/2,y:ay2+height/2};default:return anchorPosition}}var Group6=class extends NormalComponent3{constructor(){super(...arguments);__publicField(this,"pcb_group_id",null);__publicField(this,"schematic_group_id",null);__publicField(this,"subcircuit_id",null);__publicField(this,"_hasStartedAsyncAutorouting",!1);__publicField(this,"_asyncAutoroutingResult",null);__publicField(this,"unnamedElementCounter",{})}get config(){return{zodProps:groupProps,componentName:"Group"}}doInitialSourceGroupRender(){let{db}=this.root,hasExplicitName=typeof this._parsedProps.name=="string"&&this._parsedProps.name.length>0,source_group2=db.source_group.insert({name:this.name,is_subcircuit:this.isSubcircuit,was_automatically_named:!hasExplicitName});this.source_group_id=source_group2.source_group_id,this.isSubcircuit&&(this.subcircuit_id=`subcircuit_${source_group2.source_group_id}`,db.source_group.update(source_group2.source_group_id,{subcircuit_id:this.subcircuit_id}))}doInitialSourceRender(){let{db}=this.root;for(let child of this.children)db.source_component.update(child.source_component_id,{source_group_id:this.source_group_id})}doInitialSourceParentAttachment(){let{db}=this.root,parentGroup=this.parent?.getGroup?.();if(parentGroup?.source_group_id&&db.source_group.update(this.source_group_id,{parent_source_group_id:parentGroup.source_group_id}),!this.isSubcircuit)return;let parent_subcircuit_id=this.parent?.getSubcircuit?.()?.subcircuit_id;parent_subcircuit_id&&db.source_group.update(this.source_group_id,{parent_subcircuit_id})}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,groupProps2=props,hasOutline=groupProps2.outline&&groupProps2.outline.length>0,numericOutline=hasOutline?groupProps2.outline.map(point23=>({x:distance.parse(point23.x),y:distance.parse(point23.y)})):void 0,ctx=this.props,anchorPosition=this._getGlobalPcbPositionBeforeLayout(),center2=computeCenterFromAnchorPosition(anchorPosition,ctx),pcb_group2=db.pcb_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id??this.getSubcircuit()?.subcircuit_id,name:this.name,anchor_position:anchorPosition,center:center2,...hasOutline?{outline:numericOutline}:{width:0,height:0},pcb_component_ids:[],source_group_id:this.source_group_id,autorouter_configuration:props.autorouter?{trace_clearance:props.autorouter.traceClearance}:void 0,anchor_alignment:props.pcbAnchorAlignment??null});this.pcb_group_id=pcb_group2.pcb_group_id;for(let child of this.children)db.pcb_component.update(child.pcb_component_id,{pcb_group_id:pcb_group2.pcb_group_id})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,props=this._parsedProps,hasOutline=props.outline&&props.outline.length>0;if(this.pcb_group_id){let hasExplicitPositioning=this._parsedProps.pcbX!==void 0||this._parsedProps.pcbY!==void 0;if(hasOutline){let numericOutline=props.outline.map(point23=>({x:distance.parse(point23.x),y:distance.parse(point23.y)})),outlineBounds=getBoundsFromPoints(numericOutline);if(!outlineBounds)return;let centerX2=(outlineBounds.minX+outlineBounds.maxX)/2,centerY2=(outlineBounds.minY+outlineBounds.maxY)/2,center22=hasExplicitPositioning?db.pcb_group.get(this.pcb_group_id)?.center??{x:centerX2,y:centerY2}:{x:centerX2,y:centerY2};db.pcb_group.update(this.pcb_group_id,{center:center22});return}let bounds=getBoundsOfPcbComponents(this.children),width=bounds.width,height=bounds.height,centerX=(bounds.minX+bounds.maxX)/2,centerY=(bounds.minY+bounds.maxY)/2;if(this.isSubcircuit){let{padLeft,padRight,padTop,padBottom}=this._resolvePcbPadding();width+=padLeft+padRight,height+=padTop+padBottom,centerX+=(padRight-padLeft)/2,centerY+=(padTop-padBottom)/2}let center2=hasExplicitPositioning?db.pcb_group.get(this.pcb_group_id)?.center??{x:centerX,y:centerY}:{x:centerX,y:centerY};db.pcb_group.update(this.pcb_group_id,{width:Number(props.width??width),height:Number(props.height??height),center:center2})}}getNextAvailableName(elm){var _a359,_b2;return(_a359=this.unnamedElementCounter)[_b2=elm.lowercaseComponentName]??(_a359[_b2]=1),`unnamed_${elm.lowercaseComponentName}${this.unnamedElementCounter[elm.lowercaseComponentName]++}`}_resolvePcbPadding(){let props=this._parsedProps,layout=props.pcbLayout,getPaddingValue=key=>{let layoutValue=layout?.[key],propsValue=props[key];if(typeof layoutValue=="number")return layoutValue;if(typeof propsValue=="number")return propsValue},generalPadding=getPaddingValue("padding")??0,paddingX=getPaddingValue("paddingX"),paddingY=getPaddingValue("paddingY"),padLeft=getPaddingValue("paddingLeft")??paddingX??generalPadding,padRight=getPaddingValue("paddingRight")??paddingX??generalPadding,padTop=getPaddingValue("paddingTop")??paddingY??generalPadding,padBottom=getPaddingValue("paddingBottom")??paddingY??generalPadding;return{padLeft,padRight,padTop,padBottom}}doInitialCreateTraceHintsFromProps(){let{_parsedProps:props}=this,{db}=this.root,groupProps2=props;if(!this.isSubcircuit)return;let manualTraceHints=groupProps2.manualEdits?.manual_trace_hints;if(manualTraceHints)for(let manualTraceHint of manualTraceHints)this.add(new TraceHint({for:manualTraceHint.pcb_port_selector,offsets:manualTraceHint.offsets}))}doInitialSourceAddConnectivityMapKey(){Group_doInitialSourceAddConnectivityMapKey(this)}_areChildSubcircuitsRouted(){let subcircuitChildren=this.selectAll("group").filter(g4=>g4.isSubcircuit);for(let subcircuitChild of subcircuitChildren)if(subcircuitChild._shouldRouteAsync()&&!subcircuitChild._asyncAutoroutingResult)return!1;return!0}_shouldRouteAsync(){let autorouter=this._getAutorouterConfig();return autorouter.groupMode==="sequential-trace"?!1:!!(autorouter.local&&autorouter.groupMode==="subcircuit"||!autorouter.local)}_hasTracesToRoute(){let debug112=(0,import_debug10.default)("tscircuit:core:_hasTracesToRoute"),traces=this.selectAll("trace");return debug112(`[${this.getString()}] has ${traces.length} traces to route`),traces.length>0}async _runEffectMakeHttpAutoroutingRequest(){let{db}=this.root,debug112=(0,import_debug10.default)("tscircuit:core:_runEffectMakeHttpAutoroutingRequest"),props=this._parsedProps,autorouterConfig2=this._getAutorouterConfig(),serverUrl=autorouterConfig2.serverUrl,serverMode=autorouterConfig2.serverMode,fetchWithDebug=(url,options)=>(debug112("fetching",url),options.headers&&(options.headers["Tscircuit-Core-Version"]=this.root?.getCoreVersion()),fetch(url,options)),pcbAndSourceCircuitJson=this.root.db.toArray().filter(element=>element.type.startsWith("source_")||element.type.startsWith("pcb_"));if(serverMode==="solve-endpoint"){if(this.props.autorouter?.inputFormat==="simplified"){let{autorouting_result:autorouting_result2}=await fetchWithDebug(`${serverUrl}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_simple_route_json:getSimpleRouteJsonFromCircuitJson({db,minTraceWidth:this.props.autorouter?.minTraceWidth??.15,subcircuit_id:this.subcircuit_id}).simpleRouteJson,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(r4=>r4.json());this._asyncAutoroutingResult=autorouting_result2,this._markDirty("PcbTraceRender");return}let{autorouting_result}=await fetchWithDebug(`${serverUrl}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_circuit_json:pcbAndSourceCircuitJson,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(r4=>r4.json());this._asyncAutoroutingResult=autorouting_result,this._markDirty("PcbTraceRender");return}let{autorouting_job}=await fetchWithDebug(`${serverUrl}/autorouting/jobs/create`,{method:"POST",body:JSON.stringify({input_circuit_json:pcbAndSourceCircuitJson,provider:"freerouting",autostart:!0,display_name:this.root?.name,subcircuit_id:this.subcircuit_id,server_cache_enabled:autorouterConfig2.serverCacheEnabled}),headers:{"Content-Type":"application/json"}}).then(r4=>r4.json());for(;;){let{autorouting_job:job}=await fetchWithDebug(`${serverUrl}/autorouting/jobs/get`,{method:"POST",body:JSON.stringify({autorouting_job_id:autorouting_job.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(r4=>r4.json());if(job.is_finished){let{autorouting_job_output}=await fetchWithDebug(`${serverUrl}/autorouting/jobs/get_output`,{method:"POST",body:JSON.stringify({autorouting_job_id:autorouting_job.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(r4=>r4.json());this._asyncAutoroutingResult={output_pcb_traces:autorouting_job_output.output_pcb_traces},this._markDirty("PcbTraceRender");break}if(job.has_error){let err=new AutorouterError(`Autorouting job failed: ${JSON.stringify(job.error)}`);throw db.pcb_autorouting_error.insert({pcb_error_id:autorouting_job.autorouting_job_id,error_type:"pcb_autorouting_error",message:err.message}),err}await new Promise(resolve=>setTimeout(resolve,100))}}async _runLocalAutorouting(){let{db}=this.root,props=this._parsedProps,debug112=(0,import_debug10.default)("tscircuit:core:_runLocalAutorouting");debug112(`[${this.getString()}] starting local autorouting`);let autorouterConfig2=this._getAutorouterConfig(),isLaserPrefabPreset=this._isLaserPrefabAutorouter(autorouterConfig2),isSingleLayerBoard=this._getSubcircuitLayerCount()===1,{simpleRouteJson}=getSimpleRouteJsonFromCircuitJson({db,minTraceWidth:this.props.autorouter?.minTraceWidth??.15,subcircuit_id:this.subcircuit_id});if(debug112.enabled&&global.debugOutputArray?.push({name:`simpleroutejson-${this.props.name}.json`,obj:simpleRouteJson}),debug112.enabled){let graphicsObject=$e2(simpleRouteJson);graphicsObject.title=`autorouting-${this.props.name}`,global.debugGraphics?.push(graphicsObject)}this.root?.emit("autorouting:start",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),simpleRouteJson});let autorouter;autorouterConfig2.algorithmFn?autorouter=await autorouterConfig2.algorithmFn(simpleRouteJson):autorouter=new CapacityMeshAutorouter(simpleRouteJson,{capacityDepth:this.props.autorouter?.capacityDepth,targetMinCapacity:this.props.autorouter?.targetMinCapacity,useAssignableViaSolver:isLaserPrefabPreset||isSingleLayerBoard,onSolverStarted:({solverName,solverParams})=>this.root?.emit("solver:started",{type:"solver:started",solverName,solverParams,componentName:this.getString()})});let routingPromise=new Promise((resolve,reject)=>{autorouter.on("complete",event=>{debug112(`[${this.getString()}] local autorouting complete`),resolve(event.traces)}),autorouter.on("error",event=>{debug112(`[${this.getString()}] local autorouting error: ${event.error.message}`),reject(event.error)})});autorouter.on("progress",event=>{this.root?.emit("autorouting:progress",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),...event})}),autorouter.start();try{let traces=await routingPromise;this._asyncAutoroutingResult={output_pcb_traces:traces},this._markDirty("PcbTraceRender")}catch(error){let{db:db2}=this.root;throw db2.pcb_autorouting_error.insert({pcb_error_id:`pcb_autorouter_error_subcircuit_${this.subcircuit_id}`,error_type:"pcb_autorouting_error",message:error instanceof Error?error.message:String(error)}),this.root?.emit("autorouting:error",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),error:{message:error instanceof Error?error.message:String(error)},simpleRouteJson}),error}finally{autorouter.stop()}}_startAsyncAutorouting(){this._hasStartedAsyncAutorouting||(this._hasStartedAsyncAutorouting=!0,this._getAutorouterConfig().local?this._queueAsyncEffect("capacity-mesh-autorouting",async()=>this._runLocalAutorouting()):this._queueAsyncEffect("make-http-autorouting-request",async()=>this._runEffectMakeHttpAutoroutingRequest()))}doInitialPcbTraceRender(){let debug112=(0,import_debug10.default)("tscircuit:core:doInitialPcbTraceRender");if(this.isSubcircuit&&!this.root?.pcbDisabled&&!this.getInheritedProperty("routingDisabled")&&!this._shouldUseTraceByTraceRouting()){if(!this._areChildSubcircuitsRouted()){debug112(`[${this.getString()}] child subcircuits are not routed, skipping async autorouting until subcircuits routed`);return}debug112(`[${this.getString()}] no child subcircuits to wait for, initiating async routing`),this._hasTracesToRoute()&&this._startAsyncAutorouting()}}doInitialSchematicTraceRender(){Group_doInitialSchematicTraceRender(this)}updatePcbTraceRender(){let debug112=(0,import_debug10.default)("tscircuit:core:updatePcbTraceRender");if(debug112(`[${this.getString()}] updating...`),!this.isSubcircuit)return;if(this._shouldRouteAsync()&&this._hasTracesToRoute()&&!this._hasStartedAsyncAutorouting){this._areChildSubcircuitsRouted()&&(debug112(`[${this.getString()}] child subcircuits are now routed, starting async autorouting`),this._startAsyncAutorouting());return}if(!this._asyncAutoroutingResult||this._shouldUseTraceByTraceRouting())return;let{db}=this.root;if(this._asyncAutoroutingResult.output_simple_route_json){debug112(`[${this.getString()}] updating PCB traces from simple route json (${this._asyncAutoroutingResult.output_simple_route_json.traces?.length} traces)`),this._updatePcbTraceRenderFromSimpleRouteJson();return}if(this._asyncAutoroutingResult.output_pcb_traces){debug112(`[${this.getString()}] updating PCB traces from ${this._asyncAutoroutingResult.output_pcb_traces.length} traces`),this._updatePcbTraceRenderFromPcbTraces();return}}_updatePcbTraceRenderFromSimpleRouteJson(){let{db}=this.root,{traces:routedTraces}=this._asyncAutoroutingResult.output_simple_route_json;if(routedTraces)for(let routedTrace of routedTraces){let pcb_trace2=db.pcb_trace.insert({subcircuit_id:this.subcircuit_id,route:routedTrace.route})}}_updatePcbTraceRenderFromPcbTraces(){let{output_pcb_traces}=this._asyncAutoroutingResult;if(!output_pcb_traces)return;let{db}=this.root,pcbStyle2=this.getInheritedMergedProperty("pcbStyle"),{holeDiameter,padDiameter}=getViaDiameterDefaults(pcbStyle2);for(let pcb_trace2 of output_pcb_traces)if(pcb_trace2.type==="pcb_trace"){if(pcb_trace2.subcircuit_id=this.subcircuit_id,pcb_trace2.connection_name){let sourceTraceId=pcb_trace2.connection_name;pcb_trace2.source_trace_id=sourceTraceId}db.pcb_trace.insert(pcb_trace2)}for(let pcb_trace2 of output_pcb_traces)if(pcb_trace2.type!=="pcb_via"&&pcb_trace2.type==="pcb_trace")for(let point23 of pcb_trace2.route)point23.route_type==="via"&&db.pcb_via.insert({pcb_trace_id:pcb_trace2.pcb_trace_id,x:point23.x,y:point23.y,hole_diameter:holeDiameter,outer_diameter:padDiameter,layers:[point23.from_layer,point23.to_layer],from_layer:point23.from_layer,to_layer:point23.to_layer})}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;let{db}=this.root,{_parsedProps:props}=this,schematic_group2=db.schematic_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id,name:this.name,center:this._getGlobalSchematicPositionBeforeLayout(),width:0,height:0,schematic_component_ids:[],source_group_id:this.source_group_id});this.schematic_group_id=schematic_group2.schematic_group_id;for(let child of this.children)child.schematic_component_id&&db.schematic_component.update(child.schematic_component_id,{schematic_group_id:schematic_group2.schematic_group_id})}_getSchematicLayoutMode(){let props=this._parsedProps;if(props.schLayout?.layoutMode==="none"||props.schLayout?.layoutMode==="relative")return"relative";if(props.schLayout?.matchAdapt)return"match-adapt";if(props.schLayout?.flex)return"flex";if(props.schLayout?.grid)return"grid";if(props.schMatchAdapt)return"match-adapt";if(props.schFlex)return"flex";if(props.schGrid)return"grid";if(props.matchAdapt)return"match-adapt";if(props.flex)return"flex";if(props.grid)return"grid";if(props.relative||props.schRelative)return"relative";let anyChildHasSchCoords=this.children.some(child=>{let cProps=child._parsedProps;return cProps?.schX!==void 0||cProps?.schY!==void 0}),hasManualEdits=(props.manualEdits?.schematic_placements?.length??0)>0;return!anyChildHasSchCoords&&!hasManualEdits?"match-adapt":"relative"}doInitialSchematicLayout(){let schematicLayoutMode=this._getSchematicLayoutMode();schematicLayoutMode==="match-adapt"&&this._doInitialSchematicLayoutMatchpack(),schematicLayoutMode==="grid"&&this._doInitialSchematicLayoutGrid(),schematicLayoutMode==="flex"&&this._doInitialSchematicLayoutFlex(),this._insertSchematicBorder()}_doInitialSchematicLayoutMatchAdapt(){Group_doInitialSchematicLayoutMatchAdapt(this)}_doInitialSchematicLayoutMatchpack(){Group_doInitialSchematicLayoutMatchPack(this)}_doInitialSchematicLayoutGrid(){Group_doInitialSchematicLayoutGrid(this)}_doInitialSchematicLayoutFlex(){Group_doInitialSchematicLayoutFlex(this)}_getPcbLayoutMode(){let props=this._parsedProps;if(props.pcbRelative)return"none";if(props.pcbLayout?.matchAdapt)return"match-adapt";if(props.pcbLayout?.flex)return"flex";if(props.pcbLayout?.grid)return"grid";if(props.pcbLayout?.pack)return"pack";if(props.pcbFlex)return"flex";if(props.pcbGrid)return"grid";if(props.pcbPack||props.pack)return"pack";if(props.matchAdapt)return"match-adapt";if(props.flex)return"flex";if(props.grid)return"grid";let groupHasCoords=props.pcbX!==void 0||props.pcbY!==void 0,hasManualEdits=(props.manualEdits?.pcb_placements?.length??0)>0,unpositionedDirectChildrenCount=this.children.reduce((count,child)=>{if(!child.pcb_component_id&&!child.pcb_group_id)return count;let childProps=child._parsedProps,hasCoords=childProps?.pcbX!==void 0||childProps?.pcbY!==void 0;return count+(hasCoords?0:1)},0);return!hasManualEdits&&unpositionedDirectChildrenCount>1?"pack":"none"}doInitialPcbLayout(){if(this.root?.pcbDisabled)return;if(this.pcb_group_id){let{db}=this.root,props=this._parsedProps;if(props.pcbX!==void 0||props.pcbY!==void 0){let parentGroup=this.parent?.getGroup?.(),pcbParentGroupId=parentGroup?.pcb_group_id?db.pcb_group.get(parentGroup.pcb_group_id)?.pcb_group_id:void 0,positionedRelativeToBoardId=pcbParentGroupId?void 0:this._getBoard()?.pcb_board_id??void 0;db.pcb_group.update(this.pcb_group_id,{position_mode:"relative_to_group_anchor",positioned_relative_to_pcb_group_id:pcbParentGroupId,positioned_relative_to_pcb_board_id:positionedRelativeToBoardId,display_offset_x:props.pcbX,display_offset_y:props.pcbY})}}let pcbLayoutMode=this._getPcbLayoutMode();pcbLayoutMode==="grid"?this._doInitialPcbLayoutGrid():pcbLayoutMode==="pack"?this._doInitialPcbLayoutPack():pcbLayoutMode==="flex"&&this._doInitialPcbLayoutFlex()}_doInitialPcbLayoutGrid(){Group_doInitialPcbLayoutGrid(this)}_doInitialPcbLayoutPack(){Group_doInitialPcbLayoutPack(this)}_doInitialPcbLayoutFlex(){Group_doInitialPcbLayoutFlex(this)}_insertSchematicBorder(){if(this.root?.schematicDisabled)return;let{db}=this.root,props=this._parsedProps;if(!props.border)return;let width=typeof props.schWidth=="number"?props.schWidth:void 0,height=typeof props.schHeight=="number"?props.schHeight:void 0,paddingGeneral=typeof props.schPadding=="number"?props.schPadding:0,paddingLeft=typeof props.schPaddingLeft=="number"?props.schPaddingLeft:paddingGeneral,paddingRight=typeof props.schPaddingRight=="number"?props.schPaddingRight:paddingGeneral,paddingTop=typeof props.schPaddingTop=="number"?props.schPaddingTop:paddingGeneral,paddingBottom=typeof props.schPaddingBottom=="number"?props.schPaddingBottom:paddingGeneral,schematicGroup=this.schematic_group_id?db.schematic_group.get(this.schematic_group_id):null;if(schematicGroup&&(width===void 0&&typeof schematicGroup.width=="number"&&(width=schematicGroup.width),height===void 0&&typeof schematicGroup.height=="number"&&(height=schematicGroup.height)),width===void 0||height===void 0)return;let center2=schematicGroup?.center??this._getGlobalSchematicPositionBeforeLayout(),left=center2.x-width/2-paddingLeft,bottom=center2.y-height/2-paddingBottom,finalWidth=width+paddingLeft+paddingRight,finalHeight=height+paddingTop+paddingBottom;db.schematic_box.insert({width:finalWidth,height:finalHeight,x:left,y:bottom,is_dashed:props.border?.dashed??!1})}_determineSideFromPosition(port,component){if(!port.center||!component.center)return"left";let dx2=port.center.x-component.center.x,dy2=port.center.y-component.center.y;return Math.abs(dx2)>Math.abs(dy2)?dx2>0?"right":"left":dy2>0?"bottom":"top"}_calculateSchematicBounds(boxes){if(boxes.length===0)return{minX:0,maxX:0,minY:0,maxY:0};let minX=1/0,maxX=-1/0,minY=1/0,maxY=-1/0;for(let box2 of boxes)minX=Math.min(minX,box2.centerX),maxX=Math.max(maxX,box2.centerX),minY=Math.min(minY,box2.centerY),maxY=Math.max(maxY,box2.centerY);let padding=2;return{minX:minX-padding,maxX:maxX+padding,minY:minY-padding,maxY:maxY+padding}}_getAutorouterConfig(){let autorouter=this._parsedProps.autorouter||this.getInheritedProperty("autorouter");return getPresetAutoroutingConfig(autorouter)}_isLaserPrefabAutorouter(autorouterConfig2=this._getAutorouterConfig()){let autorouterProp2=this.props.autorouter,normalize3=value=>value?.replace(/-/g,"_")??value;return autorouterConfig2.preset==="laser_prefab"?!0:typeof autorouterProp2=="string"?normalize3(autorouterProp2)==="laser_prefab":typeof autorouterProp2=="object"&&autorouterProp2?normalize3(autorouterProp2.preset)==="laser_prefab":!1}_getSubcircuitLayerCount(){let layers=this.getInheritedProperty("layers");return typeof layers=="number"?layers:2}_shouldUseTraceByTraceRouting(){return this._getAutorouterConfig().groupMode==="sequential-trace"}doInitialPcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db}=this.root;if(this.isSubcircuit){let subcircuitComponentsByName=new Map;for(let child of this.children)if(!child.isSubcircuit&&child._parsedProps.name){let components=subcircuitComponentsByName.get(child._parsedProps.name)||[];components.push(child),subcircuitComponentsByName.set(child._parsedProps.name,components)}for(let[name,components]of subcircuitComponentsByName.entries())components.length>1&&db.pcb_trace_error.insert({error_type:"pcb_trace_error",message:`Multiple components found with name "${name}" in subcircuit "${this.name||"unnamed"}". Component names must be unique within a subcircuit.`,source_trace_id:"",pcb_trace_id:"",pcb_component_ids:components.map(c3=>c3.pcb_component_id).filter(Boolean),pcb_port_ids:[]})}}doInitialSchematicReplaceNetLabelsWithSymbols(){if(this.root?.schematicDisabled||!this.isSubcircuit)return;let{db}=this.root,subtree=db;for(let nl2 of subtree.schematic_net_label.list()){let net=subtree.source_net.get(nl2.source_net_id),text=nl2.text||net?.name||"";if(nl2.anchor_side==="top"&&/^gnd/i.test(text)){subtree.schematic_net_label.update(nl2.schematic_net_label_id,{symbol_name:"rail_down"});continue}nl2.anchor_side==="bottom"&&/^v/i.test(text)&&subtree.schematic_net_label.update(nl2.schematic_net_label_id,{symbol_name:"rail_up"})}}doInitialSimulationSpiceEngineRender(){Group_doInitialSimulationSpiceEngineRender(this)}doInitialPcbComponentAnchorAlignment(){Group_doInitialPcbComponentAnchorAlignment(this)}updatePcbComponentAnchorAlignment(){this.doInitialPcbComponentAnchorAlignment()}_getMinimumFlexContainerSize(){return super._getMinimumFlexContainerSize()}_repositionOnPcb(position2){return super._repositionOnPcb(position2)}};function inflatePcbBoard(pcbBoard,inflatorContext){let{subcircuit}=inflatorContext;if(subcircuit.lowercaseComponentName==="board"||subcircuit.parent?.lowercaseComponentName==="board")return;let boardProps2={name:"inflated_board"};pcbBoard.width&&(boardProps2.width=pcbBoard.width),pcbBoard.height&&(boardProps2.height=pcbBoard.height),pcbBoard.center&&(boardProps2.pcbX=pcbBoard.center.x,boardProps2.pcbY=pcbBoard.center.y),pcbBoard.outline&&(boardProps2.outline=pcbBoard.outline),pcbBoard.thickness&&(boardProps2.thickness=pcbBoard.thickness),pcbBoard.material&&(boardProps2.material=pcbBoard.material);let board=new Board(boardProps2);return board.pcb_board_id=pcbBoard.pcb_board_id,subcircuit.add(board),board}var stringProxy=new Proxy({},{get:(target,prop)=>prop}),FTYPE=stringProxy,SCHEMATIC_COMPONENT_OUTLINE_COLOR="rgba(132, 0, 0)",SCHEMATIC_COMPONENT_OUTLINE_STROKE_WIDTH=.12,Capacitor=class extends NormalComponent3{constructor(){super(...arguments);__publicField(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Capacitor",schematicSymbolName:this.props.polarized?"capacitor_polarized":this.props.symbolName??"capacitor",zodProps:capacitorProps,sourceFtype:FTYPE.simple_capacitor}}initPorts(){typeof this.props.footprint=="string"?super.initPorts({additionalAliases:{pin1:["anode","pos"],pin2:["cathode","neg"]}}):super.initPorts()}_getSchematicSymbolDisplayValue(){let inputCapacitance=this.props.capacitance,capacitanceDisplay=typeof inputCapacitance=="string"?inputCapacitance:`${formatSiUnit(this._parsedProps.capacitance)}F`;return this._parsedProps.schShowRatings&&this._parsedProps.maxVoltageRating?`${capacitanceDisplay}/${formatSiUnit(this._parsedProps.maxVoltageRating)}V`:capacitanceDisplay}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.decouplingFor,this.props.decouplingTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.decouplingFor&&this.props.decouplingTo&&(this.add(new Trace3({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.decouplingFor})),this.add(new Trace3({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.decouplingTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,source_component=db.source_component.insert({ftype:"simple_capacitor",name:this.name,manufacturer_part_number:props.manufacturerPartNumber??props.mfn,supplier_part_numbers:props.supplierPartNumbers,capacitance:props.capacitance,max_voltage_rating:props.maxVoltageRating,max_decoupling_trace_length:props.maxDecouplingTraceLength,display_capacitance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!props.polarized});this.source_component_id=source_component.source_component_id}},inflatePcbComponent=(pcbElm,inflatorContext)=>{let{injectionDb,normalComponent}=inflatorContext;if(!normalComponent)return;let componentCenter=pcbElm.center||{x:0,y:0},componentRotation=pcbElm.rotation||0,absoluteToComponentRelativeTransform=inverse(compose(translate(componentCenter.x,componentCenter.y),rotate(componentRotation*Math.PI/180))),relativeElements=injectionDb.toArray().filter(elm=>"pcb_component_id"in elm&&elm.pcb_component_id===pcbElm.pcb_component_id),clonedRelativeElements=structuredClone(relativeElements);transformPCBElements(clonedRelativeElements,absoluteToComponentRelativeTransform);let components=createComponentsFromCircuitJson({componentName:normalComponent.name,componentRotation:"0deg"},clonedRelativeElements);normalComponent.addAll(components)};function inflateSourceCapacitor(sourceElm,inflatorContext){let{injectionDb,subcircuit,groupsMap}=inflatorContext,pcbElm=injectionDb.pcb_component.getWhere({source_component_id:sourceElm.source_component_id}),cadElm=injectionDb.cad_component.getWhere({source_component_id:sourceElm.source_component_id}),capacitor=new Capacitor({name:sourceElm.name,capacitance:sourceElm.capacitance,layer:pcbElm?.layer,pcbX:pcbElm?.center?.x,pcbY:pcbElm?.center?.y,pcbRotation:pcbElm?.rotation,doNotPlace:pcbElm?.do_not_place,obstructsWithinBounds:pcbElm?.obstructs_within_bounds});pcbElm&&inflatePcbComponent(pcbElm,{...inflatorContext,normalComponent:capacitor}),sourceElm.source_group_id&&groupsMap?.has(sourceElm.source_group_id)?groupsMap.get(sourceElm.source_group_id).add(capacitor):subcircuit.add(capacitor)}var Chip=class extends NormalComponent3{constructor(props){super(props);__publicField(this,"schematicBoxDimensions",null)}get config(){return{componentName:"Chip",zodProps:chipProps,shouldRenderAsSchematicBox:!0}}initPorts(opts={}){super.initPorts(opts);let{_parsedProps:props}=this,{pcbX,pcbY}=this.getResolvedPcbPositionProp();if(props.externallyConnectedPins){let requiredPorts=new Set;for(let[pin1,pin2]of props.externallyConnectedPins)requiredPorts.add(pin1),requiredPorts.add(pin2);for(let pinIdentifier of requiredPorts)if(!this.children.find(child=>child instanceof Port&&child.isMatchingAnyOf([pinIdentifier]))){let pinMatch=pinIdentifier.match(/^pin(\d+)$/);if(pinMatch){let pinNumber=parseInt(pinMatch[1]);this.add(new Port({pinNumber,aliases:[pinIdentifier]}))}else this.add(new Port({name:pinIdentifier,aliases:[pinIdentifier]}))}}}doInitialSchematicComponentRender(){let{_parsedProps:props}=this;props?.noSchematicRepresentation!==!0&&super.doInitialSchematicComponentRender()}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,{pcbX,pcbY}=this.getResolvedPcbPositionProp(),source_component=db.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:props.manufacturerPartNumber,supplier_part_numbers:props.supplierPartNumbers});this.source_component_id=source_component.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,{pcbX,pcbY}=this.getResolvedPcbPositionProp(),componentLayer=props.layer??"top";if(componentLayer!=="top"&&componentLayer!=="bottom"){let subcircuit=this.getSubcircuit(),error=pcb_component_invalid_layer_error.parse({type:"pcb_component_invalid_layer_error",message:`Component cannot be placed on layer '${componentLayer}'. Components can only be placed on 'top' or 'bottom' layers.`,source_component_id:this.source_component_id,layer:componentLayer,subcircuit_id:subcircuit.subcircuit_id??void 0});db.pcb_component_invalid_layer_error.insert(error)}let pcb_component2=db.pcb_component.insert({center:{x:pcbX,y:pcbY},width:2,height:3,layer:componentLayer==="top"||componentLayer==="bottom"?componentLayer:"top",rotation:props.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:props.doNotPlace??!1,obstructs_within_bounds:props.obstructsWithinBounds??!0});this.pcb_component_id=pcb_component2.pcb_component_id}doInitialCreateTracesFromProps(){let{_parsedProps:props}=this;if(props.externallyConnectedPins)for(let[pin1,pin2]of props.externallyConnectedPins)this.add(new Trace3({from:`${this.getSubcircuitSelector()} > port.${pin1}`,to:`${this.getSubcircuitSelector()} > port.${pin2}`}));this._createTracesFromConnectionsProp()}doInitialSimulationRender(){let{db}=this.root,{pinAttributes}=this.props;if(!pinAttributes)return;let powerPort=null,groundPort=null,voltage2,ports=this.selectAll("port");for(let port of ports)for(let alias of port.getNameAndAliases())if(pinAttributes[alias]){let attributes2=pinAttributes[alias];attributes2.providesPower&&(powerPort=port,voltage2=attributes2.providesVoltage),attributes2.providesGround&&(groundPort=port)}if(!powerPort||!groundPort||voltage2===void 0)return;let powerSourcePort=db.source_port.get(powerPort.source_port_id);if(!powerSourcePort?.subcircuit_connectivity_map_key)return;let groundSourcePort=db.source_port.get(groundPort.source_port_id);if(!groundSourcePort?.subcircuit_connectivity_map_key)return;let powerNet=db.source_net.getWhere({subcircuit_connectivity_map_key:powerSourcePort.subcircuit_connectivity_map_key}),groundNet=db.source_net.getWhere({subcircuit_connectivity_map_key:groundSourcePort.subcircuit_connectivity_map_key});!powerNet||!groundNet||db.simulation_voltage_source.insert({type:"simulation_voltage_source",positive_source_port_id:powerPort.source_port_id,positive_source_net_id:powerNet.source_net_id,negative_source_port_id:groundPort.source_port_id,negative_source_net_id:groundNet.source_net_id,voltage:voltage2})}},mapInternallyConnectedSourcePortIdsToPinLabels=(sourcePortIds,inflatorContext)=>{if(!sourcePortIds||sourcePortIds.length===0)return;let{injectionDb}=inflatorContext,mapped=sourcePortIds.map(group=>group.map(sourcePortId=>{let port=injectionDb.source_port.get(sourcePortId);return port?port.pin_number!==void 0&&port.pin_number!==null?`pin${port.pin_number}`:port.name:null}).filter(value=>value!==null)).filter(group=>group.length>0);return mapped.length>0?mapped:void 0},inflateSourceChip=(sourceElm,inflatorContext)=>{let{injectionDb,subcircuit,groupsMap}=inflatorContext,pcbElm=injectionDb.pcb_component.getWhere({source_component_id:sourceElm.source_component_id}),schematicElm=injectionDb.schematic_component.getWhere({source_component_id:sourceElm.source_component_id}),cadElm=injectionDb.cad_component.getWhere({source_component_id:sourceElm.source_component_id}),internallyConnectedPins=mapInternallyConnectedSourcePortIdsToPinLabels(sourceElm.internally_connected_source_port_ids,inflatorContext),chip=new Chip({name:sourceElm.name,manufacturerPartNumber:sourceElm.manufacturer_part_number,supplierPartNumbers:sourceElm.supplier_part_numbers??void 0,pinLabels:schematicElm?.port_labels??void 0,schWidth:schematicElm?.size?.width,schHeight:schematicElm?.size?.height,schPinSpacing:schematicElm?.pin_spacing,schX:schematicElm?.center?.x,schY:schematicElm?.center?.y,layer:pcbElm?.layer,pcbX:pcbElm?.center?.x,pcbY:pcbElm?.center?.y,pcbRotation:pcbElm?.rotation,doNotPlace:pcbElm?.do_not_place,obstructsWithinBounds:pcbElm?.obstructs_within_bounds,internallyConnectedPins}),footprint=cadElm?.footprinter_string??null;footprint&&(Object.assign(chip.props,{footprint}),Object.assign(chip._parsedProps,{footprint}),cadElm||chip._addChildrenFromStringFootprint?.()),pcbElm&&inflatePcbComponent(pcbElm,{...inflatorContext,normalComponent:chip}),sourceElm.source_group_id&&groupsMap?.has(sourceElm.source_group_id)?groupsMap.get(sourceElm.source_group_id).add(chip):subcircuit.add(chip)},Diode=class extends NormalComponent3{constructor(){super(...arguments);__publicField(this,"pos",this.portMap.pin1);__publicField(this,"anode",this.portMap.pin1);__publicField(this,"neg",this.portMap.pin2);__publicField(this,"cathode",this.portMap.pin2)}get config(){let symbolMap={schottky:"schottky_diode",avalanche:"avalanche_diode",zener:"zener_diode",photodiode:"photodiode"},variantSymbol=this.props.schottky?"schottky":this.props.avalanche?"avalanche":this.props.zener?"zener":this.props.photo?"photodiode":null;return{schematicSymbolName:variantSymbol?symbolMap[variantSymbol]:this.props.symbolName??"diode",componentName:"Diode",zodProps:diodeProps,sourceFtype:"simple_diode"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,source_component=db.source_component.insert({ftype:"simple_diode",name:this.name,manufacturer_part_number:props.manufacturerPartNumber??props.mfn,supplier_part_numbers:props.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=source_component.source_component_id}};function inflateSourceDiode(sourceElm,inflatorContext){let{injectionDb,subcircuit,groupsMap}=inflatorContext,pcbElm=injectionDb.pcb_component.getWhere({source_component_id:sourceElm.source_component_id}),cadElm=injectionDb.cad_component.getWhere({source_component_id:sourceElm.source_component_id}),diode2=new Diode({name:sourceElm.name,layer:pcbElm?.layer,pcbX:pcbElm?.center?.x,pcbY:pcbElm?.center?.y,pcbRotation:pcbElm?.rotation,doNotPlace:pcbElm?.do_not_place,obstructsWithinBounds:pcbElm?.obstructs_within_bounds});pcbElm&&inflatePcbComponent(pcbElm,{...inflatorContext,normalComponent:diode2}),sourceElm.source_group_id&&groupsMap?.has(sourceElm.source_group_id)?groupsMap.get(sourceElm.source_group_id).add(diode2):subcircuit.add(diode2)}function inflateSourceGroup(sourceGroup,inflatorContext){let{subcircuit,groupsMap}=inflatorContext,group=new Group6({name:sourceGroup.name??`inflated_group_${sourceGroup.source_group_id}`});return group.source_group_id=sourceGroup.source_group_id,groupsMap&&groupsMap.set(sourceGroup.source_group_id,group),sourceGroup.parent_source_group_id&&groupsMap?.has(sourceGroup.parent_source_group_id)?groupsMap.get(sourceGroup.parent_source_group_id).add(group):subcircuit.add(group),group}var Inductor=class extends NormalComponent3{constructor(){super(...arguments);__publicField(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Inductor",schematicSymbolName:this.props.symbolName??"inductor",zodProps:inductorProps,sourceFtype:FTYPE.simple_inductor}}_getSchematicSymbolDisplayValue(){return`${formatSiUnit(this._parsedProps.inductance)}H`}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,source_component=db.source_component.insert({name:this.name,ftype:FTYPE.simple_inductor,inductance:this.props.inductance,display_inductance:this._getSchematicSymbolDisplayValue(),supplier_part_numbers:props.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=source_component.source_component_id}};function inflateSourceInductor(sourceElm,inflatorContext){let{injectionDb,subcircuit,groupsMap}=inflatorContext,pcbElm=injectionDb.pcb_component.getWhere({source_component_id:sourceElm.source_component_id}),cadElm=injectionDb.cad_component.getWhere({source_component_id:sourceElm.source_component_id}),inductor=new Inductor({name:sourceElm.name,inductance:sourceElm.inductance,layer:pcbElm?.layer,pcbX:pcbElm?.center?.x,pcbY:pcbElm?.center?.y,pcbRotation:pcbElm?.rotation,doNotPlace:pcbElm?.do_not_place,obstructsWithinBounds:pcbElm?.obstructs_within_bounds});pcbElm&&inflatePcbComponent(pcbElm,{...inflatorContext,normalComponent:inductor}),sourceElm.source_group_id&&groupsMap?.has(sourceElm.source_group_id)?groupsMap.get(sourceElm.source_group_id).add(inductor):subcircuit.add(inductor)}function inflateSourcePort(sourcePort,inflatorContext){let{injectionDb,subcircuit}=inflatorContext;if(sourcePort.source_component_id!==null)return;let pcbPortFromInjection=injectionDb.pcb_port.getWhere({source_port_id:sourcePort.source_port_id}),port=new Port({name:sourcePort.name,pinNumber:sourcePort.pin_number});subcircuit.add(port),port.source_port_id=sourcePort.source_port_id;let root=subcircuit.root;if(root&&pcbPortFromInjection){let{db}=root,pcb_port2=db.pcb_port.insert({pcb_component_id:void 0,layers:pcbPortFromInjection.layers,subcircuit_id:subcircuit.subcircuit_id??void 0,pcb_group_id:subcircuit.getGroup()?.pcb_group_id??void 0,x:pcbPortFromInjection.x,y:pcbPortFromInjection.y,source_port_id:sourcePort.source_port_id,is_board_pinout:!1});port.pcb_port_id=pcb_port2.pcb_port_id}}var Resistor=class extends NormalComponent3{constructor(){super(...arguments);__publicField(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Resistor",schematicSymbolName:this.props.symbolName??"boxresistor",zodProps:resistorProps,sourceFtype:"simple_resistor"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return`${formatSiUnit(this._parsedProps.resistance)}\u03A9`}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.pullupFor,this.props.pullupTo,this.props.pulldownFor,this.props.pulldownTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.pullupFor&&this.props.pullupTo&&(this.add(new Trace3({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pullupFor})),this.add(new Trace3({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pullupTo}))),this.props.pulldownFor&&this.props.pulldownTo&&(this.add(new Trace3({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pulldownFor})),this.add(new Trace3({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pulldownTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,source_component=db.source_component.insert({ftype:"simple_resistor",name:this.name,manufacturer_part_number:props.manufacturerPartNumber??props.mfn,supplier_part_numbers:props.supplierPartNumbers,resistance:props.resistance,display_resistance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!0});this.source_component_id=source_component.source_component_id}};function inflateSourceResistor(sourceElm,inflatorContext){let{injectionDb,subcircuit,groupsMap}=inflatorContext,pcbElm=injectionDb.pcb_component.getWhere({source_component_id:sourceElm.source_component_id}),cadElm=injectionDb.cad_component.getWhere({source_component_id:sourceElm.source_component_id}),resistor=new Resistor({name:sourceElm.name,resistance:sourceElm.resistance,layer:pcbElm?.layer,pcbX:pcbElm?.center?.x,pcbY:pcbElm?.center?.y,pcbRotation:pcbElm?.rotation,doNotPlace:pcbElm?.do_not_place,obstructsWithinBounds:pcbElm?.obstructs_within_bounds});pcbElm&&inflatePcbComponent(pcbElm,{...inflatorContext,normalComponent:resistor}),sourceElm.source_group_id&&groupsMap?.has(sourceElm.source_group_id)?groupsMap.get(sourceElm.source_group_id).add(resistor):subcircuit.add(resistor)}var getSelectorPath=(component,inflatorContext)=>{let{injectionDb,subcircuit,groupsMap}=inflatorContext,path_parts=[],currentGroupId=component.source_group_id;for(;currentGroupId&&currentGroupId!==subcircuit.source_group_id;){let sourceGroup=injectionDb.source_group.get(currentGroupId),groupInstance=groupsMap?.get(currentGroupId);if(!sourceGroup||!groupInstance)break;let groupName=groupInstance.props.name??groupInstance.fallbackUnassignedName;path_parts.unshift(`.${groupName}`),currentGroupId=sourceGroup.parent_source_group_id}return path_parts.push(`.${component.name}`),path_parts.join(" > ")};function inflateSourceTrace(sourceTrace,inflatorContext){let{injectionDb,subcircuit}=inflatorContext,connectedSelectors=[];for(let sourcePortId of sourceTrace.connected_source_port_ids){let sourcePort=injectionDb.source_port.get(sourcePortId);if(!sourcePort)continue;let selector;if(sourcePort.source_component_id){let sourceComponent=injectionDb.source_component.get(sourcePort.source_component_id);sourceComponent&&(selector=`${getSelectorPath({name:sourceComponent.name,source_group_id:sourceComponent.source_group_id},inflatorContext)} > .${sourcePort.name}`)}else selector=`.${sourcePort.name}`;selector&&connectedSelectors.push(selector)}for(let sourceNetId of sourceTrace.connected_source_net_ids){let sourceNet=injectionDb.source_net.get(sourceNetId);sourceNet&&connectedSelectors.push(`net.${sourceNet.name}`)}if(connectedSelectors.length<2)return;let trace=new Trace3({path:connectedSelectors});trace.source_trace_id=sourceTrace.source_trace_id,subcircuit.add(trace)}var Transistor=class extends NormalComponent3{constructor(){super(...arguments);__publicField(this,"emitter",this.portMap.pin1);__publicField(this,"collector",this.portMap.pin2);__publicField(this,"base",this.portMap.pin3)}get config(){let baseSymbolName=this.props.type==="npn"?"npn_bipolar_transistor":"pnp_bipolar_transistor";return{componentName:"Transistor",schematicSymbolName:this.props.symbolName??baseSymbolName,zodProps:transistorProps,sourceFtype:"simple_transistor",shouldRenderAsSchematicBox:!1}}initPorts(){let pinAliases={pin1:["collector","c"],pin2:["emitter","e"],pin3:["base","b"]};super.initPorts({pinCount:3,additionalAliases:pinAliases})}doInitialCreateNetsFromProps(){this._createNetsFromProps([...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,source_component=db.source_component.insert({ftype:"simple_transistor",name:this.name,transistor_type:props.type});this.source_component_id=source_component.source_component_id}};function inflateSourceTransistor(sourceElm,inflatorContext){let{injectionDb,subcircuit,groupsMap}=inflatorContext,pcbElm=injectionDb.pcb_component.getWhere({source_component_id:sourceElm.source_component_id}),cadElm=injectionDb.cad_component.getWhere({source_component_id:sourceElm.source_component_id}),transistor=new Transistor({name:sourceElm.name,type:sourceElm.transistor_type,layer:pcbElm?.layer,pcbX:pcbElm?.center?.x,pcbY:pcbElm?.center?.y,pcbRotation:pcbElm?.rotation,doNotPlace:pcbElm?.do_not_place,obstructsWithinBounds:pcbElm?.obstructs_within_bounds});pcbElm&&inflatePcbComponent(pcbElm,{...inflatorContext,normalComponent:transistor}),sourceElm.source_group_id&&groupsMap?.has(sourceElm.source_group_id)?groupsMap.get(sourceElm.source_group_id).add(transistor):subcircuit.add(transistor)}var inflateCircuitJson=(target,circuitJson,children)=>{if(!circuitJson)return;let injectionDb=cju_default(circuitJson);if(circuitJson&&children?.length>0)throw new Error("Component cannot have both circuitJson and children");let inflationCtx={injectionDb,subcircuit:target,groupsMap:new Map},sourceGroups=injectionDb.source_group.list();for(let sourceGroup of sourceGroups)inflateSourceGroup(sourceGroup,inflationCtx);let pcbBoards=injectionDb.pcb_board.list();for(let pcbBoard of pcbBoards)inflatePcbBoard(pcbBoard,inflationCtx);let sourceComponents=injectionDb.source_component.list();for(let sourceComponent of sourceComponents)switch(sourceComponent.ftype){case"simple_resistor":inflateSourceResistor(sourceComponent,inflationCtx);break;case"simple_capacitor":inflateSourceCapacitor(sourceComponent,inflationCtx);break;case"simple_inductor":inflateSourceInductor(sourceComponent,inflationCtx);break;case"simple_diode":inflateSourceDiode(sourceComponent,inflationCtx);break;case"simple_chip":inflateSourceChip(sourceComponent,inflationCtx);break;case"simple_transistor":inflateSourceTransistor(sourceComponent,inflationCtx);break;default:throw new Error(`No inflator implemented for source component ftype: "${sourceComponent.ftype}"`)}let sourcePorts=injectionDb.source_port.list();for(let sourcePort of sourcePorts)inflateSourcePort(sourcePort,inflationCtx);let sourceTraces=injectionDb.source_trace.list();for(let sourceTrace of sourceTraces)inflateSourceTrace(sourceTrace,inflationCtx)},MIN_EFFECTIVE_BORDER_RADIUS_MM=.01,getRoundedRectOutline=(width,height,radius)=>{let w22=width/2,h22=height/2,r4=Math.min(radius,w22,h22);if(r4<MIN_EFFECTIVE_BORDER_RADIUS_MM)return[{x:-w22,y:-h22},{x:w22,y:-h22},{x:w22,y:h22},{x:-w22,y:h22}];let segments=Math.max(1,Math.ceil(Math.PI/2*r4/.1)),step=Math.PI/2/segments,outline=[];outline.push({x:-w22+r4,y:-h22}),outline.push({x:w22-r4,y:-h22});for(let i3=1;i3<=segments;i3++){let theta=-Math.PI/2+i3*step;outline.push({x:w22-r4+r4*Math.cos(theta),y:-h22+r4+r4*Math.sin(theta)})}outline.push({x:w22,y:h22-r4});for(let i3=1;i3<=segments;i3++){let theta=0+i3*step;outline.push({x:w22-r4+r4*Math.cos(theta),y:h22-r4+r4*Math.sin(theta)})}outline.push({x:-w22+r4,y:h22});for(let i3=1;i3<=segments;i3++){let theta=Math.PI/2+i3*step;outline.push({x:-w22+r4+r4*Math.cos(theta),y:h22-r4+r4*Math.sin(theta)})}outline.push({x:-w22,y:-h22+r4});for(let i3=1;i3<=segments;i3++){let theta=Math.PI+i3*step;outline.push({x:-w22+r4+r4*Math.cos(theta),y:-h22+r4+r4*Math.sin(theta)})}return outline},Board=class extends Group6{constructor(){super(...arguments);__publicField(this,"pcb_board_id",null);__publicField(this,"source_board_id",null);__publicField(this,"_drcChecksComplete",!1);__publicField(this,"_connectedSchematicPortPairs",new Set)}get isSubcircuit(){return!0}get isGroup(){return!0}get config(){return{componentName:"Board",zodProps:boardProps}}get boardThickness(){return this._parsedProps.thickness??1.4}get allLayers(){return(this._parsedProps.layers??2)===4?["top","bottom","inner1","inner2"]:["top","bottom"]}_getSubcircuitLayerCount(){return this._parsedProps.layers??2}_getBoardCalcVariables(){let{_parsedProps:props}=this;if((props.width==null||props.height==null)&&!props.outline)return{};let dbBoard=this.pcb_board_id?this.root?.db.pcb_board.get(this.pcb_board_id):null,width=dbBoard?.width??props.width,height=dbBoard?.height??props.height;if((width==null||height==null)&&props.outline?.length){let outlineBounds=getBoundsFromPoints(props.outline);outlineBounds&&(width??(width=outlineBounds.maxX-outlineBounds.minX),height??(height=outlineBounds.maxY-outlineBounds.minY))}let{pcbX,pcbY}=this.getResolvedPcbPositionProp(),center2=dbBoard?.center??{x:pcbX+(props.outlineOffsetX??0),y:pcbY+(props.outlineOffsetY??0)},resolvedWidth=width??0,resolvedHeight=height??0;return{"board.minx":center2.x-resolvedWidth/2,"board.maxx":center2.x+resolvedWidth/2,"board.miny":center2.y-resolvedHeight/2,"board.maxy":center2.y+resolvedHeight/2}}doInitialPcbBoardAutoSize(){if(this.root?.pcbDisabled||!this.pcb_board_id)return;let{db}=this.root,{_parsedProps:props}=this,globalPos=this._getGlobalPcbPositionBeforeLayout(),pcbBoard=db.pcb_board.get(this.pcb_board_id);if(pcbBoard?.width&&pcbBoard?.height||pcbBoard?.outline&&pcbBoard.outline.length>0)return;let minX=1/0,minY=1/0,maxX=-1/0,maxY=-1/0,descendantIds=getDescendantSubcircuitIds(db,this.subcircuit_id),allowedSubcircuitIds=new Set([this.subcircuit_id,...descendantIds]),allPcbComponents=db.pcb_component.list().filter(c3=>c3.subcircuit_id&&allowedSubcircuitIds.has(c3.subcircuit_id)),allPcbGroups=db.pcb_group.list().filter(g4=>g4.subcircuit_id&&allowedSubcircuitIds.has(g4.subcircuit_id)),hasComponents=!1,updateBounds=(center22,width,height)=>{width===0||height===0||(hasComponents=!0,minX=Math.min(minX,center22.x-width/2),minY=Math.min(minY,center22.y-height/2),maxX=Math.max(maxX,center22.x+width/2),maxY=Math.max(maxY,center22.y+height/2))};for(let pcbComponent of allPcbComponents)updateBounds(pcbComponent.center,pcbComponent.width,pcbComponent.height);for(let pcbGroup of allPcbGroups){let width=pcbGroup.width??0,height=pcbGroup.height??0;if(pcbGroup.outline&&pcbGroup.outline.length>0){let bounds=getBoundsFromPoints(pcbGroup.outline);bounds&&(width=bounds.maxX-bounds.minX,height=bounds.maxY-bounds.minY)}updateBounds(pcbGroup.center,width,height)}if(props.boardAnchorPosition){let{x:x3,y:y3}=props.boardAnchorPosition;minX=Math.min(minX,x3),minY=Math.min(minY,y3),maxX=Math.max(maxX,x3),maxY=Math.max(maxY,y3)}let padding=2,computedWidth=hasComponents?maxX-minX+padding*2:0,computedHeight=hasComponents?maxY-minY+padding*2:0,center2={x:hasComponents?(minX+maxX)/2+(props.outlineOffsetX??0):(props.outlineOffsetX??0)+globalPos.x,y:hasComponents?(minY+maxY)/2+(props.outlineOffsetY??0):(props.outlineOffsetY??0)+globalPos.y},finalWidth=props.width??computedWidth,finalHeight=props.height??computedHeight,outline=props.outline;!outline&&props.borderRadius!=null&&finalWidth>0&&finalHeight>0&&(outline=getRoundedRectOutline(finalWidth,finalHeight,props.borderRadius));let update={width:finalWidth,height:finalHeight,center:center2};outline&&(update.outline=outline.map(point23=>({x:point23.x+(props.outlineOffsetX??0),y:point23.y+(props.outlineOffsetY??0)}))),db.pcb_board.update(this.pcb_board_id,update)}updatePcbBoardAutoSize(){this.doInitialPcbBoardAutoSize()}_addBoardInformationToSilkscreen(){let platform=this.root?.platform;if(!platform?.printBoardInformationToSilkscreen)return;let pcbBoard=this.root.db.pcb_board.get(this.pcb_board_id);if(!pcbBoard)return;let boardInformation=[];if(platform.projectName&&boardInformation.push(platform.projectName),platform.version&&boardInformation.push(`v${platform.version}`),platform.url&&boardInformation.push(platform.url),boardInformation.length===0)return;let text=boardInformation.join(`
601
- `),position2={x:pcbBoard.center.x+pcbBoard.width/2-.25,y:pcbBoard.center.y-pcbBoard.height/2+1};this.root.db.pcb_silkscreen_text.insert({pcb_component_id:this.pcb_board_id,layer:"top",font:"tscircuit2024",font_size:.45,text,ccw_rotation:0,anchor_alignment:"bottom_right",anchor_position:position2})}doInitialSourceRender(){let nestedBoard=this.getDescendants().find(d2=>d2.lowercaseComponentName==="board");if(nestedBoard)throw new Error(`Nested boards are not supported: found board "${nestedBoard.name}" inside board "${this.name}"`);super.doInitialSourceRender();let{db}=this.root,source_board2=db.source_board.insert({source_group_id:this.source_group_id,title:this.props.title||this.props.name});this.source_board_id=source_board2.source_board_id}doInitialInflateSubcircuitCircuitJson(){let{circuitJson,children}=this._parsedProps;inflateCircuitJson(this,circuitJson,children)}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,pcbBoardFromCircuitJson=props.circuitJson?.find(elm=>elm.type==="pcb_board"),computedWidth=props.width??pcbBoardFromCircuitJson?.width??0,computedHeight=props.height??pcbBoardFromCircuitJson?.height??0,globalPos=this._getGlobalPcbPositionBeforeLayout(),center2={x:globalPos.x+(props.outlineOffsetX??0),y:globalPos.y+(props.outlineOffsetY??0)},{boardAnchorPosition,boardAnchorAlignment}=props;if(boardAnchorPosition&&(center2=getBoardCenterFromAnchor({boardAnchorPosition,boardAnchorAlignment:boardAnchorAlignment??"center",width:computedWidth,height:computedHeight})),props.outline){let xValues=props.outline.map(point23=>point23.x),yValues=props.outline.map(point23=>point23.y),minX=Math.min(...xValues),maxX=Math.max(...xValues),minY=Math.min(...yValues),maxY=Math.max(...yValues);computedWidth=maxX-minX,computedHeight=maxY-minY}let outline=props.outline;!outline&&props.borderRadius!=null&&computedWidth>0&&computedHeight>0&&(outline=getRoundedRectOutline(computedWidth,computedHeight,props.borderRadius));let pcb_board2=db.pcb_board.insert({source_board_id:this.source_board_id,center:center2,thickness:this.boardThickness,num_layers:this.allLayers.length,width:computedWidth,height:computedHeight,outline:outline?.map(point23=>({x:point23.x+(props.outlineOffsetX??0),y:point23.y+(props.outlineOffsetY??0)})),material:props.material});this.pcb_board_id=pcb_board2.pcb_board_id,this._addBoardInformationToSilkscreen()}removePcbComponentRender(){let{db}=this.root;this.pcb_board_id&&(db.pcb_board.delete(this.pcb_board_id),this.pcb_board_id=null)}doInitialPcbDesignRuleChecks(){this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled")||super.doInitialPcbDesignRuleChecks()}updatePcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db}=this.root;if(!this._areChildSubcircuitsRouted()||this._drcChecksComplete)return;this._drcChecksComplete=!0;let errors=checkEachPcbTraceNonOverlapping(db.toArray());for(let error of errors)db.pcb_trace_error.insert(error);let pcbPortNotConnectedErrors=checkEachPcbPortConnectedToPcbTraces(db.toArray());for(let error of pcbPortNotConnectedErrors)db.pcb_port_not_connected_error.insert(error);let pcbComponentOutsideErrors=checkPcbComponentsOutOfBoard(db.toArray());for(let error of pcbComponentOutsideErrors)db.pcb_component_outside_board_error.insert(error);let pcbTracesOutOfBoardErrors=checkPcbTracesOutOfBoard(db.toArray());for(let error of pcbTracesOutOfBoardErrors)db.pcb_trace_error.insert(error);let differentNetViaErrors=checkDifferentNetViaSpacing(db.toArray());for(let error of differentNetViaErrors)db.pcb_via_clearance_error.insert(error);let sameNetViaErrors=checkSameNetViaSpacing(db.toArray());for(let error of sameNetViaErrors)db.pcb_via_clearance_error.insert(error);let pcbComponentOverlapErrors=checkPcbComponentOverlap(db.toArray());for(let error of pcbComponentOverlapErrors)db.pcb_footprint_overlap_error.insert(error);let sourcePinMustBeConnectedErrors=checkPinMustBeConnected(db.toArray());for(let error of sourcePinMustBeConnectedErrors)db.source_pin_must_be_connected_error.insert(error)}_emitRenderLifecycleEvent(phase,startOrEnd){super._emitRenderLifecycleEvent(phase,startOrEnd),startOrEnd==="start"&&this.root?.emit("board:renderPhaseStarted",{renderId:this._renderId,phase})}_repositionOnPcb(position2){let{db}=this.root,pcbBoard=this.pcb_board_id?db.pcb_board.get(this.pcb_board_id):null,oldPos=pcbBoard?.center;if(!oldPos){this.pcb_board_id&&db.pcb_board.update(this.pcb_board_id,{center:position2});return}let deltaX=position2.x-oldPos.x,deltaY=position2.y-oldPos.y;if(!(Math.abs(deltaX)<1e-6&&Math.abs(deltaY)<1e-6)){for(let child of this.children)if(child instanceof NormalComponent3){let childOldCenter;if(child.pcb_component_id){let comp=db.pcb_component.get(child.pcb_component_id);comp&&(childOldCenter=comp.center)}else if(child instanceof Group6&&child.pcb_group_id){let group=db.pcb_group.get(child.pcb_group_id);group&&(childOldCenter=group.center)}childOldCenter&&child._repositionOnPcb({x:childOldCenter.x+deltaX,y:childOldCenter.y+deltaY})}if(this.pcb_board_id&&(db.pcb_board.update(this.pcb_board_id,{center:position2}),pcbBoard?.outline)){let outlineBounds=getBoundsFromPoints(pcbBoard.outline);if(outlineBounds){let oldOutlineCenter={x:(outlineBounds.minX+outlineBounds.maxX)/2,y:(outlineBounds.minY+outlineBounds.maxY)/2},outlineDeltaX=position2.x-oldOutlineCenter.x,outlineDeltaY=position2.y-oldOutlineCenter.y,newOutline=pcbBoard.outline.map(p4=>({x:p4.x+outlineDeltaX,y:p4.y+outlineDeltaY}));db.pcb_board.update(this.pcb_board_id,{outline:newOutline})}}}}},DEFAULT_TAB_LENGTH=5,DEFAULT_TAB_WIDTH=2,generateCutoutsAndMousebitesForOutline=(outline,options)=>{let{gapLength,cutoutWidth,mouseBites,mouseBiteHoleDiameter,mouseBiteHoleSpacing}=options,tabCutouts=[],mouseBiteHoles=[];if(outline.length<2)return{tabCutouts,mouseBiteHoles};let outlinePolygon=new Polygon$1(outline.map(p4=>point4(p4.x,p4.y))),is_ccw;if(outline.length>2){let p02=point4(outline[0].x,outline[0].y),p12=point4(outline[1].x,outline[1].y),segmentDir=vector$1(p02,p12).normalize(),normalToLeft=segmentDir.rotate(Math.PI/2),testPoint=p02.translate(segmentDir.multiply(segment(p02,p12).length/2)).translate(normalToLeft.multiply(.01));is_ccw=outlinePolygon.contains(testPoint)}else is_ccw=outlinePolygon.area()>0;for(let i3=0;i3<outline.length;i3++){let p1_=outline[i3],p2_=outline[(i3+1)%outline.length];if(!p1_||!p2_)continue;let p12=point4(p1_.x,p1_.y),p22=point4(p2_.x,p2_.y),segment2=segment(p12,p22),segmentLength=segment2.length;if(segmentLength<1e-6)continue;let segmentVec=vector$1(p12,p22),segmentDir=segmentVec.normalize(),normalVec=segmentDir.rotate(Math.PI/2),testPoint=segment2.middle().translate(normalVec.multiply(.01));outlinePolygon.contains(testPoint)&&(normalVec=normalVec.multiply(-1));let numBitesInGap=2,totalBitesLength=numBitesInGap*mouseBiteHoleDiameter+(numBitesInGap-1)*mouseBiteHoleSpacing,effectiveGapLength;mouseBites?effectiveGapLength=totalBitesLength:effectiveGapLength=gapLength,effectiveGapLength=Math.min(effectiveGapLength,segmentLength*.9);let gapStartDist=(segmentLength-effectiveGapLength)/2,gapEndDist=gapStartDist+effectiveGapLength;if(mouseBites){let holeAndSpacing=mouseBiteHoleDiameter+mouseBiteHoleSpacing;if(effectiveGapLength>=totalBitesLength&&holeAndSpacing>0){let firstBiteCenterOffsetInGap=(effectiveGapLength-totalBitesLength)/2+mouseBiteHoleDiameter/2,firstBiteDistFromP1=gapStartDist+firstBiteCenterOffsetInGap;for(let k4=0;k4<numBitesInGap;k4++){let biteDist=firstBiteDistFromP1+k4*holeAndSpacing,pos=p12.translate(segmentDir.multiply(biteDist));mouseBiteHoles.push({x:pos.x,y:pos.y})}}}let p_prev_=outline[(i3-1+outline.length)%outline.length],p_next_=outline[(i3+2)%outline.length],start_ext=0,end_ext=0;if(p_prev_&&p_next_){let vec_in_p1=vector$1(point4(p_prev_.x,p_prev_.y),p12),p1_cross=vec_in_p1.cross(segmentVec),is_p1_convex=is_ccw?p1_cross>1e-9:p1_cross<-1e-9,vec_out_p2=vector$1(p22,point4(p_next_.x,p_next_.y)),p2_cross=segmentVec.cross(vec_out_p2),is_p2_convex=is_ccw?p2_cross>1e-9:p2_cross<-1e-9;if(is_p1_convex){let angle=vec_in_p1.angleTo(segmentVec);angle>Math.PI&&(angle=2*Math.PI-angle),start_ext=cutoutWidth*Math.tan(angle/2)}else start_ext=0;if(is_p2_convex){let angle=segmentVec.angleTo(vec_out_p2);angle>Math.PI&&(angle=2*Math.PI-angle),end_ext=cutoutWidth*Math.tan(angle/2)}else end_ext=0}let cutoutParts=[{start:0-start_ext,end:gapStartDist},{start:gapEndDist,end:segmentLength+end_ext}],extrusion=normalVec.multiply(cutoutWidth);for(let part of cutoutParts){let partLength=part.end-part.start;if(partLength<1e-6)continue;let center2=p12.translate(segmentDir.multiply(part.start+partLength/2)).translate(extrusion.multiply(.5)),width=partLength,height=cutoutWidth,rotationDeg=segmentDir.slope*180/Math.PI;tabCutouts.push({type:"pcb_cutout",shape:"rect",center:{x:center2.x,y:center2.y},width,height,rotation:rotationDeg,corner_radius:cutoutWidth/2})}}return{tabCutouts,mouseBiteHoles}};function generatePanelTabsAndMouseBites(boards,options){let finalTabCutouts=[],allMouseBites=[],{tabWidth,tabLength,mouseBites:useMouseBites}=options,processedBoards=boards.map(board=>{if((!board.outline||board.outline.length===0)&&board.width&&board.height){let w22=board.width/2,h22=board.height/2;return{...board,outline:[{x:board.center.x-w22,y:board.center.y-h22},{x:board.center.x+w22,y:board.center.y-h22},{x:board.center.x+w22,y:board.center.y+h22},{x:board.center.x-w22,y:board.center.y+h22}]}}return board});for(let board of processedBoards)if(board.outline&&board.outline.length>0){let mouseBiteDiameter2=tabWidth*.45,mouseBiteSpacing=mouseBiteDiameter2*.1,generated=generateCutoutsAndMousebitesForOutline(board.outline,{gapLength:tabLength,cutoutWidth:tabWidth,mouseBites:useMouseBites,mouseBiteHoleDiameter:mouseBiteDiameter2,mouseBiteHoleSpacing:mouseBiteSpacing});finalTabCutouts.push(...generated.tabCutouts),allMouseBites.push(...generated.mouseBiteHoles)}let tabCutouts=finalTabCutouts.map((tab,index)=>({...tab,pcb_cutout_id:`panel_tab_${index}`})),mouseBiteDiameter=tabWidth*.45,mouseBiteHoles=allMouseBites.map((bite,index)=>({type:"pcb_hole",pcb_hole_id:`panel_mouse_bite_${index}`,hole_shape:"circle",hole_diameter:mouseBiteDiameter,x:bite.x,y:bite.y}));return{tabCutouts,mouseBiteHoles}}var packBoardsIntoGrid=({boards,db,row,col,cellWidth,cellHeight,boardGap})=>{let boardsWithDims=boards.map(board=>{let pcbBoard=db.pcb_board.get(board.pcb_board_id);return!pcbBoard||pcbBoard.width===void 0||pcbBoard.height===void 0?null:{board,width:pcbBoard.width,height:pcbBoard.height}}).filter(b3=>b3!==null);if(boardsWithDims.length===0)return{positions:[],gridWidth:0,gridHeight:0};let explicitRow=row,cols=col??Math.ceil(explicitRow?boardsWithDims.length/explicitRow:Math.sqrt(boardsWithDims.length)),rows=explicitRow??Math.ceil(boardsWithDims.length/cols),colWidths=Array(cols).fill(0),rowHeights=Array(rows).fill(0);boardsWithDims.forEach((b3,i3)=>{let col2=i3%cols,row2=Math.floor(i3/cols);row2<rowHeights.length&&b3.height>rowHeights[row2]&&(rowHeights[row2]=b3.height),col2<colWidths.length&&b3.width>colWidths[col2]&&(colWidths[col2]=b3.width)});let minCellWidth=cellWidth?distance.parse(cellWidth):0,minCellHeight=cellHeight?distance.parse(cellHeight):0;for(let i3=0;i3<colWidths.length;i3++)colWidths[i3]=Math.max(colWidths[i3],minCellWidth);for(let i3=0;i3<rowHeights.length;i3++)rowHeights[i3]=Math.max(rowHeights[i3],minCellHeight);let totalGridWidth=colWidths.reduce((a3,b3)=>a3+b3,0)+(cols>1?(cols-1)*boardGap:0),totalGridHeight=rowHeights.reduce((a3,b3)=>a3+b3,0)+(rows>1?(rows-1)*boardGap:0),startX=-totalGridWidth/2,rowYOffsets=[-totalGridHeight/2];for(let i3=1;i3<rows;i3++)rowYOffsets.push(rowYOffsets[i3-1]+rowHeights[i3-1]+boardGap);let colXOffsets=[startX];for(let i3=1;i3<cols;i3++)colXOffsets.push(colXOffsets[i3-1]+colWidths[i3-1]+boardGap);let positions=[];return boardsWithDims.forEach((b3,i3)=>{let col2=i3%cols,row2=Math.floor(i3/cols);if(row2>=rowYOffsets.length||col2>=colXOffsets.length)return;let cellX=colXOffsets[col2],cellY=rowYOffsets[row2],cellWidth2=colWidths[col2],cellHeight2=rowHeights[row2],boardX=cellX+cellWidth2/2,boardY=cellY+cellHeight2/2;positions.push({board:b3.board,pos:{x:boardX,y:boardY}})}),{positions,gridWidth:totalGridWidth,gridHeight:totalGridHeight}},Panel=class extends Group6{constructor(){super(...arguments);__publicField(this,"pcb_panel_id",null);__publicField(this,"_tabsAndMouseBitesGenerated",!1)}get config(){return{componentName:"Panel",zodProps:panelProps}}get isGroup(){return!0}get isSubcircuit(){return!0}add(component){if(component.lowercaseComponentName!=="board")throw new Error("<panel> can only contain <board> elements");super.add(component)}doInitialPanelLayout(){if(this.root?.pcbDisabled)return;let{db}=this.root,childBoardInstances=this.children.filter(c3=>c3 instanceof Board),hasAnyPositionedBoards=childBoardInstances.some(b3=>b3.props.pcbX!==void 0||b3.props.pcbY!==void 0),unpositionedBoards=childBoardInstances.filter(b3=>b3.props.pcbX===void 0&&b3.props.pcbY===void 0);if(unpositionedBoards.length>0&&!hasAnyPositionedBoards){let tabWidth=this._parsedProps.tabWidth??DEFAULT_TAB_WIDTH,boardGap=this._parsedProps.boardGap??tabWidth,{positions,gridWidth,gridHeight}=packBoardsIntoGrid({boards:unpositionedBoards,db,row:this._parsedProps.row,col:this._parsedProps.col,cellWidth:this._parsedProps.cellWidth,cellHeight:this._parsedProps.cellHeight,boardGap}),panelGlobalPos=this._getGlobalPcbPositionBeforeLayout();for(let{board,pos}of positions){let absoluteX=panelGlobalPos.x+pos.x,absoluteY=panelGlobalPos.y+pos.y;board._repositionOnPcb({x:absoluteX,y:absoluteY}),db.pcb_board.update(board.pcb_board_id,{center:{x:absoluteX,y:absoluteY}})}let hasExplicitWidth=this._parsedProps.width!==void 0,hasExplicitHeight=this._parsedProps.height!==void 0;if(hasExplicitWidth&&hasExplicitHeight)db.pcb_panel.update(this.pcb_panel_id,{width:distance.parse(this._parsedProps.width),height:distance.parse(this._parsedProps.height)});else if(gridWidth>0||gridHeight>0){let{edgePadding:edgePaddingProp,edgePaddingLeft:edgePaddingLeftProp,edgePaddingRight:edgePaddingRightProp,edgePaddingTop:edgePaddingTopProp,edgePaddingBottom:edgePaddingBottomProp}=this._parsedProps,edgePadding=distance.parse(edgePaddingProp??5),edgePaddingLeft=distance.parse(edgePaddingLeftProp??edgePadding),edgePaddingRight=distance.parse(edgePaddingRightProp??edgePadding),edgePaddingTop=distance.parse(edgePaddingTopProp??edgePadding),edgePaddingBottom=distance.parse(edgePaddingBottomProp??edgePadding);db.pcb_panel.update(this.pcb_panel_id,{width:hasExplicitWidth?distance.parse(this._parsedProps.width):gridWidth+edgePaddingLeft+edgePaddingRight,height:hasExplicitHeight?distance.parse(this._parsedProps.height):gridHeight+edgePaddingTop+edgePaddingBottom})}}if(this._tabsAndMouseBitesGenerated)return;let props=this._parsedProps;if((props.panelizationMethod??"none")!=="none"){let childBoardIds=childBoardInstances.map(c3=>c3.pcb_board_id).filter(id=>!!id),boardsInPanel=db.pcb_board.list().filter(b3=>childBoardIds.includes(b3.pcb_board_id));if(boardsInPanel.length===0)return;let tabWidth=props.tabWidth??DEFAULT_TAB_WIDTH,boardGap=props.boardGap??tabWidth,{tabCutouts,mouseBiteHoles}=generatePanelTabsAndMouseBites(boardsInPanel,{boardGap,tabWidth,tabLength:props.tabLength??DEFAULT_TAB_LENGTH,mouseBites:props.mouseBites??!0});for(let tabCutout of tabCutouts)db.pcb_cutout.insert(tabCutout);for(let mouseBiteHole of mouseBiteHoles)db.pcb_hole.insert(mouseBiteHole)}this._tabsAndMouseBitesGenerated=!0}runRenderCycle(){if(!this.children.some(child=>child.componentName==="Board"))throw new Error("<panel> must contain at least one <board>");super.runRenderCycle()}doInitialPcbComponentRender(){if(super.doInitialPcbComponentRender(),this.root?.pcbDisabled)return;let{db}=this.root,props=this._parsedProps,inserted=db.pcb_panel.insert({width:props.width!==void 0?distance.parse(props.width):0,height:props.height!==void 0?distance.parse(props.height):0,center:this._getGlobalPcbPositionBeforeLayout(),covered_with_solder_mask:!(props.noSolderMask??!1)});this.pcb_panel_id=inserted.pcb_panel_id}updatePcbComponentRender(){if(this.root?.pcbDisabled||!this.pcb_panel_id)return;let{db}=this.root,props=this._parsedProps,currentPanel=db.pcb_panel.get(this.pcb_panel_id);db.pcb_panel.update(this.pcb_panel_id,{width:props.width!==void 0?distance.parse(props.width):currentPanel?.width,height:props.height!==void 0?distance.parse(props.height):currentPanel?.height,center:this._getGlobalPcbPositionBeforeLayout(),covered_with_solder_mask:!(props.noSolderMask??!1)})}removePcbComponentRender(){this.pcb_panel_id&&(this.root?.db.pcb_panel.delete(this.pcb_panel_id),this.pcb_panel_id=null)}},Pinout=class extends Chip{constructor(props){super(props)}get config(){return{...super.config,componentName:"Pinout",zodProps:pinoutProps}}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,source_component=db.source_component.insert({ftype:"simple_pinout",name:this.name,manufacturer_part_number:props.manufacturerPartNumber,supplier_part_numbers:props.supplierPartNumbers});this.source_component_id=source_component.source_component_id}},Fuse=class extends NormalComponent3{get config(){return{componentName:"fuse",schematicSymbolName:this.props.symbolName??"fuse",zodProps:fuseProps,sourceFtype:FTYPE.simple_fuse}}_getSchematicSymbolDisplayValue(){let rawCurrent=this._parsedProps.currentRating,rawVoltage=this._parsedProps.voltageRating,current2=typeof rawCurrent=="string"?parseFloat(rawCurrent):rawCurrent,voltage2=typeof rawVoltage=="string"?parseFloat(rawVoltage):rawVoltage;return`${formatSiUnit(current2)}A / ${formatSiUnit(voltage2)}V`}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,currentRating=typeof props.currentRating=="string"?parseFloat(props.currentRating):props.currentRating,voltageRating=typeof props.voltageRating=="string"?parseFloat(props.voltageRating):props.voltageRating,source_component=db.source_component.insert({name:this.name,ftype:FTYPE.simple_fuse,current_rating_amps:currentRating,voltage_rating_volts:voltageRating,display_current_rating:`${formatSiUnit(currentRating)}A`,display_voltage_rating:`${formatSiUnit(voltageRating)}V`});this.source_component_id=source_component.source_component_id}},Jumper=class extends NormalComponent3{constructor(){super(...arguments);__publicField(this,"schematicDimensions",null)}get config(){return{schematicSymbolName:void 0,componentName:"Jumper",zodProps:jumperProps,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let arrangement=super._getSchematicPortArrangement();if(arrangement&&Object.keys(arrangement).length>0)return arrangement;let pinCount=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length),direction2=this._parsedProps.schDirection??"right";return{leftSize:direction2==="left"?pinCount:0,rightSize:direction2==="right"?pinCount:0}}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,{pcbX,pcbY}=this.getResolvedPcbPositionProp(),source_component=db.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:props.manufacturerPartNumber,supplier_part_numbers:props.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=source_component.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,{pcbX,pcbY}=this.getResolvedPcbPositionProp(),pcb_component2=db.pcb_component.insert({center:{x:pcbX,y:pcbY},width:2,height:3,layer:props.layer??"top",rotation:props.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:props.doNotPlace??!1,obstructs_within_bounds:props.obstructsWithinBounds??!0});this.pcb_component_id=pcb_component2.pcb_component_id}doInitialPcbTraceRender(){let{db}=this.root,pcb_ports=db.pcb_port.list({pcb_component_id:this.pcb_component_id}),pinLabelToPortId={};for(let i3=0;i3<pcb_ports.length;i3++){let port=pcb_ports[i3],sourcePort=db.source_port.get(port.source_port_id),pinLabel="";if(typeof sourcePort?.pin_number=="number")pinLabel=sourcePort.pin_number.toString();else if(Array.isArray(sourcePort?.port_hints)){let matchedHint=sourcePort.port_hints.find(h3=>/^(pin)?\d+$/.test(h3));matchedHint&&(/^pin\d+$/.test(matchedHint)?pinLabel=matchedHint.replace(/^pin/,""):pinLabel=matchedHint)}pinLabelToPortId[pinLabel]=port.pcb_port_id}let traces=db.pcb_trace.list({pcb_component_id:this.pcb_component_id}),updatePortId=portId=>{if(portId&&typeof portId=="string"&&portId.startsWith("{PIN")){let pin=portId.replace("{PIN","").replace("}","");return pinLabelToPortId[pin]||portId}return portId};for(let trace of traces)if(trace.route)for(let segment2 of trace.route)segment2.route_type==="wire"&&(segment2.start_pcb_port_id=updatePortId(segment2.start_pcb_port_id),segment2.end_pcb_port_id=updatePortId(segment2.end_pcb_port_id))}},INTERCONNECT_STANDARD_FOOTPRINTS={"0402":"0402","0603":"0603","0805":"0805",1206:"1206"},Interconnect=class extends NormalComponent3{get config(){return{componentName:"Interconnect",zodProps:interconnectProps,shouldRenderAsSchematicBox:!0,sourceFtype:"interconnect"}}get defaultInternallyConnectedPinNames(){let{standard}=this._parsedProps;return standard&&INTERCONNECT_STANDARD_FOOTPRINTS[standard]?[["pin1","pin2"]]:[]}_getImpliedFootprintString(){let{standard}=this._parsedProps;return standard?INTERCONNECT_STANDARD_FOOTPRINTS[standard]??null:null}doInitialSourceRender(){let{db}=this.root,source_component=db.source_component.insert({ftype:"interconnect",name:this.name,are_pins_interchangeable:!0});this.source_component_id=source_component.source_component_id}doInitialSourceParentAttachment(){let{db}=this.root,internallyConnectedPorts=this._getInternallyConnectedPins();for(let ports of internallyConnectedPorts){let sourcePortIds=ports.map(port=>port.source_port_id).filter(id=>id!==null);sourcePortIds.length>=2&&db.source_component_internal_connection.insert({source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id,source_port_ids:sourcePortIds})}}},SolderJumper=class extends NormalComponent3{constructor(){super(...arguments);__publicField(this,"schematicDimensions",null)}_getPinNumberFromBridgedPinName(pinName){return this.selectOne(`port.${pinName}`,{type:"port"})?._parsedProps.pinNumber??null}get defaultInternallyConnectedPinNames(){if(this._parsedProps.bridged){let pins=this.children.filter(c3=>c3.componentName==="Port").map(p4=>p4.name);return pins.length>0?[pins]:[]}return this._parsedProps.bridgedPins??[]}get config(){let props=this._parsedProps??this.props,resolvedPinCount=props.pinCount;if(props.pinCount==null&&!props.footprint&&(resolvedPinCount=2),props.pinCount==null){let nums=(props.bridgedPins??[]).flat().map(p_str=>this._getPinNumberFromBridgedPinName(p_str)).filter(n3=>n3!==null),maxPinFromBridged=nums.length>0?Math.max(...nums):0,pinCountFromLabels=props.pinLabels?Object.keys(props.pinLabels).length:0,finalPinCount=Math.max(maxPinFromBridged,pinCountFromLabels);(finalPinCount===2||finalPinCount===3)&&(resolvedPinCount=finalPinCount),resolvedPinCount==null&&props.footprint&&[2,3].includes(this.getPortsFromFootprint().length)&&(resolvedPinCount=this.getPortsFromFootprint().length)}let symbolName="";resolvedPinCount?symbolName+=`solderjumper${resolvedPinCount}`:symbolName="solderjumper";let bridgedPinNumbers=[];return Array.isArray(props.bridgedPins)&&props.bridgedPins.length>0?bridgedPinNumbers=Array.from(new Set(props.bridgedPins.flat().map(pinName=>this._getPinNumberFromBridgedPinName(pinName)).filter(n3=>n3!==null))).sort((a3,b3)=>a3-b3):props.bridged&&resolvedPinCount&&(bridgedPinNumbers=Array.from({length:resolvedPinCount},(_4,i3)=>i3+1)),bridgedPinNumbers.length>0&&(symbolName+=`_bridged${bridgedPinNumbers.join("")}`),{schematicSymbolName:props.symbolName??symbolName,componentName:"SolderJumper",zodProps:solderjumperProps,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let arrangement=super._getSchematicPortArrangement();if(arrangement&&Object.keys(arrangement).length>0)return arrangement;let pinCount=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length);pinCount==null&&!this._parsedProps.footprint&&(pinCount=2);let direction2=this._parsedProps.schDirection??"right";return{leftSize:direction2==="left"?pinCount:0,rightSize:direction2==="right"?pinCount:0}}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,{pcbX,pcbY}=this.getResolvedPcbPositionProp(),source_component=db.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:props.manufacturerPartNumber,supplier_part_numbers:props.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=source_component.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,{pcbX,pcbY}=this.getResolvedPcbPositionProp(),pcb_component2=db.pcb_component.insert({center:{x:pcbX,y:pcbY},width:2,height:3,layer:props.layer??"top",rotation:props.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:props.doNotPlace??!1,obstructs_within_bounds:props.obstructsWithinBounds??!0});this.pcb_component_id=pcb_component2.pcb_component_id}doInitialPcbTraceRender(){let{db}=this.root,pcb_ports=db.pcb_port.list({pcb_component_id:this.pcb_component_id}),pinLabelToPortId={};for(let i3=0;i3<pcb_ports.length;i3++){let port=pcb_ports[i3],sourcePort=db.source_port.get(port.source_port_id),pinLabel="";if(typeof sourcePort?.pin_number=="number")pinLabel=sourcePort.pin_number.toString();else if(Array.isArray(sourcePort?.port_hints)){let matchedHint=sourcePort.port_hints.find(h3=>/^(pin)?\d+$/.test(h3));matchedHint&&(/^pin\d+$/.test(matchedHint)?pinLabel=matchedHint.replace(/^pin/,""):pinLabel=matchedHint)}pinLabelToPortId[pinLabel]=port.pcb_port_id}let traces=db.pcb_trace.list({pcb_component_id:this.pcb_component_id}),updatePortId=portId=>{if(portId&&typeof portId=="string"&&portId.startsWith("{PIN")){let pin=portId.replace("{PIN","").replace("}","");return pinLabelToPortId[pin]||portId}return portId};for(let trace of traces)if(trace.route)for(let segment2 of trace.route)segment2.route_type==="wire"&&(segment2.start_pcb_port_id=updatePortId(segment2.start_pcb_port_id),segment2.end_pcb_port_id=updatePortId(segment2.end_pcb_port_id))}},Led=class extends NormalComponent3{constructor(){super(...arguments);__publicField(this,"pos",this.portMap.pin1);__publicField(this,"anode",this.portMap.pin1);__publicField(this,"neg",this.portMap.pin2);__publicField(this,"cathode",this.portMap.pin2)}get config(){let symbolMap={laser:"laser_diode"},variantSymbol=this.props.laser?"laser":null;return{schematicSymbolName:variantSymbol?symbolMap[variantSymbol]:this.props.symbolName??"led",componentName:"Led",zodProps:ledProps,sourceFtype:"simple_led"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return this._parsedProps.schDisplayValue||this._parsedProps.color||void 0}getFootprinterString(){let baseFootprint=super.getFootprinterString();return baseFootprint&&this.props.color?`${baseFootprint}_color(${this.props.color})`:baseFootprint}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,source_component=db.source_component.insert({ftype:"simple_led",name:this.name,wave_length:props.wavelength,color:props.color,symbol_display_value:this._getSchematicSymbolDisplayValue(),manufacturer_part_number:props.manufacturerPartNumber??props.mfn,supplier_part_numbers:props.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=source_component.source_component_id}},PowerSource=class extends NormalComponent3{constructor(){super(...arguments);__publicField(this,"pos",this.portMap.pin1);__publicField(this,"positive",this.portMap.pin1);__publicField(this,"neg",this.portMap.pin2);__publicField(this,"negative",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"power_factor_meter_horz",componentName:"PowerSource",zodProps:powerSourceProps,sourceFtype:"simple_power_source"}}initPorts(){this.add(new Port({name:"pin1",pinNumber:1,aliases:["positive","pos"]})),this.add(new Port({name:"pin2",pinNumber:2,aliases:["negative","neg"]}))}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,source_component=db.source_component.insert({ftype:"simple_power_source",name:this.name,voltage:props.voltage,supplier_part_numbers:props.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=source_component.source_component_id}},VoltageSource=class extends NormalComponent3{constructor(){super(...arguments);__publicField(this,"terminal1",this.portMap.terminal1);__publicField(this,"terminal2",this.portMap.terminal2)}get config(){return{componentName:"VoltageSource",schematicSymbolName:this.props.waveShape==="square"?"square_wave":"ac_voltmeter",zodProps:voltageSourceProps,sourceFtype:"simple_voltage_source"}}runRenderPhaseForChildren(phase){if(!phase.startsWith("Pcb"))for(let child of this.children)child.runRenderPhaseForChildren(phase),child.runRenderPhase(phase)}doInitialPcbComponentRender(){}initPorts(){super.initPorts({additionalAliases:{pin1:["terminal1"],pin2:["terminal2"]}})}_getSchematicSymbolDisplayValue(){let{voltage:voltage2,frequency:frequency2}=this._parsedProps,parts=[];return voltage2!==void 0&&parts.push(`${formatSiUnit(voltage2)}V`),frequency2!==void 0&&parts.push(`${formatSiUnit(frequency2)}Hz`),parts.length>0?parts.join(" "):void 0}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,source_component=db.source_component.insert({ftype:"simple_voltage_source",name:this.name,voltage:props.voltage,frequency:props.frequency,peak_to_peak_voltage:props.peakToPeakVoltage,wave_shape:props.waveShape,phase:props.phase,duty_cycle:props.dutyCycle,supplier_part_numbers:props.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=source_component.source_component_id}doInitialSimulationRender(){let{db}=this.root,{_parsedProps:props}=this,terminal1Port=this.portMap.terminal1,terminal2Port=this.portMap.terminal2;db.simulation_voltage_source.insert({type:"simulation_voltage_source",is_dc_source:!1,terminal1_source_port_id:terminal1Port.source_port_id,terminal2_source_port_id:terminal2Port.source_port_id,voltage:props.voltage,frequency:props.frequency,peak_to_peak_voltage:props.peakToPeakVoltage,wave_shape:props.waveShape,phase:props.phase,duty_cycle:props.dutyCycle})}},edgeSpecifiers=["leftedge","rightedge","topedge","bottomedge","center"],Constraint3=class extends PrimitiveComponent2{get config(){return{componentName:"Constraint",zodProps:constraintProps}}constructor(props){if(super(props),("xdist"in props||"ydist"in props)&&!("edgeToEdge"in props)&&!("centerToCenter"in props))throw new Error(`edgeToEdge, centerToCenter must be set for xDist or yDist for ${this}`);if("for"in props&&props.for.length<2)throw new Error(`"for" must have at least two selectors for ${this}`)}_getAllReferencedComponents(){let componentsWithSelectors=[],container=this.getPrimitiveContainer();function addComponentFromSelector(selector){let maybeEdge=selector.split(" ").pop(),edge=edgeSpecifiers.includes(maybeEdge)?maybeEdge:void 0,componentSelector=edge?selector.replace(` ${edge}`,""):selector,component=container.selectOne(componentSelector,{pcbPrimitive:!0});component&&componentsWithSelectors.push({selector,component,componentSelector,edge})}for(let key of["left","right","top","bottom"])key in this._parsedProps&&addComponentFromSelector(this._parsedProps[key]);if("for"in this._parsedProps)for(let selector of this._parsedProps.for)addComponentFromSelector(selector);return{componentsWithSelectors}}},FabricationNoteRect=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"fabrication_note_rect_id",null)}get config(){return{componentName:"FabricationNoteRect",zodProps:fabricationNoteRectProps}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,{pcbX,pcbY}=this.getResolvedPcbPositionProp(),{maybeFlipLayer}=this._getPcbPrimitiveFlippedHelpers(),layer=maybeFlipLayer(props.layer??"top");if(layer!=="top"&&layer!=="bottom")throw new Error(`Invalid layer "${layer}" for FabricationNoteRect. Must be "top" or "bottom".`);let pcb_component_id=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,subcircuit=this.getSubcircuit(),hasStroke=props.hasStroke??(props.strokeWidth!==void 0&&props.strokeWidth!==null),fabrication_note_rect=db.pcb_fabrication_note_rect.insert({pcb_component_id,layer,color:props.color,center:{x:pcbX,y:pcbY},width:props.width,height:props.height,stroke_width:props.strokeWidth??1,is_filled:props.isFilled??!1,has_stroke:hasStroke,is_stroke_dashed:props.isStrokeDashed??!1,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,corner_radius:props.cornerRadius??void 0});this.fabrication_note_rect_id=fabrication_note_rect.pcb_fabrication_note_rect_id}getPcbSize(){let{_parsedProps:props}=this;return{width:props.width,height:props.height}}},FabricationNotePath=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"fabrication_note_path_id",null)}get config(){return{componentName:"FabricationNotePath",zodProps:fabricationNotePathProps}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,subcircuit=this.getSubcircuit(),{_parsedProps:props}=this,layer=props.layer??"top";if(layer!=="top"&&layer!=="bottom")throw new Error(`Invalid layer "${layer}" for SilkscreenPath. Must be "top" or "bottom".`);let transform5=this._computePcbGlobalTransformBeforeLayout(),pcb_component_id=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,fabrication_note_path=db.pcb_fabrication_note_path.insert({pcb_component_id,layer,color:props.color,route:props.route.map(p4=>{let transformedPosition=applyToPoint(transform5,{x:p4.x,y:p4.y});return{...p4,x:transformedPosition.x,y:transformedPosition.y}}),stroke_width:props.strokeWidth??.1,subcircuit_id:subcircuit?.subcircuit_id??void 0});this.fabrication_note_path_id=fabrication_note_path.pcb_fabrication_note_path_id}},FabricationNoteText=class extends PrimitiveComponent2{get config(){return{componentName:"FabricationNoteText",zodProps:fabricationNoteTextProps}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,{pcbX,pcbY}=this.getResolvedPcbPositionProp(),container=this.getPrimitiveContainer(),subcircuit=this.getSubcircuit();db.pcb_fabrication_note_text.insert({anchor_alignment:props.anchorAlignment,anchor_position:{x:pcbX,y:pcbY},font:props.font??"tscircuit2024",font_size:props.fontSize??1,layer:"top",color:props.color,text:normalizeTextForCircuitJson(props.text??""),pcb_component_id:container.pcb_component_id,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}},FabricationNoteDimension=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"fabrication_note_dimension_id",null);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"FabricationNoteDimension",zodProps:fabricationNoteDimensionProps}}_resolvePoint(input2,transform5){if(typeof input2=="string"){let target=this.getSubcircuit().selectOne(input2);return target?target._getGlobalPcbPositionBeforeLayout():(this.renderError(`FabricationNoteDimension could not find selector "${input2}"`),applyToPoint(transform5,{x:0,y:0}))}let numericX=typeof input2.x=="string"?parseFloat(input2.x):input2.x,numericY=typeof input2.y=="string"?parseFloat(input2.y):input2.y;return applyToPoint(transform5,{x:numericX,y:numericY})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,transform5=this._computePcbGlobalTransformBeforeLayout(),from=this._resolvePoint(props.from,transform5),to2=this._resolvePoint(props.to,transform5),subcircuit=this.getSubcircuit(),group=this.getGroup(),{maybeFlipLayer}=this._getPcbPrimitiveFlippedHelpers(),layer=maybeFlipLayer(props.layer??"top");if(layer!=="top"&&layer!=="bottom")throw new Error(`Invalid layer "${layer}" for FabricationNoteDimension. Must be "top" or "bottom".`);let pcb_component_id=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,text=props.text??this._formatDistanceText({from,to:to2,units:props.units??"mm"}),fabrication_note_dimension=db.pcb_fabrication_note_dimension.insert({pcb_component_id,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:group?.pcb_group_id??void 0,layer,from,to:to2,text,offset:props.offset,font:props.font??"tscircuit2024",font_size:props.fontSize??1,color:props.color,arrow_size:props.arrowSize??1});this.fabrication_note_dimension_id=fabrication_note_dimension.pcb_fabrication_note_dimension_id}getPcbSize(){let transform5=this._computePcbGlobalTransformBeforeLayout(),from=this._resolvePoint(this._parsedProps.from,transform5),to2=this._resolvePoint(this._parsedProps.to,transform5);return{width:Math.abs(to2.x-from.x),height:Math.abs(to2.y-from.y)}}_formatDistanceText({from,to:to2,units}){let dx2=to2.x-from.x,dy2=to2.y-from.y,distanceInMillimeters=Math.sqrt(dx2*dx2+dy2*dy2),distanceInUnits=units==="in"?distanceInMillimeters/25.4:distanceInMillimeters,roundedDistance=Math.round(distanceInUnits);if(Math.abs(distanceInUnits-roundedDistance)<1e-9)return`${roundedDistance}${units}`;let decimalPlaces=units==="in"?3:2;return`${units==="in"?Number(distanceInUnits.toFixed(decimalPlaces)).toString():distanceInUnits.toFixed(decimalPlaces)}${units}`}},PcbNoteLine=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"pcb_note_line_id",null);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteLine",zodProps:pcbNoteLineProps}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,subcircuit=this.getSubcircuit(),group=this.getGroup(),transform5=this._computePcbGlobalTransformBeforeLayout(),start=applyToPoint(transform5,{x:props.x1,y:props.y1}),end=applyToPoint(transform5,{x:props.x2,y:props.y2}),pcb_component_id=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,pcb_note_line2=db.pcb_note_line.insert({pcb_component_id,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:group?.pcb_group_id??void 0,x1:start.x,y1:start.y,x2:end.x,y2:end.y,stroke_width:props.strokeWidth??.1,color:props.color,is_dashed:props.isDashed});this.pcb_note_line_id=pcb_note_line2.pcb_note_line_id}getPcbSize(){let{_parsedProps:props}=this;return{width:Math.abs(props.x2-props.x1),height:Math.abs(props.y2-props.y1)}}},PcbNoteRect=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"pcb_note_rect_id",null);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteRect",zodProps:pcbNoteRectProps}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,transform5=this._computePcbGlobalTransformBeforeLayout(),center2=applyToPoint(transform5,{x:0,y:0}),subcircuit=this.getSubcircuit(),group=this.getGroup(),pcb_component_id=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,pcb_note_rect2=db.pcb_note_rect.insert({pcb_component_id,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:group?.pcb_group_id??void 0,center:center2,width:props.width,height:props.height,stroke_width:props.strokeWidth??.1,is_filled:props.isFilled??!1,has_stroke:props.hasStroke??!0,is_stroke_dashed:props.isStrokeDashed??!1,color:props.color,corner_radius:props.cornerRadius??void 0});this.pcb_note_rect_id=pcb_note_rect2.pcb_note_rect_id}getPcbSize(){let{_parsedProps:props}=this,width=typeof props.width=="string"?parseFloat(props.width):props.width,height=typeof props.height=="string"?parseFloat(props.height):props.height;return{width,height}}},PcbNoteText=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"pcb_note_text_id",null);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteText",zodProps:pcbNoteTextProps}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,transform5=this._computePcbGlobalTransformBeforeLayout(),anchorPosition=applyToPoint(transform5,{x:0,y:0}),subcircuit=this.getSubcircuit(),group=this.getGroup(),pcb_component_id=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,pcb_note_text2=db.pcb_note_text.insert({pcb_component_id,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:group?.pcb_group_id??void 0,font:props.font??"tscircuit2024",font_size:props.fontSize??1,text:normalizeTextForCircuitJson(props.text),anchor_position:anchorPosition,anchor_alignment:props.anchorAlignment??"center",color:props.color});this.pcb_note_text_id=pcb_note_text2.pcb_note_text_id}getPcbSize(){let{_parsedProps:props}=this,fontSize=typeof props.fontSize=="string"?parseFloat(props.fontSize):props.fontSize??1,charWidth=fontSize*.6;return{width:props.text.length*charWidth,height:fontSize}}},PcbNotePath=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"pcb_note_path_id",null);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNotePath",zodProps:pcbNotePathProps}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,transform5=this._computePcbGlobalTransformBeforeLayout(),subcircuit=this.getSubcircuit(),group=this.getGroup(),pcb_component_id=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,transformedRoute=props.route.map(point23=>{let{x:x3,y:y3,...rest}=point23,numericX=typeof x3=="string"?parseFloat(x3):x3,numericY=typeof y3=="string"?parseFloat(y3):y3,transformed=applyToPoint(transform5,{x:numericX,y:numericY});return{...rest,x:transformed.x,y:transformed.y}}),pcb_note_path2=db.pcb_note_path.insert({pcb_component_id,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:group?.pcb_group_id??void 0,route:transformedRoute,stroke_width:props.strokeWidth??.1,color:props.color});this.pcb_note_path_id=pcb_note_path2.pcb_note_path_id}getPcbSize(){let{_parsedProps:props}=this;if(props.route.length===0)return{width:0,height:0};let xs3=props.route.map(point23=>typeof point23.x=="string"?parseFloat(point23.x):point23.x),ys3=props.route.map(point23=>typeof point23.y=="string"?parseFloat(point23.y):point23.y),minX=Math.min(...xs3),maxX=Math.max(...xs3),minY=Math.min(...ys3),maxY=Math.max(...ys3);return{width:maxX-minX,height:maxY-minY}}},PcbNoteDimension=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"pcb_note_dimension_id",null);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteDimension",zodProps:pcbNoteDimensionProps}}_resolvePoint(input2,transform5){if(typeof input2=="string"){let target=this.getSubcircuit().selectOne(`.${input2}`);return target?target._getGlobalPcbPositionBeforeLayout():(this.renderError(`PcbNoteDimension could not find selector "${input2}"`),applyToPoint(transform5,{x:0,y:0}))}let numericX=typeof input2.x=="string"?parseFloat(input2.x):input2.x,numericY=typeof input2.y=="string"?parseFloat(input2.y):input2.y;return applyToPoint(transform5,{x:numericX,y:numericY})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,transform5=this._computePcbGlobalTransformBeforeLayout(),from=this._resolvePoint(props.from,transform5),to2=this._resolvePoint(props.to,transform5),subcircuit=this.getSubcircuit(),group=this.getGroup(),pcb_component_id=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,text=props.text??this._formatDistanceText({from,to:to2,units:props.units??"mm"}),pcb_note_dimension2=db.pcb_note_dimension.insert({pcb_component_id,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:group?.pcb_group_id??void 0,from,to:to2,text,font:props.font??"tscircuit2024",font_size:props.fontSize??1,color:props.color,arrow_size:props.arrowSize??1});this.pcb_note_dimension_id=pcb_note_dimension2.pcb_note_dimension_id}getPcbSize(){let transform5=this._computePcbGlobalTransformBeforeLayout(),from=this._resolvePoint(this._parsedProps.from,transform5),to2=this._resolvePoint(this._parsedProps.to,transform5);return{width:Math.abs(to2.x-from.x),height:Math.abs(to2.y-from.y)}}_formatDistanceText({from,to:to2,units}){let dx2=to2.x-from.x,dy2=to2.y-from.y,distanceInMillimeters=Math.sqrt(dx2*dx2+dy2*dy2),distanceInUnits=units==="in"?distanceInMillimeters/25.4:distanceInMillimeters,roundedDistance=Math.round(distanceInUnits);if(Math.abs(distanceInUnits-roundedDistance)<1e-9)return`${roundedDistance}${units}`;let decimalPlaces=units==="in"?3:2;return`${units==="in"?Number(distanceInUnits.toFixed(decimalPlaces)).toString():distanceInUnits.toFixed(decimalPlaces)}${units}`}},Subcircuit=class extends Group6{constructor(props){super({...props,subcircuit:!0})}doInitialInflateSubcircuitCircuitJson(){let{circuitJson,children}=this._parsedProps;inflateCircuitJson(this,circuitJson,children)}},Breakout=class extends Group6{constructor(props){super({...props,subcircuit:!0})}doInitialPcbPrimitiveRender(){if(super.doInitialPcbPrimitiveRender(),this.root?.pcbDisabled)return;let{db}=this.root,props=this._parsedProps;if(!this.pcb_group_id)return;let pcb_group2=db.pcb_group.get(this.pcb_group_id),padLeft=props.paddingLeft??props.padding??0,padRight=props.paddingRight??props.padding??0,padTop=props.paddingTop??props.padding??0,padBottom=props.paddingBottom??props.padding??0;db.pcb_group.update(this.pcb_group_id,{width:(pcb_group2.width??0)+padLeft+padRight,height:(pcb_group2.height??0)+padTop+padBottom,center:{x:pcb_group2.center.x+(padRight-padLeft)/2,y:pcb_group2.center.y+(padTop-padBottom)/2}})}},BreakoutPoint=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"pcb_breakout_point_id",null);__publicField(this,"matchedPort",null);__publicField(this,"matchedNet",null);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"BreakoutPoint",zodProps:breakoutPointProps}}_matchConnection(){let{connection}=this._parsedProps,subcircuit=this.getSubcircuit();subcircuit&&(this.matchedPort=subcircuit.selectOne(connection,{type:"port"}),this.matchedPort||(this.matchedNet=subcircuit.selectOne(connection,{type:"net"})),!this.matchedPort&&!this.matchedNet&&this.renderError(`Could not find connection target "${connection}"`))}_getSourceTraceIdForPort(port){let{db}=this.root;return db.source_trace.list().find(st3=>st3.connected_source_port_ids.includes(port.source_port_id))?.source_trace_id}_getSourceNetIdForPort(port){let{db}=this.root;return db.source_trace.list().find(st3=>st3.connected_source_port_ids.includes(port.source_port_id))?.connected_source_net_ids[0]}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root;this._matchConnection();let{pcbX,pcbY}=this.getResolvedPcbPositionProp(),group=this.parent?.getGroup(),subcircuit=this.getSubcircuit();if(!group||!group.pcb_group_id)return;let pcb_breakout_point2=db.pcb_breakout_point.insert({pcb_group_id:group.pcb_group_id,subcircuit_id:subcircuit?.subcircuit_id??void 0,source_port_id:this.matchedPort?.source_port_id??void 0,source_trace_id:this.matchedPort?this._getSourceTraceIdForPort(this.matchedPort):void 0,source_net_id:this.matchedNet?this.matchedNet.source_net_id:this.matchedPort?this._getSourceNetIdForPort(this.matchedPort):void 0,x:pcbX,y:pcbY});this.pcb_breakout_point_id=pcb_breakout_point2.pcb_breakout_point_id}_getPcbCircuitJsonBounds(){let{pcbX,pcbY}=this.getResolvedPcbPositionProp();return{center:{x:pcbX,y:pcbY},bounds:{left:pcbX,top:pcbY,right:pcbX,bottom:pcbY},width:0,height:0}}_setPositionFromLayout(newCenter){let{db}=this.root;this.pcb_breakout_point_id&&db.pcb_breakout_point.update(this.pcb_breakout_point_id,{x:newCenter.x,y:newCenter.y})}getPcbSize(){return{width:0,height:0}}},NetLabel=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"source_net_label_id")}get config(){return{componentName:"NetLabel",zodProps:netLabelProps}}_getAnchorSide(){let{_parsedProps:props}=this;if(props.anchorSide)return props.anchorSide;if(!this._resolveConnectsTo())return"right";let anchorPos=this._getGlobalSchematicPositionBeforeLayout(),connectedPorts=this._getConnectedPorts();if(connectedPorts.length===0)return"right";let connectedPortPosition=connectedPorts[0]._getGlobalSchematicPositionBeforeLayout(),dx2=connectedPortPosition.x-anchorPos.x,dy2=connectedPortPosition.y-anchorPos.y;if(Math.abs(dx2)>Math.abs(dy2)){if(dx2>0)return"right";if(dx2<0)return"left"}else{if(dy2>0)return"top";if(dy2<0)return"bottom"}return"right"}_getConnectedPorts(){let connectsTo=this._resolveConnectsTo();if(!connectsTo)return[];let connectedPorts=[];for(let connection of connectsTo){let port=this.getSubcircuit().selectOne(connection);port&&connectedPorts.push(port)}return connectedPorts}computeSchematicPropsTransform(){let{_parsedProps:props}=this;if(props.schX===void 0&&props.schY===void 0){let connectedPorts=this._getConnectedPorts();if(connectedPorts.length>0){let portPos=connectedPorts[0]._getGlobalSchematicPositionBeforeLayout(),parentCenter=applyToPoint(this.parent?.computeSchematicGlobalTransform?.()??identity(),{x:0,y:0});return translate(portPos.x-parentCenter.x,portPos.y-parentCenter.y)}}return super.computeSchematicPropsTransform()}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db}=this.root,{_parsedProps:props}=this,anchorPos=this._getGlobalSchematicPositionBeforeLayout(),net=this.getSubcircuit().selectOne(`net.${this._getNetName()}`),anchorSide=props.anchorSide??"right",center2=computeSchematicNetLabelCenter({anchor_position:anchorPos,anchor_side:anchorSide,text:props.net}),netLabel=db.schematic_net_label.insert({text:props.net,source_net_id:net.source_net_id,anchor_position:anchorPos,center:center2,anchor_side:this._getAnchorSide()});this.source_net_label_id=netLabel.source_net_id}_resolveConnectsTo(){let{_parsedProps:props}=this,connectsTo=props.connectsTo??props.connection;if(Array.isArray(connectsTo))return connectsTo;if(typeof connectsTo=="string")return[connectsTo]}_getNetName(){let{_parsedProps:props}=this;return props.net}doInitialCreateNetsFromProps(){let{_parsedProps:props}=this;props.net&&createNetsFromProps(this,[`net.${props.net}`])}doInitialCreateTracesFromNetLabels(){if(this.root?.schematicDisabled)return;let connectsTo=this._resolveConnectsTo();if(connectsTo)for(let connection of connectsTo)this.add(new Trace3({from:connection,to:`net.${this._getNetName()}`}))}doInitialSchematicTraceRender(){if(!this.root?._featureMspSchematicTraceRouting||this.root?.schematicDisabled)return;let{db}=this.root,connectsTo=this._resolveConnectsTo();if(!connectsTo||connectsTo.length===0)return;let anchorPos=this._getGlobalSchematicPositionBeforeLayout(),anchorSide=this._getAnchorSide(),anchorFacing={left:"x-",right:"x+",top:"y+",bottom:"y-"}[anchorSide],net=this.getSubcircuit().selectOne(`net.${this._getNetName()}`);for(let connection of connectsTo){let port=this.getSubcircuit().selectOne(connection,{type:"port"});if(!port||!port.schematic_port_id)continue;let existingTraceForThisConnection=!1;if(net?.source_net_id){let candidateSourceTrace=db.source_trace.list().find(st3=>st3.connected_source_net_ids?.includes(net.source_net_id)&&st3.connected_source_port_ids?.includes(port.source_port_id??""));if(candidateSourceTrace&&(existingTraceForThisConnection=db.schematic_trace.list().some(t6=>t6.source_trace_id===candidateSourceTrace.source_trace_id)),existingTraceForThisConnection)continue}let portPos=port._getGlobalSchematicPositionAfterLayout(),portFacing=convertFacingDirectionToElbowDirection(port.facingDirection??"right")??"x+",path=calculateElbow({x:portPos.x,y:portPos.y,facingDirection:portFacing},{x:anchorPos.x,y:anchorPos.y,facingDirection:anchorFacing});if(!Array.isArray(path)||path.length<2)continue;let edges=[];for(let i3=0;i3<path.length-1;i3++)edges.push({from:{x:path[i3].x,y:path[i3].y},to:{x:path[i3+1].x,y:path[i3+1].y}});let source_trace_id,subcircuit_connectivity_map_key;if(net?.source_net_id&&port.source_port_id){let st3=db.source_trace.list().find(s4=>s4.connected_source_net_ids?.includes(net.source_net_id)&&s4.connected_source_port_ids?.includes(port.source_port_id));source_trace_id=st3?.source_trace_id,subcircuit_connectivity_map_key=st3?.subcircuit_connectivity_map_key||db.source_net.get(net.source_net_id)?.subcircuit_connectivity_map_key}db.schematic_trace.insert({source_trace_id,edges,junctions:[],subcircuit_connectivity_map_key}),db.schematic_port.update(port.schematic_port_id,{is_connected:!0})}}},SilkscreenCircle=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"pcb_silkscreen_circle_id",null);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenCircle",zodProps:silkscreenCircleProps}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,{pcbX,pcbY}=this.getResolvedPcbPositionProp(),{maybeFlipLayer}=this._getPcbPrimitiveFlippedHelpers(),layer=maybeFlipLayer(props.layer??"top");if(layer!=="top"&&layer!=="bottom")throw new Error(`Invalid layer "${layer}" for SilkscreenCircle. Must be "top" or "bottom".`);let transform5=this._computePcbGlobalTransformBeforeLayout(),subcircuit=this.getSubcircuit(),pcb_component_id=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,pcb_silkscreen_circle2=db.pcb_silkscreen_circle.insert({pcb_component_id,layer,center:{x:pcbX,y:pcbY},radius:props.radius,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,stroke_width:props.strokeWidth??.1});this.pcb_silkscreen_circle_id=pcb_silkscreen_circle2.pcb_silkscreen_circle_id}getPcbSize(){let{_parsedProps:props}=this,diameter=props.radius*2;return{width:diameter,height:diameter}}},SilkscreenRect=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"pcb_silkscreen_rect_id",null);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenRect",zodProps:silkscreenRectProps}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,{maybeFlipLayer}=this._getPcbPrimitiveFlippedHelpers(),layer=maybeFlipLayer(props.layer??"top");if(layer!=="top"&&layer!=="bottom")throw new Error(`Invalid layer "${layer}" for SilkscreenRect. Must be "top" or "bottom".`);let subcircuit=this.getSubcircuit(),position2=this._getGlobalPcbPositionBeforeLayout(),pcb_component_id=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,pcb_silkscreen_rect2=db.pcb_silkscreen_rect.insert({pcb_component_id,layer,center:{x:position2.x,y:position2.y},width:props.width,height:props.height,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this?.getGroup()?.pcb_group_id??void 0,stroke_width:props.strokeWidth??.1,is_filled:props.filled??!1,corner_radius:props.cornerRadius??void 0});this.pcb_silkscreen_rect_id=pcb_silkscreen_rect2.pcb_silkscreen_rect_id}getPcbSize(){let{_parsedProps:props}=this;return{width:props.width,height:props.height}}},SilkscreenLine=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"pcb_silkscreen_line_id",null);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenLine",zodProps:silkscreenLineProps}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,{maybeFlipLayer}=this._getPcbPrimitiveFlippedHelpers(),layer=maybeFlipLayer(props.layer??"top");if(layer!=="top"&&layer!=="bottom")throw new Error(`Invalid layer "${layer}" for SilkscreenLine. Must be "top" or "bottom".`);let subcircuit=this.getSubcircuit(),pcb_component_id=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,pcb_silkscreen_line2=db.pcb_silkscreen_line.insert({pcb_component_id,layer,x1:props.x1,y1:props.y1,x2:props.x2,y2:props.y2,stroke_width:props.strokeWidth??.1,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:subcircuit?.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_line_id=pcb_silkscreen_line2.pcb_silkscreen_line_id}getPcbSize(){let{_parsedProps:props}=this,width=Math.abs(props.x2-props.x1),height=Math.abs(props.y2-props.y1);return{width,height}}},Fiducial=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"pcb_smtpad_id",null);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Fiducial",zodProps:fiducialProps,sourceFtype:"simple_fiducial"}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,position2=this._getGlobalPcbPositionBeforeLayout(),{maybeFlipLayer}=this._getPcbPrimitiveFlippedHelpers(),pcb_component_id=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,pcb_smtpad2=db.pcb_smtpad.insert({pcb_component_id,layer:maybeFlipLayer(props.layer||"top"),shape:"circle",x:position2.x,y:position2.y,radius:distance.parse(props.padDiameter)/2,soldermask_margin:props.soldermaskPullback?distance.parse(props.soldermaskPullback):distance.parse(props.padDiameter)/2,is_covered_with_solder_mask:!0});this.pcb_smtpad_id=pcb_smtpad2.pcb_smtpad_id}getPcbSize(){let{_parsedProps:props}=this,d2=distance.parse(props.padDiameter);return{width:d2,height:d2}}_setPositionFromLayout(newCenter){if(!this.pcb_smtpad_id)return;let{db}=this.root;db.pcb_smtpad.update(this.pcb_smtpad_id,{x:newCenter.x,y:newCenter.y})}},Via=class extends PrimitiveComponent2{constructor(props){super(props);__publicField(this,"pcb_via_id",null);__publicField(this,"matchedPort",null);__publicField(this,"isPcbPrimitive",!0);__publicField(this,"source_manually_placed_via_id",null);__publicField(this,"subcircuit_connectivity_map_key",null);let layers=this._getLayers();this._parsedProps.layers=layers,this.initPorts()}get config(){return{componentName:"Via",zodProps:viaProps}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}_getResolvedViaDiameters(pcbStyle2){return getViaDiameterDefaultsWithOverrides({holeDiameter:this._parsedProps.holeDiameter,padDiameter:this._parsedProps.outerDiameter},pcbStyle2)}getPcbSize(){let pcbStyle2=this.getInheritedMergedProperty("pcbStyle"),{padDiameter}=this._getResolvedViaDiameters(pcbStyle2);return{width:padDiameter,height:padDiameter}}_getPcbCircuitJsonBounds(){let{db}=this.root,via=db.pcb_via.get(this.pcb_via_id),size2=this.getPcbSize();return{center:{x:via.x,y:via.y},bounds:{left:via.x-size2.width/2,top:via.y-size2.height/2,right:via.x+size2.width/2,bottom:via.y+size2.height/2},width:size2.width,height:size2.height}}_setPositionFromLayout(newCenter){let{db}=this.root;db.pcb_via.update(this.pcb_via_id,{x:newCenter.x,y:newCenter.y})}_getLayers(){let{fromLayer="top",toLayer="bottom"}=this._parsedProps;return fromLayer===toLayer?[fromLayer]:[fromLayer,toLayer]}initPorts(){let layers=this._parsedProps.layers;for(let layer of layers){let port2=new Port({name:layer,layer});port2.registerMatch(this),this.add(port2)}let port=new Port({name:"pin1"});port.registerMatch(this),this.add(port)}_getConnectedNetOrTrace(){let connectsTo=this._parsedProps.connectsTo;if(!connectsTo)return null;let subcircuit=this.getSubcircuit(),selectors=Array.isArray(connectsTo)?connectsTo:[connectsTo];for(let selector of selectors)if(selector.startsWith("net.")){let net=subcircuit.selectOne(selector,{type:"net"});if(net)return net}return null}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,pcbStyle2=this.getInheritedMergedProperty("pcbStyle"),{padDiameter}=this._getResolvedViaDiameters(pcbStyle2),position2=this._getGlobalPcbPositionBeforeLayout(),subcircuit=this.getSubcircuit(),pcb_component2=db.pcb_component.insert({center:position2,width:padDiameter,height:padDiameter,layer:this._parsedProps.fromLayer??"top",rotation:0,source_component_id:this.source_component_id,subcircuit_id:subcircuit?.subcircuit_id??void 0,obstructs_within_bounds:!0});this.pcb_component_id=pcb_component2.pcb_component_id}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,group=this.getGroup(),subcircuit=this.getSubcircuit(),source_via=db.source_manually_placed_via.insert({source_group_id:group?.source_group_id,source_net_id:props.net??"",subcircuit_id:subcircuit?.subcircuit_id??void 0});this.source_component_id=source_via.source_manually_placed_via_id}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,pcbStyle2=this.getInheritedMergedProperty("pcbStyle"),{holeDiameter,padDiameter}=this._getResolvedViaDiameters(pcbStyle2),position2=this._getGlobalPcbPositionBeforeLayout(),subcircuit=this.getSubcircuit(),pcb_via2=db.pcb_via.insert({x:position2.x,y:position2.y,hole_diameter:holeDiameter,outer_diameter:padDiameter,layers:["bottom","top"],from_layer:this._parsedProps.fromLayer||"bottom",to_layer:this._parsedProps.toLayer||"top",subcircuit_id:subcircuit?.subcircuit_id??void 0,subcircuit_connectivity_map_key:this.subcircuit_connectivity_map_key??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,net_is_assignable:this._parsedProps.netIsAssignable??void 0});this.pcb_via_id=pcb_via2.pcb_via_id}},CopperPour=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"CopperPour",zodProps:copperPourProps}}getPcbSize(){return{width:0,height:0}}doInitialCreateNetsFromProps(){let{_parsedProps:props}=this;createNetsFromProps(this,[props.connectsTo])}doInitialPcbCopperPourRender(){this.root?.pcbDisabled||this._queueAsyncEffect("PcbCopperPourRender",async()=>{let{db}=this.root,{_parsedProps:props}=this,net=this.getSubcircuit().selectOne(props.connectsTo);if(!net||!net.source_net_id){this.renderError(`Net "${props.connectsTo}" not found for copper pour`);return}let subcircuit=this.getSubcircuit(),sourceNet=db.toArray().filter(elm=>elm.type==="source_net"&&elm.name===net.name)[0]||"",clearance=props.clearance??.2,inputProblem=convertCircuitJsonToInputProblem(db.toArray(),{layer:props.layer,pour_connectivity_key:sourceNet.subcircuit_connectivity_map_key||"",pad_margin:props.padMargin??clearance,trace_margin:props.traceMargin??clearance,board_edge_margin:props.boardEdgeMargin??clearance,cutout_margin:props.cutoutMargin??clearance}),solver=new CopperPourPipelineSolver(inputProblem);this.root.emit("solver:started",{solverName:"CopperPourPipelineSolver",solverParams:inputProblem,componentName:this.props.name});let{brep_shapes}=solver.getOutput(),coveredWithSolderMask=props.coveredWithSolderMask??!1;for(let brep_shape2 of brep_shapes)db.pcb_copper_pour.insert({shape:"brep",layer:props.layer,brep_shape:brep_shape2,source_net_id:net.source_net_id,subcircuit_id:subcircuit?.subcircuit_id??void 0,covered_with_solder_mask:coveredWithSolderMask})})}},CopperText=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"CopperText",zodProps:copperTextProps}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,container=this.getPrimitiveContainer(),position2=this._getGlobalPcbPositionBeforeLayout(),subcircuit=this.getSubcircuit();db.pcb_copper_text.insert({anchor_alignment:props.anchorAlignment,anchor_position:{x:position2.x,y:position2.y},font:"tscircuit2024",font_size:props.fontSize,layer:props.layer??"top",text:normalizeTextForCircuitJson(props.text),ccw_rotation:props.pcbRotation,is_mirrored:props.mirrored,is_knockout:props.knockout,pcb_component_id:container.pcb_component_id,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}},Battery=class extends NormalComponent3{get config(){return{componentName:"Battery",schematicSymbolName:this.props.symbolName??"battery",zodProps:batteryProps,sourceFtype:"simple_power_source"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,source_component=db.source_component.insert({name:this.name,ftype:"simple_power_source",capacity:props.capacity,supplier_part_numbers:props.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=source_component.source_component_id}},PinHeader=class extends NormalComponent3{_getPcbRotationBeforeLayout(){let orientationRotation=this.props.pcbOrientation==="vertical"?-90:0;return(super._getPcbRotationBeforeLayout()??0)+orientationRotation}get config(){return{componentName:"PinHeader",zodProps:pinHeaderProps,shouldRenderAsSchematicBox:!0}}_getImpliedFootprintString(){let pinCount=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:0),holeDiameter=this._parsedProps.holeDiameter,platedDiameter=this._parsedProps.platedDiameter,pitch=this._parsedProps.pitch,showSilkscreenPinLabels=this._parsedProps.showSilkscreenPinLabels,rows=this._parsedProps.doubleRow?2:1;if(pinCount>0){let footprintString;if(pitch)!holeDiameter&&!platedDiameter?footprintString=`pinrow${pinCount}_p${pitch}`:footprintString=`pinrow${pinCount}_p${pitch}_id${holeDiameter}_od${platedDiameter}`;else if(!holeDiameter&&!platedDiameter)footprintString=`pinrow${pinCount}`;else return null;return showSilkscreenPinLabels!==!0&&(footprintString+="_nopinlabels"),rows>1&&(footprintString+=`_rows${rows}`),footprintString}return null}initPorts(){let pinCount=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:1);for(let i3=1;i3<=pinCount;i3++){let rawLabel=Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels[i3-1]:this._parsedProps.pinLabels?.[`pin${i3}`];if(rawLabel){let primaryLabel=Array.isArray(rawLabel)?rawLabel[0]:rawLabel,otherLabels=Array.isArray(rawLabel)?rawLabel.slice(1):[];this.add(new Port({pinNumber:i3,name:primaryLabel,aliases:[`pin${i3}`,...otherLabels]}))}else this.add(new Port({pinNumber:i3,name:`pin${i3}`}))}}_getSchematicPortArrangement(){let pinCount=this._parsedProps.pinCount??1,facingDirection=this._parsedProps.schFacingDirection??this._parsedProps.facingDirection??"right",schPinArrangement=this._parsedProps.schPinArrangement;return facingDirection==="left"?{leftSide:{direction:schPinArrangement?.leftSide?.direction??"top-to-bottom",pins:schPinArrangement?.leftSide?.pins??Array.from({length:pinCount},(_4,i3)=>`pin${i3+1}`)}}:{rightSide:{direction:schPinArrangement?.rightSide?.direction??"top-to-bottom",pins:schPinArrangement?.rightSide?.pins??Array.from({length:pinCount},(_4,i3)=>`pin${i3+1}`)}}}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,source_component=db.source_component.insert({ftype:"simple_pin_header",name:this.name,supplier_part_numbers:props.supplierPartNumbers,pin_count:props.pinCount,gender:props.gender,are_pins_interchangeable:!0});this.source_component_id=source_component.source_component_id}};function getResonatorSymbolName(variant){switch(variant){case"two_ground_pins":return"crystal_4pin";case"ground_pin":return"resonator";case"no_ground":return"crystal";default:return"crystal"}}var Resonator=class extends NormalComponent3{get config(){return{componentName:"Resonator",schematicSymbolName:this.props.symbolName??getResonatorSymbolName(this.props.pinVariant),zodProps:resonatorProps,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,pinVariant=props.pinVariant||"no_ground",source_component=db.source_component.insert({ftype:"simple_resonator",name:this.name,frequency:props.frequency,load_capacitance:props.loadCapacitance,supplier_part_numbers:props.supplierPartNumbers,pin_variant:pinVariant,are_pins_interchangeable:pinVariant==="no_ground"||pinVariant==="ground_pin"});this.source_component_id=source_component.source_component_id}_getSchematicSymbolDisplayValue(){let freqDisplay=`${formatSiUnit(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${freqDisplay} / ${formatSiUnit(this._parsedProps.loadCapacitance)}F`:freqDisplay}};function getPotentiometerSymbolName(variant){switch(variant){case"three_pin":return"potentiometer3";case"two_pin":return"potentiometer2";default:return"potentiometer2"}}var Potentiometer=class extends NormalComponent3{get config(){return{componentName:"Potentiometer",schematicSymbolName:this.props.symbolName??getPotentiometerSymbolName(this.props.pinVariant),zodProps:potentiometerProps,shouldRenderAsSchematicBox:!1}}_getSchematicSymbolDisplayValue(){return`${formatSiUnit(this._parsedProps.maxResistance)}\u03A9`}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,pinVariant=props.pinVariant||"two_pin",source_component=db.source_component.insert({ftype:"simple_potentiometer",name:this.name,max_resistance:props.maxResistance,pin_variant:pinVariant,are_pins_interchangeable:pinVariant==="two_pin"});this.source_component_id=source_component.source_component_id}},PushButton=class extends NormalComponent3{get config(){return{componentName:"PushButton",schematicSymbolName:this.props.symbolName??"push_button_normally_open_momentary",zodProps:pushButtonProps,sourceFtype:FTYPE.simple_push_button}}get defaultInternallyConnectedPinNames(){return[]}initPorts(){super.initPorts({pinCount:2,ignoreSymbolPorts:!0});let symbol=ef[this._getSchematicSymbolNameOrThrow()],symPort1=symbol.ports.find(p4=>p4.labels.includes("1")),symPort2=symbol.ports.find(p4=>p4.labels.includes("2")),ports=this.selectAll("port"),pin1Port=ports.find(p4=>p4.props.pinNumber===1),pin2Port=ports.find(p4=>p4.props.pinNumber===2),pin3Port=ports.find(p4=>p4.props.pinNumber===3),pin4Port=ports.find(p4=>p4.props.pinNumber===4),{internallyConnectedPins}=this._parsedProps;pin1Port.schematicSymbolPortDef=symPort1,(!internallyConnectedPins||internallyConnectedPins.length===0)&&(pin2Port.schematicSymbolPortDef=symPort2);for(let[pn3,port]of[[2,pin2Port],[3,pin3Port],[4,pin4Port]]){let internallyConnectedRow=internallyConnectedPins?.find(([pin1,pin2])=>pin1===`pin${pn3}`||pin2===`pin${pn3}`);if(!internallyConnectedRow){port.schematicSymbolPortDef=symPort2;break}(internallyConnectedRow?.[0]===`pin${pn3}`?internallyConnectedRow[1]:internallyConnectedRow?.[0])!=="pin1"&&(port.schematicSymbolPortDef=symPort2)}}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,source_component=db.source_component.insert({name:this.name,ftype:FTYPE.simple_push_button,supplier_part_numbers:props.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=source_component.source_component_id}},Crystal=class extends NormalComponent3{get config(){return{schematicSymbolName:this.props.symbolName??(this.props.pinVariant==="four_pin"?"crystal_4pin":"crystal"),componentName:"Crystal",zodProps:crystalProps,sourceFtype:"simple_crystal"}}initPorts(){let additionalAliases=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})}_getSchematicSymbolDisplayValue(){let freqDisplay=`${formatSiUnit(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${freqDisplay} / ${formatSiUnit(this._parsedProps.loadCapacitance)}F`:freqDisplay}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,source_component=db.source_component.insert({name:this.name,ftype:"simple_crystal",frequency:props.frequency,load_capacitance:props.loadCapacitance,pin_variant:props.pinVariant||"two_pin",are_pins_interchangeable:(props.pinVariant||"two_pin")==="two_pin"});this.source_component_id=source_component.source_component_id}},Mosfet=class extends NormalComponent3{get config(){let mosfetMode=this.props.mosfetMode==="depletion"?"d":"e",baseSymbolName=`${this.props.channelType}_channel_${mosfetMode}_mosfet_transistor`;return{componentName:"Mosfet",schematicSymbolName:this.props.symbolName??baseSymbolName,zodProps:mosfetProps,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,source_component=db.source_component.insert({ftype:"simple_mosfet",name:this.name,mosfet_mode:props.mosfetMode,channel_type:props.channelType});this.source_component_id=source_component.source_component_id}};function hasSimProps(props){return props.simSwitchFrequency!==void 0||props.simCloseAt!==void 0||props.simOpenAt!==void 0||props.simStartClosed!==void 0||props.simStartOpen!==void 0}var Switch=class extends NormalComponent3{_getSwitchType(){let props=this._parsedProps;return props?props.dpdt?"dpdt":props.spst?"spst":props.spdt?"spdt":props.dpst?"dpst":props.type??"spst":"spst"}get config(){let switchType=this._getSwitchType(),isNormallyClosed=this._parsedProps?.isNormallyClosed??!1,symbolMap={spst:isNormallyClosed?"spst_normally_closed_switch":"spst_switch",spdt:isNormallyClosed?"spdt_normally_closed_switch":"spdt_switch",dpst:isNormallyClosed?"dpst_normally_closed_switch":"dpst_switch",dpdt:isNormallyClosed?"dpdt_normally_closed_switch":"dpdt_switch"};return{componentName:"Switch",schematicSymbolName:this.props.symbolName??symbolMap[switchType],zodProps:switchProps,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db}=this.root,props=this._parsedProps??{},source_component=db.source_component.insert({ftype:"simple_switch",name:this.name,are_pins_interchangeable:this._getSwitchType()==="spst"});this.source_component_id=source_component.source_component_id}doInitialSimulationRender(){let{_parsedProps:props}=this;if(!hasSimProps(props))return;let{db}=this.root,simulationSwitch={type:"simulation_switch",source_component_id:this.source_component_id||""};props.simSwitchFrequency!==void 0&&(simulationSwitch.switching_frequency=frequency.parse(props.simSwitchFrequency)),props.simCloseAt!==void 0&&(simulationSwitch.closes_at=ms.parse(props.simCloseAt)),props.simOpenAt!==void 0&&(simulationSwitch.opens_at=ms.parse(props.simOpenAt)),props.simStartOpen!==void 0&&(simulationSwitch.starts_closed=!props.simStartOpen),props.simStartClosed!==void 0&&(simulationSwitch.starts_closed=props.simStartClosed),db.simulation_switch.insert(simulationSwitch)}},TESTPOINT_DEFAULTS={HOLE_DIAMETER:.5,SMT_CIRCLE_DIAMETER:1.2,SMT_RECT_SIZE:2},TestPoint=class extends NormalComponent3{get config(){return{componentName:"TestPoint",schematicSymbolName:this.props.symbolName??"testpoint",zodProps:testpointProps,sourceFtype:FTYPE.simple_test_point}}_getPropsWithDefaults(){let{padShape,holeDiameter,footprintVariant,padDiameter,width,height}=this._parsedProps;return!footprintVariant&&holeDiameter&&(footprintVariant="through_hole"),footprintVariant??(footprintVariant="through_hole"),padShape??(padShape="circle"),footprintVariant==="pad"?padShape==="circle"?padDiameter??(padDiameter=TESTPOINT_DEFAULTS.SMT_CIRCLE_DIAMETER):padShape==="rect"&&(width??(width=TESTPOINT_DEFAULTS.SMT_RECT_SIZE),height??(height=width)):footprintVariant==="through_hole"&&(holeDiameter??(holeDiameter=TESTPOINT_DEFAULTS.HOLE_DIAMETER)),{padShape,holeDiameter,footprintVariant,padDiameter,width,height}}_getImpliedFootprintString(){let{padShape,holeDiameter,footprintVariant,padDiameter,width,height}=this._getPropsWithDefaults();if(footprintVariant==="through_hole")return`platedhole_d${holeDiameter}`;if(footprintVariant==="pad"){if(padShape==="circle")return`smtpad_circle_d${padDiameter}`;if(padShape==="rect")return`smtpad_rect_w${width}_h${height}`}throw new Error(`Footprint variant "${footprintVariant}" with pad shape "${padShape}" not implemented`)}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,{padShape,holeDiameter,footprintVariant,padDiameter,width,height}=this._getPropsWithDefaults(),source_component=db.source_component.insert({ftype:FTYPE.simple_test_point,name:this.name,supplier_part_numbers:props.supplierPartNumbers,footprint_variant:footprintVariant,pad_shape:padShape,pad_diameter:padDiameter,hole_diameter:holeDiameter,width,height,are_pins_interchangeable:!0});this.source_component_id=source_component.source_component_id}},SchematicText=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicText",zodProps:schematicTextProps}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db}=this.root,{_parsedProps:props}=this,globalPos=this._getGlobalSchematicPositionBeforeLayout();db.schematic_text.insert({anchor:props.anchor??"center",text:normalizeTextForCircuitJson(props.text),font_size:props.fontSize,color:props.color||"#000000",position:{x:globalPos.x,y:globalPos.y},rotation:props.schRotation??0})}},SchematicLine=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"isSchematicPrimitive",!0);__publicField(this,"schematic_line_id")}get config(){return{componentName:"SchematicLine",zodProps:schematicLineProps}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db}=this.root,{_parsedProps:props}=this,globalPos=this._getGlobalSchematicPositionBeforeLayout(),schematic_component_id=this.getPrimitiveContainer()?.parent?.schematic_component_id,schematic_line2=db.schematic_line.insert({schematic_component_id,x1:props.x1+globalPos.x,y1:props.y1+globalPos.y,x2:props.x2+globalPos.x,y2:props.y2+globalPos.y,stroke_width:props.strokeWidth??SCHEMATIC_COMPONENT_OUTLINE_STROKE_WIDTH,color:props.color??SCHEMATIC_COMPONENT_OUTLINE_COLOR,is_dashed:!1,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_line_id=schematic_line2.schematic_line_id}},SchematicRect=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"isSchematicPrimitive",!0);__publicField(this,"schematic_rect_id")}get config(){return{componentName:"SchematicRect",zodProps:schematicRectProps}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db}=this.root,{_parsedProps:props}=this,globalPos=this._getGlobalSchematicPositionBeforeLayout(),schematic_component_id=this.getPrimitiveContainer()?.parent?.schematic_component_id,schematic_rect2=db.schematic_rect.insert({center:{x:globalPos.x,y:globalPos.y},width:props.width,height:props.height,stroke_width:props.strokeWidth??SCHEMATIC_COMPONENT_OUTLINE_STROKE_WIDTH,color:props.color??SCHEMATIC_COMPONENT_OUTLINE_COLOR,is_filled:props.isFilled,schematic_component_id,is_dashed:props.isDashed,rotation:props.rotation??0,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_rect_id=schematic_rect2.schematic_rect_id}},SchematicArc=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"isSchematicPrimitive",!0);__publicField(this,"schematic_arc_id")}get config(){return{componentName:"SchematicArc",zodProps:schematicArcProps}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db}=this.root,{_parsedProps:props}=this,globalPos=this._getGlobalSchematicPositionBeforeLayout(),schematic_component_id=this.getPrimitiveContainer()?.parent?.schematic_component_id,schematic_arc2=db.schematic_arc.insert({schematic_component_id,center:{x:props.center.x+globalPos.x,y:props.center.y+globalPos.y},radius:props.radius,start_angle_degrees:props.startAngleDegrees,end_angle_degrees:props.endAngleDegrees,direction:props.direction,stroke_width:props.strokeWidth??SCHEMATIC_COMPONENT_OUTLINE_STROKE_WIDTH,color:props.color??SCHEMATIC_COMPONENT_OUTLINE_COLOR,is_dashed:props.isDashed,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_arc_id=schematic_arc2.schematic_arc_id}},SchematicCircle=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"isSchematicPrimitive",!0);__publicField(this,"schematic_circle_id")}get config(){return{componentName:"SchematicCircle",zodProps:schematicCircleProps}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db}=this.root,{_parsedProps:props}=this,globalPos=this._getGlobalSchematicPositionBeforeLayout(),schematic_component_id=this.getPrimitiveContainer()?.parent?.schematic_component_id,schematic_circle2=db.schematic_circle.insert({schematic_component_id,center:{x:props.center.x+globalPos.x,y:props.center.y+globalPos.y},radius:props.radius,stroke_width:props.strokeWidth??SCHEMATIC_COMPONENT_OUTLINE_STROKE_WIDTH,color:props.color??SCHEMATIC_COMPONENT_OUTLINE_COLOR,is_filled:props.isFilled,fill_color:props.fillColor,is_dashed:props.isDashed,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_circle_id=schematic_circle2.schematic_circle_id}};function getTitleAnchorAndPosition({anchor,x:x3,y:y3,width,height,isInside}){switch(anchor){case"top_left":return{x:x3,y:y3+height,textAnchor:isInside?"top_left":"bottom_left"};case"top_center":return{x:x3+width/2,y:y3+height,textAnchor:isInside?"top_center":"bottom_center"};case"top_right":return{x:x3+width,y:y3+height,textAnchor:isInside?"top_right":"bottom_right"};case"center_left":return{x:x3,y:y3+height/2,textAnchor:isInside?"center_left":"center_right"};case"center":return{x:x3+width/2,y:y3+height/2,textAnchor:"center"};case"center_right":return{x:x3+width,y:y3+height/2,textAnchor:isInside?"center_right":"center_left"};case"bottom_left":return{x:x3,y:y3,textAnchor:isInside?"bottom_left":"top_left"};case"bottom_center":return{x:x3+width/2,y:y3,textAnchor:isInside?"bottom_center":"top_center"};case"bottom_right":return{x:x3+width,y:y3,textAnchor:isInside?"bottom_right":"top_right"};default:return{x:x3+width/2,y:y3+height,textAnchor:"center"}}}var SchematicBox=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicBox",zodProps:schematicBoxProps,shouldRenderAsSchematicBox:!0}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db}=this.root,{_parsedProps:props}=this,basePadding=.6,generalPadding=typeof props.padding=="number"?props.padding:0,paddingTop=typeof props.paddingTop=="number"?props.paddingTop:generalPadding,paddingBottom=typeof props.paddingBottom=="number"?props.paddingBottom:generalPadding,paddingLeft=typeof props.paddingLeft=="number"?props.paddingLeft:generalPadding,paddingRight=typeof props.paddingRight=="number"?props.paddingRight:generalPadding,hasOverlay=props.overlay&&props.overlay.length>0,hasFixedSize=typeof props.width=="number"&&typeof props.height=="number",width,height,x3,y3,centerX,centerY;if(hasOverlay){let portsWithPosition=props.overlay.map(selector=>({selector,port:this.getSubcircuit().selectOne(selector,{type:"port"})})).filter(({port})=>port!=null).map(({port})=>({position:port._getGlobalSchematicPositionAfterLayout()}));if(portsWithPosition.length===0)return;let xs3=portsWithPosition.map(p4=>p4.position.x),ys3=portsWithPosition.map(p4=>p4.position.y),minX=Math.min(...xs3),maxX=Math.max(...xs3),minY=Math.min(...ys3),maxY=Math.max(...ys3),rawWidth=maxX-minX,rawHeight=maxY-minY,defaultHorizontalPadding=rawWidth===0?basePadding:0,defaultVerticalPadding=rawHeight===0?basePadding:0,finalPaddingLeft=paddingLeft+defaultHorizontalPadding/2,finalPaddingRight=paddingRight+defaultHorizontalPadding/2,finalPaddingTop=paddingTop+defaultVerticalPadding/2,finalPaddingBottom=paddingBottom+defaultVerticalPadding/2,left=minX-finalPaddingLeft,right=maxX+finalPaddingRight,top=minY-finalPaddingBottom,bottom=maxY+finalPaddingTop;width=right-left,height=bottom-top,x3=left+(props.schX??0),y3=top+(props.schY??0),centerX=x3+width/2,centerY=y3+height/2}else if(hasFixedSize){width=props.width,height=props.height;let center2=this._getGlobalSchematicPositionBeforeLayout();centerX=center2.x,centerY=center2.y,x3=centerX-width/2,y3=centerY-height/2}else return;if(db.schematic_box.insert({height,width,x:x3,y:y3,is_dashed:props.strokeStyle==="dashed"}),props.title){let isInside=props.titleInside,TITLE_PADDING=.1,anchor=props.titleAlignment,anchorPos=getTitleAnchorAndPosition({anchor,x:x3,y:y3,width,height,isInside}),titleOffsetY,titleOffsetX,textAnchor=anchorPos.textAnchor;isInside?(titleOffsetY=anchor.includes("top")?-TITLE_PADDING:anchor.includes("bottom")?TITLE_PADDING:0,titleOffsetX=anchor.includes("left")?TITLE_PADDING:anchor.includes("right")?-TITLE_PADDING:0):(titleOffsetY=anchor.includes("top")?TITLE_PADDING:anchor.includes("bottom")?-TITLE_PADDING:0,titleOffsetX=anchor.includes("center_left")?-TITLE_PADDING:anchor.includes("center_right")?TITLE_PADDING:0);let titleX=anchorPos.x+titleOffsetX,titleY=anchorPos.y+titleOffsetY;db.schematic_text.insert({anchor:textAnchor,text:props.title,font_size:props.titleFontSize??.18,color:props.titleColor??"#000000",position:{x:titleX,y:titleY},rotation:0})}}},SchematicTable=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"isSchematicPrimitive",!0);__publicField(this,"schematic_table_id",null)}get config(){return{componentName:"SchematicTable",zodProps:schematicTableProps}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db}=this.root,{_parsedProps:props}=this,rows=this.children.filter(c3=>c3.componentName==="SchematicRow");if(rows.length===0)return;let grid4=[],maxCols=0;for(let row of rows){let cells=row.children.filter(c3=>c3.componentName==="SchematicCell");maxCols=Math.max(maxCols,cells.length)}for(let i3=0;i3<rows.length;i3++)grid4[i3]=[];for(let i3=0;i3<rows.length;i3++){let cells=rows[i3].children.filter(c3=>c3.componentName==="SchematicCell"),k4=0;for(let j3=0;j3<cells.length;j3++){for(;grid4[i3][k4];)k4++;let cell=cells[j3],colSpan=cell._parsedProps.colSpan??1,rowSpan=cell._parsedProps.rowSpan??1;for(let r4=0;r4<rowSpan;r4++)for(let c3=0;c3<colSpan;c3++)grid4[i3+r4]||(grid4[i3+r4]=[]),grid4[i3+r4][k4+c3]=cell;k4+=colSpan}}maxCols=Math.max(0,...grid4.map(r4=>r4.length));let rowHeights=rows.map((row,i3)=>row._parsedProps.height??1),colWidths=Array.from({length:maxCols},(_4,j3)=>{let maxWidth=0;for(let i3=0;i3<rows.length;i3++){let cell=grid4[i3]?.[j3];if(cell){let text=cell._parsedProps.text??cell._parsedProps.children,cellWidth=cell._parsedProps.width??(text?.length??2)*.5;cellWidth>maxWidth&&(maxWidth=cellWidth)}}return maxWidth||10}),anchorPos=this._getGlobalSchematicPositionBeforeLayout(),table=db.schematic_table.insert({anchor_position:anchorPos,column_widths:colWidths,row_heights:rowHeights,cell_padding:props.cellPadding,border_width:props.borderWidth,anchor:props.anchor,subcircuit_id:this.getSubcircuit()?.subcircuit_id||"",schematic_component_id:this.parent?.schematic_component_id||""});this.schematic_table_id=table.schematic_table_id;let processedCells=new Set,yOffset=0;for(let i3=0;i3<rows.length;i3++){let xOffset=0;for(let j3=0;j3<maxCols;j3++){let cell=grid4[i3]?.[j3];if(cell&&!processedCells.has(cell)){processedCells.add(cell);let cellProps=cell._parsedProps,rowSpan=cellProps.rowSpan??1,colSpan=cellProps.colSpan??1,cellWidth=0;for(let c3=0;c3<colSpan;c3++)cellWidth+=colWidths[j3+c3];let cellHeight=0;for(let r4=0;r4<rowSpan;r4++)cellHeight+=rowHeights[i3+r4];db.schematic_table_cell.insert({schematic_table_id:this.schematic_table_id,start_row_index:i3,end_row_index:i3+rowSpan-1,start_column_index:j3,end_column_index:j3+colSpan-1,text:cellProps.text??cellProps.children,center:{x:anchorPos.x+xOffset+cellWidth/2,y:anchorPos.y-yOffset-cellHeight/2},width:cellWidth,height:cellHeight,horizontal_align:cellProps.horizontalAlign,vertical_align:cellProps.verticalAlign,font_size:cellProps.fontSize??props.fontSize,subcircuit_id:this.getSubcircuit()?.subcircuit_id||""})}colWidths[j3]&&(xOffset+=colWidths[j3])}yOffset+=rowHeights[i3]}}},SchematicRow=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicRow",zodProps:schematicRowProps}}},SchematicCell=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"isSchematicPrimitive",!0);__publicField(this,"canHaveTextChildren",!0)}get config(){return{componentName:"SchematicCell",zodProps:schematicCellProps}}},SymbolComponent=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"Symbol",zodProps:symbolProps}}},AnalogSimulation=class extends PrimitiveComponent2{get config(){return{componentName:"AnalogSimulation",zodProps:analogSimulationProps}}doInitialSimulationRender(){let{db}=this.root,{duration,timePerStep}=this._parsedProps,durationMs=duration||10,timePerStepMs=timePerStep||.01;db.simulation_experiment.insert({name:"spice_transient_analysis",experiment_type:"spice_transient_analysis",end_time_ms:durationMs,time_per_step:timePerStepMs})}};function getLabelBounds(probePosition,labelText,alignment,labelOffset=.3){let labelWidth=Math.max(labelText.length*.1,.3),labelHeightWithPadding=.25+.2,anchorX=probePosition.x,anchorY=probePosition.y,offsetMultiplier=labelOffset+labelWidth/2;alignment.includes("top")?anchorY+=offsetMultiplier:alignment.includes("bottom")&&(anchorY-=offsetMultiplier),alignment.includes("right")?anchorX+=offsetMultiplier:alignment.includes("left")&&(anchorX-=offsetMultiplier);let minX,maxX,minY,maxY;return alignment.includes("left")?(minX=anchorX,maxX=anchorX+labelWidth):alignment.includes("right")?(minX=anchorX-labelWidth,maxX=anchorX):(minX=anchorX-labelWidth/2,maxX=anchorX+labelWidth/2),alignment.includes("top")?(minY=anchorY-labelHeightWithPadding,maxY=anchorY):alignment.includes("bottom")?(minY=anchorY,maxY=anchorY+labelHeightWithPadding):(minY=anchorY-labelHeightWithPadding/2,maxY=anchorY+labelHeightWithPadding/2),{minX,maxX,minY,maxY}}function getElementBounds(elm){let cx2,cy2,w4,h3;if(elm.type==="schematic_component")cx2=elm.center?.x,cy2=elm.center?.y,w4=elm.size?.width,h3=elm.size?.height;else if(elm.type==="schematic_text")cx2=elm.position?.x,cy2=elm.position?.y,w4=(elm.text?.length??0)*.1,h3=.2;else return null;return typeof cx2=="number"&&typeof cy2=="number"&&typeof w4=="number"&&typeof h3=="number"?{minX:cx2-w4/2,maxX:cx2+w4/2,minY:cy2-h3/2,maxY:cy2+h3/2}:null}function getOverlapArea(a3,b3){if(!doBoundsOverlap(a3,b3))return 0;let overlapWidth=Math.min(a3.maxX,b3.maxX)-Math.max(a3.minX,b3.minX),overlapHeight=Math.min(a3.maxY,b3.maxY)-Math.max(a3.minY,b3.minY);return overlapWidth*overlapHeight}function selectBestLabelAlignment({probePosition,labelText,schematicElements,defaultAlignment="top_right"}){let orderedAlignments=[defaultAlignment,...["top_right","top_left","bottom_right","bottom_left","top_center","bottom_center","center_right","center_left"].filter(a3=>a3!==defaultAlignment)],bestAlignment=defaultAlignment,minOverlapArea=1/0;for(let alignment of orderedAlignments){let labelBounds=getLabelBounds(probePosition,labelText,alignment),totalOverlapArea=0;for(let element of schematicElements){let elementBounds=getElementBounds(element);elementBounds&&(totalOverlapArea+=getOverlapArea(labelBounds,elementBounds))}if(totalOverlapArea===0)return alignment;totalOverlapArea<minOverlapArea&&(minOverlapArea=totalOverlapArea,bestAlignment=alignment)}return bestAlignment}var VoltageProbe=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"simulation_voltage_probe_id",null);__publicField(this,"schematic_voltage_probe_id",null);__publicField(this,"finalProbeName",null);__publicField(this,"color",null)}get config(){return{componentName:"VoltageProbe",zodProps:voltageProbeProps}}doInitialSimulationRender(){let{db}=this.root,{connectsTo,name,referenceTo,color}=this._parsedProps,subcircuit=this.getSubcircuit();if(!subcircuit){this.renderError("VoltageProbe must be inside a subcircuit");return}let targets=Array.isArray(connectsTo)?connectsTo:[connectsTo];if(targets.length!==1){this.renderError("VoltageProbe must connect to exactly one port or net");return}let targetSelector=targets[0],port=subcircuit.selectOne(targetSelector,{type:"port"}),net=port?null:subcircuit.selectOne(targetSelector,{type:"net"});if(net&&net.componentName!=="Net"){this.renderError(`VoltageProbe connection target "${targetSelector}" resolved to a non-net component "${net.componentName}".`);return}if(!port&&!net){this.renderError(`VoltageProbe could not find connection target "${targetSelector}"`);return}let connectedId=port?.source_port_id??net?.source_net_id;if(!connectedId){this.renderError("Could not identify connected source for VoltageProbe");return}let referencePort=null,referenceNet=null;if(referenceTo){let referenceTargets=Array.isArray(referenceTo)?referenceTo:[referenceTo];if(referenceTargets.length!==1){this.renderError("VoltageProbe must reference exactly one port or net");return}let referenceSelector=referenceTargets[0];if(referencePort=subcircuit.selectOne(referenceSelector,{type:"port"}),referenceNet=referencePort?null:subcircuit.selectOne(referenceSelector,{type:"net"}),referenceNet&&referenceNet.componentName!=="Net"){this.renderError(`VoltageProbe reference target "${referenceSelector}" resolved to a non-net component "${referenceNet.componentName}".`);return}if(!referencePort&&!referenceNet){this.renderError(`VoltageProbe could not find reference target "${referenceSelector}"`);return}}this.color=color??getSimulationColorForId(connectedId);let finalName=name;finalName||(finalName=targets[0].split(" > ").map(s4=>s4.replace(/^\./,"")).join(".")),this.finalProbeName=finalName??null;let{simulation_voltage_probe_id}=db.simulation_voltage_probe.insert({name:finalName,signal_input_source_port_id:port?.source_port_id??void 0,signal_input_source_net_id:net?.source_net_id??void 0,reference_input_source_port_id:referencePort?.source_port_id??void 0,reference_input_source_net_id:referenceNet?.source_net_id??void 0,subcircuit_id:subcircuit.subcircuit_id||void 0,color:this.color});this.simulation_voltage_probe_id=simulation_voltage_probe_id}doInitialSchematicReplaceNetLabelsWithSymbols(){if(this.root?.schematicDisabled)return;let{db}=this.root,{connectsTo,name}=this._parsedProps,subcircuit=this.getSubcircuit();if(!subcircuit)return;let targets=Array.isArray(connectsTo)?connectsTo:[connectsTo];if(targets.length!==1)return;let targetSelector=targets[0],port=subcircuit.selectOne(targetSelector,{type:"port"});if(!port||!port.schematic_port_id)return;let position2=port._getGlobalSchematicPositionAfterLayout(),targetTraceId=null;for(let trace of db.schematic_trace.list()){for(let edge of trace.edges)if(Math.abs(edge.from.x-position2.x)<1e-6&&Math.abs(edge.from.y-position2.y)<1e-6||Math.abs(edge.to.x-position2.x)<1e-6&&Math.abs(edge.to.y-position2.y)<1e-6){targetTraceId=trace.schematic_trace_id;break}if(targetTraceId)break}if(!targetTraceId)return;let probeName=this.finalProbeName,labelAlignment=selectBestLabelAlignment({probePosition:position2,labelText:probeName,schematicElements:[...db.schematic_component.list(),...db.schematic_text.list()],defaultAlignment:"top_right"}),schematic_voltage_probe2=db.schematic_voltage_probe.insert({name:probeName,position:position2,schematic_trace_id:targetTraceId,subcircuit_id:subcircuit.subcircuit_id||void 0,color:this.color??void 0,label_alignment:labelAlignment});this.schematic_voltage_probe_id=schematic_voltage_probe2.schematic_voltage_probe_id}},package_default3={name:"@tscircuit/core",type:"module",version:"0.0.936",types:"dist/index.d.ts",main:"dist/index.js",module:"dist/index.js",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist"],repository:{type:"git",url:"https://github.com/tscircuit/core"},scripts:{build:"tsup-node index.ts --format esm --dts",format:"biome format . --write","measure-bundle":"howfat -r table .","pkg-pr-new-release":"bunx pkg-pr-new publish --comment=off --peerDeps","smoke-test:dist":"bun run scripts/smoke-tests/test-dist-simple-circuit.tsx","build:benchmarking":"bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist","build:benchmarking:watch":`chokidar "./{benchmarking,lib}/**/*.{ts,tsx}" -c 'bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist'`,"start:benchmarking":'concurrently "bun run build:benchmarking:watch" "live-server ./benchmarking-dist"',"generate-test-plan":"bun run scripts/generate-test-plan.ts"},devDependencies:{"@biomejs/biome":"^1.8.3","@resvg/resvg-js":"^2.6.2","@tscircuit/capacity-autorouter":"^0.0.178","@tscircuit/checks":"^0.0.87","@tscircuit/circuit-json-util":"^0.0.73","@tscircuit/common":"^0.0.20","@tscircuit/copper-pour-solver":"^0.0.14","@tscircuit/footprinter":"^0.0.236","@tscircuit/import-snippet":"^0.0.4","@tscircuit/infgrid-ijump-astar":"^0.0.33","@tscircuit/log-soup":"^1.0.2","@tscircuit/matchpack":"^0.0.16","@tscircuit/math-utils":"^0.0.29","@tscircuit/miniflex":"^0.0.4","@tscircuit/ngspice-spice-engine":"^0.0.8","@tscircuit/props":"^0.0.432","@tscircuit/schematic-autolayout":"^0.0.6","@tscircuit/schematic-match-adapt":"^0.0.16","@tscircuit/schematic-trace-solver":"^v0.0.45","@tscircuit/solver-utils":"^0.0.3","@types/bun":"^1.2.16","@types/debug":"^4.1.12","@types/react":"^19.1.8","@types/react-dom":"^19.1.6","@types/react-reconciler":"^0.28.9","bpc-graph":"^0.0.57","bun-match-svg":"0.0.12","calculate-elbow":"^0.0.12","chokidar-cli":"^3.0.0","circuit-json":"^0.0.336","circuit-json-to-bpc":"^0.0.13","circuit-json-to-connectivity-map":"^0.0.23","circuit-json-to-gltf":"^0.0.31","circuit-json-to-simple-3d":"^0.0.9","circuit-json-to-spice":"^0.0.30","circuit-to-svg":"^0.0.296",concurrently:"^9.1.2","connectivity-map":"^1.0.0",debug:"^4.3.6","eecircuit-engine":"^1.5.6",flatbush:"^4.5.0","graphics-debug":"^0.0.60",howfat:"^0.3.8","live-server":"^1.2.2","looks-same":"^9.0.1",minicssgrid:"^0.0.9","pkg-pr-new":"^0.0.37",poppygl:"^0.0.16",react:"^19.1.0","react-dom":"^19.1.0","schematic-symbols":"^0.0.202",spicey:"^0.0.14","ts-expect":"^1.3.0",tsup:"^8.2.4"},peerDependencies:{"@tscircuit/capacity-autorouter":"*","@tscircuit/checks":"*","@tscircuit/circuit-json-util":"*","@tscircuit/footprinter":"*","@tscircuit/infgrid-ijump-astar":"*","@tscircuit/math-utils":"*","@tscircuit/props":"*","@tscircuit/schematic-autolayout":"*","@tscircuit/schematic-match-adapt":"*","circuit-json-to-bpc":"*","bpc-graph":"*","@tscircuit/matchpack":"*","circuit-json":"*","circuit-json-to-connectivity-map":"*","schematic-symbols":"*",typescript:"^5.0.0"},dependencies:{"@flatten-js/core":"^1.6.2","@lume/kiwi":"^0.4.3","calculate-packing":"0.0.68","css-select":"5.1.0","format-si-unit":"^0.0.3",nanoid:"^5.0.7","performance-now":"^2.1.0","react-reconciler":"^0.32.0","transformation-matrix":"^2.16.1",zod:"^3.25.67"}},RootCircuit=class{constructor({platform,projectUrl}={}){__publicField(this,"firstChild",null);__publicField(this,"children");__publicField(this,"db");__publicField(this,"root",null);__publicField(this,"isRoot",!0);__publicField(this,"_schematicDisabledOverride");__publicField(this,"pcbDisabled",!1);__publicField(this,"pcbRoutingDisabled",!1);__publicField(this,"_featureMspSchematicTraceRouting",!0);__publicField(this,"name");__publicField(this,"platform");__publicField(this,"projectUrl");__publicField(this,"_hasRenderedAtleastOnce",!1);__publicField(this,"_eventListeners",{});this.children=[],this.db=su2([]),this.root=this,this.platform=platform,this.projectUrl=projectUrl,this.pcbDisabled=platform?.pcbDisabled??!1}get schematicDisabled(){return this._schematicDisabledOverride!==void 0?this._schematicDisabledOverride:this._getBoard()?._parsedProps?.schematicDisabled??!1}set schematicDisabled(value){this._schematicDisabledOverride=value}add(componentOrElm){let component;(0,import_react4.isValidElement)(componentOrElm)?component=createInstanceFromReactElement(componentOrElm):component=componentOrElm,this.children.push(component)}setPlatform(platform){this.platform={...this.platform,...platform}}_getBoard(){let directBoard=this.children.find(c3=>c3.componentName==="Board");if(directBoard)return directBoard}_guessRootComponent(){if(this.firstChild)return;if(this.children.length===0)throw new Error("Not able to guess root component: RootCircuit has no children (use circuit.add(...))");let panels=this.children.filter(child=>child.lowercaseComponentName==="panel");if(panels.length>1)throw new Error("Only one <panel> is allowed per circuit");if(panels.length===1){if(this.children.length!==1)throw new Error("<panel> must be the root element of the circuit");this.firstChild=panels[0];return}if(this.children.length===1&&this.children[0].isGroup){this.firstChild=this.children[0];return}let group=new Group6({subcircuit:!0});group.parent=this,group.addAll(this.children),this.children=[group],this.firstChild=group}render(){this.firstChild||this._guessRootComponent();let{firstChild,db}=this;if(!firstChild)throw new Error("RootCircuit has no root component");firstChild.parent=this,firstChild.runRenderCycle(),this._hasRenderedAtleastOnce=!0}async renderUntilSettled(){for(this.db.source_project_metadata.list()?.[0]||this.db.source_project_metadata.insert({software_used_string:`@tscircuit/core@${this.getCoreVersion()}`,...this.projectUrl?{project_url:this.projectUrl}:{}}),this.render();this._hasIncompleteAsyncEffects();)await new Promise(resolve=>setTimeout(resolve,100)),this.render();this.emit("renderComplete")}_hasIncompleteAsyncEffects(){return this.children.some(child=>child._hasIncompleteAsyncEffects())}getCircuitJson(){return this._hasRenderedAtleastOnce||this.render(),this.db.toArray()}toJson(){return this.getCircuitJson()}async getSvg(options){let circuitToSvg=await Promise.resolve().then(()=>(init_dist8(),dist_exports4)).catch(e4=>{throw new Error(`To use circuit.getSvg, you must install the "circuit-to-svg" package.
598
+ `||ch2==="\r"){i3++;continue}if(isDigit(ch2)||ch2==="."&&i3+1<expr.length&&isDigit(expr[i3+1])){let start=i3;for(i3++;i3<expr.length;){let c3=expr[i3];if(isDigit(c3)||c3===".")i3++;else break}let numberText=expr.slice(start,i3),num=Number(numberText);if(Number.isNaN(num))throw new Error(`Invalid number: "${numberText}"`);let unitStart=i3;for(;i3<expr.length&&/[A-Za-z]/.test(expr[i3]);)i3++;if(i3>unitStart){let unitText=expr.slice(unitStart,i3),factor=units[unitText];if(factor==null)throw new Error(`Unknown unit: "${unitText}"`);num*=factor}tokens.push({type:"number",value:num});continue}if(isIdentStart(ch2)){let start=i3;for(i3++;i3<expr.length&&isIdentChar(expr[i3]);)i3++;let ident=expr.slice(start,i3);tokens.push({type:"identifier",value:ident});continue}if(ch2==="("||ch2===")"){tokens.push({type:"paren",value:ch2}),i3++;continue}if(ch2==="+"||ch2==="-"||ch2==="*"||ch2==="/"){tokens.push({type:"operator",value:ch2}),i3++;continue}throw new Error(`Unexpected character "${ch2}" in expression "${expr}"`)}return tokens}function parseExpression(tokens,vars){let index=0,peek=()=>tokens[index],consume=()=>tokens[index++],parsePrimary=()=>{let token=peek();if(!token)throw new Error("Unexpected end of expression");if(token.type==="number")return consume(),token.value;if(token.type==="identifier"){consume();let value=vars[token.value];if(value==null)throw new Error(`Unknown variable: "${token.value}"`);return value}if(token.type==="paren"&&token.value==="("){consume();let value=parseExpr(),next2=peek();if(!next2||next2.type!=="paren"||next2.value!==")")throw new Error('Expected ")"');return consume(),value}throw new Error(`Unexpected token "${token.value}"`)},parseFactor=()=>{let token=peek();if(token&&token.type==="operator"&&(token.value==="+"||token.value==="-")){consume();let value=parseFactor();return token.value==="+"?value:-value}return parsePrimary()},parseTerm=()=>{let value=parseFactor();for(;;){let token=peek();if(!token||token.type!=="operator"||token.value!=="*"&&token.value!=="/")break;consume();let rhs=parseFactor();token.value==="*"?value*=rhs:value/=rhs}return value},parseExpr=()=>{let value=parseTerm();for(;;){let token=peek();if(!token||token.type!=="operator"||token.value!=="+"&&token.value!=="-")break;consume();let rhs=parseTerm();token.value==="+"?value+=rhs:value-=rhs}return value},result=parseExpr();if(index<tokens.length){let leftover=tokens.slice(index).map(t6=>"value"in t6?t6.value:"?").join(" ");throw new Error(`Unexpected tokens at end of expression: ${leftover}`)}return result}var cssSelectPrimitiveComponentAdapter={isTag:node=>!0,getParent:node=>node.parent,getChildren:node=>node.children,getName:node=>node.lowercaseComponentName,getAttributeValue:(node,name)=>{if(name==="class"&&"getNameAndAliases"in node)return node.getNameAndAliases().join(" ");if(name==="name"&&node._parsedProps?.name)return node._parsedProps.name;if(node._parsedProps&&name in node._parsedProps){let value=node._parsedProps[name];return typeof value=="string"?value:value!=null?String(value):null}if(name in node){let value=node[name];return typeof value=="string"?value:value!=null?String(value):null}let reverseMap=node._attributeLowerToCamelNameMap;if(reverseMap){let camelCaseName=reverseMap[name];if(camelCaseName&&camelCaseName in node){let value=node[camelCaseName];return typeof value=="string"?value:value!=null?String(value):null}}return null},hasAttrib:(node,name)=>{if(name==="class")return!!node._parsedProps?.name;if(node._parsedProps&&name in node._parsedProps||name in node)return!0;let reverseMap=node._attributeLowerToCamelNameMap;if(reverseMap){let camelCaseName=reverseMap[name];if(camelCaseName&&camelCaseName in node)return!0}return!1},getSiblings:node=>node.parent?node.parent.children:[],prevElementSibling:node=>{if(!node.parent)return null;let siblings=node.parent.children,idx=siblings.indexOf(node);return idx>0?siblings[idx-1]:null},getText:()=>"",removeSubsets:nodes=>nodes.filter((node,i3)=>!nodes.some((other,j3)=>i3!==j3&&other!==node&&other.getDescendants().includes(node))),existsOne:(test,nodes)=>nodes.some(test),findAll:(test,nodes)=>{let result=[],recurse=node=>{test(node)&&result.push(node);for(let child of node.children)recurse(child)};for(let node of nodes)recurse(node);return result},findOne:(test,nodes)=>{for(let node of nodes){if(test(node))return node;let children=node.children;if(children.length>0){let result=cssSelectPrimitiveComponentAdapter.findOne(test,children);if(result)return result}}return null},equals:(a3,b3)=>a3._renderId===b3._renderId,isHovered:elem=>!1,isVisited:elem=>!1,isActive:elem=>!1},cssSelectPrimitiveComponentAdapterWithoutSubcircuits={...cssSelectPrimitiveComponentAdapter,getChildren:node=>node.children.filter(c3=>!c3.isSubcircuit)},cssSelectPrimitiveComponentAdapterOnlySubcircuits={...cssSelectPrimitiveComponentAdapter,getChildren:node=>node.children.filter(c3=>c3.isSubcircuit)},buildPlusMinusNetErrorMessage=(selector,component)=>{let netName=selector.split("net.")[1]?.split(/[ >]/)[0]??selector;return`Net names cannot contain "+" or "-" (component "${component?.componentName??"Unknown component"}" received "${netName}" via "${selector}"). Try using underscores instead, e.g. VCC_P`},preprocessSelector=(selector,component)=>{if(/net\.[^\s>]*\./.test(selector))throw new Error('Net names cannot contain a period, try using "sel.net..." to autocomplete with conventional net names, e.g. V3_3');if(/net\.[^\s>]*[+-]/.test(selector))throw new Error(buildPlusMinusNetErrorMessage(selector,component));if(/net\.[0-9]/.test(selector)){let match2=selector.match(/net\.([^ >]+)/),netName=match2?match2[1]:"";throw new Error(`Net name "${netName}" cannot start with a number, try using a prefix like "VBUS1"`)}return selector.replace(/ pin(?=[\d.])/g," port").replace(/ subcircuit\./g," group[isSubcircuit=true]").replace(/([^ ])\>([^ ])/g,"$1 > $2").replace(/(^|[ >])(?!pin\.)(?!port\.)(?!net\.)([A-Z][A-Za-z0-9_-]*)\.([A-Za-z0-9_-]+)/g,(_4,sep,name,pin)=>{let pinPart=/^\d+$/.test(pin)?`pin${pin}`:pin;return`${sep}.${name} > .${pinPart}`}).trim()},cssSelectOptionsInsideSubcircuit={adapter:cssSelectPrimitiveComponentAdapterWithoutSubcircuits,cacheResults:!0},PrimitiveComponent2=class extends Renderable{constructor(props){super(props);__publicField(this,"parent",null);__publicField(this,"children");__publicField(this,"childrenPendingRemoval");__publicField(this,"props");__publicField(this,"_parsedProps");__publicField(this,"externallyAddedAliases");__publicField(this,"isPrimitiveContainer",!1);__publicField(this,"canHaveTextChildren",!1);__publicField(this,"source_group_id",null);__publicField(this,"source_component_id",null);__publicField(this,"schematic_component_id",null);__publicField(this,"pcb_component_id",null);__publicField(this,"cad_component_id",null);__publicField(this,"fallbackUnassignedName");__publicField(this,"_cachedSelectAllQueries",new Map);__publicField(this,"_cachedSelectOneQueries",new Map);this.children=[],this.childrenPendingRemoval=[],this.props=props??{},this.externallyAddedAliases=[];let parsePropsResult=("partial"in this.config.zodProps?this.config.zodProps.partial({name:!0}):this.config.zodProps).safeParse(props??{});if(parsePropsResult.success)this._parsedProps=parsePropsResult.data;else throw new InvalidProps(this.lowercaseComponentName,this.props,parsePropsResult.error.format())}get config(){return{componentName:"",zodProps:external_exports.object({}).passthrough()}}get componentName(){return this.config.componentName}getInheritedProperty(propertyName){let current2=this;for(;current2;){if(current2._parsedProps&&propertyName in current2._parsedProps)return current2._parsedProps[propertyName];current2=current2.parent}if(this.root?.platform&&propertyName in this.root.platform)return this.root.platform[propertyName]}getInheritedMergedProperty(propertyName){let parentPropertyObject=this.parent?.getInheritedMergedProperty?.(propertyName),myPropertyObject=this._parsedProps?.[propertyName];return{...parentPropertyObject,...myPropertyObject}}get lowercaseComponentName(){return this.componentName.toLowerCase()}get isSubcircuit(){return!!this.props.subcircuit||this.lowercaseComponentName==="group"&&this?.parent?.isRoot}get isGroup(){return this.lowercaseComponentName==="group"}get name(){return this._parsedProps.name??this.fallbackUnassignedName}setProps(props){let newProps=this.config.zodProps.parse({...this.props,...props}),oldProps=this.props;this.props=newProps,this._parsedProps=this.config.zodProps.parse(props),this.onPropsChange({oldProps,newProps,changedProps:Object.keys(props)}),this.parent?.onChildChanged?.(this)}_getPcbRotationBeforeLayout(){let{pcbRotation}=this.props;return typeof pcbRotation=="string"?parseFloat(pcbRotation):pcbRotation??null}getResolvedPcbPositionProp(){return{pcbX:this._resolvePcbCoordinate(this._parsedProps.pcbX,"pcbX"),pcbY:this._resolvePcbCoordinate(this._parsedProps.pcbY,"pcbY")}}_resolvePcbCoordinate(rawValue,axis,options={}){if(rawValue==null)return 0;if(typeof rawValue=="number")return rawValue;if(typeof rawValue!="string")throw new Error(`Invalid ${axis} value for ${this.componentName}: ${String(rawValue)}`);let allowBoardVariables=options.allowBoardVariables??this._isNormalComponent===!0,includesBoardVariable=rawValue.includes("board."),knownVariables={};if(allowBoardVariables){let board=this._getBoard(),boardVariables=board?._getBoardCalcVariables()??{};if(includesBoardVariable&&!board)throw new Error(`Cannot resolve ${axis} for ${this.componentName}: no board found for board.* variables`);if(includesBoardVariable&&board&&Object.keys(boardVariables).length===0)throw new Error("Cannot do calculations based on board size when the board is auto-sized");Object.assign(knownVariables,boardVariables)}try{return evaluateCalcString(rawValue,{knownVariables})}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`Invalid ${axis} value for ${this.componentName}: ${message}`)}}computePcbPropsTransform(){let rotation4=this._getPcbRotationBeforeLayout()??0,{pcbX,pcbY}=this.getResolvedPcbPositionProp();return compose(translate(pcbX,pcbY),rotate(rotation4*Math.PI/180))}_computePcbGlobalTransformBeforeLayout(){let manualPlacement=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if(manualPlacement&&this.props.pcbX===void 0&&this.props.pcbY===void 0){let rotation4=this._getPcbRotationBeforeLayout()??0;return compose(this.parent?._computePcbGlobalTransformBeforeLayout()??identity(),compose(translate(manualPlacement.x,manualPlacement.y),rotate(rotation4*Math.PI/180)))}if(this.isPcbPrimitive){let primitiveContainer=this.getPrimitiveContainer();if(primitiveContainer&&primitiveContainer._parsedProps.layer==="bottom")return compose(this.parent?._computePcbGlobalTransformBeforeLayout()??identity(),flipY(),this.computePcbPropsTransform())}return compose(this.parent?._computePcbGlobalTransformBeforeLayout()??identity(),this.computePcbPropsTransform())}getPrimitiveContainer(){return this.isPrimitiveContainer?this:this.parent?.getPrimitiveContainer?.()??null}getParentNormalComponent(){let current2=this.parent;for(;current2;){if(current2.isPrimitiveContainer&&current2.doInitialPcbComponentRender)return current2;current2=current2.parent}return null}_getPcbCircuitJsonBounds(){return{center:{x:0,y:0},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getPcbPrimitiveFlippedHelpers(){let container=this.getPrimitiveContainer(),isFlipped=container?container._parsedProps.layer==="bottom":!1;return{isFlipped,maybeFlipLayer:layer=>isFlipped?layer==="top"?"bottom":"top":layer}}_setPositionFromLayout(newCenter){throw new Error(`_setPositionFromLayout not implemented for ${this.componentName}`)}computeSchematicPropsTransform(){let{_parsedProps:props}=this;return compose(translate(props.schX??0,props.schY??0))}computeSchematicGlobalTransform(){let manualPlacementTransform=this._getSchematicGlobalManualPlacementTransform(this);return manualPlacementTransform||compose(this.parent?.computeSchematicGlobalTransform?.()??identity(),this.computeSchematicPropsTransform())}_getSchematicSymbolName(){let{_parsedProps:props}=this,base_symbol_name=this.config.schematicSymbolName,orientationRotationMap={horizontal:0,pos_left:0,neg_right:0,pos_right:180,neg_left:180,pos_top:270,neg_bottom:90,vertical:270,pos_bottom:90,neg_top:90},normalizedRotation=props.schOrientation!==void 0?orientationRotationMap[props.schOrientation]:props.schRotation;if(normalizedRotation===void 0&&(normalizedRotation=0),normalizedRotation=normalizedRotation%360,normalizedRotation<0&&(normalizedRotation+=360),props.schRotation!==void 0&&normalizedRotation%90!==0)throw new Error(`Schematic rotation ${props.schRotation} is not supported for ${this.componentName}`);let symbol_name_horz=`${base_symbol_name}_horz`,symbol_name_vert=`${base_symbol_name}_vert`,symbol_name_up=`${base_symbol_name}_up`,symbol_name_down=`${base_symbol_name}_down`,symbol_name_left=`${base_symbol_name}_left`,symbol_name_right=`${base_symbol_name}_right`;if(symbol_name_right in ef&&normalizedRotation===0)return symbol_name_right;if(symbol_name_up in ef&&normalizedRotation===90)return symbol_name_up;if(symbol_name_left in ef&&normalizedRotation===180)return symbol_name_left;if(symbol_name_down in ef&&normalizedRotation===270)return symbol_name_down;if(symbol_name_horz in ef&&(normalizedRotation===0||normalizedRotation===180))return symbol_name_horz;if(symbol_name_vert in ef&&(normalizedRotation===90||normalizedRotation===270))return symbol_name_vert;if(base_symbol_name in ef)return base_symbol_name}_getSchematicSymbolNameOrThrow(){let symbol_name=this._getSchematicSymbolName();if(!symbol_name)throw new Error(`No schematic symbol found (given: "${this.config.schematicSymbolName}")`);return symbol_name}getSchematicSymbol(){let symbol_name=this._getSchematicSymbolName();return symbol_name?ef[symbol_name]??null:null}_getPcbManualPlacementForComponent(component){if(!this.isSubcircuit)return null;let manualEdits=this.props.manualEdits;if(!manualEdits)return null;let placementConfigPositions=manualEdits?.pcb_placements;if(!placementConfigPositions)return null;for(let position2 of placementConfigPositions)if(isMatchingSelector(component,position2.selector)||component.props.name===position2.selector)return applyToPoint(this._computePcbGlobalTransformBeforeLayout(),position2.center);return null}_getSchematicManualPlacementForComponent(component){if(!this.isSubcircuit)return null;let manualEdits=this.props.manualEdits;if(!manualEdits)return null;let placementConfigPositions=manualEdits.schematic_placements;if(!placementConfigPositions)return null;for(let position2 of placementConfigPositions)if(isMatchingSelector(component,position2.selector)||component.props.name===position2.selector)return applyToPoint(this.computeSchematicGlobalTransform(),position2.center);return null}_getSchematicGlobalManualPlacementTransform(component){let manualEdits=this.getSubcircuit()?._parsedProps.manualEdits;if(!manualEdits)return null;for(let position2 of manualEdits.schematic_placements??[])if((isMatchingSelector(component,position2.selector)||component.props.name===position2.selector)&&position2.relative_to==="group_center")return compose(this.parent?._computePcbGlobalTransformBeforeLayout()??identity(),translate(position2.center.x,position2.center.y));return null}_getGlobalPcbPositionBeforeLayout(){return applyToPoint(this._computePcbGlobalTransformBeforeLayout(),{x:0,y:0})}_getGlobalSchematicPositionBeforeLayout(){return applyToPoint(this.computeSchematicGlobalTransform(),{x:0,y:0})}_getBoard(){let current2=this;for(;current2;){let maybePrimitive=current2;if(maybePrimitive.componentName==="Board")return maybePrimitive;current2=current2.parent??null}return this.root?._getBoard()}get root(){return this.parent?.root??null}onAddToParent(parent){this.parent=parent}onPropsChange(params){}onChildChanged(child){this.parent?.onChildChanged?.(child)}add(component){let textContent2=component.__text;if(typeof textContent2=="string"){if(this.canHaveTextChildren||textContent2.trim()==="")return;throw new Error(`Invalid JSX Element: Expected a React component but received text "${textContent2}"`)}if(Object.keys(component).length!==0){if(component.lowercaseComponentName==="panel")throw new Error("<panel> must be a root-level element");if(!component.onAddToParent)throw new Error(`Invalid JSX Element: Expected a React component but received "${JSON.stringify(component)}"`);component.onAddToParent(this),component.parent=this,this.children.push(component)}}addAll(components){for(let component of components)this.add(component)}remove(component){this.children=this.children.filter(c3=>c3!==component),this.childrenPendingRemoval.push(component),component.shouldBeRemoved=!0}getSubcircuitSelector(){let name=this.name,endPart=name?`${this.lowercaseComponentName}.${name}`:this.lowercaseComponentName;return!this.parent||this.parent.isSubcircuit?endPart:`${this.parent.getSubcircuitSelector()} > ${endPart}`}getFullPathSelector(){let name=this.name,endPart=name?`${this.lowercaseComponentName}.${name}`:this.lowercaseComponentName,parentSelector=this.parent?.getFullPathSelector?.();return parentSelector?`${parentSelector} > ${endPart}`:endPart}getNameAndAliases(){return[this.name,...this._parsedProps.portHints??[]].filter(Boolean)}isMatchingNameOrAlias(name){return this.getNameAndAliases().includes(name)}isMatchingAnyOf(aliases2){return this.getNameAndAliases().some(a3=>aliases2.map(a22=>a22.toString()).includes(a3))}getPcbSize(){throw new Error(`getPcbSize not implemented for ${this.componentName}`)}doesSelectorMatch(selector){let myTypeNames=[this.componentName,this.lowercaseComponentName],myClassNames=[this.name].filter(Boolean),parts=selector.trim().split(/\> /)[0],firstPart=parts[0];return parts.length>1?!1:!!(selector==="*"||selector[0]==="#"&&selector.slice(1)===this.props.id||selector[0]==="."&&myClassNames.includes(selector.slice(1))||/^[a-zA-Z0-9_]/.test(firstPart)&&myTypeNames.includes(firstPart))}getSubcircuit(){if(this.isSubcircuit)return this;let group=this.parent?.getSubcircuit?.();if(!group)throw new Error("Component is not inside an opaque group (no board?)");return group}getGroup(){return this.isGroup?this:this.parent?.getGroup?.()??null}doInitialAssignNameToUnnamedComponents(){this._parsedProps.name||(this.fallbackUnassignedName=this.getSubcircuit().getNextAvailableName(this))}doInitialOptimizeSelectorCache(){if(!this.isSubcircuit)return;let ports=this.selectAll("port");for(let port of ports){let parentAliases=(port.getParentNormalComponent?.()??port.parent)?.getNameAndAliases(),portAliases=port.getNameAndAliases();if(parentAliases)for(let parentAlias of parentAliases)for(let portAlias of portAliases){let selectors=[`.${parentAlias} > .${portAlias}`,`.${parentAlias} .${portAlias}`];for(let selector of selectors){let ar2=this._cachedSelectAllQueries.get(selector);ar2?ar2.push(port):this._cachedSelectAllQueries.set(selector,[port])}}}for(let[selector,ports2]of this._cachedSelectAllQueries.entries())ports2.length===1&&this._cachedSelectOneQueries.set(selector,ports2[0])}selectAll(selectorRaw){if(this._cachedSelectAllQueries.has(selectorRaw))return this._cachedSelectAllQueries.get(selectorRaw);let selector=preprocessSelector(selectorRaw,this),result=selectAll(selector,this,cssSelectOptionsInsideSubcircuit);if(result.length>0)return this._cachedSelectAllQueries.set(selectorRaw,result),result;let[firstpart,...rest]=selector.split(" "),subcircuit=selectOne(firstpart,this,{adapter:cssSelectPrimitiveComponentAdapterOnlySubcircuits});if(!subcircuit)return[];let result2=subcircuit.selectAll(rest.join(" "));return this._cachedSelectAllQueries.set(selectorRaw,result2),result2}selectOne(selectorRaw,options){if(this._cachedSelectOneQueries.has(selectorRaw))return this._cachedSelectOneQueries.get(selectorRaw);let selector=preprocessSelector(selectorRaw,this);options?.port&&(options.type="port");let result=null;if(options?.type&&(result=selectAll(selector,this,cssSelectOptionsInsideSubcircuit).find(n3=>n3.lowercaseComponentName===options.type)),result??(result=selectOne(selector,this,cssSelectOptionsInsideSubcircuit)),result)return this._cachedSelectOneQueries.set(selectorRaw,result),result;let[firstpart,...rest]=selector.split(" "),subcircuit=selectOne(firstpart,this,{adapter:cssSelectPrimitiveComponentAdapterOnlySubcircuits});return subcircuit?(result=subcircuit.selectOne(rest.join(" "),options),this._cachedSelectOneQueries.set(selectorRaw,result),result):null}getAvailablePcbLayers(){if(this.isPcbPrimitive){let{maybeFlipLayer}=this._getPcbPrimitiveFlippedHelpers();return"layer"in this._parsedProps||this.componentName==="SmtPad"?[maybeFlipLayer(this._parsedProps.layer??"top")]:"layers"in this._parsedProps?this._parsedProps.layers:this.componentName==="PlatedHole"?[...this.root?._getBoard()?.allLayers??["top","bottom"]]:[]}return[]}getDescendants(){let descendants=[];for(let child of this.children)descendants.push(child),descendants.push(...child.getDescendants());return descendants}getSelectableDescendants(){let descendants=[];for(let child of this.children)child.isSubcircuit?descendants.push(child):(descendants.push(child),descendants.push(...child.getSelectableDescendants()));return descendants}_getPinCount(){return 0}_getSchematicBoxDimensions(){return null}_getSchematicBoxComponentDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;let{_parsedProps:props}=this;return{schWidth:props.schWidth,schHeight:props.schHeight}}renderError(message){if(typeof message=="string")return super.renderError(message);switch(message.type){case"pcb_placement_error":this.root?.db.pcb_placement_error.insert(message);break;case"pcb_via_clearance_error":this.root?.db.pcb_via_clearance_error.insert(message);break;case"pcb_trace_error":this.root?.db.pcb_trace_error.insert(message);break;case"pcb_manual_edit_conflict_warning":this.root?.db.pcb_manual_edit_conflict_warning.insert(message);break;default:this.root?.db.pcb_placement_error.insert(message)}}getString(){let{lowercaseComponentName:cname,_parsedProps:props,parent}=this;return props?.pinNumber!==void 0&&parent?.props?.name&&props?.name?`<${cname}#${this._renderId}(pin:${props.pinNumber} .${parent?.props.name}>.${props.name}) />`:parent?.props?.name&&props?.name?`<${cname}#${this._renderId}(.${parent?.props.name}>.${props?.name}) />`:props?.from&&props?.to?`<${cname}#${this._renderId}(from:${props.from} to:${props?.to}) />`:props?.name?`<${cname}#${this._renderId} name=".${props?.name}" />`:props?.portHints?`<${cname}#${this._renderId}(${props.portHints.map(ph2=>`.${ph2}`).join(", ")}) />`:`<${cname}#${this._renderId} />`}get[Symbol.toStringTag](){return this.getString()}[Symbol.for("nodejs.util.inspect.custom")](){return this.getString()}},ErrorPlaceholderComponent=class extends PrimitiveComponent2{constructor(props,error){super(props);let resolveCoordinate=(value,axis)=>{if(typeof value=="number")return value;if(typeof value=="string")try{return this._resolvePcbCoordinate(value,axis,{allowBoardVariables:!1})}catch{return 0}return 0};this._parsedProps={...props,error,type:props.type||"unknown",component_name:props.name,error_type:"source_failed_to_create_component_error",message:error instanceof Error?error.message:String(error),pcbX:resolveCoordinate(props.pcbX,"pcbX"),pcbY:resolveCoordinate(props.pcbY,"pcbY"),schX:props.schX,schY:props.schY}}get config(){return{componentName:"ErrorPlaceholder",zodProps:external_exports.object({}).passthrough()}}doInitialSourceRender(){if(this.root?.db){let pcbPosition2=this._getGlobalPcbPositionBeforeLayout(),schematicPosition=this._getGlobalSchematicPositionBeforeLayout();this.root.db.source_failed_to_create_component_error.insert({component_name:this._parsedProps.component_name,error_type:"source_failed_to_create_component_error",message:`Could not create ${this._parsedProps.componentType??"component"}${this._parsedProps.name?` "${this._parsedProps.name}"`:""}. ${this._parsedProps.error?.formattedError?._errors?.join("; ")||this._parsedProps.message}`,pcb_center:pcbPosition2,schematic_center:schematicPosition})}}};function createErrorPlaceholderComponent(props,error){return new ErrorPlaceholderComponent(props,error)}function prepare(object,state2){let instance=object;return instance.__tsci={...state2},object}var hostConfig={supportsMutation:!0,createInstance(type,props){let target=catalogue[type];if(!target)throw Object.keys(catalogue).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 "${type}". No element with this name is registered in the @tscircuit/core catalogue. Check for typos or see https://docs.tscircuit.com/category/built-in-elements for a list of valid components. To add your own component, see docs/CREATING_NEW_COMPONENTS.md`);try{return prepare(new target(props),{})}catch(error){return createErrorPlaceholderComponent({...props,componentType:type},error)}},createTextInstance(text){return{__text:text}},appendInitialChild(parentInstance,child){parentInstance.add(child)},appendChild(parentInstance,child){parentInstance.add(child)},appendChildToContainer(container,child){container.add(child)},finalizeInitialChildren(){return!1},prepareUpdate(){return null},shouldSetTextContent(){return!1},getRootHostContext(){return{}},getChildHostContext(){return{}},prepareForCommit(){return null},resetAfterCommit(){},commitMount(){},commitUpdate(){},removeChild(){},clearContainer(){},supportsPersistence:!1,getPublicInstance(instance){return instance},preparePortalMount(containerInfo){throw new Error("Function not implemented.")},scheduleTimeout(fn3,delay){throw new Error("Function not implemented.")},cancelTimeout(id){throw new Error("Function not implemented.")},noTimeout:void 0,isPrimaryRenderer:!1,getInstanceFromNode(node){throw new Error("Function not implemented.")},beforeActiveInstanceBlur(){throw new Error("Function not implemented.")},afterActiveInstanceBlur(){throw new Error("Function not implemented.")},prepareScopeUpdate:(scopeInstance,instance)=>{throw new Error("Function not implemented.")},getInstanceFromScope:scopeInstance=>{throw new Error("Function not implemented.")},detachDeletedInstance:node=>{throw new Error("Function not implemented.")},getCurrentEventPriority:()=>import_constants.DefaultEventPriority,getCurrentUpdatePriority:()=>import_constants.DefaultEventPriority,resolveUpdatePriority:()=>import_constants.DefaultEventPriority,setCurrentUpdatePriority:()=>{},maySuspendCommit:()=>!1,supportsHydration:!1},reconciler=(0,import_react_reconciler.default)(hostConfig),createInstanceFromReactElement=reactElm=>{let rootContainer={children:[],props:{name:"$root"},add(instance){instance.parent=this,this.children.push(instance)},computePcbGlobalTransform(){return identity()}},containerErrors=[],container=reconciler.createContainer(rootContainer,0,null,!1,null,"tsci",error=>{console.log("Error in createContainer"),console.error(error),containerErrors.push(error)},null);if(reconciler.updateContainerSync(reactElm,container,null,()=>{}),reconciler.flushSyncWork(),containerErrors.length>0)throw containerErrors[0];let rootInstance=reconciler.getPublicRootInstance(container);return rootInstance||rootContainer.children[0]},parsePinNumberFromLabelsOrThrow=(pinNumberOrLabel,pinLabels)=>{if(typeof pinNumberOrLabel=="number")return pinNumberOrLabel;if(pinNumberOrLabel.startsWith("pin"))return Number(pinNumberOrLabel.slice(3));if(!pinLabels)throw new Error(`No pin labels provided and pin number or label is not a number: "${pinNumberOrLabel}"`);for(let pinNumberKey in pinLabels)if((Array.isArray(pinLabels[pinNumberKey])?pinLabels[pinNumberKey]:[pinLabels[pinNumberKey]]).includes(pinNumberOrLabel))return Number(pinNumberKey.replace("pin",""));throw new Error(`No pin labels provided and pin number or label is not a number: "${pinNumberOrLabel}"`)},underscorifyPinStyles=(pinStyles,pinLabels)=>{if(!pinStyles)return;let underscorePinStyles={},mergedStyles={};for(let[pinNameOrLabel,pinStyle]of Object.entries(pinStyles)){let pinNumber=parsePinNumberFromLabelsOrThrow(pinNameOrLabel,pinLabels);mergedStyles[pinNumber]={...mergedStyles[pinNumber],...pinStyle}}for(let[pinNumber,pinStyle]of Object.entries(mergedStyles)){let pinKey=`pin${pinNumber}`;underscorePinStyles[pinKey]={bottom_margin:pinStyle.bottomMargin,left_margin:pinStyle.leftMargin,right_margin:pinStyle.rightMargin,top_margin:pinStyle.topMargin}}return underscorePinStyles},underscorifyPortArrangement=portArrangement=>{if(portArrangement){if("leftSide"in portArrangement||"rightSide"in portArrangement||"topSide"in portArrangement||"bottomSide"in portArrangement)return{left_side:portArrangement.leftSide,right_side:portArrangement.rightSide,top_side:portArrangement.topSide,bottom_side:portArrangement.bottomSide};if("leftPinCount"in portArrangement||"rightPinCount"in portArrangement||"topPinCount"in portArrangement||"bottomPinCount"in portArrangement)return{left_size:portArrangement.leftPinCount,right_size:portArrangement.rightPinCount,top_size:portArrangement.topPinCount,bottom_size:portArrangement.bottomPinCount};if("leftSize"in portArrangement||"rightSize"in portArrangement||"topSize"in portArrangement||"bottomSize"in portArrangement)return{left_size:portArrangement.leftSize,right_size:portArrangement.rightSize,top_size:portArrangement.topSize,bottom_size:portArrangement.bottomSize}}};function pairs2(arr){let result=[];for(let i3=0;i3<arr.length-1;i3++)result.push([arr[i3],arr[i3+1]]);return result}var netProps2=external_exports.object({name:external_exports.string().refine(val=>!/[+-]/.test(val),val=>({message:`Net names cannot contain "+" or "-" (component "Net" received "${val}"). Try using underscores instead, e.g. VCC_P`}))}),Net=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"source_net_id");__publicField(this,"subcircuit_connectivity_map_key",null)}get config(){return{componentName:"Net",zodProps:netProps2}}getPortSelector(){return`net.${this.props.name}`}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,isGround=props.name.startsWith("GND"),isPositiveVoltageSource=props.name.startsWith("V"),net=db.source_net.insert({name:props.name,member_source_group_ids:[],is_ground:isGround,is_power:isPositiveVoltageSource,is_positive_voltage_source:isPositiveVoltageSource});this.source_net_id=net.source_net_id}doInitialSourceParentAttachment(){let subcircuit=this.getSubcircuit();if(!subcircuit)return;let{db}=this.root;db.source_net.update(this.source_net_id,{subcircuit_id:subcircuit.subcircuit_id})}getAllConnectedPorts(){let allPorts=this.getSubcircuit().selectAll("port"),connectedPorts=[];for(let port of allPorts){let traces=port._getDirectlyConnectedTraces();for(let trace of traces)if(trace._isExplicitlyConnectedToNet(this)){connectedPorts.push(port);break}}return connectedPorts}_getAllDirectlyConnectedTraces(){let allTraces=this.getSubcircuit().selectAll("trace"),connectedTraces=[];for(let trace of allTraces)trace._isExplicitlyConnectedToNet(this)&&connectedTraces.push(trace);return connectedTraces}doInitialPcbRouteNetIslands(){if(this.root?.pcbDisabled||this.getSubcircuit()._parsedProps.routingDisabled||this.getSubcircuit()._getAutorouterConfig().groupMode!=="sequential-trace")return;let{db}=this.root,{_parsedProps:props}=this,traces=this._getAllDirectlyConnectedTraces().filter(trace=>(trace._portsRoutedOnPcb?.length??0)>0),islands=[];for(let trace of traces){let tracePorts=trace._portsRoutedOnPcb,traceIsland=islands.find(island=>tracePorts.some(port=>island.ports.includes(port)));if(!traceIsland){islands.push({ports:[...tracePorts],traces:[trace]});continue}traceIsland.traces.push(trace),traceIsland.ports.push(...tracePorts)}if(islands.length===0)return;let islandPairs=pairs2(islands);for(let[A4,B4]of islandPairs){let Apositions=A4.ports.map(port=>port._getGlobalPcbPositionBeforeLayout()),Bpositions=B4.ports.map(port=>port._getGlobalPcbPositionBeforeLayout()),closestDist=1/0,closestPair=[-1,-1];for(let i3=0;i3<Apositions.length;i3++){let Apos=Apositions[i3];for(let j3=0;j3<Bpositions.length;j3++){let Bpos=Bpositions[j3],dist=Math.sqrt((Apos.x-Bpos.x)**2+(Apos.y-Bpos.y)**2);dist<closestDist&&(closestDist=dist,closestPair=[i3,j3])}}let Aport=A4.ports[closestPair[0]],Bport=B4.ports[closestPair[1]],pcbElements=db.toArray().filter(elm=>elm.type==="pcb_smtpad"||elm.type==="pcb_trace"||elm.type==="pcb_plated_hole"||elm.type==="pcb_hole"||elm.type==="source_port"||elm.type==="pcb_port"),{solution}=autoroute2(pcbElements.concat([{type:"source_trace",source_trace_id:"__net_trace_tmp",connected_source_port_ids:[Aport.source_port_id,Bport.source_port_id]}])),trace=solution[0];if(!trace){this.renderError({pcb_trace_error_id:"",pcb_trace_id:"__net_trace_tmp",pcb_component_ids:[Aport.pcb_component_id,Bport.pcb_component_id].filter(Boolean),pcb_port_ids:[Aport.pcb_port_id,Bport.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}db.pcb_trace.insert(trace)}}renderError(message){if(typeof message=="string")return super.renderError(message);this.root?.db.pcb_trace_error.insert(message)}},createNetsFromProps=(component,props)=>{for(let prop of props)if(typeof prop=="string"&&prop.startsWith("net.")){if(/net\.[^\s>]*\./.test(prop))throw new Error('Net names cannot contain a period, try using "sel.net..." to autocomplete with conventional net names, e.g. V3_3');if(/net\.[^\s>]*[+-]/.test(prop)){let netName=prop.split("net.")[1],message=`Net names cannot contain "+" or "-" (component "${component.componentName}" received "${netName}" via "${prop}"). Try using underscores instead, e.g. VCC_P`;throw new Error(message)}if(/net\.[0-9]/.test(prop)){let netName=prop.split("net.")[1];throw new Error(`Net name "${netName}" cannot start with a number, try using a prefix like "VBUS1"`)}let subcircuit=component.getSubcircuit();if(!subcircuit.selectOne(prop)){let net=new Net({name:prop.split("net.")[1]});subcircuit.add(net)}}},SmtPad=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"pcb_smtpad_id",null);__publicField(this,"matchedPort",null);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SmtPad",zodProps:smtPadProps}}getPcbSize(){let{_parsedProps:props}=this;if(props.shape==="circle")return{width:props.radius*2,height:props.radius*2};if(props.shape==="rect")return{width:props.width,height:props.height};if(props.shape==="rotated_rect"){let angleRad=(props.ccwRotation??0)*Math.PI/180,cosAngle=Math.cos(angleRad),sinAngle=Math.sin(angleRad),width=Math.abs(props.width*cosAngle)+Math.abs(props.height*sinAngle),height=Math.abs(props.width*sinAngle)+Math.abs(props.height*cosAngle);return{width,height}}if(props.shape==="polygon"){let points=props.points,xs3=points.map(p4=>p4.x),ys3=points.map(p4=>p4.y),minX=Math.min(...xs3),maxX=Math.max(...xs3),minY=Math.min(...ys3),maxY=Math.max(...ys3);return{width:maxX-minX,height:maxY-minY}}if(props.shape==="pill")return{width:props.width,height:props.height};throw new Error(`getPcbSize for shape "${props.shape}" not implemented for ${this.componentName}`)}doInitialPortMatching(){let parentPorts=this.getPrimitiveContainer()?.selectAll("port");if(this.props.portHints){for(let port of parentPorts)if(port.isMatchingAnyOf(this.props.portHints)){this.matchedPort=port,port.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,isCoveredWithSolderMask=props.coveredWithSolderMask??!1,shouldCreateSolderPaste=!isCoveredWithSolderMask,soldermaskMargin=props.solderMaskMargin,subcircuit=this.getSubcircuit(),position2=this._getGlobalPcbPositionBeforeLayout(),globalTransform=this._computePcbGlobalTransformBeforeLayout(),normalizedRotationDegrees=(decomposeTSR(this._computePcbGlobalTransformBeforeLayout()).rotation.angle*180/Math.PI%360+360)%360,rotationTolerance=.01,isAxisAligned=Math.abs(normalizedRotationDegrees)<rotationTolerance||Math.abs(normalizedRotationDegrees-180)<rotationTolerance||Math.abs(normalizedRotationDegrees-360)<rotationTolerance,isRotated90Degrees=Math.abs(normalizedRotationDegrees-90)<rotationTolerance||Math.abs(normalizedRotationDegrees-270)<rotationTolerance,finalRotationDegrees=Math.abs(normalizedRotationDegrees-360)<rotationTolerance?0:normalizedRotationDegrees,transformRotationBeforeFlip=finalRotationDegrees,{maybeFlipLayer,isFlipped}=this._getPcbPrimitiveFlippedHelpers();isFlipped&&(finalRotationDegrees=(360-finalRotationDegrees+360)%360);let portHints2=props.portHints?.map(ph2=>ph2.toString())??[],pcb_smtpad2=null,pcb_component_id=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id;if(props.shape==="circle")pcb_smtpad2=db.pcb_smtpad.insert({pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,layer:maybeFlipLayer(props.layer??"top"),shape:"circle",radius:props.radius,port_hints:portHints2,is_covered_with_solder_mask:isCoveredWithSolderMask,soldermask_margin:soldermaskMargin,x:position2.x,y:position2.y,subcircuit_id:subcircuit?.subcircuit_id??void 0}),shouldCreateSolderPaste&&db.pcb_solder_paste.insert({layer:pcb_smtpad2.layer,shape:"circle",radius:pcb_smtpad2.radius*.7,x:pcb_smtpad2.x,y:pcb_smtpad2.y,pcb_component_id:pcb_smtpad2.pcb_component_id,pcb_smtpad_id:pcb_smtpad2.pcb_smtpad_id,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});else if(props.shape==="rect")!isAxisAligned&&!isRotated90Degrees?pcb_smtpad2=db.pcb_smtpad.insert({pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,layer:maybeFlipLayer(props.layer??"top"),shape:"rotated_rect",width:props.width,height:props.height,corner_radius:props.cornerRadius??void 0,x:position2.x,y:position2.y,ccw_rotation:finalRotationDegrees,port_hints:portHints2,is_covered_with_solder_mask:isCoveredWithSolderMask,soldermask_margin:soldermaskMargin,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):pcb_smtpad2=db.pcb_smtpad.insert({pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,layer:maybeFlipLayer(props.layer??"top"),shape:"rect",width:isRotated90Degrees?props.height:props.width,height:isRotated90Degrees?props.width:props.height,corner_radius:props.cornerRadius??void 0,port_hints:portHints2,is_covered_with_solder_mask:isCoveredWithSolderMask,soldermask_margin:soldermaskMargin,x:position2.x,y:position2.y,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),shouldCreateSolderPaste&&(pcb_smtpad2.shape==="rect"?db.pcb_solder_paste.insert({layer:maybeFlipLayer(props.layer??"top"),shape:"rect",width:pcb_smtpad2.width*.7,height:pcb_smtpad2.height*.7,x:pcb_smtpad2.x,y:pcb_smtpad2.y,pcb_component_id:pcb_smtpad2.pcb_component_id,pcb_smtpad_id:pcb_smtpad2.pcb_smtpad_id,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}):pcb_smtpad2.shape==="rotated_rect"&&db.pcb_solder_paste.insert({layer:maybeFlipLayer(props.layer??"top"),shape:"rotated_rect",width:pcb_smtpad2.width*.7,height:pcb_smtpad2.height*.7,x:pcb_smtpad2.x,y:pcb_smtpad2.y,ccw_rotation:pcb_smtpad2.ccw_rotation,pcb_component_id:pcb_smtpad2.pcb_component_id,pcb_smtpad_id:pcb_smtpad2.pcb_smtpad_id,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}));else if(props.shape==="rotated_rect"){let baseRotation=props.ccwRotation??0,combinedRotationBeforeFlip=(transformRotationBeforeFlip+baseRotation+360)%360,padRotation=isFlipped?(360-combinedRotationBeforeFlip+360)%360:combinedRotationBeforeFlip;pcb_smtpad2=db.pcb_smtpad.insert({pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,layer:maybeFlipLayer(props.layer??"top"),shape:"rotated_rect",width:props.width,height:props.height,corner_radius:props.cornerRadius??void 0,x:position2.x,y:position2.y,ccw_rotation:padRotation,port_hints:portHints2,is_covered_with_solder_mask:isCoveredWithSolderMask,soldermask_margin:soldermaskMargin,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),shouldCreateSolderPaste&&db.pcb_solder_paste.insert({layer:maybeFlipLayer(props.layer??"top"),shape:"rotated_rect",width:pcb_smtpad2.width*.7,height:pcb_smtpad2.height*.7,x:position2.x,y:position2.y,ccw_rotation:padRotation,pcb_component_id,pcb_smtpad_id:pcb_smtpad2.pcb_smtpad_id,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(props.shape==="polygon"){let transformedPoints=props.points.map(point23=>{let transformed=applyToPoint(globalTransform,{x:distance.parse(point23.x),y:distance.parse(point23.y)});return{x:transformed.x,y:transformed.y}});pcb_smtpad2=db.pcb_smtpad.insert({pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,layer:maybeFlipLayer(props.layer??"top"),shape:"polygon",points:transformedPoints,port_hints:portHints2,is_covered_with_solder_mask:isCoveredWithSolderMask,soldermask_margin:soldermaskMargin,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else props.shape==="pill"&&(pcb_smtpad2=db.pcb_smtpad.insert({pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,layer:maybeFlipLayer(props.layer??"top"),shape:"pill",x:position2.x,y:position2.y,radius:props.radius,height:props.height,width:props.width,port_hints:portHints2,is_covered_with_solder_mask:isCoveredWithSolderMask,soldermask_margin:soldermaskMargin,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}));pcb_smtpad2&&(this.pcb_smtpad_id=pcb_smtpad2.pcb_smtpad_id)}doInitialPcbPortAttachment(){if(this.root?.pcbDisabled)return;let{db}=this.root;db.pcb_smtpad.update(this.pcb_smtpad_id,{pcb_port_id:this.matchedPort?.pcb_port_id})}_getPcbCircuitJsonBounds(){let{db}=this.root,smtpad2=db.pcb_smtpad.get(this.pcb_smtpad_id);if(smtpad2.shape==="rect")return{center:{x:smtpad2.x,y:smtpad2.y},bounds:{left:smtpad2.x-smtpad2.width/2,top:smtpad2.y+smtpad2.height/2,right:smtpad2.x+smtpad2.width/2,bottom:smtpad2.y-smtpad2.height/2},width:smtpad2.width,height:smtpad2.height};if(smtpad2.shape==="rotated_rect"){let angleRad=smtpad2.ccw_rotation*Math.PI/180,cosAngle=Math.cos(angleRad),sinAngle=Math.sin(angleRad),w22=smtpad2.width/2,h22=smtpad2.height/2,xExtent=Math.abs(w22*cosAngle)+Math.abs(h22*sinAngle),yExtent=Math.abs(w22*sinAngle)+Math.abs(h22*cosAngle);return{center:{x:smtpad2.x,y:smtpad2.y},bounds:{left:smtpad2.x-xExtent,right:smtpad2.x+xExtent,top:smtpad2.y-yExtent,bottom:smtpad2.y+yExtent},width:xExtent*2,height:yExtent*2}}if(smtpad2.shape==="circle")return{center:{x:smtpad2.x,y:smtpad2.y},bounds:{left:smtpad2.x-smtpad2.radius,top:smtpad2.y-smtpad2.radius,right:smtpad2.x+smtpad2.radius,bottom:smtpad2.y+smtpad2.radius},width:smtpad2.radius*2,height:smtpad2.radius*2};if(smtpad2.shape==="polygon"){let points=smtpad2.points,xs3=points.map(p4=>p4.x),ys3=points.map(p4=>p4.y),minX=Math.min(...xs3),maxX=Math.max(...xs3),minY=Math.min(...ys3),maxY=Math.max(...ys3);return{center:{x:(minX+maxX)/2,y:(minY+maxY)/2},bounds:{left:minX,top:maxY,right:maxX,bottom:minY},width:maxX-minX,height:maxY-minY}}if(smtpad2.shape==="pill"){let halfWidth=smtpad2.width/2,halfHeight=smtpad2.height/2;return{center:{x:smtpad2.x,y:smtpad2.y},bounds:{left:smtpad2.x-halfWidth,top:smtpad2.y-halfHeight,right:smtpad2.x+halfWidth,bottom:smtpad2.y+halfHeight},width:smtpad2.width,height:smtpad2.height}}throw new Error(`circuitJson bounds calculation not implemented for shape "${smtpad2.shape}"`)}_setPositionFromLayout(newCenter){let{db}=this.root;db.pcb_smtpad.update(this.pcb_smtpad_id,{x:newCenter.x,y:newCenter.y});let solderPaste=db.pcb_solder_paste.list().find(elm=>elm.pcb_smtpad_id===this.pcb_smtpad_id);solderPaste&&db.pcb_solder_paste.update(solderPaste.pcb_solder_paste_id,{x:newCenter.x,y:newCenter.y}),this.matchedPort?._setPositionFromLayout(newCenter)}},SilkscreenPath=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"pcb_silkscreen_path_id",null);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenPath",zodProps:silkscreenPathProps}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,{maybeFlipLayer}=this._getPcbPrimitiveFlippedHelpers(),layer=maybeFlipLayer(props.layer??"top");if(layer!=="top"&&layer!=="bottom")throw new Error(`Invalid layer "${layer}" for SilkscreenPath. Must be "top" or "bottom".`);let transform5=this._computePcbGlobalTransformBeforeLayout(),subcircuit=this.getSubcircuit(),pcb_component_id=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,pcb_silkscreen_path2=db.pcb_silkscreen_path.insert({pcb_component_id,layer,route:props.route.map(p4=>{let transformedPosition=applyToPoint(transform5,{x:p4.x,y:p4.y});return{...p4,x:transformedPosition.x,y:transformedPosition.y}}),stroke_width:props.strokeWidth??.1,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_path_id=pcb_silkscreen_path2.pcb_silkscreen_path_id}_setPositionFromLayout(newCenter){let{db}=this.root,{_parsedProps:props}=this,currentPath=db.pcb_silkscreen_path.get(this.pcb_silkscreen_path_id);if(!currentPath)return;let currentCenterX=0,currentCenterY=0;for(let point23 of currentPath.route)currentCenterX+=point23.x,currentCenterY+=point23.y;currentCenterX/=currentPath.route.length,currentCenterY/=currentPath.route.length;let offsetX=newCenter.x-currentCenterX,offsetY=newCenter.y-currentCenterY,newRoute=currentPath.route.map(point23=>({...point23,x:point23.x+offsetX,y:point23.y+offsetY}));db.pcb_silkscreen_path.update(this.pcb_silkscreen_path_id,{route:newRoute})}_repositionOnPcb({deltaX,deltaY}){if(this.root?.pcbDisabled)return;let{db}=this.root;if(!this.pcb_silkscreen_path_id)return;let path=db.pcb_silkscreen_path.get(this.pcb_silkscreen_path_id);path&&db.pcb_silkscreen_path.update(this.pcb_silkscreen_path_id,{route:path.route.map(p4=>({...p4,x:p4.x+deltaX,y:p4.y+deltaY}))})}getPcbSize(){let{_parsedProps:props}=this;if(!props.route||props.route.length===0)return{width:0,height:0};let minX=1/0,maxX=-1/0,minY=1/0,maxY=-1/0;for(let point23 of props.route)minX=Math.min(minX,point23.x),maxX=Math.max(maxX,point23.x),minY=Math.min(minY,point23.y),maxY=Math.max(maxY,point23.y);return{width:maxX-minX,height:maxY-minY}}},pcbTraceProps2=external_exports.object({route:external_exports.array(pcb_trace_route_point),source_trace_id:external_exports.string().optional()}),PcbTrace=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"pcb_trace_id",null);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbTrace",zodProps:pcbTraceProps2}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,container=this.getPrimitiveContainer(),subcircuit=this.getSubcircuit(),{maybeFlipLayer}=this._getPcbPrimitiveFlippedHelpers(),parentTransform=this._computePcbGlobalTransformBeforeLayout(),transformedRoute=props.route.map(point23=>{let{x:x3,y:y3,...restOfPoint}=point23,transformedPoint=applyToPoint(parentTransform,{x:x3,y:y3});return point23.route_type==="wire"&&point23.layer?{...transformedPoint,...restOfPoint,layer:maybeFlipLayer(point23.layer)}:{...transformedPoint,...restOfPoint}}),pcb_trace2=db.pcb_trace.insert({pcb_component_id:container.pcb_component_id,source_trace_id:props.source_trace_id,route:transformedRoute,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_trace_id=pcb_trace2.pcb_trace_id}getPcbSize(){let{_parsedProps:props}=this;if(!props.route||props.route.length===0)return{width:0,height:0};let minX=1/0,maxX=-1/0,minY=1/0,maxY=-1/0;for(let point23 of props.route)minX=Math.min(minX,point23.x),maxX=Math.max(maxX,point23.x),minY=Math.min(minY,point23.y),maxY=Math.max(maxY,point23.y),point23.route_type==="wire"&&(minX=Math.min(minX,point23.x-point23.width/2),maxX=Math.max(maxX,point23.x+point23.width/2),minY=Math.min(minY,point23.y-point23.width/2),maxY=Math.max(maxY,point23.y+point23.width/2));return minX===1/0||maxX===-1/0||minY===1/0||maxY===-1/0?{width:0,height:0}:{width:maxX-minX,height:maxY-minY}}},PlatedHole=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"pcb_plated_hole_id",null);__publicField(this,"matchedPort",null);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PlatedHole",zodProps:platedHoleProps}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){let{_parsedProps:props}=this;if(props.shape==="circle")return{width:props.outerDiameter,height:props.outerDiameter};if(props.shape==="oval"||props.shape==="pill")return{width:props.outerWidth,height:props.outerHeight};if(props.shape==="circular_hole_with_rect_pad")return{width:props.rectPadWidth,height:props.rectPadHeight};if(props.shape==="pill_hole_with_rect_pad")return{width:props.rectPadWidth,height:props.rectPadHeight};if(props.shape==="hole_with_polygon_pad"){if(!props.padOutline||props.padOutline.length===0)throw new Error("padOutline is required for hole_with_polygon_pad shape");let xs3=props.padOutline.map(p4=>typeof p4.x=="number"?p4.x:parseFloat(String(p4.x))),ys3=props.padOutline.map(p4=>typeof p4.y=="number"?p4.y:parseFloat(String(p4.y))),minX=Math.min(...xs3),maxX=Math.max(...xs3),minY=Math.min(...ys3),maxY=Math.max(...ys3);return{width:maxX-minX,height:maxY-minY}}throw new Error(`getPcbSize for shape "${props.shape}" not implemented for ${this.componentName}`)}_getPcbCircuitJsonBounds(){let{db}=this.root,platedHole=db.pcb_plated_hole.get(this.pcb_plated_hole_id),size2=this.getPcbSize();return{center:{x:platedHole.x,y:platedHole.y},bounds:{left:platedHole.x-size2.width/2,top:platedHole.y+size2.height/2,right:platedHole.x+size2.width/2,bottom:platedHole.y-size2.height/2},width:size2.width,height:size2.height}}_setPositionFromLayout(newCenter){let{db}=this.root;db.pcb_plated_hole.update(this.pcb_plated_hole_id,{x:newCenter.x,y:newCenter.y}),this.matchedPort?._setPositionFromLayout(newCenter)}doInitialPortMatching(){let parentPorts=this.getPrimitiveContainer()?.selectAll("port");if(this.props.portHints){for(let port of parentPorts)if(port.isMatchingAnyOf(this.props.portHints)){this.matchedPort=port,port.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,position2=this._getGlobalPcbPositionBeforeLayout(),pcb_component_id=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,subcircuit=this.getSubcircuit(),soldermaskMargin=props.solderMaskMargin,isCoveredWithSolderMask=props.coveredWithSolderMask??!1;if(props.shape==="circle"){let pcb_plated_hole2=db.pcb_plated_hole.insert({pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,outer_diameter:props.outerDiameter,hole_diameter:props.holeDiameter,shape:"circle",port_hints:this.getNameAndAliases(),x:position2.x,y:position2.y,layers:["top","bottom"],soldermask_margin:soldermaskMargin,is_covered_with_solder_mask:isCoveredWithSolderMask,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=pcb_plated_hole2.pcb_plated_hole_id,db.pcb_solder_paste.insert({layer:"top",shape:"circle",radius:props.outerDiameter/2,x:position2.x,y:position2.y,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),db.pcb_solder_paste.insert({layer:"bottom",shape:"circle",radius:props.outerDiameter/2,x:position2.x,y:position2.y,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(props.shape==="pill"&&props.rectPad){let pcb_plated_hole2=db.pcb_plated_hole.insert({pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:props.outerWidth,outer_height:props.outerHeight,hole_width:props.holeWidth,hole_height:props.holeHeight,shape:"rotated_pill_hole_with_rect_pad",type:"pcb_plated_hole",port_hints:this.getNameAndAliases(),pcb_plated_hole_id:this.pcb_plated_hole_id,x:position2.x,y:position2.y,layers:["top","bottom"],soldermask_margin:soldermaskMargin,is_covered_with_solder_mask:isCoveredWithSolderMask,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_shape:"rotated_pill",pad_shape:"rect",hole_ccw_rotation:props.pcbRotation??0,rect_ccw_rotation:props.pcbRotation??0,rect_pad_width:props.outerWidth,rect_pad_height:props.outerHeight,hole_offset_x:props.holeOffsetX,hole_offset_y:props.holeOffsetY});this.pcb_plated_hole_id=pcb_plated_hole2.pcb_plated_hole_id}else if(props.shape==="pill"||props.shape==="oval"){let pcb_plated_hole2=db.pcb_plated_hole.insert({pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,outer_width:props.outerWidth,outer_height:props.outerHeight,hole_width:props.holeWidth,hole_height:props.holeHeight,shape:props.shape,port_hints:this.getNameAndAliases(),x:position2.x,y:position2.y,layers:["top","bottom"],soldermask_margin:soldermaskMargin,is_covered_with_solder_mask:isCoveredWithSolderMask,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,ccw_rotation:props.pcbRotation??0});this.pcb_plated_hole_id=pcb_plated_hole2.pcb_plated_hole_id,db.pcb_solder_paste.insert({layer:"top",shape:props.shape,width:props.outerWidth,height:props.outerHeight,x:position2.x,y:position2.y,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0}),db.pcb_solder_paste.insert({layer:"bottom",shape:props.shape,width:props.outerWidth,height:props.outerHeight,x:position2.x,y:position2.y,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}else if(props.shape==="circular_hole_with_rect_pad"){let pcb_plated_hole2=db.pcb_plated_hole.insert({pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,hole_diameter:props.holeDiameter,rect_pad_width:props.rectPadWidth,rect_pad_height:props.rectPadHeight,shape:"circular_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:position2.x,y:position2.y,layers:["top","bottom"],soldermask_margin:soldermaskMargin,is_covered_with_solder_mask:isCoveredWithSolderMask,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,hole_offset_x:props.holeOffsetX,hole_offset_y:props.holeOffsetY,rect_border_radius:props.rectBorderRadius??0});this.pcb_plated_hole_id=pcb_plated_hole2.pcb_plated_hole_id}else if(props.shape==="pill_hole_with_rect_pad"){let pcb_plated_hole2=db.pcb_plated_hole.insert({pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,hole_width:props.holeWidth,hole_height:props.holeHeight,rect_pad_width:props.rectPadWidth,rect_pad_height:props.rectPadHeight,hole_offset_x:props.holeOffsetX,hole_offset_y:props.holeOffsetY,shape:"pill_hole_with_rect_pad",port_hints:this.getNameAndAliases(),x:position2.x,y:position2.y,layers:["top","bottom"],soldermask_margin:soldermaskMargin,is_covered_with_solder_mask:isCoveredWithSolderMask,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=pcb_plated_hole2.pcb_plated_hole_id}else if(props.shape==="hole_with_polygon_pad"){let padOutline=(props.padOutline||[]).map(point23=>{let x3=typeof point23.x=="number"?point23.x:parseFloat(String(point23.x)),y3=typeof point23.y=="number"?point23.y:parseFloat(String(point23.y));return{x:x3,y:y3}}),pcb_plated_hole2=db.pcb_plated_hole.insert({pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,shape:"hole_with_polygon_pad",hole_shape:props.holeShape||"circle",hole_diameter:props.holeDiameter,hole_width:props.holeWidth,hole_height:props.holeHeight,pad_outline:padOutline,hole_offset_x:typeof props.holeOffsetX=="number"?props.holeOffsetX:parseFloat(String(props.holeOffsetX||0)),hole_offset_y:typeof props.holeOffsetY=="number"?props.holeOffsetY:parseFloat(String(props.holeOffsetY||0)),port_hints:this.getNameAndAliases(),x:position2.x,y:position2.y,layers:["top","bottom"],soldermask_margin:soldermaskMargin,is_covered_with_solder_mask:isCoveredWithSolderMask,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_plated_hole_id=pcb_plated_hole2.pcb_plated_hole_id}}doInitialPcbPortAttachment(){if(this.root?.pcbDisabled)return;let{db}=this.root;db.pcb_plated_hole.update(this.pcb_plated_hole_id,{pcb_port_id:this.matchedPort?.pcb_port_id})}},Keepout=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"pcb_keepout_id",null);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Keepout",zodProps:pcbKeepoutProps}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let subcircuit=this.getSubcircuit(),{db}=this.root,{_parsedProps:props}=this,position2=this._getGlobalPcbPositionBeforeLayout(),decomposedMat=decomposeTSR(this._computePcbGlobalTransformBeforeLayout()),isRotated90=Math.abs(decomposedMat.rotation.angle*(180/Math.PI)-90)%180<.01,pcb_keepout2=null;props.shape==="circle"?pcb_keepout2=db.pcb_keepout.insert({layers:["top"],shape:"circle",radius:props.radius,center:{x:position2.x,y:position2.y},subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:subcircuit?.getGroup()?.pcb_group_id??void 0}):props.shape==="rect"&&(pcb_keepout2=db.pcb_keepout.insert({layers:["top"],shape:"rect",...isRotated90?{width:props.height,height:props.width}:{width:props.width,height:props.height},center:{x:position2.x,y:position2.y},subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:subcircuit?.getGroup()?.pcb_group_id??void 0})),pcb_keepout2&&(this.pcb_keepout_id=pcb_keepout2.pcb_keepout_id)}},Hole=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"pcb_hole_id",null);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Hole",zodProps:holeProps}}getPcbSize(){let{_parsedProps:props}=this,isPill=props.shape==="pill",isRect=props.shape==="rect";return isPill?{width:props.width,height:props.height}:isRect?{width:props.width,height:props.height}:{width:props.diameter,height:props.diameter}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,subcircuit=this.getSubcircuit(),position2=this._getGlobalPcbPositionBeforeLayout(),soldermaskMargin=props.solderMaskMargin,isCoveredWithSolderMask=props.coveredWithSolderMask??!1,pcb_component_id=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id;if(props.shape==="pill")if(props.pcbRotation&&props.pcbRotation!==0){let inserted_hole=db.pcb_hole.insert({pcb_component_id,type:"pcb_hole",hole_shape:"rotated_pill",hole_width:props.width,hole_height:props.height,x:position2.x,y:position2.y,ccw_rotation:props.pcbRotation,soldermask_margin:soldermaskMargin,is_covered_with_solder_mask:isCoveredWithSolderMask,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:subcircuit?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=inserted_hole.pcb_hole_id}else{let inserted_hole=db.pcb_hole.insert({pcb_component_id,type:"pcb_hole",hole_shape:"pill",hole_width:props.width,hole_height:props.height,x:position2.x,y:position2.y,soldermask_margin:soldermaskMargin,is_covered_with_solder_mask:isCoveredWithSolderMask,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:subcircuit?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=inserted_hole.pcb_hole_id}else if(props.shape==="rect"){let inserted_hole=db.pcb_hole.insert({pcb_component_id,type:"pcb_hole",hole_shape:"rect",hole_width:props.width,hole_height:props.height,x:position2.x,y:position2.y,soldermask_margin:soldermaskMargin,is_covered_with_solder_mask:isCoveredWithSolderMask,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:subcircuit?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=inserted_hole.pcb_hole_id}else{let inserted_hole=db.pcb_hole.insert({pcb_component_id,type:"pcb_hole",hole_shape:"circle",hole_diameter:props.diameter,x:position2.x,y:position2.y,soldermask_margin:soldermaskMargin,is_covered_with_solder_mask:isCoveredWithSolderMask,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:subcircuit?.getGroup()?.pcb_group_id??void 0});this.pcb_hole_id=inserted_hole.pcb_hole_id}}_getPcbCircuitJsonBounds(){let{db}=this.root,hole=db.pcb_hole.get(this.pcb_hole_id),size2=this.getPcbSize();return{center:{x:hole.x,y:hole.y},bounds:{left:hole.x-size2.width/2,top:hole.y-size2.height/2,right:hole.x+size2.width/2,bottom:hole.y+size2.height/2},width:size2.width,height:size2.height}}_setPositionFromLayout(newCenter){let{db}=this.root;db.pcb_hole.update(this.pcb_hole_id,{x:newCenter.x,y:newCenter.y})}};function normalizeTextForCircuitJson(text){return text.replace(/\\n/g,`
599
+ `)}var SilkscreenText=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"pcb_silkscreen_text_ids",[]);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenText",zodProps:silkscreenTextProps}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,container=this.getPrimitiveContainer(),position2=this._getGlobalPcbPositionBeforeLayout(),{maybeFlipLayer,isFlipped}=this._getPcbPrimitiveFlippedHelpers(),subcircuit=this.getSubcircuit(),rotation4=0;if(props.pcbRotation!==void 0&&props.pcbRotation!==0)rotation4=props.pcbRotation;else{let globalTransform=this._computePcbGlobalTransformBeforeLayout();rotation4=decomposeTSR(globalTransform).rotation.angle*180/Math.PI}isFlipped&&(rotation4=(rotation4+180)%360);let uniqueLayers=new Set(props.layers);props.layer&&uniqueLayers.add(props.layer);let targetLayers=uniqueLayers.size>0?Array.from(uniqueLayers):["top"],fontSize=props.fontSize??this.getInheritedProperty("pcbStyle")?.silkscreenFontSize??1;for(let layer of targetLayers){let pcb_silkscreen_text2=db.pcb_silkscreen_text.insert({anchor_alignment:props.anchorAlignment,anchor_position:{x:position2.x,y:position2.y},font:props.font??"tscircuit2024",font_size:fontSize,layer:maybeFlipLayer(layer),text:normalizeTextForCircuitJson(props.text??""),ccw_rotation:rotation4,pcb_component_id:container.pcb_component_id,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_text_ids.push(pcb_silkscreen_text2.pcb_silkscreen_text_id)}}getPcbSize(){let{_parsedProps:props}=this,fontSize=props.fontSize??this.getInheritedProperty("pcbStyle")?.silkscreenFontSize??1,textWidth=(props.text??"").length*fontSize,textHeight=fontSize;return{width:textWidth*fontSize,height:textHeight*fontSize}}_repositionOnPcb({deltaX,deltaY}){if(this.root?.pcbDisabled)return;let{db}=this.root;for(let id of this.pcb_silkscreen_text_ids){let text=db.pcb_silkscreen_text.get(id);text&&db.pcb_silkscreen_text.update(id,{anchor_position:{x:text.anchor_position.x+deltaX,y:text.anchor_position.y+deltaY}})}}},Cutout=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"pcb_cutout_id",null);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Cutout",zodProps:cutoutProps}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,subcircuit=this.getSubcircuit(),pcb_group_id=this.getGroup()?.pcb_group_id??void 0,globalPosition=this._getGlobalPcbPositionBeforeLayout(),parentRotation=this.getPrimitiveContainer()?._parsedProps.pcbRotation??0,inserted_pcb_cutout;if(props.shape==="rect"){let rotationDeg=typeof parentRotation=="string"?parseInt(parentRotation.replace("deg",""),10):parentRotation,isRotated90=Math.abs(rotationDeg%180)===90,rectData={shape:"rect",center:globalPosition,width:isRotated90?props.height:props.width,height:isRotated90?props.width:props.height,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id};inserted_pcb_cutout=db.pcb_cutout.insert(rectData)}else if(props.shape==="circle"){let circleData={shape:"circle",center:globalPosition,radius:props.radius,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id};inserted_pcb_cutout=db.pcb_cutout.insert(circleData)}else if(props.shape==="polygon"){let transform5=this._computePcbGlobalTransformBeforeLayout(),polygonData={shape:"polygon",points:props.points.map(p4=>applyToPoint(transform5,p4)),subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id};inserted_pcb_cutout=db.pcb_cutout.insert(polygonData)}inserted_pcb_cutout&&(this.pcb_cutout_id=inserted_pcb_cutout.pcb_cutout_id)}getPcbSize(){let{_parsedProps:props}=this;if(props.shape==="rect")return{width:props.width,height:props.height};if(props.shape==="circle")return{width:props.radius*2,height:props.radius*2};if(props.shape==="polygon"){if(props.points.length===0)return{width:0,height:0};let minX=1/0,maxX=-1/0,minY=1/0,maxY=-1/0;for(let point23 of props.points)minX=Math.min(minX,point23.x),maxX=Math.max(maxX,point23.x),minY=Math.min(minY,point23.y),maxY=Math.max(maxY,point23.y);return{width:maxX-minX,height:maxY-minY}}return{width:0,height:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_cutout_id)return super._getPcbCircuitJsonBounds();let{db}=this.root,cutout=db.pcb_cutout.get(this.pcb_cutout_id);if(!cutout)return super._getPcbCircuitJsonBounds();if(cutout.shape==="rect")return{center:cutout.center,bounds:{left:cutout.center.x-cutout.width/2,top:cutout.center.y+cutout.height/2,right:cutout.center.x+cutout.width/2,bottom:cutout.center.y-cutout.height/2},width:cutout.width,height:cutout.height};if(cutout.shape==="circle")return{center:cutout.center,bounds:{left:cutout.center.x-cutout.radius,top:cutout.center.y+cutout.radius,right:cutout.center.x+cutout.radius,bottom:cutout.center.y-cutout.radius},width:cutout.radius*2,height:cutout.radius*2};if(cutout.shape==="polygon"){if(cutout.points.length===0)return super._getPcbCircuitJsonBounds();let minX=1/0,maxX=-1/0,minY=1/0,maxY=-1/0;for(let point23 of cutout.points)minX=Math.min(minX,point23.x),maxX=Math.max(maxX,point23.x),minY=Math.min(minY,point23.y),maxY=Math.max(maxY,point23.y);return{center:{x:(minX+maxX)/2,y:(minY+maxY)/2},bounds:{left:minX,top:maxY,right:maxX,bottom:minY},width:maxX-minX,height:maxY-minY}}return super._getPcbCircuitJsonBounds()}_setPositionFromLayout(newCenter){if(!this.pcb_cutout_id)return;let{db}=this.root,cutout=db.pcb_cutout.get(this.pcb_cutout_id);if(cutout){if(cutout.shape==="rect"||cutout.shape==="circle")db.pcb_cutout.update(this.pcb_cutout_id,{...cutout,center:newCenter});else if(cutout.shape==="polygon"){let oldCenter=this._getPcbCircuitJsonBounds().center,dx2=newCenter.x-oldCenter.x,dy2=newCenter.y-oldCenter.y,newPoints=cutout.points.map(p4=>({x:p4.x+dx2,y:p4.y+dy2}));db.pcb_cutout.update(this.pcb_cutout_id,{...cutout,points:newPoints})}}}},createPinrowSilkscreenText=({elm,pinLabels,layer,readableRotation,anchorAlignment})=>{let pinNum=elm.text.replace(/[{}]/g,"").toLowerCase(),label=pinNum;if(Array.isArray(pinLabels)){let index=parseInt(pinNum.replace(/[^\d]/g,""),10)-1;label=String(pinLabels[index]??pinNum)}else typeof pinLabels=="object"&&(label=String(pinLabels[pinNum]??pinNum));return new SilkscreenText({anchorAlignment:anchorAlignment||"center",text:label??pinNum,layer:layer||"top",fontSize:elm.font_size+.2,pcbX:isNaN(elm.anchor_position.x)?0:elm.anchor_position.x,pcbY:elm.anchor_position.y,pcbRotation:readableRotation??0})},calculateCcwRotation=(componentRotationStr,elementCcwRotation)=>{let componentAngle=parseInt(componentRotationStr||"0",10),totalRotation;return elementCcwRotation!=null?totalRotation=elementCcwRotation-componentAngle:totalRotation=componentAngle,(totalRotation%360+360)%360},createComponentsFromCircuitJson=({componentName,componentRotation,footprinterString,pinLabels,pcbPinLabels},circuitJson)=>{let components=[];for(let elm of circuitJson)if(elm.type==="pcb_smtpad"&&elm.shape==="rect")components.push(new SmtPad({pcbX:elm.x,pcbY:elm.y,layer:elm.layer,shape:"rect",height:elm.height,width:elm.width,portHints:elm.port_hints,rectBorderRadius:elm.rect_border_radius}));else if(elm.type==="pcb_smtpad"&&elm.shape==="circle")components.push(new SmtPad({pcbX:elm.x,pcbY:elm.y,layer:elm.layer,shape:"circle",radius:elm.radius,portHints:elm.port_hints}));else if(elm.type==="pcb_smtpad"&&elm.shape==="pill")components.push(new SmtPad({shape:"pill",height:elm.height,width:elm.width,radius:elm.radius,portHints:elm.port_hints,pcbX:elm.x,pcbY:elm.y,layer:elm.layer}));else if(elm.type==="pcb_silkscreen_path")components.push(new SilkscreenPath({layer:elm.layer,route:elm.route,strokeWidth:elm.stroke_width}));else if(elm.type==="pcb_plated_hole")elm.shape==="circle"?components.push(new PlatedHole({pcbX:elm.x,pcbY:elm.y,shape:"circle",holeDiameter:elm.hole_diameter,outerDiameter:elm.outer_diameter,portHints:elm.port_hints})):elm.shape==="circular_hole_with_rect_pad"?components.push(new PlatedHole({pcbX:elm.x,pcbY:elm.y,shape:"circular_hole_with_rect_pad",holeDiameter:elm.hole_diameter,rectPadHeight:elm.rect_pad_height,rectPadWidth:elm.rect_pad_width,portHints:elm.port_hints,rectBorderRadius:elm.rect_border_radius,holeOffsetX:elm.hole_offset_x,holeOffsetY:elm.hole_offset_y})):elm.shape==="pill"||elm.shape==="oval"?components.push(new PlatedHole({pcbX:elm.x,pcbY:elm.y,shape:elm.shape,holeWidth:elm.hole_width,holeHeight:elm.hole_height,outerWidth:elm.outer_width,outerHeight:elm.outer_height,portHints:elm.port_hints})):elm.shape==="pill_hole_with_rect_pad"?components.push(new PlatedHole({pcbX:elm.x,pcbY:elm.y,shape:"pill_hole_with_rect_pad",holeShape:"pill",padShape:"rect",holeWidth:elm.hole_width,holeHeight:elm.hole_height,rectPadWidth:elm.rect_pad_width,rectPadHeight:elm.rect_pad_height,portHints:elm.port_hints,holeOffsetX:elm.hole_offset_x,holeOffsetY:elm.hole_offset_y})):elm.shape==="hole_with_polygon_pad"&&components.push(new PlatedHole({pcbX:elm.x,pcbY:elm.y,shape:"hole_with_polygon_pad",holeShape:elm.hole_shape||"circle",holeDiameter:elm.hole_diameter,holeWidth:elm.hole_width,holeHeight:elm.hole_height,padOutline:elm.pad_outline||[],holeOffsetX:elm.hole_offset_x,holeOffsetY:elm.hole_offset_y,portHints:elm.port_hints}));else if(elm.type==="pcb_keepout"&&elm.shape==="circle")components.push(new Keepout({pcbX:elm.center.x,pcbY:elm.center.y,shape:"circle",radius:elm.radius}));else if(elm.type==="pcb_keepout"&&elm.shape==="rect")components.push(new Keepout({pcbX:elm.center.x,pcbY:elm.center.y,shape:"rect",width:elm.width,height:elm.height}));else if(elm.type==="pcb_hole"&&elm.hole_shape==="circle")components.push(new Hole({pcbX:elm.x,pcbY:elm.y,diameter:elm.hole_diameter}));else if(elm.type==="pcb_hole"&&elm.hole_shape==="rect")components.push(new Hole({pcbX:elm.x,pcbY:elm.y,shape:"rect",width:elm.hole_width,height:elm.hole_height}));else if(elm.type==="pcb_hole"&&elm.hole_shape==="pill")components.push(new Hole({pcbX:elm.x,pcbY:elm.y,shape:"pill",width:elm.hole_width,height:elm.hole_height}));else if(elm.type==="pcb_hole"&&elm.hole_shape==="rotated_pill")components.push(new Hole({pcbX:elm.x,pcbY:elm.y,shape:"pill",width:elm.hole_width,height:elm.hole_height,pcbRotation:elm.ccw_rotation}));else if(elm.type==="pcb_cutout")elm.shape==="rect"?components.push(new Cutout({pcbX:elm.center.x,pcbY:elm.center.y,shape:"rect",width:elm.width,height:elm.height})):elm.shape==="circle"?components.push(new Cutout({pcbX:elm.center.x,pcbY:elm.center.y,shape:"circle",radius:elm.radius})):elm.shape==="polygon"&&components.push(new Cutout({shape:"polygon",points:elm.points}));else if(elm.type==="pcb_silkscreen_text"){let ccwRotation=calculateCcwRotation(componentRotation,elm.ccw_rotation);footprinterString?.includes("pinrow")&&elm.text.includes("PIN")?components.push(createPinrowSilkscreenText({elm,pinLabels:pcbPinLabels??pinLabels??{},layer:elm.layer,readableRotation:ccwRotation,anchorAlignment:elm.anchor_alignment})):components.push(new SilkscreenText({anchorAlignment:elm.anchor_alignment||"center",text:componentName||elm.text,fontSize:elm.font_size+.2,pcbX:Number.isNaN(elm.anchor_position.x)?0:elm.anchor_position.x,pcbY:elm.anchor_position.y,pcbRotation:ccwRotation??0}))}else elm.type==="pcb_trace"&&components.push(new PcbTrace({route:elm.route}));return components};function getBoundsOfPcbComponents(components){let minX=1/0,minY=1/0,maxX=-1/0,maxY=-1/0,hasValidComponents=!1;for(let child of components)if(child.isPcbPrimitive&&!child.componentName.startsWith("Silkscreen")){let{x:x3,y:y3}=child._getGlobalPcbPositionBeforeLayout(),{width:width2,height:height2}=child.getPcbSize();minX=Math.min(minX,x3-width2/2),minY=Math.min(minY,y3-height2/2),maxX=Math.max(maxX,x3+width2/2),maxY=Math.max(maxY,y3+height2/2),hasValidComponents=!0}else if(child.children.length>0){let childBounds=getBoundsOfPcbComponents(child.children);(childBounds.width>0||childBounds.height>0)&&(minX=Math.min(minX,childBounds.minX),minY=Math.min(minY,childBounds.minY),maxX=Math.max(maxX,childBounds.maxX),maxY=Math.max(maxY,childBounds.maxY),hasValidComponents=!0)}if(!hasValidComponents)return{minX:0,minY:0,maxX:0,maxY:0,width:0,height:0};let width=maxX-minX,height=maxY-minY;return width<0&&(width=0),height<0&&(height=0),{minX,minY,maxX,maxY,width,height}}function normalizeAngle(angle){let normalized=angle%360;return normalized<0?normalized+360:normalized}function isAngleBetween(angle,start,end,direction2){return direction2==="counterclockwise"?end>=start?angle>=start&&angle<=end:angle>=start||angle<=end:end<=start?angle<=start&&angle>=end:angle<=start||angle>=end}function getArcBounds(elm){let center2=elm.center,radius=elm.radius,startAngle=elm.start_angle_degrees,endAngle=elm.end_angle_degrees,direction2=elm.direction??"counterclockwise";if(!center2||typeof center2.x!="number"||typeof center2.y!="number"||typeof radius!="number"||typeof startAngle!="number"||typeof endAngle!="number")return null;let start=normalizeAngle(startAngle),end=normalizeAngle(endAngle),consideredAngles=new Set([start,end]),cardinalAngles=[0,90,180,270];for(let cardinal of cardinalAngles)isAngleBetween(cardinal,start,end,direction2)&&consideredAngles.add(cardinal);let minX=1/0,minY=1/0,maxX=-1/0,maxY=-1/0;for(let angle of consideredAngles){let radians=angle*Math.PI/180,x3=center2.x+radius*Math.cos(radians),y3=center2.y+radius*Math.sin(radians);minX=Math.min(minX,x3),maxX=Math.max(maxX,x3),minY=Math.min(minY,y3),maxY=Math.max(maxY,y3)}return!Number.isFinite(minX)||!Number.isFinite(minY)?null:{minX,maxX,minY,maxY}}function getBoundsForSchematic(db){let minX=1/0,minY=1/0,maxX=-1/0,maxY=-1/0;for(let elm of db){let cx2,cy2,w4,h3;if(elm.type==="schematic_component")cx2=elm.center?.x,cy2=elm.center?.y,w4=elm.size?.width,h3=elm.size?.height;else if(elm.type==="schematic_box")cx2=elm.x,cy2=elm.y,w4=elm.width,h3=elm.height;else if(elm.type==="schematic_port")cx2=elm.center?.x,cy2=elm.center?.y,w4=.2,h3=.2;else if(elm.type==="schematic_text")cx2=elm.position?.x,cy2=elm.position?.y,w4=(elm.text?.length??0)*.1,h3=.2;else if(elm.type==="schematic_line"){let x12=elm.x1??0,y12=elm.y1??0,x22=elm.x2??0,y22=elm.y2??0;cx2=(x12+x22)/2,cy2=(y12+y22)/2,w4=Math.abs(x22-x12),h3=Math.abs(y22-y12)}else if(elm.type==="schematic_rect")cx2=elm.center?.x,cy2=elm.center?.y,w4=elm.width,h3=elm.height;else if(elm.type==="schematic_circle"){cx2=elm.center?.x,cy2=elm.center?.y;let radius=elm.radius;typeof radius=="number"&&(w4=radius*2,h3=radius*2)}else if(elm.type==="schematic_arc"){let bounds=getArcBounds(elm);bounds&&(minX=Math.min(minX,bounds.minX),maxX=Math.max(maxX,bounds.maxX),minY=Math.min(minY,bounds.minY),maxY=Math.max(maxY,bounds.maxY));continue}typeof cx2=="number"&&typeof cy2=="number"&&typeof w4=="number"&&typeof h3=="number"&&(minX=Math.min(minX,cx2-w4/2),maxX=Math.max(maxX,cx2+w4/2),minY=Math.min(minY,cy2-h3/2),maxY=Math.max(maxY,cy2+h3/2))}return{minX,maxX,minY,maxY}}function getRelativeDirection(pointA,pointB){let dx2=pointB.x-pointA.x,dy2=pointB.y-pointA.y;return Math.abs(dx2)>Math.abs(dy2)?dx2>=0?"right":"left":dy2>=0?"up":"down"}var areAllPcbPrimitivesOverlapping=pcbPrimitives=>{if(pcbPrimitives.length<=1)return!0;let bounds=pcbPrimitives.map(p4=>{let circuitBounds=p4._getPcbCircuitJsonBounds();return{left:circuitBounds.bounds.left,right:circuitBounds.bounds.right,top:circuitBounds.bounds.top,bottom:circuitBounds.bounds.bottom}}),overlaps=Array(bounds.length).fill(!1).map(()=>Array(bounds.length).fill(!1));for(let i3=0;i3<bounds.length;i3++)for(let j3=i3+1;j3<bounds.length;j3++){let a3=bounds[i3],b3=bounds[j3];overlaps[i3][j3]=overlaps[j3][i3]=!(a3.right<b3.left||a3.left>b3.right||a3.bottom>b3.top||a3.top<b3.bottom)}let visited=new Set,dfs=node=>{visited.add(node);for(let i3=0;i3<bounds.length;i3++)overlaps[node][i3]&&!visited.has(i3)&&dfs(i3)};return dfs(0),visited.size===bounds.length},getCenterOfPcbPrimitives=pcbPrimitives=>{if(pcbPrimitives.length===0)throw new Error("Cannot get center of empty PCB primitives array");let positions=pcbPrimitives.map(p4=>p4._getPcbCircuitJsonBounds().center).filter(Boolean),sumX=positions.reduce((sum,pos)=>sum+pos.x,0),sumY=positions.reduce((sum,pos)=>sum+pos.y,0);return{x:sumX/positions.length,y:sumY/positions.length}},portProps2=external_exports.object({name:external_exports.string().optional(),pinNumber:external_exports.number().optional(),aliases:external_exports.array(external_exports.string()).optional(),layer:external_exports.string().optional(),layers:external_exports.array(external_exports.string()).optional(),schX:external_exports.number().optional(),schY:external_exports.number().optional(),direction:external_exports.enum(["up","down","left","right"]).optional(),connectsTo:external_exports.union([external_exports.string(),external_exports.array(external_exports.string())]).optional()}),Port=class extends PrimitiveComponent2{constructor(props,opts={}){if(!props.name&&props.pinNumber!==void 0&&(props.name=`pin${props.pinNumber}`),!props.name)throw new Error("Port must have a name or a pinNumber");super(props);__publicField(this,"source_port_id",null);__publicField(this,"pcb_port_id",null);__publicField(this,"schematic_port_id",null);__publicField(this,"schematicSymbolPortDef",null);__publicField(this,"matchedComponents");__publicField(this,"facingDirection",null);__publicField(this,"originDescription",null);opts.originDescription&&(this.originDescription=opts.originDescription),this.matchedComponents=[]}get config(){return{componentName:"Port",zodProps:portProps2}}isGroupPort(){return this.parent?.componentName==="Group"}isComponentPort(){return!this.isGroupPort()}_getConnectedPortsFromConnectsTo(){let{_parsedProps:props}=this,connectsTo=props.connectsTo;if(!connectsTo)return[];let connectedPorts=[],connectsToArray=Array.isArray(connectsTo)?connectsTo:[connectsTo];for(let connection of connectsToArray){let port=this.getSubcircuit().selectOne(connection,{type:"port"});port&&connectedPorts.push(port)}return connectedPorts}_isBoardPinoutFromAttributes(){let parent=this.parent;if(parent?._parsedProps?.pinAttributes){let pinAttributes=parent._parsedProps.pinAttributes;for(let alias of this.getNameAndAliases())if(pinAttributes[alias]?.includeInBoardPinout)return!0}}_getGlobalPcbPositionBeforeLayout(){let matchedPcbElm=this.matchedComponents.find(c3=>c3.isPcbPrimitive),parentComponent=this.parent;if(parentComponent&&!parentComponent.props.footprint)throw new Error(`${parentComponent.componentName} "${parentComponent.props.name}" does not have a footprint. Add a footprint prop, e.g. <${parentComponent.componentName.toLowerCase()} footprint="..." />`);if(!matchedPcbElm)throw new Error(`Port ${this} has no matching PCB primitives. This often means the footprint's pads lack matching port hints.`);return matchedPcbElm?._getGlobalPcbPositionBeforeLayout()??{x:0,y:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_port_id)return super._getPcbCircuitJsonBounds();let{db}=this.root,pcb_port2=db.pcb_port.get(this.pcb_port_id);return{center:{x:pcb_port2.x,y:pcb_port2.y},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getGlobalPcbPositionAfterLayout(){return this._getPcbCircuitJsonBounds().center}_getPortsInternallyConnectedToThisPort(){let parent=this.parent;if(!parent||!parent._getInternallyConnectedPins)return[];let internallyConnectedPorts=parent._getInternallyConnectedPins();for(let ports of internallyConnectedPorts)if(ports.some(port=>port===this))return ports;return[]}_hasSchematicPort(){let{schX,schY}=this._parsedProps;if(schX!==void 0&&schY!==void 0)return!0;let parentNormalComponent=this.getParentNormalComponent();if(parentNormalComponent?.getSchematicSymbol())return!!(this.schematicSymbolPortDef||this._getPortsInternallyConnectedToThisPort().some(p4=>p4.schematicSymbolPortDef));let parentBoxDim=parentNormalComponent?._getSchematicBoxDimensions();return!!(parentBoxDim&&this.props.pinNumber!==void 0&&parentBoxDim.getPortPositionByPinNumber(this.props.pinNumber))}_getGlobalSchematicPositionBeforeLayout(){let{schX,schY}=this._parsedProps;if(schX!==void 0&&schY!==void 0)return{x:schX,y:schY};let parentNormalComponent=this.getParentNormalComponent(),symbol=parentNormalComponent?.getSchematicSymbol();if(symbol){let schematicSymbolPortDef=this.schematicSymbolPortDef;if(!schematicSymbolPortDef&&(schematicSymbolPortDef=this._getPortsInternallyConnectedToThisPort().find(p4=>p4.schematicSymbolPortDef)?.schematicSymbolPortDef??null,!schematicSymbolPortDef))throw new Error(`Couldn't find schematicSymbolPortDef for port ${this.getString()}, searched internally connected ports and none had a schematicSymbolPortDef. Why are we trying to get the schematic position of this port?`);let transform5=compose(parentNormalComponent.computeSchematicGlobalTransform(),translate(-symbol.center.x,-symbol.center.y));return applyToPoint(transform5,schematicSymbolPortDef)}let parentBoxDim=parentNormalComponent?._getSchematicBoxDimensions();if(parentBoxDim&&this.props.pinNumber!==void 0){let localPortPosition=parentBoxDim.getPortPositionByPinNumber(this.props.pinNumber);if(!localPortPosition)throw new Error(`Couldn't find position for schematic_port for port ${this.getString()} inside of the schematic box`);return applyToPoint(parentNormalComponent.computeSchematicGlobalTransform(),localPortPosition)}throw new Error(`Couldn't find position for schematic_port for port ${this.getString()}`)}_getGlobalSchematicPositionAfterLayout(){let{db}=this.root;if(!this.schematic_port_id)throw new Error(`Can't get schematic port position after layout for "${this.getString()}", no schematic_port_id`);let schematic_port2=db.schematic_port.get(this.schematic_port_id);if(!schematic_port2)throw new Error(`Schematic port not found when trying to get post-layout position: ${this.schematic_port_id}`);return schematic_port2.center}registerMatch(component){this.matchedComponents.push(component)}getNameAndAliases(){let{_parsedProps:props}=this;return Array.from(new Set([...props.name?[props.name]:[],...props.aliases??[],...typeof props.pinNumber=="number"?[`pin${props.pinNumber}`,props.pinNumber.toString()]:[],...this.externallyAddedAliases??[]]))}_getMatchingPinAttributes(){let pinAttributes=this.parent?._parsedProps?.pinAttributes;if(!pinAttributes)return[];let matches=[];for(let alias of this.getNameAndAliases()){let attributes2=pinAttributes[alias];attributes2&&matches.push(attributes2)}return matches}_shouldIncludeInBoardPinout(){return this._getMatchingPinAttributes().some(attributes2=>attributes2.includeInBoardPinout===!0)}isMatchingPort(port){return this.isMatchingAnyOf(port.getNameAndAliases())}getPortSelector(){return`.${(this.getParentNormalComponent()??this.parent)?.props.name} > port.${this.props.name}`}getAvailablePcbLayers(){let{layer,layers}=this._parsedProps;return layers||(layer?[layer]:Array.from(new Set(this.matchedComponents.flatMap(c3=>c3.getAvailablePcbLayers()))))}_getDirectlyConnectedTraces(){return this.getSubcircuit().selectAll("trace").filter(trace=>!trace._couldNotFindPort).filter(trace=>trace._isExplicitlyConnectedToPort(this))}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,port_hints=this.getNameAndAliases(),parentNormalComponent=this.getParentNormalComponent(),source_component_id=(this.parent?.source_component_id?this.parent:parentNormalComponent)?.source_component_id??null,pinAttributes=this._getMatchingPinAttributes(),portAttributesFromParent={};for(let attributes2 of pinAttributes)attributes2.mustBeConnected!==void 0&&(portAttributesFromParent.must_be_connected=attributes2.mustBeConnected);let source_port2=db.source_port.insert({name:props.name,pin_number:props.pinNumber,port_hints,source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id,...portAttributesFromParent});this.source_port_id=source_port2.source_port_id}doInitialSourceParentAttachment(){let{db}=this.root,parentNormalComponent=this.getParentNormalComponent(),parentWithSourceId=this.parent?.source_component_id?this.parent:parentNormalComponent;if(this.isGroupPort()){db.source_port.update(this.source_port_id,{source_component_id:null,subcircuit_id:this.getSubcircuit()?.subcircuit_id});return}if(!parentWithSourceId?.source_component_id)throw new Error(`${this.getString()} has no parent source component (parent: ${this.parent?.getString()})`);db.source_port.update(this.source_port_id,{source_component_id:parentWithSourceId.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id}),this.source_component_id=parentWithSourceId.source_component_id}doInitialPcbPortRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{matchedComponents}=this;if(this.isGroupPort()){let connectedPorts=this._getConnectedPortsFromConnectsTo();if(connectedPorts.length===0)return;let connectedPort=connectedPorts[0];if(!connectedPort.pcb_port_id)return;let connectedPcbPort=db.pcb_port.get(connectedPort.pcb_port_id),matchCenter2={x:connectedPcbPort.x,y:connectedPcbPort.y},subcircuit=this.getSubcircuit(),pcb_port2=db.pcb_port.insert({pcb_component_id:void 0,layers:connectedPort.getAvailablePcbLayers(),subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...matchCenter2,source_port_id:this.source_port_id,is_board_pinout:!1});this.pcb_port_id=pcb_port2.pcb_port_id;return}let parentNormalComponent=this.getParentNormalComponent(),parentWithPcbComponentId=this.parent?.pcb_component_id?this.parent:parentNormalComponent;if(!parentWithPcbComponentId?.pcb_component_id)throw new Error(`${this.getString()} has no parent pcb component, cannot render pcb_port (parent: ${this.parent?.getString()}, parentNormalComponent: ${parentNormalComponent?.getString()})`);let pcbMatches=matchedComponents.filter(c3=>c3.isPcbPrimitive);if(pcbMatches.length===0)return;let matchCenter=null;if(pcbMatches.length===1&&(matchCenter=pcbMatches[0]._getPcbCircuitJsonBounds().center),pcbMatches.length>1){if(!areAllPcbPrimitivesOverlapping(pcbMatches))throw new Error(`${this.getString()} has multiple non-overlapping pcb matches, unclear how to place pcb_port: ${pcbMatches.map(c3=>c3.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)`);matchCenter=getCenterOfPcbPrimitives(pcbMatches)}if(matchCenter){let subcircuit=this.getSubcircuit(),isBoardPinout=this._shouldIncludeInBoardPinout(),pcb_port2=db.pcb_port.insert({pcb_component_id:parentWithPcbComponentId.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...isBoardPinout?{is_board_pinout:!0}:{},...matchCenter,source_port_id:this.source_port_id,is_board_pinout:this._isBoardPinoutFromAttributes()});this.pcb_port_id=pcb_port2.pcb_port_id}else{let pcbMatch=pcbMatches[0];throw new Error(`${pcbMatch.getString()} does not have a center or _getGlobalPcbPositionBeforeLayout method (needed for pcb_port placement)`)}}updatePcbPortRender(){if(this.root?.pcbDisabled)return;let{db}=this.root;if(this.pcb_port_id)return;if(this.isGroupPort()){let connectedPorts=this._getConnectedPortsFromConnectsTo();if(connectedPorts.length===0)return;let connectedPort=connectedPorts[0];if(!connectedPort.pcb_port_id)return;let connectedPcbPort=db.pcb_port.get(connectedPort.pcb_port_id),matchCenter2={x:connectedPcbPort.x,y:connectedPcbPort.y},subcircuit2=this.getSubcircuit(),pcb_port22=db.pcb_port.insert({pcb_component_id:void 0,layers:connectedPort.getAvailablePcbLayers(),subcircuit_id:subcircuit2?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...matchCenter2,source_port_id:this.source_port_id,is_board_pinout:!1});this.pcb_port_id=pcb_port22.pcb_port_id;return}let pcbMatches=this.matchedComponents.filter(c3=>c3.isPcbPrimitive);if(pcbMatches.length===0)return;let matchCenter=null;if(pcbMatches.length===1&&(matchCenter=pcbMatches[0]._getPcbCircuitJsonBounds().center),pcbMatches.length>1)try{areAllPcbPrimitivesOverlapping(pcbMatches)&&(matchCenter=getCenterOfPcbPrimitives(pcbMatches))}catch{}if(!matchCenter)return;let parentNormalComponent=this.getParentNormalComponent(),parentWithPcbComponentId=this.parent?.pcb_component_id?this.parent:parentNormalComponent,subcircuit=this.getSubcircuit(),isBoardPinout=this._shouldIncludeInBoardPinout(),pcb_port2=db.pcb_port.insert({pcb_component_id:parentWithPcbComponentId?.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,...isBoardPinout?{is_board_pinout:!0}:{},...matchCenter,source_port_id:this.source_port_id,is_board_pinout:this._isBoardPinoutFromAttributes()});this.pcb_port_id=pcb_port2.pcb_port_id}_getBestDisplayPinLabel(){let{db}=this.root,sourcePort=db.source_port.get(this.source_port_id),labelHints=[];for(let portHint of sourcePort?.port_hints??[])portHint.match(/^(pin)?\d+$/)||portHint.match(/^(left|right)/)&&!sourcePort?.name.match(/^(left|right)/)||labelHints.push(portHint);if(this.getParentNormalComponent()?.props?.showPinAliases&&labelHints.length>0)return labelHints.join("/");if(labelHints.length>0)return labelHints[0]}doInitialSchematicPortRender(){let{db}=this.root,{_parsedProps:props}=this,{schX,schY}=props,container=schX!==void 0&&schY!==void 0?this.getParentNormalComponent():this.getPrimitiveContainer();if(!container||!this._hasSchematicPort())return;let containerCenter=container._getGlobalSchematicPositionBeforeLayout(),portCenter=this._getGlobalSchematicPositionBeforeLayout(),localPortInfo=null,containerDims=container._getSchematicBoxDimensions();containerDims&&props.pinNumber!==void 0&&(localPortInfo=containerDims.getPortPositionByPinNumber(props.pinNumber)),this.getSubcircuit().props._schDebugObjectsEnabled&&db.schematic_debug_object.insert({shape:"rect",center:portCenter,size:{width:.1,height:.1},label:"obstacle"}),localPortInfo?.side?this.facingDirection={left:"left",right:"right",top:"up",bottom:"down"}[localPortInfo.side]:this.facingDirection=getRelativeDirection(containerCenter,portCenter);let bestDisplayPinLabel=this._getBestDisplayPinLabel(),schematicPortInsertProps={type:"schematic_port",schematic_component_id:this.getParentNormalComponent()?.schematic_component_id,center:portCenter,source_port_id:this.source_port_id,facing_direction:this.facingDirection,distance_from_component_edge:.4,side_of_component:localPortInfo?.side,pin_number:props.pinNumber,true_ccw_index:localPortInfo?.trueIndex,display_pin_label:bestDisplayPinLabel,is_connected:!1};for(let attributes2 of this._getMatchingPinAttributes())attributes2.requiresPower&&(schematicPortInsertProps.has_input_arrow=!0),attributes2.providesPower&&(schematicPortInsertProps.has_output_arrow=!0);let schematic_port2=db.schematic_port.insert(schematicPortInsertProps);this.schematic_port_id=schematic_port2.schematic_port_id}_getSubcircuitConnectivityKey(){return this.root?.db.source_port.get(this.source_port_id)?.subcircuit_connectivity_map_key}_setPositionFromLayout(newCenter){let{db}=this.root;this.pcb_port_id&&db.pcb_port.update(this.pcb_port_id,{x:newCenter.x,y:newCenter.y})}_hasMatchedPcbPrimitive(){return this.matchedComponents.some(c3=>c3.isPcbPrimitive)}_getNetLabelText(){return`${this.parent?.props.name}_${this.props.name}`}},getPinNumberFromLabels=labels=>{let pinNumber=labels.find(p4=>/^(pin)?\d+$/.test(p4));return pinNumber?Number.parseInt(pinNumber.replace(/^pin/,"")):null};function getPortFromHints(hints,opts){let pinNumber=getPinNumberFromLabels(hints);if(!pinNumber)return null;let aliases2=[...hints.filter(p4=>p4.toString()!==pinNumber.toString()&&p4!==`pin${pinNumber}`),...opts?.additionalAliases?.[`pin${pinNumber}`]??[]];return new Port({pinNumber,aliases:aliases2})}var hasExplicitPinMapping=pa2=>{for(let side of["leftSide","rightSide","topSide","bottomSide"])if(side in pa2&&typeof pa2[side]=="number")throw new Error(`A number was specified for "${side}", you probably meant to use "size" not "side"`);return"leftSide"in pa2||"rightSide"in pa2||"topSide"in pa2||"bottomSide"in pa2},getSizeOfSidesFromPortArrangement=pa2=>{if(hasExplicitPinMapping(pa2))return{leftSize:pa2.leftSide?.pins.length??0,rightSize:pa2.rightSide?.pins.length??0,topSize:pa2.topSide?.pins.length??0,bottomSize:pa2.bottomSide?.pins.length??0};let{leftSize=0,rightSize=0,topSize=0,bottomSize=0}=pa2;return{leftSize,rightSize,topSize,bottomSize}},DEFAULT_SCHEMATIC_BOX_PADDING_MM=.4;function isExplicitPinMappingArrangement(arrangement){let a3=arrangement;return a3.leftSide!==void 0||a3.rightSide!==void 0||a3.topSide!==void 0||a3.bottomSide!==void 0}var getAllDimensionsForSchematicBox=params=>{let portDistanceFromEdge=params.portDistanceFromEdge??.4,sidePinCounts=params.schPortArrangement?getSizeOfSidesFromPortArrangement(params.schPortArrangement):null,sideLengths={left:0,right:0,top:0,bottom:0},pinCount=params.pinCount??null;if(pinCount===null)if(sidePinCounts)pinCount=sidePinCounts.leftSize+sidePinCounts.rightSize+sidePinCounts.topSize;else throw new Error("Could not determine pin count for the schematic box");if(pinCount&&!sidePinCounts){let rightSize=Math.floor(pinCount/2);sidePinCounts={leftSize:pinCount-rightSize,rightSize,topSize:0,bottomSize:0}}sidePinCounts||(sidePinCounts={leftSize:0,rightSize:0,topSize:0,bottomSize:0});let getPinNumberUsingSideIndex=({side,sideIndex,truePinIndex:truePinIndex2})=>{if(!params.schPortArrangement||!isExplicitPinMappingArrangement(params.schPortArrangement))return truePinIndex2+1;let normalCcwDirection={left:"top-to-bottom",bottom:"left-to-right",right:"bottom-to-top",top:"right-to-left"}[side],directionAlongSide=params.schPortArrangement?.[`${side}Side`]?.direction??normalCcwDirection,pinsDefinitionForSide=params.schPortArrangement?.[`${side}Side`]?.pins,sideIndexWithDirectionCorrection=sideIndex;return directionAlongSide!==normalCcwDirection&&(sideIndexWithDirectionCorrection=pinsDefinitionForSide.length-sideIndex-1),parsePinNumberFromLabelsOrThrow(pinsDefinitionForSide[sideIndexWithDirectionCorrection],params.pinLabels)},orderedTruePorts=[],currentDistanceFromEdge=0,truePinIndex=0;for(let sideIndex=0;sideIndex<sidePinCounts.leftSize;sideIndex++){let pinNumber=getPinNumberUsingSideIndex({side:"left",sideIndex,truePinIndex}),pinStyle=params.numericSchPinStyle?.[`pin${pinNumber}`]??params.numericSchPinStyle?.[pinNumber];pinStyle?.topMargin&&(currentDistanceFromEdge+=pinStyle.topMargin),orderedTruePorts.push({trueIndex:truePinIndex,pinNumber,side:"left",distanceFromOrthogonalEdge:currentDistanceFromEdge}),pinStyle?.bottomMargin&&(currentDistanceFromEdge+=pinStyle.bottomMargin),sideIndex===sidePinCounts.leftSize-1?sideLengths.left=currentDistanceFromEdge:currentDistanceFromEdge+=params.schPinSpacing,truePinIndex++}currentDistanceFromEdge=0;for(let sideIndex=0;sideIndex<sidePinCounts.bottomSize;sideIndex++){let pinNumber=getPinNumberUsingSideIndex({side:"bottom",sideIndex,truePinIndex}),pinStyle=params.numericSchPinStyle?.[`pin${pinNumber}`]??params.numericSchPinStyle?.[pinNumber];pinStyle?.leftMargin&&(currentDistanceFromEdge+=pinStyle.leftMargin),orderedTruePorts.push({trueIndex:truePinIndex,pinNumber,side:"bottom",distanceFromOrthogonalEdge:currentDistanceFromEdge}),pinStyle?.rightMargin&&(currentDistanceFromEdge+=pinStyle.rightMargin),sideIndex===sidePinCounts.bottomSize-1?sideLengths.bottom=currentDistanceFromEdge:currentDistanceFromEdge+=params.schPinSpacing,truePinIndex++}currentDistanceFromEdge=0;for(let sideIndex=0;sideIndex<sidePinCounts.rightSize;sideIndex++){let pinNumber=getPinNumberUsingSideIndex({side:"right",sideIndex,truePinIndex}),pinStyle=params.numericSchPinStyle?.[`pin${pinNumber}`]??params.numericSchPinStyle?.[pinNumber];pinStyle?.bottomMargin&&(currentDistanceFromEdge+=pinStyle.bottomMargin),orderedTruePorts.push({trueIndex:truePinIndex,pinNumber,side:"right",distanceFromOrthogonalEdge:currentDistanceFromEdge}),pinStyle?.topMargin&&(currentDistanceFromEdge+=pinStyle.topMargin),sideIndex===sidePinCounts.rightSize-1?sideLengths.right=currentDistanceFromEdge:currentDistanceFromEdge+=params.schPinSpacing,truePinIndex++}currentDistanceFromEdge=0;for(let sideIndex=0;sideIndex<sidePinCounts.topSize;sideIndex++){let pinNumber=getPinNumberUsingSideIndex({side:"top",sideIndex,truePinIndex}),pinStyle=params.numericSchPinStyle?.[`pin${pinNumber}`]??params.numericSchPinStyle?.[pinNumber];pinStyle?.rightMargin&&(currentDistanceFromEdge+=pinStyle.rightMargin),orderedTruePorts.push({trueIndex:truePinIndex,pinNumber,side:"top",distanceFromOrthogonalEdge:currentDistanceFromEdge}),pinStyle?.leftMargin&&(currentDistanceFromEdge+=pinStyle.leftMargin),sideIndex===sidePinCounts.topSize-1?sideLengths.top=currentDistanceFromEdge:currentDistanceFromEdge+=params.schPinSpacing,truePinIndex++}let resolvedSchWidth=params.schWidth;if(resolvedSchWidth===void 0){resolvedSchWidth=Math.max(sideLengths.top+DEFAULT_SCHEMATIC_BOX_PADDING_MM,sideLengths.bottom+DEFAULT_SCHEMATIC_BOX_PADDING_MM),params.pinLabels&&orderedTruePorts.filter(p4=>p4.side==="left"||p4.side==="right").some(p4=>params.pinLabels?.[`pin${p4.pinNumber}`]||params.pinLabels?.[p4.pinNumber])&&(resolvedSchWidth=Math.max(resolvedSchWidth,.5));let labelWidth=params.pinLabels?Math.max(...Object.values(params.pinLabels).map(label=>label.length*.1)):0,LABEL_PADDING=labelWidth>0?1.1:0;resolvedSchWidth=Math.max(resolvedSchWidth,labelWidth+LABEL_PADDING)}let schHeight=params.schHeight;schHeight||(schHeight=Math.max(sideLengths.left+DEFAULT_SCHEMATIC_BOX_PADDING_MM,sideLengths.right+DEFAULT_SCHEMATIC_BOX_PADDING_MM));let trueEdgePositions={left:{x:-resolvedSchWidth/2-portDistanceFromEdge,y:sideLengths.left/2},bottom:{x:-sideLengths.bottom/2,y:-schHeight/2-portDistanceFromEdge},right:{x:resolvedSchWidth/2+portDistanceFromEdge,y:-sideLengths.right/2},top:{x:sideLengths.top/2,y:schHeight/2+portDistanceFromEdge}},trueEdgeTraversalDirections={left:{x:0,y:-1},right:{x:0,y:1},top:{x:-1,y:0},bottom:{x:1,y:0}},truePortsWithPositions=orderedTruePorts.map(p4=>{let{distanceFromOrthogonalEdge,side}=p4,edgePos=trueEdgePositions[side],edgeDir=trueEdgeTraversalDirections[side];return{x:edgePos.x+distanceFromOrthogonalEdge*edgeDir.x,y:edgePos.y+distanceFromOrthogonalEdge*edgeDir.y,...p4}});return{getPortPositionByPinNumber(pinNumber){let port=truePortsWithPositions.find(p4=>p4.pinNumber.toString()===pinNumber.toString());return port||null},getSize(){return{width:resolvedSchWidth,height:schHeight}},getSizeIncludingPins(){return{width:resolvedSchWidth+(sidePinCounts.leftSize||sidePinCounts.rightSize?.4:0),height:schHeight+(sidePinCounts.topSize||sidePinCounts.bottomSize?.4:0)}},pinCount}},debug22=(0,import_debug8.default)("tscircuit:core:footprint"),Footprint=class extends PrimitiveComponent2{get config(){return{componentName:"Footprint",zodProps:footprintProps}}doInitialPcbFootprintLayout(){if(this.root?.pcbDisabled)return;let constraints=this.children.filter(child=>child.componentName==="Constraint");if(constraints.length===0)return;let{isFlipped}=this._getPcbPrimitiveFlippedHelpers(),maybeFlipLeftRight=props=>isFlipped&&"left"in props&&"right"in props?{...props,left:props.right,right:props.left}:props,involvedComponents=constraints.flatMap(constraint=>constraint._getAllReferencedComponents().componentsWithSelectors).map(({component,selector,componentSelector,edge})=>({component,selector,componentSelector,edge,bounds:component._getPcbCircuitJsonBounds()}));if(involvedComponents.some(c3=>c3.edge))throw new Error("edge constraints not implemented yet for footprint layout, contributions welcome!");function getComponentDetails(selector){return involvedComponents.find(({selector:s4})=>s4===selector)}let solver=new Solver,kVars={};function getKVar(name){return name in kVars||(kVars[name]=new Variable(name),solver.addEditVariable(kVars[name],Strength.weak)),kVars[name]}for(let{selector,bounds:bounds2}of involvedComponents){let kvx=getKVar(`${selector}_x`),kvy=getKVar(`${selector}_y`);solver.suggestValue(kvx,bounds2.center.x),solver.suggestValue(kvy,bounds2.center.y)}for(let constraint of constraints){let props=constraint._parsedProps;if("xDist"in props){let{xDist,left,right,edgeToEdge,centerToCenter}=maybeFlipLeftRight(props),leftVar=getKVar(`${left}_x`),rightVar=getKVar(`${right}_x`),leftBounds=getComponentDetails(left)?.bounds,rightBounds=getComponentDetails(right)?.bounds;if(centerToCenter){let expr=new Expression(rightVar,[-1,leftVar]);solver.addConstraint(new Constraint(expr,Operator.Eq,props.xDist,Strength.required))}else if(edgeToEdge){let expr=new Expression(rightVar,-rightBounds.width/2,[-1,leftVar],-leftBounds.width/2);solver.addConstraint(new Constraint(expr,Operator.Eq,props.xDist,Strength.required))}}else if("yDist"in props){let{yDist,top,bottom,edgeToEdge,centerToCenter}=props,topVar=getKVar(`${top}_y`),bottomVar=getKVar(`${bottom}_y`),topBounds=getComponentDetails(top)?.bounds,bottomBounds=getComponentDetails(bottom)?.bounds;if(centerToCenter){let expr=new Expression(topVar,[-1,bottomVar]);solver.addConstraint(new Constraint(expr,Operator.Eq,props.yDist,Strength.required))}else if(edgeToEdge){let expr=new Expression(topVar,topBounds.height/2,[-1,bottomVar],-bottomBounds.height/2);solver.addConstraint(new Constraint(expr,Operator.Eq,props.yDist,Strength.required))}}else if("sameY"in props){let{for:selectors}=props;if(selectors.length<2)continue;let vars=selectors.map(selector=>getKVar(`${selector}_y`)),expr=new Expression(...vars.slice(1));solver.addConstraint(new Constraint(expr,Operator.Eq,vars[0],Strength.required))}else if("sameX"in props){let{for:selectors}=props;if(selectors.length<2)continue;let vars=selectors.map(selector=>getKVar(`${selector}_x`)),expr=new Expression(...vars.slice(1));solver.addConstraint(new Constraint(expr,Operator.Eq,vars[0],Strength.required))}}solver.updateVariables(),debug22.enabled&&(console.log("Solution to layout constraints:"),console.table(Object.entries(kVars).map(([key,kvar])=>({var:key,val:kvar.value()}))));let bounds={left:1/0,right:-1/0,top:-1/0,bottom:1/0};for(let{selector,bounds:{width,height}}of involvedComponents){let kvx=getKVar(`${selector}_x`),kvy=getKVar(`${selector}_y`),newLeft=kvx.value()-width/2,newRight=kvx.value()+width/2,newTop=kvy.value()+height/2,newBottom=kvy.value()-height/2;bounds.left=Math.min(bounds.left,newLeft),bounds.right=Math.max(bounds.right,newRight),bounds.top=Math.max(bounds.top,newTop),bounds.bottom=Math.min(bounds.bottom,newBottom)}let globalOffset={x:-(bounds.right+bounds.left)/2,y:-(bounds.top+bounds.bottom)/2},containerPos=this.getPrimitiveContainer()._getGlobalPcbPositionBeforeLayout();globalOffset.x+=containerPos.x,globalOffset.y+=containerPos.y;for(let{component,selector}of involvedComponents){let kvx=getKVar(`${selector}_x`),kvy=getKVar(`${selector}_y`);component._setPositionFromLayout({x:kvx.value()+globalOffset.x,y:kvy.value()+globalOffset.y})}}},getFileExtension=filename=>{if(!filename)return null;let fragmentMatch=filename.match(/#ext=(\w+)$/);if(fragmentMatch)return fragmentMatch[1].toLowerCase();let sanitized=filename.split("?")[0].split("#")[0],lastSegment=sanitized.split("/").pop()??sanitized;return lastSegment.includes(".")?lastSegment.split(".").pop()?.toLowerCase()??null:null},joinUrlPath=(base,path)=>{let trimmedBase=base.replace(/\/+$/,""),trimmedPath=path.replace(/^\/+/,"");return`${trimmedBase}/${trimmedPath}`},constructAssetUrl=(targetUrl,baseUrl)=>{if(!baseUrl||!targetUrl.startsWith("/"))return targetUrl;try{let baseUrlObj=new URL(baseUrl);return baseUrlObj.pathname!=="/"&&targetUrl.startsWith(baseUrlObj.pathname)?new URL(targetUrl,baseUrlObj.origin).toString():joinUrlPath(baseUrl,targetUrl)}catch{return targetUrl}},rotation2=external_exports.union([external_exports.number(),external_exports.string()]),rotation3=external_exports.object({x:rotation2,y:rotation2,z:rotation2}),CadModel=class extends PrimitiveComponent2{get config(){return{componentName:"CadModel",zodProps:cadmodelProps}}doInitialCadModelRender(){let parent=this._findParentWithPcbComponent();if(!parent||!parent.pcb_component_id)return;let{db}=this.root,{boardThickness=0}=this.root?._getBoard()??{},bounds=parent._getPcbCircuitJsonBounds(),pcb_component2=db.pcb_component.get(parent.pcb_component_id),props=this._parsedProps;if(!props||typeof props.modelUrl!="string"&&typeof props.stepUrl!="string")return;let parentTransform=parent._computePcbGlobalTransformBeforeLayout(),accumulatedRotation=decomposeTSR(parentTransform).rotation.angle*180/Math.PI,rotationOffset=rotation3.parse({x:0,y:0,z:0});if(typeof props.rotationOffset=="number")rotationOffset.z=Number(props.rotationOffset);else if(typeof props.rotationOffset=="object"){let parsed=rotation3.parse(props.rotationOffset);rotationOffset.x=Number(parsed.x),rotationOffset.y=Number(parsed.y),rotationOffset.z=Number(parsed.z)}let{pcbX,pcbY}=this.getResolvedPcbPositionProp(),positionOffset=point32.parse({x:pcbX,y:pcbY,z:props.pcbZ??0,...typeof props.positionOffset=="object"?props.positionOffset:{}}),zOffsetFromSurface=props.zOffsetFromSurface!==void 0?distance.parse(props.zOffsetFromSurface):0,layer=parent.props.layer==="bottom"?"bottom":"top",ext=props.modelUrl?getFileExtension(props.modelUrl):void 0,modelUrlWithoutExtFragment=props.modelUrl?.replace(/#ext=\w+$/,""),urlProps={};if(ext==="stl"?urlProps.model_stl_url=this._addCachebustToModelUrl(modelUrlWithoutExtFragment):ext==="obj"?urlProps.model_obj_url=this._addCachebustToModelUrl(modelUrlWithoutExtFragment):ext==="gltf"?urlProps.model_gltf_url=this._addCachebustToModelUrl(modelUrlWithoutExtFragment):ext==="glb"?urlProps.model_glb_url=this._addCachebustToModelUrl(modelUrlWithoutExtFragment):ext==="step"||ext==="stp"?urlProps.model_step_url=this._addCachebustToModelUrl(modelUrlWithoutExtFragment):ext==="wrl"||ext==="vrml"?urlProps.model_wrl_url=this._addCachebustToModelUrl(modelUrlWithoutExtFragment):urlProps.model_stl_url=this._addCachebustToModelUrl(modelUrlWithoutExtFragment),props.stepUrl){let transformed=this._addCachebustToModelUrl(props.stepUrl);transformed&&(urlProps.model_step_url=transformed)}let cad=db.cad_component.insert({position:{x:bounds.center.x+Number(positionOffset.x),y:bounds.center.y+Number(positionOffset.y),z:(layer==="bottom"?-boardThickness/2:boardThickness/2)+(layer==="bottom"?-zOffsetFromSurface:zOffsetFromSurface)+Number(positionOffset.z)},rotation:{x:Number(rotationOffset.x),y:(layer==="top"?0:180)+Number(rotationOffset.y),z:layer==="bottom"?-(accumulatedRotation+Number(rotationOffset.z))+180:accumulatedRotation+Number(rotationOffset.z)},pcb_component_id:parent.pcb_component_id,source_component_id:parent.source_component_id,model_unit_to_mm_scale_factor:typeof props.modelUnitToMmScale=="number"?props.modelUnitToMmScale:void 0,show_as_translucent_model:parent._parsedProps.showAsTranslucentModel,...urlProps});this.cad_component_id=cad.cad_component_id}_findParentWithPcbComponent(){let p4=this.parent;for(;p4&&!p4.pcb_component_id;)p4=p4.parent;return p4}_addCachebustToModelUrl(url){if(!url)return url;let baseUrl=this.root?.platform?.projectBaseUrl,transformedUrl=constructAssetUrl(url,baseUrl);if(!transformedUrl.includes("modelcdn.tscircuit.com"))return transformedUrl;let origin=this.root?.getClientOrigin()??"";return`${transformedUrl}${transformedUrl.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(origin)}`}},CadAssembly=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"CadAssembly",zodProps:cadassemblyProps}}},getNumericSchPinStyle=(pinStyles,pinLabels)=>{if(!pinStyles)return;let numericPinStyles={};for(let[pinNameOrLabel,pinStyle]of Object.entries(pinStyles)){let pinNumber=parsePinNumberFromLabelsOrThrow(pinNameOrLabel,pinLabels),pinStyleWithSideFirst={leftMargin:pinStyle.marginLeft??pinStyle.leftMargin,rightMargin:pinStyle.marginRight??pinStyle.rightMargin,topMargin:pinStyle.marginTop??pinStyle.topMargin,bottomMargin:pinStyle.marginBottom??pinStyle.bottomMargin};numericPinStyles[`pin${pinNumber}`]={...numericPinStyles[`pin${pinNumber}`],...pinStyleWithSideFirst}}return numericPinStyles},DirectLineRouter=class{constructor({input:input2}){__publicField(this,"input");this.input=input2}solveAndMapToTraces(){let traces=[];for(let connection of this.input.connections){if(connection.pointsToConnect.length!==2)continue;let[start,end]=connection.pointsToConnect,trace={type:"pcb_trace",pcb_trace_id:"",connection_name:connection.name,route:[{route_type:"wire",x:start.x,y:start.y,layer:"top",width:.1},{route_type:"wire",x:end.x,y:end.y,layer:"top",width:.1}]};traces.push(trace)}return traces}},computeObstacleBounds=obstacles=>{let minX=Math.min(...obstacles.map(o3=>o3.center.x)),maxX=Math.max(...obstacles.map(o3=>o3.center.x)),minY=Math.min(...obstacles.map(o3=>o3.center.y)),maxY=Math.max(...obstacles.map(o3=>o3.center.y));return{minX,maxX,minY,maxY}},LAYER_SELECTION_PREFERENCE=["top","bottom","inner1","inner2"],findPossibleTraceLayerCombinations=(hints,layer_path=[])=>{let candidates=[];if(layer_path.length===0){let starting_layers=hints[0].layers;for(let layer of starting_layers)candidates.push(...findPossibleTraceLayerCombinations(hints.slice(1),[layer]));return candidates}if(hints.length===0)return[];let current_hint=hints[0],is_possibly_via=current_hint.via||current_hint.optional_via,last_layer=layer_path[layer_path.length-1];if(hints.length===1){let last_hint=current_hint;return last_hint.layers&&is_possibly_via?last_hint.layers.map(layer=>({layer_path:[...layer_path,layer]})):last_hint.layers?.includes(last_layer)?[{layer_path:[...layer_path,last_layer]}]:[]}if(!is_possibly_via)return current_hint.layers&&!current_hint.layers.includes(last_layer)?[]:findPossibleTraceLayerCombinations(hints.slice(1),layer_path.concat([last_layer]));let candidate_next_layers=(current_hint.optional_via?LAYER_SELECTION_PREFERENCE:LAYER_SELECTION_PREFERENCE.filter(layer=>layer!==last_layer)).filter(layer=>!current_hint.layers||current_hint.layers?.includes(layer));for(let candidate_next_layer of candidate_next_layers)candidates.push(...findPossibleTraceLayerCombinations(hints.slice(1),layer_path.concat(candidate_next_layer)));return candidates};function getDominantDirection(edge){let delta={x:edge.to.x-edge.from.x,y:edge.to.y-edge.from.y},absX=Math.abs(delta.x),absY=Math.abs(delta.y);return absX>absY?delta.x>0?"right":"left":delta.y>0?"down":"up"}function pdist(a3,b3){return Math.hypot(a3.x-b3.x,a3.y-b3.y)}var mergeRoutes=routes=>{if(routes.length===1)return routes[0];if(routes.some(r4=>r4.length===0))throw new Error("Cannot merge routes with zero length");let merged=[],first_route_fp=routes[0][0],first_route_lp=routes[0][routes[0].length-1],second_route_fp=routes[1][0],second_route_lp=routes[1][routes[1].length-1],best_reverse_dist=Math.min(pdist(first_route_fp,second_route_fp),pdist(first_route_fp,second_route_lp)),best_normal_dist=Math.min(pdist(first_route_lp,second_route_fp),pdist(first_route_lp,second_route_lp));best_reverse_dist<best_normal_dist?merged.push(...routes[0].reverse()):merged.push(...routes[0]);for(let i3=1;i3<routes.length;i3++){let last_merged_point=merged[merged.length-1],next_route=routes[i3],next_first_point=next_route[0],next_last_point=next_route[next_route.length-1],distance_to_first=pdist(last_merged_point,next_first_point),distance_to_last=pdist(last_merged_point,next_last_point);distance_to_first<distance_to_last?merged.push(...next_route):merged.push(...next_route.reverse())}for(let i3=1;i3<merged.length-1;i3++){let lastPoint=merged[i3-1],currentPoint=merged[i3];lastPoint.route_type==="wire"&&currentPoint.route_type==="wire"&&lastPoint.layer!==currentPoint.layer&&merged.splice(i3,0,{x:lastPoint.x,y:lastPoint.y,from_layer:lastPoint.layer,to_layer:currentPoint.layer,route_type:"via"})}return merged},getDistance=(a3,b3)=>{let aPos="_getGlobalPcbPositionBeforeLayout"in a3?a3._getGlobalPcbPositionBeforeLayout():a3,bPos="_getGlobalPcbPositionBeforeLayout"in b3?b3._getGlobalPcbPositionBeforeLayout():b3;return Math.sqrt((aPos.x-bPos.x)**2+(aPos.y-bPos.y)**2)};function getClosest(point23,candidates){if(candidates.length===0)throw new Error("No candidates given to getClosest method");let closest=candidates[0],closestDist=1/0;for(let candidate of candidates){let dist=getDistance(point23,candidate);dist<closestDist&&(closest=candidate,closestDist=dist)}return closest}var countComplexElements=(junctions,edges)=>{let count=0;count+=junctions.length??0,count+=edges.filter(edge=>edge.is_crossing).length;for(let i3=1;i3<edges.length;i3++){let prev=edges[i3-1],curr=edges[i3],prevVertical=Math.abs(prev.from.x-prev.to.x)<.01,currVertical=Math.abs(curr.from.x-curr.to.x)<.01;prevVertical!==currVertical&&count++}return count},getEnteringEdgeFromDirection=direction2=>({up:"bottom",down:"top",left:"right",right:"left"})[direction2]??null,getStubEdges=({firstEdge,firstEdgePort,firstDominantDirection,lastEdge,lastEdgePort,lastDominantDirection})=>{if(firstEdge&&firstEdgePort)return getStubEdges({lastEdge:{from:firstEdge.to,to:firstEdge.from},lastEdgePort:firstEdgePort,lastDominantDirection:firstDominantDirection}).reverse().map(e4=>({from:e4.to,to:e4.from}));let edges=[];if(lastEdge&&lastEdgePort){let intermediatePoint={x:lastEdge.to.x,y:lastEdge.to.y};lastDominantDirection==="left"||lastDominantDirection==="right"?(intermediatePoint.x=lastEdgePort.position.x,edges.push({from:lastEdge.to,to:{...intermediatePoint}}),edges.push({from:intermediatePoint,to:{...lastEdgePort.position}})):(intermediatePoint.y=lastEdgePort.position.y,edges.push({from:lastEdge.to,to:{...intermediatePoint}}),edges.push({from:intermediatePoint,to:{...lastEdgePort.position}}))}return edges=edges.filter(e4=>distance4(e4.from,e4.to)>.01),edges};function tryNow(fn3){try{return[fn3(),null]}catch(e4){return[null,e4]}}var getMaxLengthFromConnectedCapacitors=(ports,{db})=>{let capacitorMaxLengths=ports.map(port=>{let sourcePort=db.source_port.get(port.source_port_id);if(!sourcePort?.source_component_id)return null;let sourceComponent=db.source_component.get(sourcePort.source_component_id);return sourceComponent?.ftype==="simple_capacitor"?sourceComponent.max_decoupling_trace_length:null}).filter(length7=>length7!==null);if(capacitorMaxLengths.length!==0)return Math.min(...capacitorMaxLengths)};function getTraceDisplayName({ports,nets}){if(ports.length>=2)return`${ports[0]?.selector} to ${ports[1]?.selector}`;if(ports.length===1&&nets.length===1)return`${ports[0]?.selector} to net.${nets[0]._parsedProps.name}`}var isRouteOutsideBoard=(mergedRoute,{db})=>{let pcbBoard=db.pcb_board.list()[0];if(pcbBoard.outline){let boardOutline=pcbBoard.outline,isInsidePolygon=(point23,polygon2)=>{let inside2=!1;for(let i3=0,j3=polygon2.length-1;i3<polygon2.length;j3=i3++){let xi3=polygon2[i3].x,yi3=polygon2[i3].y,xj=polygon2[j3].x,yj=polygon2[j3].y;yi3>point23.y!=yj>point23.y&&point23.x<(xj-xi3)*(point23.y-yi3)/(yj-yi3)+xi3&&(inside2=!inside2)}return inside2};return mergedRoute.some(point23=>!isInsidePolygon(point23,boardOutline))}let boardWidth=pcbBoard.width,boardHeight=pcbBoard.height,boardCenterX=pcbBoard.center.x,boardCenterY=pcbBoard.center.y;return mergedRoute.some(point23=>point23.x<boardCenterX-boardWidth/2||point23.y<boardCenterY-boardHeight/2||point23.x>boardCenterX+boardWidth/2||point23.y>boardCenterY+boardHeight/2)},isCloseTo2=(a3,b3)=>Math.abs(a3-b3)<1e-4,getObstaclesFromRoute2=(route,source_trace_id,{viaDiameter=.5}={})=>{let obstacles=[];for(let i3=0;i3<route.length-1;i3++){let[start,end]=[route[i3],route[i3+1]],prev=i3-1>=0?route[i3-1]:null,isHorz=isCloseTo2(start.y,end.y),isVert=isCloseTo2(start.x,end.x);if(!isHorz&&!isVert)throw new Error(`getObstaclesFromTrace currently only supports horizontal and vertical traces (not diagonals) Conflicting trace: ${source_trace_id}, start: (${start.x}, ${start.y}), end: (${end.x}, ${end.y})`);let obstacle={type:"rect",layers:[start.layer],center:{x:(start.x+end.x)/2,y:(start.y+end.y)/2},width:isHorz?Math.abs(start.x-end.x):.1,height:isVert?Math.abs(start.y-end.y):.1,connectedTo:[source_trace_id]};if(obstacles.push(obstacle),prev&&prev.layer===start.layer&&start.layer!==end.layer){let via={type:"rect",layers:[start.layer,end.layer],center:{x:start.x,y:start.y},connectedTo:[source_trace_id],width:viaDiameter,height:viaDiameter};obstacles.push(via)}}return obstacles};function generateApproximatingRects2(rotatedRect,numRects=4){let{center:center2,width,height,rotation:rotation4}=rotatedRect,rects=[],angleRad=rotation4*Math.PI/180,cosAngle=Math.cos(angleRad),sinAngle=Math.sin(angleRad),normalizedRotation=(rotation4%360+360)%360;if(height<=width?normalizedRotation>=45&&normalizedRotation<135||normalizedRotation>=225&&normalizedRotation<315:normalizedRotation>=135&&normalizedRotation<225||normalizedRotation>=315||normalizedRotation<45){let sliceWidth=width/numRects;for(let i3=0;i3<numRects;i3++){let x3=(i3-numRects/2+.5)*sliceWidth,rotatedX=-x3*cosAngle,rotatedY=-x3*sinAngle,coverageWidth=sliceWidth*1.1,coverageHeight=Math.abs(height*cosAngle)+Math.abs(sliceWidth*sinAngle);rects.push({center:{x:center2.x+rotatedX,y:center2.y+rotatedY},width:coverageWidth,height:coverageHeight})}}else{let sliceHeight=height/numRects;for(let i3=0;i3<numRects;i3++){let y3=(i3-numRects/2+.5)*sliceHeight,rotatedX=-y3*sinAngle,rotatedY=y3*cosAngle,coverageWidth=Math.abs(width*cosAngle)+Math.abs(sliceHeight*sinAngle),coverageHeight=sliceHeight*1.1;rects.push({center:{x:center2.x+rotatedX,y:center2.y+rotatedY},width:coverageWidth,height:coverageHeight})}}return rects}function fillPolygonWithRects(polygon2,options={}){if(polygon2.length<3)return[];let{rectHeight=.1}=options,rects=[],yCoords=polygon2.map(p4=>p4.y),minY=Math.min(...yCoords),maxY=Math.max(...yCoords);for(let y3=minY;y3<maxY;y3+=rectHeight){let scanlineY=y3+rectHeight/2,intersections=[];for(let i3=0;i3<polygon2.length;i3++){let p12=polygon2[i3],p22=polygon2[(i3+1)%polygon2.length];if(p12.y<=scanlineY&&p22.y>scanlineY||p22.y<=scanlineY&&p12.y>scanlineY){let x3=(scanlineY-p12.y)*(p22.x-p12.x)/(p22.y-p12.y)+p12.x;intersections.push(x3)}}intersections.sort((a3,b3)=>a3-b3);for(let i3=0;i3<intersections.length;i3+=2)if(i3+1<intersections.length){let x12=intersections[i3],width=intersections[i3+1]-x12;width>1e-6&&rects.push({center:{x:x12+width/2,y:scanlineY},width,height:rectHeight})}}return rects}function fillCircleWithRects(circle2,options={}){let{center:center2,radius}=circle2,{rectHeight=.1}=options,rects=[],numSlices=Math.ceil(radius*2/rectHeight);for(let i3=0;i3<numSlices;i3++){let y3=center2.y-radius+(i3+.5)*rectHeight,dy2=y3-center2.y,halfWidth=Math.sqrt(radius*radius-dy2*dy2);halfWidth>0&&rects.push({center:{x:center2.x,y:y3},width:halfWidth*2,height:rectHeight})}return rects}var EVERY_LAYER2=["top","inner1","inner2","bottom"],getObstaclesFromCircuitJson2=(soup,connMap)=>{let withNetId=idList=>connMap?idList.concat(idList.map(id=>connMap?.getNetConnectedToId(id)).filter(Boolean)):idList,obstacles=[];for(let element of soup)if(element.type==="pcb_smtpad"){if(element.shape==="circle")obstacles.push({type:"oval",layers:[element.layer],center:{x:element.x,y:element.y},width:element.radius*2,height:element.radius*2,connectedTo:withNetId([element.pcb_smtpad_id])});else if(element.shape==="rect")obstacles.push({type:"rect",layers:[element.layer],center:{x:element.x,y:element.y},width:element.width,height:element.height,connectedTo:withNetId([element.pcb_smtpad_id])});else if(element.shape==="rotated_rect"){let rotatedRect={center:{x:element.x,y:element.y},width:element.width,height:element.height,rotation:element.ccw_rotation},approximatingRects=generateApproximatingRects2(rotatedRect);for(let rect of approximatingRects)obstacles.push({type:"rect",layers:[element.layer],center:rect.center,width:rect.width,height:rect.height,connectedTo:withNetId([element.pcb_smtpad_id])})}}else if(element.type==="pcb_keepout")element.shape==="circle"?obstacles.push({type:"oval",layers:element.layers,center:{x:element.center.x,y:element.center.y},width:element.radius*2,height:element.radius*2,connectedTo:[]}):element.shape==="rect"&&obstacles.push({type:"rect",layers:element.layers,center:{x:element.center.x,y:element.center.y},width:element.width,height:element.height,connectedTo:[]});else if(element.type==="pcb_cutout"){if(element.shape==="rect")obstacles.push({type:"rect",layers:EVERY_LAYER2,center:{x:element.center.x,y:element.center.y},width:element.width,height:element.height,connectedTo:[]});else if(element.shape==="circle"){let approximatingRects=fillCircleWithRects({center:element.center,radius:element.radius},{rectHeight:.6});for(let rect of approximatingRects)obstacles.push({type:"rect",layers:EVERY_LAYER2,center:rect.center,width:rect.width,height:rect.height,connectedTo:[]})}else if(element.shape==="polygon"){let approximatingRects=fillPolygonWithRects(element.points,{rectHeight:.6});for(let rect of approximatingRects)obstacles.push({type:"rect",layers:EVERY_LAYER2,center:rect.center,width:rect.width,height:rect.height,connectedTo:[]})}}else if(element.type==="pcb_hole")element.hole_shape==="oval"?obstacles.push({type:"oval",center:{x:element.x,y:element.y},width:element.hole_width,height:element.hole_height,connectedTo:[]}):element.hole_shape==="rect"?obstacles.push({type:"rect",layers:EVERY_LAYER2,center:{x:element.x,y:element.y},width:element.hole_width,height:element.hole_height,connectedTo:[]}):element.hole_shape==="square"?obstacles.push({type:"rect",layers:EVERY_LAYER2,center:{x:element.x,y:element.y},width:element.hole_diameter,height:element.hole_diameter,connectedTo:[]}):(element.hole_shape==="round"||element.hole_shape==="circle")&&obstacles.push({type:"rect",layers:EVERY_LAYER2,center:{x:element.x,y:element.y},width:element.hole_diameter,height:element.hole_diameter,connectedTo:[]});else if(element.type==="pcb_plated_hole"){if(element.shape==="circle")obstacles.push({type:"oval",layers:EVERY_LAYER2,center:{x:element.x,y:element.y},width:element.outer_diameter,height:element.outer_diameter,connectedTo:withNetId([element.pcb_plated_hole_id])});else if(element.shape==="circular_hole_with_rect_pad")obstacles.push({type:"rect",layers:EVERY_LAYER2,center:{x:element.x,y:element.y},width:element.rect_pad_width,height:element.rect_pad_height,connectedTo:withNetId([element.pcb_plated_hole_id])});else if(element.shape==="oval"||element.shape==="pill")obstacles.push({type:"oval",layers:EVERY_LAYER2,center:{x:element.x,y:element.y},width:element.outer_width,height:element.outer_height,connectedTo:withNetId([element.pcb_plated_hole_id])});else if(element.shape==="hole_with_polygon_pad"&&"pad_outline"in element&&element.pad_outline&&element.pad_outline.length>0){let xs3=element.pad_outline.map(p4=>element.x+p4.x),ys3=element.pad_outline.map(p4=>element.y+p4.y),minX=Math.min(...xs3),maxX=Math.max(...xs3),minY=Math.min(...ys3),maxY=Math.max(...ys3),centerX=(minX+maxX)/2,centerY=(minY+maxY)/2;obstacles.push({type:"rect",layers:EVERY_LAYER2,center:{x:centerX,y:centerY},width:maxX-minX,height:maxY-minY,connectedTo:withNetId([element.pcb_plated_hole_id])})}}else if(element.type==="pcb_trace"){let traceObstacles=getObstaclesFromRoute2(element.route.map(rp2=>({x:rp2.x,y:rp2.y,layer:"layer"in rp2?rp2.layer:rp2.from_layer})),element.source_trace_id);obstacles.push(...traceObstacles)}else if(element.type==="pcb_via"){let netIsAssignable=!!(element.net_is_assignable??element.netIsAssignable);obstacles.push({type:"rect",layers:element.layers,center:{x:element.x,y:element.y},connectedTo:[],width:element.outer_diameter,height:element.outer_diameter,netIsAssignable:netIsAssignable||void 0})}return obstacles},computeSchematicNetLabelCenter=({anchor_position,anchor_side,text,font_size=.18})=>{let charWidth=.1*(font_size/.18),width=text.length*charWidth,height=font_size,center2={...anchor_position};switch(anchor_side){case"right":center2.x-=width/2;break;case"left":center2.x+=width/2;break;case"top":center2.y-=height/2;break;case"bottom":center2.y+=height/2;break}return center2},getOtherSchematicTraces=({db,source_trace_id,sameNetOnly,differentNetOnly})=>{!sameNetOnly&&!differentNetOnly&&(differentNetOnly=!0);let mySourceTrace=db.source_trace.get(source_trace_id),traces=[];for(let otherSchematicTrace of db.schematic_trace.list()){if(otherSchematicTrace.source_trace_id===source_trace_id)continue;let isSameNet=db.source_trace.get(otherSchematicTrace.source_trace_id)?.subcircuit_connectivity_map_key===mySourceTrace.subcircuit_connectivity_map_key;differentNetOnly&&isSameNet||sameNetOnly&&!isSameNet||traces.push(otherSchematicTrace)}return traces},createSchematicTraceCrossingSegments=({edges:inputEdges,otherEdges})=>{let edges=[...inputEdges];for(let i3=0;i3<edges.length;i3++){if(i3>2e3)throw new Error("Over 2000 iterations spent inside createSchematicTraceCrossingSegments, you have triggered an infinite loop, please report this!");let edge=edges[i3],edgeOrientation=Math.abs(edge.from.x-edge.to.x)<.01?"vertical":edge.from.y===edge.to.y?"horizontal":"not-orthogonal";if(edgeOrientation==="not-orthogonal")continue;let otherEdgesIntersections=[];for(let otherEdge of otherEdges){let otherOrientation=otherEdge.from.x===otherEdge.to.x?"vertical":otherEdge.from.y===otherEdge.to.y?"horizontal":"not-orthogonal";if(otherOrientation==="not-orthogonal"||edgeOrientation===otherOrientation)continue;if(doesLineIntersectLine2([edge.from,edge.to],[otherEdge.from,otherEdge.to],{lineThickness:.01})){let intersectX=edgeOrientation==="vertical"?edge.from.x:otherEdge.from.x,intersectY=edgeOrientation==="vertical"?otherEdge.from.y:edge.from.y,crossingPoint2={x:intersectX,y:intersectY};otherEdgesIntersections.push({otherEdge,crossingPoint:crossingPoint2,distanceFromEdgeFrom:distance4(edge.from,crossingPoint2)})}}if(otherEdgesIntersections.length===0)continue;let closestIntersection=otherEdgesIntersections[0];for(let intersection of otherEdgesIntersections)intersection.distanceFromEdgeFrom<closestIntersection.distanceFromEdgeFrom&&(closestIntersection=intersection);let crossingPoint=closestIntersection.crossingPoint,crossingSegmentLength=.075;if(crossingPoint.x===edge.from.x&&crossingPoint.y===edge.from.y)continue;let crossingUnitVec=getUnitVectorFromPointAToB2(edge.from,crossingPoint),beforeCrossing={x:crossingPoint.x-crossingUnitVec.x*crossingSegmentLength/2,y:crossingPoint.y-crossingUnitVec.y*crossingSegmentLength/2},afterCrossing={x:crossingPoint.x+crossingUnitVec.x*crossingSegmentLength/2,y:crossingPoint.y+crossingUnitVec.y*crossingSegmentLength/2},overshot=distance4(afterCrossing,edge.to)<crossingSegmentLength,newEdges=[{from:edge.from,to:beforeCrossing},{from:beforeCrossing,to:afterCrossing,is_crossing:!0},{from:afterCrossing,to:edge.to}];edges.splice(i3,1,...newEdges),i3+=newEdges.length-2,overshot&&i3++}return edges},TOLERANCE=.001,isPointWithinEdge=(point23,edge)=>{let minX=Math.min(edge.from.x,edge.to.x),maxX=Math.max(edge.from.x,edge.to.x),minY=Math.min(edge.from.y,edge.to.y),maxY=Math.max(edge.from.y,edge.to.y);return point23.x>=minX&&point23.x<=maxX&&point23.y>=minY&&point23.y<=maxY},getEdgeOrientation=edge=>{let isVertical3=Math.abs(edge.from.x-edge.to.x)<TOLERANCE,isHorizontal2=Math.abs(edge.from.y-edge.to.y)<TOLERANCE;return isVertical3?"vertical":isHorizontal2?"horizontal":"diagonal"},getIntersectionPoint=(edge1,edge2)=>{let orientation1=getEdgeOrientation(edge1),orientation22=getEdgeOrientation(edge2);if(orientation1===orientation22)return null;if(orientation1==="vertical"&&orientation22==="horizontal"||orientation1==="horizontal"&&orientation22==="vertical"){let verticalEdge=orientation1==="vertical"?edge1:edge2,horizontalEdge=orientation1==="horizontal"?edge1:edge2,x22=verticalEdge.from.x,y22=horizontalEdge.from.y,intersection2={x:x22,y:y22};return isPointWithinEdge(intersection2,edge1)&&isPointWithinEdge(intersection2,edge2)?intersection2:null}if(orientation1==="vertical"||orientation22==="vertical"){let verticalEdge=orientation1==="vertical"?edge1:edge2,diagonalEdge=orientation1==="vertical"?edge2:edge1,x22=verticalEdge.from.x,m3=(diagonalEdge.to.y-diagonalEdge.from.y)/(diagonalEdge.to.x-diagonalEdge.from.x),b3=diagonalEdge.from.y-m3*diagonalEdge.from.x,y22=m3*x22+b3,intersection2={x:x22,y:y22};return isPointWithinEdge(intersection2,edge1)&&isPointWithinEdge(intersection2,edge2)?intersection2:null}let m12=(edge1.to.y-edge1.from.y)/(edge1.to.x-edge1.from.x),b12=edge1.from.y-m12*edge1.from.x,m22=(edge2.to.y-edge2.from.y)/(edge2.to.x-edge2.from.x),b22=edge2.from.y-m22*edge2.from.x;if(Math.abs(m12-m22)<TOLERANCE)return null;let x3=(b22-b12)/(m12-m22),y3=m12*x3+b12,intersection={x:x3,y:y3};return isPointWithinEdge(intersection,edge1)&&isPointWithinEdge(intersection,edge2)?intersection:null},createSchematicTraceJunctions=({edges:myEdges,db,source_trace_id})=>{let otherEdges=getOtherSchematicTraces({db,source_trace_id,sameNetOnly:!0}).flatMap(t6=>t6.edges),junctions=new Map;for(let myEdge of myEdges)for(let otherEdge of otherEdges){let intersection=getIntersectionPoint(myEdge,otherEdge);if(intersection){let key=`${intersection.x.toFixed(6)},${intersection.y.toFixed(6)}`;junctions.has(key)||junctions.set(key,intersection)}}return Array.from(junctions.values())};function getObstaclesFromBounds(bounds,opts={}){let{minX,maxX,minY,maxY}=bounds,PADDING=opts.padding??1;if(!isFinite(minX)||!isFinite(maxX)||!isFinite(minY)||!isFinite(maxY))return[];let left=minX-PADDING,right=maxX+PADDING,top=maxY+PADDING,bottom=minY-PADDING,thickness=.01;return[{type:"rect",layers:["top"],center:{x:(left+right)/2,y:top},width:right-left,height:thickness,connectedTo:[]},{type:"rect",layers:["top"],center:{x:(left+right)/2,y:bottom},width:right-left,height:thickness,connectedTo:[]},{type:"rect",layers:["top"],center:{x:left,y:(top+bottom)/2},width:thickness,height:top-bottom,connectedTo:[]},{type:"rect",layers:["top"],center:{x:right,y:(top+bottom)/2},width:thickness,height:top-bottom,connectedTo:[]}]}var getSchematicObstaclesForTrace=trace=>{let db=trace.root.db,connectedPorts=trace._findConnectedPorts().ports??[],connectedPortIds=new Set(connectedPorts.map(p4=>p4.schematic_port_id)),obstacles=[];for(let elm of db.toArray()){if(elm.type==="schematic_component"){let isSymbol3=!!elm.symbol_name,dominateAxis=elm.size.width>elm.size.height?"horz":"vert";obstacles.push({type:"rect",layers:["top"],center:elm.center,width:elm.size.width+(isSymbol3&&dominateAxis==="horz"?-.5:0),height:elm.size.height+(isSymbol3&&dominateAxis==="vert"?-.5:0),connectedTo:[]})}if(elm.type==="schematic_port"){if(connectedPortIds.has(elm.schematic_port_id))continue;let dirVec=elm.facing_direction?getUnitVectorFromDirection2(elm.facing_direction):{x:0,y:0};obstacles.push({type:"rect",layers:["top"],center:{x:elm.center.x-dirVec.x*.1,y:elm.center.y-dirVec.y*.1},width:.1+Math.abs(dirVec.x)*.3,height:.1+Math.abs(dirVec.y)*.3,connectedTo:[]})}elm.type==="schematic_text"&&obstacles.push({type:"rect",layers:["top"],center:elm.position,width:(elm.text?.length??0)*.1,height:.2,connectedTo:[]}),elm.type==="schematic_box"&&obstacles.push({type:"rect",layers:["top"],center:{x:elm.x,y:elm.y},width:elm.width,height:elm.height,connectedTo:[]})}let bounds=getBoundsForSchematic(db.toArray());return obstacles.push(...getObstaclesFromBounds(bounds,{padding:1})),obstacles},pushEdgesOfSchematicTraceToPreventOverlap=({edges,db,source_trace_id})=>{let mySourceTrace=db.source_trace.get(source_trace_id),otherEdges=getOtherSchematicTraces({db,source_trace_id,differentNetOnly:!0}).flatMap(t6=>t6.edges),edgeOrientation=edge=>{let{from,to:to2}=edge;return from.x===to2.x?"vertical":"horizontal"};for(let mySegment of edges){let mySegmentOrientation=edgeOrientation(mySegment),findOverlappingParallelSegment=()=>otherEdges.find(otherEdge=>edgeOrientation(otherEdge)===mySegmentOrientation&&doesLineIntersectLine2([mySegment.from,mySegment.to],[otherEdge.from,otherEdge.to],{lineThickness:.05})),overlappingParallelSegmentFromOtherTrace=findOverlappingParallelSegment();for(;overlappingParallelSegmentFromOtherTrace;)mySegmentOrientation==="horizontal"?(mySegment.from.y+=.1,mySegment.to.y+=.1):(mySegment.from.x+=.1,mySegment.to.x+=.1),overlappingParallelSegmentFromOtherTrace=findOverlappingParallelSegment()}},convertFacingDirectionToElbowDirection=facingDirection=>{switch(facingDirection){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:}},autorouterVersion=package_default.version??"unknown",AutorouterError=class extends Error{constructor(message){super(`${message} (capacity-autorouter@${autorouterVersion})`),this.name="AutorouterError"}},TraceConnectionError=class extends Error{constructor(errorData){super(errorData.message),this.errorData=errorData,this.name="TraceConnectionError"}},Trace_doInitialSchematicTraceRender=trace=>{if(trace.root?._featureMspSchematicTraceRouting||trace._couldNotFindPort||trace.root?.schematicDisabled)return;let{db}=trace.root,{_parsedProps:props,parent}=trace;if(!parent)throw new Error("Trace has no parent");let allPortsFound,connectedPorts;try{let result=trace._findConnectedPorts();allPortsFound=result.allPortsFound,connectedPorts=result.portsWithSelectors??[]}catch(error){if(error instanceof TraceConnectionError){db.source_trace_not_connected_error.insert({...error.errorData,error_type:"source_trace_not_connected_error"});return}throw error}let{netsWithSelectors}=trace._findConnectedNets();if(!allPortsFound)return;let portPairKey=connectedPorts.map(p4=>p4.port.schematic_port_id).sort().join(","),board=trace.root?._getBoard();if(board?._connectedSchematicPortPairs&&board._connectedSchematicPortPairs.has(portPairKey))return;let connection={name:trace.source_trace_id,pointsToConnect:[]},obstacles=getSchematicObstaclesForTrace(trace),portsWithPosition=connectedPorts.filter(({port})=>port.schematic_port_id!==null).map(({port})=>({port,position:port._getGlobalSchematicPositionAfterLayout(),schematic_port_id:port.schematic_port_id??void 0,facingDirection:port.facingDirection}));if(portsWithPosition.length===1&&netsWithSelectors.length===1){let net=netsWithSelectors[0].net,{port,position:anchorPos}=portsWithPosition[0],connectedNetLabel=trace.getSubcircuit().selectAll("netlabel").find(nl2=>{let conn=nl2._parsedProps.connection??nl2._parsedProps.connectsTo;return conn?Array.isArray(conn)?conn.some(selector=>trace.getSubcircuit().selectOne(selector,{port:!0})===port):trace.getSubcircuit().selectOne(conn,{port:!0})===port:!1});if(!connectedNetLabel){let dbNetLabel=db.schematic_net_label.getWhere({source_trace_id:trace.source_trace_id});dbNetLabel&&(connectedNetLabel=dbNetLabel)}if(connectedNetLabel){let labelPos="_getGlobalSchematicPositionBeforeLayout"in connectedNetLabel?connectedNetLabel._getGlobalSchematicPositionBeforeLayout():connectedNetLabel.anchor_position,edges2=[];anchorPos.x===labelPos.x||anchorPos.y===labelPos.y?edges2.push({from:anchorPos,to:labelPos}):(edges2.push({from:anchorPos,to:{x:labelPos.x,y:anchorPos.y}}),edges2.push({from:{x:labelPos.x,y:anchorPos.y},to:labelPos}));let dbTrace2=db.schematic_trace.insert({source_trace_id:trace.source_trace_id,edges:edges2,junctions:[],subcircuit_connectivity_map_key:trace.subcircuit_connectivity_map_key??void 0});trace.schematic_trace_id=dbTrace2.schematic_trace_id;return}if(trace.props.schDisplayLabel){let side2=getEnteringEdgeFromDirection(port.facingDirection)??"bottom";db.schematic_net_label.insert({text:trace.props.schDisplayLabel,source_net_id:net.source_net_id,anchor_position:anchorPos,center:computeSchematicNetLabelCenter({anchor_position:anchorPos,anchor_side:side2,text:trace.props.schDisplayLabel}),anchor_side:side2});return}let side=getEnteringEdgeFromDirection(port.facingDirection)??"bottom",netLabel=db.schematic_net_label.insert({text:net._parsedProps.name,source_net_id:net.source_net_id,anchor_position:anchorPos,center:computeSchematicNetLabelCenter({anchor_position:anchorPos,anchor_side:side,text:net._parsedProps.name}),anchor_side:side});return}if(trace.props.schDisplayLabel&&("from"in trace.props&&"to"in trace.props||"path"in trace.props)){trace._doInitialSchematicTraceRenderWithDisplayLabel();return}if(portsWithPosition.length<2)return;let edges=(()=>{let elbowEdges=[];for(let i3=0;i3<portsWithPosition.length-1;i3++){let start=portsWithPosition[i3],end=portsWithPosition[i3+1],path=calculateElbow({x:start.position.x,y:start.position.y,facingDirection:convertFacingDirectionToElbowDirection(start.facingDirection)},{x:end.position.x,y:end.position.y,facingDirection:convertFacingDirectionToElbowDirection(end.facingDirection)});for(let j3=0;j3<path.length-1;j3++)elbowEdges.push({from:path[j3],to:path[j3+1]})}let doesSegmentIntersectRect2=(edge,rect)=>{let halfW=rect.width/2,halfH=rect.height/2,left=rect.center.x-halfW,right=rect.center.x+halfW,top=rect.center.y-halfH,bottom=rect.center.y+halfH,inRect=p4=>p4.x>=left&&p4.x<=right&&p4.y>=top&&p4.y<=bottom;return inRect(edge.from)||inRect(edge.to)?!0:[[{x:left,y:top},{x:right,y:top}],[{x:right,y:top},{x:right,y:bottom}],[{x:right,y:bottom},{x:left,y:bottom}],[{x:left,y:bottom},{x:left,y:top}]].some(r4=>doesLineIntersectLine2([edge.from,edge.to],r4,{lineThickness:0}))};for(let edge of elbowEdges)for(let obstacle of obstacles)if(doesSegmentIntersectRect2(edge,obstacle))return null;return elbowEdges})();edges&&edges.length===0&&(edges=null),connection.pointsToConnect=portsWithPosition.map(({position:position2})=>({...position2,layer:"top"}));let bounds=computeObstacleBounds(obstacles),BOUNDS_MARGIN=2,simpleRouteJsonInput={minTraceWidth:.1,obstacles,connections:[connection],bounds:{minX:bounds.minX-BOUNDS_MARGIN,maxX:bounds.maxX+BOUNDS_MARGIN,minY:bounds.minY-BOUNDS_MARGIN,maxY:bounds.maxY+BOUNDS_MARGIN},layerCount:1},Autorouter=MultilayerIjump,skipOtherTraceInteraction=!1;if(trace.getSubcircuit().props._schDirectLineRoutingEnabled&&(Autorouter=DirectLineRouter,skipOtherTraceInteraction=!0),!edges){let results=new Autorouter({input:simpleRouteJsonInput,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(results.length===0){if(trace._isSymbolToChipConnection()||trace._isSymbolToSymbolConnection()||trace._isChipToChipConnection()){trace._doInitialSchematicTraceRenderWithDisplayLabel();return}results=new DirectLineRouter({input:simpleRouteJsonInput}).solveAndMapToTraces(),skipOtherTraceInteraction=!0}let[{route}]=results;edges=[];for(let i3=0;i3<route.length-1;i3++)edges.push({from:route[i3],to:route[i3+1]})}let source_trace_id=trace.source_trace_id,junctions=[];if(!skipOtherTraceInteraction){pushEdgesOfSchematicTraceToPreventOverlap({edges,db,source_trace_id});let otherEdges=getOtherSchematicTraces({db,source_trace_id,differentNetOnly:!0}).flatMap(t6=>t6.edges);edges=createSchematicTraceCrossingSegments({edges,otherEdges}),junctions=createSchematicTraceJunctions({edges,db,source_trace_id:trace.source_trace_id})}if(!edges||edges.length===0)return;let lastEdge=edges[edges.length-1],lastEdgePort=portsWithPosition[portsWithPosition.length-1],lastDominantDirection=getDominantDirection(lastEdge);edges.push(...getStubEdges({lastEdge,lastEdgePort,lastDominantDirection}));let firstEdge=edges[0],firstEdgePort=portsWithPosition[0],firstDominantDirection=getDominantDirection(firstEdge);if(edges.unshift(...getStubEdges({firstEdge,firstEdgePort,firstDominantDirection})),!trace.source_trace_id)throw new Error("Missing source_trace_id for schematic trace insertion.");if(trace.getSubcircuit()._parsedProps.schTraceAutoLabelEnabled&&countComplexElements(junctions,edges)>=5&&(trace._isSymbolToChipConnection()||trace._isSymbolToSymbolConnection()||trace._isChipToChipConnection())){trace._doInitialSchematicTraceRenderWithDisplayLabel();return}let dbTrace=db.schematic_trace.insert({source_trace_id:trace.source_trace_id,edges,junctions,subcircuit_connectivity_map_key:trace.subcircuit_connectivity_map_key??void 0});trace.schematic_trace_id=dbTrace.schematic_trace_id;for(let{port}of connectedPorts)port.schematic_port_id&&db.schematic_port.update(port.schematic_port_id,{is_connected:!0});board?._connectedSchematicPortPairs&&board._connectedSchematicPortPairs.add(portPairKey)};function getTraceLength(route){let totalLength=0;for(let i3=0;i3<route.length;i3++){let point23=route[i3];if(point23.route_type==="wire"){let nextPoint=route[i3+1];if(nextPoint){let dx2=nextPoint.x-point23.x,dy2=nextPoint.y-point23.y;totalLength+=Math.sqrt(dx2*dx2+dy2*dy2)}}else point23.route_type==="via"&&(totalLength+=1.6)}return totalLength}var DEFAULT_VIA_HOLE_DIAMETER=.3,DEFAULT_VIA_PAD_DIAMETER=.6,parseDistance=(value,fallback)=>{if(value===void 0)return fallback;if(typeof value=="number")return value;let parsed=parseFloat(value);return Number.isFinite(parsed)?parsed:fallback},getViaDiameterDefaults=pcbStyle2=>({holeDiameter:parseDistance(pcbStyle2?.viaHoleDiameter,DEFAULT_VIA_HOLE_DIAMETER),padDiameter:parseDistance(pcbStyle2?.viaPadDiameter,DEFAULT_VIA_PAD_DIAMETER)}),getViaDiameterDefaultsWithOverrides=(overrides,pcbStyle2)=>{let defaults=getViaDiameterDefaults(pcbStyle2);return{holeDiameter:overrides.holeDiameter??defaults.holeDiameter,padDiameter:overrides.padDiameter??defaults.padDiameter}},portToObjective=port=>({...port._getGlobalPcbPositionAfterLayout(),layers:port.getAvailablePcbLayers()}),SHOULD_USE_SINGLE_LAYER_ROUTING=!1;function Trace_doInitialPcbTraceRender(trace){if(trace.root?.pcbDisabled)return;let{db}=trace.root,{_parsedProps:props,parent}=trace,subcircuit=trace.getSubcircuit();if(!parent)throw new Error("Trace has no parent");if(subcircuit._parsedProps.routingDisabled)return;let cachedRoute=subcircuit._parsedProps.pcbRouteCache?.pcbTraces;if(cachedRoute){let pcb_trace22=db.pcb_trace.insert({route:cachedRoute.flatMap(trace2=>trace2.route),source_trace_id:trace.source_trace_id,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:trace.getGroup()?.pcb_group_id??void 0});trace.pcb_trace_id=pcb_trace22.pcb_trace_id;return}if(props.pcbPath&&props.pcbPath.length>0||props.pcbStraightLine||!subcircuit._shouldUseTraceByTraceRouting())return;let{allPortsFound,ports}=trace._findConnectedPorts(),portsConnectedOnPcbViaNet=[];if(!allPortsFound)return;let portsWithoutMatchedPcbPrimitive=[];for(let port of ports)port._hasMatchedPcbPrimitive()||portsWithoutMatchedPcbPrimitive.push(port);if(portsWithoutMatchedPcbPrimitive.length>0){db.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:trace.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, ${trace} wasn't routed. Missing ports: ${portsWithoutMatchedPcbPrimitive.map(p4=>p4.getString()).join(", ")}`,pcb_trace_id:trace.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:portsWithoutMatchedPcbPrimitive.map(p4=>p4.pcb_port_id).filter(Boolean)});return}let nets=trace._findConnectedNets().netsWithSelectors;if(ports.length===0&&nets.length===2){trace.renderError("Trace connects two nets, we haven't implemented a way to route this yet");return}else if(ports.length===1&&nets.length===1){let port=ports[0],otherPortsInNet=nets[0].net.getAllConnectedPorts().filter(p4=>p4!==port);if(otherPortsInNet.length===0){console.log("Nothing to connect this port to, the net is empty. TODO should emit a warning!");return}let closestPortInNet=getClosest(port,otherPortsInNet);portsConnectedOnPcbViaNet.push(closestPortInNet),ports.push(closestPortInNet)}else if(ports.length>1&&nets.length>=1){trace.renderError("Trace has more than one port and one or more nets, we don't currently support this type of complex trace routing");return}let hints=ports.flatMap(port=>port.matchedComponents.filter(c3=>c3.componentName==="TraceHint")),pcbRouteHints=(trace._parsedProps.pcbRouteHints??[]).concat(hints.flatMap(h3=>h3.getPcbRouteHints()));if(ports.length>2){trace.renderError(`Trace has more than two ports (${ports.map(p4=>p4.getString()).join(", ")}), routing between more than two ports for a single trace is not implemented`);return}if(trace.getSubcircuit().selectAll("trace").filter(trace2=>trace2.renderPhaseStates.PcbTraceRender.initialized).some(trace2=>trace2._portsRoutedOnPcb.length===ports.length&&trace2._portsRoutedOnPcb.every(portRoutedByOtherTrace=>ports.includes(portRoutedByOtherTrace))))return;let orderedRouteObjectives=[];pcbRouteHints.length===0?orderedRouteObjectives=[portToObjective(ports[0]),portToObjective(ports[1])]:orderedRouteObjectives=[portToObjective(ports[0]),...pcbRouteHints,portToObjective(ports[1])];let candidateLayerCombinations=findPossibleTraceLayerCombinations(orderedRouteObjectives);if(SHOULD_USE_SINGLE_LAYER_ROUTING&&candidateLayerCombinations.length===0){trace.renderError(`Could not find a common layer (using hints) for trace ${trace.getString()}`);return}let connMap=getFullConnectivityMapFromCircuitJson(trace.root.db.toArray()),[obstacles,errGettingObstacles]=tryNow(()=>getObstaclesFromCircuitJson2(trace.root.db.toArray()));if(errGettingObstacles){trace.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:trace.pcb_trace_id,message:`Error getting obstacles for autorouting: ${errGettingObstacles.message}`,source_trace_id:trace.source_trace_id,center:{x:0,y:0},pcb_port_ids:ports.map(p4=>p4.pcb_port_id),pcb_trace_id:trace.pcb_trace_id,pcb_component_ids:[]});return}for(let obstacle of obstacles)if(obstacle.connectedTo.length>0){let netId=connMap.getNetConnectedToId(obstacle.connectedTo[0]);netId&&obstacle.connectedTo.push(netId)}let orderedRoutePoints=[];if(candidateLayerCombinations.length===0)orderedRoutePoints=orderedRouteObjectives;else{let candidateLayerSelections=candidateLayerCombinations[0].layer_path;orderedRoutePoints=orderedRouteObjectives.map((t6,idx)=>t6.via?{...t6,via_to_layer:candidateLayerSelections[idx]}:{...t6,layers:[candidateLayerSelections[idx]]})}orderedRoutePoints[0].pcb_port_id=ports[0].pcb_port_id,orderedRoutePoints[orderedRoutePoints.length-1].pcb_port_id=ports[1].pcb_port_id;let routes=[];for(let[a3,b3]of pairs2(orderedRoutePoints)){let dominantLayer="via_to_layer"in a3?a3.via_to_layer:null,BOUNDS_MARGIN=2,aLayer="layers"in a3&&a3.layers.length===1?a3.layers[0]:dominantLayer??"top",bLayer="layers"in b3&&b3.layers.length===1?b3.layers[0]:dominantLayer??"top",pcbPortA="pcb_port_id"in a3?a3.pcb_port_id:null,pcbPortB="pcb_port_id"in b3?b3.pcb_port_id:null,minTraceWidth=trace._getExplicitTraceThickness()??trace.getSubcircuit()._parsedProps.minTraceWidth??.16,ijump=new MultilayerIjump({OBSTACLE_MARGIN:minTraceWidth*2,isRemovePathLoopsEnabled:!0,optimizeWithGoalBoxes:!!(pcbPortA&&pcbPortB),connMap,input:{obstacles,minTraceWidth,connections:[{name:trace.source_trace_id,pointsToConnect:[{...a3,layer:aLayer,pcb_port_id:pcbPortA},{...b3,layer:bLayer,pcb_port_id:pcbPortB}]}],layerCount:trace.getSubcircuit()._getSubcircuitLayerCount(),bounds:{minX:Math.min(a3.x,b3.x)-BOUNDS_MARGIN,maxX:Math.max(a3.x,b3.x)+BOUNDS_MARGIN,minY:Math.min(a3.y,b3.y)-BOUNDS_MARGIN,maxY:Math.max(a3.y,b3.y)+BOUNDS_MARGIN}}}),traces=null;try{traces=ijump.solveAndMapToTraces()}catch(e4){trace.renderError({type:"pcb_trace_error",pcb_trace_error_id:trace.source_trace_id,error_type:"pcb_trace_error",message:`error solving route: ${e4.message}`,source_trace_id:trace.pcb_trace_id,center:{x:(a3.x+b3.x)/2,y:(a3.y+b3.y)/2},pcb_port_ids:ports.map(p4=>p4.pcb_port_id),pcb_trace_id:trace.pcb_trace_id,pcb_component_ids:ports.map(p4=>p4.pcb_component_id)})}if(!traces)return;if(traces.length===0){trace.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:trace.pcb_trace_id,message:`Could not find a route for ${trace}`,source_trace_id:trace.source_trace_id,center:{x:(a3.x+b3.x)/2,y:(a3.y+b3.y)/2},pcb_port_ids:ports.map(p4=>p4.pcb_port_id),pcb_trace_id:trace.pcb_trace_id,pcb_component_ids:ports.map(p4=>p4.pcb_component_id)});return}let[autoroutedTrace]=traces;dominantLayer&&(autoroutedTrace.route=autoroutedTrace.route.map(p4=>(p4.route_type==="wire"&&!p4.layer&&(p4.layer=dominantLayer),p4))),pcbPortA&&autoroutedTrace.route[0].route_type==="wire"&&(autoroutedTrace.route[0].start_pcb_port_id=pcbPortA);let lastRoutePoint=autoroutedTrace.route[autoroutedTrace.route.length-1];pcbPortB&&lastRoutePoint.route_type==="wire"&&(lastRoutePoint.end_pcb_port_id=pcbPortB),routes.push(autoroutedTrace.route)}let mergedRoute=mergeRoutes(routes),traceLength=getTraceLength(mergedRoute),pcbStyle2=trace.getInheritedMergedProperty("pcbStyle"),{holeDiameter,padDiameter}=getViaDiameterDefaults(pcbStyle2),pcb_trace2=db.pcb_trace.insert({route:mergedRoute,source_trace_id:trace.source_trace_id,subcircuit_id:trace.getSubcircuit()?.subcircuit_id,trace_length:traceLength});trace._portsRoutedOnPcb=ports,trace.pcb_trace_id=pcb_trace2.pcb_trace_id;for(let point23 of mergedRoute)point23.route_type==="via"&&db.pcb_via.insert({pcb_trace_id:pcb_trace2.pcb_trace_id,x:point23.x,y:point23.y,hole_diameter:holeDiameter,outer_diameter:padDiameter,layers:[point23.from_layer,point23.to_layer],from_layer:point23.from_layer,to_layer:point23.to_layer});trace._insertErrorIfTraceIsOutsideBoard(mergedRoute,ports)}function computeLineRectIntersection(params){let{lineStart,lineEnd,rectCenter,rectWidth,rectHeight}=params,left=rectCenter.x-rectWidth/2,right=rectCenter.x+rectWidth/2,top=rectCenter.y+rectHeight/2,bottom=rectCenter.y-rectHeight/2,dx2=lineEnd.x-lineStart.x,dy2=lineEnd.y-lineStart.y,intersections=[];if(dx2!==0){let t6=(left-lineStart.x)/dx2;if(t6>=0&&t6<=1){let y3=lineStart.y+t6*dy2;y3>=bottom&&y3<=top&&intersections.push({x:left,y:y3,t:t6})}}if(dx2!==0){let t6=(right-lineStart.x)/dx2;if(t6>=0&&t6<=1){let y3=lineStart.y+t6*dy2;y3>=bottom&&y3<=top&&intersections.push({x:right,y:y3,t:t6})}}if(dy2!==0){let t6=(bottom-lineStart.y)/dy2;if(t6>=0&&t6<=1){let x3=lineStart.x+t6*dx2;x3>=left&&x3<=right&&intersections.push({x:x3,y:bottom,t:t6})}}if(dy2!==0){let t6=(top-lineStart.y)/dy2;if(t6>=0&&t6<=1){let x3=lineStart.x+t6*dx2;x3>=left&&x3<=right&&intersections.push({x:x3,y:top,t:t6})}}return intersections.length===0?null:(intersections.sort((a3,b3)=>a3.t-b3.t),{x:intersections[0].x,y:intersections[0].y})}function computeLineCircleIntersection(params){let{lineStart,lineEnd,circleCenter,circleRadius}=params,x12=lineStart.x-circleCenter.x,y12=lineStart.y-circleCenter.y,x22=lineEnd.x-circleCenter.x,y22=lineEnd.y-circleCenter.y,dx2=x22-x12,dy2=y22-y12,a3=dx2*dx2+dy2*dy2,b3=2*(x12*dx2+y12*dy2),c3=x12*x12+y12*y12-circleRadius*circleRadius,discriminant=b3*b3-4*a3*c3;if(discriminant<0)return null;let sqrtDisc=Math.sqrt(discriminant),t12=(-b3-sqrtDisc)/(2*a3),t22=(-b3+sqrtDisc)/(2*a3),t6=null;return t12>=0&&t12<=1?t6=t12:t22>=0&&t22<=1&&(t6=t22),t6===null?null:{x:lineStart.x+t6*dx2,y:lineStart.y+t6*dy2}}function clipTraceEndAtPad(params){let{traceStart,traceEnd,traceWidth,port}=params,pcbPrimitive=port.matchedComponents.find(c3=>c3.isPcbPrimitive);if(!pcbPrimitive)return traceEnd;let padBounds=pcbPrimitive._getPcbCircuitJsonBounds(),padWidth=padBounds.width,padHeight=padBounds.height,padCenter=padBounds.center,smallestPadDimension=Math.min(padWidth,padHeight);if(traceWidth<=smallestPadDimension/2)return traceEnd;let clippedPoint=null;if(pcbPrimitive.componentName==="SmtPad"){let smtPad=pcbPrimitive,padShape=smtPad._parsedProps.shape;if(padShape==="circle"){let radius=smtPad._parsedProps.radius;clippedPoint=computeLineCircleIntersection({lineStart:traceStart,lineEnd:traceEnd,circleCenter:padCenter,circleRadius:radius})}else(padShape==="rect"||padShape==="rotated_rect"||padShape==="pill"||padShape==="polygon")&&(clippedPoint=computeLineRectIntersection({lineStart:traceStart,lineEnd:traceEnd,rectCenter:padCenter,rectWidth:padWidth,rectHeight:padHeight}))}else if(pcbPrimitive.componentName==="PlatedHole"){let platedHole=pcbPrimitive;if(platedHole._parsedProps.shape==="circle"){let outerDiameter=platedHole._parsedProps.outerDiameter;clippedPoint=computeLineCircleIntersection({lineStart:traceStart,lineEnd:traceEnd,circleCenter:padCenter,circleRadius:outerDiameter/2})}else clippedPoint=computeLineRectIntersection({lineStart:traceStart,lineEnd:traceEnd,rectCenter:padCenter,rectWidth:padWidth,rectHeight:padHeight})}return clippedPoint??traceEnd}function Trace_doInitialPcbManualTraceRender(trace){if(trace.root?.pcbDisabled)return;let{db}=trace.root,{_parsedProps:props}=trace,subcircuit=trace.getSubcircuit(),hasPcbPath=props.pcbPath!==void 0,wantsStraightLine=!!props.pcbStraightLine;if(!hasPcbPath&&!wantsStraightLine)return;let{allPortsFound,ports,portsWithSelectors}=trace._findConnectedPorts();if(!allPortsFound)return;let portsWithoutMatchedPcbPrimitive=[];for(let port of ports)port._hasMatchedPcbPrimitive()||portsWithoutMatchedPcbPrimitive.push(port);if(portsWithoutMatchedPcbPrimitive.length>0){db.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:trace.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, ${trace} wasn't routed. Missing ports: ${portsWithoutMatchedPcbPrimitive.map(p4=>p4.getString()).join(", ")}`,pcb_trace_id:trace.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:portsWithoutMatchedPcbPrimitive.map(p4=>p4.pcb_port_id).filter(Boolean)});return}let width=trace._getExplicitTraceThickness()??trace.getSubcircuit()._parsedProps.minTraceWidth??.16;if(wantsStraightLine&&!hasPcbPath){if(!ports||ports.length<2){trace.renderError("pcbStraightLine requires exactly two connected ports");return}let[startPort,endPort]=ports,startLayers=startPort.getAvailablePcbLayers(),endLayers=endPort.getAvailablePcbLayers(),layer2=startLayers.find(layer3=>endLayers.includes(layer3))??startLayers[0]??endLayers[0]??"top",startPos=startPort._getGlobalPcbPositionAfterLayout(),endPos=endPort._getGlobalPcbPositionAfterLayout(),clippedStartPos=clipTraceEndAtPad({traceStart:endPos,traceEnd:startPos,traceWidth:width,port:startPort}),clippedEndPos=clipTraceEndAtPad({traceStart:startPos,traceEnd:endPos,traceWidth:width,port:endPort}),route2=[{route_type:"wire",x:clippedStartPos.x,y:clippedStartPos.y,width,layer:layer2,start_pcb_port_id:startPort.pcb_port_id},{route_type:"wire",x:clippedEndPos.x,y:clippedEndPos.y,width,layer:layer2,end_pcb_port_id:endPort.pcb_port_id}],traceLength2=getTraceLength(route2),pcb_trace22=db.pcb_trace.insert({route:route2,source_trace_id:trace.source_trace_id,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:trace.getGroup()?.pcb_group_id??void 0,trace_length:traceLength2});trace._portsRoutedOnPcb=ports,trace.pcb_trace_id=pcb_trace22.pcb_trace_id,trace._insertErrorIfTraceIsOutsideBoard(route2,ports);return}if(!props.pcbPath)return;let anchorPort;props.pcbPathRelativeTo&&(anchorPort=portsWithSelectors.find(p4=>p4.selector===props.pcbPathRelativeTo)?.port,anchorPort||(anchorPort=trace.getSubcircuit().selectOne(props.pcbPathRelativeTo))),anchorPort||(anchorPort=ports[0]);let otherPort=ports.find(p4=>p4!==anchorPort)??ports[1],layer=anchorPort.getAvailablePcbLayers()[0]||"top",anchorPos=anchorPort._getGlobalPcbPositionAfterLayout(),otherPos=otherPort._getGlobalPcbPositionAfterLayout(),route=[];route.push({route_type:"wire",x:anchorPos.x,y:anchorPos.y,width,layer,start_pcb_port_id:anchorPort.pcb_port_id});let transform5=anchorPort?._computePcbGlobalTransformBeforeLayout?.()||identity();for(let pt3 of props.pcbPath){let coordinates,isGlobalPosition=!1;if(typeof pt3=="string"){let resolvedPort=trace.getSubcircuit().selectOne(pt3,{type:"port"});if(!resolvedPort){db.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:trace.source_trace_id,message:`Could not resolve pcbPath selector "${pt3}" for ${trace}`,pcb_trace_id:trace.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:[]});continue}let portPos=resolvedPort._getGlobalPcbPositionAfterLayout();coordinates={x:portPos.x,y:portPos.y},isGlobalPosition=!0}else coordinates={x:pt3.x,y:pt3.y},isGlobalPosition=!1;let finalCoordinates=isGlobalPosition?coordinates:applyToPoint(transform5,coordinates);route.push({route_type:"wire",x:finalCoordinates.x,y:finalCoordinates.y,width,layer})}route.push({route_type:"wire",x:otherPos.x,y:otherPos.y,width,layer,end_pcb_port_id:otherPort.pcb_port_id});let traceLength=getTraceLength(route),pcb_trace2=db.pcb_trace.insert({route,source_trace_id:trace.source_trace_id,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:trace.getGroup()?.pcb_group_id??void 0,trace_length:traceLength});trace._portsRoutedOnPcb=ports,trace.pcb_trace_id=pcb_trace2.pcb_trace_id,trace._insertErrorIfTraceIsOutsideBoard(route,ports)}function Trace__doInitialSchematicTraceRenderWithDisplayLabel(trace){if(trace.root?.schematicDisabled)return;let{db}=trace.root,{_parsedProps:props,parent}=trace;if(!parent)throw new Error("Trace has no parent");let{allPortsFound,portsWithSelectors:connectedPorts}=trace._findConnectedPorts();if(!allPortsFound)return;let portsWithPosition=connectedPorts.map(({port})=>({port,position:port._getGlobalSchematicPositionAfterLayout(),schematic_port_id:port.schematic_port_id,facingDirection:port.facingDirection}));if(portsWithPosition.length<2)throw new Error("Expected at least two ports in portsWithPosition.");let fromPortName,toPortName,fromAnchorPos=portsWithPosition[0].position,fromPort=portsWithPosition[0].port;if("path"in trace.props){if(trace.props.path.length!==2)throw new Error("Invalid 'path': Must contain exactly two elements.");[fromPortName,toPortName]=trace.props.path}else{if(!("from"in trace.props&&"to"in trace.props))throw new Error("Missing 'from' or 'to' properties in props.");fromPortName=trace.props.from,toPortName=trace.props.to}if(!fromPort.source_port_id)throw new Error(`Missing source_port_id for the 'from' port (${fromPortName}).`);let toAnchorPos=portsWithPosition[1].position,toPort=portsWithPosition[1].port;if(!toPort.source_port_id)throw new Error(`Missing source_port_id for the 'to' port (${toPortName}).`);let existingFromNetLabel=db.schematic_net_label.list().find(label=>label.source_net_id===fromPort.source_port_id),existingToNetLabel=db.schematic_net_label.list().find(label=>label.source_net_id===toPort.source_port_id),[firstPort,secondPort]=connectedPorts.map(({port})=>port),pinFullName=firstPort.parent?.config.shouldRenderAsSchematicBox?`${firstPort?.parent?.props.name}_${firstPort?.props.name}`:`${secondPort?.parent?.props.name}_${secondPort?.props.name}`,netLabelText=trace.props.schDisplayLabel??pinFullName;if(existingFromNetLabel&&existingFromNetLabel.text!==netLabelText&&(existingFromNetLabel.text=`${netLabelText} / ${existingFromNetLabel.text}`),existingToNetLabel&&existingToNetLabel?.text!==netLabelText&&(existingToNetLabel.text=`${netLabelText} / ${existingToNetLabel.text}`),!existingToNetLabel){let toSide=getEnteringEdgeFromDirection(toPort.facingDirection)??"bottom";db.schematic_net_label.insert({text:trace.props.schDisplayLabel??pinFullName,source_net_id:toPort.source_port_id,anchor_position:toAnchorPos,center:computeSchematicNetLabelCenter({anchor_position:toAnchorPos,anchor_side:toSide,text:trace.props.schDisplayLabel??pinFullName}),anchor_side:toSide})}if(!existingFromNetLabel){let fromSide=getEnteringEdgeFromDirection(fromPort.facingDirection)??"bottom";db.schematic_net_label.insert({text:trace.props.schDisplayLabel??pinFullName,source_net_id:fromPort.source_port_id,anchor_position:fromAnchorPos,center:computeSchematicNetLabelCenter({anchor_position:fromAnchorPos,anchor_side:fromSide,text:trace.props.schDisplayLabel??pinFullName}),anchor_side:fromSide})}}function Trace__findConnectedPorts(trace){let{_parsedProps:props,parent}=trace;if(!parent)throw new Error("Trace has no parent");let portsWithSelectors=trace.getTracePortPathSelectors().map(selector=>({selector,port:trace.getSubcircuit().selectOne(selector,{type:"port"})??null}));for(let{selector,port}of portsWithSelectors)if(!port){let parentSelector,portToken,dotIndex=selector.lastIndexOf(".");if(dotIndex!==-1&&dotIndex>selector.lastIndexOf(" "))parentSelector=selector.slice(0,dotIndex),portToken=selector.slice(dotIndex+1);else{let match2=selector.match(/^(.*[ >])?([^ >]+)$/);parentSelector=match2?.[1]?.trim()??"",portToken=match2?.[2]??selector}let targetComponent=parentSelector?trace.getSubcircuit().selectOne(parentSelector):null;if(!targetComponent&&parentSelector&&!/[.#\[]/.test(parentSelector)&&(targetComponent=trace.getSubcircuit().selectOne(`.${parentSelector}`)),!targetComponent){let errorMessage2=parentSelector?`Could not find port for selector "${selector}". Component "${parentSelector}" not found`:`Could not find port for selector "${selector}"`,subcircuit2=trace.getSubcircuit(),sourceGroup2=subcircuit2.getGroup();throw new TraceConnectionError({error_type:"source_trace_not_connected_error",message:errorMessage2,subcircuit_id:subcircuit2.subcircuit_id??void 0,source_group_id:sourceGroup2?.source_group_id??void 0,source_trace_id:trace.source_trace_id??void 0,selectors_not_found:[selector]})}let ports=targetComponent.children.filter(c3=>c3.componentName==="Port"),portLabel=portToken.includes(".")?portToken.split(".").pop()??"":portToken,portNames=ports.flatMap(c3=>c3.getNameAndAliases()),hasCustomLabels=portNames.some(n3=>!/^(pin\d+|\d+)$/.test(n3)),labelList=Array.from(new Set(portNames)).join(", "),detail;ports.length===0?detail="It has no ports":hasCustomLabels?detail=`It has [${labelList}]`:detail=`It has ${ports.length} pins and no pinLabels (consider adding pinLabels)`;let errorMessage=`Could not find port for selector "${selector}". Component "${targetComponent.props.name??parentSelector}" found, but does not have pin "${portLabel}". ${detail}`,subcircuit=trace.getSubcircuit(),sourceGroup=subcircuit.getGroup();throw new TraceConnectionError({error_type:"source_trace_not_connected_error",message:errorMessage,subcircuit_id:subcircuit.subcircuit_id??void 0,source_group_id:sourceGroup?.source_group_id??void 0,source_trace_id:trace.source_trace_id??void 0,selectors_not_found:[selector]})}return portsWithSelectors.some(p4=>!p4.port)?{allPortsFound:!1}:{allPortsFound:!0,portsWithSelectors,ports:portsWithSelectors.map(({port})=>port)}}var Trace3=class extends PrimitiveComponent2{constructor(props){super(props);__publicField(this,"source_trace_id",null);__publicField(this,"pcb_trace_id",null);__publicField(this,"schematic_trace_id",null);__publicField(this,"_portsRoutedOnPcb");__publicField(this,"subcircuit_connectivity_map_key",null);__publicField(this,"_traceConnectionHash",null);__publicField(this,"_couldNotFindPort");this._portsRoutedOnPcb=[]}_getExplicitTraceThickness(){return this._parsedProps.thickness??this._parsedProps.width}get config(){return{zodProps:traceProps,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(p4=>typeof p4=="string"?p4:p4.getPortSelector()):[]}getTracePortPathSelectors(){return this._getTracePortOrNetSelectorListFromProps().filter(selector=>!selector.includes("net."))}getTracePathNetSelectors(){return this._getTracePortOrNetSelectorListFromProps().filter(selector=>selector.includes("net."))}_findConnectedPorts(){return Trace__findConnectedPorts(this)}_resolveNet(selector){let direct=this.getSubcircuit().selectOne(selector,{type:"net"});if(direct)return direct;let match2=selector.match(/^net\.(.+)$/),netName=match2?match2[1]:null;if(!netName)return null;let board=this.root?._getBoard();return board?board.getDescendants().find(d2=>d2.componentName==="Net"&&d2._parsedProps.name===netName)||null:(this.renderError(`Could not find a <board> ancestor for ${this}, so net "${selector}" cannot be resolved`),null)}_findConnectedNets(){let netsWithSelectors=this.getTracePathNetSelectors().map(selector=>({selector,net:this._resolveNet(selector)})),undefinedNets=netsWithSelectors.filter(n3=>!n3.net);return undefinedNets.length>0&&this.renderError(`Could not find net for selector "${undefinedNets[0].selector}" inside ${this}`),{netsWithSelectors,nets:netsWithSelectors.map(n3=>n3.net)}}_getAllTracesConnectedToSameNet(){let traces=this.getSubcircuit().selectAll("trace"),myNets=this._findConnectedNets().nets,myPorts=this._findConnectedPorts().ports??[];return traces.filter(t6=>{if(t6===this)return!1;let tNets=t6._findConnectedNets().nets,tPorts=t6._findConnectedPorts().ports??[];return tNets.some(n3=>myNets.includes(n3))||tPorts.some(p4=>myPorts.includes(p4))})}_isExplicitlyConnectedToPort(port){let{allPortsFound,portsWithSelectors:portsWithMetadata}=this._findConnectedPorts();return allPortsFound?portsWithMetadata.map(p4=>p4.port).includes(port):!1}_isExplicitlyConnectedToNet(net){return this._findConnectedNets().nets.includes(net)}doInitialCreateNetsFromProps(){createNetsFromProps(this,this.getTracePathNetSelectors())}_computeTraceConnectionHash(){let{allPortsFound,ports}=this._findConnectedPorts();return!allPortsFound||!ports?null:[...ports].sort((a3,b3)=>(a3.pcb_port_id||"").localeCompare(b3.pcb_port_id||"")).map(p4=>p4.pcb_port_id).join(",")}doInitialSourceTraceRender(){let{db}=this.root,{_parsedProps:props,parent}=this;if(!parent){this.renderError("Trace has no parent");return}let allPortsFound,ports;try{let result=this._findConnectedPorts();allPortsFound=result.allPortsFound,ports=result.portsWithSelectors??[]}catch(error){if(error instanceof TraceConnectionError){db.source_trace_not_connected_error.insert({...error.errorData,error_type:"source_trace_not_connected_error"}),this._couldNotFindPort=!0;return}throw error}if(!allPortsFound)return;this._traceConnectionHash=this._computeTraceConnectionHash();let existingTrace=db.source_trace.list().find(t6=>t6.subcircuit_connectivity_map_key===this.subcircuit_connectivity_map_key&&t6.connected_source_port_ids.sort().join(",")===this._traceConnectionHash);if(existingTrace){this.source_trace_id=existingTrace.source_trace_id;return}let nets=this._findConnectedNets().nets,displayName=getTraceDisplayName({ports,nets}),trace=db.source_trace.insert({connected_source_port_ids:ports.map(p4=>p4.port.source_port_id),connected_source_net_ids:nets.map(n3=>n3.source_net_id),subcircuit_id:this.getSubcircuit()?.subcircuit_id,max_length:getMaxLengthFromConnectedCapacitors(ports.map(p4=>p4.port),{db})??props.maxLength,display_name:displayName,min_trace_thickness:this._getExplicitTraceThickness()});this.source_trace_id=trace.source_trace_id}_insertErrorIfTraceIsOutsideBoard(mergedRoute,ports){let{db}=this.root;isRouteOutsideBoard(mergedRoute,{db})&&db.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:ports.map(p4=>p4.pcb_port_id)})}doInitialPcbManualTraceRender(){Trace_doInitialPcbManualTraceRender(this)}doInitialPcbTraceRender(){Trace_doInitialPcbTraceRender(this)}_doInitialSchematicTraceRenderWithDisplayLabel(){Trace__doInitialSchematicTraceRenderWithDisplayLabel(this)}_isSymbolToChipConnection(){let{allPortsFound,ports}=this._findConnectedPorts();if(!allPortsFound||ports.length!==2)return!1;let[port1,port2]=ports;if(!port1?.parent||!port2?.parent)return!1;let isPort1Chip=port1.parent.config.shouldRenderAsSchematicBox,isPort2Chip=port2.parent.config.shouldRenderAsSchematicBox;return isPort1Chip&&!isPort2Chip||!isPort1Chip&&isPort2Chip}_isSymbolToSymbolConnection(){let{allPortsFound,ports}=this._findConnectedPorts();if(!allPortsFound||ports.length!==2)return!1;let[port1,port2]=ports;if(!port1?.parent||!port2?.parent)return!1;let isPort1Symbol=!port1.parent.config.shouldRenderAsSchematicBox,isPort2Symbol=!port2.parent.config.shouldRenderAsSchematicBox;return isPort1Symbol&&isPort2Symbol}_isChipToChipConnection(){let{allPortsFound,ports}=this._findConnectedPorts();if(!allPortsFound||ports.length!==2)return!1;let[port1,port2]=ports;if(!port1?.parent||!port2?.parent)return!1;let isPort1Chip=port1.parent.config.shouldRenderAsSchematicBox,isPort2Chip=port2.parent.config.shouldRenderAsSchematicBox;return isPort1Chip&&isPort2Chip}doInitialSchematicTraceRender(){Trace_doInitialSchematicTraceRender(this)}},NormalComponent__getMinimumFlexContainerSize=component=>{let{db}=component.root;if(component.pcb_component_id){let pcbComponent=db.pcb_component.get(component.pcb_component_id);return pcbComponent?{width:pcbComponent.width,height:pcbComponent.height}:null}if(component.pcb_group_id){let pcbGroup=db.pcb_group.get(component.pcb_group_id);if(!pcbGroup)return null;if(pcbGroup.outline&&pcbGroup.outline.length>0){let bounds=getBoundsFromPoints(pcbGroup.outline);return bounds?{width:bounds.maxX-bounds.minX,height:bounds.maxY-bounds.minY}:null}return{width:pcbGroup.width??0,height:pcbGroup.height??0}}return null},NormalComponent__repositionOnPcb=(component,position2)=>{let{db}=component.root,allCircuitJson=db.toArray();if(component.pcb_component_id){repositionPcbComponentTo(allCircuitJson,component.pcb_component_id,position2);return}if(component.source_group_id){repositionPcbGroupTo(allCircuitJson,component.source_group_id,position2);return}throw new Error(`Cannot reposition component ${component.getString()}: no pcb_component_id or source_group_id`)},NormalComponent_doInitialSourceDesignRuleChecks=component=>{let{db}=component.root;if(!component.source_component_id)return;let ports=component.selectAll("port"),traces=db.source_trace.list(),connected=new Set;for(let trace of traces)for(let id of trace.connected_source_port_ids)connected.add(id);let internalGroups=component._getInternallyConnectedPins();for(let group of internalGroups)if(group.some(p4=>p4.source_port_id&&connected.has(p4.source_port_id)))for(let p4 of group)p4.source_port_id&&connected.add(p4.source_port_id);for(let port of ports)port.source_port_id&&shouldCheckPortForMissingTrace(component,port)&&(connected.has(port.source_port_id)||db.source_pin_missing_trace_warning.insert({message:`Port ${port.getNameAndAliases()[0]} on ${component.props.name} is missing a trace`,source_component_id:component.source_component_id,source_port_id:port.source_port_id,subcircuit_id:component.getSubcircuit().subcircuit_id??void 0,warning_type:"source_pin_missing_trace_warning"}))},shouldCheckPortForMissingTrace=(component,port)=>{if(component.config.componentName==="Chip"){let pinAttributes=component.props.pinAttributes;if(!pinAttributes)return!1;for(let alias of port.getNameAndAliases()){let attrs=pinAttributes[alias];if(attrs?.requiresPower||attrs?.requiresGround||attrs?.requiresVoltage!==void 0)return!0}return!1}return!0};function getPcbTextBounds(text){let fontSize=text.font_size,textWidth=text.text.length*fontSize*.6,textHeight=fontSize,anchorAlignment=text.anchor_alignment||"center",centerX=text.anchor_position.x,centerY=text.anchor_position.y;switch(anchorAlignment){case"top_left":centerX=text.anchor_position.x+textWidth/2,centerY=text.anchor_position.y+textHeight/2;break;case"top_center":centerX=text.anchor_position.x,centerY=text.anchor_position.y+textHeight/2;break;case"top_right":centerX=text.anchor_position.x-textWidth/2,centerY=text.anchor_position.y+textHeight/2;break;case"center_left":centerX=text.anchor_position.x+textWidth/2,centerY=text.anchor_position.y;break;case"center":centerX=text.anchor_position.x,centerY=text.anchor_position.y;break;case"center_right":centerX=text.anchor_position.x-textWidth/2,centerY=text.anchor_position.y;break;case"bottom_left":centerX=text.anchor_position.x+textWidth/2,centerY=text.anchor_position.y-textHeight/2;break;case"bottom_center":centerX=text.anchor_position.x,centerY=text.anchor_position.y-textHeight/2;break;case"bottom_right":centerX=text.anchor_position.x-textWidth/2,centerY=text.anchor_position.y-textHeight/2;break;default:centerX=text.anchor_position.x,centerY=text.anchor_position.y;break}return{x:centerX-textWidth/2,y:centerY-textHeight/2,width:textWidth,height:textHeight}}function NormalComponent_doInitialSilkscreenOverlapAdjustment(component){if(!component._adjustSilkscreenTextAutomatically||component.root?.pcbDisabled||!component.pcb_component_id)return;let{db}=component.root,componentCenter=component._getPcbCircuitJsonBounds().center,silkscreenTexts=db.pcb_silkscreen_text.list({pcb_component_id:component.pcb_component_id}).filter(text=>text.text===component.name);if(silkscreenTexts.length===0)return;let obstacleBounds=component.getSubcircuit().selectAll("[_isNormalComponent=true]").filter(comp=>comp!==component&&comp.pcb_component_id).map(comp=>{let bounds=comp._getPcbCircuitJsonBounds(),box2={center:bounds.center,width:bounds.width,height:bounds.height};return getBoundingBox2(box2)});for(let silkscreenText of silkscreenTexts){let currentPosition=silkscreenText.anchor_position,textBounds=getPcbTextBounds(silkscreenText),textBox={center:{x:textBounds.x+textBounds.width/2,y:textBounds.y+textBounds.height/2},width:textBounds.width,height:textBounds.height},textBoundsBox=getBoundingBox2(textBox);if(!obstacleBounds.some(obstacle=>doBoundsOverlap(textBoundsBox,obstacle)))continue;let flippedX=2*componentCenter.x-currentPosition.x,flippedY=2*componentCenter.y-currentPosition.y,flippedTextBox={center:{x:flippedX,y:flippedY},width:textBounds.width,height:textBounds.height},flippedTextBounds=getBoundingBox2(flippedTextBox);obstacleBounds.some(obstacle=>doBoundsOverlap(flippedTextBounds,obstacle))||db.pcb_silkscreen_text.update(silkscreenText.pcb_silkscreen_text_id,{anchor_position:{x:flippedX,y:flippedY}})}}function filterPinLabels(pinLabels){if(!pinLabels)return{validPinLabels:pinLabels,invalidPinLabelsMessages:[]};let validPinLabels={},invalidPinLabelsMessages=[];for(let[pin,labelOrLabels]of Object.entries(pinLabels)){let labels=Array.isArray(labelOrLabels)?labelOrLabels.slice():[labelOrLabels],validLabels=[];for(let label of labels)isValidPinLabel(pin,label)?validLabels.push(label):invalidPinLabelsMessages.push(`Invalid pin label: ${pin} = '${label}' - excluding from component. Please use a valid pin label.`);validLabels.length>0&&(validPinLabels[pin]=Array.isArray(labelOrLabels)?validLabels:validLabels[0])}return{validPinLabels:Object.keys(validPinLabels).length>0?validPinLabels:void 0,invalidPinLabelsMessages}}function isValidPinLabel(pin,label){try{let testProps={name:"test",footprint:"test",pinLabels:{[pin]:label}};return chipProps.safeParse(testProps).success}catch{return!1}}var isHttpUrl=s4=>s4.startsWith("http://")||s4.startsWith("https://"),parseLibraryFootprintRef=s4=>{if(isHttpUrl(s4))return null;let idx=s4.indexOf(":");if(idx<=0)return null;let footprintLib=s4.slice(0,idx),footprintName=s4.slice(idx+1);return!footprintLib||!footprintName?null:{footprintLib,footprintName}},isStaticAssetPath=s4=>s4.startsWith("/"),resolveStaticFileImportDebug=(0,import_debug9.default)("tscircuit:core:resolveStaticFileImport");async function resolveStaticFileImport(path,platform){if(!path)return path;let resolver=platform?.resolveProjectStaticFileImportUrl;if(resolver&&path.startsWith("/"))try{let resolved=await resolver(path);if(resolved)return resolved}catch(error){resolveStaticFileImportDebug("failed to resolve static file via platform resolver",error)}return constructAssetUrl(path,platform?.projectBaseUrl)}function NormalComponent_doInitialPcbFootprintStringRender(component,queueAsyncEffect){let{footprint}=component.props;if(footprint??(footprint=component._getImpliedFootprintString?.()),!footprint)return;let{pcbRotation,pinLabels,pcbPinLabels}=component.props,fileExtension=getFileExtension(String(footprint)),footprintParser=fileExtension?component.root?.platform?.footprintFileParserMap?.[fileExtension]:null;if(typeof footprint=="string"&&(isHttpUrl(footprint)||isStaticAssetPath(footprint))&&footprintParser){if(component._hasStartedFootprintUrlLoad)return;component._hasStartedFootprintUrlLoad=!0,queueAsyncEffect("load-footprint-from-platform-file-parser",async()=>{let footprintUrl=isHttpUrl(footprint)?footprint:await resolveStaticFileImport(footprint,component.root?.platform);try{let result=await footprintParser.loadFromUrl(footprintUrl),fpComponents=createComponentsFromCircuitJson({componentName:component.name,componentRotation:pcbRotation,footprinterString:footprintUrl,pinLabels,pcbPinLabels},result.footprintCircuitJson);component.addAll(fpComponents),component._markDirty("InitializePortsFromChildren")}catch(err){let db=component.root?.db;if(db&&component.source_component_id&&component.pcb_component_id){let subcircuit=component.getSubcircuit(),errorMsg=`${component.getString()} failed to load footprint "${footprintUrl}": `+(err instanceof Error?err.message:String(err)),errorObj=external_footprint_load_error.parse({type:"external_footprint_load_error",message:errorMsg,pcb_component_id:component.pcb_component_id,source_component_id:component.source_component_id,subcircuit_id:subcircuit.subcircuit_id??void 0,pcb_group_id:component.getGroup()?.pcb_group_id??void 0,footprinter_string:footprintUrl});db.external_footprint_load_error.insert(errorObj)}throw err}});return}if(typeof footprint=="string"&&isHttpUrl(footprint)){if(component._hasStartedFootprintUrlLoad)return;component._hasStartedFootprintUrlLoad=!0;let url=footprint;queueAsyncEffect("load-footprint-url",async()=>{try{let res2=await fetch(url);if(!res2.ok)throw new Error(`Failed to fetch footprint: ${res2.status}`);let soup=await res2.json(),fpComponents=createComponentsFromCircuitJson({componentName:component.name,componentRotation:pcbRotation,footprinterString:url,pinLabels,pcbPinLabels},soup);component.addAll(fpComponents),component._markDirty("InitializePortsFromChildren")}catch(err){let db=component.root?.db;if(db&&component.source_component_id&&component.pcb_component_id){let subcircuit=component.getSubcircuit(),errorMsg=`${component.getString()} failed to load external footprint "${url}": `+(err instanceof Error?err.message:String(err)),errorObj=external_footprint_load_error.parse({type:"external_footprint_load_error",message:errorMsg,pcb_component_id:component.pcb_component_id,source_component_id:component.source_component_id,subcircuit_id:subcircuit.subcircuit_id??void 0,pcb_group_id:component.getGroup()?.pcb_group_id??void 0,footprinter_string:url});db.external_footprint_load_error.insert(errorObj)}throw err}});return}if(typeof footprint=="string"){let libRef=parseLibraryFootprintRef(footprint);if(!libRef||component._hasStartedFootprintUrlLoad)return;component._hasStartedFootprintUrlLoad=!0;let libMap=component.root?.platform?.footprintLibraryMap?.[libRef.footprintLib],resolverFn;if(typeof libMap=="function"&&(resolverFn=libMap),!resolverFn)return;let resolvedPcbStyle=component.getInheritedMergedProperty("pcbStyle");queueAsyncEffect("load-lib-footprint",async()=>{try{let result=await resolverFn(libRef.footprintName,{resolvedPcbStyle}),circuitJson=null;if(Array.isArray(result)?circuitJson=result:Array.isArray(result.footprintCircuitJson)&&(circuitJson=result.footprintCircuitJson),!circuitJson)return;let fpComponents=createComponentsFromCircuitJson({componentName:component.name,componentRotation:pcbRotation,footprinterString:footprint,pinLabels,pcbPinLabels},circuitJson);component.addAll(fpComponents),!Array.isArray(result)&&result.cadModel&&(component._asyncFootprintCadModel=result.cadModel);for(let child of component.children)child.componentName==="Port"&&child._markDirty?.("PcbPortRender");component._markDirty("InitializePortsFromChildren")}catch(err){let db=component.root?.db;if(db&&component.source_component_id&&component.pcb_component_id){let subcircuit=component.getSubcircuit(),errorMsg=`${component.getString()} failed to load external footprint "${footprint}": `+(err instanceof Error?err.message:String(err)),errorObj=external_footprint_load_error.parse({type:"external_footprint_load_error",message:errorMsg,pcb_component_id:component.pcb_component_id,source_component_id:component.source_component_id,subcircuit_id:subcircuit.subcircuit_id??void 0,pcb_group_id:component.getGroup()?.pcb_group_id??void 0,footprinter_string:footprint});db.external_footprint_load_error.insert(errorObj)}throw err}});return}if(!(0,import_react3.isValidElement)(footprint)&&footprint.componentName==="Footprint"&&component.add(footprint),Array.isArray(footprint)&&!(0,import_react3.isValidElement)(footprint)&&footprint.length>0){try{let fpComponents=createComponentsFromCircuitJson({componentName:component.name,componentRotation:pcbRotation,footprinterString:"",pinLabels,pcbPinLabels},footprint);component.addAll(fpComponents)}catch(err){let db=component.root?.db;if(db&&component.source_component_id&&component.pcb_component_id){let subcircuit=component.getSubcircuit(),errorMsg=`${component.getString()} failed to load json footprint: `+(err instanceof Error?err.message:String(err)),errorObj=circuit_json_footprint_load_error.parse({type:"circuit_json_footprint_load_error",message:errorMsg,pcb_component_id:component.pcb_component_id,source_component_id:component.source_component_id,subcircuit_id:subcircuit.subcircuit_id??void 0,pcb_group_id:component.getGroup()?.pcb_group_id??void 0});db.circuit_json_footprint_load_error.insert(errorObj)}throw err}return}}function NormalComponent_doInitialPcbComponentAnchorAlignment(component){if(component.root?.pcbDisabled||!component.pcb_component_id)return;let{pcbX,pcbY}=component._parsedProps,pcbPositionAnchor=component.props?.pcbPositionAnchor;if(!pcbPositionAnchor||pcbX===void 0&&pcbY===void 0)return;let bounds=getBoundsOfPcbComponents(component.children);if(bounds.width===0||bounds.height===0)return;let currentCenter={...{x:(bounds.minX+bounds.maxX)/2,y:(bounds.minY+bounds.maxY)/2}},anchorPos=null;if(new Set(["center","top_left","top_center","top_right","center_left","center_right","bottom_left","bottom_center","bottom_right"]).has(pcbPositionAnchor)){let b3={left:bounds.minX,right:bounds.maxX,top:bounds.minY,bottom:bounds.maxY};switch(pcbPositionAnchor){case"center":anchorPos=currentCenter;break;case"top_left":anchorPos={x:b3.left,y:b3.top};break;case"top_center":anchorPos={x:currentCenter.x,y:b3.top};break;case"top_right":anchorPos={x:b3.right,y:b3.top};break;case"center_left":anchorPos={x:b3.left,y:currentCenter.y};break;case"center_right":anchorPos={x:b3.right,y:currentCenter.y};break;case"bottom_left":anchorPos={x:b3.left,y:b3.bottom};break;case"bottom_center":anchorPos={x:currentCenter.x,y:b3.bottom};break;case"bottom_right":anchorPos={x:b3.right,y:b3.bottom};break}}else try{let port=component.portMap[pcbPositionAnchor];port&&(anchorPos=port._getGlobalPcbPositionBeforeLayout())}catch{}if(!anchorPos)return;let newCenter={...currentCenter};pcbX!==void 0&&(newCenter.x+=pcbX-anchorPos.x),pcbY!==void 0&&(newCenter.y+=pcbY-anchorPos.y),(Math.abs(newCenter.x-currentCenter.x)>1e-6||Math.abs(newCenter.y-currentCenter.y)>1e-6)&&component._repositionOnPcb(newCenter)}var debug32=(0,import_debug5.default)("tscircuit:core"),rotation32=external_exports.object({x:rotation,y:rotation,z:rotation}),NormalComponent3=class extends PrimitiveComponent2{constructor(props){let filteredProps={...props},invalidPinLabelsMessages=[];if(filteredProps.pinLabels&&!Array.isArray(filteredProps.pinLabels)){let{validPinLabels,invalidPinLabelsMessages:messages}=filterPinLabels(filteredProps.pinLabels);filteredProps.pinLabels=validPinLabels,invalidPinLabelsMessages=messages}super(filteredProps);__publicField(this,"reactSubtrees",[]);__publicField(this,"_impliedFootprint");__publicField(this,"isPrimitiveContainer",!0);__publicField(this,"_isNormalComponent",!0);__publicField(this,"_attributeLowerToCamelNameMap",{_isnormalcomponent:"_isNormalComponent"});__publicField(this,"_asyncSupplierPartNumbers");__publicField(this,"_asyncFootprintCadModel");__publicField(this,"_isCadModelChild");__publicField(this,"pcb_missing_footprint_error_id");__publicField(this,"_hasStartedFootprintUrlLoad",!1);__publicField(this,"_invalidPinLabelMessages",[]);__publicField(this,"_adjustSilkscreenTextAutomatically",!1);this._invalidPinLabelMessages=invalidPinLabelsMessages,this._addChildrenFromStringFootprint(),this.initPorts()}get defaultInternallyConnectedPinNames(){return[]}get internallyConnectedPinNames(){return(this._parsedProps.internallyConnectedPins??this.defaultInternallyConnectedPinNames).map(pinGroup=>pinGroup.map(pin=>typeof pin=="number"?`pin${pin}`:pin))}doInitialSourceNameDuplicateComponentRemoval(){if(!this.name)return;let root=this.root;if(this.getSubcircuit().selectAll(`.${this.name}`).filter(component=>component!==this&&component._isNormalComponent&&component.renderPhaseStates?.SourceNameDuplicateComponentRemoval?.initialized).length>0){let pcbPosition2=this._getGlobalPcbPositionBeforeLayout(),schematicPosition=this._getGlobalSchematicPositionBeforeLayout();root.db.source_failed_to_create_component_error.insert({component_name:this.name,error_type:"source_failed_to_create_component_error",message:`Cannot create component "${this.name}": A component with the same name already exists`,pcb_center:pcbPosition2,schematic_center:schematicPosition}),this.shouldBeRemoved=!0;let childrenToRemove=[...this.children];for(let child of childrenToRemove)this.remove(child)}}initPorts(opts={}){if(this.root?.schematicDisabled)return;let{config}=this,portsToCreate=[],schPortArrangement=this._getSchematicPortArrangement();if(schPortArrangement&&!this._parsedProps.pinLabels){for(let side in schPortArrangement){let pins=schPortArrangement[side].pins;if(Array.isArray(pins))for(let pinNumberOrLabel of pins){let pinNumber=parsePinNumberFromLabelsOrThrow(pinNumberOrLabel,this._parsedProps.pinLabels);portsToCreate.push(new Port({pinNumber,aliases:opts.additionalAliases?.[`pin${pinNumber}`]??[]},{originDescription:`schPortArrangement:${side}`}))}}let sides=["left","right","top","bottom"],pinNum=1;for(let side of sides){let size2=schPortArrangement[`${side}Size`];for(let i3=0;i3<size2;i3++)portsToCreate.push(new Port({pinNumber:pinNum++,aliases:opts.additionalAliases?.[`pin${pinNum}`]??[]},{originDescription:`schPortArrangement:${side}`}))}}let pinLabels=this._parsedProps.pinLabels;if(pinLabels)for(let[pinNumber,label]of Object.entries(pinLabels)){pinNumber=pinNumber.replace("pin","");let existingPort=portsToCreate.find(p4=>p4._parsedProps.pinNumber===Number(pinNumber)),primaryLabel=Array.isArray(label)?label[0]:label,otherLabels=Array.isArray(label)?label.slice(1):[];existingPort?(existingPort.externallyAddedAliases.push(primaryLabel,...otherLabels),existingPort.props.name=primaryLabel):(existingPort=new Port({pinNumber:parseInt(pinNumber),name:primaryLabel,aliases:[...otherLabels,...opts.additionalAliases?.[`pin${parseInt(pinNumber)}`]??[]]},{originDescription:`pinLabels:pin${pinNumber}`}),portsToCreate.push(existingPort))}if(config.schematicSymbolName&&!opts.ignoreSymbolPorts){let sym=ef[this._getSchematicSymbolNameOrThrow()];if(!sym)return;for(let symPort of sym.ports){let pinNumber=getPinNumberFromLabels(symPort.labels);if(!pinNumber)continue;let existingPort=portsToCreate.find(p4=>p4._parsedProps.pinNumber===Number(pinNumber));if(existingPort)existingPort.schematicSymbolPortDef=symPort;else{let port=getPortFromHints(symPort.labels.concat(opts.additionalAliases?.[`pin${pinNumber}`]??[]));port&&(port.originDescription=`schematicSymbol:labels[0]:${symPort.labels[0]}`,port.schematicSymbolPortDef=symPort,portsToCreate.push(port))}}this.addAll(portsToCreate)}if(!this._getSchematicPortArrangement()){let portsFromFootprint=this.getPortsFromFootprint(opts);for(let port of portsFromFootprint)portsToCreate.some(p4=>p4.isMatchingAnyOf(port.getNameAndAliases()))||portsToCreate.push(port)}let requiredPinCount=opts.pinCount??this._getPinCount()??0;for(let pn3=1;pn3<=requiredPinCount;pn3++){if(portsToCreate.find(p4=>p4._parsedProps.pinNumber===pn3))continue;if(!schPortArrangement){portsToCreate.push(new Port({pinNumber:pn3,aliases:opts.additionalAliases?.[`pin${pn3}`]??[]}));continue}let explicitlyListedPinNumbersInSchPortArrangement=[...schPortArrangement.leftSide?.pins??[],...schPortArrangement.rightSide?.pins??[],...schPortArrangement.topSide?.pins??[],...schPortArrangement.bottomSide?.pins??[]].map(pn22=>parsePinNumberFromLabelsOrThrow(pn22,this._parsedProps.pinLabels));["leftSize","rightSize","topSize","bottomSize","leftPinCount","rightPinCount","topPinCount","bottomPinCount"].some(key=>key in schPortArrangement)&&(explicitlyListedPinNumbersInSchPortArrangement=Array.from({length:this._getPinCount()},(_4,i3)=>i3+1)),explicitlyListedPinNumbersInSchPortArrangement.includes(pn3)&&portsToCreate.push(new Port({pinNumber:pn3,aliases:opts.additionalAliases?.[`pin${pn3}`]??[]},{originDescription:`notOtherwiseAddedButDeducedFromPinCount:${pn3}`}))}portsToCreate.length>0&&this.addAll(portsToCreate)}_getImpliedFootprintString(){return null}_addChildrenFromStringFootprint(){let{pcbRotation,pinLabels,pcbPinLabels}=this.props,{footprint}=this.props;if(footprint??(footprint=this._getImpliedFootprintString?.()),!!footprint&&typeof footprint=="string"){if(isHttpUrl(footprint)||isStaticAssetPath(footprint)||parseLibraryFootprintRef(footprint))return;let fpSoup=fp.string(footprint).soup(),fpComponents=createComponentsFromCircuitJson({componentName:this.name??this.componentName,componentRotation:pcbRotation,footprinterString:footprint,pinLabels,pcbPinLabels},fpSoup);this.addAll(fpComponents)}}get portMap(){return new Proxy({},{get:(target,prop)=>{let port=this.children.find(c3=>c3.componentName==="Port"&&c3.isMatchingNameOrAlias(prop));if(!port)throw new Error(`There was an issue finding the port "${prop.toString()}" inside of a ${this.componentName} component with name: "${this.props.name}". This is a bug in @tscircuit/core`);return port}})}getInstanceForReactElement(element){for(let subtree of this.reactSubtrees)if(subtree.element===element)return subtree.component;return null}doInitialSourceRender(){let ftype=this.config.sourceFtype;if(!ftype)return;let{db}=this.root,{_parsedProps:props}=this,source_component=db.source_component.insert({ftype,name:this.name,manufacturer_part_number:props.manufacturerPartNumber??props.mfn,supplier_part_numbers:props.supplierPartNumbers});this.source_component_id=source_component.source_component_id}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;let{db}=this.root;if(this._invalidPinLabelMessages?.length&&this.root?.db)for(let message of this._invalidPinLabelMessages){let property_name="pinLabels",match2=message.match(/^Invalid pin label:\s*([^=]+)=\s*'([^']+)'/);match2&&(property_name=`pinLabels['${match2[2]}']`),this.root.db.source_property_ignored_warning.insert({source_component_id:this.source_component_id,property_name,message,error_type:"source_property_ignored_warning"})}let{schematicSymbolName}=this.config,{_parsedProps:props}=this;props.symbol&&(0,import_react2.isValidElement)(props.symbol)?this._doInitialSchematicComponentRenderWithReactSymbol(props.symbol):schematicSymbolName?this._doInitialSchematicComponentRenderWithSymbol():this._getSchematicBoxDimensions()&&this._doInitialSchematicComponentRenderWithSchematicBoxDimensions();let manualPlacement=this.getSubcircuit()?._getSchematicManualPlacementForComponent(this);if(this.schematic_component_id&&(this.props.schX!==void 0||this.props.schY!==void 0)&&manualPlacement){if(!this.schematic_component_id)return;let warning=schematic_manual_edit_conflict_warning.parse({type:"schematic_manual_edit_conflict_warning",schematic_manual_edit_conflict_warning_id:`schematic_manual_edit_conflict_${this.source_component_id}`,message:`${this.getString()} has both manual placement and prop coordinates. schX and schY will be used. Remove schX/schY or clear the manual placement.`,schematic_component_id:this.schematic_component_id,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id});db.schematic_manual_edit_conflict_warning.insert(warning)}}_getSchematicSymbolDisplayValue(){}_getInternallyConnectedPins(){if(this.internallyConnectedPinNames.length===0)return[];let internallyConnectedPorts=[];for(let netPortNames of this.internallyConnectedPinNames){let ports=[];for(let portName of netPortNames)ports.push(this.portMap[portName]);internallyConnectedPorts.push(ports)}return internallyConnectedPorts}_doInitialSchematicComponentRenderWithSymbol(){if(this.root?.schematicDisabled)return;let{db}=this.root,{_parsedProps:props}=this,symbol_name=this._getSchematicSymbolNameOrThrow(),symbol=ef[symbol_name],center2=this._getGlobalSchematicPositionBeforeLayout();if(symbol){let schematic_component2=db.schematic_component.insert({center:center2,size:symbol.size,source_component_id:this.source_component_id,is_box_with_pins:!0,symbol_name,symbol_display_value:this._getSchematicSymbolDisplayValue()});this.schematic_component_id=schematic_component2.schematic_component_id}}_doInitialSchematicComponentRenderWithReactSymbol(symbolElement){if(this.root?.schematicDisabled)return;let{db}=this.root,center2=this._getGlobalSchematicPositionBeforeLayout(),schematic_component2=db.schematic_component.insert({center:center2,size:{width:0,height:0},source_component_id:this.source_component_id,symbol_display_value:this._getSchematicSymbolDisplayValue(),is_box_with_pins:!1});this.schematic_component_id=schematic_component2.schematic_component_id}_doInitialSchematicComponentRenderWithSchematicBoxDimensions(){if(this.root?.schematicDisabled)return;let{db}=this.root,{_parsedProps:props}=this,dimensions=this._getSchematicBoxDimensions(),primaryPortLabels={};if(Array.isArray(props.pinLabels))props.pinLabels.forEach((label,index)=>{primaryPortLabels[String(index+1)]=label});else for(let[port,label]of Object.entries(props.pinLabels??{}))primaryPortLabels[port]=Array.isArray(label)?label[0]:label;let center2=this._getGlobalSchematicPositionBeforeLayout(),schPortArrangement=this._getSchematicPortArrangement(),schematic_component2=db.schematic_component.insert({center:center2,rotation:props.schRotation??0,size:dimensions.getSize(),port_arrangement:underscorifyPortArrangement(schPortArrangement),pin_spacing:props.schPinSpacing??.2,pin_styles:underscorifyPinStyles(props.schPinStyle,props.pinLabels),port_labels:primaryPortLabels,source_component_id:this.source_component_id}),hasTopOrBottomPins=schPortArrangement?.topSide!==void 0||schPortArrangement?.bottomSide!==void 0,schematic_box_width=dimensions?.getSize().width,schematic_box_height=dimensions?.getSize().height,manufacturer_part_number_schematic_text=db.schematic_text.insert({text:props.manufacturerPartNumber??"",schematic_component_id:schematic_component2.schematic_component_id,anchor:"left",rotation:0,position:{x:hasTopOrBottomPins?center2.x+(schematic_box_width??0)/2+.1:center2.x-(schematic_box_width??0)/2,y:hasTopOrBottomPins?center2.y+(schematic_box_height??0)/2+.35:center2.y-(schematic_box_height??0)/2-.13},color:"#006464",font_size:.18}),component_name_text=db.schematic_text.insert({text:props.name??"",schematic_component_id:schematic_component2.schematic_component_id,anchor:"left",rotation:0,position:{x:hasTopOrBottomPins?center2.x+(schematic_box_width??0)/2+.1:center2.x-(schematic_box_width??0)/2,y:hasTopOrBottomPins?center2.y+(schematic_box_height??0)/2+.55:center2.y+(schematic_box_height??0)/2+.13},color:"#006464",font_size:.18});this.schematic_component_id=schematic_component2.schematic_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,subcircuit=this.getSubcircuit(),componentLayer=props.layer??"top";if(componentLayer!=="top"&&componentLayer!=="bottom"){let error=pcb_component_invalid_layer_error.parse({type:"pcb_component_invalid_layer_error",message:`Component cannot be placed on layer '${componentLayer}'. Components can only be placed on 'top' or 'bottom' layers.`,source_component_id:this.source_component_id,layer:componentLayer,subcircuit_id:subcircuit.subcircuit_id??void 0});db.pcb_component_invalid_layer_error.insert(error)}let globalTransform=this._computePcbGlobalTransformBeforeLayout(),accumulatedRotation=decomposeTSR(globalTransform).rotation.angle*180/Math.PI,pcb_component2=db.pcb_component.insert({center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,layer:componentLayer==="top"||componentLayer==="bottom"?componentLayer:"top",rotation:props.pcbRotation??accumulatedRotation,source_component_id:this.source_component_id,subcircuit_id:subcircuit.subcircuit_id??void 0,do_not_place:props.doNotPlace??!1,obstructs_within_bounds:props.obstructsWithinBounds??!0});if(!(props.footprint??this._getImpliedFootprintString())&&!this.isGroup){let footprint_error=db.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=footprint_error.pcb_missing_footprint_error_id}this.pcb_component_id=pcb_component2.pcb_component_id;let manualPlacement=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if((this.props.pcbX!==void 0||this.props.pcbY!==void 0)&&manualPlacement){let warning=pcb_manual_edit_conflict_warning.parse({type:"pcb_manual_edit_conflict_warning",pcb_manual_edit_conflict_warning_id:`pcb_manual_edit_conflict_${this.source_component_id}`,message:`${this.getString()} has both manual placement and prop coordinates. pcbX and pcbY will be used. Remove pcbX/pcbY or clear the manual placement.`,pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,subcircuit_id:subcircuit.subcircuit_id??void 0});db.pcb_manual_edit_conflict_warning.insert(warning)}}doInitialPcbComponentSizeCalculation(){if(this.root?.pcbDisabled||!this.pcb_component_id)return;let{db}=this.root,{_parsedProps:props}=this,bounds=getBoundsOfPcbComponents(this.children);if(bounds.width===0||bounds.height===0)return;let center2={x:(bounds.minX+bounds.maxX)/2,y:(bounds.minY+bounds.maxY)/2};db.pcb_component.update(this.pcb_component_id,{center:center2,width:bounds.width,height:bounds.height})}updatePcbComponentSizeCalculation(){this.doInitialPcbComponentSizeCalculation()}doInitialSchematicComponentSizeCalculation(){if(this.root?.schematicDisabled||!this.schematic_component_id)return;let{db}=this.root;if(!db.schematic_component.get(this.schematic_component_id))return;let schematicElements=[],collectSchematicPrimitives=children=>{for(let child of children){if(child.isSchematicPrimitive&&child.componentName==="SchematicLine"){let line2=db.schematic_line.get(child.schematic_line_id);line2&&schematicElements.push(line2)}if(child.isSchematicPrimitive&&child.componentName==="SchematicRect"){let rect=db.schematic_rect.get(child.schematic_rect_id);rect&&schematicElements.push(rect)}if(child.isSchematicPrimitive&&child.componentName==="SchematicCircle"){let circle2=db.schematic_circle.get(child.schematic_circle_id);circle2&&schematicElements.push(circle2)}if(child.isSchematicPrimitive&&child.componentName==="SchematicArc"){let arc2=db.schematic_arc.get(child.schematic_arc_id);arc2&&schematicElements.push(arc2)}if(child.isSchematicPrimitive&&child.componentName==="SchematicText"){let text=db.schematic_text.get(child.schematic_text_id);text&&schematicElements.push(text)}child.children&&child.children.length>0&&collectSchematicPrimitives(child.children)}};if(collectSchematicPrimitives(this.children),schematicElements.length===0)return;let bounds=getBoundsForSchematic(schematicElements),width=Math.abs(bounds.maxX-bounds.minX),height=Math.abs(bounds.maxY-bounds.minY);if(width===0&&height===0)return;let centerX=(bounds.minX+bounds.maxX)/2,centerY=(bounds.minY+bounds.maxY)/2;db.schematic_component.update(this.schematic_component_id,{center:{x:centerX,y:centerY},size:{width,height}})}updateSchematicComponentSizeCalculation(){this.doInitialSchematicComponentSizeCalculation()}doInitialPcbComponentAnchorAlignment(){NormalComponent_doInitialPcbComponentAnchorAlignment(this)}updatePcbComponentAnchorAlignment(){this.doInitialPcbComponentAnchorAlignment()}_renderReactSubtree(element){let component=createInstanceFromReactElement(element);return{element,component}}doInitialInitializePortsFromChildren(){this.initPorts()}doInitialReactSubtreesRender(){let fpElm=this.props.footprint;(0,import_react2.isValidElement)(fpElm)&&(this.children.some(c3=>c3.componentName==="Footprint")||this.add(fpElm));let symElm=this.props.symbol;(0,import_react2.isValidElement)(symElm)&&(this.children.some(c3=>c3.componentName==="Symbol")||this.add(symElm));let cmElm=this.props.cadModel;if((0,import_react2.isValidElement)(cmElm)){this._isCadModelChild=!0;let hasCadAssemblyChild=this.children.some(c3=>c3.componentName==="CadAssembly"),hasCadModelChild=this.children.some(c3=>c3.componentName==="CadModel");!hasCadAssemblyChild&&!hasCadModelChild&&this.add(cmElm)}}doInitialPcbFootprintStringRender(){NormalComponent_doInitialPcbFootprintStringRender(this,(name,effect)=>this._queueAsyncEffect(name,effect))}_hasExistingPortExactly(port1){return this.children.filter(c3=>c3.componentName==="Port").some(port2=>{let aliases1=port1.getNameAndAliases(),aliases2=port2.getNameAndAliases();return aliases1.length===aliases2.length&&aliases1.every(alias=>aliases2.includes(alias))})}add(componentOrElm){let component;if((0,import_react2.isValidElement)(componentOrElm)){let subtree=this._renderReactSubtree(componentOrElm);this.reactSubtrees.push(subtree),component=subtree.component}else component=componentOrElm;if(component.componentName==="Port"){if(this._hasExistingPortExactly(component))return;let conflictingPort=this.children.filter(c3=>c3.componentName==="Port").find(p4=>p4.isMatchingAnyOf(component.getNameAndAliases()));conflictingPort&&debug32(`Similar ports added. Port 1: ${conflictingPort}, Port 2: ${component}`)}super.add(component)}getPortsFromFootprint(opts){let{footprint}=this.props;if((!footprint||(0,import_react2.isValidElement)(footprint))&&(footprint=this.children.find(c3=>c3.componentName==="Footprint")),typeof footprint=="string"){if(isHttpUrl(footprint))return[];if(isStaticAssetPath(footprint))return[];if(parseLibraryFootprintRef(footprint))return[];let fpSoup=fp.string(footprint).soup(),newPorts2=[];for(let elm of fpSoup)if("port_hints"in elm&&elm.port_hints){let newPort=getPortFromHints(elm.port_hints,opts);if(!newPort)continue;newPort.originDescription=`footprint:string:${footprint}:port_hints[0]:${elm.port_hints[0]}`,newPorts2.push(newPort)}return newPorts2}if(!(0,import_react2.isValidElement)(footprint)&&footprint&&footprint.componentName==="Footprint"){let fp22=footprint,pinNumber=1,newPorts2=[];for(let fpChild of fp22.children){if(!fpChild.props.portHints)continue;let portHintsList=fpChild.props.portHints;portHintsList.some(hint=>hint.startsWith("pin"))||(portHintsList=[...portHintsList,`pin${pinNumber}`]),pinNumber++;let newPort=getPortFromHints(portHintsList);newPort&&(newPort.originDescription=`footprint:${footprint}`,newPorts2.push(newPort))}return newPorts2}let newPorts=[];if(!footprint){for(let child of this.children)if(child.props.portHints&&child.isPcbPrimitive){let port=getPortFromHints(child.props.portHints);port&&newPorts.push(port)}}return newPorts}getPortsFromSchematicSymbol(){if(this.root?.schematicDisabled)return[];let{config}=this;if(!config.schematicSymbolName)return[];let symbol=ef[config.schematicSymbolName];if(!symbol)return[];let newPorts=[];for(let symbolPort of symbol.ports){let port=getPortFromHints(symbolPort.labels);port&&(port.schematicSymbolPortDef=symbolPort,newPorts.push(port))}return newPorts}doInitialCreateNetsFromProps(){this._createNetsFromProps(this._getNetsFromConnectionsProp())}_getNetsFromConnectionsProp(){let{_parsedProps:props}=this,propsWithConnections=[];if(props.connections)for(let[pinName,target]of Object.entries(props.connections)){let targets=Array.isArray(target)?target:[target];for(let targetPath of targets)propsWithConnections.push(String(targetPath))}return propsWithConnections}_createNetsFromProps(propsWithConnections){createNetsFromProps(this,propsWithConnections)}_getPcbCircuitJsonBounds(){let{db}=this.root;if(!this.pcb_component_id)return super._getPcbCircuitJsonBounds();let pcb_component2=db.pcb_component.get(this.pcb_component_id);return{center:{x:pcb_component2.center.x,y:pcb_component2.center.y},bounds:{left:pcb_component2.center.x-pcb_component2.width/2,top:pcb_component2.center.y-pcb_component2.height/2,right:pcb_component2.center.x+pcb_component2.width/2,bottom:pcb_component2.center.y+pcb_component2.height/2},width:pcb_component2.width,height:pcb_component2.height}}_getPinCountFromSchematicPortArrangement(){let schPortArrangement=this._getSchematicPortArrangement();if(!schPortArrangement)return 0;if(!isExplicitPinMappingArrangement(schPortArrangement))return(schPortArrangement.leftSize??schPortArrangement.leftPinCount??0)+(schPortArrangement.rightSize??schPortArrangement.rightPinCount??0)+(schPortArrangement.topSize??schPortArrangement.topPinCount??0)+(schPortArrangement.bottomSize??schPortArrangement.bottomPinCount??0);let{leftSide,rightSide,topSide,bottomSide}=schPortArrangement;return Math.max(...leftSide?.pins??[],...rightSide?.pins??[],...topSide?.pins??[],...bottomSide?.pins??[])}_getPinCount(){if(this._getSchematicPortArrangement())return this._getPinCountFromSchematicPortArrangement();let portsFromFootprint=this.getPortsFromFootprint();if(portsFromFootprint.length>0)return portsFromFootprint.length;let{pinLabels}=this._parsedProps;if(pinLabels){if(Array.isArray(pinLabels))return pinLabels.length;let pinNumbers=Object.keys(pinLabels).map(k4=>k4.startsWith("pin")?parseInt(k4.slice(3)):parseInt(k4)).filter(n3=>!Number.isNaN(n3));return pinNumbers.length>0?Math.max(...pinNumbers):Object.keys(pinLabels).length}return 0}_getSchematicPortArrangement(){return this._parsedProps.schPinArrangement??this._parsedProps.schPortArrangement}_getPinLabelsFromPorts(){let ports=this.selectAll("port"),pinLabels={};for(let port of ports){let pinNumber=port.props.pinNumber;if(pinNumber!==void 0){let bestLabel=port._getBestDisplayPinLabel();bestLabel&&(pinLabels[`pin${pinNumber}`]=bestLabel)}}return pinLabels}_getSchematicBoxDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;let{_parsedProps:props}=this,pinCount=this._getPinCount(),pinSpacing=props.schPinSpacing??.2,allPinLabels={...this._getPinLabelsFromPorts(),...props.pinLabels};return getAllDimensionsForSchematicBox({schWidth:props.schWidth,schHeight:props.schHeight,schPinSpacing:pinSpacing,numericSchPinStyle:getNumericSchPinStyle(props.schPinStyle,allPinLabels),pinCount,schPortArrangement:this._getSchematicPortArrangement(),pinLabels:allPinLabels})}getFootprinterString(){return typeof this._parsedProps.footprint=="string"?this._parsedProps.footprint:null}doInitialCadModelRender(){if(this._isCadModelChild||this.props.doNotPlace)return;let{db}=this.root,{boardThickness=0}=this.root?._getBoard()??{},cadModelProp2=this._parsedProps.cadModel,cadModel=cadModelProp2===void 0?this._asyncFootprintCadModel:cadModelProp2,footprint=this.getFootprinterString()??this._getImpliedFootprintString();if(!this.pcb_component_id||!cadModel&&!footprint||cadModel===null)return;let bounds=this._getPcbCircuitJsonBounds();if(typeof cadModel=="string")throw new Error("String cadModel not yet implemented");let rotationOffset=rotation32.parse({x:0,y:0,z:typeof cadModel?.rotationOffset=="number"?cadModel.rotationOffset:0,...typeof cadModel?.rotationOffset=="object"?cadModel.rotationOffset??{}:{}}),positionOffset=point3.parse({x:0,y:0,z:0,...typeof cadModel?.positionOffset=="object"?cadModel.positionOffset:{}}),zOffsetFromSurface=cadModel&&typeof cadModel=="object"&&"zOffsetFromSurface"in cadModel&&cadModel.zOffsetFromSurface!==void 0?distance.parse(cadModel.zOffsetFromSurface):0,computedLayer=this.props.layer==="bottom"?"bottom":"top",globalTransform=this._computePcbGlobalTransformBeforeLayout(),totalRotation=decomposeTSR(globalTransform).rotation.angle*180/Math.PI,isBottomLayer=computedLayer==="bottom",rotationWithOffset=totalRotation+(rotationOffset.z??0),cadRotationZ=normalizeDegrees(rotationWithOffset),cad_model=db.cad_component.insert({position:{x:bounds.center.x+positionOffset.x,y:bounds.center.y+positionOffset.y,z:(computedLayer==="bottom"?-boardThickness/2:boardThickness/2)+(computedLayer==="bottom"?-zOffsetFromSurface:zOffsetFromSurface)+positionOffset.z},rotation:{x:rotationOffset.x,y:rotationOffset.y+(isBottomLayer?180:0),z:normalizeDegrees(isBottomLayer?-cadRotationZ:cadRotationZ)},pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,model_stl_url:"stlUrl"in(cadModel??{})?this._addCachebustToModelUrl(cadModel.stlUrl):void 0,model_obj_url:"objUrl"in(cadModel??{})?this._addCachebustToModelUrl(cadModel.objUrl):void 0,model_mtl_url:"mtlUrl"in(cadModel??{})?this._addCachebustToModelUrl(cadModel.mtlUrl):void 0,model_gltf_url:"gltfUrl"in(cadModel??{})?this._addCachebustToModelUrl(cadModel.gltfUrl):void 0,model_glb_url:"glbUrl"in(cadModel??{})?this._addCachebustToModelUrl(cadModel.glbUrl):void 0,model_step_url:"stepUrl"in(cadModel??{})?this._addCachebustToModelUrl(cadModel.stepUrl):void 0,model_wrl_url:"wrlUrl"in(cadModel??{})?this._addCachebustToModelUrl(cadModel.wrlUrl):void 0,model_jscad:"jscad"in(cadModel??{})?cadModel.jscad:void 0,model_unit_to_mm_scale_factor:typeof cadModel?.modelUnitToMmScale=="number"?cadModel.modelUnitToMmScale:void 0,footprinter_string:typeof footprint=="string"&&!cadModel?footprint:void 0,show_as_translucent_model:this._parsedProps.showAsTranslucentModel});this.cad_component_id=cad_model.cad_component_id}_addCachebustToModelUrl(url){if(!url||!url.includes("modelcdn.tscircuit.com"))return url;let origin=this.root?.getClientOrigin()??"";return`${url}${url.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(origin)}`}_getPartsEngineCacheKey(source_component,footprinterString){return JSON.stringify({ftype:source_component.ftype,name:source_component.name,manufacturer_part_number:source_component.manufacturer_part_number,footprinterString})}async _getSupplierPartNumbers(partsEngine2,source_component,footprinterString){if(this.props.doNotPlace)return{};let cacheEngine=this.root?.platform?.localCacheEngine,cacheKey=this._getPartsEngineCacheKey(source_component,footprinterString);if(cacheEngine){let cached=await cacheEngine.getItem(cacheKey);if(cached)try{return JSON.parse(cached)}catch{}}let result=await Promise.resolve(partsEngine2.findPart({sourceComponent:source_component,footprinterString}));if(typeof result=="string"){if(result.includes("<!DOCTYPE")||result.includes("<html"))throw new Error(`Failed to fetch supplier part numbers: Received HTML response instead of JSON. Response starts with: ${result.substring(0,100)}`);if(result==="Not found")return{};throw new Error(`Invalid supplier part numbers format: Expected object but got string: "${result}"`)}if(!result||Array.isArray(result)||typeof result!="object"){let actualType=result===null?"null":Array.isArray(result)?"array":typeof result;throw new Error(`Invalid supplier part numbers format: Expected object but got ${actualType}`)}let supplierPartNumbers=result;if(cacheEngine)try{await cacheEngine.setItem(cacheKey,JSON.stringify(supplierPartNumbers))}catch{}return supplierPartNumbers}doInitialPartsEngineRender(){if(this.props.doNotPlace)return;let partsEngine2=this.getInheritedProperty("partsEngine");if(!partsEngine2)return;let{db}=this.root,source_component=db.source_component.get(this.source_component_id);if(!source_component||source_component.supplier_part_numbers)return;let footprinterString;this.props.footprint&&typeof this.props.footprint=="string"&&(footprinterString=this.props.footprint);let supplierPartNumbersMaybePromise=this._getSupplierPartNumbers(partsEngine2,source_component,footprinterString);if(!(supplierPartNumbersMaybePromise instanceof Promise)){db.source_component.update(this.source_component_id,{supplier_part_numbers:supplierPartNumbersMaybePromise});return}this._queueAsyncEffect("get-supplier-part-numbers",async()=>{await supplierPartNumbersMaybePromise.then(supplierPartNumbers=>{this._asyncSupplierPartNumbers=supplierPartNumbers,this._markDirty("PartsEngineRender")}).catch(error=>{this._asyncSupplierPartNumbers={};let errorObj=unknown_error_finding_part.parse({type:"unknown_error_finding_part",message:`Failed to fetch supplier part numbers for ${this.getString()}: ${error.message}`,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id});db.unknown_error_finding_part.insert(errorObj),this._markDirty("PartsEngineRender")})})}updatePartsEngineRender(){if(this.props.doNotPlace)return;let{db}=this.root,source_component=db.source_component.get(this.source_component_id);if(source_component&&!source_component.supplier_part_numbers&&this._asyncSupplierPartNumbers){db.source_component.update(this.source_component_id,{supplier_part_numbers:this._asyncSupplierPartNumbers});return}}doInitialAssignFallbackProps(){let{_parsedProps:props}=this;props.connections&&!this.name&&(this.fallbackUnassignedName=this.getSubcircuit().getNextAvailableName(this))}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}_createTracesFromConnectionsProp(){let{_parsedProps:props}=this;if(props.connections)for(let[pinName,target]of Object.entries(props.connections)){let targets=Array.isArray(target)?target:[target];for(let targetPath of targets)this.add(new Trace3({from:`.${this.name} > .${pinName}`,to:String(targetPath)}))}}doInitialSourceDesignRuleChecks(){NormalComponent_doInitialSourceDesignRuleChecks(this)}doInitialPcbLayout(){if(this.root?.pcbDisabled||!this.pcb_component_id)return;let{db}=this.root,props=this._parsedProps;if(!(props.pcbX!==void 0||props.pcbY!==void 0))return;let sourceComponent=db.source_component.get(this.source_component_id),positionedRelativeToGroupId=sourceComponent?.source_group_id?db.pcb_group.getWhere({source_group_id:sourceComponent.source_group_id})?.pcb_group_id:void 0,positionedRelativeToBoardId=positionedRelativeToGroupId?void 0:this._getBoard()?.pcb_board_id??void 0;db.pcb_component.update(this.pcb_component_id,{position_mode:"relative_to_group_anchor",positioned_relative_to_pcb_group_id:positionedRelativeToGroupId,positioned_relative_to_pcb_board_id:positionedRelativeToBoardId,display_offset_x:props.pcbX,display_offset_y:props.pcbY})}_getMinimumFlexContainerSize(){return NormalComponent__getMinimumFlexContainerSize(this)}_repositionOnPcb(position2){return NormalComponent__repositionOnPcb(this,position2)}doInitialSilkscreenOverlapAdjustment(){return NormalComponent_doInitialSilkscreenOverlapAdjustment(this)}isRelativelyPositioned(){return this._parsedProps.pcbX!==void 0||this._parsedProps.pcbY!==void 0}},getBoardCenterFromAnchor=({boardAnchorPosition,boardAnchorAlignment,width,height})=>{let{x:ax2,y:ay2}=boardAnchorPosition,cx2=ax2,cy2=ay2;switch(boardAnchorAlignment){case"top_left":cx2=ax2+width/2,cy2=ay2-height/2;break;case"top_right":cx2=ax2-width/2,cy2=ay2-height/2;break;case"bottom_left":cx2=ax2+width/2,cy2=ay2+height/2;break;case"bottom_right":cx2=ax2-width/2,cy2=ay2+height/2;break;case"top":cx2=ax2,cy2=ay2-height/2;break;case"bottom":cx2=ax2,cy2=ay2+height/2;break;case"left":cx2=ax2+width/2,cy2=ay2;break;case"right":cx2=ax2-width/2,cy2=ay2;break;default:break}return{x:cx2,y:cy2}},SOLVERS={PackSolver2,AutoroutingPipelineSolver:pi2,AssignableViaAutoroutingPipelineSolver:wi2,CopperPourPipelineSolver},CapacityMeshAutorouter=class{constructor(input2,options={}){__publicField(this,"input");__publicField(this,"isRouting",!1);__publicField(this,"solver");__publicField(this,"eventHandlers",{complete:[],error:[],progress:[]});__publicField(this,"cycleCount",0);__publicField(this,"stepDelay");__publicField(this,"timeoutId");this.input=input2;let{capacityDepth,targetMinCapacity,stepDelay=0,useAssignableViaSolver=!1,onSolverStarted}=options,{AutoroutingPipelineSolver:AutoroutingPipelineSolver2,AssignableViaAutoroutingPipelineSolver:AssignableViaAutoroutingPipelineSolver2}=dist_exports3,solverName=useAssignableViaSolver?"AssignableViaAutoroutingPipelineSolver":"AutoroutingPipelineSolver",SolverClass=SOLVERS[solverName];this.solver=new SolverClass(input2,{capacityDepth,targetMinCapacity,cacheProvider:null}),onSolverStarted?.({solverName,solverParams:{input:input2,options:{capacityDepth,targetMinCapacity,cacheProvider:null}}}),this.stepDelay=stepDelay}start(){this.isRouting||(this.isRouting=!0,this.cycleCount=0,this.runCycleAndQueueNextCycle())}runCycleAndQueueNextCycle(){if(this.isRouting)try{if(this.solver.solved||this.solver.failed){this.solver.failed?this.emitEvent({type:"error",error:new AutorouterError(this.solver.error||"Routing failed")}):this.emitEvent({type:"complete",traces:this.solver.getOutputSimpleRouteJson().traces||[]}),this.isRouting=!1;return}let startTime=Date.now(),startIterations=this.solver.iterations;for(;Date.now()-startTime<250&&!this.solver.failed&&!this.solver.solved;)this.solver.step();let iterationsPerSecond=(this.solver.iterations-startIterations)/(Date.now()-startTime)*1e3;this.cycleCount++;let debugGraphics=this.solver?.preview()||void 0,progress=this.solver.progress;this.emitEvent({type:"progress",steps:this.cycleCount,iterationsPerSecond,progress,phase:this.solver.getCurrentPhase(),debugGraphics}),this.stepDelay>0?this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),this.stepDelay):this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),0)}catch(error){this.emitEvent({type:"error",error:error instanceof Error?new AutorouterError(error.message):new AutorouterError(String(error))}),this.isRouting=!1}}stop(){this.isRouting&&(this.isRouting=!1,this.timeoutId!==void 0&&(clearTimeout(this.timeoutId),this.timeoutId=void 0))}on(event,callback){event==="complete"?this.eventHandlers.complete.push(callback):event==="error"?this.eventHandlers.error.push(callback):event==="progress"&&this.eventHandlers.progress.push(callback)}emitEvent(event){if(event.type==="complete")for(let handler of this.eventHandlers.complete)handler(event);else if(event.type==="error")for(let handler of this.eventHandlers.error)handler(event);else if(event.type==="progress")for(let handler of this.eventHandlers.progress)handler(event)}solveSync(){if(this.solver.solve(),this.solver.failed)throw new AutorouterError(this.solver.error||"Routing failed");return this.solver.getOutputSimpleRouteJson().traces||[]}},TraceHint=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"matchedPort",null)}get config(){return{componentName:"TraceHint",zodProps:traceHintProps}}doInitialPortMatching(){let{db}=this.root,{_parsedProps:props,parent}=this;if(!parent)return;if(parent.componentName==="Trace"){this.renderError(`Port inference inside trace is not yet supported (${this})`);return}if(!parent)throw new Error("TraceHint has no parent");if(!props.for){this.renderError(`TraceHint has no for property (${this})`);return}let port=parent.selectOne(props.for,{type:"port"});port||this.renderError(`${this} could not find port for selector "${props.for}"`),this.matchedPort=port,port.registerMatch(this)}getPcbRouteHints(){let{_parsedProps:props}=this,offsets=props.offset?[props.offset]:props.offsets;if(!offsets)return[];let globalTransform=this._computePcbGlobalTransformBeforeLayout();return offsets.map(offset=>({...applyToPoint(globalTransform,offset),via:offset.via,to_layer:offset.to_layer,trace_width:offset.trace_width}))}doInitialPcbTraceHintRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this;db.pcb_trace_hint.insert({pcb_component_id:this.matchedPort?.pcb_component_id,pcb_port_id:this.matchedPort?.pcb_port_id,route:this.getPcbRouteHints()})}},applyPcbEditEventsToManualEditsFile=({circuitJson,editEvents,manualEditsFile})=>{let updatedManualEditsFile={...manualEditsFile,pcb_placements:[...manualEditsFile.pcb_placements??[]]};for(let editEvent of editEvents)if(editEvent.edit_event_type==="edit_pcb_component_location"){let{pcb_component_id,new_center}=editEvent,pcb_component2=su2(circuitJson).pcb_component.get(pcb_component_id);if(!pcb_component2)continue;let source_component=su2(circuitJson).source_component.get(pcb_component2.source_component_id);if(!source_component)continue;let existingPlacementIndex=updatedManualEditsFile.pcb_placements?.findIndex(p4=>p4.selector===source_component.name),newPlacement={selector:source_component.name,center:new_center,relative_to:"group_center"};existingPlacementIndex>=0?updatedManualEditsFile.pcb_placements[existingPlacementIndex]=newPlacement:updatedManualEditsFile.pcb_placements.push(newPlacement)}return updatedManualEditsFile},applySchematicEditEventsToManualEditsFile=({circuitJson,editEvents,manualEditsFile})=>{let updatedManualEditsFile={...manualEditsFile,schematic_placements:[...manualEditsFile.schematic_placements??[]]};for(let editEvent of editEvents)if(editEvent.edit_event_type==="edit_schematic_component_location"){let{schematic_component_id,new_center}=editEvent,schematic_component2=su2(circuitJson).schematic_component.get(schematic_component_id);if(!schematic_component2||!schematic_component2.source_component_id)continue;let source_component=su2(circuitJson).source_component.get(schematic_component2.source_component_id);if(!source_component)continue;let existingPlacementIndex=updatedManualEditsFile.schematic_placements?.findIndex(p4=>p4.selector===source_component.name),newPlacement={selector:source_component.name,center:new_center,relative_to:"group_center"};existingPlacementIndex>=0?updatedManualEditsFile.schematic_placements[existingPlacementIndex]=newPlacement:updatedManualEditsFile.schematic_placements.push(newPlacement)}return updatedManualEditsFile},applyEditEventsToManualEditsFile=({circuitJson,editEvents,manualEditsFile})=>{let schematicEditEvents=editEvents.filter(event=>event.edit_event_type==="edit_schematic_component_location"),pcbEditEvents=editEvents.filter(event=>event.edit_event_type==="edit_pcb_component_location"),updatedManualEditsFile=manualEditsFile;return schematicEditEvents.length>0&&(updatedManualEditsFile=applySchematicEditEventsToManualEditsFile({circuitJson,editEvents:schematicEditEvents,manualEditsFile:updatedManualEditsFile})),pcbEditEvents.length>0&&(updatedManualEditsFile=applyPcbEditEventsToManualEditsFile({circuitJson,editEvents:pcbEditEvents,manualEditsFile:updatedManualEditsFile})),updatedManualEditsFile},applyTraceHintEditEvent=(circuitJson,edit_event)=>{if(su2(circuitJson).pcb_trace_hint.get(edit_event.pcb_trace_hint_id))circuitJson=circuitJson.map(e4=>e4.pcb_trace_hint_id===edit_event.pcb_trace_hint_id?{...e4,route:edit_event.route}:e4);else{let pcbPort=su2(circuitJson).pcb_port.get(edit_event.pcb_port_id);circuitJson=circuitJson.filter(e4=>!(e4.type==="pcb_trace_hint"&&e4.pcb_port_id===edit_event.pcb_port_id)).concat([{type:"pcb_trace_hint",pcb_trace_hint_id:edit_event.pcb_trace_hint_id,route:edit_event.route,pcb_port_id:edit_event.pcb_port_id,pcb_component_id:pcbPort?.pcb_component_id}])}return circuitJson},applyEditEvents=({circuitJson,editEvents})=>{circuitJson=JSON.parse(JSON.stringify(circuitJson));for(let editEvent of editEvents)if(editEvent.edit_event_type==="edit_pcb_component_location"){let component=circuitJson.find(e4=>e4.type==="pcb_component"&&e4.pcb_component_id===editEvent.pcb_component_id);if((!component||component.center.x!==editEvent.new_center.x||component.center.y!==editEvent.new_center.y)&&editEvent.original_center){let mat=translate(editEvent.new_center.x-editEvent.original_center.x,editEvent.new_center.y-editEvent.original_center.y);circuitJson=circuitJson.map(e4=>e4.pcb_component_id!==editEvent.pcb_component_id?e4:transformPCBElement(e4,mat))}}else editEvent.edit_event_type==="edit_schematic_component_location"?circuitJson=circuitJson.map(e4=>e4.type==="schematic_component"&&e4.schematic_component_id===editEvent.schematic_component_id?{...e4,center:editEvent.new_center}:e4):editEvent.edit_event_type==="edit_pcb_trace_hint"&&(circuitJson=applyTraceHintEditEvent(circuitJson,editEvent));return circuitJson},getDescendantSubcircuitIds=(db,root_subcircuit_id)=>{let groups=db.source_group.list(),result=[],findDescendants=parentId=>{let children=groups.filter(group=>group.parent_subcircuit_id===parentId);for(let child of children)child.subcircuit_id&&(result.push(child.subcircuit_id),findDescendants(child.subcircuit_id))};return findDescendants(root_subcircuit_id),result},getSimpleRouteJsonFromCircuitJson=({db,circuitJson,subcircuit_id,minTraceWidth=.1})=>{if(!db&&circuitJson&&(db=su2(circuitJson)),!db)throw new Error("db or circuitJson is required");let traceHints=db.pcb_trace_hint.list(),relevantSubcircuitIds=subcircuit_id?new Set([subcircuit_id]):null;if(subcircuit_id){let descendantSubcircuitIds=getDescendantSubcircuitIds(db,subcircuit_id);for(let id of descendantSubcircuitIds)relevantSubcircuitIds.add(id)}let subcircuitElements=(circuitJson??db.toArray()).filter(e4=>!subcircuit_id||"subcircuit_id"in e4&&relevantSubcircuitIds.has(e4.subcircuit_id)),board=null;if(subcircuit_id){let source_group_id=subcircuit_id.replace(/^subcircuit_/,""),source_board2=db.source_board.getWhere({source_group_id});source_board2&&(board=db.pcb_board.getWhere({source_board_id:source_board2.source_board_id}))}board||(board=db.pcb_board.list()[0]),db=su2(subcircuitElements);let connMap=getFullConnectivityMapFromCircuitJson(subcircuitElements),obstacles=getObstaclesFromCircuitJson2([...db.pcb_component.list(),...db.pcb_smtpad.list(),...db.pcb_plated_hole.list(),...db.pcb_hole.list(),...db.pcb_via.list(),...db.pcb_cutout.list()].filter(e4=>!subcircuit_id||relevantSubcircuitIds?.has(e4.subcircuit_id)),connMap);for(let obstacle of obstacles){let additionalIds=obstacle.connectedTo.flatMap(id=>connMap.getIdsConnectedToNet(id));obstacle.connectedTo.push(...additionalIds)}let internalConnections=db.source_component_internal_connection.list(),sourcePortIdToInternalConnectionId=new Map;for(let ic2 of internalConnections)for(let sourcePortId of ic2.source_port_ids)sourcePortIdToInternalConnectionId.set(sourcePortId,ic2.source_component_internal_connection_id);let pcbElementIdToSourcePortId=new Map;for(let pcbPort of db.pcb_port.list())if(pcbPort.source_port_id){let smtpad2=db.pcb_smtpad.getWhere({pcb_port_id:pcbPort.pcb_port_id});smtpad2&&pcbElementIdToSourcePortId.set(smtpad2.pcb_smtpad_id,pcbPort.source_port_id);let platedHole=db.pcb_plated_hole.getWhere({pcb_port_id:pcbPort.pcb_port_id});platedHole&&pcbElementIdToSourcePortId.set(platedHole.pcb_plated_hole_id,pcbPort.source_port_id)}for(let obstacle of obstacles)for(let connectedId of obstacle.connectedTo){let sourcePortId=pcbElementIdToSourcePortId.get(connectedId);if(sourcePortId){let internalConnectionId=sourcePortIdToInternalConnectionId.get(sourcePortId);if(internalConnectionId){obstacle.offBoardConnectsTo=[internalConnectionId],obstacle.netIsAssignable=!0;break}}}let allPoints=obstacles.flatMap(o3=>[{x:o3.center.x-o3.width/2,y:o3.center.y-o3.height/2},{x:o3.center.x+o3.width/2,y:o3.center.y+o3.height/2}]).concat(board?.outline??[]),bounds;if(board&&!board.outline?bounds={minX:board.center.x-board.width/2,maxX:board.center.x+board.width/2,minY:board.center.y-board.height/2,maxY:board.center.y+board.height/2}:bounds={minX:Math.min(...allPoints.map(p4=>p4.x))-1,maxX:Math.max(...allPoints.map(p4=>p4.x))+1,minY:Math.min(...allPoints.map(p4=>p4.y))-1,maxY:Math.max(...allPoints.map(p4=>p4.y))+1},subcircuit_id){let group=db.pcb_group.getWhere({subcircuit_id});if(group?.width&&group.height){let groupBounds={minX:group.center.x-group.width/2,maxX:group.center.x+group.width/2,minY:group.center.y-group.height/2,maxY:group.center.y+group.height/2};bounds={minX:Math.min(bounds.minX,groupBounds.minX),maxX:Math.max(bounds.maxX,groupBounds.maxX),minY:Math.min(bounds.minY,groupBounds.minY),maxY:Math.max(bounds.maxY,groupBounds.maxY)}}}let routedTraceIds=new Set(db.pcb_trace.list().map(t6=>t6.source_trace_id).filter(id=>!!id)),directTraceConnections=db.source_trace.list().filter(trace=>!routedTraceIds.has(trace.source_trace_id)).map(trace=>{let connectedPorts=trace.connected_source_port_ids.map(id=>{let source_port2=db.source_port.get(id),pcb_port2=db.pcb_port.getWhere({source_port_id:id});return{...source_port2,...pcb_port2}});if(connectedPorts.length<2)return null;let[portA,portB]=connectedPorts;if(portA.x===void 0||portA.y===void 0)return console.error(`(source_port_id: ${portA.source_port_id}) for trace ${trace.source_trace_id} does not have x/y coordinates. Skipping this trace.`),null;if(portB.x===void 0||portB.y===void 0)return console.error(`(source_port_id: ${portB.source_port_id}) for trace ${trace.source_trace_id} does not have x/y coordinates. Skipping this trace.`),null;let layerA=portA.layers?.[0]??"top",layerB=portB.layers?.[0]??"top",matchingHints=traceHints.filter(hint=>hint.pcb_port_id===portA.pcb_port_id||hint.pcb_port_id===portB.pcb_port_id),hintPoints=[];for(let hint of matchingHints){let layer=db.pcb_port.get(hint.pcb_port_id)?.layers?.[0]??"top";for(let pt3 of hint.route)hintPoints.push({x:pt3.x,y:pt3.y,layer})}return{name:trace.source_trace_id??connMap.getNetConnectedToId(trace.source_trace_id)??"",source_trace_id:trace.source_trace_id,width:trace.min_trace_thickness,pointsToConnect:[{x:portA.x,y:portA.y,layer:layerA,pointId:portA.pcb_port_id,pcb_port_id:portA.pcb_port_id},...hintPoints,{x:portB.x,y:portB.y,layer:layerB,pointId:portB.pcb_port_id,pcb_port_id:portB.pcb_port_id}]}}).filter(c3=>c3!==null),directTraceConnectionsById=new Map(directTraceConnections.map(c3=>[c3.source_trace_id,c3])),source_nets=db.source_net.list().filter(e4=>!subcircuit_id||relevantSubcircuitIds?.has(e4.subcircuit_id)),connectionsFromNets=[];for(let net of source_nets){let connectedSourceTraces=db.source_trace.list().filter(st3=>st3.connected_source_net_ids?.includes(net.source_net_id));connectionsFromNets.push({name:net.source_net_id??connMap.getNetConnectedToId(net.source_net_id),pointsToConnect:connectedSourceTraces.flatMap(st3=>db.pcb_port.list().filter(p4=>st3.connected_source_port_ids.includes(p4.source_port_id)).map(p4=>({x:p4.x,y:p4.y,layer:p4.layers?.[0]??"top",pointId:p4.pcb_port_id,pcb_port_id:p4.pcb_port_id})))})}let breakoutPoints=db.pcb_breakout_point.list().filter(bp2=>!subcircuit_id||relevantSubcircuitIds?.has(bp2.subcircuit_id)),connectionsFromBreakoutPoints=[],breakoutTraceConnectionsById=new Map;for(let bp2 of breakoutPoints){let pt3={x:bp2.x,y:bp2.y,layer:"top"};if(bp2.source_trace_id){let conn=directTraceConnectionsById.get(bp2.source_trace_id)??breakoutTraceConnectionsById.get(bp2.source_trace_id);if(conn)conn.pointsToConnect.push(pt3);else{let newConn={name:bp2.source_trace_id,source_trace_id:bp2.source_trace_id,pointsToConnect:[pt3]};connectionsFromBreakoutPoints.push(newConn),breakoutTraceConnectionsById.set(bp2.source_trace_id,newConn)}}else if(bp2.source_net_id){let conn=connectionsFromNets.find(c3=>c3.name===bp2.source_net_id);conn?conn.pointsToConnect.push(pt3):connectionsFromBreakoutPoints.push({name:bp2.source_net_id,pointsToConnect:[pt3]})}else if(bp2.source_port_id){let pcb_port2=db.pcb_port.getWhere({source_port_id:bp2.source_port_id});pcb_port2&&connectionsFromBreakoutPoints.push({name:bp2.source_port_id,source_trace_id:void 0,pointsToConnect:[{x:pcb_port2.x,y:pcb_port2.y,layer:pcb_port2.layers?.[0]??"top",pointId:pcb_port2.pcb_port_id,pcb_port_id:pcb_port2.pcb_port_id},pt3]})}}let allConns=[...directTraceConnections,...connectionsFromNets,...connectionsFromBreakoutPoints],pointIdToConn=new Map;for(let conn of allConns)for(let pt3 of conn.pointsToConnect)pt3.pointId&&pointIdToConn.set(pt3.pointId,conn);let existingTraces=db.pcb_trace.list().filter(t6=>!subcircuit_id||relevantSubcircuitIds?.has(t6.subcircuit_id));for(let tr2 of existingTraces){let tracePortIds=new Set;for(let seg of tr2.route)seg.start_pcb_port_id&&tracePortIds.add(seg.start_pcb_port_id),seg.end_pcb_port_id&&tracePortIds.add(seg.end_pcb_port_id);if(tracePortIds.size<2)continue;let firstId=tracePortIds.values().next().value;if(!firstId)continue;let conn=pointIdToConn.get(firstId);conn&&[...tracePortIds].every(pid=>pointIdToConn.get(pid)===conn)&&(conn.externallyConnectedPointIds??(conn.externallyConnectedPointIds=[]),conn.externallyConnectedPointIds.push([...tracePortIds]))}return{simpleRouteJson:{bounds,obstacles,connections:allConns,layerCount:board?.num_layers??2,minTraceWidth,outline:board?.outline?.map(point23=>({...point23}))},connMap}},getPhaseTimingsFromRenderEvents=renderEvents=>{let phaseTimings={};if(!renderEvents)return phaseTimings;for(let renderPhase of orderedRenderPhases)phaseTimings[renderPhase]=0;let startEvents=new Map;for(let event of renderEvents){let[,,phase,eventType]=event.type.split(":");if(eventType==="start"){startEvents.set(`${phase}:${event.renderId}`,event);continue}if(eventType==="end"){let startEvent=startEvents.get(`${phase}:${event.renderId}`);if(startEvent){let duration=event.createdAt-startEvent.createdAt;phaseTimings[phase]=(phaseTimings[phase]||0)+duration}}}return phaseTimings},normalizePinLabels=inputPinLabels=>{let unqInputPinLabels=inputPinLabels.map(labels=>[...new Set(labels)]),result=unqInputPinLabels.map(()=>[]),desiredNumbers=unqInputPinLabels.map(()=>null);for(let i3=0;i3<unqInputPinLabels.length;i3++)for(let label of unqInputPinLabels[i3])if(/^\d+$/.test(label)){desiredNumbers[i3]=Number.parseInt(label);break}let highestPinNumber=0,alreadyAcceptedDesiredNumbers=new Set;for(let i3=0;i3<desiredNumbers.length;i3++){let desiredNumber=desiredNumbers[i3];if(desiredNumber===null||desiredNumber<1)continue;if(!alreadyAcceptedDesiredNumbers.has(desiredNumber)){alreadyAcceptedDesiredNumbers.add(desiredNumber),result[i3].push(`pin${desiredNumber}`),highestPinNumber=Math.max(highestPinNumber,desiredNumber);continue}let existingAltsForPin=0;for(let label of result[i3])label.startsWith(`pin${desiredNumber}_alt`)&&existingAltsForPin++;result[i3].push(`pin${desiredNumber}_alt${existingAltsForPin+1}`)}for(let i3=0;i3<result.length;i3++)result[i3][0]?.includes("_alt")&&(highestPinNumber++,result[i3].unshift(`pin${highestPinNumber}`));for(let i3=0;i3<result.length;i3++)result[i3].length===0&&(highestPinNumber++,result[i3].push(`pin${highestPinNumber}`));let totalLabelCounts={};for(let inputLabels of unqInputPinLabels)for(let label of inputLabels)/^\d+$/.test(label)||(totalLabelCounts[label]=(totalLabelCounts[label]??0)+1);let incrementalLabelCounts={};for(let i3=0;i3<unqInputPinLabels.length;i3++){let inputLabels=unqInputPinLabels[i3];for(let label of inputLabels)/^\d+$/.test(label)||(totalLabelCounts[label]===1?result[i3].push(label):(incrementalLabelCounts[label]=(incrementalLabelCounts[label]??0)+1,result[i3].push(`${label}${incrementalLabelCounts[label]}`)))}return result};function updateSchematicPrimitivesForLayoutShift({db,schematicComponentId,deltaX,deltaY}){let rects=db.schematic_rect.list({schematic_component_id:schematicComponentId});for(let rect of rects)rect.center.x+=deltaX,rect.center.y+=deltaY;let lines=db.schematic_line.list({schematic_component_id:schematicComponentId});for(let line2 of lines)line2.x1+=deltaX,line2.y1+=deltaY,line2.x2+=deltaX,line2.y2+=deltaY;let circles=db.schematic_circle.list({schematic_component_id:schematicComponentId});for(let circle2 of circles)circle2.center.x+=deltaX,circle2.center.y+=deltaY;let arcs=db.schematic_arc.list({schematic_component_id:schematicComponentId});for(let arc2 of arcs)arc2.center.x+=deltaX,arc2.center.y+=deltaY}var debug42=(0,import_debug11.default)("Group_doInitialSchematicLayoutMatchAdapt");function Group_doInitialSchematicLayoutMatchAdapt(group){let{db}=group.root,subtreeCircuitJson=buildSubtree(db.toArray(),{source_group_id:group.source_group_id}),bpcGraphBeforeGeneratedNetLabels=convertCircuitJsonToBpc(subtreeCircuitJson);debug42.enabled&&global?.debugGraphics&&global.debugGraphics?.push(getGraphicsForBpcGraph(bpcGraphBeforeGeneratedNetLabels,{title:`floatingBpcGraph-${group.name}`}));let floatingGraph=convertCircuitJsonToBpc(subtreeCircuitJson),floatingGraphNoNotConnected={boxes:floatingGraph.boxes,pins:floatingGraph.pins.map(p4=>({...p4,color:p4.color.replace("not_connected","normal")}))},{result:laidOutBpcGraph}=layoutSchematicGraphVariants([{variantName:"default",floatingGraph},{variantName:"noNotConnected",floatingGraph:floatingGraphNoNotConnected}],{singletonKeys:["vcc/2","gnd/2"],centerPinColors:["netlabel_center","component_center"],floatingBoxIdsWithMutablePinOffsets:new Set(floatingGraph.boxes.filter(box2=>floatingGraph.pins.filter(p4=>p4.boxId===box2.boxId).filter(bp2=>!bp2.color.includes("center")).length<=2).map(b3=>b3.boxId)),corpus:{}});debug42.enabled&&global?.debugGraphics&&global.debugGraphics?.push(getGraphicsForBpcGraph(laidOutBpcGraph,{title:`laidOutBpcGraph-${group.name}`}));let groupOffset=group._getGlobalSchematicPositionBeforeLayout();for(let box2 of laidOutBpcGraph.boxes){if(!box2.center)continue;let schematic_component2=db.schematic_component.get(box2.boxId);if(schematic_component2){let newCenter={x:box2.center.x+groupOffset.x,y:box2.center.y+groupOffset.y},ports=db.schematic_port.list({schematic_component_id:schematic_component2.schematic_component_id}),texts=db.schematic_text.list({schematic_component_id:schematic_component2.schematic_component_id}),positionDelta={x:newCenter.x-schematic_component2.center.x,y:newCenter.y-schematic_component2.center.y};for(let port of ports)port.center.x+=positionDelta.x,port.center.y+=positionDelta.y;for(let text of texts)text.position.x+=positionDelta.x,text.position.y+=positionDelta.y;updateSchematicPrimitivesForLayoutShift({db,schematicComponentId:schematic_component2.schematic_component_id,deltaX:positionDelta.x,deltaY:positionDelta.y}),schematic_component2.center=newCenter;continue}let schematic_net_label2=db.schematic_net_label.get(box2.boxId);if(schematic_net_label2){let pin=laidOutBpcGraph.pins.find(p4=>p4.boxId===box2.boxId&&p4.color==="netlabel_center");if(!pin)throw new Error(`No pin found for net label: ${box2.boxId}`);let finalCenter={x:box2.center.x+groupOffset.x,y:box2.center.y+groupOffset.y};schematic_net_label2.center=finalCenter,schematic_net_label2.anchor_position={x:finalCenter.x+pin.offset.x,y:finalCenter.y+pin.offset.y};continue}console.error(`No schematic element found for box: ${box2.boxId}. This is a bug in the matchAdapt binding with @tscircuit/core`)}}var debug52=(0,import_debug12.default)("Group_doInitialSchematicLayoutMatchpack");function facingDirectionToSide(facingDirection){switch(facingDirection){case"up":return"y+";case"down":return"y-";case"left":return"x-";case"right":return"x+";default:return"y+"}}function rotateDirection2(direction2,degrees){let directions=["right","up","left","down"],currentIndex=directions.indexOf(direction2);if(currentIndex===-1)return direction2;let steps=Math.round(degrees/90),newIndex=(currentIndex+steps)%4;return directions[newIndex<0?newIndex+4:newIndex]}function convertTreeToInputProblem(tree,db,group){let problem={chipMap:{},chipPinMap:{},netMap:{},pinStrongConnMap:{},netConnMap:{},chipGap:.6,decouplingCapsGap:.4,partitionGap:1.2};debug52(`[${group.name}] Processing ${tree.childNodes.length} child nodes for input problem`),tree.childNodes.forEach((child,index)=>{if(debug52(`[${group.name}] Processing child ${index}: nodeType=${child.nodeType}`),child.nodeType==="component"?debug52(`[${group.name}] - Component: ${child.sourceComponent?.name}`):child.nodeType==="group"&&debug52(`[${group.name}] - Group: ${child.sourceGroup?.name}`),child.nodeType==="component"&&child.sourceComponent){let chipId=child.sourceComponent.name||`chip_${index}`,schematicComponent=db.schematic_component.getWhere({source_component_id:child.sourceComponent.source_component_id});if(!schematicComponent)return;let component=group.children.find(groupChild=>groupChild.source_component_id===child.sourceComponent?.source_component_id),availableRotations=[0,90,180,270];component?._parsedProps?.schOrientation&&(availableRotations=[0]),component?._parsedProps?.schRotation!==void 0&&(availableRotations=[0]),component?._parsedProps?.facingDirection&&(availableRotations=[0]),component?._parsedProps?.schFacingDirection&&(availableRotations=[0]),component?.componentName==="Chip"&&(availableRotations=[0]);let marginLeft=component?._parsedProps?.schMarginLeft??component?._parsedProps?.schMarginX??0,marginRight=component?._parsedProps?.schMarginRight??component?._parsedProps?.schMarginX??0,marginTop=component?._parsedProps?.schMarginTop??component?._parsedProps?.schMarginY??0,marginBottom=component?._parsedProps?.schMarginBottom??component?._parsedProps?.schMarginY??0;component?.config.shouldRenderAsSchematicBox&&(marginTop+=.4,marginBottom+=.4);let marginXShift=(marginRight-marginLeft)/2,marginYShift=(marginTop-marginBottom)/2;problem.chipMap[chipId]={chipId,pins:[],size:{x:(schematicComponent.size?.width||1)+marginLeft+marginRight,y:(schematicComponent.size?.height||1)+marginTop+marginBottom},availableRotations};let ports=db.schematic_port.list({schematic_component_id:schematicComponent.schematic_component_id});for(let port of ports){let sourcePort=db.source_port.get(port.source_port_id);if(!sourcePort)continue;let pinId=`${chipId}.${sourcePort.pin_number||sourcePort.name||port.schematic_port_id}`;problem.chipMap[chipId].pins.push(pinId);let side=facingDirectionToSide(port.facing_direction);problem.chipPinMap[pinId]={pinId,offset:{x:(port.center?.x||0)-(schematicComponent.center.x||0)+marginXShift,y:(port.center?.y||0)-(schematicComponent.center.y||0)+marginYShift},side}}}else if(child.nodeType==="group"&&child.sourceGroup){let groupId=child.sourceGroup.name||`group_${index}`;debug52(`[${group.name}] Processing nested group: ${groupId}`);let schematicGroup=db.schematic_group?.getWhere?.({source_group_id:child.sourceGroup.source_group_id}),groupInstance=group.children.find(groupChild=>groupChild.source_group_id===child.sourceGroup?.source_group_id);if(debug52(`[${group.name}] Found schematic_group for ${groupId}:`,schematicGroup),schematicGroup){debug52(`[${group.name}] Treating group ${groupId} as composite chip`);let groupComponents=db.schematic_component.list({schematic_group_id:schematicGroup.schematic_group_id});debug52(`[${group.name}] Group ${groupId} has ${groupComponents.length} components:`,groupComponents.map(c3=>c3.source_component_id));let minX=1/0,maxX=-1/0,minY=1/0,maxY=-1/0,hasValidBounds=!1;for(let comp of groupComponents)if(comp.center&&comp.size){hasValidBounds=!0;let halfWidth=comp.size.width/2,halfHeight=comp.size.height/2;minX=Math.min(minX,comp.center.x-halfWidth),maxX=Math.max(maxX,comp.center.x+halfWidth),minY=Math.min(minY,comp.center.y-halfHeight),maxY=Math.max(maxY,comp.center.y+halfHeight)}let marginLeft=groupInstance?._parsedProps?.schMarginLeft??groupInstance?._parsedProps?.schMarginX??0,marginRight=groupInstance?._parsedProps?.schMarginRight??groupInstance?._parsedProps?.schMarginX??0,marginTop=groupInstance?._parsedProps?.schMarginTop??groupInstance?._parsedProps?.schMarginY??0,marginBottom=groupInstance?._parsedProps?.schMarginBottom??groupInstance?._parsedProps?.schMarginY??0,marginXShift=(marginRight-marginLeft)/2,marginYShift=(marginTop-marginBottom)/2,groupWidth=(hasValidBounds?maxX-minX:2)+marginLeft+marginRight,groupHeight=(hasValidBounds?maxY-minY:2)+marginTop+marginBottom;debug52(`[${group.name}] Group ${groupId} computed size: ${groupWidth} x ${groupHeight}`);let groupPins=[];for(let comp of groupComponents){let ports=db.schematic_port.list({schematic_component_id:comp.schematic_component_id});for(let port of ports){let sourcePort=db.source_port.get(port.source_port_id);if(!sourcePort)continue;let pinId=`${groupId}.${sourcePort.pin_number||sourcePort.name||port.schematic_port_id}`;groupPins.push(pinId);let groupCenter=schematicGroup.center||{x:0,y:0},side=facingDirectionToSide(port.facing_direction);problem.chipPinMap[pinId]={pinId,offset:{x:(port.center?.x||0)-groupCenter.x+marginXShift,y:(port.center?.y||0)-groupCenter.y+marginYShift},side}}}debug52(`[${group.name}] Group ${groupId} has ${groupPins.length} pins:`,groupPins),problem.chipMap[groupId]={chipId:groupId,pins:groupPins,size:{x:groupWidth,y:groupHeight}},debug52(`[${group.name}] Added group ${groupId} to chipMap`)}else debug52(`[${group.name}] Warning: No schematic_group found for group ${groupId}`)}}),debug52(`[${group.name}] Creating connections using connectivity keys`);let connectivityGroups=new Map;for(let[chipId,chip]of Object.entries(problem.chipMap))for(let pinId of chip.pins){let pinNumber=pinId.split(".").pop(),treeNode=tree.childNodes.find(child=>child.nodeType==="component"&&child.sourceComponent?child.sourceComponent.name===chipId:child.nodeType==="group"&&child.sourceGroup?`group_${tree.childNodes.indexOf(child)}`===chipId:!1);if(treeNode?.nodeType==="group"&&treeNode.sourceGroup){let schematicGroup=db.schematic_group?.getWhere?.({source_group_id:treeNode.sourceGroup.source_group_id});if(schematicGroup){let groupComponents=db.schematic_component.list({schematic_group_id:schematicGroup.schematic_group_id});for(let comp of groupComponents){let sourcePorts=db.source_port.list({source_component_id:comp.source_component_id});for(let sourcePort of sourcePorts){let portNumber=sourcePort.pin_number||sourcePort.name;if(String(portNumber)===String(pinNumber))if(sourcePort.subcircuit_connectivity_map_key){let connectivityKey=sourcePort.subcircuit_connectivity_map_key;connectivityGroups.has(connectivityKey)||connectivityGroups.set(connectivityKey,[]),connectivityGroups.get(connectivityKey).push(pinId),debug52(`[${group.name}] \u2713 Pin ${pinId} has connectivity key: ${connectivityKey}`)}else debug52(`[${group.name}] Pin ${pinId} has no connectivity key`)}}}}else if(treeNode?.nodeType==="component"&&treeNode.sourceComponent){let sourcePorts=db.source_port.list({source_component_id:treeNode.sourceComponent.source_component_id});for(let sourcePort of sourcePorts){let portNumber=sourcePort.pin_number||sourcePort.name;if(String(portNumber)===String(pinNumber)&&sourcePort.subcircuit_connectivity_map_key){let connectivityKey=sourcePort.subcircuit_connectivity_map_key;connectivityGroups.has(connectivityKey)||connectivityGroups.set(connectivityKey,[]),connectivityGroups.get(connectivityKey).push(pinId),debug52(`[${group.name}] Pin ${pinId} has connectivity key: ${connectivityKey}`)}}}}debug52(`[${group.name}] Found ${connectivityGroups.size} connectivity groups:`,Array.from(connectivityGroups.entries()).map(([key,pins])=>({key,pins})));for(let[connectivityKey,pins]of connectivityGroups)if(pins.length>=2){let tracesWithThisKey=db.source_trace.list().filter(trace=>trace.subcircuit_connectivity_map_key===connectivityKey),hasNetConnections=tracesWithThisKey.some(trace=>trace.connected_source_net_ids&&trace.connected_source_net_ids.length>0),hasDirectConnections=tracesWithThisKey.some(trace=>trace.connected_source_port_ids&&trace.connected_source_port_ids.length>=2);if(debug52(`[${group.name}] Connectivity ${connectivityKey}: hasNetConnections=${hasNetConnections}, hasDirectConnections=${hasDirectConnections}`),hasDirectConnections){for(let trace of tracesWithThisKey)if(trace.connected_source_port_ids&&trace.connected_source_port_ids.length>=2){let directlyConnectedPins=[];for(let portId of trace.connected_source_port_ids)for(let pinId of pins){let pinNumber=pinId.split(".").pop(),sourcePort=db.source_port.get(portId);if(sourcePort&&String(sourcePort.pin_number||sourcePort.name)===String(pinNumber)){let chipId=pinId.split(".")[0],treeNode=tree.childNodes.find(child=>child.nodeType==="component"&&child.sourceComponent?child.sourceComponent.name===chipId:child.nodeType==="group"&&child.sourceGroup?`group_${tree.childNodes.indexOf(child)}`===chipId:!1);treeNode?.nodeType==="component"&&treeNode.sourceComponent&&db.source_port.list({source_component_id:treeNode.sourceComponent.source_component_id}).some(p4=>p4.source_port_id===portId)&&directlyConnectedPins.push(pinId)}}for(let i3=0;i3<directlyConnectedPins.length;i3++)for(let j3=i3+1;j3<directlyConnectedPins.length;j3++){let pin1=directlyConnectedPins[i3],pin2=directlyConnectedPins[j3];problem.pinStrongConnMap[`${pin1}-${pin2}`]=!0,problem.pinStrongConnMap[`${pin2}-${pin1}`]=!0,debug52(`[${group.name}] Created strong connection: ${pin1} <-> ${pin2}`)}}}if(hasNetConnections){let source_net2=db.source_net.getWhere({subcircuit_connectivity_map_key:connectivityKey}),isGround=source_net2?.is_ground??!1,isPositiveVoltageSource=source_net2?.is_power??!1;problem.netMap[connectivityKey]={netId:connectivityKey,isGround,isPositiveVoltageSource};for(let pinId of pins)problem.netConnMap[`${pinId}-${connectivityKey}`]=!0;debug52(`[${group.name}] Created net ${connectivityKey} with ${pins.length} pins:`,pins)}}return problem}function Group_doInitialSchematicLayoutMatchPack(group){let{db}=group.root,tree=getCircuitJsonTree(db.toArray(),{source_group_id:group.source_group_id});if(debug52(`[${group.name}] Starting matchpack layout with ${tree.childNodes.length} children`),debug52(`[${group.name}] Tree structure:`,JSON.stringify(tree,null,2)),tree.childNodes.length<=1){debug52(`[${group.name}] Only ${tree.childNodes.length} children, skipping layout`);return}debug52("Converting circuit tree to InputProblem...");let inputProblem=convertTreeToInputProblem(tree,db,group);debug52.enabled&&group.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`matchpack-input-problem-${group.name}`,content:JSON.stringify(inputProblem,null,2)});let solver=new LayoutPipelineSolver(inputProblem);if(debug52("Starting LayoutPipelineSolver..."),debug52.enabled&&global?.debugGraphics){let initialViz=solver.visualize();global.debugGraphics.push({...initialViz,title:`matchpack-initial-${group.name}`})}if(solver.solve(),debug52(`Solver completed in ${solver.iterations} iterations`),debug52(`Solved: ${solver.solved}, Failed: ${solver.failed}`),solver.failed)throw debug52(`Solver failed with error: ${solver.error}`),new Error(`Matchpack layout solver failed: ${solver.error}`);let outputLayout=solver.getOutputLayout();if(debug52("OutputLayout:",JSON.stringify(outputLayout,null,2)),debug52("Solver completed successfully:",!solver.failed),debug52.enabled&&global?.debugGraphics){let finalViz=solver.visualize();global.debugGraphics.push({...finalViz,title:`matchpack-final-${group.name}`})}let overlaps=solver.checkForOverlaps(outputLayout);if(overlaps.length>0){debug52(`Warning: Found ${overlaps.length} overlapping components:`);for(let overlap of overlaps)debug52(` ${overlap.chip1} overlaps ${overlap.chip2} (area: ${overlap.overlapArea})`)}let groupOffset=group._getGlobalSchematicPositionBeforeLayout();debug52(`Group offset: x=${groupOffset.x}, y=${groupOffset.y}`),debug52(`Applying layout results for ${Object.keys(outputLayout.chipPlacements).length} chip placements`);for(let[chipId,placement]of Object.entries(outputLayout.chipPlacements)){debug52(`Processing placement for chip: ${chipId} at (${placement.x}, ${placement.y})`);let treeNode=tree.childNodes.find(child=>{if(child.nodeType==="component"&&child.sourceComponent){let matches=child.sourceComponent.name===chipId;return debug52(` Checking component ${child.sourceComponent.name}: matches=${matches}`),matches}if(child.nodeType==="group"&&child.sourceGroup){let groupName=child.sourceGroup.name,expectedChipId=`group_${tree.childNodes.indexOf(child)}`,matches=expectedChipId===chipId;return debug52(` Checking group ${groupName} (expected chipId: ${expectedChipId}): matches=${matches}`),matches}return!1});if(!treeNode){debug52(`Warning: No tree node found for chip: ${chipId}`),debug52("Available tree nodes:",tree.childNodes.map((child,idx)=>({type:child.nodeType,name:child.nodeType==="component"?child.sourceComponent?.name:child.sourceGroup?.name,expectedChipId:child.nodeType==="group"?`group_${idx}`:child.sourceComponent?.name})));continue}let newCenter={x:placement.x+groupOffset.x,y:placement.y+groupOffset.y};if(treeNode.nodeType==="component"&&treeNode.sourceComponent){let schematicComponent=db.schematic_component.getWhere({source_component_id:treeNode.sourceComponent.source_component_id});if(schematicComponent){debug52(`Moving component ${chipId} to (${newCenter.x}, ${newCenter.y})`);let ports=db.schematic_port.list({schematic_component_id:schematicComponent.schematic_component_id}),texts=db.schematic_text.list({schematic_component_id:schematicComponent.schematic_component_id}),positionDelta={x:newCenter.x-schematicComponent.center.x,y:newCenter.y-schematicComponent.center.y};for(let port of ports)port.center.x+=positionDelta.x,port.center.y+=positionDelta.y;for(let text of texts)text.position.x+=positionDelta.x,text.position.y+=positionDelta.y;if(updateSchematicPrimitivesForLayoutShift({db,schematicComponentId:schematicComponent.schematic_component_id,deltaX:positionDelta.x,deltaY:positionDelta.y}),schematicComponent.center=newCenter,placement.ccwRotationDegrees!==0){debug52(`Component ${chipId} has rotation: ${placement.ccwRotationDegrees}\xB0`);let angleRad=placement.ccwRotationDegrees*Math.PI/180,cos4=Math.cos(angleRad),sin4=Math.sin(angleRad);for(let port of ports){let dx2=port.center.x-newCenter.x,dy2=port.center.y-newCenter.y,rotatedDx=dx2*cos4-dy2*sin4,rotatedDy=dx2*sin4+dy2*cos4;port.center.x=newCenter.x+rotatedDx,port.center.y=newCenter.y+rotatedDy;let originalDirection=port.facing_direction||"right";port.facing_direction=rotateDirection2(originalDirection,placement.ccwRotationDegrees),port.side_of_component=(port.facing_direction==="up"?"top":port.facing_direction==="down"?"bottom":port.facing_direction)||port.side_of_component}for(let text of texts){let dx2=text.position.x-newCenter.x,dy2=text.position.y-newCenter.y,rotatedDx=dx2*cos4-dy2*sin4,rotatedDy=dx2*sin4+dy2*cos4;text.position.x=newCenter.x+rotatedDx,text.position.y=newCenter.y+rotatedDy}if(schematicComponent.symbol_name){let schematicSymbolDirection=schematicComponent.symbol_name.match(/_(right|left|up|down)$/);schematicSymbolDirection&&(schematicComponent.symbol_name=schematicComponent.symbol_name.replace(schematicSymbolDirection[0],`_${rotateDirection2(schematicSymbolDirection[1],placement.ccwRotationDegrees)}`))}}}}else if(treeNode.nodeType==="group"&&treeNode.sourceGroup){let schematicGroup=db.schematic_group?.getWhere?.({source_group_id:treeNode.sourceGroup.source_group_id});if(schematicGroup){debug52(`Moving group ${chipId} to (${newCenter.x}, ${newCenter.y}) from (${schematicGroup.center?.x}, ${schematicGroup.center?.y})`);let groupComponents=db.schematic_component.list({schematic_group_id:schematicGroup.schematic_group_id});debug52(`Group ${chipId} has ${groupComponents.length} components to move`);let oldCenter=schematicGroup.center||{x:0,y:0},positionDelta={x:newCenter.x-oldCenter.x,y:newCenter.y-oldCenter.y};debug52(`Position delta for group ${chipId}: (${positionDelta.x}, ${positionDelta.y})`);for(let component of groupComponents)if(component.center){let oldComponentCenter={...component.center};component.center.x+=positionDelta.x,component.center.y+=positionDelta.y,debug52(`Moved component ${component.source_component_id} from (${oldComponentCenter.x}, ${oldComponentCenter.y}) to (${component.center.x}, ${component.center.y})`);let ports=db.schematic_port.list({schematic_component_id:component.schematic_component_id}),texts=db.schematic_text.list({schematic_component_id:component.schematic_component_id});for(let port of ports)port.center&&(port.center.x+=positionDelta.x,port.center.y+=positionDelta.y);for(let text of texts)text.position&&(text.position.x+=positionDelta.x,text.position.y+=positionDelta.y)}schematicGroup.center=newCenter,debug52(`Updated group ${chipId} center to (${newCenter.x}, ${newCenter.y})`)}}}debug52("Matchpack layout completed successfully")}function Group_doInitialSourceAddConnectivityMapKey(group){if(!group.isSubcircuit)return;let{db}=group.root,traces=group.selectAll("trace"),vias=group.selectAll("via"),nets=group.selectAll("net"),connMap=new ConnectivityMap({});connMap.addConnections(traces.map(t6=>{let source_trace2=db.source_trace.get(t6.source_trace_id);return source_trace2?[source_trace2.source_trace_id,...source_trace2.connected_source_port_ids,...source_trace2.connected_source_net_ids]:null}).filter(c3=>c3!==null));let sourceNets=db.source_net.list().filter(net=>net.subcircuit_id===group.subcircuit_id);for(let sourceNet of sourceNets)connMap.addConnections([[sourceNet.source_net_id]]);let{name:subcircuitName}=group._parsedProps;for(let trace of traces){if(!trace.source_trace_id)continue;let connNetId=connMap.getNetConnectedToId(trace.source_trace_id);connNetId&&(trace.subcircuit_connectivity_map_key=`${subcircuitName??`unnamedsubcircuit${group._renderId}`}_${connNetId}`,db.source_trace.update(trace.source_trace_id,{subcircuit_connectivity_map_key:trace.subcircuit_connectivity_map_key}))}let allSourcePortIds=new Set;for(let trace of traces){if(!trace.source_trace_id)continue;let source_trace2=db.source_trace.get(trace.source_trace_id);if(source_trace2)for(let id of source_trace2.connected_source_port_ids)allSourcePortIds.add(id)}for(let portId of allSourcePortIds){let connNetId=connMap.getNetConnectedToId(portId);if(!connNetId)continue;let connectivityMapKey=`${subcircuitName??`unnamedsubcircuit${group._renderId}`}_${connNetId}`;db.source_port.update(portId,{subcircuit_connectivity_map_key:connectivityMapKey})}let allSourceNetIds=new Set;for(let trace of traces){if(!trace.source_trace_id)continue;let source_trace2=db.source_trace.get(trace.source_trace_id);if(source_trace2)for(let source_net_id of source_trace2.connected_source_net_ids)allSourceNetIds.add(source_net_id)}for(let sourceNet of sourceNets)allSourceNetIds.add(sourceNet.source_net_id);for(let netId of allSourceNetIds){let connNetId=connMap.getNetConnectedToId(netId);if(!connNetId)continue;let connectivityMapKey=`${subcircuitName??`unnamedsubcircuit${group._renderId}`}_${connNetId}`;db.source_net.update(netId,{subcircuit_connectivity_map_key:connectivityMapKey});let netInstance=nets.find(n3=>n3.source_net_id===netId);netInstance&&(netInstance.subcircuit_connectivity_map_key=connectivityMapKey)}for(let via of vias){let connectedNetOrTrace=via._getConnectedNetOrTrace();connectedNetOrTrace&&connectedNetOrTrace.subcircuit_connectivity_map_key&&(via.subcircuit_connectivity_map_key=connectedNetOrTrace.subcircuit_connectivity_map_key)}}function Group_doInitialSchematicLayoutGrid(group){let{db}=group.root,props=group._parsedProps,schematicChildren=group.children.filter(child=>{let isExplicitlyPositioned=child._parsedProps?.schX!==void 0||child._parsedProps?.schY!==void 0;return child.schematic_component_id&&!isExplicitlyPositioned});if(schematicChildren.length===0)return;let maxCellWidth=0,maxCellHeight=0;for(let child of schematicChildren){let schComp=db.schematic_component.get(child.schematic_component_id);schComp?.size&&(maxCellWidth=Math.max(maxCellWidth,schComp.size.width),maxCellHeight=Math.max(maxCellHeight,schComp.size.height))}maxCellWidth===0&&schematicChildren.length>0&&(maxCellWidth=1),maxCellHeight===0&&schematicChildren.length>0&&(maxCellHeight=1);let gridColsOption=props.gridCols,gridRowsOption,gridGapOption=props.gridGap,gridRowGapOption=props.gridRowGap,gridColumnGapOption=props.gridColumnGap;props.schLayout?.grid&&(gridColsOption=props.schLayout.grid.cols??gridColsOption,gridRowsOption=props.schLayout.grid.rows,gridGapOption=props.schLayout.gridGap??gridGapOption,gridRowGapOption=props.schLayout.gridRowGap??gridRowGapOption,gridColumnGapOption=props.schLayout.gridColumnGap??gridColumnGapOption);let numCols,numRows;gridColsOption!==void 0&&gridRowsOption!==void 0?(numCols=gridColsOption,numRows=gridRowsOption):gridColsOption!==void 0?(numCols=gridColsOption,numRows=Math.ceil(schematicChildren.length/numCols)):gridRowsOption!==void 0?(numRows=gridRowsOption,numCols=Math.ceil(schematicChildren.length/numRows)):(numCols=Math.ceil(Math.sqrt(schematicChildren.length)),numRows=Math.ceil(schematicChildren.length/numCols)),numCols===0&&schematicChildren.length>0&&(numCols=1),numRows===0&&schematicChildren.length>0&&(numRows=schematicChildren.length);let gridGapX,gridGapY,parseGap=val=>{if(val!==void 0)return typeof val=="number"?val:length.parse(val)};if(gridRowGapOption!==void 0||gridColumnGapOption!==void 0){let fallbackX=typeof gridGapOption=="object"&&gridGapOption!==null?gridGapOption.x:gridGapOption,fallbackY=typeof gridGapOption=="object"&&gridGapOption!==null?gridGapOption.y:gridGapOption;gridGapX=parseGap(gridColumnGapOption??fallbackX)??1,gridGapY=parseGap(gridRowGapOption??fallbackY)??1}else if(typeof gridGapOption=="number")gridGapX=gridGapOption,gridGapY=gridGapOption;else if(typeof gridGapOption=="string"){let parsed=length.parse(gridGapOption);gridGapX=parsed,gridGapY=parsed}else if(typeof gridGapOption=="object"&&gridGapOption!==null){let xRaw=gridGapOption.x,yRaw=gridGapOption.y;gridGapX=typeof xRaw=="number"?xRaw:length.parse(xRaw??"0mm"),gridGapY=typeof yRaw=="number"?yRaw:length.parse(yRaw??"0mm")}else gridGapX=1,gridGapY=1;let totalGridWidth=numCols*maxCellWidth+Math.max(0,numCols-1)*gridGapX,totalGridHeight=numRows*maxCellHeight+Math.max(0,numRows-1)*gridGapY,groupCenter=group._getGlobalSchematicPositionBeforeLayout(),firstCellCenterX=groupCenter.x-totalGridWidth/2+maxCellWidth/2,firstCellCenterY=groupCenter.y+totalGridHeight/2-maxCellHeight/2;for(let i3=0;i3<schematicChildren.length;i3++){let child=schematicChildren[i3];if(!child.schematic_component_id)continue;let row=Math.floor(i3/numCols),col=i3%numCols;if(row>=numRows||col>=numCols){console.warn(`Schematic grid layout: Child ${child.getString()} at index ${i3} (row ${row}, col ${col}) exceeds specified grid dimensions (${numRows}x${numCols}). Skipping placement.`);continue}let targetCellCenterX=firstCellCenterX+col*(maxCellWidth+gridGapX),targetCellCenterY=firstCellCenterY-row*(maxCellHeight+gridGapY),schComp=db.schematic_component.get(child.schematic_component_id);if(schComp){let oldChildCenter=schComp.center,newChildCenter={x:targetCellCenterX,y:targetCellCenterY};db.schematic_component.update(child.schematic_component_id,{center:newChildCenter});let deltaX=newChildCenter.x-oldChildCenter.x,deltaY=newChildCenter.y-oldChildCenter.y,schPorts=db.schematic_port.list({schematic_component_id:child.schematic_component_id});for(let port of schPorts)db.schematic_port.update(port.schematic_port_id,{center:{x:port.center.x+deltaX,y:port.center.y+deltaY}});let schTexts=db.schematic_text.list({schematic_component_id:child.schematic_component_id});for(let text of schTexts)db.schematic_text.update(text.schematic_text_id,{position:{x:text.position.x+deltaX,y:text.position.y+deltaY}});updateSchematicPrimitivesForLayoutShift({db,schematicComponentId:child.schematic_component_id,deltaX,deltaY})}}group.schematic_group_id&&db.schematic_group.update(group.schematic_group_id,{width:totalGridWidth,height:totalGridHeight,center:groupCenter})}var getSizeOfTreeNodeChild=(db,child)=>{let{sourceComponent,sourceGroup}=child;if(child.nodeType==="component"){let schComponent=db.schematic_component.getWhere({source_component_id:sourceComponent?.source_component_id});return schComponent?.size?{width:schComponent.size.width,height:schComponent.size.height}:null}if(child.nodeType==="group"){let schGroup=db.schematic_group.getWhere({source_group_id:sourceGroup?.source_group_id});if(schGroup?.width&&schGroup?.height)return{width:schGroup.width,height:schGroup.height};let groupComponents=db.schematic_component.list({schematic_group_id:schGroup?.schematic_group_id}),minX=1/0,maxX=-1/0,minY=1/0,maxY=-1/0;for(let comp of groupComponents)if(comp.center&&comp.size){let halfWidth=comp.size.width/2,halfHeight=comp.size.height/2;minX=Math.min(minX,comp.center.x-halfWidth),maxX=Math.max(maxX,comp.center.x+halfWidth),minY=Math.min(minY,comp.center.y-halfHeight),maxY=Math.max(maxY,comp.center.y+halfHeight)}let groupWidth=maxX-minX,groupHeight=maxY-minY;return{width:groupWidth,height:groupHeight}}return null},Group_doInitialSchematicLayoutFlex=group=>{let{db}=group.root,props=group._parsedProps,tree=getCircuitJsonTree(db.toArray(),{source_group_id:group.source_group_id}),rawJustify=props.schJustifyContent??props.justifyContent,rawAlign=props.schAlignItems??props.alignItems,rawGap=props.schFlexGap??props.schGap??props.gap,direction2=props.schFlexDirection??"row",justifyContent={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"space-between","space-between":"space-between","space-around":"space-around","space-evenly":"space-evenly",center:"center"}[rawJustify??"space-between"],alignItems={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[rawAlign??"center"];if(!justifyContent)throw new Error(`Invalid justifyContent value: "${rawJustify}"`);if(!alignItems)throw new Error(`Invalid alignItems value: "${rawAlign}"`);let rowGap=0,columnGap=0;typeof rawGap=="object"?(rowGap=rawGap.y??0,columnGap=rawGap.x??0):typeof rawGap=="number"?(rowGap=rawGap,columnGap=rawGap):typeof rawGap=="string"&&(rowGap=length.parse(rawGap),columnGap=length.parse(rawGap));let minFlexContainer,width=props.width??props.schWidth??void 0,height=props.height??props.schHeight??void 0;(width===void 0||height===void 0)&&(minFlexContainer=getMinimumFlexContainer(tree.childNodes.map(child=>getSizeOfTreeNodeChild(db,child)).filter(size2=>size2!==null),{alignItems,justifyContent,direction:direction2,rowGap,columnGap}),width=minFlexContainer.width,height=minFlexContainer.height);let flexBox=new RootFlexBox(width,height,{alignItems,justifyContent,direction:direction2,rowGap,columnGap});for(let child of tree.childNodes){let size2=getSizeOfTreeNodeChild(db,child);flexBox.addChild({metadata:child,width:size2?.width??0,height:size2?.height??0,flexBasis:size2?direction2==="row"?size2.width:size2.height:void 0})}flexBox.build();let bounds={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let child of flexBox.children)bounds.minX=Math.min(bounds.minX,child.position.x),bounds.minY=Math.min(bounds.minY,child.position.y),bounds.maxX=Math.max(bounds.maxX,child.position.x+child.size.width),bounds.maxY=Math.max(bounds.maxY,child.position.y+child.size.height);bounds.width=bounds.maxX-bounds.minX,bounds.height=bounds.maxY-bounds.minY;let offset={x:-(bounds.maxX+bounds.minX)/2,y:-(bounds.maxY+bounds.minY)/2},allCircuitJson=db.toArray();for(let child of flexBox.children){let{sourceComponent,sourceGroup}=child.metadata;if(sourceComponent){let schComponent=db.schematic_component.getWhere({source_component_id:sourceComponent.source_component_id});if(!schComponent)continue;repositionSchematicComponentTo(allCircuitJson,schComponent.schematic_component_id,{x:child.position.x+child.size.width/2+offset.x,y:child.position.y+child.size.height/2+offset.y})}if(sourceGroup){if(!db.schematic_group.getWhere({source_group_id:sourceGroup.source_group_id}))continue;repositionSchematicGroupTo(allCircuitJson,sourceGroup.source_group_id,{x:child.position.x+child.size.width/2+offset.x,y:child.position.y+child.size.height/2+offset.y})}}group.schematic_group_id&&db.schematic_group.update(group.schematic_group_id,{width:bounds.width,height:bounds.height})},MIN_GAP=1;function Group_doInitialPcbLayoutGrid(group){let{db}=group.root,props=group._parsedProps,pcbChildren=getPcbChildren(group);if(pcbChildren.length===0)return;let childDimensions=calculateChildDimensions({db,pcbChildren}),gridConfig=parseGridConfiguration(props),gridLayout=createGridLayout({props,pcbChildren,childDimensions,gridConfig}),cssGrid=createCssGrid({pcbChildren,childDimensions,gridLayout,gridConfig}),{itemCoordinates}=cssGrid.layout();positionChildren({db,group,pcbChildren,itemCoordinates,gridLayout}),updateGroupDimensions({db,group,props,gridLayout})}function getPcbChildren(group){return group.children.filter(child=>child.pcb_component_id||child.pcb_group_id)}function calculateChildDimensions(params){let{db,pcbChildren}=params,maxWidth=0,maxHeight=0;for(let child of pcbChildren){let width=0,height=0;if(child.pcb_group_id){let pcbGroup=db.pcb_group.get(child.pcb_group_id);width=pcbGroup?.width??0,height=pcbGroup?.height??0}else if(child.pcb_component_id){let pcbComp=db.pcb_component.get(child.pcb_component_id);width=pcbComp?.width??0,height=pcbComp?.height??0}maxWidth=Math.max(maxWidth,width),maxHeight=Math.max(maxHeight,height)}return{width:maxWidth,height:maxHeight}}function parseGridConfiguration(props){let cols=props.pcbGridCols??props.gridCols??props.pcbLayout?.grid?.cols,rows=props.pcbGridRows??props.pcbLayout?.grid?.rows,templateColumns=props.pcbGridTemplateColumns,templateRows=props.pcbGridTemplateRows,parseGap=gapValue=>gapValue===void 0?MIN_GAP:typeof gapValue=="number"?gapValue:length.parse(gapValue),gridGapOption=props.pcbGridGap??props.gridGap??props.pcbLayout?.gridGap,rowGapOption=props.pcbGridRowGap??props.gridRowGap??props.pcbLayout?.gridRowGap,colGapOption=props.pcbGridColumnGap??props.gridColumnGap??props.pcbLayout?.gridColumnGap,gapX=MIN_GAP,gapY=MIN_GAP;if(rowGapOption!==void 0||colGapOption!==void 0){let fallbackX=typeof gridGapOption=="object"?gridGapOption?.x:gridGapOption,fallbackY=typeof gridGapOption=="object"?gridGapOption?.y:gridGapOption;gapX=parseGap(colGapOption??fallbackX),gapY=parseGap(rowGapOption??fallbackY)}else if(typeof gridGapOption=="object"&&gridGapOption!==null)gapX=parseGap(gridGapOption.x),gapY=parseGap(gridGapOption.y);else{let gap=parseGap(gridGapOption);gapX=gap,gapY=gap}return{cols,rows,gapX,gapY,templateColumns,templateRows}}function createGridLayout(params){let{props,pcbChildren,childDimensions,gridConfig}=params;return props.pcbGridTemplateColumns||props.pcbGridTemplateRows?createTemplateBasedLayout({props,gridConfig,pcbChildren,childDimensions}):createDefaultLayout({gridConfig,pcbChildren,childDimensions})}function createTemplateBasedLayout(params){let{props,gridConfig,pcbChildren,childDimensions}=params,gridTemplateColumns=props.pcbGridTemplateColumns??"",gridTemplateRows=props.pcbGridTemplateRows??"",extractRepeatCount=template=>{let match2=template.match(/repeat\((\d+),/);return match2?parseInt(match2[1]):Math.ceil(Math.sqrt(pcbChildren.length))},numCols=props.pcbGridTemplateColumns?extractRepeatCount(gridTemplateColumns):Math.ceil(Math.sqrt(pcbChildren.length)),numRows=props.pcbGridTemplateRows?extractRepeatCount(gridTemplateRows):Math.ceil(pcbChildren.length/numCols),containerWidth=numCols*childDimensions.width+Math.max(0,numCols-1)*gridConfig.gapX,containerHeight=numRows*childDimensions.height+Math.max(0,numRows-1)*gridConfig.gapY;return{gridTemplateColumns,gridTemplateRows,containerWidth,containerHeight}}function createDefaultLayout(params){let{gridConfig,pcbChildren,childDimensions}=params,numCols,numRows;gridConfig.cols!==void 0&&gridConfig.rows!==void 0?(numCols=gridConfig.cols,numRows=gridConfig.rows):gridConfig.cols!==void 0?(numCols=gridConfig.cols,numRows=Math.ceil(pcbChildren.length/numCols)):gridConfig.rows!==void 0?(numRows=gridConfig.rows,numCols=Math.ceil(pcbChildren.length/numRows)):(numCols=Math.ceil(Math.sqrt(pcbChildren.length)),numRows=Math.ceil(pcbChildren.length/numCols)),numCols=Math.max(1,numCols),numRows=Math.max(1,numRows);let containerWidth=numCols*childDimensions.width+Math.max(0,numCols-1)*gridConfig.gapX,containerHeight=numRows*childDimensions.height+Math.max(0,numRows-1)*gridConfig.gapY,gridTemplateColumns=`repeat(${numCols}, ${childDimensions.width}px)`,gridTemplateRows=`repeat(${numRows}, ${childDimensions.height}px)`;return{gridTemplateColumns,gridTemplateRows,containerWidth,containerHeight}}function createCssGrid(params){let{pcbChildren,childDimensions,gridLayout,gridConfig}=params,gridChildren=pcbChildren.map((child,index)=>({key:child.getString()||`child-${index}`,contentWidth:childDimensions.width,contentHeight:childDimensions.height}));return new CssGrid({containerWidth:gridLayout.containerWidth,containerHeight:gridLayout.containerHeight,gridTemplateColumns:gridLayout.gridTemplateColumns,gridTemplateRows:gridLayout.gridTemplateRows,gap:[gridConfig.gapY,gridConfig.gapX],children:gridChildren})}function positionChildren(params){let{db,group,pcbChildren,itemCoordinates,gridLayout}=params,groupCenter=group._getGlobalPcbPositionBeforeLayout(),allCircuitJson=db.toArray();for(let i3=0;i3<pcbChildren.length;i3++){let child=pcbChildren[i3],childKey=child.getString()||`child-${i3}`,coordinates=itemCoordinates[childKey];if(!coordinates){console.warn(`PCB grid layout: No coordinates found for child ${childKey}`);continue}let targetX=groupCenter.x-gridLayout.containerWidth/2+coordinates.x+coordinates.width/2,targetY=groupCenter.y+gridLayout.containerHeight/2-coordinates.y-coordinates.height/2;if(child.pcb_component_id)repositionPcbComponentTo(allCircuitJson,child.pcb_component_id,{x:targetX,y:targetY});else{let groupChild=child;groupChild.pcb_group_id&&groupChild.source_group_id&&repositionPcbGroupTo(allCircuitJson,groupChild.source_group_id,{x:targetX,y:targetY})}}}function updateGroupDimensions(params){let{db,group,props,gridLayout}=params;if(group.pcb_group_id){let groupCenter=group._getGlobalPcbPositionBeforeLayout();db.pcb_group.update(group.pcb_group_id,{width:props.width??gridLayout.containerWidth,height:props.height??gridLayout.containerHeight,center:groupCenter})}}function getPresetAutoroutingConfig(autorouterConfig2){let defaults={serverUrl:"https://registry-api.tscircuit.com",serverMode:"job",serverCacheEnabled:!0};if(typeof autorouterConfig2=="object"&&!autorouterConfig2.preset)return{local:!(autorouterConfig2.serverUrl||autorouterConfig2.serverMode||autorouterConfig2.serverCacheEnabled),...defaults,...autorouterConfig2};let preset=typeof autorouterConfig2=="object"?autorouterConfig2.preset:autorouterConfig2,providedConfig=typeof autorouterConfig2=="object"?autorouterConfig2:{};switch(typeof preset=="string"?preset.replace(/_/g,"-"):preset){case"auto-local":return{local:!0,groupMode:"subcircuit"};case"sequential-trace":return{local:!0,groupMode:"sequential-trace"};case"subcircuit":return{local:!0,groupMode:"subcircuit"};case"auto-cloud":{let{preset:_preset,local:_local,groupMode:_groupMode,...rest}=providedConfig;return{local:!1,groupMode:"subcircuit",...defaults,...rest}}case"laser-prefab":{let{preset:_preset,local:_local,groupMode:_groupMode,...rest}=providedConfig;return{local:!0,groupMode:"subcircuit",preset:"laser_prefab",...rest}}default:return{local:!0,groupMode:"subcircuit"}}}var applyComponentConstraintClusters=(group,packInput)=>{let constraints=group.children.filter(c3=>c3.componentName==="Constraint"&&c3._parsedProps.pcb),clusterByRoot=new Map,parent={},find2=x3=>(parent[x3]!==x3&&(parent[x3]=find2(parent[x3])),parent[x3]),union2=(a3,b3)=>{let ra2=find2(a3),rb2=find2(b3);ra2!==rb2&&(parent[rb2]=ra2)},makeSet=x3=>{x3 in parent||(parent[x3]=x3)},getIdFromSelector=sel2=>{let name=sel2.startsWith(".")?sel2.slice(1):sel2;return group.children.find(c3=>c3.name===name)?.pcb_component_id??void 0};for(let constraint of constraints){let props=constraint._parsedProps;if("left"in props&&"right"in props){let a3=getIdFromSelector(props.left),b3=getIdFromSelector(props.right);a3&&b3&&(makeSet(a3),makeSet(b3),union2(a3,b3))}else if("top"in props&&"bottom"in props){let a3=getIdFromSelector(props.top),b3=getIdFromSelector(props.bottom);a3&&b3&&(makeSet(a3),makeSet(b3),union2(a3,b3))}else if("for"in props&&Array.isArray(props.for)){let ids=props.for.map(s4=>getIdFromSelector(s4)).filter(s4=>!!s4);for(let id of ids)makeSet(id);for(let i3=1;i3<ids.length;i3++)union2(ids[0],ids[i3])}}for(let id of Object.keys(parent)){let rootId=find2(id);clusterByRoot.has(rootId)||clusterByRoot.set(rootId,{componentIds:[],constraints:[]}),clusterByRoot.get(rootId).componentIds.push(id)}for(let constraint of constraints){let props=constraint._parsedProps,compId;if("left"in props?compId=getIdFromSelector(props.left):"top"in props?compId=getIdFromSelector(props.top):"for"in props&&(compId=getIdFromSelector(props.for[0])),!compId)continue;let root=find2(compId);clusterByRoot.get(root)?.constraints.push(constraint)}let clusterMap={},packCompById=Object.fromEntries(packInput.components.map(c3=>[c3.componentId,c3]));for(let[rootId,info]of clusterByRoot.entries()){if(info.componentIds.length<=1)continue;let solver=new Solver,kVars={},getVar=(id,axis)=>{let key=`${id}_${axis}`;return kVars[key]||(kVars[key]=new Variable(key)),kVars[key]},anchor=info.componentIds[0];solver.addConstraint(new Constraint(getVar(anchor,"x"),Operator.Eq,0,Strength.required)),solver.addConstraint(new Constraint(getVar(anchor,"y"),Operator.Eq,0,Strength.required));for(let constraint of info.constraints){let props=constraint._parsedProps;if("xDist"in props){let left=getIdFromSelector(props.left),right=getIdFromSelector(props.right);left&&right&&solver.addConstraint(new Constraint(new Expression(getVar(right,"x"),[-1,getVar(left,"x")]),Operator.Eq,props.xDist,Strength.required))}else if("yDist"in props){let top=getIdFromSelector(props.top),bottom=getIdFromSelector(props.bottom);top&&bottom&&solver.addConstraint(new Constraint(new Expression(getVar(top,"y"),[-1,getVar(bottom,"y")]),Operator.Eq,props.yDist,Strength.required))}else if("sameX"in props&&Array.isArray(props.for)){let ids=props.for.map(s4=>getIdFromSelector(s4)).filter(s4=>!!s4);if(ids.length>1){let base=getVar(ids[0],"x");for(let i3=1;i3<ids.length;i3++)solver.addConstraint(new Constraint(new Expression(getVar(ids[i3],"x"),[-1,base]),Operator.Eq,0,Strength.required))}}else if("sameY"in props&&Array.isArray(props.for)){let ids=props.for.map(s4=>getIdFromSelector(s4)).filter(s4=>!!s4);if(ids.length>1){let base=getVar(ids[0],"y");for(let i3=1;i3<ids.length;i3++)solver.addConstraint(new Constraint(new Expression(getVar(ids[i3],"y"),[-1,base]),Operator.Eq,0,Strength.required))}}}solver.updateVariables();let positions={};for(let id of info.componentIds)positions[id]={x:getVar(id,"x").value(),y:getVar(id,"y").value()};let minX=1/0,minY=1/0,maxX=-1/0,maxY=-1/0;for(let id of info.componentIds){let comp=packCompById[id],pos=positions[id];if(comp)for(let pad2 of comp.pads){let ax2=pos.x+pad2.offset.x,ay2=pos.y+pad2.offset.y;minX=Math.min(minX,ax2-pad2.size.x/2),maxX=Math.max(maxX,ax2+pad2.size.x/2),minY=Math.min(minY,ay2-pad2.size.y/2),maxY=Math.max(maxY,ay2+pad2.size.y/2)}}let clusterCenter={x:(minX+maxX)/2,y:(minY+maxY)/2},mergedPads=[],relCenters={};for(let id of info.componentIds){let comp=packCompById[id],pos=positions[id];if(comp){relCenters[id]={x:pos.x-clusterCenter.x,y:pos.y-clusterCenter.y};for(let pad2 of comp.pads)mergedPads.push({padId:pad2.padId,networkId:pad2.networkId,type:pad2.type,size:pad2.size,offset:{x:pos.x+pad2.offset.x-clusterCenter.x,y:pos.y+pad2.offset.y-clusterCenter.y}})}}packInput.components=packInput.components.filter(c3=>!info.componentIds.includes(c3.componentId)),packInput.components.push({componentId:info.componentIds[0],pads:mergedPads,availableRotationDegrees:[0]}),info.relativeCenters=relCenters,clusterMap[info.componentIds[0]]=info}return clusterMap},updateCadRotation=({db,pcbComponentId,rotationDegrees,layer})=>{if(rotationDegrees==null||!db?.cad_component?.list)return;let cadComponent=db.cad_component.getWhere({pcb_component_id:pcbComponentId});if(!cadComponent)return;let delta=layer?.toLowerCase?.()==="bottom"?-rotationDegrees:rotationDegrees,currentRotationZ=cadComponent.rotation?.z??0,nextRotation={...cadComponent.rotation??{x:0,y:0,z:0},z:normalizeDegrees(currentRotationZ+delta)};db.cad_component.update(cadComponent.cad_component_id,{rotation:nextRotation}),cadComponent.rotation=nextRotation},isDescendantGroup=(db,groupId,ancestorId)=>{if(groupId===ancestorId)return!0;let group=db.source_group.get(groupId);return!group||!group.parent_source_group_id?!1:isDescendantGroup(db,group.parent_source_group_id,ancestorId)},applyPackOutput=(group,packOutput,clusterMap)=>{let{db}=group.root;for(let packedComponent of packOutput.components){let{center:center2,componentId,ccwRotationOffset,ccwRotationDegrees}=packedComponent,cluster=clusterMap[componentId];if(cluster){let rotationDegrees2=ccwRotationDegrees??ccwRotationOffset??0,angleRad=rotationDegrees2*Math.PI/180;for(let memberId of cluster.componentIds){let rel=cluster.relativeCenters[memberId];if(!rel)continue;db.pcb_component.update(memberId,{position_mode:"packed"});let rotatedRel={x:rel.x*Math.cos(angleRad)-rel.y*Math.sin(angleRad),y:rel.x*Math.sin(angleRad)+rel.y*Math.cos(angleRad)},member=db.pcb_component.get(memberId);if(!member)continue;let originalCenter2=member.center,transformMatrix2=compose(group._computePcbGlobalTransformBeforeLayout(),translate(center2.x+rotatedRel.x,center2.y+rotatedRel.y),rotate(angleRad),translate(-originalCenter2.x,-originalCenter2.y)),related=db.toArray().filter(elm=>"pcb_component_id"in elm&&elm.pcb_component_id===memberId);transformPCBElements(related,transformMatrix2),updateCadRotation({db,pcbComponentId:memberId,rotationDegrees:rotationDegrees2,layer:member.layer})}continue}let pcbComponent=db.pcb_component.get(componentId);if(pcbComponent){db.pcb_component.update(componentId,{position_mode:"packed"});let currentGroupId=group.source_group_id,componentGroupId=db.source_component.get(pcbComponent.source_component_id)?.source_group_id;if(componentGroupId!==void 0&&!isDescendantGroup(db,componentGroupId,currentGroupId))continue;let originalCenter2=pcbComponent.center,rotationDegrees2=ccwRotationDegrees??ccwRotationOffset??0,transformMatrix2=compose(group._computePcbGlobalTransformBeforeLayout(),translate(center2.x,center2.y),rotate(rotationDegrees2*Math.PI/180),translate(-originalCenter2.x,-originalCenter2.y)),related=db.toArray().filter(elm=>"pcb_component_id"in elm&&elm.pcb_component_id===componentId);transformPCBElements(related,transformMatrix2),updateCadRotation({db,pcbComponentId:componentId,rotationDegrees:rotationDegrees2,layer:pcbComponent.layer});continue}let pcbGroup=db.pcb_group.list().find(g4=>g4.source_group_id===componentId);if(!pcbGroup)continue;let originalCenter=pcbGroup.center,rotationDegrees=ccwRotationDegrees??ccwRotationOffset??0,transformMatrix=compose(group._computePcbGlobalTransformBeforeLayout(),translate(center2.x,center2.y),rotate(rotationDegrees*Math.PI/180),translate(-originalCenter.x,-originalCenter.y)),relatedElements=db.toArray().filter(elm=>{if("source_group_id"in elm&&elm.source_group_id&&(elm.source_group_id===componentId||isDescendantGroup(db,elm.source_group_id,componentId)))return!0;if("source_component_id"in elm&&elm.source_component_id){let sourceComponent=db.source_component.get(elm.source_component_id);if(sourceComponent?.source_group_id&&(sourceComponent.source_group_id===componentId||isDescendantGroup(db,sourceComponent.source_group_id,componentId)))return!0}if("pcb_component_id"in elm&&elm.pcb_component_id){let pcbComp=db.pcb_component.get(elm.pcb_component_id);if(pcbComp?.source_component_id){let sourceComp=db.source_component.get(pcbComp.source_component_id);if(sourceComp?.source_group_id&&(sourceComp.source_group_id===componentId||isDescendantGroup(db,sourceComp.source_group_id,componentId)))return!0}}return!1});for(let elm of relatedElements)elm.type==="pcb_component"&&db.pcb_component.update(elm.pcb_component_id,{position_mode:"packed"});transformPCBElements(relatedElements,transformMatrix),db.pcb_group.update(pcbGroup.pcb_group_id,{center:center2})}},DEFAULT_MIN_GAP="1mm",debug6=(0,import_debug13.default)("Group_doInitialPcbLayoutPack"),Group_doInitialPcbLayoutPack=group=>{let{db}=group.root,{_parsedProps:props}=group;group.root?.emit("packing:start",{subcircuit_id:group.subcircuit_id,componentDisplayName:group.getString()});let{packOrderStrategy,packPlacementStrategy,gap:gapProp,pcbGap,pcbPackGap}=props,gap=pcbPackGap??pcbGap??gapProp,gapMm=length.parse(gap??DEFAULT_MIN_GAP),chipMarginsMap={},staticPcbComponentIds=new Set,collectMargins=comp=>{if(comp?.pcb_component_id&&comp?._parsedProps){let props2=comp._parsedProps,left=length.parse(props2.pcbMarginLeft??props2.pcbMarginX??0),right=length.parse(props2.pcbMarginRight??props2.pcbMarginX??0),top=length.parse(props2.pcbMarginTop??props2.pcbMarginY??0),bottom=length.parse(props2.pcbMarginBottom??props2.pcbMarginY??0);(left||right||top||bottom)&&(chipMarginsMap[comp.pcb_component_id]={left,right,top,bottom})}comp?.children&&comp.children.forEach(collectMargins)};collectMargins(group);let excludedPcbGroupIds=new Set;for(let child of group.children){let childIsGroupOrNormalComponent=child;childIsGroupOrNormalComponent._isNormalComponent&&childIsGroupOrNormalComponent.isRelativelyPositioned?.()&&(childIsGroupOrNormalComponent.pcb_component_id&&staticPcbComponentIds.add(childIsGroupOrNormalComponent.pcb_component_id),childIsGroupOrNormalComponent.pcb_group_id&&excludedPcbGroupIds.add(childIsGroupOrNormalComponent.pcb_group_id))}let isDescendantGroup2=(db2,groupId,ancestorId)=>{if(groupId===ancestorId)return!0;let group2=db2.source_group.get(groupId);return!group2||!group2.parent_source_group_id?!1:isDescendantGroup2(db2,group2.parent_source_group_id,ancestorId)};if(excludedPcbGroupIds.size>0)for(let element of db.toArray()){if(element.type!=="pcb_component")continue;let sourceComponent=db.source_component.get(element.source_component_id);if(sourceComponent?.source_group_id)for(let groupId of excludedPcbGroupIds)isDescendantGroup2(db,sourceComponent.source_group_id,groupId)&&staticPcbComponentIds.add(element.pcb_component_id)}let filteredCircuitJson=db.toArray(),bounds;if(props.width!==void 0&&props.height!==void 0){let widthMm=length.parse(props.width),heightMm=length.parse(props.height);bounds={minX:-widthMm/2,maxX:widthMm/2,minY:-heightMm/2,maxY:heightMm/2}}let packInput={...convertPackOutputToPackInput(convertCircuitJsonToPackOutput(filteredCircuitJson,{source_group_id:group.source_group_id,chipMarginsMap,staticPcbComponentIds:Array.from(staticPcbComponentIds)})),orderStrategy:packOrderStrategy??"largest_to_smallest",placementStrategy:packPlacementStrategy??"minimum_sum_squared_distance_to_network",minGap:gapMm,bounds},clusterMap=applyComponentConstraintClusters(group,packInput);debug6.enabled&&(group.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-circuitjson-${group.name}`,content:JSON.stringify(db.toArray())}),group.root?.emit("debug:logOutput",{type:"debug:logOutput",name:`packInput-${group.name}`,content:packInput}));let packOutput;try{let solver=new PackSolver2(packInput);group.root?.emit("solver:started",{type:"solver:started",solverName:"PackSolver2",solverParams:solver.getConstructorParams(),componentName:group.getString()}),solver.solve(),packOutput={...packInput,components:solver.packedComponents}}catch(error){throw group.root?.emit("packing:error",{subcircuit_id:group.subcircuit_id,componentDisplayName:group.getString(),error:{message:error instanceof Error?error.message:String(error)}}),error}if(debug6.enabled&&global?.debugGraphics){let graphics=getGraphicsFromPackOutput(packOutput);graphics.title=`packOutput-${group.name}`,global.debugGraphics?.push(graphics)}applyPackOutput(group,packOutput,clusterMap),group.root?.emit("packing:end",{subcircuit_id:group.subcircuit_id,componentDisplayName:group.getString()})},Group_doInitialPcbLayoutFlex=group=>{let{db}=group.root,{_parsedProps:props}=group,pcbChildren=group.children.filter(c3=>c3.pcb_component_id||c3.pcb_group_id);if(pcbChildren.some(child=>{let childProps=child._parsedProps;return childProps?.pcbX!==void 0||childProps?.pcbY!==void 0}))return;let rawJustify=props.pcbJustifyContent??props.justifyContent,rawAlign=props.pcbAlignItems??props.alignItems,rawGap=props.pcbFlexGap??props.pcbGap??props.gap,direction2=props.pcbFlexDirection??"row",justifyContent={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"space-between","space-between":"space-between","space-around":"space-around","space-evenly":"space-evenly",center:"center"}[rawJustify??"space-between"],alignItems={start:"flex-start",end:"flex-end","flex-start":"flex-start","flex-end":"flex-end",stretch:"stretch",center:"center"}[rawAlign??"center"];if(!justifyContent)throw new Error(`Invalid justifyContent value: "${rawJustify}"`);if(!alignItems)throw new Error(`Invalid alignItems value: "${rawAlign}"`);let rowGap=0,columnGap=0;typeof rawGap=="object"?(rowGap=rawGap.y??0,columnGap=rawGap.x??0):typeof rawGap=="number"?(rowGap=rawGap,columnGap=rawGap):typeof rawGap=="string"&&(rowGap=length.parse(rawGap),columnGap=length.parse(rawGap));let minFlexContainer,width=props.width??props.pcbWidth??void 0,height=props.height??props.pcbHeight??void 0;(width===void 0||height===void 0)&&(minFlexContainer=getMinimumFlexContainer(pcbChildren.map(child=>child._getMinimumFlexContainerSize()).filter(size2=>size2!==null),{alignItems,justifyContent,direction:direction2,rowGap,columnGap}),width=minFlexContainer.width,height=minFlexContainer.height);let flexBox=new RootFlexBox(width,height,{alignItems,justifyContent,direction:direction2,rowGap,columnGap});for(let child of pcbChildren){let size2=child._getMinimumFlexContainerSize();flexBox.addChild({metadata:child,width:size2?.width??0,height:size2?.height??0,flexBasis:size2?direction2==="row"?size2.width:size2.height:void 0})}flexBox.build();let bounds={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,width:0,height:0};for(let child of flexBox.children)bounds.minX=Math.min(bounds.minX,child.position.x),bounds.minY=Math.min(bounds.minY,child.position.y),bounds.maxX=Math.max(bounds.maxX,child.position.x+child.size.width),bounds.maxY=Math.max(bounds.maxY,child.position.y+child.size.height);bounds.width=bounds.maxX-bounds.minX,bounds.height=bounds.maxY-bounds.minY;let groupCenter=group._getGlobalPcbPositionBeforeLayout(),offset={x:groupCenter.x-(bounds.maxX+bounds.minX)/2,y:groupCenter.y-(bounds.maxY+bounds.minY)/2};for(let child of flexBox.children)child.metadata._repositionOnPcb({x:child.position.x+child.size.width/2+offset.x,y:child.position.y+child.size.height/2+offset.y});db.pcb_group.update(group.pcb_group_id,{width:bounds.width,height:bounds.height,center:groupCenter})};function createSchematicTraceSolverInputProblem(group){let{db}=group.root,sckToSourceNet=new Map,sckToUserNetId=new Map,allScks=new Set,displayLabelTraces=group.selectAll("trace").filter(t6=>t6._parsedProps?.schDisplayLabel),childGroups=group.selectAll("group"),allSchematicGroupIds=[group.schematic_group_id,...childGroups.map(a3=>a3.schematic_group_id)],schematicComponents=db.schematic_component.list().filter(a3=>allSchematicGroupIds.includes(a3.schematic_group_id)),chips=[],pinIdToSchematicPortId=new Map,schematicPortIdToPinId=new Map;for(let schematicComponent of schematicComponents){let chipId=schematicComponent.schematic_component_id,pins=[],sourceComponent=db.source_component.getWhere({source_component_id:schematicComponent.source_component_id}),schematicPorts=db.schematic_port.list({schematic_component_id:schematicComponent.schematic_component_id});for(let schematicPort of schematicPorts){let pinId=`${sourceComponent?.name??schematicComponent.schematic_component_id}.${schematicPort.pin_number}`;pinIdToSchematicPortId.set(pinId,schematicPort.schematic_port_id),schematicPortIdToPinId.set(schematicPort.schematic_port_id,pinId)}for(let schematicPort of schematicPorts){let pinId=schematicPortIdToPinId.get(schematicPort.schematic_port_id);pins.push({pinId,x:schematicPort.center.x,y:schematicPort.center.y})}chips.push({chipId,center:schematicComponent.center,width:schematicComponent.size.width,height:schematicComponent.size.height,pins})}let allSourceAndSchematicPortIdsInScope=new Set,schPortIdToSourcePortId=new Map,sourcePortIdToSchPortId=new Map,userNetIdToSck=new Map;for(let sc2 of schematicComponents){let ports=db.schematic_port.list({schematic_component_id:sc2.schematic_component_id});for(let sp2 of ports)allSourceAndSchematicPortIdsInScope.add(sp2.schematic_port_id),sp2.source_port_id&&(schPortIdToSourcePortId.set(sp2.schematic_port_id,sp2.source_port_id),sourcePortIdToSchPortId.set(sp2.source_port_id,sp2.schematic_port_id))}let allowedSubcircuitIds=new Set;group.subcircuit_id&&allowedSubcircuitIds.add(group.subcircuit_id);for(let cg of childGroups)cg.subcircuit_id&&allowedSubcircuitIds.add(cg.subcircuit_id);let externalNetIds=db.source_trace.list().filter(st3=>{if(st3.subcircuit_id===group.subcircuit_id)return!0;for(let source_port_id of st3.connected_source_port_ids)if(sourcePortIdToSchPortId.has(source_port_id))return!0;return!1}).flatMap(st3=>st3.connected_source_net_ids);for(let netId of externalNetIds){let net=db.source_net.get(netId);net?.subcircuit_id&&allowedSubcircuitIds.add(net.subcircuit_id)}let directConnections=[],pairKeyToSourceTraceId=new Map;for(let st3 of db.source_trace.list()){if(st3.subcircuit_id&&!allowedSubcircuitIds.has(st3.subcircuit_id))continue;let connected=(st3.connected_source_port_ids??[]).map(srcId=>sourcePortIdToSchPortId.get(srcId)).filter(sourcePortId=>!!sourcePortId&&allSourceAndSchematicPortIdsInScope.has(sourcePortId));if(connected.length>=2){let[a3,b3]=connected.slice(0,2),pairKey=[a3,b3].sort().join("::");if(!pairKeyToSourceTraceId.has(pairKey)){pairKeyToSourceTraceId.set(pairKey,st3.source_trace_id);let userNetId=st3.display_name??st3.source_trace_id;st3.subcircuit_connectivity_map_key&&(allScks.add(st3.subcircuit_connectivity_map_key),userNetIdToSck.set(userNetId,st3.subcircuit_connectivity_map_key),sckToUserNetId.set(st3.subcircuit_connectivity_map_key,userNetId)),directConnections.push({pinIds:[a3,b3].map(id=>schematicPortIdToPinId.get(id)),netId:userNetId})}}}let netConnections=[];for(let net of db.source_net.list().filter(n3=>!n3.subcircuit_id||allowedSubcircuitIds.has(n3.subcircuit_id)))net.subcircuit_connectivity_map_key&&(allScks.add(net.subcircuit_connectivity_map_key),sckToSourceNet.set(net.subcircuit_connectivity_map_key,net));let sckToPinIds=new Map;for(let[schId,srcPortId]of schPortIdToSourcePortId){let sp2=db.source_port.get(srcPortId);if(!sp2?.subcircuit_connectivity_map_key)continue;let sck=sp2.subcircuit_connectivity_map_key;allScks.add(sck),sckToPinIds.has(sck)||sckToPinIds.set(sck,[]),sckToPinIds.get(sck).push(schId)}for(let[subcircuitConnectivityKey,schematicPortIds]of sckToPinIds){let sourceNet=sckToSourceNet.get(subcircuitConnectivityKey);if(sourceNet&&schematicPortIds.length>=2){let userNetId=String(sourceNet.name||sourceNet.source_net_id||subcircuitConnectivityKey);userNetIdToSck.set(userNetId,subcircuitConnectivityKey),sckToUserNetId.set(subcircuitConnectivityKey,userNetId);let charWidth=.1*(.18/.18),netLabelWidth=Number((String(userNetId).length*charWidth).toFixed(2));netConnections.push({netId:userNetId,pinIds:schematicPortIds.map(portId=>schematicPortIdToPinId.get(portId)),netLabelWidth})}}let availableNetLabelOrientations=(()=>{let netToAllowedOrientations={},presentNetIds=new Set(netConnections.map(nc2=>nc2.netId));for(let net of db.source_net.list().filter(n3=>!n3.subcircuit_id||allowedSubcircuitIds.has(n3.subcircuit_id)))net.name&&presentNetIds.has(net.name)&&(net.is_ground||net.name.toLowerCase().startsWith("gnd")?netToAllowedOrientations[net.name]=["y-"]:net.is_power||net.name.toLowerCase().startsWith("v")?netToAllowedOrientations[net.name]=["y+"]:netToAllowedOrientations[net.name]=["x-","x+"]);return netToAllowedOrientations})();return{inputProblem:{chips,directConnections,netConnections,availableNetLabelOrientations,maxMspPairDistance:group._parsedProps.schMaxTraceDistance??2.4},pinIdToSchematicPortId,pairKeyToSourceTraceId,sckToSourceNet,sckToUserNetId,userNetIdToSck,allSourceAndSchematicPortIdsInScope,schPortIdToSourcePortId,displayLabelTraces,allScks}}var TOL=1e-6;function isHorizontalEdge(edge){let dx2=Math.abs(edge.to.x-edge.from.x),dy2=Math.abs(edge.to.y-edge.from.y);return dx2>=dy2}function length6(a3,b3){return Math.hypot(b3.x-a3.x,b3.y-a3.y)}function pointAt(a3,b3,t6){return{x:a3.x+(b3.x-a3.x)*t6,y:a3.y+(b3.y-a3.y)*t6}}function paramAlong(a3,b3,p4){let L5=length6(a3,b3);if(L5<TOL)return 0;let t6=((p4.x-a3.x)*(b3.x-a3.x)+(p4.y-a3.y)*(b3.y-a3.y))/((b3.x-a3.x)*(b3.x-a3.x)+(b3.y-a3.y)*(b3.y-a3.y));return Math.max(0,Math.min(1,t6))*L5}function cross2(ax2,ay2,bx2,by2){return ax2*by2-ay2*bx2}function segmentIntersection(p12,p22,q12,q22){let r4={x:p22.x-p12.x,y:p22.y-p12.y},s4={x:q22.x-q12.x,y:q22.y-q12.y},rxs=cross2(r4.x,r4.y,s4.x,s4.y),q_p={x:q12.x-p12.x,y:q12.y-p12.y},q_pxr=cross2(q_p.x,q_p.y,r4.x,r4.y);if(Math.abs(rxs)<TOL&&Math.abs(q_pxr)<TOL||Math.abs(rxs)<TOL&&Math.abs(q_pxr)>=TOL)return null;let t6=cross2(q_p.x,q_p.y,s4.x,s4.y)/rxs,u4=cross2(q_p.x,q_p.y,r4.x,r4.y)/rxs;return t6<-TOL||t6>1+TOL||u4<-TOL||u4>1+TOL?null:{x:p12.x+t6*r4.x,y:p12.y+t6*r4.y}}function mergeIntervals(intervals,tol=TOL){if(intervals.length===0)return intervals;intervals.sort((a3,b3)=>a3.start-b3.start);let merged=[],cur={...intervals[0]};for(let i3=1;i3<intervals.length;i3++){let nxt=intervals[i3];nxt.start<=cur.end+tol?cur.end=Math.max(cur.end,nxt.end):(merged.push(cur),cur={...nxt})}return merged.push(cur),merged}function splitEdgeByCrossings(edge,crossingDistances,crossLen){let L5=length6(edge.from,edge.to);if(L5<TOL||crossingDistances.length===0)return[edge];let half=crossLen/2,rawIntervals=crossingDistances.map(d2=>({start:Math.max(0,d2-half),end:Math.min(L5,d2+half)})).filter(iv=>iv.end-iv.start>TOL),intervals=mergeIntervals(rawIntervals),result=[],cursor=0,dir={x:edge.to.x-edge.from.x,y:edge.to.y-edge.from.y},addSeg=(d02,d12,isCrossing)=>{if(d12-d02<=TOL)return;let t02=d02/L5,t12=d12/L5;result.push({from:pointAt(edge.from,edge.to,t02),to:pointAt(edge.from,edge.to,t12),...isCrossing?{is_crossing:!0}:{}})};for(let iv of intervals)iv.start-cursor>TOL&&addSeg(cursor,iv.start,!1),addSeg(iv.start,iv.end,!0),cursor=iv.end;return L5-cursor>TOL&&addSeg(cursor,L5,!1),result.length>0?result:[edge]}function computeCrossings(traces,opts={}){let crossLen=opts.crossSegmentLength??.075,tol=opts.tolerance??TOL,crossingsByEdge=new Map,keyOf=ref=>`${ref.traceIdx}:${ref.edgeIdx}`,getEdge=ref=>traces[ref.traceIdx].edges[ref.edgeIdx];for(let ti3=0;ti3<traces.length;ti3++){let A4=traces[ti3];for(let ei3=0;ei3<A4.edges.length;ei3++){let eA=A4.edges[ei3];for(let tj=ti3;tj<traces.length;tj++){let B4=traces[tj];for(let ej=tj===ti3?ei3+1:0;ej<B4.edges.length;ej++){let eB=B4.edges[ej],P4=segmentIntersection(eA.from,eA.to,eB.from,eB.to);if(!P4)continue;let LA=length6(eA.from,eA.to),LB=length6(eB.from,eB.to);if(LA<tol||LB<tol)continue;let dA=paramAlong(eA.from,eA.to,P4),dB=paramAlong(eB.from,eB.to,P4),nearEndpointA=dA<=tol||Math.abs(LA-dA)<=tol||Number.isNaN(dA),nearEndpointB=dB<=tol||Math.abs(LB-dB)<=tol||Number.isNaN(dB);if(!nearEndpointA&&!nearEndpointB){let aIsHorizontal=isHorizontalEdge(eA),bIsHorizontal=isHorizontalEdge(eB),assignToA;if(aIsHorizontal!==bIsHorizontal)assignToA=aIsHorizontal;else{let ax2=Math.abs(eA.to.x-eA.from.x),ay2=Math.abs(eA.to.y-eA.from.y),bx2=Math.abs(eB.to.x-eB.from.x),by2=Math.abs(eB.to.y-eB.from.y),aScore=ax2-ay2,bScore=bx2-by2;assignToA=aScore===bScore?!0:aScore>bScore}let chosenKey=keyOf({traceIdx:assignToA?ti3:tj,edgeIdx:assignToA?ei3:ej}),chosenList=crossingsByEdge.get(chosenKey)??[];chosenList.push(assignToA?dA:dB),crossingsByEdge.set(chosenKey,chosenList)}}}}}let out=traces.map(t6=>({source_trace_id:t6.source_trace_id,edges:[]}));for(let ti3=0;ti3<traces.length;ti3++){let trace=traces[ti3];for(let ei3=0;ei3<trace.edges.length;ei3++){let eRefKey=keyOf({traceIdx:ti3,edgeIdx:ei3}),splittingDistances=crossingsByEdge.get(eRefKey)??[];if(splittingDistances.length===0){out[ti3].edges.push(trace.edges[ei3]);continue}let uniqueSorted=Array.from(new Set(splittingDistances.map(d2=>Number(d2.toFixed(6))))).sort((a3,b3)=>a3-b3),split=splitEdgeByCrossings(trace.edges[ei3],uniqueSorted,crossLen);out[ti3].edges.push(...split)}}return out}var TOL2=1e-6;function nearlyEqual(a3,b3,tol=TOL2){return Math.abs(a3-b3)<=tol}function pointEq(a3,b3,tol=TOL2){return nearlyEqual(a3.x,b3.x,tol)&&nearlyEqual(a3.y,b3.y,tol)}function onSegment4(p4,a3,b3,tol=TOL2){let minX=Math.min(a3.x,b3.x)-tol,maxX=Math.max(a3.x,b3.x)+tol,minY=Math.min(a3.y,b3.y)-tol,maxY=Math.max(a3.y,b3.y)+tol;return p4.x<minX||p4.x>maxX||p4.y<minY||p4.y>maxY?!1:Math.abs((b3.x-a3.x)*(p4.y-a3.y)-(b3.y-a3.y)*(p4.x-a3.x))<=tol}function dedupePoints(points,tol=TOL2){let map=new Map;for(let p4 of points){let key=`${p4.x.toFixed(6)},${p4.y.toFixed(6)}`;map.has(key)||map.set(key,p4)}return Array.from(map.values())}function edgeVec(e4){return{x:e4.to.x-e4.from.x,y:e4.to.y-e4.from.y}}function isParallel(e12,e22,tol=TOL2){let v12=edgeVec(e12),v22=edgeVec(e22),L12=Math.hypot(v12.x,v12.y),L22=Math.hypot(v22.x,v22.y);if(L12<tol||L22<tol)return!0;let cross22=v12.x*v22.y-v12.y*v22.x;return Math.abs(cross22)<=tol*L12*L22}function incidentEdgesAtPoint(trace,p4,tol=TOL2){return trace.edges.filter(e4=>pointEq(e4.from,p4,tol)||pointEq(e4.to,p4,tol))}function nearestEndpointOnTrace(trace,p4,tol=TOL2){for(let e4 of trace.edges){if(pointEq(e4.from,p4,tol))return e4.from;if(pointEq(e4.to,p4,tol))return e4.to}return null}function edgeDirectionFromPoint(e4,p4,tol=TOL2){let other=pointEq(e4.from,p4,tol)||nearlyEqual(e4.from.x,p4.x,tol)&&nearlyEqual(e4.from.y,p4.y,tol)?e4.to:e4.from,dx2=other.x-p4.x,dy2=other.y-p4.y;return Math.abs(dx2)<tol&&Math.abs(dy2)<tol?null:Math.abs(dx2)>=Math.abs(dy2)?dx2>=0?"right":"left":dy2>=0?"up":"down"}function getCornerOrientationAtPoint(trace,p4,tol=TOL2){let incident=incidentEdgesAtPoint(trace,p4,tol);if(incident.length<2)return null;let dirs=incident.map(e4=>edgeDirectionFromPoint(e4,p4,tol)),hasUp=dirs.includes("up"),hasDown=dirs.includes("down"),hasLeft=dirs.includes("left"),hasRight=dirs.includes("right"),vertical=hasUp?"up":hasDown?"down":null,horizontal=hasRight?"right":hasLeft?"left":null;return vertical&&horizontal?`${vertical}-${horizontal}`:null}function computeJunctions(traces,opts={}){let tol=opts.tolerance??TOL2,result={};for(let t6 of traces)result[t6.source_trace_id]=[];let endpointsByTrace=traces.map(t6=>{let pts=[];for(let e4 of t6.edges)pts.push(e4.from,e4.to);return dedupePoints(pts,tol)});for(let i3=0;i3<traces.length;i3++){let A4=traces[i3],AEnds=endpointsByTrace[i3];for(let j3=i3+1;j3<traces.length;j3++){let B4=traces[j3],BEnds=endpointsByTrace[j3];for(let pa2 of AEnds)for(let pb2 of BEnds)if(pointEq(pa2,pb2,tol)){let aEdgesAtP=incidentEdgesAtPoint(A4,pa2,tol),bEdgesAtP=incidentEdgesAtPoint(B4,pb2,tol),hasCorner=aEdgesAtP.some(eA=>bEdgesAtP.some(eB=>!isParallel(eA,eB,tol))),aCorner=getCornerOrientationAtPoint(A4,pa2,tol),bCorner=getCornerOrientationAtPoint(B4,pb2,tol);hasCorner&&!(aCorner!==null&&bCorner!==null&&aCorner===bCorner)&&(result[A4.source_trace_id].push(pa2),A4.source_trace_id!==B4.source_trace_id&&result[B4.source_trace_id].push(pb2))}for(let pa2 of AEnds)for(let eB of B4.edges)if(onSegment4(pa2,eB.from,eB.to,tol)){let hasCorner=incidentEdgesAtPoint(A4,pa2,tol).some(eA=>!isParallel(eA,eB,tol)),aCorner=getCornerOrientationAtPoint(A4,pa2,tol),bEndpointNearPa=nearestEndpointOnTrace(B4,pa2,tol*1e3),bCorner=bEndpointNearPa?getCornerOrientationAtPoint(B4,bEndpointNearPa,tol):null;hasCorner&&!(aCorner!==null&&bCorner!==null&&aCorner===bCorner)&&(result[A4.source_trace_id].push(pa2),A4.source_trace_id!==B4.source_trace_id&&result[B4.source_trace_id].push(pa2))}for(let pb2 of BEnds)for(let eA of A4.edges)if(onSegment4(pb2,eA.from,eA.to,tol)){let hasCorner=incidentEdgesAtPoint(B4,pb2,tol).some(eB=>!isParallel(eA,eB,tol)),bCorner=getCornerOrientationAtPoint(B4,pb2,tol),aEndpointNearPb=nearestEndpointOnTrace(A4,pb2,tol*1e3),aCorner=aEndpointNearPb?getCornerOrientationAtPoint(A4,aEndpointNearPb,tol):null;hasCorner&&!(aCorner!==null&&bCorner!==null&&aCorner===bCorner)&&(result[B4.source_trace_id].push(pb2),A4.source_trace_id!==B4.source_trace_id&&result[A4.source_trace_id].push(pb2))}}}for(let id of Object.keys(result))result[id]=dedupePoints(result[id],tol);return result}var debug7=(0,import_debug15.default)("Group_doInitialSchematicTraceRender");function applyTracesFromSolverOutput(args){let{group,solver,pinIdToSchematicPortId,userNetIdToSck}=args,{db}=group.root,traces=solver.traceCleanupSolver?.getOutput().traces??solver.traceLabelOverlapAvoidanceSolver?.getOutput().traces??solver.schematicTraceLinesSolver?.solvedTracePaths,pendingTraces=[];debug7(`Traces inside SchematicTraceSolver output: ${(traces??[]).length}`);for(let solvedTracePath of traces??[]){let points=solvedTracePath?.tracePath;if(!Array.isArray(points)||points.length<2){debug7(`Skipping trace ${solvedTracePath?.pinIds.join(",")} because it has less than 2 points`);continue}let edges=[];for(let i3=0;i3<points.length-1;i3++)edges.push({from:{x:points[i3].x,y:points[i3].y},to:{x:points[i3+1].x,y:points[i3+1].y}});let source_trace_id=null,subcircuit_connectivity_map_key;if(Array.isArray(solvedTracePath?.pins)&&solvedTracePath.pins.length===2){let pA=pinIdToSchematicPortId.get(solvedTracePath.pins[0]?.pinId),pB=pinIdToSchematicPortId.get(solvedTracePath.pins[1]?.pinId);if(pA&&pB){for(let schPid of[pA,pB])db.schematic_port.get(schPid)&&db.schematic_port.update(schPid,{is_connected:!0});subcircuit_connectivity_map_key=userNetIdToSck.get(String(solvedTracePath.userNetId))}}source_trace_id||(source_trace_id=`solver_${solvedTracePath?.mspPairId}`,subcircuit_connectivity_map_key=userNetIdToSck.get(String(solvedTracePath.userNetId))),pendingTraces.push({source_trace_id,edges,subcircuit_connectivity_map_key})}debug7(`Applying ${pendingTraces.length} traces from SchematicTraceSolver output`);let withCrossings=computeCrossings(pendingTraces.map(t6=>({source_trace_id:t6.source_trace_id,edges:t6.edges}))),junctionsById=computeJunctions(withCrossings);for(let t6 of withCrossings)db.schematic_trace.insert({source_trace_id:t6.source_trace_id,edges:t6.edges,junctions:junctionsById[t6.source_trace_id]??[],subcircuit_connectivity_map_key:pendingTraces.find(p4=>p4.source_trace_id===t6.source_trace_id)?.subcircuit_connectivity_map_key})}var oppositeSide2=input2=>{switch(input2){case"x+":return"left";case"x-":return"right";case"y+":return"bottom";case"y-":return"top";case"left":return"right";case"top":return"bottom";case"right":return"left";case"bottom":return"top"}},getNetNameFromPorts=ports=>{for(let port of ports){let traces=port._getDirectlyConnectedTraces();for(let trace of traces){let displayLabel=trace._parsedProps.schDisplayLabel;if(displayLabel)return{name:displayLabel,wasAssignedDisplayLabel:!0}}}return{name:ports.map(p4=>p4._getNetLabelText()).join("/"),wasAssignedDisplayLabel:!1}},debug8=(0,import_debug16.default)("Group_doInitialSchematicTraceRender");function applyNetLabelPlacements(args){let{group,solver,sckToSourceNet,allScks,allSourceAndSchematicPortIdsInScope,schPortIdToSourcePortId,userNetIdToSck,pinIdToSchematicPortId,schematicPortIdsWithPreExistingNetLabels,schematicPortIdsWithRoutedTraces}=args,{db}=group.root,netLabelPlacements=solver.netLabelPlacementSolver?.netLabelPlacements??solver.traceLabelOverlapAvoidanceSolver?.getOutput().netLabelPlacements??[],globalConnMap=solver.mspConnectionPairSolver.globalConnMap;for(let placement of netLabelPlacements){debug8(`processing placement: ${placement.netId}`);let placementUserNetId=globalConnMap.getIdsConnectedToNet(placement.globalConnNetId).find(id=>userNetIdToSck.get(id)),placementSck=userNetIdToSck.get(placementUserNetId),anchor_position=placement.anchorPoint,orientation4=placement.orientation,anchor_side=oppositeSide2(orientation4),sourceNet=placementSck?sckToSourceNet.get(placementSck):void 0,schPortIds=placement.pinIds.map(pinId=>pinIdToSchematicPortId.get(pinId));if(schPortIds.some(schPortId=>schematicPortIdsWithPreExistingNetLabels.has(schPortId))){debug8(`skipping net label placement for "${placement.netId}" REASON:schematic port has pre-existing net label`);continue}if(sourceNet){let text2=sourceNet.name,center22=computeSchematicNetLabelCenter({anchor_position,anchor_side,text:text2});db.schematic_net_label.insert({text:text2,anchor_position,center:center22,anchor_side,...sourceNet?.source_net_id?{source_net_id:sourceNet.source_net_id}:{}});continue}let ports=group.selectAll("port").filter(p4=>p4._getSubcircuitConnectivityKey()===placementSck),{name:text,wasAssignedDisplayLabel}=getNetNameFromPorts(ports);if(!wasAssignedDisplayLabel&&schPortIds.some(schPortId=>schematicPortIdsWithRoutedTraces.has(schPortId))){debug8(`skipping net label placement for "${placement.netId}" REASON:schematic port has routed traces and no display label`);continue}let center2=computeSchematicNetLabelCenter({anchor_position,anchor_side,text});db.schematic_net_label.insert({text,anchor_position,center:center2,anchor_side})}}var insertNetLabelsForPortsMissingTrace=({allSourceAndSchematicPortIdsInScope,group,schPortIdToSourcePortId,sckToSourceNet:connKeyToNet,pinIdToSchematicPortId,schematicPortIdsWithPreExistingNetLabels})=>{let{db}=group.root;for(let schOrSrcPortId of Array.from(allSourceAndSchematicPortIdsInScope)){let schPort=db.schematic_port.get(schOrSrcPortId);if(!schPort||schPort.is_connected)continue;let srcPortId=schPortIdToSourcePortId.get(schOrSrcPortId);if(!srcPortId)continue;let key=db.source_port.get(srcPortId)?.subcircuit_connectivity_map_key;if(!key)continue;let sourceNet=connKeyToNet.get(key);if(!sourceNet||db.schematic_net_label.list().some(nl2=>Math.abs(nl2.anchor_position.x-schPort.center.x)<.1&&Math.abs(nl2.anchor_position.y-schPort.center.y)<.1?sourceNet.source_net_id&&nl2.source_net_id?nl2.source_net_id===sourceNet.source_net_id:nl2.text===(sourceNet.name||key):!1))continue;let text=sourceNet.name||sourceNet.source_net_id||key,side=getEnteringEdgeFromDirection(schPort.facing_direction||"right")||"right",center2=computeSchematicNetLabelCenter({anchor_position:schPort.center,anchor_side:side,text});db.schematic_net_label.insert({text,anchor_position:schPort.center,center:center2,anchor_side:side,...sourceNet.source_net_id?{source_net_id:sourceNet.source_net_id}:{}})}},getSchematicPortIdsWithAssignedNetLabels=group=>{let schematicPortIdsWithNetLabels=new Set,netLabels=group.selectAll("netlabel");for(let netLabel of netLabels){let netLabelPorts=netLabel._getConnectedPorts();for(let port of netLabelPorts)port.schematic_port_id&&schematicPortIdsWithNetLabels.add(port.schematic_port_id)}return schematicPortIdsWithNetLabels},getSchematicPortIdsWithRoutedTraces=({solver,pinIdToSchematicPortId})=>{let solvedTraces=solver.schematicTraceLinesSolver.solvedTracePaths,schematicPortIdsWithRoutedTraces=new Set;for(let solvedTrace of solvedTraces)for(let pinId of solvedTrace.pinIds){let schPortId=pinIdToSchematicPortId.get(pinId);schPortId&&schematicPortIdsWithRoutedTraces.add(schPortId)}return schematicPortIdsWithRoutedTraces},debug9=(0,import_debug14.default)("Group_doInitialSchematicTraceRender"),Group_doInitialSchematicTraceRender=group=>{if(!group.root?._featureMspSchematicTraceRouting||!group.isSubcircuit||group.root?.schematicDisabled)return;let{inputProblem,pinIdToSchematicPortId,pairKeyToSourceTraceId,sckToSourceNet,allSourceAndSchematicPortIdsInScope,schPortIdToSourcePortId,displayLabelTraces,allScks,userNetIdToSck}=createSchematicTraceSolverInputProblem(group),schematicPortIdsWithPreExistingNetLabels=getSchematicPortIdsWithAssignedNetLabels(group);debug9.enabled&&group.root?.emit("debug:logOutput",{type:"debug:logOutput",name:"group-trace-render-input-problem",content:JSON.stringify(inputProblem,null,2)});let solver=new SchematicTracePipelineSolver(inputProblem);solver.solve();let schematicPortIdsWithRoutedTraces=getSchematicPortIdsWithRoutedTraces({solver,pinIdToSchematicPortId});applyTracesFromSolverOutput({group,solver,pinIdToSchematicPortId,userNetIdToSck}),applyNetLabelPlacements({group,solver,sckToSourceNet,allSourceAndSchematicPortIdsInScope,schPortIdToSourcePortId,pinIdToSchematicPortId,allScks,userNetIdToSck,schematicPortIdsWithPreExistingNetLabels,schematicPortIdsWithRoutedTraces}),insertNetLabelsForPortsMissingTrace({group,allSourceAndSchematicPortIdsInScope,schPortIdToSourcePortId,sckToSourceNet,pinIdToSchematicPortId,schematicPortIdsWithPreExistingNetLabels})},getSpiceyEngine=()=>({async simulate(spiceString){let simulation_experiment_id="spice-experiment-1",{circuit:parsedCircuit,tran}=simulate(spiceString);return{simulationResultCircuitJson:spiceyTranToVGraphs(tran,parsedCircuit,simulation_experiment_id)}}}),SIMULATION_COLOR_PALETTE=["rgb(132, 0, 0)","rgb(194, 194, 0)","rgb(194, 0, 194)","rgb(194, 0, 0)","rgb(0, 132, 132)","rgb(0, 132, 0)","rgb(0, 0, 132)","rgb(132, 132, 132)","rgb(132, 0, 132)","rgb(194, 194, 194)","rgb(132, 0, 132)","rgb(132, 0, 0)","rgb(132, 132, 0)","rgb(194, 194, 194)","rgb(0, 0, 132)","rgb(0, 132, 0)"],idToColorMap=new Map,colorIndex=0;function getSimulationColorForId(id){if(idToColorMap.has(id))return idToColorMap.get(id);let color=SIMULATION_COLOR_PALETTE[colorIndex];return colorIndex=(colorIndex+1)%SIMULATION_COLOR_PALETTE.length,idToColorMap.set(id,color),color}function resetSimulationColorState(){idToColorMap.clear(),colorIndex=0}var debug10=(0,import_debug17.default)("tscircuit:core:Group_doInitialSimulationSpiceEngineRender");function Group_doInitialSimulationSpiceEngineRender(group){if(!group.isSubcircuit)return;let{root}=group;if(!root)return;let analogSims=group.selectAll("analogsimulation");if(analogSims.length===0)return;let voltageProbes=group.selectAll("voltageprobe");resetSimulationColorState();let spiceEngineMap={...root.platform?.spiceEngineMap};spiceEngineMap.spicey||(spiceEngineMap.spicey=getSpiceyEngine());let circuitJson=root.db.toArray(),spiceString,spiceNetlist;try{spiceNetlist=circuitJsonToSpice(circuitJson),spiceString=spiceNetlist.toSpiceString(),debug10(`Generated SPICE string:
600
+ ${spiceString}`)}catch(error){debug10(`Failed to convert circuit JSON to SPICE: ${error}`);return}for(let analogSim of analogSims){let engineName=analogSim._parsedProps.spiceEngine??"spicey",spiceEngine2=spiceEngineMap[engineName];if(!spiceEngine2)throw new Error(`SPICE engine "${engineName}" not found in platform config. Available engines: ${JSON.stringify(Object.keys(spiceEngineMap).filter(k4=>k4!=="spicey"))}`);let effectId=`spice-simulation-${engineName}-${analogSim.source_component_id}`;debug10(`Queueing simulation for spice engine: ${engineName} (id: ${effectId})`),group._queueAsyncEffect(effectId,async()=>{try{debug10(`Running simulation with engine: ${engineName}`);let result=await spiceEngine2.simulate(spiceString);debug10(`Simulation completed, received ${result.simulationResultCircuitJson.length} elements`);let simulationExperiment=root.db.simulation_experiment.list()[0];if(!simulationExperiment){debug10("No simulation experiment found, skipping result insertion");return}for(let element of result.simulationResultCircuitJson){if(element.type==="simulation_transient_voltage_graph"){element.simulation_experiment_id=simulationExperiment.simulation_experiment_id;let probeMatch=voltageProbes.find(p4=>p4.finalProbeName===element.name);probeMatch&&(element.color=probeMatch.color)}let elementType=element.type;elementType&&root.db[elementType]?(root.db[elementType].insert(element),debug10(`Inserted ${elementType} into database`)):(debug10(`Warning: Unknown element type ${elementType}, adding to raw db`),root.db._addElement(element))}group._markDirty("SimulationSpiceEngineRender")}catch(error){debug10(`Simulation failed for engine ${engineName}: ${error}`);let simulationExperiment=root.db.simulation_experiment.list()[0];root.db.simulation_unknown_experiment_error.insert({simulation_experiment_id:simulationExperiment?.simulation_experiment_id,error_type:"simulation_unknown_experiment_error",message:error instanceof Error?error.message:String(error)})}})}}function Group_doInitialPcbComponentAnchorAlignment(group){if(group.root?.pcbDisabled||!group.pcb_group_id)return;let pcbPositionAnchor=group._parsedProps?.pcbPositionAnchor;if(!pcbPositionAnchor)return;let targetPosition=group._getGlobalPcbPositionBeforeLayout(),{pcbX,pcbY}=group._parsedProps;if(pcbX===void 0&&pcbY===void 0)return;let{db}=group.root,pcbGroup=db.pcb_group.get(group.pcb_group_id);if(!pcbGroup)return;let width=pcbGroup.width,height=pcbGroup.height,{center:center2}=pcbGroup;if(pcbGroup.outline&&pcbGroup.outline.length>0){let bounds2=getBoundsFromPoints(pcbGroup.outline);bounds2&&(width=bounds2.maxX-bounds2.minX,height=bounds2.maxY-bounds2.minY)}if(!width||!height)return;let bounds={left:center2.x-width/2,right:center2.x+width/2,top:center2.y+height/2,bottom:center2.y-height/2},currentCenter={...center2},anchorPos=null;if(new Set(["center","top_left","top_center","top_right","center_left","center_right","bottom_left","bottom_center","bottom_right"]).has(pcbPositionAnchor))switch(pcbPositionAnchor){case"center":anchorPos=currentCenter;break;case"top_left":anchorPos={x:bounds.left,y:bounds.top};break;case"top_center":anchorPos={x:currentCenter.x,y:bounds.top};break;case"top_right":anchorPos={x:bounds.right,y:bounds.top};break;case"center_left":anchorPos={x:bounds.left,y:currentCenter.y};break;case"center_right":anchorPos={x:bounds.right,y:currentCenter.y};break;case"bottom_left":anchorPos={x:bounds.left,y:bounds.bottom};break;case"bottom_center":anchorPos={x:currentCenter.x,y:bounds.bottom};break;case"bottom_right":anchorPos={x:bounds.right,y:bounds.bottom};break}if(!anchorPos)return;let newCenter={...currentCenter};targetPosition.x!==void 0&&(newCenter.x+=targetPosition.x-anchorPos.x),targetPosition.y!==void 0&&(newCenter.y+=targetPosition.y-anchorPos.y),(Math.abs(newCenter.x-currentCenter.x)>1e-6||Math.abs(newCenter.y-currentCenter.y)>1e-6)&&(group._repositionOnPcb(newCenter),db.pcb_group.update(group.pcb_group_id,{center:newCenter})),db.pcb_group.update(group.pcb_group_id,{anchor_position:targetPosition,anchor_alignment:pcbPositionAnchor,display_offset_x:pcbX,display_offset_y:pcbY})}function computeCenterFromAnchorPosition(anchorPosition,ctx){let{width,height,pcbAnchorAlignment}=ctx;if(!pcbAnchorAlignment)return anchorPosition;let alignment=pcbAnchorAlignment;if(typeof width!="number"||typeof height!="number")return console.log("width or height is not a number"),anchorPosition;let ax2=anchorPosition.x,ay2=anchorPosition.y;switch(alignment){case"top_left":return{x:ax2+width/2,y:ay2-height/2};case"top_center":return{x:ax2,y:ay2-height/2};case"top_right":return{x:ax2-width/2,y:ay2-height/2};case"center_left":return{x:ax2+width/2,y:ay2};case"center_right":return{x:ax2-width/2,y:ay2};case"bottom_left":return{x:ax2+width/2,y:ay2+height/2};case"bottom_center":return{x:ax2,y:ay2+height/2};case"bottom_right":return{x:ax2-width/2,y:ay2+height/2};default:return anchorPosition}}var Group6=class extends NormalComponent3{constructor(){super(...arguments);__publicField(this,"pcb_group_id",null);__publicField(this,"schematic_group_id",null);__publicField(this,"subcircuit_id",null);__publicField(this,"_hasStartedAsyncAutorouting",!1);__publicField(this,"_asyncAutoroutingResult",null);__publicField(this,"unnamedElementCounter",{})}get config(){return{zodProps:groupProps,componentName:"Group"}}doInitialSourceGroupRender(){let{db}=this.root,hasExplicitName=typeof this._parsedProps.name=="string"&&this._parsedProps.name.length>0,source_group2=db.source_group.insert({name:this.name,is_subcircuit:this.isSubcircuit,was_automatically_named:!hasExplicitName});this.source_group_id=source_group2.source_group_id,this.isSubcircuit&&(this.subcircuit_id=`subcircuit_${source_group2.source_group_id}`,db.source_group.update(source_group2.source_group_id,{subcircuit_id:this.subcircuit_id}))}doInitialSourceRender(){let{db}=this.root;for(let child of this.children)db.source_component.update(child.source_component_id,{source_group_id:this.source_group_id})}doInitialSourceParentAttachment(){let{db}=this.root,parentGroup=this.parent?.getGroup?.();if(parentGroup?.source_group_id&&db.source_group.update(this.source_group_id,{parent_source_group_id:parentGroup.source_group_id}),!this.isSubcircuit)return;let parent_subcircuit_id=this.parent?.getSubcircuit?.()?.subcircuit_id;parent_subcircuit_id&&db.source_group.update(this.source_group_id,{parent_subcircuit_id})}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,groupProps2=props,hasOutline=groupProps2.outline&&groupProps2.outline.length>0,numericOutline=hasOutline?groupProps2.outline.map(point23=>({x:distance.parse(point23.x),y:distance.parse(point23.y)})):void 0,ctx=this.props,anchorPosition=this._getGlobalPcbPositionBeforeLayout(),center2=computeCenterFromAnchorPosition(anchorPosition,ctx),pcb_group2=db.pcb_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id??this.getSubcircuit()?.subcircuit_id,name:this.name,anchor_position:anchorPosition,center:center2,...hasOutline?{outline:numericOutline}:{width:0,height:0},pcb_component_ids:[],source_group_id:this.source_group_id,autorouter_configuration:props.autorouter?{trace_clearance:props.autorouter.traceClearance}:void 0,anchor_alignment:props.pcbAnchorAlignment??null});this.pcb_group_id=pcb_group2.pcb_group_id;for(let child of this.children)db.pcb_component.update(child.pcb_component_id,{pcb_group_id:pcb_group2.pcb_group_id})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,props=this._parsedProps,hasOutline=props.outline&&props.outline.length>0;if(this.pcb_group_id){let hasExplicitPositioning=this._parsedProps.pcbX!==void 0||this._parsedProps.pcbY!==void 0;if(hasOutline){let numericOutline=props.outline.map(point23=>({x:distance.parse(point23.x),y:distance.parse(point23.y)})),outlineBounds=getBoundsFromPoints(numericOutline);if(!outlineBounds)return;let centerX2=(outlineBounds.minX+outlineBounds.maxX)/2,centerY2=(outlineBounds.minY+outlineBounds.maxY)/2,center22=hasExplicitPositioning?db.pcb_group.get(this.pcb_group_id)?.center??{x:centerX2,y:centerY2}:{x:centerX2,y:centerY2};db.pcb_group.update(this.pcb_group_id,{center:center22});return}let bounds=getBoundsOfPcbComponents(this.children),width=bounds.width,height=bounds.height,centerX=(bounds.minX+bounds.maxX)/2,centerY=(bounds.minY+bounds.maxY)/2;if(this.isSubcircuit){let{padLeft,padRight,padTop,padBottom}=this._resolvePcbPadding();width+=padLeft+padRight,height+=padTop+padBottom,centerX+=(padRight-padLeft)/2,centerY+=(padTop-padBottom)/2}let center2=hasExplicitPositioning?db.pcb_group.get(this.pcb_group_id)?.center??{x:centerX,y:centerY}:{x:centerX,y:centerY};db.pcb_group.update(this.pcb_group_id,{width:Number(props.width??width),height:Number(props.height??height),center:center2})}}getNextAvailableName(elm){var _a359,_b2;return(_a359=this.unnamedElementCounter)[_b2=elm.lowercaseComponentName]??(_a359[_b2]=1),`unnamed_${elm.lowercaseComponentName}${this.unnamedElementCounter[elm.lowercaseComponentName]++}`}_resolvePcbPadding(){let props=this._parsedProps,layout=props.pcbLayout,getPaddingValue=key=>{let layoutValue=layout?.[key],propsValue=props[key];if(typeof layoutValue=="number")return layoutValue;if(typeof propsValue=="number")return propsValue},generalPadding=getPaddingValue("padding")??0,paddingX=getPaddingValue("paddingX"),paddingY=getPaddingValue("paddingY"),padLeft=getPaddingValue("paddingLeft")??paddingX??generalPadding,padRight=getPaddingValue("paddingRight")??paddingX??generalPadding,padTop=getPaddingValue("paddingTop")??paddingY??generalPadding,padBottom=getPaddingValue("paddingBottom")??paddingY??generalPadding;return{padLeft,padRight,padTop,padBottom}}doInitialCreateTraceHintsFromProps(){let{_parsedProps:props}=this,{db}=this.root,groupProps2=props;if(!this.isSubcircuit)return;let manualTraceHints=groupProps2.manualEdits?.manual_trace_hints;if(manualTraceHints)for(let manualTraceHint of manualTraceHints)this.add(new TraceHint({for:manualTraceHint.pcb_port_selector,offsets:manualTraceHint.offsets}))}doInitialSourceAddConnectivityMapKey(){Group_doInitialSourceAddConnectivityMapKey(this)}_areChildSubcircuitsRouted(){let subcircuitChildren=this.selectAll("group").filter(g4=>g4.isSubcircuit);for(let subcircuitChild of subcircuitChildren)if(subcircuitChild._shouldRouteAsync()&&!subcircuitChild._asyncAutoroutingResult)return!1;return!0}_shouldRouteAsync(){let autorouter=this._getAutorouterConfig();return autorouter.groupMode==="sequential-trace"?!1:!!(autorouter.local&&autorouter.groupMode==="subcircuit"||!autorouter.local)}_hasTracesToRoute(){let debug112=(0,import_debug10.default)("tscircuit:core:_hasTracesToRoute"),traces=this.selectAll("trace");return debug112(`[${this.getString()}] has ${traces.length} traces to route`),traces.length>0}async _runEffectMakeHttpAutoroutingRequest(){let{db}=this.root,debug112=(0,import_debug10.default)("tscircuit:core:_runEffectMakeHttpAutoroutingRequest"),props=this._parsedProps,autorouterConfig2=this._getAutorouterConfig(),serverUrl=autorouterConfig2.serverUrl,serverMode=autorouterConfig2.serverMode,fetchWithDebug=(url,options)=>(debug112("fetching",url),options.headers&&(options.headers["Tscircuit-Core-Version"]=this.root?.getCoreVersion()),fetch(url,options)),pcbAndSourceCircuitJson=this.root.db.toArray().filter(element=>element.type.startsWith("source_")||element.type.startsWith("pcb_"));if(serverMode==="solve-endpoint"){if(this.props.autorouter?.inputFormat==="simplified"){let{autorouting_result:autorouting_result2}=await fetchWithDebug(`${serverUrl}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_simple_route_json:getSimpleRouteJsonFromCircuitJson({db,minTraceWidth:this.props.autorouter?.minTraceWidth??.15,subcircuit_id:this.subcircuit_id}).simpleRouteJson,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(r4=>r4.json());this._asyncAutoroutingResult=autorouting_result2,this._markDirty("PcbTraceRender");return}let{autorouting_result}=await fetchWithDebug(`${serverUrl}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_circuit_json:pcbAndSourceCircuitJson,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(r4=>r4.json());this._asyncAutoroutingResult=autorouting_result,this._markDirty("PcbTraceRender");return}let{autorouting_job}=await fetchWithDebug(`${serverUrl}/autorouting/jobs/create`,{method:"POST",body:JSON.stringify({input_circuit_json:pcbAndSourceCircuitJson,provider:"freerouting",autostart:!0,display_name:this.root?.name,subcircuit_id:this.subcircuit_id,server_cache_enabled:autorouterConfig2.serverCacheEnabled}),headers:{"Content-Type":"application/json"}}).then(r4=>r4.json());for(;;){let{autorouting_job:job}=await fetchWithDebug(`${serverUrl}/autorouting/jobs/get`,{method:"POST",body:JSON.stringify({autorouting_job_id:autorouting_job.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(r4=>r4.json());if(job.is_finished){let{autorouting_job_output}=await fetchWithDebug(`${serverUrl}/autorouting/jobs/get_output`,{method:"POST",body:JSON.stringify({autorouting_job_id:autorouting_job.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(r4=>r4.json());this._asyncAutoroutingResult={output_pcb_traces:autorouting_job_output.output_pcb_traces},this._markDirty("PcbTraceRender");break}if(job.has_error){let err=new AutorouterError(`Autorouting job failed: ${JSON.stringify(job.error)}`);throw db.pcb_autorouting_error.insert({pcb_error_id:autorouting_job.autorouting_job_id,error_type:"pcb_autorouting_error",message:err.message}),err}await new Promise(resolve=>setTimeout(resolve,100))}}async _runLocalAutorouting(){let{db}=this.root,props=this._parsedProps,debug112=(0,import_debug10.default)("tscircuit:core:_runLocalAutorouting");debug112(`[${this.getString()}] starting local autorouting`);let autorouterConfig2=this._getAutorouterConfig(),isLaserPrefabPreset=this._isLaserPrefabAutorouter(autorouterConfig2),isSingleLayerBoard=this._getSubcircuitLayerCount()===1,{simpleRouteJson}=getSimpleRouteJsonFromCircuitJson({db,minTraceWidth:this.props.autorouter?.minTraceWidth??.15,subcircuit_id:this.subcircuit_id});if(debug112.enabled&&global.debugOutputArray?.push({name:`simpleroutejson-${this.props.name}.json`,obj:simpleRouteJson}),debug112.enabled){let graphicsObject=$e2(simpleRouteJson);graphicsObject.title=`autorouting-${this.props.name}`,global.debugGraphics?.push(graphicsObject)}this.root?.emit("autorouting:start",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),simpleRouteJson});let autorouter;autorouterConfig2.algorithmFn?autorouter=await autorouterConfig2.algorithmFn(simpleRouteJson):autorouter=new CapacityMeshAutorouter(simpleRouteJson,{capacityDepth:this.props.autorouter?.capacityDepth,targetMinCapacity:this.props.autorouter?.targetMinCapacity,useAssignableViaSolver:isLaserPrefabPreset||isSingleLayerBoard,onSolverStarted:({solverName,solverParams})=>this.root?.emit("solver:started",{type:"solver:started",solverName,solverParams,componentName:this.getString()})});let routingPromise=new Promise((resolve,reject)=>{autorouter.on("complete",event=>{debug112(`[${this.getString()}] local autorouting complete`),resolve(event.traces)}),autorouter.on("error",event=>{debug112(`[${this.getString()}] local autorouting error: ${event.error.message}`),reject(event.error)})});autorouter.on("progress",event=>{this.root?.emit("autorouting:progress",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),...event})}),autorouter.start();try{let traces=await routingPromise;this._asyncAutoroutingResult={output_pcb_traces:traces},this._markDirty("PcbTraceRender")}catch(error){let{db:db2}=this.root;throw db2.pcb_autorouting_error.insert({pcb_error_id:`pcb_autorouter_error_subcircuit_${this.subcircuit_id}`,error_type:"pcb_autorouting_error",message:error instanceof Error?error.message:String(error)}),this.root?.emit("autorouting:error",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),error:{message:error instanceof Error?error.message:String(error)},simpleRouteJson}),error}finally{autorouter.stop()}}_startAsyncAutorouting(){this._hasStartedAsyncAutorouting||(this._hasStartedAsyncAutorouting=!0,this._getAutorouterConfig().local?this._queueAsyncEffect("capacity-mesh-autorouting",async()=>this._runLocalAutorouting()):this._queueAsyncEffect("make-http-autorouting-request",async()=>this._runEffectMakeHttpAutoroutingRequest()))}doInitialPcbTraceRender(){let debug112=(0,import_debug10.default)("tscircuit:core:doInitialPcbTraceRender");if(this.isSubcircuit&&!this.root?.pcbDisabled&&!this.getInheritedProperty("routingDisabled")&&!this._shouldUseTraceByTraceRouting()){if(!this._areChildSubcircuitsRouted()){debug112(`[${this.getString()}] child subcircuits are not routed, skipping async autorouting until subcircuits routed`);return}debug112(`[${this.getString()}] no child subcircuits to wait for, initiating async routing`),this._hasTracesToRoute()&&this._startAsyncAutorouting()}}doInitialSchematicTraceRender(){Group_doInitialSchematicTraceRender(this)}updatePcbTraceRender(){let debug112=(0,import_debug10.default)("tscircuit:core:updatePcbTraceRender");if(debug112(`[${this.getString()}] updating...`),!this.isSubcircuit)return;if(this._shouldRouteAsync()&&this._hasTracesToRoute()&&!this._hasStartedAsyncAutorouting){this._areChildSubcircuitsRouted()&&(debug112(`[${this.getString()}] child subcircuits are now routed, starting async autorouting`),this._startAsyncAutorouting());return}if(!this._asyncAutoroutingResult||this._shouldUseTraceByTraceRouting())return;let{db}=this.root;if(this._asyncAutoroutingResult.output_simple_route_json){debug112(`[${this.getString()}] updating PCB traces from simple route json (${this._asyncAutoroutingResult.output_simple_route_json.traces?.length} traces)`),this._updatePcbTraceRenderFromSimpleRouteJson();return}if(this._asyncAutoroutingResult.output_pcb_traces){debug112(`[${this.getString()}] updating PCB traces from ${this._asyncAutoroutingResult.output_pcb_traces.length} traces`),this._updatePcbTraceRenderFromPcbTraces();return}}_updatePcbTraceRenderFromSimpleRouteJson(){let{db}=this.root,{traces:routedTraces}=this._asyncAutoroutingResult.output_simple_route_json;if(routedTraces)for(let routedTrace of routedTraces){let pcb_trace2=db.pcb_trace.insert({subcircuit_id:this.subcircuit_id,route:routedTrace.route})}}_updatePcbTraceRenderFromPcbTraces(){let{output_pcb_traces}=this._asyncAutoroutingResult;if(!output_pcb_traces)return;let{db}=this.root,pcbStyle2=this.getInheritedMergedProperty("pcbStyle"),{holeDiameter,padDiameter}=getViaDiameterDefaults(pcbStyle2);for(let pcb_trace2 of output_pcb_traces)if(pcb_trace2.type==="pcb_trace"){if(pcb_trace2.subcircuit_id=this.subcircuit_id,pcb_trace2.connection_name){let sourceTraceId=pcb_trace2.connection_name;pcb_trace2.source_trace_id=sourceTraceId}db.pcb_trace.insert(pcb_trace2)}for(let pcb_trace2 of output_pcb_traces)if(pcb_trace2.type!=="pcb_via"&&pcb_trace2.type==="pcb_trace")for(let point23 of pcb_trace2.route)point23.route_type==="via"&&db.pcb_via.insert({pcb_trace_id:pcb_trace2.pcb_trace_id,x:point23.x,y:point23.y,hole_diameter:holeDiameter,outer_diameter:padDiameter,layers:[point23.from_layer,point23.to_layer],from_layer:point23.from_layer,to_layer:point23.to_layer})}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;let{db}=this.root,{_parsedProps:props}=this,schematic_group2=db.schematic_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id,name:this.name,center:this._getGlobalSchematicPositionBeforeLayout(),width:0,height:0,schematic_component_ids:[],source_group_id:this.source_group_id});this.schematic_group_id=schematic_group2.schematic_group_id;for(let child of this.children)child.schematic_component_id&&db.schematic_component.update(child.schematic_component_id,{schematic_group_id:schematic_group2.schematic_group_id})}_getSchematicLayoutMode(){let props=this._parsedProps;if(props.schLayout?.layoutMode==="none"||props.schLayout?.layoutMode==="relative")return"relative";if(props.schLayout?.matchAdapt)return"match-adapt";if(props.schLayout?.flex)return"flex";if(props.schLayout?.grid)return"grid";if(props.schMatchAdapt)return"match-adapt";if(props.schFlex)return"flex";if(props.schGrid)return"grid";if(props.matchAdapt)return"match-adapt";if(props.flex)return"flex";if(props.grid)return"grid";if(props.relative||props.schRelative)return"relative";let anyChildHasSchCoords=this.children.some(child=>{let cProps=child._parsedProps;return cProps?.schX!==void 0||cProps?.schY!==void 0}),hasManualEdits=(props.manualEdits?.schematic_placements?.length??0)>0;return!anyChildHasSchCoords&&!hasManualEdits?"match-adapt":"relative"}doInitialSchematicLayout(){let schematicLayoutMode=this._getSchematicLayoutMode();schematicLayoutMode==="match-adapt"&&this._doInitialSchematicLayoutMatchpack(),schematicLayoutMode==="grid"&&this._doInitialSchematicLayoutGrid(),schematicLayoutMode==="flex"&&this._doInitialSchematicLayoutFlex(),this._insertSchematicBorder()}_doInitialSchematicLayoutMatchAdapt(){Group_doInitialSchematicLayoutMatchAdapt(this)}_doInitialSchematicLayoutMatchpack(){Group_doInitialSchematicLayoutMatchPack(this)}_doInitialSchematicLayoutGrid(){Group_doInitialSchematicLayoutGrid(this)}_doInitialSchematicLayoutFlex(){Group_doInitialSchematicLayoutFlex(this)}_getPcbLayoutMode(){let props=this._parsedProps;if(props.pcbRelative)return"none";if(props.pcbLayout?.matchAdapt)return"match-adapt";if(props.pcbLayout?.flex)return"flex";if(props.pcbLayout?.grid)return"grid";if(props.pcbLayout?.pack)return"pack";if(props.pcbFlex)return"flex";if(props.pcbGrid)return"grid";if(props.pcbPack||props.pack)return"pack";if(props.matchAdapt)return"match-adapt";if(props.flex)return"flex";if(props.grid)return"grid";let groupHasCoords=props.pcbX!==void 0||props.pcbY!==void 0,hasManualEdits=(props.manualEdits?.pcb_placements?.length??0)>0,unpositionedDirectChildrenCount=this.children.reduce((count,child)=>{if(!child.pcb_component_id&&!child.pcb_group_id)return count;let childProps=child._parsedProps,hasCoords=childProps?.pcbX!==void 0||childProps?.pcbY!==void 0;return count+(hasCoords?0:1)},0);return!hasManualEdits&&unpositionedDirectChildrenCount>1?"pack":"none"}doInitialPcbLayout(){if(this.root?.pcbDisabled)return;if(this.pcb_group_id){let{db}=this.root,props=this._parsedProps;if(props.pcbX!==void 0||props.pcbY!==void 0){let parentGroup=this.parent?.getGroup?.(),pcbParentGroupId=parentGroup?.pcb_group_id?db.pcb_group.get(parentGroup.pcb_group_id)?.pcb_group_id:void 0,positionedRelativeToBoardId=pcbParentGroupId?void 0:this._getBoard()?.pcb_board_id??void 0;db.pcb_group.update(this.pcb_group_id,{position_mode:"relative_to_group_anchor",positioned_relative_to_pcb_group_id:pcbParentGroupId,positioned_relative_to_pcb_board_id:positionedRelativeToBoardId,display_offset_x:props.pcbX,display_offset_y:props.pcbY})}}let pcbLayoutMode=this._getPcbLayoutMode();pcbLayoutMode==="grid"?this._doInitialPcbLayoutGrid():pcbLayoutMode==="pack"?this._doInitialPcbLayoutPack():pcbLayoutMode==="flex"&&this._doInitialPcbLayoutFlex()}_doInitialPcbLayoutGrid(){Group_doInitialPcbLayoutGrid(this)}_doInitialPcbLayoutPack(){Group_doInitialPcbLayoutPack(this)}_doInitialPcbLayoutFlex(){Group_doInitialPcbLayoutFlex(this)}_insertSchematicBorder(){if(this.root?.schematicDisabled)return;let{db}=this.root,props=this._parsedProps;if(!props.border)return;let width=typeof props.schWidth=="number"?props.schWidth:void 0,height=typeof props.schHeight=="number"?props.schHeight:void 0,paddingGeneral=typeof props.schPadding=="number"?props.schPadding:0,paddingLeft=typeof props.schPaddingLeft=="number"?props.schPaddingLeft:paddingGeneral,paddingRight=typeof props.schPaddingRight=="number"?props.schPaddingRight:paddingGeneral,paddingTop=typeof props.schPaddingTop=="number"?props.schPaddingTop:paddingGeneral,paddingBottom=typeof props.schPaddingBottom=="number"?props.schPaddingBottom:paddingGeneral,schematicGroup=this.schematic_group_id?db.schematic_group.get(this.schematic_group_id):null;if(schematicGroup&&(width===void 0&&typeof schematicGroup.width=="number"&&(width=schematicGroup.width),height===void 0&&typeof schematicGroup.height=="number"&&(height=schematicGroup.height)),width===void 0||height===void 0)return;let center2=schematicGroup?.center??this._getGlobalSchematicPositionBeforeLayout(),left=center2.x-width/2-paddingLeft,bottom=center2.y-height/2-paddingBottom,finalWidth=width+paddingLeft+paddingRight,finalHeight=height+paddingTop+paddingBottom;db.schematic_box.insert({width:finalWidth,height:finalHeight,x:left,y:bottom,is_dashed:props.border?.dashed??!1})}_determineSideFromPosition(port,component){if(!port.center||!component.center)return"left";let dx2=port.center.x-component.center.x,dy2=port.center.y-component.center.y;return Math.abs(dx2)>Math.abs(dy2)?dx2>0?"right":"left":dy2>0?"bottom":"top"}_calculateSchematicBounds(boxes){if(boxes.length===0)return{minX:0,maxX:0,minY:0,maxY:0};let minX=1/0,maxX=-1/0,minY=1/0,maxY=-1/0;for(let box2 of boxes)minX=Math.min(minX,box2.centerX),maxX=Math.max(maxX,box2.centerX),minY=Math.min(minY,box2.centerY),maxY=Math.max(maxY,box2.centerY);let padding=2;return{minX:minX-padding,maxX:maxX+padding,minY:minY-padding,maxY:maxY+padding}}_getAutorouterConfig(){let autorouter=this._parsedProps.autorouter||this.getInheritedProperty("autorouter");return getPresetAutoroutingConfig(autorouter)}_isLaserPrefabAutorouter(autorouterConfig2=this._getAutorouterConfig()){let autorouterProp2=this.props.autorouter,normalize3=value=>value?.replace(/-/g,"_")??value;return autorouterConfig2.preset==="laser_prefab"?!0:typeof autorouterProp2=="string"?normalize3(autorouterProp2)==="laser_prefab":typeof autorouterProp2=="object"&&autorouterProp2?normalize3(autorouterProp2.preset)==="laser_prefab":!1}_getSubcircuitLayerCount(){let layers=this.getInheritedProperty("layers");return typeof layers=="number"?layers:2}_shouldUseTraceByTraceRouting(){return this._getAutorouterConfig().groupMode==="sequential-trace"}doInitialPcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db}=this.root;if(this.isSubcircuit){let subcircuitComponentsByName=new Map;for(let child of this.children)if(!child.isSubcircuit&&child._parsedProps.name){let components=subcircuitComponentsByName.get(child._parsedProps.name)||[];components.push(child),subcircuitComponentsByName.set(child._parsedProps.name,components)}for(let[name,components]of subcircuitComponentsByName.entries())components.length>1&&db.pcb_trace_error.insert({error_type:"pcb_trace_error",message:`Multiple components found with name "${name}" in subcircuit "${this.name||"unnamed"}". Component names must be unique within a subcircuit.`,source_trace_id:"",pcb_trace_id:"",pcb_component_ids:components.map(c3=>c3.pcb_component_id).filter(Boolean),pcb_port_ids:[]})}}doInitialSchematicReplaceNetLabelsWithSymbols(){if(this.root?.schematicDisabled||!this.isSubcircuit)return;let{db}=this.root,subtree=db;for(let nl2 of subtree.schematic_net_label.list()){let net=subtree.source_net.get(nl2.source_net_id),text=nl2.text||net?.name||"";if(nl2.anchor_side==="top"&&/^gnd/i.test(text)){subtree.schematic_net_label.update(nl2.schematic_net_label_id,{symbol_name:"rail_down"});continue}nl2.anchor_side==="bottom"&&/^v/i.test(text)&&subtree.schematic_net_label.update(nl2.schematic_net_label_id,{symbol_name:"rail_up"})}}doInitialSimulationSpiceEngineRender(){Group_doInitialSimulationSpiceEngineRender(this)}doInitialPcbComponentAnchorAlignment(){Group_doInitialPcbComponentAnchorAlignment(this)}updatePcbComponentAnchorAlignment(){this.doInitialPcbComponentAnchorAlignment()}_getMinimumFlexContainerSize(){return super._getMinimumFlexContainerSize()}_repositionOnPcb(position2){return super._repositionOnPcb(position2)}};function inflatePcbBoard(pcbBoard,inflatorContext){let{subcircuit}=inflatorContext;if(subcircuit.lowercaseComponentName==="board"||subcircuit.parent?.lowercaseComponentName==="board")return;let boardProps2={name:"inflated_board"};pcbBoard.width&&(boardProps2.width=pcbBoard.width),pcbBoard.height&&(boardProps2.height=pcbBoard.height),pcbBoard.center&&(boardProps2.pcbX=pcbBoard.center.x,boardProps2.pcbY=pcbBoard.center.y),pcbBoard.outline&&(boardProps2.outline=pcbBoard.outline),pcbBoard.thickness&&(boardProps2.thickness=pcbBoard.thickness),pcbBoard.material&&(boardProps2.material=pcbBoard.material);let board=new Board(boardProps2);return board.pcb_board_id=pcbBoard.pcb_board_id,subcircuit.add(board),board}var stringProxy=new Proxy({},{get:(target,prop)=>prop}),FTYPE=stringProxy,SCHEMATIC_COMPONENT_OUTLINE_COLOR="rgba(132, 0, 0)",SCHEMATIC_COMPONENT_OUTLINE_STROKE_WIDTH=.12,Capacitor=class extends NormalComponent3{constructor(){super(...arguments);__publicField(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Capacitor",schematicSymbolName:this.props.polarized?"capacitor_polarized":this.props.symbolName??"capacitor",zodProps:capacitorProps,sourceFtype:FTYPE.simple_capacitor}}initPorts(){typeof this.props.footprint=="string"?super.initPorts({additionalAliases:{pin1:["anode","pos"],pin2:["cathode","neg"]}}):super.initPorts()}_getSchematicSymbolDisplayValue(){let inputCapacitance=this.props.capacitance,capacitanceDisplay=typeof inputCapacitance=="string"?inputCapacitance:`${formatSiUnit(this._parsedProps.capacitance)}F`;return this._parsedProps.schShowRatings&&this._parsedProps.maxVoltageRating?`${capacitanceDisplay}/${formatSiUnit(this._parsedProps.maxVoltageRating)}V`:capacitanceDisplay}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.decouplingFor,this.props.decouplingTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.decouplingFor&&this.props.decouplingTo&&(this.add(new Trace3({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.decouplingFor})),this.add(new Trace3({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.decouplingTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,source_component=db.source_component.insert({ftype:"simple_capacitor",name:this.name,manufacturer_part_number:props.manufacturerPartNumber??props.mfn,supplier_part_numbers:props.supplierPartNumbers,capacitance:props.capacitance,max_voltage_rating:props.maxVoltageRating,max_decoupling_trace_length:props.maxDecouplingTraceLength,display_capacitance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!props.polarized});this.source_component_id=source_component.source_component_id}},inflatePcbComponent=(pcbElm,inflatorContext)=>{let{injectionDb,normalComponent}=inflatorContext;if(!normalComponent)return;let componentCenter=pcbElm.center||{x:0,y:0},componentRotation=pcbElm.rotation||0,absoluteToComponentRelativeTransform=inverse(compose(translate(componentCenter.x,componentCenter.y),rotate(componentRotation*Math.PI/180))),relativeElements=injectionDb.toArray().filter(elm=>"pcb_component_id"in elm&&elm.pcb_component_id===pcbElm.pcb_component_id),clonedRelativeElements=structuredClone(relativeElements);transformPCBElements(clonedRelativeElements,absoluteToComponentRelativeTransform);let components=createComponentsFromCircuitJson({componentName:normalComponent.name,componentRotation:"0deg"},clonedRelativeElements);normalComponent.addAll(components)};function inflateSourceCapacitor(sourceElm,inflatorContext){let{injectionDb,subcircuit,groupsMap}=inflatorContext,pcbElm=injectionDb.pcb_component.getWhere({source_component_id:sourceElm.source_component_id}),cadElm=injectionDb.cad_component.getWhere({source_component_id:sourceElm.source_component_id}),capacitor=new Capacitor({name:sourceElm.name,capacitance:sourceElm.capacitance,layer:pcbElm?.layer,pcbX:pcbElm?.center?.x,pcbY:pcbElm?.center?.y,pcbRotation:pcbElm?.rotation,doNotPlace:pcbElm?.do_not_place,obstructsWithinBounds:pcbElm?.obstructs_within_bounds});pcbElm&&inflatePcbComponent(pcbElm,{...inflatorContext,normalComponent:capacitor}),sourceElm.source_group_id&&groupsMap?.has(sourceElm.source_group_id)?groupsMap.get(sourceElm.source_group_id).add(capacitor):subcircuit.add(capacitor)}var Chip=class extends NormalComponent3{constructor(props){super(props);__publicField(this,"schematicBoxDimensions",null)}get config(){return{componentName:"Chip",zodProps:chipProps,shouldRenderAsSchematicBox:!0}}initPorts(opts={}){super.initPorts(opts);let{_parsedProps:props}=this,{pcbX,pcbY}=this.getResolvedPcbPositionProp();if(props.externallyConnectedPins){let requiredPorts=new Set;for(let[pin1,pin2]of props.externallyConnectedPins)requiredPorts.add(pin1),requiredPorts.add(pin2);for(let pinIdentifier of requiredPorts)if(!this.children.find(child=>child instanceof Port&&child.isMatchingAnyOf([pinIdentifier]))){let pinMatch=pinIdentifier.match(/^pin(\d+)$/);if(pinMatch){let pinNumber=parseInt(pinMatch[1]);this.add(new Port({pinNumber,aliases:[pinIdentifier]}))}else this.add(new Port({name:pinIdentifier,aliases:[pinIdentifier]}))}}}doInitialSchematicComponentRender(){let{_parsedProps:props}=this;props?.noSchematicRepresentation!==!0&&super.doInitialSchematicComponentRender()}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,{pcbX,pcbY}=this.getResolvedPcbPositionProp(),source_component=db.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:props.manufacturerPartNumber,supplier_part_numbers:props.supplierPartNumbers});this.source_component_id=source_component.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,{pcbX,pcbY}=this.getResolvedPcbPositionProp(),componentLayer=props.layer??"top";if(componentLayer!=="top"&&componentLayer!=="bottom"){let subcircuit=this.getSubcircuit(),error=pcb_component_invalid_layer_error.parse({type:"pcb_component_invalid_layer_error",message:`Component cannot be placed on layer '${componentLayer}'. Components can only be placed on 'top' or 'bottom' layers.`,source_component_id:this.source_component_id,layer:componentLayer,subcircuit_id:subcircuit.subcircuit_id??void 0});db.pcb_component_invalid_layer_error.insert(error)}let pcb_component2=db.pcb_component.insert({center:{x:pcbX,y:pcbY},width:2,height:3,layer:componentLayer==="top"||componentLayer==="bottom"?componentLayer:"top",rotation:props.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:props.doNotPlace??!1,obstructs_within_bounds:props.obstructsWithinBounds??!0});this.pcb_component_id=pcb_component2.pcb_component_id}doInitialCreateTracesFromProps(){let{_parsedProps:props}=this;if(props.externallyConnectedPins)for(let[pin1,pin2]of props.externallyConnectedPins)this.add(new Trace3({from:`${this.getSubcircuitSelector()} > port.${pin1}`,to:`${this.getSubcircuitSelector()} > port.${pin2}`}));this._createTracesFromConnectionsProp()}doInitialSimulationRender(){let{db}=this.root,{pinAttributes}=this.props;if(!pinAttributes)return;let powerPort=null,groundPort=null,voltage2,ports=this.selectAll("port");for(let port of ports)for(let alias of port.getNameAndAliases())if(pinAttributes[alias]){let attributes2=pinAttributes[alias];attributes2.providesPower&&(powerPort=port,voltage2=attributes2.providesVoltage),attributes2.providesGround&&(groundPort=port)}if(!powerPort||!groundPort||voltage2===void 0)return;let powerSourcePort=db.source_port.get(powerPort.source_port_id);if(!powerSourcePort?.subcircuit_connectivity_map_key)return;let groundSourcePort=db.source_port.get(groundPort.source_port_id);if(!groundSourcePort?.subcircuit_connectivity_map_key)return;let powerNet=db.source_net.getWhere({subcircuit_connectivity_map_key:powerSourcePort.subcircuit_connectivity_map_key}),groundNet=db.source_net.getWhere({subcircuit_connectivity_map_key:groundSourcePort.subcircuit_connectivity_map_key});!powerNet||!groundNet||db.simulation_voltage_source.insert({type:"simulation_voltage_source",positive_source_port_id:powerPort.source_port_id,positive_source_net_id:powerNet.source_net_id,negative_source_port_id:groundPort.source_port_id,negative_source_net_id:groundNet.source_net_id,voltage:voltage2})}},mapInternallyConnectedSourcePortIdsToPinLabels=(sourcePortIds,inflatorContext)=>{if(!sourcePortIds||sourcePortIds.length===0)return;let{injectionDb}=inflatorContext,mapped=sourcePortIds.map(group=>group.map(sourcePortId=>{let port=injectionDb.source_port.get(sourcePortId);return port?port.pin_number!==void 0&&port.pin_number!==null?`pin${port.pin_number}`:port.name:null}).filter(value=>value!==null)).filter(group=>group.length>0);return mapped.length>0?mapped:void 0},inflateSourceChip=(sourceElm,inflatorContext)=>{let{injectionDb,subcircuit,groupsMap}=inflatorContext,pcbElm=injectionDb.pcb_component.getWhere({source_component_id:sourceElm.source_component_id}),schematicElm=injectionDb.schematic_component.getWhere({source_component_id:sourceElm.source_component_id}),cadElm=injectionDb.cad_component.getWhere({source_component_id:sourceElm.source_component_id}),internallyConnectedPins=mapInternallyConnectedSourcePortIdsToPinLabels(sourceElm.internally_connected_source_port_ids,inflatorContext),chip=new Chip({name:sourceElm.name,manufacturerPartNumber:sourceElm.manufacturer_part_number,supplierPartNumbers:sourceElm.supplier_part_numbers??void 0,pinLabels:schematicElm?.port_labels??void 0,schWidth:schematicElm?.size?.width,schHeight:schematicElm?.size?.height,schPinSpacing:schematicElm?.pin_spacing,schX:schematicElm?.center?.x,schY:schematicElm?.center?.y,layer:pcbElm?.layer,pcbX:pcbElm?.center?.x,pcbY:pcbElm?.center?.y,pcbRotation:pcbElm?.rotation,doNotPlace:pcbElm?.do_not_place,obstructsWithinBounds:pcbElm?.obstructs_within_bounds,internallyConnectedPins}),footprint=cadElm?.footprinter_string??null;footprint&&(Object.assign(chip.props,{footprint}),Object.assign(chip._parsedProps,{footprint}),cadElm||chip._addChildrenFromStringFootprint?.()),pcbElm&&inflatePcbComponent(pcbElm,{...inflatorContext,normalComponent:chip}),sourceElm.source_group_id&&groupsMap?.has(sourceElm.source_group_id)?groupsMap.get(sourceElm.source_group_id).add(chip):subcircuit.add(chip)},Diode=class extends NormalComponent3{constructor(){super(...arguments);__publicField(this,"pos",this.portMap.pin1);__publicField(this,"anode",this.portMap.pin1);__publicField(this,"neg",this.portMap.pin2);__publicField(this,"cathode",this.portMap.pin2)}get config(){let symbolMap={schottky:"schottky_diode",avalanche:"avalanche_diode",zener:"zener_diode",photodiode:"photodiode"},variantSymbol=this.props.schottky?"schottky":this.props.avalanche?"avalanche":this.props.zener?"zener":this.props.photo?"photodiode":null;return{schematicSymbolName:variantSymbol?symbolMap[variantSymbol]:this.props.symbolName??"diode",componentName:"Diode",zodProps:diodeProps,sourceFtype:"simple_diode"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,source_component=db.source_component.insert({ftype:"simple_diode",name:this.name,manufacturer_part_number:props.manufacturerPartNumber??props.mfn,supplier_part_numbers:props.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=source_component.source_component_id}};function inflateSourceDiode(sourceElm,inflatorContext){let{injectionDb,subcircuit,groupsMap}=inflatorContext,pcbElm=injectionDb.pcb_component.getWhere({source_component_id:sourceElm.source_component_id}),cadElm=injectionDb.cad_component.getWhere({source_component_id:sourceElm.source_component_id}),diode2=new Diode({name:sourceElm.name,layer:pcbElm?.layer,pcbX:pcbElm?.center?.x,pcbY:pcbElm?.center?.y,pcbRotation:pcbElm?.rotation,doNotPlace:pcbElm?.do_not_place,obstructsWithinBounds:pcbElm?.obstructs_within_bounds});pcbElm&&inflatePcbComponent(pcbElm,{...inflatorContext,normalComponent:diode2}),sourceElm.source_group_id&&groupsMap?.has(sourceElm.source_group_id)?groupsMap.get(sourceElm.source_group_id).add(diode2):subcircuit.add(diode2)}function inflateSourceGroup(sourceGroup,inflatorContext){let{subcircuit,groupsMap}=inflatorContext,group=new Group6({name:sourceGroup.name??`inflated_group_${sourceGroup.source_group_id}`});return group.source_group_id=sourceGroup.source_group_id,groupsMap&&groupsMap.set(sourceGroup.source_group_id,group),sourceGroup.parent_source_group_id&&groupsMap?.has(sourceGroup.parent_source_group_id)?groupsMap.get(sourceGroup.parent_source_group_id).add(group):subcircuit.add(group),group}var Inductor=class extends NormalComponent3{constructor(){super(...arguments);__publicField(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Inductor",schematicSymbolName:this.props.symbolName??"inductor",zodProps:inductorProps,sourceFtype:FTYPE.simple_inductor}}_getSchematicSymbolDisplayValue(){return`${formatSiUnit(this._parsedProps.inductance)}H`}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,source_component=db.source_component.insert({name:this.name,ftype:FTYPE.simple_inductor,inductance:this.props.inductance,display_inductance:this._getSchematicSymbolDisplayValue(),supplier_part_numbers:props.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=source_component.source_component_id}};function inflateSourceInductor(sourceElm,inflatorContext){let{injectionDb,subcircuit,groupsMap}=inflatorContext,pcbElm=injectionDb.pcb_component.getWhere({source_component_id:sourceElm.source_component_id}),cadElm=injectionDb.cad_component.getWhere({source_component_id:sourceElm.source_component_id}),inductor=new Inductor({name:sourceElm.name,inductance:sourceElm.inductance,layer:pcbElm?.layer,pcbX:pcbElm?.center?.x,pcbY:pcbElm?.center?.y,pcbRotation:pcbElm?.rotation,doNotPlace:pcbElm?.do_not_place,obstructsWithinBounds:pcbElm?.obstructs_within_bounds});pcbElm&&inflatePcbComponent(pcbElm,{...inflatorContext,normalComponent:inductor}),sourceElm.source_group_id&&groupsMap?.has(sourceElm.source_group_id)?groupsMap.get(sourceElm.source_group_id).add(inductor):subcircuit.add(inductor)}function inflateSourcePort(sourcePort,inflatorContext){let{injectionDb,subcircuit}=inflatorContext;if(sourcePort.source_component_id!==null)return;let pcbPortFromInjection=injectionDb.pcb_port.getWhere({source_port_id:sourcePort.source_port_id}),port=new Port({name:sourcePort.name,pinNumber:sourcePort.pin_number});subcircuit.add(port),port.source_port_id=sourcePort.source_port_id;let root=subcircuit.root;if(root&&pcbPortFromInjection){let{db}=root,pcb_port2=db.pcb_port.insert({pcb_component_id:void 0,layers:pcbPortFromInjection.layers,subcircuit_id:subcircuit.subcircuit_id??void 0,pcb_group_id:subcircuit.getGroup()?.pcb_group_id??void 0,x:pcbPortFromInjection.x,y:pcbPortFromInjection.y,source_port_id:sourcePort.source_port_id,is_board_pinout:!1});port.pcb_port_id=pcb_port2.pcb_port_id}}var Resistor=class extends NormalComponent3{constructor(){super(...arguments);__publicField(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Resistor",schematicSymbolName:this.props.symbolName??"boxresistor",zodProps:resistorProps,sourceFtype:"simple_resistor"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return`${formatSiUnit(this._parsedProps.resistance)}\u03A9`}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.pullupFor,this.props.pullupTo,this.props.pulldownFor,this.props.pulldownTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.pullupFor&&this.props.pullupTo&&(this.add(new Trace3({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pullupFor})),this.add(new Trace3({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pullupTo}))),this.props.pulldownFor&&this.props.pulldownTo&&(this.add(new Trace3({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pulldownFor})),this.add(new Trace3({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pulldownTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,source_component=db.source_component.insert({ftype:"simple_resistor",name:this.name,manufacturer_part_number:props.manufacturerPartNumber??props.mfn,supplier_part_numbers:props.supplierPartNumbers,resistance:props.resistance,display_resistance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!0});this.source_component_id=source_component.source_component_id}};function inflateSourceResistor(sourceElm,inflatorContext){let{injectionDb,subcircuit,groupsMap}=inflatorContext,pcbElm=injectionDb.pcb_component.getWhere({source_component_id:sourceElm.source_component_id}),cadElm=injectionDb.cad_component.getWhere({source_component_id:sourceElm.source_component_id}),resistor=new Resistor({name:sourceElm.name,resistance:sourceElm.resistance,layer:pcbElm?.layer,pcbX:pcbElm?.center?.x,pcbY:pcbElm?.center?.y,pcbRotation:pcbElm?.rotation,doNotPlace:pcbElm?.do_not_place,obstructsWithinBounds:pcbElm?.obstructs_within_bounds});pcbElm&&inflatePcbComponent(pcbElm,{...inflatorContext,normalComponent:resistor}),sourceElm.source_group_id&&groupsMap?.has(sourceElm.source_group_id)?groupsMap.get(sourceElm.source_group_id).add(resistor):subcircuit.add(resistor)}var getSelectorPath=(component,inflatorContext)=>{let{injectionDb,subcircuit,groupsMap}=inflatorContext,path_parts=[],currentGroupId=component.source_group_id;for(;currentGroupId&&currentGroupId!==subcircuit.source_group_id;){let sourceGroup=injectionDb.source_group.get(currentGroupId),groupInstance=groupsMap?.get(currentGroupId);if(!sourceGroup||!groupInstance)break;let groupName=groupInstance.props.name??groupInstance.fallbackUnassignedName;path_parts.unshift(`.${groupName}`),currentGroupId=sourceGroup.parent_source_group_id}return path_parts.push(`.${component.name}`),path_parts.join(" > ")};function inflateSourceTrace(sourceTrace,inflatorContext){let{injectionDb,subcircuit}=inflatorContext,connectedSelectors=[];for(let sourcePortId of sourceTrace.connected_source_port_ids){let sourcePort=injectionDb.source_port.get(sourcePortId);if(!sourcePort)continue;let selector;if(sourcePort.source_component_id){let sourceComponent=injectionDb.source_component.get(sourcePort.source_component_id);sourceComponent&&(selector=`${getSelectorPath({name:sourceComponent.name,source_group_id:sourceComponent.source_group_id},inflatorContext)} > .${sourcePort.name}`)}else selector=`.${sourcePort.name}`;selector&&connectedSelectors.push(selector)}for(let sourceNetId of sourceTrace.connected_source_net_ids){let sourceNet=injectionDb.source_net.get(sourceNetId);sourceNet&&connectedSelectors.push(`net.${sourceNet.name}`)}if(connectedSelectors.length<2)return;let trace=new Trace3({path:connectedSelectors});trace.source_trace_id=sourceTrace.source_trace_id,subcircuit.add(trace)}var Transistor=class extends NormalComponent3{constructor(){super(...arguments);__publicField(this,"emitter",this.portMap.pin1);__publicField(this,"collector",this.portMap.pin2);__publicField(this,"base",this.portMap.pin3)}get config(){let baseSymbolName=this.props.type==="npn"?"npn_bipolar_transistor":"pnp_bipolar_transistor";return{componentName:"Transistor",schematicSymbolName:this.props.symbolName??baseSymbolName,zodProps:transistorProps,sourceFtype:"simple_transistor",shouldRenderAsSchematicBox:!1}}initPorts(){let pinAliases={pin1:["collector","c"],pin2:["emitter","e"],pin3:["base","b"]};super.initPorts({pinCount:3,additionalAliases:pinAliases})}doInitialCreateNetsFromProps(){this._createNetsFromProps([...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,source_component=db.source_component.insert({ftype:"simple_transistor",name:this.name,transistor_type:props.type});this.source_component_id=source_component.source_component_id}};function inflateSourceTransistor(sourceElm,inflatorContext){let{injectionDb,subcircuit,groupsMap}=inflatorContext,pcbElm=injectionDb.pcb_component.getWhere({source_component_id:sourceElm.source_component_id}),cadElm=injectionDb.cad_component.getWhere({source_component_id:sourceElm.source_component_id}),transistor=new Transistor({name:sourceElm.name,type:sourceElm.transistor_type,layer:pcbElm?.layer,pcbX:pcbElm?.center?.x,pcbY:pcbElm?.center?.y,pcbRotation:pcbElm?.rotation,doNotPlace:pcbElm?.do_not_place,obstructsWithinBounds:pcbElm?.obstructs_within_bounds});pcbElm&&inflatePcbComponent(pcbElm,{...inflatorContext,normalComponent:transistor}),sourceElm.source_group_id&&groupsMap?.has(sourceElm.source_group_id)?groupsMap.get(sourceElm.source_group_id).add(transistor):subcircuit.add(transistor)}var inflateCircuitJson=(target,circuitJson,children)=>{if(!circuitJson)return;let injectionDb=cju_default(circuitJson);if(circuitJson&&children?.length>0)throw new Error("Component cannot have both circuitJson and children");let inflationCtx={injectionDb,subcircuit:target,groupsMap:new Map},sourceGroups=injectionDb.source_group.list();for(let sourceGroup of sourceGroups)inflateSourceGroup(sourceGroup,inflationCtx);let pcbBoards=injectionDb.pcb_board.list();for(let pcbBoard of pcbBoards)inflatePcbBoard(pcbBoard,inflationCtx);let sourceComponents=injectionDb.source_component.list();for(let sourceComponent of sourceComponents)switch(sourceComponent.ftype){case"simple_resistor":inflateSourceResistor(sourceComponent,inflationCtx);break;case"simple_capacitor":inflateSourceCapacitor(sourceComponent,inflationCtx);break;case"simple_inductor":inflateSourceInductor(sourceComponent,inflationCtx);break;case"simple_diode":inflateSourceDiode(sourceComponent,inflationCtx);break;case"simple_chip":inflateSourceChip(sourceComponent,inflationCtx);break;case"simple_transistor":inflateSourceTransistor(sourceComponent,inflationCtx);break;default:throw new Error(`No inflator implemented for source component ftype: "${sourceComponent.ftype}"`)}let sourcePorts=injectionDb.source_port.list();for(let sourcePort of sourcePorts)inflateSourcePort(sourcePort,inflationCtx);let sourceTraces=injectionDb.source_trace.list();for(let sourceTrace of sourceTraces)inflateSourceTrace(sourceTrace,inflationCtx)},MIN_EFFECTIVE_BORDER_RADIUS_MM=.01,getRoundedRectOutline=(width,height,radius)=>{let w22=width/2,h22=height/2,r4=Math.min(radius,w22,h22);if(r4<MIN_EFFECTIVE_BORDER_RADIUS_MM)return[{x:-w22,y:-h22},{x:w22,y:-h22},{x:w22,y:h22},{x:-w22,y:h22}];let segments=Math.max(1,Math.ceil(Math.PI/2*r4/.1)),step=Math.PI/2/segments,outline=[];outline.push({x:-w22+r4,y:-h22}),outline.push({x:w22-r4,y:-h22});for(let i3=1;i3<=segments;i3++){let theta=-Math.PI/2+i3*step;outline.push({x:w22-r4+r4*Math.cos(theta),y:-h22+r4+r4*Math.sin(theta)})}outline.push({x:w22,y:h22-r4});for(let i3=1;i3<=segments;i3++){let theta=0+i3*step;outline.push({x:w22-r4+r4*Math.cos(theta),y:h22-r4+r4*Math.sin(theta)})}outline.push({x:-w22+r4,y:h22});for(let i3=1;i3<=segments;i3++){let theta=Math.PI/2+i3*step;outline.push({x:-w22+r4+r4*Math.cos(theta),y:h22-r4+r4*Math.sin(theta)})}outline.push({x:-w22,y:-h22+r4});for(let i3=1;i3<=segments;i3++){let theta=Math.PI+i3*step;outline.push({x:-w22+r4+r4*Math.cos(theta),y:-h22+r4+r4*Math.sin(theta)})}return outline},Board=class extends Group6{constructor(){super(...arguments);__publicField(this,"pcb_board_id",null);__publicField(this,"source_board_id",null);__publicField(this,"_drcChecksComplete",!1);__publicField(this,"_connectedSchematicPortPairs",new Set)}get isSubcircuit(){return!0}get isGroup(){return!0}get config(){return{componentName:"Board",zodProps:boardProps}}get boardThickness(){return this._parsedProps.thickness??1.4}get allLayers(){let layerCount=this._parsedProps.layers??2;return layerCount===1?["top"]:layerCount===4?["top","bottom","inner1","inner2"]:["top","bottom"]}_getSubcircuitLayerCount(){return this._parsedProps.layers??2}_getBoardCalcVariables(){let{_parsedProps:props}=this;if((props.width==null||props.height==null)&&!props.outline)return{};let dbBoard=this.pcb_board_id?this.root?.db.pcb_board.get(this.pcb_board_id):null,width=dbBoard?.width??props.width,height=dbBoard?.height??props.height;if((width==null||height==null)&&props.outline?.length){let outlineBounds=getBoundsFromPoints(props.outline);outlineBounds&&(width??(width=outlineBounds.maxX-outlineBounds.minX),height??(height=outlineBounds.maxY-outlineBounds.minY))}let{pcbX,pcbY}=this.getResolvedPcbPositionProp(),center2=dbBoard?.center??{x:pcbX+(props.outlineOffsetX??0),y:pcbY+(props.outlineOffsetY??0)},resolvedWidth=width??0,resolvedHeight=height??0;return{"board.minx":center2.x-resolvedWidth/2,"board.maxx":center2.x+resolvedWidth/2,"board.miny":center2.y-resolvedHeight/2,"board.maxy":center2.y+resolvedHeight/2}}doInitialPcbBoardAutoSize(){if(this.root?.pcbDisabled||!this.pcb_board_id)return;let{db}=this.root,{_parsedProps:props}=this,globalPos=this._getGlobalPcbPositionBeforeLayout(),pcbBoard=db.pcb_board.get(this.pcb_board_id);if(pcbBoard?.width&&pcbBoard?.height||pcbBoard?.outline&&pcbBoard.outline.length>0)return;let minX=1/0,minY=1/0,maxX=-1/0,maxY=-1/0,descendantIds=getDescendantSubcircuitIds(db,this.subcircuit_id),allowedSubcircuitIds=new Set([this.subcircuit_id,...descendantIds]),allPcbComponents=db.pcb_component.list().filter(c3=>c3.subcircuit_id&&allowedSubcircuitIds.has(c3.subcircuit_id)),allPcbGroups=db.pcb_group.list().filter(g4=>g4.subcircuit_id&&allowedSubcircuitIds.has(g4.subcircuit_id)),hasComponents=!1,updateBounds=(center22,width,height)=>{width===0||height===0||(hasComponents=!0,minX=Math.min(minX,center22.x-width/2),minY=Math.min(minY,center22.y-height/2),maxX=Math.max(maxX,center22.x+width/2),maxY=Math.max(maxY,center22.y+height/2))};for(let pcbComponent of allPcbComponents)updateBounds(pcbComponent.center,pcbComponent.width,pcbComponent.height);for(let pcbGroup of allPcbGroups){let width=pcbGroup.width??0,height=pcbGroup.height??0;if(pcbGroup.outline&&pcbGroup.outline.length>0){let bounds=getBoundsFromPoints(pcbGroup.outline);bounds&&(width=bounds.maxX-bounds.minX,height=bounds.maxY-bounds.minY)}updateBounds(pcbGroup.center,width,height)}if(props.boardAnchorPosition){let{x:x3,y:y3}=props.boardAnchorPosition;minX=Math.min(minX,x3),minY=Math.min(minY,y3),maxX=Math.max(maxX,x3),maxY=Math.max(maxY,y3)}let padding=2,computedWidth=hasComponents?maxX-minX+padding*2:0,computedHeight=hasComponents?maxY-minY+padding*2:0,center2={x:hasComponents?(minX+maxX)/2+(props.outlineOffsetX??0):(props.outlineOffsetX??0)+globalPos.x,y:hasComponents?(minY+maxY)/2+(props.outlineOffsetY??0):(props.outlineOffsetY??0)+globalPos.y},finalWidth=props.width??computedWidth,finalHeight=props.height??computedHeight,outline=props.outline;!outline&&props.borderRadius!=null&&finalWidth>0&&finalHeight>0&&(outline=getRoundedRectOutline(finalWidth,finalHeight,props.borderRadius));let update={width:finalWidth,height:finalHeight,center:center2};outline&&(update.outline=outline.map(point23=>({x:point23.x+(props.outlineOffsetX??0),y:point23.y+(props.outlineOffsetY??0)}))),db.pcb_board.update(this.pcb_board_id,update)}updatePcbBoardAutoSize(){this.doInitialPcbBoardAutoSize()}_addBoardInformationToSilkscreen(){let platform=this.root?.platform;if(!platform?.printBoardInformationToSilkscreen)return;let pcbBoard=this.root.db.pcb_board.get(this.pcb_board_id);if(!pcbBoard)return;let boardInformation=[];if(platform.projectName&&boardInformation.push(platform.projectName),platform.version&&boardInformation.push(`v${platform.version}`),platform.url&&boardInformation.push(platform.url),boardInformation.length===0)return;let text=boardInformation.join(`
601
+ `),position2={x:pcbBoard.center.x+pcbBoard.width/2-.25,y:pcbBoard.center.y-pcbBoard.height/2+1};this.root.db.pcb_silkscreen_text.insert({pcb_component_id:this.pcb_board_id,layer:"top",font:"tscircuit2024",font_size:.45,text,ccw_rotation:0,anchor_alignment:"bottom_right",anchor_position:position2})}doInitialSourceRender(){let nestedBoard=this.getDescendants().find(d2=>d2.lowercaseComponentName==="board");if(nestedBoard)throw new Error(`Nested boards are not supported: found board "${nestedBoard.name}" inside board "${this.name}"`);super.doInitialSourceRender();let{db}=this.root,source_board2=db.source_board.insert({source_group_id:this.source_group_id,title:this.props.title||this.props.name});this.source_board_id=source_board2.source_board_id}doInitialInflateSubcircuitCircuitJson(){let{circuitJson,children}=this._parsedProps;inflateCircuitJson(this,circuitJson,children)}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,pcbBoardFromCircuitJson=props.circuitJson?.find(elm=>elm.type==="pcb_board"),computedWidth=props.width??pcbBoardFromCircuitJson?.width??0,computedHeight=props.height??pcbBoardFromCircuitJson?.height??0,globalPos=this._getGlobalPcbPositionBeforeLayout(),center2={x:globalPos.x+(props.outlineOffsetX??0),y:globalPos.y+(props.outlineOffsetY??0)},{boardAnchorPosition,boardAnchorAlignment}=props;if(boardAnchorPosition&&(center2=getBoardCenterFromAnchor({boardAnchorPosition,boardAnchorAlignment:boardAnchorAlignment??"center",width:computedWidth,height:computedHeight})),props.outline){let xValues=props.outline.map(point23=>point23.x),yValues=props.outline.map(point23=>point23.y),minX=Math.min(...xValues),maxX=Math.max(...xValues),minY=Math.min(...yValues),maxY=Math.max(...yValues);computedWidth=maxX-minX,computedHeight=maxY-minY}let outline=props.outline;!outline&&props.borderRadius!=null&&computedWidth>0&&computedHeight>0&&(outline=getRoundedRectOutline(computedWidth,computedHeight,props.borderRadius));let pcb_board2=db.pcb_board.insert({source_board_id:this.source_board_id,center:center2,thickness:this.boardThickness,num_layers:this.allLayers.length,width:computedWidth,height:computedHeight,outline:outline?.map(point23=>({x:point23.x+(props.outlineOffsetX??0),y:point23.y+(props.outlineOffsetY??0)})),material:props.material});this.pcb_board_id=pcb_board2.pcb_board_id,this._addBoardInformationToSilkscreen()}removePcbComponentRender(){let{db}=this.root;this.pcb_board_id&&(db.pcb_board.delete(this.pcb_board_id),this.pcb_board_id=null)}doInitialPcbDesignRuleChecks(){this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled")||super.doInitialPcbDesignRuleChecks()}updatePcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db}=this.root;if(!this._areChildSubcircuitsRouted()||this._drcChecksComplete)return;this._drcChecksComplete=!0;let errors=checkEachPcbTraceNonOverlapping(db.toArray());for(let error of errors)db.pcb_trace_error.insert(error);let pcbPortNotConnectedErrors=checkEachPcbPortConnectedToPcbTraces(db.toArray());for(let error of pcbPortNotConnectedErrors)db.pcb_port_not_connected_error.insert(error);let pcbComponentOutsideErrors=checkPcbComponentsOutOfBoard(db.toArray());for(let error of pcbComponentOutsideErrors)db.pcb_component_outside_board_error.insert(error);let pcbTracesOutOfBoardErrors=checkPcbTracesOutOfBoard(db.toArray());for(let error of pcbTracesOutOfBoardErrors)db.pcb_trace_error.insert(error);let differentNetViaErrors=checkDifferentNetViaSpacing(db.toArray());for(let error of differentNetViaErrors)db.pcb_via_clearance_error.insert(error);let sameNetViaErrors=checkSameNetViaSpacing(db.toArray());for(let error of sameNetViaErrors)db.pcb_via_clearance_error.insert(error);let pcbComponentOverlapErrors=checkPcbComponentOverlap(db.toArray());for(let error of pcbComponentOverlapErrors)db.pcb_footprint_overlap_error.insert(error);let sourcePinMustBeConnectedErrors=checkPinMustBeConnected(db.toArray());for(let error of sourcePinMustBeConnectedErrors)db.source_pin_must_be_connected_error.insert(error)}_emitRenderLifecycleEvent(phase,startOrEnd){super._emitRenderLifecycleEvent(phase,startOrEnd),startOrEnd==="start"&&this.root?.emit("board:renderPhaseStarted",{renderId:this._renderId,phase})}_repositionOnPcb(position2){let{db}=this.root,pcbBoard=this.pcb_board_id?db.pcb_board.get(this.pcb_board_id):null,oldPos=pcbBoard?.center;if(!oldPos){this.pcb_board_id&&db.pcb_board.update(this.pcb_board_id,{center:position2});return}let deltaX=position2.x-oldPos.x,deltaY=position2.y-oldPos.y;if(!(Math.abs(deltaX)<1e-6&&Math.abs(deltaY)<1e-6)){for(let child of this.children)if(child instanceof NormalComponent3){let childOldCenter;if(child.pcb_component_id){let comp=db.pcb_component.get(child.pcb_component_id);comp&&(childOldCenter=comp.center)}else if(child instanceof Group6&&child.pcb_group_id){let group=db.pcb_group.get(child.pcb_group_id);group&&(childOldCenter=group.center)}childOldCenter&&child._repositionOnPcb({x:childOldCenter.x+deltaX,y:childOldCenter.y+deltaY})}else child.isPcbPrimitive&&"_repositionOnPcb"in child&&typeof child._repositionOnPcb=="function"&&child._repositionOnPcb({deltaX,deltaY});if(this.pcb_board_id&&(db.pcb_board.update(this.pcb_board_id,{center:position2}),pcbBoard?.outline)){let outlineBounds=getBoundsFromPoints(pcbBoard.outline);if(outlineBounds){let oldOutlineCenter={x:(outlineBounds.minX+outlineBounds.maxX)/2,y:(outlineBounds.minY+outlineBounds.maxY)/2},outlineDeltaX=position2.x-oldOutlineCenter.x,outlineDeltaY=position2.y-oldOutlineCenter.y,newOutline=pcbBoard.outline.map(p4=>({x:p4.x+outlineDeltaX,y:p4.y+outlineDeltaY}));db.pcb_board.update(this.pcb_board_id,{outline:newOutline})}}}}},DEFAULT_TAB_LENGTH=5,DEFAULT_TAB_WIDTH=2,generateCutoutsAndMousebitesForOutline=(outline,options)=>{let{gapLength,cutoutWidth,mouseBites,mouseBiteHoleDiameter,mouseBiteHoleSpacing}=options,tabCutouts=[],mouseBiteHoles=[];if(outline.length<2)return{tabCutouts,mouseBiteHoles};let outlinePolygon=new Polygon$1(outline.map(p4=>point4(p4.x,p4.y))),is_ccw;if(outline.length>2){let p02=point4(outline[0].x,outline[0].y),p12=point4(outline[1].x,outline[1].y),segmentDir=vector$1(p02,p12).normalize(),normalToLeft=segmentDir.rotate(Math.PI/2),testPoint=p02.translate(segmentDir.multiply(segment(p02,p12).length/2)).translate(normalToLeft.multiply(.01));is_ccw=outlinePolygon.contains(testPoint)}else is_ccw=outlinePolygon.area()>0;for(let i3=0;i3<outline.length;i3++){let p1_=outline[i3],p2_=outline[(i3+1)%outline.length];if(!p1_||!p2_)continue;let p12=point4(p1_.x,p1_.y),p22=point4(p2_.x,p2_.y),segment2=segment(p12,p22),segmentLength=segment2.length;if(segmentLength<1e-6)continue;let segmentVec=vector$1(p12,p22),segmentDir=segmentVec.normalize(),normalVec=segmentDir.rotate(Math.PI/2),testPoint=segment2.middle().translate(normalVec.multiply(.01));outlinePolygon.contains(testPoint)&&(normalVec=normalVec.multiply(-1));let numBitesInGap=2,totalBitesLength=numBitesInGap*mouseBiteHoleDiameter+(numBitesInGap-1)*mouseBiteHoleSpacing,effectiveGapLength;mouseBites?effectiveGapLength=totalBitesLength:effectiveGapLength=gapLength,effectiveGapLength=Math.min(effectiveGapLength,segmentLength*.9);let gapStartDist=(segmentLength-effectiveGapLength)/2,gapEndDist=gapStartDist+effectiveGapLength;if(mouseBites){let holeAndSpacing=mouseBiteHoleDiameter+mouseBiteHoleSpacing;if(effectiveGapLength>=totalBitesLength&&holeAndSpacing>0){let firstBiteCenterOffsetInGap=(effectiveGapLength-totalBitesLength)/2+mouseBiteHoleDiameter/2,firstBiteDistFromP1=gapStartDist+firstBiteCenterOffsetInGap;for(let k4=0;k4<numBitesInGap;k4++){let biteDist=firstBiteDistFromP1+k4*holeAndSpacing,pos=p12.translate(segmentDir.multiply(biteDist));mouseBiteHoles.push({x:pos.x,y:pos.y})}}}let p_prev_=outline[(i3-1+outline.length)%outline.length],p_next_=outline[(i3+2)%outline.length],start_ext=0,end_ext=0;if(p_prev_&&p_next_){let vec_in_p1=vector$1(point4(p_prev_.x,p_prev_.y),p12),p1_cross=vec_in_p1.cross(segmentVec),is_p1_convex=is_ccw?p1_cross>1e-9:p1_cross<-1e-9,vec_out_p2=vector$1(p22,point4(p_next_.x,p_next_.y)),p2_cross=segmentVec.cross(vec_out_p2),is_p2_convex=is_ccw?p2_cross>1e-9:p2_cross<-1e-9;if(is_p1_convex){let angle=vec_in_p1.angleTo(segmentVec);angle>Math.PI&&(angle=2*Math.PI-angle),start_ext=cutoutWidth*Math.tan(angle/2)}else start_ext=0;if(is_p2_convex){let angle=segmentVec.angleTo(vec_out_p2);angle>Math.PI&&(angle=2*Math.PI-angle),end_ext=cutoutWidth*Math.tan(angle/2)}else end_ext=0}let cutoutParts=[{start:0-start_ext,end:gapStartDist},{start:gapEndDist,end:segmentLength+end_ext}],extrusion=normalVec.multiply(cutoutWidth);for(let part of cutoutParts){let partLength=part.end-part.start;if(partLength<1e-6)continue;let center2=p12.translate(segmentDir.multiply(part.start+partLength/2)).translate(extrusion.multiply(.5)),width=partLength,height=cutoutWidth,rotationDeg=segmentDir.slope*180/Math.PI;tabCutouts.push({type:"pcb_cutout",shape:"rect",center:{x:center2.x,y:center2.y},width,height,rotation:rotationDeg,corner_radius:cutoutWidth/2})}}return{tabCutouts,mouseBiteHoles}};function generatePanelTabsAndMouseBites(boards,options){let finalTabCutouts=[],allMouseBites=[],{tabWidth,tabLength,mouseBites:useMouseBites}=options,processedBoards=boards.map(board=>{if((!board.outline||board.outline.length===0)&&board.width&&board.height){let w22=board.width/2,h22=board.height/2;return{...board,outline:[{x:board.center.x-w22,y:board.center.y-h22},{x:board.center.x+w22,y:board.center.y-h22},{x:board.center.x+w22,y:board.center.y+h22},{x:board.center.x-w22,y:board.center.y+h22}]}}return board});for(let board of processedBoards)if(board.outline&&board.outline.length>0){let mouseBiteDiameter2=tabWidth*.45,mouseBiteSpacing=mouseBiteDiameter2*.1,generated=generateCutoutsAndMousebitesForOutline(board.outline,{gapLength:tabLength,cutoutWidth:tabWidth,mouseBites:useMouseBites,mouseBiteHoleDiameter:mouseBiteDiameter2,mouseBiteHoleSpacing:mouseBiteSpacing});finalTabCutouts.push(...generated.tabCutouts),allMouseBites.push(...generated.mouseBiteHoles)}let tabCutouts=finalTabCutouts.map((tab,index)=>({...tab,pcb_cutout_id:`panel_tab_${index}`})),mouseBiteDiameter=tabWidth*.45,mouseBiteHoles=allMouseBites.map((bite,index)=>({type:"pcb_hole",pcb_hole_id:`panel_mouse_bite_${index}`,hole_shape:"circle",hole_diameter:mouseBiteDiameter,x:bite.x,y:bite.y}));return{tabCutouts,mouseBiteHoles}}var packBoardsIntoGrid=({boards,db,row,col,cellWidth,cellHeight,boardGap})=>{let boardsWithDims=boards.map(board=>{let pcbBoard=db.pcb_board.get(board.pcb_board_id);return!pcbBoard||pcbBoard.width===void 0||pcbBoard.height===void 0?null:{board,width:pcbBoard.width,height:pcbBoard.height}}).filter(b3=>b3!==null);if(boardsWithDims.length===0)return{positions:[],gridWidth:0,gridHeight:0};let explicitRow=row,cols=col??Math.ceil(explicitRow?boardsWithDims.length/explicitRow:Math.sqrt(boardsWithDims.length)),rows=explicitRow??Math.ceil(boardsWithDims.length/cols),colWidths=Array(cols).fill(0),rowHeights=Array(rows).fill(0);boardsWithDims.forEach((b3,i3)=>{let col2=i3%cols,row2=Math.floor(i3/cols);row2<rowHeights.length&&b3.height>rowHeights[row2]&&(rowHeights[row2]=b3.height),col2<colWidths.length&&b3.width>colWidths[col2]&&(colWidths[col2]=b3.width)});let minCellWidth=cellWidth?distance.parse(cellWidth):0,minCellHeight=cellHeight?distance.parse(cellHeight):0;for(let i3=0;i3<colWidths.length;i3++)colWidths[i3]=Math.max(colWidths[i3],minCellWidth);for(let i3=0;i3<rowHeights.length;i3++)rowHeights[i3]=Math.max(rowHeights[i3],minCellHeight);let totalGridWidth=colWidths.reduce((a3,b3)=>a3+b3,0)+(cols>1?(cols-1)*boardGap:0),totalGridHeight=rowHeights.reduce((a3,b3)=>a3+b3,0)+(rows>1?(rows-1)*boardGap:0),startX=-totalGridWidth/2,rowYOffsets=[-totalGridHeight/2];for(let i3=1;i3<rows;i3++)rowYOffsets.push(rowYOffsets[i3-1]+rowHeights[i3-1]+boardGap);let colXOffsets=[startX];for(let i3=1;i3<cols;i3++)colXOffsets.push(colXOffsets[i3-1]+colWidths[i3-1]+boardGap);let positions=[];return boardsWithDims.forEach((b3,i3)=>{let col2=i3%cols,row2=Math.floor(i3/cols);if(row2>=rowYOffsets.length||col2>=colXOffsets.length)return;let cellX=colXOffsets[col2],cellY=rowYOffsets[row2],cellWidth2=colWidths[col2],cellHeight2=rowHeights[row2],boardX=cellX+cellWidth2/2,boardY=cellY+cellHeight2/2;positions.push({board:b3.board,pos:{x:boardX,y:boardY}})}),{positions,gridWidth:totalGridWidth,gridHeight:totalGridHeight}},Panel=class extends Group6{constructor(){super(...arguments);__publicField(this,"pcb_panel_id",null);__publicField(this,"_tabsAndMouseBitesGenerated",!1)}get config(){return{componentName:"Panel",zodProps:panelProps}}get isGroup(){return!0}get isSubcircuit(){return!0}add(component){if(component.lowercaseComponentName!=="board")throw new Error("<panel> can only contain <board> elements");super.add(component)}doInitialPanelLayout(){if(this.root?.pcbDisabled)return;let{db}=this.root,childBoardInstances=this.children.filter(c3=>c3 instanceof Board),hasAnyPositionedBoards=childBoardInstances.some(b3=>b3.props.pcbX!==void 0||b3.props.pcbY!==void 0),unpositionedBoards=childBoardInstances.filter(b3=>b3.props.pcbX===void 0&&b3.props.pcbY===void 0);if(unpositionedBoards.length>0&&!hasAnyPositionedBoards){let tabWidth=this._parsedProps.tabWidth??DEFAULT_TAB_WIDTH,boardGap=this._parsedProps.boardGap??tabWidth,{positions,gridWidth,gridHeight}=packBoardsIntoGrid({boards:unpositionedBoards,db,row:this._parsedProps.row,col:this._parsedProps.col,cellWidth:this._parsedProps.cellWidth,cellHeight:this._parsedProps.cellHeight,boardGap}),panelGlobalPos=this._getGlobalPcbPositionBeforeLayout();for(let{board,pos}of positions){let absoluteX=panelGlobalPos.x+pos.x,absoluteY=panelGlobalPos.y+pos.y;board._repositionOnPcb({x:absoluteX,y:absoluteY}),db.pcb_board.update(board.pcb_board_id,{center:{x:absoluteX,y:absoluteY}})}let hasExplicitWidth=this._parsedProps.width!==void 0,hasExplicitHeight=this._parsedProps.height!==void 0;if(hasExplicitWidth&&hasExplicitHeight)db.pcb_panel.update(this.pcb_panel_id,{width:distance.parse(this._parsedProps.width),height:distance.parse(this._parsedProps.height)});else if(gridWidth>0||gridHeight>0){let{edgePadding:edgePaddingProp,edgePaddingLeft:edgePaddingLeftProp,edgePaddingRight:edgePaddingRightProp,edgePaddingTop:edgePaddingTopProp,edgePaddingBottom:edgePaddingBottomProp}=this._parsedProps,edgePadding=distance.parse(edgePaddingProp??5),edgePaddingLeft=distance.parse(edgePaddingLeftProp??edgePadding),edgePaddingRight=distance.parse(edgePaddingRightProp??edgePadding),edgePaddingTop=distance.parse(edgePaddingTopProp??edgePadding),edgePaddingBottom=distance.parse(edgePaddingBottomProp??edgePadding);db.pcb_panel.update(this.pcb_panel_id,{width:hasExplicitWidth?distance.parse(this._parsedProps.width):gridWidth+edgePaddingLeft+edgePaddingRight,height:hasExplicitHeight?distance.parse(this._parsedProps.height):gridHeight+edgePaddingTop+edgePaddingBottom})}}if(this._tabsAndMouseBitesGenerated)return;let props=this._parsedProps;if((props.panelizationMethod??"none")!=="none"){let childBoardIds=childBoardInstances.map(c3=>c3.pcb_board_id).filter(id=>!!id),boardsInPanel=db.pcb_board.list().filter(b3=>childBoardIds.includes(b3.pcb_board_id));if(boardsInPanel.length===0)return;let tabWidth=props.tabWidth??DEFAULT_TAB_WIDTH,boardGap=props.boardGap??tabWidth,{tabCutouts,mouseBiteHoles}=generatePanelTabsAndMouseBites(boardsInPanel,{boardGap,tabWidth,tabLength:props.tabLength??DEFAULT_TAB_LENGTH,mouseBites:props.mouseBites??!0});for(let tabCutout of tabCutouts)db.pcb_cutout.insert(tabCutout);for(let mouseBiteHole of mouseBiteHoles)db.pcb_hole.insert(mouseBiteHole)}this._tabsAndMouseBitesGenerated=!0}runRenderCycle(){if(!this.children.some(child=>child.componentName==="Board"))throw new Error("<panel> must contain at least one <board>");super.runRenderCycle()}doInitialPcbComponentRender(){if(super.doInitialPcbComponentRender(),this.root?.pcbDisabled)return;let{db}=this.root,props=this._parsedProps,inserted=db.pcb_panel.insert({width:props.width!==void 0?distance.parse(props.width):0,height:props.height!==void 0?distance.parse(props.height):0,center:this._getGlobalPcbPositionBeforeLayout(),covered_with_solder_mask:!(props.noSolderMask??!1)});this.pcb_panel_id=inserted.pcb_panel_id}updatePcbComponentRender(){if(this.root?.pcbDisabled||!this.pcb_panel_id)return;let{db}=this.root,props=this._parsedProps,currentPanel=db.pcb_panel.get(this.pcb_panel_id);db.pcb_panel.update(this.pcb_panel_id,{width:props.width!==void 0?distance.parse(props.width):currentPanel?.width,height:props.height!==void 0?distance.parse(props.height):currentPanel?.height,center:this._getGlobalPcbPositionBeforeLayout(),covered_with_solder_mask:!(props.noSolderMask??!1)})}removePcbComponentRender(){this.pcb_panel_id&&(this.root?.db.pcb_panel.delete(this.pcb_panel_id),this.pcb_panel_id=null)}},Pinout=class extends Chip{constructor(props){super(props)}get config(){return{...super.config,componentName:"Pinout",zodProps:pinoutProps}}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,source_component=db.source_component.insert({ftype:"simple_pinout",name:this.name,manufacturer_part_number:props.manufacturerPartNumber,supplier_part_numbers:props.supplierPartNumbers});this.source_component_id=source_component.source_component_id}},Fuse=class extends NormalComponent3{get config(){return{componentName:"fuse",schematicSymbolName:this.props.symbolName??"fuse",zodProps:fuseProps,sourceFtype:FTYPE.simple_fuse}}_getSchematicSymbolDisplayValue(){let rawCurrent=this._parsedProps.currentRating,rawVoltage=this._parsedProps.voltageRating,current2=typeof rawCurrent=="string"?parseFloat(rawCurrent):rawCurrent,voltage2=typeof rawVoltage=="string"?parseFloat(rawVoltage):rawVoltage;return`${formatSiUnit(current2)}A / ${formatSiUnit(voltage2)}V`}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,currentRating=typeof props.currentRating=="string"?parseFloat(props.currentRating):props.currentRating,voltageRating=typeof props.voltageRating=="string"?parseFloat(props.voltageRating):props.voltageRating,source_component=db.source_component.insert({name:this.name,ftype:FTYPE.simple_fuse,current_rating_amps:currentRating,voltage_rating_volts:voltageRating,display_current_rating:`${formatSiUnit(currentRating)}A`,display_voltage_rating:`${formatSiUnit(voltageRating)}V`});this.source_component_id=source_component.source_component_id}},Jumper=class extends NormalComponent3{constructor(){super(...arguments);__publicField(this,"schematicDimensions",null)}get config(){return{schematicSymbolName:void 0,componentName:"Jumper",zodProps:jumperProps,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let arrangement=super._getSchematicPortArrangement();if(arrangement&&Object.keys(arrangement).length>0)return arrangement;let pinCount=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length),direction2=this._parsedProps.schDirection??"right";return{leftSize:direction2==="left"?pinCount:0,rightSize:direction2==="right"?pinCount:0}}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,{pcbX,pcbY}=this.getResolvedPcbPositionProp(),source_component=db.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:props.manufacturerPartNumber,supplier_part_numbers:props.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=source_component.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,{pcbX,pcbY}=this.getResolvedPcbPositionProp(),pcb_component2=db.pcb_component.insert({center:{x:pcbX,y:pcbY},width:2,height:3,layer:props.layer??"top",rotation:props.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:props.doNotPlace??!1,obstructs_within_bounds:props.obstructsWithinBounds??!0});this.pcb_component_id=pcb_component2.pcb_component_id}doInitialPcbTraceRender(){let{db}=this.root,pcb_ports=db.pcb_port.list({pcb_component_id:this.pcb_component_id}),pinLabelToPortId={};for(let i3=0;i3<pcb_ports.length;i3++){let port=pcb_ports[i3],sourcePort=db.source_port.get(port.source_port_id),pinLabel="";if(typeof sourcePort?.pin_number=="number")pinLabel=sourcePort.pin_number.toString();else if(Array.isArray(sourcePort?.port_hints)){let matchedHint=sourcePort.port_hints.find(h3=>/^(pin)?\d+$/.test(h3));matchedHint&&(/^pin\d+$/.test(matchedHint)?pinLabel=matchedHint.replace(/^pin/,""):pinLabel=matchedHint)}pinLabelToPortId[pinLabel]=port.pcb_port_id}let traces=db.pcb_trace.list({pcb_component_id:this.pcb_component_id}),updatePortId=portId=>{if(portId&&typeof portId=="string"&&portId.startsWith("{PIN")){let pin=portId.replace("{PIN","").replace("}","");return pinLabelToPortId[pin]||portId}return portId};for(let trace of traces)if(trace.route)for(let segment2 of trace.route)segment2.route_type==="wire"&&(segment2.start_pcb_port_id=updatePortId(segment2.start_pcb_port_id),segment2.end_pcb_port_id=updatePortId(segment2.end_pcb_port_id))}},INTERCONNECT_STANDARD_FOOTPRINTS={"0402":"0402","0603":"0603","0805":"0805",1206:"1206"},Interconnect=class extends NormalComponent3{get config(){return{componentName:"Interconnect",zodProps:interconnectProps,shouldRenderAsSchematicBox:!0,sourceFtype:"interconnect"}}get defaultInternallyConnectedPinNames(){let{standard}=this._parsedProps;return standard&&INTERCONNECT_STANDARD_FOOTPRINTS[standard]?[["pin1","pin2"]]:[]}_getImpliedFootprintString(){let{standard}=this._parsedProps;return standard?INTERCONNECT_STANDARD_FOOTPRINTS[standard]??null:null}doInitialSourceRender(){let{db}=this.root,source_component=db.source_component.insert({ftype:"interconnect",name:this.name,are_pins_interchangeable:!0});this.source_component_id=source_component.source_component_id}doInitialSourceParentAttachment(){let{db}=this.root,internallyConnectedPorts=this._getInternallyConnectedPins();for(let ports of internallyConnectedPorts){let sourcePortIds=ports.map(port=>port.source_port_id).filter(id=>id!==null);sourcePortIds.length>=2&&db.source_component_internal_connection.insert({source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit()?.subcircuit_id,source_port_ids:sourcePortIds})}}},SolderJumper=class extends NormalComponent3{constructor(){super(...arguments);__publicField(this,"schematicDimensions",null)}_getPinNumberFromBridgedPinName(pinName){return this.selectOne(`port.${pinName}`,{type:"port"})?._parsedProps.pinNumber??null}get defaultInternallyConnectedPinNames(){if(this._parsedProps.bridged){let pins=this.children.filter(c3=>c3.componentName==="Port").map(p4=>p4.name);return pins.length>0?[pins]:[]}return this._parsedProps.bridgedPins??[]}get config(){let props=this._parsedProps??this.props,resolvedPinCount=props.pinCount;if(props.pinCount==null&&!props.footprint&&(resolvedPinCount=2),props.pinCount==null){let nums=(props.bridgedPins??[]).flat().map(p_str=>this._getPinNumberFromBridgedPinName(p_str)).filter(n3=>n3!==null),maxPinFromBridged=nums.length>0?Math.max(...nums):0,pinCountFromLabels=props.pinLabels?Object.keys(props.pinLabels).length:0,finalPinCount=Math.max(maxPinFromBridged,pinCountFromLabels);(finalPinCount===2||finalPinCount===3)&&(resolvedPinCount=finalPinCount),resolvedPinCount==null&&props.footprint&&[2,3].includes(this.getPortsFromFootprint().length)&&(resolvedPinCount=this.getPortsFromFootprint().length)}let symbolName="";resolvedPinCount?symbolName+=`solderjumper${resolvedPinCount}`:symbolName="solderjumper";let bridgedPinNumbers=[];return Array.isArray(props.bridgedPins)&&props.bridgedPins.length>0?bridgedPinNumbers=Array.from(new Set(props.bridgedPins.flat().map(pinName=>this._getPinNumberFromBridgedPinName(pinName)).filter(n3=>n3!==null))).sort((a3,b3)=>a3-b3):props.bridged&&resolvedPinCount&&(bridgedPinNumbers=Array.from({length:resolvedPinCount},(_4,i3)=>i3+1)),bridgedPinNumbers.length>0&&(symbolName+=`_bridged${bridgedPinNumbers.join("")}`),{schematicSymbolName:props.symbolName??symbolName,componentName:"SolderJumper",zodProps:solderjumperProps,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let arrangement=super._getSchematicPortArrangement();if(arrangement&&Object.keys(arrangement).length>0)return arrangement;let pinCount=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length);pinCount==null&&!this._parsedProps.footprint&&(pinCount=2);let direction2=this._parsedProps.schDirection??"right";return{leftSize:direction2==="left"?pinCount:0,rightSize:direction2==="right"?pinCount:0}}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,{pcbX,pcbY}=this.getResolvedPcbPositionProp(),source_component=db.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:props.manufacturerPartNumber,supplier_part_numbers:props.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=source_component.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,{pcbX,pcbY}=this.getResolvedPcbPositionProp(),pcb_component2=db.pcb_component.insert({center:{x:pcbX,y:pcbY},width:2,height:3,layer:props.layer??"top",rotation:props.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:props.doNotPlace??!1,obstructs_within_bounds:props.obstructsWithinBounds??!0});this.pcb_component_id=pcb_component2.pcb_component_id}doInitialPcbTraceRender(){let{db}=this.root,pcb_ports=db.pcb_port.list({pcb_component_id:this.pcb_component_id}),pinLabelToPortId={};for(let i3=0;i3<pcb_ports.length;i3++){let port=pcb_ports[i3],sourcePort=db.source_port.get(port.source_port_id),pinLabel="";if(typeof sourcePort?.pin_number=="number")pinLabel=sourcePort.pin_number.toString();else if(Array.isArray(sourcePort?.port_hints)){let matchedHint=sourcePort.port_hints.find(h3=>/^(pin)?\d+$/.test(h3));matchedHint&&(/^pin\d+$/.test(matchedHint)?pinLabel=matchedHint.replace(/^pin/,""):pinLabel=matchedHint)}pinLabelToPortId[pinLabel]=port.pcb_port_id}let traces=db.pcb_trace.list({pcb_component_id:this.pcb_component_id}),updatePortId=portId=>{if(portId&&typeof portId=="string"&&portId.startsWith("{PIN")){let pin=portId.replace("{PIN","").replace("}","");return pinLabelToPortId[pin]||portId}return portId};for(let trace of traces)if(trace.route)for(let segment2 of trace.route)segment2.route_type==="wire"&&(segment2.start_pcb_port_id=updatePortId(segment2.start_pcb_port_id),segment2.end_pcb_port_id=updatePortId(segment2.end_pcb_port_id))}},Led=class extends NormalComponent3{constructor(){super(...arguments);__publicField(this,"pos",this.portMap.pin1);__publicField(this,"anode",this.portMap.pin1);__publicField(this,"neg",this.portMap.pin2);__publicField(this,"cathode",this.portMap.pin2)}get config(){let symbolMap={laser:"laser_diode"},variantSymbol=this.props.laser?"laser":null;return{schematicSymbolName:variantSymbol?symbolMap[variantSymbol]:this.props.symbolName??"led",componentName:"Led",zodProps:ledProps,sourceFtype:"simple_led"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return this._parsedProps.schDisplayValue||this._parsedProps.color||void 0}getFootprinterString(){let baseFootprint=super.getFootprinterString();return baseFootprint&&this.props.color?`${baseFootprint}_color(${this.props.color})`:baseFootprint}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,source_component=db.source_component.insert({ftype:"simple_led",name:this.name,wave_length:props.wavelength,color:props.color,symbol_display_value:this._getSchematicSymbolDisplayValue(),manufacturer_part_number:props.manufacturerPartNumber??props.mfn,supplier_part_numbers:props.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=source_component.source_component_id}},PowerSource=class extends NormalComponent3{constructor(){super(...arguments);__publicField(this,"pos",this.portMap.pin1);__publicField(this,"positive",this.portMap.pin1);__publicField(this,"neg",this.portMap.pin2);__publicField(this,"negative",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"power_factor_meter_horz",componentName:"PowerSource",zodProps:powerSourceProps,sourceFtype:"simple_power_source"}}initPorts(){this.add(new Port({name:"pin1",pinNumber:1,aliases:["positive","pos"]})),this.add(new Port({name:"pin2",pinNumber:2,aliases:["negative","neg"]}))}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,source_component=db.source_component.insert({ftype:"simple_power_source",name:this.name,voltage:props.voltage,supplier_part_numbers:props.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=source_component.source_component_id}},VoltageSource=class extends NormalComponent3{constructor(){super(...arguments);__publicField(this,"terminal1",this.portMap.terminal1);__publicField(this,"terminal2",this.portMap.terminal2)}get config(){return{componentName:"VoltageSource",schematicSymbolName:this.props.waveShape==="square"?"square_wave":"ac_voltmeter",zodProps:voltageSourceProps,sourceFtype:"simple_voltage_source"}}runRenderPhaseForChildren(phase){if(!phase.startsWith("Pcb"))for(let child of this.children)child.runRenderPhaseForChildren(phase),child.runRenderPhase(phase)}doInitialPcbComponentRender(){}initPorts(){super.initPorts({additionalAliases:{pin1:["terminal1"],pin2:["terminal2"]}})}_getSchematicSymbolDisplayValue(){let{voltage:voltage2,frequency:frequency2}=this._parsedProps,parts=[];return voltage2!==void 0&&parts.push(`${formatSiUnit(voltage2)}V`),frequency2!==void 0&&parts.push(`${formatSiUnit(frequency2)}Hz`),parts.length>0?parts.join(" "):void 0}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,source_component=db.source_component.insert({ftype:"simple_voltage_source",name:this.name,voltage:props.voltage,frequency:props.frequency,peak_to_peak_voltage:props.peakToPeakVoltage,wave_shape:props.waveShape,phase:props.phase,duty_cycle:props.dutyCycle,supplier_part_numbers:props.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=source_component.source_component_id}doInitialSimulationRender(){let{db}=this.root,{_parsedProps:props}=this,terminal1Port=this.portMap.terminal1,terminal2Port=this.portMap.terminal2;db.simulation_voltage_source.insert({type:"simulation_voltage_source",is_dc_source:!1,terminal1_source_port_id:terminal1Port.source_port_id,terminal2_source_port_id:terminal2Port.source_port_id,voltage:props.voltage,frequency:props.frequency,peak_to_peak_voltage:props.peakToPeakVoltage,wave_shape:props.waveShape,phase:props.phase,duty_cycle:props.dutyCycle})}},edgeSpecifiers=["leftedge","rightedge","topedge","bottomedge","center"],Constraint3=class extends PrimitiveComponent2{get config(){return{componentName:"Constraint",zodProps:constraintProps}}constructor(props){if(super(props),("xdist"in props||"ydist"in props)&&!("edgeToEdge"in props)&&!("centerToCenter"in props))throw new Error(`edgeToEdge, centerToCenter must be set for xDist or yDist for ${this}`);if("for"in props&&props.for.length<2)throw new Error(`"for" must have at least two selectors for ${this}`)}_getAllReferencedComponents(){let componentsWithSelectors=[],container=this.getPrimitiveContainer();function addComponentFromSelector(selector){let maybeEdge=selector.split(" ").pop(),edge=edgeSpecifiers.includes(maybeEdge)?maybeEdge:void 0,componentSelector=edge?selector.replace(` ${edge}`,""):selector,component=container.selectOne(componentSelector,{pcbPrimitive:!0});component&&componentsWithSelectors.push({selector,component,componentSelector,edge})}for(let key of["left","right","top","bottom"])key in this._parsedProps&&addComponentFromSelector(this._parsedProps[key]);if("for"in this._parsedProps)for(let selector of this._parsedProps.for)addComponentFromSelector(selector);return{componentsWithSelectors}}},FabricationNoteRect=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"fabrication_note_rect_id",null)}get config(){return{componentName:"FabricationNoteRect",zodProps:fabricationNoteRectProps}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,{pcbX,pcbY}=this.getResolvedPcbPositionProp(),{maybeFlipLayer}=this._getPcbPrimitiveFlippedHelpers(),layer=maybeFlipLayer(props.layer??"top");if(layer!=="top"&&layer!=="bottom")throw new Error(`Invalid layer "${layer}" for FabricationNoteRect. Must be "top" or "bottom".`);let pcb_component_id=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,subcircuit=this.getSubcircuit(),hasStroke=props.hasStroke??(props.strokeWidth!==void 0&&props.strokeWidth!==null),fabrication_note_rect=db.pcb_fabrication_note_rect.insert({pcb_component_id,layer,color:props.color,center:{x:pcbX,y:pcbY},width:props.width,height:props.height,stroke_width:props.strokeWidth??1,is_filled:props.isFilled??!1,has_stroke:hasStroke,is_stroke_dashed:props.isStrokeDashed??!1,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,corner_radius:props.cornerRadius??void 0});this.fabrication_note_rect_id=fabrication_note_rect.pcb_fabrication_note_rect_id}getPcbSize(){let{_parsedProps:props}=this;return{width:props.width,height:props.height}}},FabricationNotePath=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"fabrication_note_path_id",null)}get config(){return{componentName:"FabricationNotePath",zodProps:fabricationNotePathProps}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,subcircuit=this.getSubcircuit(),{_parsedProps:props}=this,layer=props.layer??"top";if(layer!=="top"&&layer!=="bottom")throw new Error(`Invalid layer "${layer}" for SilkscreenPath. Must be "top" or "bottom".`);let transform5=this._computePcbGlobalTransformBeforeLayout(),pcb_component_id=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,fabrication_note_path=db.pcb_fabrication_note_path.insert({pcb_component_id,layer,color:props.color,route:props.route.map(p4=>{let transformedPosition=applyToPoint(transform5,{x:p4.x,y:p4.y});return{...p4,x:transformedPosition.x,y:transformedPosition.y}}),stroke_width:props.strokeWidth??.1,subcircuit_id:subcircuit?.subcircuit_id??void 0});this.fabrication_note_path_id=fabrication_note_path.pcb_fabrication_note_path_id}},FabricationNoteText=class extends PrimitiveComponent2{get config(){return{componentName:"FabricationNoteText",zodProps:fabricationNoteTextProps}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,{pcbX,pcbY}=this.getResolvedPcbPositionProp(),container=this.getPrimitiveContainer(),subcircuit=this.getSubcircuit();db.pcb_fabrication_note_text.insert({anchor_alignment:props.anchorAlignment,anchor_position:{x:pcbX,y:pcbY},font:props.font??"tscircuit2024",font_size:props.fontSize??1,layer:"top",color:props.color,text:normalizeTextForCircuitJson(props.text??""),pcb_component_id:container.pcb_component_id,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}},FabricationNoteDimension=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"fabrication_note_dimension_id",null);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"FabricationNoteDimension",zodProps:fabricationNoteDimensionProps}}_resolvePoint(input2,transform5){if(typeof input2=="string"){let target=this.getSubcircuit().selectOne(input2);return target?target._getGlobalPcbPositionBeforeLayout():(this.renderError(`FabricationNoteDimension could not find selector "${input2}"`),applyToPoint(transform5,{x:0,y:0}))}let numericX=typeof input2.x=="string"?parseFloat(input2.x):input2.x,numericY=typeof input2.y=="string"?parseFloat(input2.y):input2.y;return applyToPoint(transform5,{x:numericX,y:numericY})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,transform5=this._computePcbGlobalTransformBeforeLayout(),from=this._resolvePoint(props.from,transform5),to2=this._resolvePoint(props.to,transform5),subcircuit=this.getSubcircuit(),group=this.getGroup(),{maybeFlipLayer}=this._getPcbPrimitiveFlippedHelpers(),layer=maybeFlipLayer(props.layer??"top");if(layer!=="top"&&layer!=="bottom")throw new Error(`Invalid layer "${layer}" for FabricationNoteDimension. Must be "top" or "bottom".`);let pcb_component_id=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,text=props.text??this._formatDistanceText({from,to:to2,units:props.units??"mm"}),fabrication_note_dimension=db.pcb_fabrication_note_dimension.insert({pcb_component_id,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:group?.pcb_group_id??void 0,layer,from,to:to2,text,offset:props.offset,font:props.font??"tscircuit2024",font_size:props.fontSize??1,color:props.color,arrow_size:props.arrowSize??1});this.fabrication_note_dimension_id=fabrication_note_dimension.pcb_fabrication_note_dimension_id}getPcbSize(){let transform5=this._computePcbGlobalTransformBeforeLayout(),from=this._resolvePoint(this._parsedProps.from,transform5),to2=this._resolvePoint(this._parsedProps.to,transform5);return{width:Math.abs(to2.x-from.x),height:Math.abs(to2.y-from.y)}}_formatDistanceText({from,to:to2,units}){let dx2=to2.x-from.x,dy2=to2.y-from.y,distanceInMillimeters=Math.sqrt(dx2*dx2+dy2*dy2),distanceInUnits=units==="in"?distanceInMillimeters/25.4:distanceInMillimeters,roundedDistance=Math.round(distanceInUnits);if(Math.abs(distanceInUnits-roundedDistance)<1e-9)return`${roundedDistance}${units}`;let decimalPlaces=units==="in"?3:2;return`${units==="in"?Number(distanceInUnits.toFixed(decimalPlaces)).toString():distanceInUnits.toFixed(decimalPlaces)}${units}`}},PcbNoteLine=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"pcb_note_line_id",null);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteLine",zodProps:pcbNoteLineProps}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,subcircuit=this.getSubcircuit(),group=this.getGroup(),transform5=this._computePcbGlobalTransformBeforeLayout(),start=applyToPoint(transform5,{x:props.x1,y:props.y1}),end=applyToPoint(transform5,{x:props.x2,y:props.y2}),pcb_component_id=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,pcb_note_line2=db.pcb_note_line.insert({pcb_component_id,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:group?.pcb_group_id??void 0,x1:start.x,y1:start.y,x2:end.x,y2:end.y,stroke_width:props.strokeWidth??.1,color:props.color,is_dashed:props.isDashed});this.pcb_note_line_id=pcb_note_line2.pcb_note_line_id}getPcbSize(){let{_parsedProps:props}=this;return{width:Math.abs(props.x2-props.x1),height:Math.abs(props.y2-props.y1)}}},PcbNoteRect=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"pcb_note_rect_id",null);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteRect",zodProps:pcbNoteRectProps}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,transform5=this._computePcbGlobalTransformBeforeLayout(),center2=applyToPoint(transform5,{x:0,y:0}),subcircuit=this.getSubcircuit(),group=this.getGroup(),pcb_component_id=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,pcb_note_rect2=db.pcb_note_rect.insert({pcb_component_id,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:group?.pcb_group_id??void 0,center:center2,width:props.width,height:props.height,stroke_width:props.strokeWidth??.1,is_filled:props.isFilled??!1,has_stroke:props.hasStroke??!0,is_stroke_dashed:props.isStrokeDashed??!1,color:props.color,corner_radius:props.cornerRadius??void 0});this.pcb_note_rect_id=pcb_note_rect2.pcb_note_rect_id}getPcbSize(){let{_parsedProps:props}=this,width=typeof props.width=="string"?parseFloat(props.width):props.width,height=typeof props.height=="string"?parseFloat(props.height):props.height;return{width,height}}},PcbNoteText=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"pcb_note_text_id",null);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteText",zodProps:pcbNoteTextProps}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,transform5=this._computePcbGlobalTransformBeforeLayout(),anchorPosition=applyToPoint(transform5,{x:0,y:0}),subcircuit=this.getSubcircuit(),group=this.getGroup(),pcb_component_id=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,pcb_note_text2=db.pcb_note_text.insert({pcb_component_id,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:group?.pcb_group_id??void 0,font:props.font??"tscircuit2024",font_size:props.fontSize??1,text:normalizeTextForCircuitJson(props.text),anchor_position:anchorPosition,anchor_alignment:props.anchorAlignment??"center",color:props.color});this.pcb_note_text_id=pcb_note_text2.pcb_note_text_id}getPcbSize(){let{_parsedProps:props}=this,fontSize=typeof props.fontSize=="string"?parseFloat(props.fontSize):props.fontSize??1,charWidth=fontSize*.6;return{width:props.text.length*charWidth,height:fontSize}}},PcbNotePath=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"pcb_note_path_id",null);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNotePath",zodProps:pcbNotePathProps}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,transform5=this._computePcbGlobalTransformBeforeLayout(),subcircuit=this.getSubcircuit(),group=this.getGroup(),pcb_component_id=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,transformedRoute=props.route.map(point23=>{let{x:x3,y:y3,...rest}=point23,numericX=typeof x3=="string"?parseFloat(x3):x3,numericY=typeof y3=="string"?parseFloat(y3):y3,transformed=applyToPoint(transform5,{x:numericX,y:numericY});return{...rest,x:transformed.x,y:transformed.y}}),pcb_note_path2=db.pcb_note_path.insert({pcb_component_id,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:group?.pcb_group_id??void 0,route:transformedRoute,stroke_width:props.strokeWidth??.1,color:props.color});this.pcb_note_path_id=pcb_note_path2.pcb_note_path_id}getPcbSize(){let{_parsedProps:props}=this;if(props.route.length===0)return{width:0,height:0};let xs3=props.route.map(point23=>typeof point23.x=="string"?parseFloat(point23.x):point23.x),ys3=props.route.map(point23=>typeof point23.y=="string"?parseFloat(point23.y):point23.y),minX=Math.min(...xs3),maxX=Math.max(...xs3),minY=Math.min(...ys3),maxY=Math.max(...ys3);return{width:maxX-minX,height:maxY-minY}}},PcbNoteDimension=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"pcb_note_dimension_id",null);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteDimension",zodProps:pcbNoteDimensionProps}}_resolvePoint(input2,transform5){if(typeof input2=="string"){let target=this.getSubcircuit().selectOne(`.${input2}`);return target?target._getGlobalPcbPositionBeforeLayout():(this.renderError(`PcbNoteDimension could not find selector "${input2}"`),applyToPoint(transform5,{x:0,y:0}))}let numericX=typeof input2.x=="string"?parseFloat(input2.x):input2.x,numericY=typeof input2.y=="string"?parseFloat(input2.y):input2.y;return applyToPoint(transform5,{x:numericX,y:numericY})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,transform5=this._computePcbGlobalTransformBeforeLayout(),from=this._resolvePoint(props.from,transform5),to2=this._resolvePoint(props.to,transform5),subcircuit=this.getSubcircuit(),group=this.getGroup(),pcb_component_id=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,text=props.text??this._formatDistanceText({from,to:to2,units:props.units??"mm"}),pcb_note_dimension2=db.pcb_note_dimension.insert({pcb_component_id,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:group?.pcb_group_id??void 0,from,to:to2,text,font:props.font??"tscircuit2024",font_size:props.fontSize??1,color:props.color,arrow_size:props.arrowSize??1});this.pcb_note_dimension_id=pcb_note_dimension2.pcb_note_dimension_id}getPcbSize(){let transform5=this._computePcbGlobalTransformBeforeLayout(),from=this._resolvePoint(this._parsedProps.from,transform5),to2=this._resolvePoint(this._parsedProps.to,transform5);return{width:Math.abs(to2.x-from.x),height:Math.abs(to2.y-from.y)}}_formatDistanceText({from,to:to2,units}){let dx2=to2.x-from.x,dy2=to2.y-from.y,distanceInMillimeters=Math.sqrt(dx2*dx2+dy2*dy2),distanceInUnits=units==="in"?distanceInMillimeters/25.4:distanceInMillimeters,roundedDistance=Math.round(distanceInUnits);if(Math.abs(distanceInUnits-roundedDistance)<1e-9)return`${roundedDistance}${units}`;let decimalPlaces=units==="in"?3:2;return`${units==="in"?Number(distanceInUnits.toFixed(decimalPlaces)).toString():distanceInUnits.toFixed(decimalPlaces)}${units}`}},Subcircuit=class extends Group6{constructor(props){super({...props,subcircuit:!0})}doInitialInflateSubcircuitCircuitJson(){let{circuitJson,children}=this._parsedProps;inflateCircuitJson(this,circuitJson,children)}},Breakout=class extends Group6{constructor(props){super({...props,subcircuit:!0})}doInitialPcbPrimitiveRender(){if(super.doInitialPcbPrimitiveRender(),this.root?.pcbDisabled)return;let{db}=this.root,props=this._parsedProps;if(!this.pcb_group_id)return;let pcb_group2=db.pcb_group.get(this.pcb_group_id),padLeft=props.paddingLeft??props.padding??0,padRight=props.paddingRight??props.padding??0,padTop=props.paddingTop??props.padding??0,padBottom=props.paddingBottom??props.padding??0;db.pcb_group.update(this.pcb_group_id,{width:(pcb_group2.width??0)+padLeft+padRight,height:(pcb_group2.height??0)+padTop+padBottom,center:{x:pcb_group2.center.x+(padRight-padLeft)/2,y:pcb_group2.center.y+(padTop-padBottom)/2}})}},BreakoutPoint=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"pcb_breakout_point_id",null);__publicField(this,"matchedPort",null);__publicField(this,"matchedNet",null);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"BreakoutPoint",zodProps:breakoutPointProps}}_matchConnection(){let{connection}=this._parsedProps,subcircuit=this.getSubcircuit();subcircuit&&(this.matchedPort=subcircuit.selectOne(connection,{type:"port"}),this.matchedPort||(this.matchedNet=subcircuit.selectOne(connection,{type:"net"})),!this.matchedPort&&!this.matchedNet&&this.renderError(`Could not find connection target "${connection}"`))}_getSourceTraceIdForPort(port){let{db}=this.root;return db.source_trace.list().find(st3=>st3.connected_source_port_ids.includes(port.source_port_id))?.source_trace_id}_getSourceNetIdForPort(port){let{db}=this.root;return db.source_trace.list().find(st3=>st3.connected_source_port_ids.includes(port.source_port_id))?.connected_source_net_ids[0]}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root;this._matchConnection();let{pcbX,pcbY}=this.getResolvedPcbPositionProp(),group=this.parent?.getGroup(),subcircuit=this.getSubcircuit();if(!group||!group.pcb_group_id)return;let pcb_breakout_point2=db.pcb_breakout_point.insert({pcb_group_id:group.pcb_group_id,subcircuit_id:subcircuit?.subcircuit_id??void 0,source_port_id:this.matchedPort?.source_port_id??void 0,source_trace_id:this.matchedPort?this._getSourceTraceIdForPort(this.matchedPort):void 0,source_net_id:this.matchedNet?this.matchedNet.source_net_id:this.matchedPort?this._getSourceNetIdForPort(this.matchedPort):void 0,x:pcbX,y:pcbY});this.pcb_breakout_point_id=pcb_breakout_point2.pcb_breakout_point_id}_getPcbCircuitJsonBounds(){let{pcbX,pcbY}=this.getResolvedPcbPositionProp();return{center:{x:pcbX,y:pcbY},bounds:{left:pcbX,top:pcbY,right:pcbX,bottom:pcbY},width:0,height:0}}_setPositionFromLayout(newCenter){let{db}=this.root;this.pcb_breakout_point_id&&db.pcb_breakout_point.update(this.pcb_breakout_point_id,{x:newCenter.x,y:newCenter.y})}getPcbSize(){return{width:0,height:0}}},NetLabel=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"source_net_label_id")}get config(){return{componentName:"NetLabel",zodProps:netLabelProps}}_getAnchorSide(){let{_parsedProps:props}=this;if(props.anchorSide)return props.anchorSide;if(!this._resolveConnectsTo())return"right";let anchorPos=this._getGlobalSchematicPositionBeforeLayout(),connectedPorts=this._getConnectedPorts();if(connectedPorts.length===0)return"right";let connectedPortPosition=connectedPorts[0]._getGlobalSchematicPositionBeforeLayout(),dx2=connectedPortPosition.x-anchorPos.x,dy2=connectedPortPosition.y-anchorPos.y;if(Math.abs(dx2)>Math.abs(dy2)){if(dx2>0)return"right";if(dx2<0)return"left"}else{if(dy2>0)return"top";if(dy2<0)return"bottom"}return"right"}_getConnectedPorts(){let connectsTo=this._resolveConnectsTo();if(!connectsTo)return[];let connectedPorts=[];for(let connection of connectsTo){let port=this.getSubcircuit().selectOne(connection);port&&connectedPorts.push(port)}return connectedPorts}computeSchematicPropsTransform(){let{_parsedProps:props}=this;if(props.schX===void 0&&props.schY===void 0){let connectedPorts=this._getConnectedPorts();if(connectedPorts.length>0){let portPos=connectedPorts[0]._getGlobalSchematicPositionBeforeLayout(),parentCenter=applyToPoint(this.parent?.computeSchematicGlobalTransform?.()??identity(),{x:0,y:0});return translate(portPos.x-parentCenter.x,portPos.y-parentCenter.y)}}return super.computeSchematicPropsTransform()}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db}=this.root,{_parsedProps:props}=this,anchorPos=this._getGlobalSchematicPositionBeforeLayout(),net=this.getSubcircuit().selectOne(`net.${this._getNetName()}`),anchorSide=props.anchorSide??"right",center2=computeSchematicNetLabelCenter({anchor_position:anchorPos,anchor_side:anchorSide,text:props.net}),netLabel=db.schematic_net_label.insert({text:props.net,source_net_id:net.source_net_id,anchor_position:anchorPos,center:center2,anchor_side:this._getAnchorSide()});this.source_net_label_id=netLabel.source_net_id}_resolveConnectsTo(){let{_parsedProps:props}=this,connectsTo=props.connectsTo??props.connection;if(Array.isArray(connectsTo))return connectsTo;if(typeof connectsTo=="string")return[connectsTo]}_getNetName(){let{_parsedProps:props}=this;return props.net}doInitialCreateNetsFromProps(){let{_parsedProps:props}=this;props.net&&createNetsFromProps(this,[`net.${props.net}`])}doInitialCreateTracesFromNetLabels(){if(this.root?.schematicDisabled)return;let connectsTo=this._resolveConnectsTo();if(connectsTo)for(let connection of connectsTo)this.add(new Trace3({from:connection,to:`net.${this._getNetName()}`}))}doInitialSchematicTraceRender(){if(!this.root?._featureMspSchematicTraceRouting||this.root?.schematicDisabled)return;let{db}=this.root,connectsTo=this._resolveConnectsTo();if(!connectsTo||connectsTo.length===0)return;let anchorPos=this._getGlobalSchematicPositionBeforeLayout(),anchorSide=this._getAnchorSide(),anchorFacing={left:"x-",right:"x+",top:"y+",bottom:"y-"}[anchorSide],net=this.getSubcircuit().selectOne(`net.${this._getNetName()}`);for(let connection of connectsTo){let port=this.getSubcircuit().selectOne(connection,{type:"port"});if(!port||!port.schematic_port_id)continue;let existingTraceForThisConnection=!1;if(net?.source_net_id){let candidateSourceTrace=db.source_trace.list().find(st3=>st3.connected_source_net_ids?.includes(net.source_net_id)&&st3.connected_source_port_ids?.includes(port.source_port_id??""));if(candidateSourceTrace&&(existingTraceForThisConnection=db.schematic_trace.list().some(t6=>t6.source_trace_id===candidateSourceTrace.source_trace_id)),existingTraceForThisConnection)continue}let portPos=port._getGlobalSchematicPositionAfterLayout(),portFacing=convertFacingDirectionToElbowDirection(port.facingDirection??"right")??"x+",path=calculateElbow({x:portPos.x,y:portPos.y,facingDirection:portFacing},{x:anchorPos.x,y:anchorPos.y,facingDirection:anchorFacing});if(!Array.isArray(path)||path.length<2)continue;let edges=[];for(let i3=0;i3<path.length-1;i3++)edges.push({from:{x:path[i3].x,y:path[i3].y},to:{x:path[i3+1].x,y:path[i3+1].y}});let source_trace_id,subcircuit_connectivity_map_key;if(net?.source_net_id&&port.source_port_id){let st3=db.source_trace.list().find(s4=>s4.connected_source_net_ids?.includes(net.source_net_id)&&s4.connected_source_port_ids?.includes(port.source_port_id));source_trace_id=st3?.source_trace_id,subcircuit_connectivity_map_key=st3?.subcircuit_connectivity_map_key||db.source_net.get(net.source_net_id)?.subcircuit_connectivity_map_key}db.schematic_trace.insert({source_trace_id,edges,junctions:[],subcircuit_connectivity_map_key}),db.schematic_port.update(port.schematic_port_id,{is_connected:!0})}}},SilkscreenCircle=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"pcb_silkscreen_circle_id",null);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenCircle",zodProps:silkscreenCircleProps}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,{pcbX,pcbY}=this.getResolvedPcbPositionProp(),{maybeFlipLayer}=this._getPcbPrimitiveFlippedHelpers(),layer=maybeFlipLayer(props.layer??"top");if(layer!=="top"&&layer!=="bottom")throw new Error(`Invalid layer "${layer}" for SilkscreenCircle. Must be "top" or "bottom".`);let transform5=this._computePcbGlobalTransformBeforeLayout(),subcircuit=this.getSubcircuit(),pcb_component_id=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,pcb_silkscreen_circle2=db.pcb_silkscreen_circle.insert({pcb_component_id,layer,center:{x:pcbX,y:pcbY},radius:props.radius,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,stroke_width:props.strokeWidth??.1});this.pcb_silkscreen_circle_id=pcb_silkscreen_circle2.pcb_silkscreen_circle_id}getPcbSize(){let{_parsedProps:props}=this,diameter=props.radius*2;return{width:diameter,height:diameter}}_repositionOnPcb({deltaX,deltaY}){if(this.root?.pcbDisabled)return;let{db}=this.root;if(!this.pcb_silkscreen_circle_id)return;let circle2=db.pcb_silkscreen_circle.get(this.pcb_silkscreen_circle_id);circle2&&db.pcb_silkscreen_circle.update(this.pcb_silkscreen_circle_id,{center:{x:circle2.center.x+deltaX,y:circle2.center.y+deltaY}})}},SilkscreenRect=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"pcb_silkscreen_rect_id",null);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenRect",zodProps:silkscreenRectProps}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,{maybeFlipLayer}=this._getPcbPrimitiveFlippedHelpers(),layer=maybeFlipLayer(props.layer??"top");if(layer!=="top"&&layer!=="bottom")throw new Error(`Invalid layer "${layer}" for SilkscreenRect. Must be "top" or "bottom".`);let subcircuit=this.getSubcircuit(),position2=this._getGlobalPcbPositionBeforeLayout(),pcb_component_id=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,pcb_silkscreen_rect2=db.pcb_silkscreen_rect.insert({pcb_component_id,layer,center:{x:position2.x,y:position2.y},width:props.width,height:props.height,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this?.getGroup()?.pcb_group_id??void 0,stroke_width:props.strokeWidth??.1,is_filled:props.filled??!1,corner_radius:props.cornerRadius??void 0});this.pcb_silkscreen_rect_id=pcb_silkscreen_rect2.pcb_silkscreen_rect_id}getPcbSize(){let{_parsedProps:props}=this;return{width:props.width,height:props.height}}_repositionOnPcb({deltaX,deltaY}){if(this.root?.pcbDisabled)return;let{db}=this.root;if(!this.pcb_silkscreen_rect_id)return;let rect=db.pcb_silkscreen_rect.get(this.pcb_silkscreen_rect_id);rect&&db.pcb_silkscreen_rect.update(this.pcb_silkscreen_rect_id,{center:{x:rect.center.x+deltaX,y:rect.center.y+deltaY}})}},SilkscreenLine=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"pcb_silkscreen_line_id",null);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenLine",zodProps:silkscreenLineProps}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,{maybeFlipLayer}=this._getPcbPrimitiveFlippedHelpers(),layer=maybeFlipLayer(props.layer??"top");if(layer!=="top"&&layer!=="bottom")throw new Error(`Invalid layer "${layer}" for SilkscreenLine. Must be "top" or "bottom".`);let subcircuit=this.getSubcircuit(),pcb_component_id=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,pcb_silkscreen_line2=db.pcb_silkscreen_line.insert({pcb_component_id,layer,x1:props.x1,y1:props.y1,x2:props.x2,y2:props.y2,stroke_width:props.strokeWidth??.1,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:subcircuit?.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_line_id=pcb_silkscreen_line2.pcb_silkscreen_line_id}getPcbSize(){let{_parsedProps:props}=this,width=Math.abs(props.x2-props.x1),height=Math.abs(props.y2-props.y1);return{width,height}}_repositionOnPcb({deltaX,deltaY}){if(this.root?.pcbDisabled)return;let{db}=this.root;if(!this.pcb_silkscreen_line_id)return;let line2=db.pcb_silkscreen_line.get(this.pcb_silkscreen_line_id);line2&&db.pcb_silkscreen_line.update(this.pcb_silkscreen_line_id,{x1:line2.x1+deltaX,y1:line2.y1+deltaY,x2:line2.x2+deltaX,y2:line2.y2+deltaY})}},Fiducial=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"pcb_smtpad_id",null);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Fiducial",zodProps:fiducialProps,sourceFtype:"simple_fiducial"}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,position2=this._getGlobalPcbPositionBeforeLayout(),{maybeFlipLayer}=this._getPcbPrimitiveFlippedHelpers(),pcb_component_id=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,pcb_smtpad2=db.pcb_smtpad.insert({pcb_component_id,layer:maybeFlipLayer(props.layer||"top"),shape:"circle",x:position2.x,y:position2.y,radius:distance.parse(props.padDiameter)/2,soldermask_margin:props.soldermaskPullback?distance.parse(props.soldermaskPullback):distance.parse(props.padDiameter)/2,is_covered_with_solder_mask:!0});this.pcb_smtpad_id=pcb_smtpad2.pcb_smtpad_id}getPcbSize(){let{_parsedProps:props}=this,d2=distance.parse(props.padDiameter);return{width:d2,height:d2}}_setPositionFromLayout(newCenter){if(!this.pcb_smtpad_id)return;let{db}=this.root;db.pcb_smtpad.update(this.pcb_smtpad_id,{x:newCenter.x,y:newCenter.y})}},Via=class extends PrimitiveComponent2{constructor(props){super(props);__publicField(this,"pcb_via_id",null);__publicField(this,"matchedPort",null);__publicField(this,"isPcbPrimitive",!0);__publicField(this,"source_manually_placed_via_id",null);__publicField(this,"subcircuit_connectivity_map_key",null);let layers=this._getLayers();this._parsedProps.layers=layers,this.initPorts()}get config(){return{componentName:"Via",zodProps:viaProps}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}_getResolvedViaDiameters(pcbStyle2){return getViaDiameterDefaultsWithOverrides({holeDiameter:this._parsedProps.holeDiameter,padDiameter:this._parsedProps.outerDiameter},pcbStyle2)}getPcbSize(){let pcbStyle2=this.getInheritedMergedProperty("pcbStyle"),{padDiameter}=this._getResolvedViaDiameters(pcbStyle2);return{width:padDiameter,height:padDiameter}}_getPcbCircuitJsonBounds(){let{db}=this.root,via=db.pcb_via.get(this.pcb_via_id),size2=this.getPcbSize();return{center:{x:via.x,y:via.y},bounds:{left:via.x-size2.width/2,top:via.y-size2.height/2,right:via.x+size2.width/2,bottom:via.y+size2.height/2},width:size2.width,height:size2.height}}_setPositionFromLayout(newCenter){let{db}=this.root;db.pcb_via.update(this.pcb_via_id,{x:newCenter.x,y:newCenter.y})}_getLayers(){let{fromLayer="top",toLayer="bottom"}=this._parsedProps;return fromLayer===toLayer?[fromLayer]:[fromLayer,toLayer]}initPorts(){let layers=this._parsedProps.layers;for(let layer of layers){let port2=new Port({name:layer,layer});port2.registerMatch(this),this.add(port2)}let port=new Port({name:"pin1"});port.registerMatch(this),this.add(port)}_getConnectedNetOrTrace(){let connectsTo=this._parsedProps.connectsTo;if(!connectsTo)return null;let subcircuit=this.getSubcircuit(),selectors=Array.isArray(connectsTo)?connectsTo:[connectsTo];for(let selector of selectors)if(selector.startsWith("net.")){let net=subcircuit.selectOne(selector,{type:"net"});if(net)return net}return null}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,pcbStyle2=this.getInheritedMergedProperty("pcbStyle"),{padDiameter}=this._getResolvedViaDiameters(pcbStyle2),position2=this._getGlobalPcbPositionBeforeLayout(),subcircuit=this.getSubcircuit(),pcb_component2=db.pcb_component.insert({center:position2,width:padDiameter,height:padDiameter,layer:this._parsedProps.fromLayer??"top",rotation:0,source_component_id:this.source_component_id,subcircuit_id:subcircuit?.subcircuit_id??void 0,obstructs_within_bounds:!0});this.pcb_component_id=pcb_component2.pcb_component_id}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,group=this.getGroup(),subcircuit=this.getSubcircuit(),source_via=db.source_manually_placed_via.insert({source_group_id:group?.source_group_id,source_net_id:props.net??"",subcircuit_id:subcircuit?.subcircuit_id??void 0});this.source_component_id=source_via.source_manually_placed_via_id}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,pcbStyle2=this.getInheritedMergedProperty("pcbStyle"),{holeDiameter,padDiameter}=this._getResolvedViaDiameters(pcbStyle2),position2=this._getGlobalPcbPositionBeforeLayout(),subcircuit=this.getSubcircuit(),pcb_via2=db.pcb_via.insert({x:position2.x,y:position2.y,hole_diameter:holeDiameter,outer_diameter:padDiameter,layers:["bottom","top"],from_layer:this._parsedProps.fromLayer||"bottom",to_layer:this._parsedProps.toLayer||"top",subcircuit_id:subcircuit?.subcircuit_id??void 0,subcircuit_connectivity_map_key:this.subcircuit_connectivity_map_key??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,net_is_assignable:this._parsedProps.netIsAssignable??void 0});this.pcb_via_id=pcb_via2.pcb_via_id}},CopperPour=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"CopperPour",zodProps:copperPourProps}}getPcbSize(){return{width:0,height:0}}doInitialCreateNetsFromProps(){let{_parsedProps:props}=this;createNetsFromProps(this,[props.connectsTo])}doInitialPcbCopperPourRender(){this.root?.pcbDisabled||this._queueAsyncEffect("PcbCopperPourRender",async()=>{let{db}=this.root,{_parsedProps:props}=this,net=this.getSubcircuit().selectOne(props.connectsTo);if(!net||!net.source_net_id){this.renderError(`Net "${props.connectsTo}" not found for copper pour`);return}let subcircuit=this.getSubcircuit(),sourceNet=db.toArray().filter(elm=>elm.type==="source_net"&&elm.name===net.name)[0]||"",clearance=props.clearance??.2,inputProblem=convertCircuitJsonToInputProblem(db.toArray(),{layer:props.layer,pour_connectivity_key:sourceNet.subcircuit_connectivity_map_key||"",pad_margin:props.padMargin??clearance,trace_margin:props.traceMargin??clearance,board_edge_margin:props.boardEdgeMargin??clearance,cutout_margin:props.cutoutMargin??clearance}),solver=new CopperPourPipelineSolver(inputProblem);this.root.emit("solver:started",{solverName:"CopperPourPipelineSolver",solverParams:inputProblem,componentName:this.props.name});let{brep_shapes}=solver.getOutput(),coveredWithSolderMask=props.coveredWithSolderMask??!1;for(let brep_shape2 of brep_shapes)db.pcb_copper_pour.insert({shape:"brep",layer:props.layer,brep_shape:brep_shape2,source_net_id:net.source_net_id,subcircuit_id:subcircuit?.subcircuit_id??void 0,covered_with_solder_mask:coveredWithSolderMask})})}},CopperText=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"isPcbPrimitive",!0)}get config(){return{componentName:"CopperText",zodProps:copperTextProps}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db}=this.root,{_parsedProps:props}=this,container=this.getPrimitiveContainer(),position2=this._getGlobalPcbPositionBeforeLayout(),subcircuit=this.getSubcircuit();db.pcb_copper_text.insert({anchor_alignment:props.anchorAlignment,anchor_position:{x:position2.x,y:position2.y},font:"tscircuit2024",font_size:props.fontSize,layer:props.layer??"top",text:normalizeTextForCircuitJson(props.text),ccw_rotation:props.pcbRotation,is_mirrored:props.mirrored,is_knockout:props.knockout,pcb_component_id:container.pcb_component_id,subcircuit_id:subcircuit?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}},Battery=class extends NormalComponent3{get config(){return{componentName:"Battery",schematicSymbolName:this.props.symbolName??"battery",zodProps:batteryProps,sourceFtype:"simple_power_source"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,source_component=db.source_component.insert({name:this.name,ftype:"simple_power_source",capacity:props.capacity,supplier_part_numbers:props.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=source_component.source_component_id}},PinHeader=class extends NormalComponent3{_getPcbRotationBeforeLayout(){let orientationRotation=this.props.pcbOrientation==="vertical"?-90:0;return(super._getPcbRotationBeforeLayout()??0)+orientationRotation}get config(){return{componentName:"PinHeader",zodProps:pinHeaderProps,shouldRenderAsSchematicBox:!0}}_getImpliedFootprintString(){let pinCount=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:0),holeDiameter=this._parsedProps.holeDiameter,platedDiameter=this._parsedProps.platedDiameter,pitch=this._parsedProps.pitch,showSilkscreenPinLabels=this._parsedProps.showSilkscreenPinLabels,rows=this._parsedProps.doubleRow?2:1;if(pinCount>0){let footprintString;if(pitch)!holeDiameter&&!platedDiameter?footprintString=`pinrow${pinCount}_p${pitch}`:footprintString=`pinrow${pinCount}_p${pitch}_id${holeDiameter}_od${platedDiameter}`;else if(!holeDiameter&&!platedDiameter)footprintString=`pinrow${pinCount}`;else return null;return showSilkscreenPinLabels!==!0&&(footprintString+="_nopinlabels"),rows>1&&(footprintString+=`_rows${rows}`),footprintString}return null}initPorts(){let pinCount=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:1);for(let i3=1;i3<=pinCount;i3++){let rawLabel=Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels[i3-1]:this._parsedProps.pinLabels?.[`pin${i3}`];if(rawLabel){let primaryLabel=Array.isArray(rawLabel)?rawLabel[0]:rawLabel,otherLabels=Array.isArray(rawLabel)?rawLabel.slice(1):[];this.add(new Port({pinNumber:i3,name:primaryLabel,aliases:[`pin${i3}`,...otherLabels]}))}else this.add(new Port({pinNumber:i3,name:`pin${i3}`}))}}_getSchematicPortArrangement(){let pinCount=this._parsedProps.pinCount??1,facingDirection=this._parsedProps.schFacingDirection??this._parsedProps.facingDirection??"right",schPinArrangement=this._parsedProps.schPinArrangement;return facingDirection==="left"?{leftSide:{direction:schPinArrangement?.leftSide?.direction??"top-to-bottom",pins:schPinArrangement?.leftSide?.pins??Array.from({length:pinCount},(_4,i3)=>`pin${i3+1}`)}}:{rightSide:{direction:schPinArrangement?.rightSide?.direction??"top-to-bottom",pins:schPinArrangement?.rightSide?.pins??Array.from({length:pinCount},(_4,i3)=>`pin${i3+1}`)}}}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,source_component=db.source_component.insert({ftype:"simple_pin_header",name:this.name,supplier_part_numbers:props.supplierPartNumbers,pin_count:props.pinCount,gender:props.gender,are_pins_interchangeable:!0});this.source_component_id=source_component.source_component_id}};function getResonatorSymbolName(variant){switch(variant){case"two_ground_pins":return"crystal_4pin";case"ground_pin":return"resonator";case"no_ground":return"crystal";default:return"crystal"}}var Resonator=class extends NormalComponent3{get config(){return{componentName:"Resonator",schematicSymbolName:this.props.symbolName??getResonatorSymbolName(this.props.pinVariant),zodProps:resonatorProps,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,pinVariant=props.pinVariant||"no_ground",source_component=db.source_component.insert({ftype:"simple_resonator",name:this.name,frequency:props.frequency,load_capacitance:props.loadCapacitance,supplier_part_numbers:props.supplierPartNumbers,pin_variant:pinVariant,are_pins_interchangeable:pinVariant==="no_ground"||pinVariant==="ground_pin"});this.source_component_id=source_component.source_component_id}_getSchematicSymbolDisplayValue(){let freqDisplay=`${formatSiUnit(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${freqDisplay} / ${formatSiUnit(this._parsedProps.loadCapacitance)}F`:freqDisplay}};function getPotentiometerSymbolName(variant){switch(variant){case"three_pin":return"potentiometer3";case"two_pin":return"potentiometer2";default:return"potentiometer2"}}var Potentiometer=class extends NormalComponent3{get config(){return{componentName:"Potentiometer",schematicSymbolName:this.props.symbolName??getPotentiometerSymbolName(this.props.pinVariant),zodProps:potentiometerProps,shouldRenderAsSchematicBox:!1}}_getSchematicSymbolDisplayValue(){return`${formatSiUnit(this._parsedProps.maxResistance)}\u03A9`}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,pinVariant=props.pinVariant||"two_pin",source_component=db.source_component.insert({ftype:"simple_potentiometer",name:this.name,max_resistance:props.maxResistance,pin_variant:pinVariant,are_pins_interchangeable:pinVariant==="two_pin"});this.source_component_id=source_component.source_component_id}},PushButton=class extends NormalComponent3{get config(){return{componentName:"PushButton",schematicSymbolName:this.props.symbolName??"push_button_normally_open_momentary",zodProps:pushButtonProps,sourceFtype:FTYPE.simple_push_button}}get defaultInternallyConnectedPinNames(){return[]}initPorts(){super.initPorts({pinCount:2,ignoreSymbolPorts:!0});let symbol=ef[this._getSchematicSymbolNameOrThrow()],symPort1=symbol.ports.find(p4=>p4.labels.includes("1")),symPort2=symbol.ports.find(p4=>p4.labels.includes("2")),ports=this.selectAll("port"),pin1Port=ports.find(p4=>p4.props.pinNumber===1),pin2Port=ports.find(p4=>p4.props.pinNumber===2),pin3Port=ports.find(p4=>p4.props.pinNumber===3),pin4Port=ports.find(p4=>p4.props.pinNumber===4),{internallyConnectedPins}=this._parsedProps;pin1Port.schematicSymbolPortDef=symPort1,(!internallyConnectedPins||internallyConnectedPins.length===0)&&(pin2Port.schematicSymbolPortDef=symPort2);for(let[pn3,port]of[[2,pin2Port],[3,pin3Port],[4,pin4Port]]){let internallyConnectedRow=internallyConnectedPins?.find(([pin1,pin2])=>pin1===`pin${pn3}`||pin2===`pin${pn3}`);if(!internallyConnectedRow){port.schematicSymbolPortDef=symPort2;break}(internallyConnectedRow?.[0]===`pin${pn3}`?internallyConnectedRow[1]:internallyConnectedRow?.[0])!=="pin1"&&(port.schematicSymbolPortDef=symPort2)}}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,source_component=db.source_component.insert({name:this.name,ftype:FTYPE.simple_push_button,supplier_part_numbers:props.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=source_component.source_component_id}},Crystal=class extends NormalComponent3{get config(){return{schematicSymbolName:this.props.symbolName??(this.props.pinVariant==="four_pin"?"crystal_4pin":"crystal"),componentName:"Crystal",zodProps:crystalProps,sourceFtype:"simple_crystal"}}initPorts(){let additionalAliases=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})}_getSchematicSymbolDisplayValue(){let freqDisplay=`${formatSiUnit(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${freqDisplay} / ${formatSiUnit(this._parsedProps.loadCapacitance)}F`:freqDisplay}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,source_component=db.source_component.insert({name:this.name,ftype:"simple_crystal",frequency:props.frequency,load_capacitance:props.loadCapacitance,pin_variant:props.pinVariant||"two_pin",are_pins_interchangeable:(props.pinVariant||"two_pin")==="two_pin"});this.source_component_id=source_component.source_component_id}},Mosfet=class extends NormalComponent3{get config(){let mosfetMode=this.props.mosfetMode==="depletion"?"d":"e",baseSymbolName=`${this.props.channelType}_channel_${mosfetMode}_mosfet_transistor`;return{componentName:"Mosfet",schematicSymbolName:this.props.symbolName??baseSymbolName,zodProps:mosfetProps,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,source_component=db.source_component.insert({ftype:"simple_mosfet",name:this.name,mosfet_mode:props.mosfetMode,channel_type:props.channelType});this.source_component_id=source_component.source_component_id}};function hasSimProps(props){return props.simSwitchFrequency!==void 0||props.simCloseAt!==void 0||props.simOpenAt!==void 0||props.simStartClosed!==void 0||props.simStartOpen!==void 0}var Switch=class extends NormalComponent3{_getSwitchType(){let props=this._parsedProps;return props?props.dpdt?"dpdt":props.spst?"spst":props.spdt?"spdt":props.dpst?"dpst":props.type??"spst":"spst"}get config(){let switchType=this._getSwitchType(),isNormallyClosed=this._parsedProps?.isNormallyClosed??!1,symbolMap={spst:isNormallyClosed?"spst_normally_closed_switch":"spst_switch",spdt:isNormallyClosed?"spdt_normally_closed_switch":"spdt_switch",dpst:isNormallyClosed?"dpst_normally_closed_switch":"dpst_switch",dpdt:isNormallyClosed?"dpdt_normally_closed_switch":"dpdt_switch"};return{componentName:"Switch",schematicSymbolName:this.props.symbolName??symbolMap[switchType],zodProps:switchProps,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db}=this.root,props=this._parsedProps??{},source_component=db.source_component.insert({ftype:"simple_switch",name:this.name,are_pins_interchangeable:this._getSwitchType()==="spst"});this.source_component_id=source_component.source_component_id}doInitialSimulationRender(){let{_parsedProps:props}=this;if(!hasSimProps(props))return;let{db}=this.root,simulationSwitch={type:"simulation_switch",source_component_id:this.source_component_id||""};props.simSwitchFrequency!==void 0&&(simulationSwitch.switching_frequency=frequency.parse(props.simSwitchFrequency)),props.simCloseAt!==void 0&&(simulationSwitch.closes_at=ms.parse(props.simCloseAt)),props.simOpenAt!==void 0&&(simulationSwitch.opens_at=ms.parse(props.simOpenAt)),props.simStartOpen!==void 0&&(simulationSwitch.starts_closed=!props.simStartOpen),props.simStartClosed!==void 0&&(simulationSwitch.starts_closed=props.simStartClosed),db.simulation_switch.insert(simulationSwitch)}},TESTPOINT_DEFAULTS={HOLE_DIAMETER:.5,SMT_CIRCLE_DIAMETER:1.2,SMT_RECT_SIZE:2},TestPoint=class extends NormalComponent3{get config(){return{componentName:"TestPoint",schematicSymbolName:this.props.symbolName??"testpoint",zodProps:testpointProps,sourceFtype:FTYPE.simple_test_point}}_getPropsWithDefaults(){let{padShape,holeDiameter,footprintVariant,padDiameter,width,height}=this._parsedProps;return!footprintVariant&&holeDiameter&&(footprintVariant="through_hole"),footprintVariant??(footprintVariant="through_hole"),padShape??(padShape="circle"),footprintVariant==="pad"?padShape==="circle"?padDiameter??(padDiameter=TESTPOINT_DEFAULTS.SMT_CIRCLE_DIAMETER):padShape==="rect"&&(width??(width=TESTPOINT_DEFAULTS.SMT_RECT_SIZE),height??(height=width)):footprintVariant==="through_hole"&&(holeDiameter??(holeDiameter=TESTPOINT_DEFAULTS.HOLE_DIAMETER)),{padShape,holeDiameter,footprintVariant,padDiameter,width,height}}_getImpliedFootprintString(){let{padShape,holeDiameter,footprintVariant,padDiameter,width,height}=this._getPropsWithDefaults();if(footprintVariant==="through_hole")return`platedhole_d${holeDiameter}`;if(footprintVariant==="pad"){if(padShape==="circle")return`smtpad_circle_d${padDiameter}`;if(padShape==="rect")return`smtpad_rect_w${width}_h${height}`}throw new Error(`Footprint variant "${footprintVariant}" with pad shape "${padShape}" not implemented`)}doInitialSourceRender(){let{db}=this.root,{_parsedProps:props}=this,{padShape,holeDiameter,footprintVariant,padDiameter,width,height}=this._getPropsWithDefaults(),source_component=db.source_component.insert({ftype:FTYPE.simple_test_point,name:this.name,supplier_part_numbers:props.supplierPartNumbers,footprint_variant:footprintVariant,pad_shape:padShape,pad_diameter:padDiameter,hole_diameter:holeDiameter,width,height,are_pins_interchangeable:!0});this.source_component_id=source_component.source_component_id}},SchematicText=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicText",zodProps:schematicTextProps}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db}=this.root,{_parsedProps:props}=this,globalPos=this._getGlobalSchematicPositionBeforeLayout();db.schematic_text.insert({anchor:props.anchor??"center",text:normalizeTextForCircuitJson(props.text),font_size:props.fontSize,color:props.color||"#000000",position:{x:globalPos.x,y:globalPos.y},rotation:props.schRotation??0})}},SchematicLine=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"isSchematicPrimitive",!0);__publicField(this,"schematic_line_id")}get config(){return{componentName:"SchematicLine",zodProps:schematicLineProps}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db}=this.root,{_parsedProps:props}=this,globalPos=this._getGlobalSchematicPositionBeforeLayout(),schematic_component_id=this.getPrimitiveContainer()?.parent?.schematic_component_id,schematic_line2=db.schematic_line.insert({schematic_component_id,x1:props.x1+globalPos.x,y1:props.y1+globalPos.y,x2:props.x2+globalPos.x,y2:props.y2+globalPos.y,stroke_width:props.strokeWidth??SCHEMATIC_COMPONENT_OUTLINE_STROKE_WIDTH,color:props.color??SCHEMATIC_COMPONENT_OUTLINE_COLOR,is_dashed:!1,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_line_id=schematic_line2.schematic_line_id}},SchematicRect=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"isSchematicPrimitive",!0);__publicField(this,"schematic_rect_id")}get config(){return{componentName:"SchematicRect",zodProps:schematicRectProps}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db}=this.root,{_parsedProps:props}=this,globalPos=this._getGlobalSchematicPositionBeforeLayout(),schematic_component_id=this.getPrimitiveContainer()?.parent?.schematic_component_id,schematic_rect2=db.schematic_rect.insert({center:{x:globalPos.x,y:globalPos.y},width:props.width,height:props.height,stroke_width:props.strokeWidth??SCHEMATIC_COMPONENT_OUTLINE_STROKE_WIDTH,color:props.color??SCHEMATIC_COMPONENT_OUTLINE_COLOR,is_filled:props.isFilled,schematic_component_id,is_dashed:props.isDashed,rotation:props.rotation??0,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_rect_id=schematic_rect2.schematic_rect_id}},SchematicArc=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"isSchematicPrimitive",!0);__publicField(this,"schematic_arc_id")}get config(){return{componentName:"SchematicArc",zodProps:schematicArcProps}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db}=this.root,{_parsedProps:props}=this,globalPos=this._getGlobalSchematicPositionBeforeLayout(),schematic_component_id=this.getPrimitiveContainer()?.parent?.schematic_component_id,schematic_arc2=db.schematic_arc.insert({schematic_component_id,center:{x:props.center.x+globalPos.x,y:props.center.y+globalPos.y},radius:props.radius,start_angle_degrees:props.startAngleDegrees,end_angle_degrees:props.endAngleDegrees,direction:props.direction,stroke_width:props.strokeWidth??SCHEMATIC_COMPONENT_OUTLINE_STROKE_WIDTH,color:props.color??SCHEMATIC_COMPONENT_OUTLINE_COLOR,is_dashed:props.isDashed,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_arc_id=schematic_arc2.schematic_arc_id}},SchematicCircle=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"isSchematicPrimitive",!0);__publicField(this,"schematic_circle_id")}get config(){return{componentName:"SchematicCircle",zodProps:schematicCircleProps}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db}=this.root,{_parsedProps:props}=this,globalPos=this._getGlobalSchematicPositionBeforeLayout(),schematic_component_id=this.getPrimitiveContainer()?.parent?.schematic_component_id,schematic_circle2=db.schematic_circle.insert({schematic_component_id,center:{x:props.center.x+globalPos.x,y:props.center.y+globalPos.y},radius:props.radius,stroke_width:props.strokeWidth??SCHEMATIC_COMPONENT_OUTLINE_STROKE_WIDTH,color:props.color??SCHEMATIC_COMPONENT_OUTLINE_COLOR,is_filled:props.isFilled,fill_color:props.fillColor,is_dashed:props.isDashed,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_circle_id=schematic_circle2.schematic_circle_id}};function getTitleAnchorAndPosition({anchor,x:x3,y:y3,width,height,isInside}){switch(anchor){case"top_left":return{x:x3,y:y3+height,textAnchor:isInside?"top_left":"bottom_left"};case"top_center":return{x:x3+width/2,y:y3+height,textAnchor:isInside?"top_center":"bottom_center"};case"top_right":return{x:x3+width,y:y3+height,textAnchor:isInside?"top_right":"bottom_right"};case"center_left":return{x:x3,y:y3+height/2,textAnchor:isInside?"center_left":"center_right"};case"center":return{x:x3+width/2,y:y3+height/2,textAnchor:"center"};case"center_right":return{x:x3+width,y:y3+height/2,textAnchor:isInside?"center_right":"center_left"};case"bottom_left":return{x:x3,y:y3,textAnchor:isInside?"bottom_left":"top_left"};case"bottom_center":return{x:x3+width/2,y:y3,textAnchor:isInside?"bottom_center":"top_center"};case"bottom_right":return{x:x3+width,y:y3,textAnchor:isInside?"bottom_right":"top_right"};default:return{x:x3+width/2,y:y3+height,textAnchor:"center"}}}var SchematicBox=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicBox",zodProps:schematicBoxProps,shouldRenderAsSchematicBox:!0}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db}=this.root,{_parsedProps:props}=this,basePadding=.6,generalPadding=typeof props.padding=="number"?props.padding:0,paddingTop=typeof props.paddingTop=="number"?props.paddingTop:generalPadding,paddingBottom=typeof props.paddingBottom=="number"?props.paddingBottom:generalPadding,paddingLeft=typeof props.paddingLeft=="number"?props.paddingLeft:generalPadding,paddingRight=typeof props.paddingRight=="number"?props.paddingRight:generalPadding,hasOverlay=props.overlay&&props.overlay.length>0,hasFixedSize=typeof props.width=="number"&&typeof props.height=="number",width,height,x3,y3,centerX,centerY;if(hasOverlay){let portsWithPosition=props.overlay.map(selector=>({selector,port:this.getSubcircuit().selectOne(selector,{type:"port"})})).filter(({port})=>port!=null).map(({port})=>({position:port._getGlobalSchematicPositionAfterLayout()}));if(portsWithPosition.length===0)return;let xs3=portsWithPosition.map(p4=>p4.position.x),ys3=portsWithPosition.map(p4=>p4.position.y),minX=Math.min(...xs3),maxX=Math.max(...xs3),minY=Math.min(...ys3),maxY=Math.max(...ys3),rawWidth=maxX-minX,rawHeight=maxY-minY,defaultHorizontalPadding=rawWidth===0?basePadding:0,defaultVerticalPadding=rawHeight===0?basePadding:0,finalPaddingLeft=paddingLeft+defaultHorizontalPadding/2,finalPaddingRight=paddingRight+defaultHorizontalPadding/2,finalPaddingTop=paddingTop+defaultVerticalPadding/2,finalPaddingBottom=paddingBottom+defaultVerticalPadding/2,left=minX-finalPaddingLeft,right=maxX+finalPaddingRight,top=minY-finalPaddingBottom,bottom=maxY+finalPaddingTop;width=right-left,height=bottom-top,x3=left+(props.schX??0),y3=top+(props.schY??0),centerX=x3+width/2,centerY=y3+height/2}else if(hasFixedSize){width=props.width,height=props.height;let center2=this._getGlobalSchematicPositionBeforeLayout();centerX=center2.x,centerY=center2.y,x3=centerX-width/2,y3=centerY-height/2}else return;if(db.schematic_box.insert({height,width,x:x3,y:y3,is_dashed:props.strokeStyle==="dashed"}),props.title){let isInside=props.titleInside,TITLE_PADDING=.1,anchor=props.titleAlignment,anchorPos=getTitleAnchorAndPosition({anchor,x:x3,y:y3,width,height,isInside}),titleOffsetY,titleOffsetX,textAnchor=anchorPos.textAnchor;isInside?(titleOffsetY=anchor.includes("top")?-TITLE_PADDING:anchor.includes("bottom")?TITLE_PADDING:0,titleOffsetX=anchor.includes("left")?TITLE_PADDING:anchor.includes("right")?-TITLE_PADDING:0):(titleOffsetY=anchor.includes("top")?TITLE_PADDING:anchor.includes("bottom")?-TITLE_PADDING:0,titleOffsetX=anchor.includes("center_left")?-TITLE_PADDING:anchor.includes("center_right")?TITLE_PADDING:0);let titleX=anchorPos.x+titleOffsetX,titleY=anchorPos.y+titleOffsetY;db.schematic_text.insert({anchor:textAnchor,text:props.title,font_size:props.titleFontSize??.18,color:props.titleColor??"#000000",position:{x:titleX,y:titleY},rotation:0})}}},SchematicTable=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"isSchematicPrimitive",!0);__publicField(this,"schematic_table_id",null)}get config(){return{componentName:"SchematicTable",zodProps:schematicTableProps}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db}=this.root,{_parsedProps:props}=this,rows=this.children.filter(c3=>c3.componentName==="SchematicRow");if(rows.length===0)return;let grid4=[],maxCols=0;for(let row of rows){let cells=row.children.filter(c3=>c3.componentName==="SchematicCell");maxCols=Math.max(maxCols,cells.length)}for(let i3=0;i3<rows.length;i3++)grid4[i3]=[];for(let i3=0;i3<rows.length;i3++){let cells=rows[i3].children.filter(c3=>c3.componentName==="SchematicCell"),k4=0;for(let j3=0;j3<cells.length;j3++){for(;grid4[i3][k4];)k4++;let cell=cells[j3],colSpan=cell._parsedProps.colSpan??1,rowSpan=cell._parsedProps.rowSpan??1;for(let r4=0;r4<rowSpan;r4++)for(let c3=0;c3<colSpan;c3++)grid4[i3+r4]||(grid4[i3+r4]=[]),grid4[i3+r4][k4+c3]=cell;k4+=colSpan}}maxCols=Math.max(0,...grid4.map(r4=>r4.length));let rowHeights=rows.map((row,i3)=>row._parsedProps.height??1),colWidths=Array.from({length:maxCols},(_4,j3)=>{let maxWidth=0;for(let i3=0;i3<rows.length;i3++){let cell=grid4[i3]?.[j3];if(cell){let text=cell._parsedProps.text??cell._parsedProps.children,cellWidth=cell._parsedProps.width??(text?.length??2)*.5;cellWidth>maxWidth&&(maxWidth=cellWidth)}}return maxWidth||10}),anchorPos=this._getGlobalSchematicPositionBeforeLayout(),table=db.schematic_table.insert({anchor_position:anchorPos,column_widths:colWidths,row_heights:rowHeights,cell_padding:props.cellPadding,border_width:props.borderWidth,anchor:props.anchor,subcircuit_id:this.getSubcircuit()?.subcircuit_id||"",schematic_component_id:this.parent?.schematic_component_id||""});this.schematic_table_id=table.schematic_table_id;let processedCells=new Set,yOffset=0;for(let i3=0;i3<rows.length;i3++){let xOffset=0;for(let j3=0;j3<maxCols;j3++){let cell=grid4[i3]?.[j3];if(cell&&!processedCells.has(cell)){processedCells.add(cell);let cellProps=cell._parsedProps,rowSpan=cellProps.rowSpan??1,colSpan=cellProps.colSpan??1,cellWidth=0;for(let c3=0;c3<colSpan;c3++)cellWidth+=colWidths[j3+c3];let cellHeight=0;for(let r4=0;r4<rowSpan;r4++)cellHeight+=rowHeights[i3+r4];db.schematic_table_cell.insert({schematic_table_id:this.schematic_table_id,start_row_index:i3,end_row_index:i3+rowSpan-1,start_column_index:j3,end_column_index:j3+colSpan-1,text:cellProps.text??cellProps.children,center:{x:anchorPos.x+xOffset+cellWidth/2,y:anchorPos.y-yOffset-cellHeight/2},width:cellWidth,height:cellHeight,horizontal_align:cellProps.horizontalAlign,vertical_align:cellProps.verticalAlign,font_size:cellProps.fontSize??props.fontSize,subcircuit_id:this.getSubcircuit()?.subcircuit_id||""})}colWidths[j3]&&(xOffset+=colWidths[j3])}yOffset+=rowHeights[i3]}}},SchematicRow=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicRow",zodProps:schematicRowProps}}},SchematicCell=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"isSchematicPrimitive",!0);__publicField(this,"canHaveTextChildren",!0)}get config(){return{componentName:"SchematicCell",zodProps:schematicCellProps}}},SymbolComponent=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"Symbol",zodProps:symbolProps}}},AnalogSimulation=class extends PrimitiveComponent2{get config(){return{componentName:"AnalogSimulation",zodProps:analogSimulationProps}}doInitialSimulationRender(){let{db}=this.root,{duration,timePerStep}=this._parsedProps,durationMs=duration||10,timePerStepMs=timePerStep||.01;db.simulation_experiment.insert({name:"spice_transient_analysis",experiment_type:"spice_transient_analysis",end_time_ms:durationMs,time_per_step:timePerStepMs})}};function getLabelBounds(probePosition,labelText,alignment,labelOffset=.3){let labelWidth=Math.max(labelText.length*.1,.3),labelHeightWithPadding=.25+.2,anchorX=probePosition.x,anchorY=probePosition.y,offsetMultiplier=labelOffset+labelWidth/2;alignment.includes("top")?anchorY+=offsetMultiplier:alignment.includes("bottom")&&(anchorY-=offsetMultiplier),alignment.includes("right")?anchorX+=offsetMultiplier:alignment.includes("left")&&(anchorX-=offsetMultiplier);let minX,maxX,minY,maxY;return alignment.includes("left")?(minX=anchorX,maxX=anchorX+labelWidth):alignment.includes("right")?(minX=anchorX-labelWidth,maxX=anchorX):(minX=anchorX-labelWidth/2,maxX=anchorX+labelWidth/2),alignment.includes("top")?(minY=anchorY-labelHeightWithPadding,maxY=anchorY):alignment.includes("bottom")?(minY=anchorY,maxY=anchorY+labelHeightWithPadding):(minY=anchorY-labelHeightWithPadding/2,maxY=anchorY+labelHeightWithPadding/2),{minX,maxX,minY,maxY}}function getElementBounds(elm){let cx2,cy2,w4,h3;if(elm.type==="schematic_component")cx2=elm.center?.x,cy2=elm.center?.y,w4=elm.size?.width,h3=elm.size?.height;else if(elm.type==="schematic_text")cx2=elm.position?.x,cy2=elm.position?.y,w4=(elm.text?.length??0)*.1,h3=.2;else return null;return typeof cx2=="number"&&typeof cy2=="number"&&typeof w4=="number"&&typeof h3=="number"?{minX:cx2-w4/2,maxX:cx2+w4/2,minY:cy2-h3/2,maxY:cy2+h3/2}:null}function getOverlapArea(a3,b3){if(!doBoundsOverlap(a3,b3))return 0;let overlapWidth=Math.min(a3.maxX,b3.maxX)-Math.max(a3.minX,b3.minX),overlapHeight=Math.min(a3.maxY,b3.maxY)-Math.max(a3.minY,b3.minY);return overlapWidth*overlapHeight}function selectBestLabelAlignment({probePosition,labelText,schematicElements,defaultAlignment="top_right"}){let orderedAlignments=[defaultAlignment,...["top_right","top_left","bottom_right","bottom_left","top_center","bottom_center","center_right","center_left"].filter(a3=>a3!==defaultAlignment)],bestAlignment=defaultAlignment,minOverlapArea=1/0;for(let alignment of orderedAlignments){let labelBounds=getLabelBounds(probePosition,labelText,alignment),totalOverlapArea=0;for(let element of schematicElements){let elementBounds=getElementBounds(element);elementBounds&&(totalOverlapArea+=getOverlapArea(labelBounds,elementBounds))}if(totalOverlapArea===0)return alignment;totalOverlapArea<minOverlapArea&&(minOverlapArea=totalOverlapArea,bestAlignment=alignment)}return bestAlignment}var VoltageProbe=class extends PrimitiveComponent2{constructor(){super(...arguments);__publicField(this,"simulation_voltage_probe_id",null);__publicField(this,"schematic_voltage_probe_id",null);__publicField(this,"finalProbeName",null);__publicField(this,"color",null)}get config(){return{componentName:"VoltageProbe",zodProps:voltageProbeProps}}doInitialSimulationRender(){let{db}=this.root,{connectsTo,name,referenceTo,color}=this._parsedProps,subcircuit=this.getSubcircuit();if(!subcircuit){this.renderError("VoltageProbe must be inside a subcircuit");return}let targets=Array.isArray(connectsTo)?connectsTo:[connectsTo];if(targets.length!==1){this.renderError("VoltageProbe must connect to exactly one port or net");return}let targetSelector=targets[0],port=subcircuit.selectOne(targetSelector,{type:"port"}),net=port?null:subcircuit.selectOne(targetSelector,{type:"net"});if(net&&net.componentName!=="Net"){this.renderError(`VoltageProbe connection target "${targetSelector}" resolved to a non-net component "${net.componentName}".`);return}if(!port&&!net){this.renderError(`VoltageProbe could not find connection target "${targetSelector}"`);return}let connectedId=port?.source_port_id??net?.source_net_id;if(!connectedId){this.renderError("Could not identify connected source for VoltageProbe");return}let referencePort=null,referenceNet=null;if(referenceTo){let referenceTargets=Array.isArray(referenceTo)?referenceTo:[referenceTo];if(referenceTargets.length!==1){this.renderError("VoltageProbe must reference exactly one port or net");return}let referenceSelector=referenceTargets[0];if(referencePort=subcircuit.selectOne(referenceSelector,{type:"port"}),referenceNet=referencePort?null:subcircuit.selectOne(referenceSelector,{type:"net"}),referenceNet&&referenceNet.componentName!=="Net"){this.renderError(`VoltageProbe reference target "${referenceSelector}" resolved to a non-net component "${referenceNet.componentName}".`);return}if(!referencePort&&!referenceNet){this.renderError(`VoltageProbe could not find reference target "${referenceSelector}"`);return}}this.color=color??getSimulationColorForId(connectedId);let finalName=name;finalName||(finalName=targets[0].split(" > ").map(s4=>s4.replace(/^\./,"")).join(".")),this.finalProbeName=finalName??null;let{simulation_voltage_probe_id}=db.simulation_voltage_probe.insert({name:finalName,signal_input_source_port_id:port?.source_port_id??void 0,signal_input_source_net_id:net?.source_net_id??void 0,reference_input_source_port_id:referencePort?.source_port_id??void 0,reference_input_source_net_id:referenceNet?.source_net_id??void 0,subcircuit_id:subcircuit.subcircuit_id||void 0,color:this.color});this.simulation_voltage_probe_id=simulation_voltage_probe_id}doInitialSchematicReplaceNetLabelsWithSymbols(){if(this.root?.schematicDisabled)return;let{db}=this.root,{connectsTo,name}=this._parsedProps,subcircuit=this.getSubcircuit();if(!subcircuit)return;let targets=Array.isArray(connectsTo)?connectsTo:[connectsTo];if(targets.length!==1)return;let targetSelector=targets[0],port=subcircuit.selectOne(targetSelector,{type:"port"});if(!port||!port.schematic_port_id)return;let position2=port._getGlobalSchematicPositionAfterLayout(),targetTraceId=null;for(let trace of db.schematic_trace.list()){for(let edge of trace.edges)if(Math.abs(edge.from.x-position2.x)<1e-6&&Math.abs(edge.from.y-position2.y)<1e-6||Math.abs(edge.to.x-position2.x)<1e-6&&Math.abs(edge.to.y-position2.y)<1e-6){targetTraceId=trace.schematic_trace_id;break}if(targetTraceId)break}if(!targetTraceId)return;let probeName=this.finalProbeName,labelAlignment=selectBestLabelAlignment({probePosition:position2,labelText:probeName,schematicElements:[...db.schematic_component.list(),...db.schematic_text.list()],defaultAlignment:"top_right"}),schematic_voltage_probe2=db.schematic_voltage_probe.insert({name:probeName,position:position2,schematic_trace_id:targetTraceId,subcircuit_id:subcircuit.subcircuit_id||void 0,color:this.color??void 0,label_alignment:labelAlignment});this.schematic_voltage_probe_id=schematic_voltage_probe2.schematic_voltage_probe_id}},package_default3={name:"@tscircuit/core",type:"module",version:"0.0.938",types:"dist/index.d.ts",main:"dist/index.js",module:"dist/index.js",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist"],repository:{type:"git",url:"https://github.com/tscircuit/core"},scripts:{build:"tsup-node index.ts --format esm --dts",format:"biome format . --write","measure-bundle":"howfat -r table .","pkg-pr-new-release":"bunx pkg-pr-new publish --comment=off --peerDeps","smoke-test:dist":"bun run scripts/smoke-tests/test-dist-simple-circuit.tsx","build:benchmarking":"bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist","build:benchmarking:watch":`chokidar "./{benchmarking,lib}/**/*.{ts,tsx}" -c 'bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist'`,"start:benchmarking":'concurrently "bun run build:benchmarking:watch" "live-server ./benchmarking-dist"',"generate-test-plan":"bun run scripts/generate-test-plan.ts"},devDependencies:{"@biomejs/biome":"^1.8.3","@resvg/resvg-js":"^2.6.2","@tscircuit/capacity-autorouter":"^0.0.178","@tscircuit/checks":"^0.0.87","@tscircuit/circuit-json-util":"^0.0.73","@tscircuit/common":"^0.0.20","@tscircuit/copper-pour-solver":"^0.0.14","@tscircuit/footprinter":"^0.0.236","@tscircuit/import-snippet":"^0.0.4","@tscircuit/infgrid-ijump-astar":"^0.0.33","@tscircuit/log-soup":"^1.0.2","@tscircuit/matchpack":"^0.0.16","@tscircuit/math-utils":"^0.0.29","@tscircuit/miniflex":"^0.0.4","@tscircuit/ngspice-spice-engine":"^0.0.8","@tscircuit/props":"^0.0.432","@tscircuit/schematic-autolayout":"^0.0.6","@tscircuit/schematic-match-adapt":"^0.0.16","@tscircuit/schematic-trace-solver":"^v0.0.45","@tscircuit/solver-utils":"^0.0.3","@types/bun":"^1.2.16","@types/debug":"^4.1.12","@types/react":"^19.1.8","@types/react-dom":"^19.1.6","@types/react-reconciler":"^0.28.9","bpc-graph":"^0.0.57","bun-match-svg":"0.0.12","calculate-elbow":"^0.0.12","chokidar-cli":"^3.0.0","circuit-json":"^0.0.336","circuit-json-to-bpc":"^0.0.13","circuit-json-to-connectivity-map":"^0.0.23","circuit-json-to-gltf":"^0.0.31","circuit-json-to-simple-3d":"^0.0.9","circuit-json-to-spice":"^0.0.30","circuit-to-svg":"^0.0.296",concurrently:"^9.1.2","connectivity-map":"^1.0.0",debug:"^4.3.6","eecircuit-engine":"^1.5.6",flatbush:"^4.5.0","graphics-debug":"^0.0.60",howfat:"^0.3.8","live-server":"^1.2.2","looks-same":"^9.0.1",minicssgrid:"^0.0.9","pkg-pr-new":"^0.0.37",poppygl:"^0.0.16",react:"^19.1.0","react-dom":"^19.1.0","schematic-symbols":"^0.0.202",spicey:"^0.0.14","ts-expect":"^1.3.0",tsup:"^8.2.4"},peerDependencies:{"@tscircuit/capacity-autorouter":"*","@tscircuit/checks":"*","@tscircuit/circuit-json-util":"*","@tscircuit/footprinter":"*","@tscircuit/infgrid-ijump-astar":"*","@tscircuit/math-utils":"*","@tscircuit/props":"*","@tscircuit/schematic-autolayout":"*","@tscircuit/schematic-match-adapt":"*","circuit-json-to-bpc":"*","bpc-graph":"*","@tscircuit/matchpack":"*","circuit-json":"*","circuit-json-to-connectivity-map":"*","schematic-symbols":"*",typescript:"^5.0.0"},dependencies:{"@flatten-js/core":"^1.6.2","@lume/kiwi":"^0.4.3","calculate-packing":"0.0.68","css-select":"5.1.0","format-si-unit":"^0.0.3",nanoid:"^5.0.7","performance-now":"^2.1.0","react-reconciler":"^0.32.0","transformation-matrix":"^2.16.1",zod:"^3.25.67"}},RootCircuit=class{constructor({platform,projectUrl}={}){__publicField(this,"firstChild",null);__publicField(this,"children");__publicField(this,"db");__publicField(this,"root",null);__publicField(this,"isRoot",!0);__publicField(this,"_schematicDisabledOverride");__publicField(this,"pcbDisabled",!1);__publicField(this,"pcbRoutingDisabled",!1);__publicField(this,"_featureMspSchematicTraceRouting",!0);__publicField(this,"name");__publicField(this,"platform");__publicField(this,"projectUrl");__publicField(this,"_hasRenderedAtleastOnce",!1);__publicField(this,"_eventListeners",{});this.children=[],this.db=su2([]),this.root=this,this.platform=platform,this.projectUrl=projectUrl,this.pcbDisabled=platform?.pcbDisabled??!1}get schematicDisabled(){return this._schematicDisabledOverride!==void 0?this._schematicDisabledOverride:this._getBoard()?._parsedProps?.schematicDisabled??!1}set schematicDisabled(value){this._schematicDisabledOverride=value}add(componentOrElm){let component;(0,import_react4.isValidElement)(componentOrElm)?component=createInstanceFromReactElement(componentOrElm):component=componentOrElm,this.children.push(component)}setPlatform(platform){this.platform={...this.platform,...platform}}_getBoard(){let directBoard=this.children.find(c3=>c3.componentName==="Board");if(directBoard)return directBoard}_guessRootComponent(){if(this.firstChild)return;if(this.children.length===0)throw new Error("Not able to guess root component: RootCircuit has no children (use circuit.add(...))");let panels=this.children.filter(child=>child.lowercaseComponentName==="panel");if(panels.length>1)throw new Error("Only one <panel> is allowed per circuit");if(panels.length===1){if(this.children.length!==1)throw new Error("<panel> must be the root element of the circuit");this.firstChild=panels[0];return}if(this.children.length===1&&this.children[0].isGroup){this.firstChild=this.children[0];return}let group=new Group6({subcircuit:!0});group.parent=this,group.addAll(this.children),this.children=[group],this.firstChild=group}render(){this.firstChild||this._guessRootComponent();let{firstChild,db}=this;if(!firstChild)throw new Error("RootCircuit has no root component");firstChild.parent=this,firstChild.runRenderCycle(),this._hasRenderedAtleastOnce=!0}async renderUntilSettled(){for(this.db.source_project_metadata.list()?.[0]||this.db.source_project_metadata.insert({software_used_string:`@tscircuit/core@${this.getCoreVersion()}`,...this.projectUrl?{project_url:this.projectUrl}:{}}),this.render();this._hasIncompleteAsyncEffects();)await new Promise(resolve=>setTimeout(resolve,100)),this.render();this.emit("renderComplete")}_hasIncompleteAsyncEffects(){return this.children.some(child=>child._hasIncompleteAsyncEffects())}getCircuitJson(){return this._hasRenderedAtleastOnce||this.render(),this.db.toArray()}toJson(){return this.getCircuitJson()}async getSvg(options){let circuitToSvg=await Promise.resolve().then(()=>(init_dist8(),dist_exports4)).catch(e4=>{throw new Error(`To use circuit.getSvg, you must install the "circuit-to-svg" package.
602
602
 
603
603
  "${e4.message}"`)});if(options.view==="pcb")return circuitToSvg.convertCircuitJsonToPcbSvg(this.getCircuitJson());if(options.view==="schematic")return circuitToSvg.convertCircuitJsonToSchematicSvg(this.getCircuitJson());throw new Error(`Invalid view: ${options.view}`)}getCoreVersion(){let[major,minor,patch]=package_default3.version.split(".").map(Number);return`${major}.${minor}.${patch+1}`}async preview(previewNameOrOpts){let previewOpts=typeof previewNameOrOpts=="object"?previewNameOrOpts:{previewName:previewNameOrOpts};throw new Error("project.preview is not yet implemented")}computeSchematicGlobalTransform(){return identity()}_computePcbGlobalTransformBeforeLayout(){return identity()}selectAll(selector){return this._guessRootComponent(),this.firstChild?.selectAll(selector)??[]}selectOne(selector,opts){return this._guessRootComponent(),this.firstChild?.selectOne(selector,opts)??null}emit(event,...args){if(this._eventListeners[event])for(let listener of this._eventListeners[event])listener(...args)}on(event,listener){this._eventListeners[event]||(this._eventListeners[event]=[]),this._eventListeners[event].push(listener)}removeListener(event,listener){this._eventListeners[event]&&(this._eventListeners[event]=this._eventListeners[event].filter(l3=>l3!==listener))}enableDebug(debug112){typeof debug112=="string"?import_debug18.default.enable(debug112):(debug112===null||debug112===!1)&&import_debug18.default.disable()}getClientOrigin(){return typeof window<"u"&&window.location?window.location.origin:typeof self<"u"&&self.location?self.location.origin:""}},Project=RootCircuit,Circuit=RootCircuit,useRenderedCircuit=reactElements=>{let[isLoading,setIsLoading]=import_react5.default.useState(!0),[error,setError]=import_react5.default.useState(null),[circuit,setCircuit]=import_react5.default.useState(),[circuitJson,setCircuitJson]=import_react5.default.useState();return import_react5.default.useEffect(()=>{setIsLoading(!0),setError(null),reactElements&&setTimeout(()=>{try{let circuit2=new RootCircuit;circuit2.add(reactElements),setCircuit(circuit2),setCircuitJson(circuit2.toJson())}catch(error2){setError(error2)}setIsLoading(!1)},1)},[reactElements]),{isLoading,error,circuit,circuitJson}},createUseComponent=(Component2,pins)=>(name,props)=>{let pinLabelsFlatArray=[];Array.isArray(pins)?pinLabelsFlatArray.push(...pins.flat()):typeof pins=="object"&&pinLabelsFlatArray.push(...Object.values(pins).flat(),...Object.keys(pins));let R4=props2=>{if(props2?.name&&props2.name!==name)throw new Error(`Component name mismatch. Hook name: ${name}, Component prop name: ${props2.name}`);let combinedProps={...props,...props2,name},tracesToCreate=[];for(let portLabel of pinLabelsFlatArray)if(combinedProps[portLabel]){let from=`.${name} > .${portLabel}`,to2=combinedProps[portLabel];tracesToCreate.push({from,to:to2}),delete combinedProps[portLabel]}return(0,import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment,{children:[(0,import_jsx_runtime.jsx)(Component2,{...combinedProps}),tracesToCreate.map((trace,i3)=>(0,import_jsx_runtime.jsx)("trace",{...trace},i3))]})};for(let port of pinLabelsFlatArray)R4[port]=`.${name} > .${port}`;return R4},useCapacitor=createUseComponent(props=>(0,import_jsx_runtime2.jsx)("capacitor",{...props}),capacitorPins),useChip=pinLabels=>createUseComponent(props=>(0,import_jsx_runtime3.jsx)("chip",{pinLabels,...props}),pinLabels),useDiode=createUseComponent(props=>(0,import_jsx_runtime4.jsx)("diode",{...props}),diodePins),useLed=createUseComponent(props=>(0,import_jsx_runtime5.jsx)("led",{...props}),ledPins),useResistor=createUseComponent(props=>(0,import_jsx_runtime6.jsx)("resistor",{...props}),resistorPins),sel=new Proxy(refdes=>new Proxy({},{get:(_4,pin)=>`.${refdes} > .${pin}`}),{get:(_4,prop1)=>{let fn3=(...args)=>{let chipFnOrPinType=args[0];return new Proxy({},{get:(_22,pinName)=>`.${prop1} > .${pinName}`})};return new Proxy(fn3,{get:(_22,prop2)=>prop1==="net"?`net.${prop2}`:prop1==="subcircuit"?new Proxy({},{get:(_32,prop3)=>new Proxy({},{get:(_42,prop4)=>`subcircuit.${prop2} > .${prop3} > .${prop4}`})}):`.${prop1} > .${prop2}`,apply:(target,_22,args)=>prop1==="net"?new Proxy({},{get:(_32,netName)=>`net.${netName}`}):new Proxy({},{get:(_32,pinOrSubComponentName)=>{let pinResult=`.${prop1} > .${pinOrSubComponentName}`;return["U","J","CN"].some(p4=>prop1.startsWith(p4))?pinResult:new Proxy(new String(pinResult),{get:(_42,nestedProp)=>typeof nestedProp=="symbol"||nestedProp==="toString"?()=>pinResult:`.${prop1} > .${pinOrSubComponentName} > .${nestedProp}`})}})})}});extendCatalogue(components_exports);extendCatalogue({Bug:Chip});var React=__toESM(require_react(),1),ReactJsxRuntime=__toESM(require_jsx_runtime(),1);var getFootprinterStringFromKicad=kicadFootprint=>{let match2=kicadFootprint.match(/:[RC]_(\d{4})_/);if(match2||(match2=kicadFootprint.match(/:(SOIC-\d+|SOT-\d+|SOD-\d+|SSOP-\d+|TSSOP-\d+|QFP-\d+|QFN-\d+)/),match2))return match2[1]};var getJlcPackageFromFootprinterString=footprinterString=>footprinterString.includes("cap")?footprinterString.replace(/cap/g,""):footprinterString;var getJlcpcbPackageName=footprint=>{if(footprint){if(footprint.startsWith("kicad:")){let footprinterString=getFootprinterStringFromKicad(footprint);return footprinterString?getJlcPackageFromFootprinterString(footprinterString):footprint}return getJlcPackageFromFootprinterString(footprint)}};var cache=new Map,getJlcPartsCached=async(name,params)=>{let paramString=new URLSearchParams({...params,json:"true"}).toString();if(cache.has(paramString))return cache.get(paramString);let responseJson=await(await fetch(`https://jlcsearch.tscircuit.com/${name}/list?${paramString}`)).json();return cache.set(paramString,responseJson),responseJson},withBasicPartPreference=parts=>parts?[...parts].sort((a3,b3)=>Number(b3.is_basic??!1)-Number(a3.is_basic??!1)):[],jlcPartsEngine={findPart:async({sourceComponent,footprinterString})=>{let jlcpcbPackage=getJlcpcbPackageName(footprinterString);if(sourceComponent.type==="source_component"&&sourceComponent.ftype==="simple_resistor"){let{resistors}=await getJlcPartsCached("resistors",{resistance:sourceComponent.resistance,package:jlcpcbPackage});return{jlcpcb:withBasicPartPreference(resistors).map(r4=>`C${r4.lcsc}`).slice(0,3)}}else if(sourceComponent.type==="source_component"&&sourceComponent.ftype==="simple_capacitor"){let{capacitors}=await getJlcPartsCached("capacitors",{capacitance:sourceComponent.capacitance,package:jlcpcbPackage});return{jlcpcb:withBasicPartPreference(capacitors).map(c3=>`C${c3.lcsc}`).slice(0,3)}}else if(sourceComponent.type==="source_component"&&sourceComponent.ftype==="simple_pin_header"){let pitch;footprinterString?.includes("_p")&&(pitch=Number(footprinterString.split("_p")[1]));let{headers}=await getJlcPartsCached("headers",pitch?{pitch,num_pins:sourceComponent.pin_count,gender:sourceComponent.gender}:{num_pins:sourceComponent.pin_count,gender:sourceComponent.gender});return{jlcpcb:withBasicPartPreference(headers).map(h3=>`C${h3.lcsc}`).slice(0,3)}}else if(sourceComponent.type==="source_component"&&sourceComponent.ftype==="simple_potentiometer"){let{potentiometers}=await getJlcPartsCached("potentiometers",{resistance:sourceComponent.max_resistance,package:jlcpcbPackage});return{jlcpcb:withBasicPartPreference(potentiometers).map(p4=>`C${p4.lcsc}`).slice(0,3)}}else if(sourceComponent.type==="source_component"&&sourceComponent.ftype==="simple_diode"){let{diodes}=await getJlcPartsCached("diodes",{package:jlcpcbPackage});return{jlcpcb:withBasicPartPreference(diodes).map(d2=>`C${d2.lcsc}`).slice(0,3)}}else if(sourceComponent.type==="source_component"&&sourceComponent.ftype==="simple_chip"){let{chips}=await getJlcPartsCached("chips",{package:jlcpcbPackage});return{jlcpcb:withBasicPartPreference(chips).map(c3=>`C${c3.lcsc}`).slice(0,3)}}else if(sourceComponent.type==="source_component"&&sourceComponent.ftype==="simple_transistor"){let{transistors}=await getJlcPartsCached("transistors",{package:jlcpcbPackage,transistor_type:sourceComponent.transistor_type});return{jlcpcb:withBasicPartPreference(transistors).map(t6=>`C${t6.lcsc}`).slice(0,3)}}else if(sourceComponent.type==="source_component"&&sourceComponent.ftype==="simple_power_source"){let{power_sources}=await getJlcPartsCached("power_sources",{voltage:sourceComponent.voltage,package:jlcpcbPackage});return{jlcpcb:withBasicPartPreference(power_sources).map(p4=>`C${p4.lcsc}`).slice(0,3)}}else if(sourceComponent.type==="source_component"&&sourceComponent.ftype==="simple_inductor"){let{inductors}=await getJlcPartsCached("inductors",{inductance:sourceComponent.inductance,package:jlcpcbPackage});return{jlcpcb:withBasicPartPreference(inductors).map(i3=>`C${i3.lcsc}`).slice(0,3)}}else if(sourceComponent.type==="source_component"&&sourceComponent.ftype==="simple_crystal"){let{crystals}=await getJlcPartsCached("crystals",{frequency:sourceComponent.frequency,load_capacitance:sourceComponent.load_capacitance,package:jlcpcbPackage});return{jlcpcb:withBasicPartPreference(crystals).map(c3=>`C${c3.lcsc}`).slice(0,3)}}else if(sourceComponent.type==="source_component"&&sourceComponent.ftype==="simple_mosfet"){let{mosfets}=await getJlcPartsCached("mosfets",{package:jlcpcbPackage,mosfet_mode:sourceComponent.mosfet_mode,channel_type:sourceComponent.channel_type});return{jlcpcb:withBasicPartPreference(mosfets).map(m3=>`C${m3.lcsc}`).slice(0,3)}}else if(sourceComponent.type==="source_component"&&sourceComponent.ftype==="simple_resonator"){let{resonators}=await getJlcPartsCached("resonators",{frequency:sourceComponent.frequency,package:jlcpcbPackage});return{jlcpcb:withBasicPartPreference(resonators).map(r4=>`C${r4.lcsc}`).slice(0,3)}}else if(sourceComponent.type==="source_component"&&sourceComponent.ftype==="simple_switch"){let{switches}=await getJlcPartsCached("switches",{switch_type:sourceComponent.type,package:jlcpcbPackage});return{jlcpcb:withBasicPartPreference(switches).map(s4=>`C${s4.lcsc}`).slice(0,3)}}else if(sourceComponent.type==="source_component"&&sourceComponent.ftype==="simple_led"){let{leds}=await getJlcPartsCached("leds",{package:jlcpcbPackage});return{jlcpcb:withBasicPartPreference(leds).map(l3=>`C${l3.lcsc}`).slice(0,3)}}else if(sourceComponent.type==="source_component"&&sourceComponent.ftype==="simple_fuse"){let{fuses}=await getJlcPartsCached("fuses",{package:jlcpcbPackage});return{jlcpcb:withBasicPartPreference(fuses).map(l3=>`C${l3.lcsc}`).slice(0,3)}}return{}}};var import_s_expression=__toESM(require_s_expression(),1);init_zod();var import_debug19=__toESM(require_browser(),1),import_debug20=__toESM(require_browser(),1),point22=external_exports.tuple([external_exports.coerce.number(),external_exports.coerce.number()]),point33=external_exports.tuple([external_exports.number(),external_exports.number(),external_exports.number()]),point5=external_exports.union([point22,point33]),fp_poly_arc_segment_def=external_exports.object({kind:external_exports.literal("arc"),start:point22,mid:point22,end:point22}),fp_poly_point_def=external_exports.union([point22,fp_poly_arc_segment_def]),attributes_def=external_exports.object({at:point5,size:point22,layer:external_exports.string(),layers:external_exports.array(external_exports.string()),roundrect_rratio:external_exports.number(),uuid:external_exports.string()}).partial(),property_def=external_exports.object({key:external_exports.string(),val:external_exports.string(),attributes:attributes_def}),drill_def=external_exports.object({oval:external_exports.boolean().default(!1),width:external_exports.number().optional(),height:external_exports.number().optional(),offset:point22.optional()}),hole_def=external_exports.object({name:external_exports.string(),pad_type:external_exports.enum(["thru_hole","smd","np_thru_hole","connect"]),pad_shape:external_exports.enum(["roundrect","circle","rect","oval","trapezoid","custom"]),at:point5,drill:external_exports.union([external_exports.number(),external_exports.array(external_exports.any()),drill_def]).transform(a3=>typeof a3=="number"?{oval:!1,width:a3,height:a3}:"oval"in a3?a3:a3.length===2?{oval:!1,width:Number.parseFloat(a3[0]),height:Number.parseFloat(a3[0]),offset:point22.parse(a3[1].slice(1))}:a3.length===3||a3.length===4?{oval:a3[0]==="oval",width:Number.parseFloat(a3[1]),height:Number.parseFloat(a3[2]),offset:a3[3]?point22.parse(a3[3].slice(1)):void 0}:a3).pipe(drill_def),size:external_exports.union([external_exports.array(external_exports.number()).length(2).transform(([w4,h3])=>({width:w4,height:h3})),external_exports.object({width:external_exports.number(),height:external_exports.number()})]),layers:external_exports.array(external_exports.string()).optional(),roundrect_rratio:external_exports.number().optional(),uuid:external_exports.string().optional()}),pad_def2=external_exports.object({name:external_exports.string(),pad_type:external_exports.enum(["thru_hole","smd","np_thru_hole","connect"]),pad_shape:external_exports.enum(["roundrect","circle","rect","oval","trapezoid","custom"]),at:point5,size:point22,drill:external_exports.union([external_exports.number(),external_exports.array(external_exports.any()),drill_def]).transform(a3=>typeof a3=="number"?{oval:!1,width:a3,height:a3}:"oval"in a3?a3:a3.length===2?{oval:!1,width:Number.parseFloat(a3[0]),height:Number.parseFloat(a3[0]),offset:point22.parse(a3[1].slice(1))}:a3.length===3||a3.length===4?{oval:a3[0]==="oval",width:Number.parseFloat(a3[1]),height:Number.parseFloat(a3[2]),offset:a3[3]?point22.parse(a3[3].slice(1)):void 0}:a3).pipe(drill_def).optional(),layers:external_exports.array(external_exports.string()).optional(),roundrect_rratio:external_exports.number().optional(),chamfer_ratio:external_exports.number().optional(),solder_paste_margin:external_exports.number().optional(),solder_paste_margin_ratio:external_exports.number().optional(),clearance:external_exports.number().optional(),zone_connection:external_exports.union([external_exports.literal(0).describe("Pad is not connect to zone"),external_exports.literal(1).describe("Pad is connected to zone using thermal relief"),external_exports.literal(2).describe("Pad is connected to zone using solid fill")]).optional(),thermal_width:external_exports.number().optional(),thermal_gap:external_exports.number().optional(),uuid:external_exports.string().optional()}),effects_def=external_exports.object({font:external_exports.object({size:point22,thickness:external_exports.number().optional()})}).partial(),fp_text_def=external_exports.object({fp_text_type:external_exports.literal("user"),text:external_exports.string(),at:point5,layer:external_exports.string(),uuid:external_exports.string().optional(),effects:effects_def.partial()}),fp_arc_def=external_exports.object({start:point22,mid:point22,end:point22,stroke:external_exports.object({width:external_exports.number(),type:external_exports.string()}),layer:external_exports.string(),uuid:external_exports.string().optional()}),fp_circle_def=external_exports.object({center:point22,end:point22,stroke:external_exports.object({width:external_exports.number(),type:external_exports.string()}),fill:external_exports.string().optional(),layer:external_exports.string(),uuid:external_exports.string().optional()}),fp_poly_def=external_exports.object({pts:external_exports.array(fp_poly_point_def),stroke:external_exports.object({width:external_exports.number(),type:external_exports.string()}).optional(),width:external_exports.number().optional(),layer:external_exports.string(),uuid:external_exports.string().optional(),fill:external_exports.string().optional()}).transform(data=>({...data,width:void 0,stroke:data.stroke??{width:data.width}})),fp_line=external_exports.object({start:point22,end:point22,stroke:external_exports.object({width:external_exports.number(),type:external_exports.string()}).optional(),width:external_exports.number().optional(),layer:external_exports.string(),uuid:external_exports.string().optional()}).transform(data=>({...data,width:void 0,stroke:data.stroke??{width:data.width}})),kicad_mod_json_def=external_exports.object({footprint_name:external_exports.string(),version:external_exports.string().optional(),generator:external_exports.string().optional(),generator_version:external_exports.string().optional(),layer:external_exports.string(),descr:external_exports.string().default(""),tags:external_exports.array(external_exports.string()).optional(),properties:external_exports.array(property_def),fp_lines:external_exports.array(fp_line),fp_texts:external_exports.array(fp_text_def),fp_arcs:external_exports.array(fp_arc_def),fp_circles:external_exports.array(fp_circle_def).optional(),fp_polys:external_exports.array(fp_poly_def).optional(),pads:external_exports.array(pad_def2),holes:external_exports.array(hole_def).optional()}),formatAttr=(val,attrKey)=>{if(attrKey==="effects"&&Array.isArray(val)){let effectsObj={};for(let elm of val)if(elm[0]==="font"){let fontObj={};for(let fontElm of elm.slice(1))fontElm.length===2?fontObj[fontElm[0].valueOf()]=Number.parseFloat(fontElm[1].valueOf()):fontObj[fontElm[0].valueOf()]=fontElm.slice(1).map(n3=>Number.parseFloat(n3.valueOf()));effectsObj.font=fontObj}return effects_def.parse(effectsObj)}if(attrKey==="pts")return val.map(segment2=>{let segmentType=segment2[0]?.valueOf?.()??segment2[0];if(segmentType==="xy")return segment2.slice(1).map(n3=>Number.parseFloat(n3.valueOf()));if(segmentType==="arc"){let arcObj={kind:"arc"};for(let arcAttr of segment2.slice(1)){let key=arcAttr[0].valueOf();arcObj[key]=arcAttr.slice(1).map(n3=>Number.parseFloat(n3.valueOf()))}return arcObj}return segment2});if(attrKey==="stroke"){let strokeObj={};for(let strokeElm of val){let strokePropKey=strokeElm[0].valueOf();strokeObj[strokePropKey]=formatAttr(strokeElm.slice(1),strokePropKey)}return strokeObj}return attrKey==="at"||attrKey==="size"||attrKey==="start"||attrKey==="mid"||attrKey==="end"?(Array.isArray(val)?val:[val]).map(n3=>n3?.valueOf?.()??n3).filter(v4=>typeof v4=="number"||typeof v4=="string"&&/^[-+]?\d*\.?\d+(e[-+]?\d+)?$/i.test(v4)).map(v4=>typeof v4=="number"?v4:Number.parseFloat(v4)):attrKey==="tags"?val.map(n3=>n3.valueOf()):attrKey==="generator_version"||attrKey==="version"?val[0].valueOf():val.length===2?val.valueOf():attrKey==="uuid"?Array.isArray(val)?val[0].valueOf():val.valueOf():/^[\d\.]+$/.test(val)&&!Number.isNaN(Number.parseFloat(val))?Number.parseFloat(val):Array.isArray(val)&&val.length===1?val[0].valueOf():Array.isArray(val)?val.map(s4=>s4.valueOf()):val},getAttr=(s4,key)=>{for(let elm of s4)if(Array.isArray(elm)&&elm[0]===key)return formatAttr(elm.slice(1),key)},debug11=(0,import_debug19.default)("kicad-mod-converter"),parseKicadModToKicadJson=fileContent=>{let kicadSExpr=(0,import_s_expression.default)(fileContent),footprintName=kicadSExpr[1].valueOf(),topLevelAttributes={},simpleTopLevelAttributes=Object.entries(kicad_mod_json_def.shape).filter(([attributeKey,def])=>def._def.typeName==="ZodString"||attributeKey==="tags").map(([attributeKey])=>attributeKey);for(let kicadSExprRow of kicadSExpr.slice(2)){if(!simpleTopLevelAttributes.includes(kicadSExprRow[0]))continue;let key=kicadSExprRow[0].valueOf(),val=formatAttr(kicadSExprRow.slice(1),key);topLevelAttributes[key]=val}let properties=kicadSExpr.slice(2).filter(row=>row[0]==="property").map(row=>{let key=row[1].valueOf(),val=row[2].valueOf(),attributes2=attributes_def.parse(row.slice(3).reduce((acc,attrAr)=>{let attrKey=attrAr[0].valueOf();return acc[attrKey]=formatAttr(attrAr.slice(1),attrKey),acc},{}));return{key,val,attributes:attributes2}}),padRows=kicadSExpr.slice(2).filter(row=>row[0]==="pad"),pads=[];for(let row of padRows){let at3=getAttr(row,"at"),size2=getAttr(row,"size"),drill=getAttr(row,"drill"),layers=getAttr(row,"layers");if(Array.isArray(layers)?layers=layers.map(layer=>layer.valueOf()):typeof layers=="string"?layers=[layers]:layers||(layers=[]),!layers.includes("F.Cu")){debug11(`Skipping pad without F.Cu layer: layers=${layers.join(", ")}`);continue}let roundrect_rratio=getAttr(row,"roundrect_rratio"),uuid=getAttr(row,"uuid"),padRaw={name:row[1].valueOf(),pad_type:row[2].valueOf(),pad_shape:row[3].valueOf(),at:at3,drill,size:size2,layers,roundrect_rratio,uuid};debug11(`attempting to parse pad: ${JSON.stringify(padRaw,null," ")}`),pads.push(pad_def2.parse(padRaw))}let fp_texts_rows=kicadSExpr.slice(2).filter(row=>row[0]==="fp_text"),fp_texts=[];for(let fp_text_row of fp_texts_rows){let text=fp_text_row[2].valueOf(),at3=getAttr(fp_text_row,"at"),layer=getAttr(fp_text_row,"layer"),uuid=getAttr(fp_text_row,"uuid"),effects=getAttr(fp_text_row,"effects");fp_texts.push({fp_text_type:"user",text,at:at3,layer,uuid,effects})}let fp_lines=[],fp_lines_rows=kicadSExpr.slice(2).filter(row=>row[0]==="fp_line");for(let fp_line_row of fp_lines_rows){let start=getAttr(fp_line_row,"start"),end=getAttr(fp_line_row,"end"),stroke=getAttr(fp_line_row,"stroke"),layer=getAttr(fp_line_row,"layer"),uuid=getAttr(fp_line_row,"uuid");fp_lines.push({start,end,stroke,layer,uuid})}let fp_arcs=[],fp_arcs_rows=kicadSExpr.slice(2).filter(row=>row[0]==="fp_arc");for(let fp_arc_row of fp_arcs_rows){let start=getAttr(fp_arc_row,"start"),mid=getAttr(fp_arc_row,"mid"),end=getAttr(fp_arc_row,"end"),stroke=getAttr(fp_arc_row,"stroke"),layer=getAttr(fp_arc_row,"layer"),uuid=getAttr(fp_arc_row,"uuid");!start||!end||!mid||!stroke||!layer||fp_arcs.push({start,mid,end,stroke,layer,uuid})}let fp_circles=[],fp_circles_rows=kicadSExpr.slice(2).filter(row=>row[0]==="fp_circle");for(let fp_circle_row of fp_circles_rows){let center2=getAttr(fp_circle_row,"center"),end=getAttr(fp_circle_row,"end"),stroke=getAttr(fp_circle_row,"stroke"),fill=getAttr(fp_circle_row,"fill"),layer=getAttr(fp_circle_row,"layer"),uuid=getAttr(fp_circle_row,"uuid");!center2||!end||!stroke||!layer||fp_circles.push({center:center2,end,stroke,fill,layer,uuid})}let fp_polys=[],fp_polys_rows=kicadSExpr.slice(2).filter(row=>row[0]==="fp_poly");for(let fp_poly_row of fp_polys_rows){let pts=getAttr(fp_poly_row,"pts"),stroke=getAttr(fp_poly_row,"stroke"),width=getAttr(fp_poly_row,"width"),layer=getAttr(fp_poly_row,"layer"),uuid=getAttr(fp_poly_row,"uuid"),fill=getAttr(fp_poly_row,"fill"),normalizedStroke=stroke;!normalizedStroke&&typeof width=="number"?normalizedStroke={width,type:"solid"}:normalizedStroke&&typeof normalizedStroke=="object"&&typeof width=="number"&&normalizedStroke.width===void 0&&(normalizedStroke={...normalizedStroke,width}),fp_polys.push({pts,stroke:normalizedStroke,layer,uuid,fill})}let holes=[];for(let row of kicadSExpr.slice(2)){if(row[0]!=="pad"||row[2]?.valueOf?.()!=="thru_hole")continue;let name=row[1]?.valueOf?.(),pad_type=row[2]?.valueOf?.(),pad_shape=row[3]?.valueOf?.(),at3=getAttr(row,"at"),drill=getAttr(row,"drill"),size2=getAttr(row,"size");Array.isArray(size2)&&(size2[0]==="size"&&(size2=size2.slice(1)),size2={width:Number(size2[0]),height:Number(size2[1])});let uuid=getAttr(row,"uuid"),roundrect_rratio=getAttr(row,"roundrect_rratio"),layers=getAttr(row,"layers");Array.isArray(layers)?layers=layers.map(layer=>layer.valueOf()):typeof layers=="string"?layers=[layers]:layers||(layers=[]);let holeRaw={name,pad_type,pad_shape,at:at3,drill,size:size2,layers,roundrect_rratio,uuid};debug11(`attempting to parse holes: ${JSON.stringify(holeRaw,null,2)}`),holes.push(hole_def.parse(holeRaw))}return kicad_mod_json_def.parse({footprint_name:footprintName,...topLevelAttributes,properties,fp_lines,fp_texts,fp_arcs,fp_circles,pads,holes,fp_polys})},TWO_PI=Math.PI*2,normalizeAngle2=angle=>{let result=angle%TWO_PI;return result<0&&(result+=TWO_PI),result},directedAngleCCW=(start,target)=>{let startNorm=normalizeAngle2(start),delta=normalizeAngle2(target)-startNorm;return delta<0&&(delta+=TWO_PI),delta};function calculateCenter(start,mid,end){let mid1={x:(start.x+mid.x)/2,y:(start.y+mid.y)/2},mid2={x:(mid.x+end.x)/2,y:(mid.y+end.y)/2},slope1=-(start.x-mid.x)/(start.y-mid.y),slope2=-(mid.x-end.x)/(mid.y-end.y),centerX=(mid1.y-mid2.y+slope2*mid2.x-slope1*mid1.x)/(slope2-slope1),centerY=mid1.y+slope1*(centerX-mid1.x);return{x:centerX,y:centerY}}function calculateRadius(center2,point42){return Math.sqrt((center2.x-point42.x)**2+(center2.y-point42.y)**2)}function calculateAngle(center2,point42){return Math.atan2(point42.y-center2.y,point42.x-center2.x)}var getArcLength=(start,mid,end)=>{let center2=calculateCenter(start,mid,end),radius=calculateRadius(center2,start),angleStart=calculateAngle(center2,start),angleMid=calculateAngle(center2,mid),angleEnd=calculateAngle(center2,end),ccwToMid=directedAngleCCW(angleStart,angleMid),ccwToEnd=directedAngleCCW(angleStart,angleEnd),angleDelta=ccwToEnd;return ccwToMid>ccwToEnd&&(angleDelta=ccwToEnd-TWO_PI),Math.abs(radius*angleDelta)};function generateArcPath(start,mid,end,numPoints){let center2=calculateCenter(start,mid,end),radius=calculateRadius(center2,start),angleStart=calculateAngle(center2,start),angleMid=calculateAngle(center2,mid),angleEnd=calculateAngle(center2,end),ccwToMid=directedAngleCCW(angleStart,angleMid),ccwToEnd=directedAngleCCW(angleStart,angleEnd),angleDelta=ccwToEnd;ccwToMid>ccwToEnd&&(angleDelta=ccwToEnd-TWO_PI);let path=[];for(let i3=0;i3<=numPoints;i3++){let angle=angleStart+i3/numPoints*angleDelta,x3=center2.x+radius*Math.cos(angle),y3=center2.y+radius*Math.sin(angle);path.push({x:x3,y:y3})}return path}var makePoint=p4=>Array.isArray(p4)?{x:p4[0],y:p4[1]}:p4,pointsEqual=(p12,p22,tolerance=1e-4)=>Math.abs(p12.x-p22.x)<tolerance&&Math.abs(p12.y-p22.y)<tolerance,findClosedPolygons=segments=>{let polygons=[],used=new Set;for(let i3=0;i3<segments.length;i3++){if(used.has(i3))continue;let polygon2=[segments[i3]];used.add(i3);let currentEnd=segments[i3].end,foundNext=!0;for(;foundNext;){if(foundNext=!1,polygon2.length>1&&pointsEqual(currentEnd,polygon2[0].start)){polygons.push(polygon2);break}for(let j3=0;j3<segments.length;j3++)if(!used.has(j3)){if(pointsEqual(currentEnd,segments[j3].start)){polygon2.push(segments[j3]),used.add(j3),currentEnd=segments[j3].end,foundNext=!0;break}else if(pointsEqual(currentEnd,segments[j3].end)){segments[j3].type==="arc"?polygon2.push({...segments[j3],reversed:!0}):polygon2.push({...segments[j3],start:segments[j3].end,end:segments[j3].start}),used.add(j3),currentEnd=segments[j3].start,foundNext=!0;break}}if(!foundNext){for(let k4=polygon2.length-1;k4>=0;k4--){let idx=segments.indexOf(polygon2[k4]);idx!==-1&&used.delete(idx)}break}}}return polygons},polygonToPoints=polygon2=>{let points=[];for(let segment2 of polygon2)if(segment2.type==="line")points.push(segment2.start);else if(segment2.type==="arc"&&segment2.mid){let arcLength=getArcLength(segment2.start,segment2.mid,segment2.end),numPoints=Math.max(3,Math.ceil(arcLength)),arcPoints=generateArcPath(segment2.start,segment2.mid,segment2.end,numPoints);segment2.reversed&&(arcPoints=arcPoints.reverse()),points.push(...arcPoints.slice(0,-1))}return points};function getSilkscreenFontSizeFromFpTexts(fp_texts){if(!Array.isArray(fp_texts))return null;let refText=fp_texts.find(t6=>t6.layer?.toLowerCase()==="f.silks"&&(t6.text?.includes("${REFERENCE}")||t6.fp_text_type?.toLowerCase()==="reference"||t6.text?.match(/^R\d+|C\d+|U\d+/))),fallbackText=refText||fp_texts.find(t6=>t6.layer?.toLowerCase()==="f.fab"&&(t6.text?.includes("${REFERENCE}")||t6.fp_text_type?.toLowerCase()==="reference")),target=refText||fallbackText;if(!target?.effects?.font?.size)return null;let[width,height]=target.effects.font.size;return height??width??1}var degToRad=deg=>deg*Math.PI/180,rotatePoint3=(x3,y3,deg)=>{let r4=degToRad(deg),cos4=Math.cos(r4),sin4=Math.sin(r4);return{x:x3*cos4-y3*sin4,y:x3*sin4+y3*cos4}},getAxisAlignedRectFromPoints=points=>{let uniquePoints=[...new Map(points.map(p4=>[`${p4.x},${p4.y}`,p4])).values()];if(uniquePoints.length!==4)return null;let xs3=uniquePoints.map(p4=>p4.x),ys3=uniquePoints.map(p4=>p4.y),uniqueXs=[...new Set(xs3)],uniqueYs=[...new Set(ys3)];if(uniqueXs.length!==2||uniqueYs.length!==2)return null;let[minX,maxX]=uniqueXs.sort((a3,b3)=>a3-b3),[minY,maxY]=uniqueYs.sort((a3,b3)=>a3-b3);return minX===void 0||maxX===void 0||minY===void 0||maxY===void 0?null:{x:(minX+maxX)/2,y:(minY+maxY)/2,width:maxX-minX,height:maxY-minY}},fpPolyHasFill=fill=>{if(!fill)return!1;let normalized=fill.toLowerCase();return normalized!=="no"&&normalized!=="none"&&normalized!=="outline"},getRotationDeg=at3=>at3&&Array.isArray(at3)&&at3.length>=3&&typeof at3[2]=="number"?at3[2]:0,isNinetyLike=deg=>{let n3=(deg%360+360)%360;return n3===90||n3===270},normalizePortName=name=>{if(name!=null)return`${name}`},getPinNumber=name=>{let normalized=normalizePortName(name),parsed=normalized!==void 0?Number(normalized):NaN;return Number.isFinite(parsed)?parsed:void 0},debug23=(0,import_debug20.default)("kicad-mod-converter"),convertKicadLayerToTscircuitLayer=kicadLayer=>{switch(kicadLayer.toLowerCase()){case"f.cu":case"f.fab":case"f.silks":case"edge.cuts":return"top";case"b.cu":case"b.fab":case"b.silks":return"bottom"}},convertKicadJsonToTsCircuitSoup=async kicadJson=>{let{fp_lines,fp_texts,fp_arcs,fp_circles,pads,properties,holes,fp_polys}=kicadJson,circuitJson=[];circuitJson.push({type:"source_component",source_component_id:"source_component_0",supplier_part_numbers:{}}),circuitJson.push({type:"schematic_component",schematic_component_id:"schematic_component_0",source_component_id:"source_component_0",center:{x:0,y:0},rotation:0,size:{width:0,height:0}});let portNames=new Set,portNameToPinNumber=new Map;for(let pad2 of pads){let portName=normalizePortName(pad2.name);if(portName){portNames.add(portName);let pinNumber=getPinNumber(pad2.name);pinNumber!==void 0&&portNameToPinNumber.set(portName,pinNumber)}}if(holes)for(let hole of holes){let portName=normalizePortName(hole.name);if(portName){portNames.add(portName);let pinNumber=getPinNumber(hole.name);pinNumber!==void 0&&portNameToPinNumber.set(portName,pinNumber)}}let sourcePortId=0,portNameToSourcePortId=new Map;for(let portName of portNames){let source_port_id=`source_port_${sourcePortId++}`;portNameToSourcePortId.set(portName,source_port_id);let pinNumber=portNameToPinNumber.get(portName);circuitJson.push({type:"source_port",source_port_id,source_component_id:"source_component_0",name:portName,port_hints:[portName],pin_number:pinNumber,pin_label:pinNumber!==void 0?`pin${pinNumber}`:void 0}),circuitJson.push({type:"schematic_port",schematic_port_id:`schematic_port_${sourcePortId++}`,source_port_id,schematic_component_id:"schematic_component_0",center:{x:0,y:0}})}let minX=Number.POSITIVE_INFINITY,maxX=Number.NEGATIVE_INFINITY,minY=Number.POSITIVE_INFINITY,maxY=Number.NEGATIVE_INFINITY;for(let pad2 of pads){let x3=pad2.at[0],y3=-pad2.at[1],w4=pad2.size[0],h3=pad2.size[1];minX=Math.min(minX,x3-w4/2),maxX=Math.max(maxX,x3+w4/2),minY=Math.min(minY,y3-h3/2),maxY=Math.max(maxY,y3+h3/2)}let pcb_component_id="pcb_component_0";circuitJson.push({type:"pcb_component",source_component_id:"source_component_0",pcb_component_id,layer:"top",center:{x:0,y:0},rotation:0,width:Number.isFinite(minX)?maxX-minX:0,height:Number.isFinite(minY)?maxY-minY:0});let pcbPortId=0,portNameToPcbPortId=new Map;for(let portName of portNames){let pcb_port_id=`pcb_port_${pcbPortId++}`,source_port_id=portNameToSourcePortId.get(portName);portNameToPcbPortId.set(portName,pcb_port_id);let x3=0,y3=0,layers=["top","bottom"],pad2=pads.find(p4=>normalizePortName(p4.name)===portName);if(pad2)x3=pad2.at[0],y3=-pad2.at[1],layers=pad2.layers?pad2.layers.map(l3=>convertKicadLayerToTscircuitLayer(l3)).filter(Boolean):["top","bottom"];else if(holes){let hole=holes.find(h3=>normalizePortName(h3.name)===portName);hole&&(x3=hole.at[0],y3=-hole.at[1],layers=hole.layers?hole.layers.map(l3=>convertKicadLayerToTscircuitLayer(l3)).filter(Boolean):["top","bottom"])}circuitJson.push({type:"pcb_port",pcb_port_id,source_port_id,pcb_component_id,x:x3,y:y3,layers})}let smtpadId=0,platedHoleId=0,holeId=0;for(let pad2 of pads){let portName=normalizePortName(pad2.name),pinNumber=portName?portNameToPinNumber.get(portName):void 0;if(pad2.pad_type==="smd"){let rotation4=getRotationDeg(pad2.at),width=isNinetyLike(rotation4)?pad2.size[1]:pad2.size[0],height=isNinetyLike(rotation4)?pad2.size[0]:pad2.size[1],pcb_port_id=portName?portNameToPcbPortId.get(portName):void 0,pinLabel=pinNumber!==void 0?`pin${pinNumber}`:void 0;circuitJson.push({type:"pcb_smtpad",pcb_smtpad_id:`pcb_smtpad_${smtpadId++}`,shape:"rect",x:pad2.at[0],y:-pad2.at[1],width,height,layer:convertKicadLayerToTscircuitLayer(pad2.layers?.[0]??"F.Cu"),pcb_component_id,port_hints:pinLabel?[pinLabel]:portName?[portName]:[],pcb_port_id,pin_number:pinNumber,pin_label:pinLabel})}else if(pad2.pad_type==="thru_hole"){if(pad2.pad_shape==="rect"){let rotation4=getRotationDeg(pad2.at),width=isNinetyLike(rotation4)?pad2.size[1]:pad2.size[0],height=isNinetyLike(rotation4)?pad2.size[0]:pad2.size[1],offX=pad2.drill?.offset?.[0]??0,offY=pad2.drill?.offset?.[1]??0,rotOff=rotatePoint3(offX,offY,rotation4),pcb_port_id=portName?portNameToPcbPortId.get(portName):void 0,pinLabel=pinNumber!==void 0?`pin${pinNumber}`:void 0;circuitJson.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${platedHoleId++}`,shape:"circular_hole_with_rect_pad",hole_shape:"circle",pad_shape:"rect",x:pad2.at[0],y:-pad2.at[1],hole_offset_x:-rotOff.x,hole_offset_y:-rotOff.y,hole_diameter:pad2.drill?.width,rect_pad_width:width,rect_pad_height:height,layers:["top","bottom"],pcb_component_id,port_hints:pinLabel?[pinLabel]:portName?[portName]:[],pcb_port_id,pin_number:pinNumber,pin_label:pinLabel})}else if(pad2.pad_shape==="circle"){let pcb_port_id=portName?portNameToPcbPortId.get(portName):void 0,pinLabel=pinNumber!==void 0?`pin${pinNumber}`:void 0;circuitJson.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${platedHoleId++}`,shape:"circle",x:pad2.at[0],y:-pad2.at[1],outer_diameter:pad2.size[0],hole_diameter:pad2.drill?.width,layers:["top","bottom"],pcb_component_id,port_hints:pinLabel?[pinLabel]:portName?[portName]:[],pcb_port_id,pin_number:pinNumber,pin_label:pinLabel})}else if(pad2.pad_shape==="oval"){let pcb_port_id=portName?portNameToPcbPortId.get(portName):void 0,pinLabel=pinNumber!==void 0?`pin${pinNumber}`:void 0;circuitJson.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${platedHoleId++}`,shape:"pill",x:pad2.at[0],y:-pad2.at[1],outer_width:pad2.size[0],outer_height:pad2.size[1],hole_width:pad2.drill?.width,hole_height:pad2.drill?.height,layers:["top","bottom"],pcb_component_id,port_hints:pinLabel?[pinLabel]:portName?[portName]:[],pcb_port_id,pin_number:pinNumber,pin_label:pinLabel})}}else pad2.pad_type==="np_thru_hole"&&circuitJson.push({type:"pcb_hole",pcb_hole_id:`pcb_hole_${holeId++}`,x:pad2.at[0],y:-pad2.at[1],hole_diameter:pad2.drill?.width,pcb_component_id})}if(holes)for(let hole of holes){let portName=normalizePortName(hole.name),pinNumber=portName?portNameToPinNumber.get(portName):void 0,hasCuLayer=hole.layers?.some(l3=>l3.endsWith(".Cu")||l3==="*.Cu"),rotation4=getRotationDeg(hole.at),offX=hole.drill?.offset?.[0]??0,offY=hole.drill?.offset?.[1]??0,rotOff=rotatePoint3(offX,offY,rotation4),x3=hole.at[0]+rotOff.x,y3=-(hole.at[1]+rotOff.y),holeDiameter=hole.drill?.width??0,outerDiameter=hole.size?.width??holeDiameter,rr2=hole.roundrect_rratio??0,rectBorderRadius=rr2>0?Math.min(isNinetyLike(rotation4)?hole.size?.height??outerDiameter:hole.size?.width??outerDiameter,isNinetyLike(rotation4)?hole.size?.width??outerDiameter:hole.size?.height??outerDiameter)/2*rr2:0;if(hasCuLayer)if(hole.pad_shape==="rect"){let pcb_port_id=portName?portNameToPcbPortId.get(portName):void 0;circuitJson.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${platedHoleId++}`,shape:"circular_hole_with_rect_pad",hole_shape:"circle",pad_shape:"rect",x:hole.at[0],y:-hole.at[1],hole_offset_x:-rotOff.x,hole_offset_y:-rotOff.y,hole_diameter:holeDiameter,rect_pad_width:isNinetyLike(rotation4)?hole.size?.height??outerDiameter:hole.size?.width??outerDiameter,rect_pad_height:isNinetyLike(rotation4)?hole.size?.width??outerDiameter:hole.size?.height??outerDiameter,rect_border_radius:rectBorderRadius,port_hints:pinNumber!==void 0?[`pin${pinNumber}`]:portName?[portName]:[],layers:["top","bottom"],pcb_component_id,pcb_port_id,pin_number:pinNumber,pin_label:pinNumber!==void 0?`pin${pinNumber}`:void 0})}else if(hole.pad_shape==="oval"){let pcb_port_id=portName?portNameToPcbPortId.get(portName):void 0;circuitJson.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${platedHoleId++}`,shape:"pill",x:x3,y:y3,outer_width:isNinetyLike(rotation4)?hole.size?.height??outerDiameter:hole.size?.width??outerDiameter,outer_height:isNinetyLike(rotation4)?hole.size?.width??outerDiameter:hole.size?.height??outerDiameter,hole_width:isNinetyLike(rotation4)?hole.drill?.height??holeDiameter:hole.drill?.width??holeDiameter,hole_height:isNinetyLike(rotation4)?hole.drill?.width??holeDiameter:hole.drill?.height??holeDiameter,port_hints:pinNumber!==void 0?[`pin${pinNumber}`]:portName?[portName]:[],layers:["top","bottom"],pcb_component_id,pcb_port_id,pin_number:pinNumber,pin_label:pinNumber!==void 0?`pin${pinNumber}`:void 0})}else if(hole.pad_shape==="roundrect"){let pcb_port_id=portName?portNameToPcbPortId.get(portName):void 0,offX2=hole.drill?.offset?.[0]??0,offY2=hole.drill?.offset?.[1]??0,rotOff2=rotatePoint3(offX2,offY2,rotation4),width=isNinetyLike(rotation4)?hole.size?.height??outerDiameter:hole.size?.width??outerDiameter,height=isNinetyLike(rotation4)?hole.size?.width??outerDiameter:hole.size?.height??outerDiameter;circuitJson.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${platedHoleId++}`,shape:"circular_hole_with_rect_pad",hole_shape:"circle",pad_shape:"rect",x:x3,y:y3,hole_offset_x:-rotOff2.x,hole_offset_y:rotOff2.y,hole_diameter:holeDiameter,rect_pad_width:width,rect_pad_height:height,rect_border_radius:rectBorderRadius,port_hints:pinNumber!==void 0?[`pin${pinNumber}`]:portName?[portName]:[],layers:["top","bottom"],pcb_component_id,pcb_port_id,pin_number:pinNumber,pin_label:pinNumber!==void 0?`pin${pinNumber}`:void 0})}else{let pcb_port_id=portName?portNameToPcbPortId.get(portName):void 0;circuitJson.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${platedHoleId++}`,shape:"circle",x:x3,y:y3,outer_diameter:outerDiameter,hole_diameter:holeDiameter,port_hints:pinNumber!==void 0?[`pin${pinNumber}`]:portName?[portName]:[],layers:["top","bottom"],pcb_component_id,pcb_port_id,pin_number:pinNumber,pin_label:pinNumber!==void 0?`pin${pinNumber}`:void 0})}else circuitJson.push({type:"pcb_hole",pcb_hole_id:`pcb_hole_${holeId++}`,x:x3,y:y3,hole_diameter:outerDiameter,hole_shape:"circle",pcb_component_id})}let edgeCutSegments=[];for(let fp_line2 of fp_lines)fp_line2.layer.toLowerCase()==="edge.cuts"&&edgeCutSegments.push({type:"line",start:{x:fp_line2.start[0],y:fp_line2.start[1]},end:{x:fp_line2.end[0],y:fp_line2.end[1]},strokeWidth:fp_line2.stroke.width});for(let fp_arc of fp_arcs)fp_arc.layer.toLowerCase()==="edge.cuts"&&edgeCutSegments.push({type:"arc",start:{x:fp_arc.start[0],y:fp_arc.start[1]},mid:{x:fp_arc.mid[0],y:fp_arc.mid[1]},end:{x:fp_arc.end[0],y:fp_arc.end[1]},strokeWidth:fp_arc.stroke.width});let closedPolygons=findClosedPolygons(edgeCutSegments),cutoutId=0;for(let polygon2 of closedPolygons){let points=polygonToPoints(polygon2);points.length>=3&&circuitJson.push({type:"pcb_cutout",pcb_cutout_id:`pcb_cutout_${cutoutId++}`,shape:"polygon",points:points.map(p4=>({x:p4.x,y:-p4.y})),pcb_component_id})}let traceId=0,silkPathId=0,fabPathId=0,noteLineId=0;for(let fp_line2 of fp_lines){let route=[{x:fp_line2.start[0],y:-fp_line2.start[1]},{x:fp_line2.end[0],y:-fp_line2.end[1]}],lowerLayer=fp_line2.layer.toLowerCase();lowerLayer==="f.cu"?circuitJson.push({type:"pcb_trace",pcb_trace_id:`pcb_trace_${traceId++}`,pcb_component_id,layer:convertKicadLayerToTscircuitLayer(fp_line2.layer),route,thickness:fp_line2.stroke.width}):lowerLayer==="f.silks"?circuitJson.push({type:"pcb_silkscreen_path",pcb_silkscreen_path_id:`pcb_silkscreen_path_${silkPathId++}`,pcb_component_id,layer:"top",route,stroke_width:fp_line2.stroke.width}):lowerLayer==="edge.cuts"?debug23("Skipping Edge.Cuts fp_line (converted to pcb_cutout)",fp_line2.layer):lowerLayer==="f.fab"?circuitJson.push({type:"pcb_fabrication_note_path",fabrication_note_path_id:`fabrication_note_path_${fabPathId++}`,pcb_component_id,layer:"top",route,stroke_width:fp_line2.stroke.width,port_hints:[]}):lowerLayer.startsWith("user.")?circuitJson.push({type:"pcb_note_line",pcb_note_line_id:`pcb_note_line_${noteLineId++}`,pcb_component_id,x1:fp_line2.start[0],y1:-fp_line2.start[1],x2:fp_line2.end[0],y2:-fp_line2.end[1],stroke_width:fp_line2.stroke.width}):debug23("Unhandled layer for fp_line",fp_line2.layer)}if(fp_polys)for(let fp_poly of fp_polys){let route=[],pushRoutePoint=point42=>{!Number.isFinite(point42.x)||!Number.isFinite(point42.y)||route.push(point42)};for(let segment2 of fp_poly.pts){if(Array.isArray(segment2)){pushRoutePoint({x:segment2[0],y:-segment2[1]});continue}if(segment2&&typeof segment2=="object"&&"kind"in segment2){if(segment2.kind==="arc"){let start=makePoint(segment2.start),mid=makePoint(segment2.mid),end=makePoint(segment2.end),arcLength=getArcLength(start,mid,end),numPoints=Math.max(8,Math.ceil(arcLength)),adjustedNumPoints=Math.max(2,Math.ceil(arcLength/.1)),arcPoints=generateArcPath(start,mid,end,adjustedNumPoints).map(p4=>({x:p4.x,y:-p4.y}));for(let point42 of arcPoints)pushRoutePoint(point42)}continue}}let routePoints=route,polygonPoints=routePoints.length>2&&routePoints[0].x===routePoints[routePoints.length-1].x&&routePoints[0].y===routePoints[routePoints.length-1].y?routePoints.slice(0,-1):routePoints;if(routePoints.length===0)continue;let strokeWidth=fp_poly.stroke?.width??0;if(fp_poly.layer.endsWith(".Cu")){let rect=getAxisAlignedRectFromPoints(polygonPoints);rect?circuitJson.push({type:"pcb_smtpad",pcb_smtpad_id:`pcb_smtpad_${smtpadId++}`,shape:"rect",x:rect.x,y:rect.y,width:rect.width,height:rect.height,layer:convertKicadLayerToTscircuitLayer(fp_poly.layer),pcb_component_id}):fpPolyHasFill(fp_poly.fill)?polygonPoints.length>=3?circuitJson.push({type:"pcb_smtpad",pcb_smtpad_id:`pcb_smtpad_${smtpadId++}`,shape:"polygon",points:polygonPoints,layer:convertKicadLayerToTscircuitLayer(fp_poly.layer),pcb_component_id}):polygonPoints.length>=2&&circuitJson.push({type:"pcb_trace",pcb_trace_id:`pcb_trace_${traceId++}`,pcb_component_id,layer:convertKicadLayerToTscircuitLayer(fp_poly.layer),route:polygonPoints,thickness:strokeWidth}):polygonPoints.length>=2&&circuitJson.push({type:"pcb_trace",pcb_trace_id:`pcb_trace_${traceId++}`,pcb_component_id,layer:convertKicadLayerToTscircuitLayer(fp_poly.layer),route:polygonPoints,thickness:strokeWidth})}else fp_poly.layer.endsWith(".SilkS")?circuitJson.push({type:"pcb_silkscreen_path",pcb_silkscreen_path_id:`pcb_silkscreen_path_${silkPathId++}`,pcb_component_id,layer:convertKicadLayerToTscircuitLayer(fp_poly.layer),route:routePoints,stroke_width:strokeWidth}):fp_poly.layer.endsWith(".Fab")?circuitJson.push({type:"pcb_fabrication_note_path",fabrication_note_path_id:`fabrication_note_path_${fabPathId++}`,pcb_component_id,layer:convertKicadLayerToTscircuitLayer(fp_poly.layer),route:polygonPoints,stroke_width:strokeWidth,port_hints:[]}):debug23("Unhandled layer for fp_poly",fp_poly.layer)}let notePathId=0;for(let fp_arc of fp_arcs){let lowerLayer=fp_arc.layer.toLowerCase();if(lowerLayer==="edge.cuts"){debug23("Skipping Edge.Cuts fp_arc (converted to pcb_cutout)",fp_arc.layer);continue}let start=makePoint(fp_arc.start),mid=makePoint(fp_arc.mid),end=makePoint(fp_arc.end),arcLength=getArcLength(start,mid,end),arcPoints=generateArcPath(start,mid,end,Math.ceil(arcLength));if(lowerLayer.startsWith("user.")){circuitJson.push({type:"pcb_note_path",pcb_note_path_id:`pcb_note_path_${notePathId++}`,pcb_component_id,route:arcPoints.map(p4=>({x:p4.x,y:-p4.y})),stroke_width:fp_arc.stroke.width});continue}let tscircuitLayer=convertKicadLayerToTscircuitLayer(fp_arc.layer);if(!tscircuitLayer){debug23("Unable to convert layer for fp_arc",fp_arc.layer);continue}circuitJson.push({type:"pcb_silkscreen_path",pcb_silkscreen_path_id:`pcb_silkscreen_path_${silkPathId++}`,layer:tscircuitLayer,pcb_component_id,route:arcPoints.map(p4=>({x:p4.x,y:-p4.y})),stroke_width:fp_arc.stroke.width})}if(fp_circles)for(let fp_circle of fp_circles){let lowerLayer=fp_circle.layer.toLowerCase(),center2=makePoint(fp_circle.center),endPoint=makePoint(fp_circle.end),radius=Math.sqrt((endPoint.x-center2.x)**2+(endPoint.y-center2.y)**2),numPoints=Math.max(16,Math.ceil(2*Math.PI*radius)),circlePoints=[];for(let i3=0;i3<=numPoints;i3++){let angle=i3/numPoints*2*Math.PI;circlePoints.push({x:center2.x+radius*Math.cos(angle),y:center2.y+radius*Math.sin(angle)})}lowerLayer.startsWith("user.")&&circuitJson.push({type:"pcb_note_path",pcb_note_path_id:`pcb_note_path_${notePathId++}`,pcb_component_id,route:circlePoints.map(p4=>({x:p4.x,y:-p4.y})),stroke_width:fp_circle.stroke.width})}for(let fp_text of fp_texts){let layerRef=convertKicadLayerToTscircuitLayer(fp_text.layer);fp_text.layer.endsWith(".SilkS")?circuitJson.push({type:"pcb_silkscreen_text",layer:layerRef,font:"tscircuit2024",font_size:fp_text.effects?.font?.size[0]??1,pcb_component_id,anchor_position:{x:fp_text.at[0],y:-fp_text.at[1]},anchor_alignment:"center",text:fp_text.text}):fp_text.layer.endsWith(".Fab")?circuitJson.push({type:"pcb_fabrication_note_text",layer:layerRef,font:"tscircuit2024",font_size:fp_text.effects?.font?.size[0]??1,pcb_component_id,anchor_position:{x:fp_text.at[0],y:-fp_text.at[1]},anchor_alignment:"center",text:fp_text.text}):debug23("Unhandled layer for fp_text",fp_text.layer)}let refProp=properties.find(prop=>prop.key==="Reference"),valProp=properties.find(prop=>prop.key==="Value"),propFabTexts=[refProp,valProp].filter(p4=>p4&&!!p4.val);for(let propFab of propFabTexts){let at3=propFab.attributes.at;if(!at3)continue;let isFabLayer=propFab.attributes.layer?.toLowerCase()?.endsWith(".fab"),font_size=getSilkscreenFontSizeFromFpTexts(fp_texts);circuitJson.push({type:isFabLayer?"pcb_fabrication_note_text":"pcb_silkscreen_text",layer:"top",font:"tscircuit2024",font_size,pcb_component_id,anchor_position:{x:at3[0],y:-at3[1]},anchor_alignment:"center",text:propFab.val})}return circuitJson},parseKicadModToCircuitJson=async kicadMod=>{let kicadJson=parseKicadModToKicadJson(kicadMod);return await convertKicadJsonToTsCircuitSoup(kicadJson)};var dynamicallyLoadDependencyWithCdnBackup=async packageName=>{try{return(await import(packageName)).default}catch{console.log(`Failed to load ${packageName} locally, trying CDN fallback...`);try{let res2=await fetch(`https://cdn.jsdelivr.net/npm/${packageName}/+esm`);if(!res2.ok)throw new Error(`Failed to fetch ${packageName} from CDN: ${res2.statusText}`);let code=await res2.text(),blob=new Blob([code],{type:"application/javascript"}),url=URL.createObjectURL(blob);try{let{default:loadedModule}=await import(url);return loadedModule}finally{URL.revokeObjectURL(url)}}catch(cdnError){throw console.error(`CDN fallback for ${packageName} also failed:`,cdnError),cdnError}}};var KICAD_FOOTPRINT_CACHE_URL="https://kicad-mod-cache.tscircuit.com",ngspiceEngineCache=null,getPlatformConfig=()=>({partsEngine:jlcPartsEngine,spiceEngineMap:{ngspice:{simulate:async spice=>{if(!ngspiceEngineCache){let createNgspiceSpiceEngine=await dynamicallyLoadDependencyWithCdnBackup("@tscircuit/ngspice-spice-engine").catch(error=>{throw new Error("Could not load ngspice engine from local node_modules or CDN fallback.",{cause:error})});createNgspiceSpiceEngine&&(ngspiceEngineCache=await createNgspiceSpiceEngine())}if(!ngspiceEngineCache)throw new Error("Could not load ngspice engine from local node_modules or CDN fallback.");return ngspiceEngineCache.simulate(spice)}}},footprintLibraryMap:{kicad:async footprintName=>{let baseUrl=`${KICAD_FOOTPRINT_CACHE_URL}/${footprintName}`,circuitJsonUrl=`${baseUrl}.circuit.json`,raw=await(await fetch(circuitJsonUrl)).json(),filtered=Array.isArray(raw)?raw.filter(el2=>el2?.type==="pcb_silkscreen_text"?el2?.text==="REF**":!0):raw,wrlUrl=`${baseUrl}.wrl`;return{footprintCircuitJson:filtered,cadModel:{wrlUrl,modelUnitToMmScale:2.54}}}},footprintFileParserMap:{kicad_mod:{loadFromUrl:async url=>{let kicadContent=await fetch(url).then(res2=>res2.text()),kicadJson=await parseKicadModToCircuitJson(kicadContent);return{footprintCircuitJson:Array.isArray(kicadJson)?kicadJson:[kicadJson]}}}}});var tslib_es6_exports={};__export(tslib_es6_exports,{__addDisposableResource:()=>__addDisposableResource,__assign:()=>__assign,__asyncDelegator:()=>__asyncDelegator,__asyncGenerator:()=>__asyncGenerator,__asyncValues:()=>__asyncValues,__await:()=>__await,__awaiter:()=>__awaiter,__classPrivateFieldGet:()=>__classPrivateFieldGet,__classPrivateFieldIn:()=>__classPrivateFieldIn,__classPrivateFieldSet:()=>__classPrivateFieldSet,__createBinding:()=>__createBinding,__decorate:()=>__decorate,__disposeResources:()=>__disposeResources,__esDecorate:()=>__esDecorate,__exportStar:()=>__exportStar,__extends:()=>__extends,__generator:()=>__generator,__importDefault:()=>__importDefault,__importStar:()=>__importStar,__makeTemplateObject:()=>__makeTemplateObject,__metadata:()=>__metadata,__param:()=>__param,__propKey:()=>__propKey,__read:()=>__read,__rest:()=>__rest,__rewriteRelativeImportExtension:()=>__rewriteRelativeImportExtension,__runInitializers:()=>__runInitializers,__setFunctionName:()=>__setFunctionName,__spread:()=>__spread,__spreadArray:()=>__spreadArray,__spreadArrays:()=>__spreadArrays,__values:()=>__values,default:()=>tslib_es6_default});var extendStatics=function(d2,b3){return extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d3,b4){d3.__proto__=b4}||function(d3,b4){for(var p4 in b4)Object.prototype.hasOwnProperty.call(b4,p4)&&(d3[p4]=b4[p4])},extendStatics(d2,b3)};function __extends(d2,b3){if(typeof b3!="function"&&b3!==null)throw new TypeError("Class extends value "+String(b3)+" is not a constructor or null");extendStatics(d2,b3);function __(){this.constructor=d2}d2.prototype=b3===null?Object.create(b3):(__.prototype=b3.prototype,new __)}var __assign=function(){return __assign=Object.assign||function(t6){for(var s4,i3=1,n3=arguments.length;i3<n3;i3++){s4=arguments[i3];for(var p4 in s4)Object.prototype.hasOwnProperty.call(s4,p4)&&(t6[p4]=s4[p4])}return t6},__assign.apply(this,arguments)};function __rest(s4,e4){var t6={};for(var p4 in s4)Object.prototype.hasOwnProperty.call(s4,p4)&&e4.indexOf(p4)<0&&(t6[p4]=s4[p4]);if(s4!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i3=0,p4=Object.getOwnPropertySymbols(s4);i3<p4.length;i3++)e4.indexOf(p4[i3])<0&&Object.prototype.propertyIsEnumerable.call(s4,p4[i3])&&(t6[p4[i3]]=s4[p4[i3]]);return t6}function __decorate(decorators,target,key,desc){var c3=arguments.length,r4=c3<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d2;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r4=Reflect.decorate(decorators,target,key,desc);else for(var i3=decorators.length-1;i3>=0;i3--)(d2=decorators[i3])&&(r4=(c3<3?d2(r4):c3>3?d2(target,key,r4):d2(target,key))||r4);return c3>3&&r4&&Object.defineProperty(target,key,r4),r4}function __param(paramIndex,decorator){return function(target,key){decorator(target,key,paramIndex)}}function __esDecorate(ctor,descriptorIn,decorators,contextIn,initializers,extraInitializers){function accept(f2){if(f2!==void 0&&typeof f2!="function")throw new TypeError("Function expected");return f2}for(var kind=contextIn.kind,key=kind==="getter"?"get":kind==="setter"?"set":"value",target=!descriptorIn&&ctor?contextIn.static?ctor:ctor.prototype:null,descriptor=descriptorIn||(target?Object.getOwnPropertyDescriptor(target,contextIn.name):{}),_4,done=!1,i3=decorators.length-1;i3>=0;i3--){var context={};for(var p4 in contextIn)context[p4]=p4==="access"?{}:contextIn[p4];for(var p4 in contextIn.access)context.access[p4]=contextIn.access[p4];context.addInitializer=function(f2){if(done)throw new TypeError("Cannot add initializers after decoration has completed");extraInitializers.push(accept(f2||null))};var result=(0,decorators[i3])(kind==="accessor"?{get:descriptor.get,set:descriptor.set}:descriptor[key],context);if(kind==="accessor"){if(result===void 0)continue;if(result===null||typeof result!="object")throw new TypeError("Object expected");(_4=accept(result.get))&&(descriptor.get=_4),(_4=accept(result.set))&&(descriptor.set=_4),(_4=accept(result.init))&&initializers.unshift(_4)}else(_4=accept(result))&&(kind==="field"?initializers.unshift(_4):descriptor[key]=_4)}target&&Object.defineProperty(target,contextIn.name,descriptor),done=!0}function __runInitializers(thisArg,initializers,value){for(var useValue=arguments.length>2,i3=0;i3<initializers.length;i3++)value=useValue?initializers[i3].call(thisArg,value):initializers[i3].call(thisArg);return useValue?value:void 0}function __propKey(x3){return typeof x3=="symbol"?x3:"".concat(x3)}function __setFunctionName(f2,name,prefix){return typeof name=="symbol"&&(name=name.description?"[".concat(name.description,"]"):""),Object.defineProperty(f2,"name",{configurable:!0,value:prefix?"".concat(prefix," ",name):name})}function __metadata(metadataKey,metadataValue){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(metadataKey,metadataValue)}function __awaiter(thisArg,_arguments,P4,generator){function adopt(value){return value instanceof P4?value:new P4(function(resolve){resolve(value)})}return new(P4||(P4=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e4){reject(e4)}}function rejected(value){try{step(generator.throw(value))}catch(e4){reject(e4)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})}function __generator(thisArg,body){var _4={label:0,sent:function(){if(t6[0]&1)throw t6[1];return t6[1]},trys:[],ops:[]},f2,y3,t6,g4=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return g4.next=verb(0),g4.throw=verb(1),g4.return=verb(2),typeof Symbol=="function"&&(g4[Symbol.iterator]=function(){return this}),g4;function verb(n3){return function(v4){return step([n3,v4])}}function step(op2){if(f2)throw new TypeError("Generator is already executing.");for(;g4&&(g4=0,op2[0]&&(_4=0)),_4;)try{if(f2=1,y3&&(t6=op2[0]&2?y3.return:op2[0]?y3.throw||((t6=y3.return)&&t6.call(y3),0):y3.next)&&!(t6=t6.call(y3,op2[1])).done)return t6;switch(y3=0,t6&&(op2=[op2[0]&2,t6.value]),op2[0]){case 0:case 1:t6=op2;break;case 4:return _4.label++,{value:op2[1],done:!1};case 5:_4.label++,y3=op2[1],op2=[0];continue;case 7:op2=_4.ops.pop(),_4.trys.pop();continue;default:if(t6=_4.trys,!(t6=t6.length>0&&t6[t6.length-1])&&(op2[0]===6||op2[0]===2)){_4=0;continue}if(op2[0]===3&&(!t6||op2[1]>t6[0]&&op2[1]<t6[3])){_4.label=op2[1];break}if(op2[0]===6&&_4.label<t6[1]){_4.label=t6[1],t6=op2;break}if(t6&&_4.label<t6[2]){_4.label=t6[2],_4.ops.push(op2);break}t6[2]&&_4.ops.pop(),_4.trys.pop();continue}op2=body.call(thisArg,_4)}catch(e4){op2=[6,e4],y3=0}finally{f2=t6=0}if(op2[0]&5)throw op2[1];return{value:op2[0]?op2[1]:void 0,done:!0}}}var __createBinding=Object.create?(function(o3,m3,k4,k22){k22===void 0&&(k22=k4);var desc=Object.getOwnPropertyDescriptor(m3,k4);(!desc||("get"in desc?!m3.__esModule:desc.writable||desc.configurable))&&(desc={enumerable:!0,get:function(){return m3[k4]}}),Object.defineProperty(o3,k22,desc)}):(function(o3,m3,k4,k22){k22===void 0&&(k22=k4),o3[k22]=m3[k4]});function __exportStar(m3,o3){for(var p4 in m3)p4!=="default"&&!Object.prototype.hasOwnProperty.call(o3,p4)&&__createBinding(o3,m3,p4)}function __values(o3){var s4=typeof Symbol=="function"&&Symbol.iterator,m3=s4&&o3[s4],i3=0;if(m3)return m3.call(o3);if(o3&&typeof o3.length=="number")return{next:function(){return o3&&i3>=o3.length&&(o3=void 0),{value:o3&&o3[i3++],done:!o3}}};throw new TypeError(s4?"Object is not iterable.":"Symbol.iterator is not defined.")}function __read(o3,n3){var m3=typeof Symbol=="function"&&o3[Symbol.iterator];if(!m3)return o3;var i3=m3.call(o3),r4,ar2=[],e4;try{for(;(n3===void 0||n3-- >0)&&!(r4=i3.next()).done;)ar2.push(r4.value)}catch(error){e4={error}}finally{try{r4&&!r4.done&&(m3=i3.return)&&m3.call(i3)}finally{if(e4)throw e4.error}}return ar2}function __spread(){for(var ar2=[],i3=0;i3<arguments.length;i3++)ar2=ar2.concat(__read(arguments[i3]));return ar2}function __spreadArrays(){for(var s4=0,i3=0,il2=arguments.length;i3<il2;i3++)s4+=arguments[i3].length;for(var r4=Array(s4),k4=0,i3=0;i3<il2;i3++)for(var a3=arguments[i3],j3=0,jl2=a3.length;j3<jl2;j3++,k4++)r4[k4]=a3[j3];return r4}function __spreadArray(to2,from,pack2){if(pack2||arguments.length===2)for(var i3=0,l3=from.length,ar2;i3<l3;i3++)(ar2||!(i3 in from))&&(ar2||(ar2=Array.prototype.slice.call(from,0,i3)),ar2[i3]=from[i3]);return to2.concat(ar2||Array.prototype.slice.call(from))}function __await(v4){return this instanceof __await?(this.v=v4,this):new __await(v4)}function __asyncGenerator(thisArg,_arguments,generator){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var g4=generator.apply(thisArg,_arguments||[]),i3,q4=[];return i3=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),verb("next"),verb("throw"),verb("return",awaitReturn),i3[Symbol.asyncIterator]=function(){return this},i3;function awaitReturn(f2){return function(v4){return Promise.resolve(v4).then(f2,reject)}}function verb(n3,f2){g4[n3]&&(i3[n3]=function(v4){return new Promise(function(a3,b3){q4.push([n3,v4,a3,b3])>1||resume(n3,v4)})},f2&&(i3[n3]=f2(i3[n3])))}function resume(n3,v4){try{step(g4[n3](v4))}catch(e4){settle(q4[0][3],e4)}}function step(r4){r4.value instanceof __await?Promise.resolve(r4.value.v).then(fulfill,reject):settle(q4[0][2],r4)}function fulfill(value){resume("next",value)}function reject(value){resume("throw",value)}function settle(f2,v4){f2(v4),q4.shift(),q4.length&&resume(q4[0][0],q4[0][1])}}function __asyncDelegator(o3){var i3,p4;return i3={},verb("next"),verb("throw",function(e4){throw e4}),verb("return"),i3[Symbol.iterator]=function(){return this},i3;function verb(n3,f2){i3[n3]=o3[n3]?function(v4){return(p4=!p4)?{value:__await(o3[n3](v4)),done:!1}:f2?f2(v4):v4}:f2}}function __asyncValues(o3){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var m3=o3[Symbol.asyncIterator],i3;return m3?m3.call(o3):(o3=typeof __values=="function"?__values(o3):o3[Symbol.iterator](),i3={},verb("next"),verb("throw"),verb("return"),i3[Symbol.asyncIterator]=function(){return this},i3);function verb(n3){i3[n3]=o3[n3]&&function(v4){return new Promise(function(resolve,reject){v4=o3[n3](v4),settle(resolve,reject,v4.done,v4.value)})}}function settle(resolve,reject,d2,v4){Promise.resolve(v4).then(function(v5){resolve({value:v5,done:d2})},reject)}}function __makeTemplateObject(cooked,raw){return Object.defineProperty?Object.defineProperty(cooked,"raw",{value:raw}):cooked.raw=raw,cooked}var __setModuleDefault=Object.create?(function(o3,v4){Object.defineProperty(o3,"default",{enumerable:!0,value:v4})}):function(o3,v4){o3.default=v4},ownKeys=function(o3){return ownKeys=Object.getOwnPropertyNames||function(o4){var ar2=[];for(var k4 in o4)Object.prototype.hasOwnProperty.call(o4,k4)&&(ar2[ar2.length]=k4);return ar2},ownKeys(o3)};function __importStar(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null)for(var k4=ownKeys(mod),i3=0;i3<k4.length;i3++)k4[i3]!=="default"&&__createBinding(result,mod,k4[i3]);return __setModuleDefault(result,mod),result}function __importDefault(mod){return mod&&mod.__esModule?mod:{default:mod}}function __classPrivateFieldGet(receiver,state2,kind,f2){if(kind==="a"&&!f2)throw new TypeError("Private accessor was defined without a getter");if(typeof state2=="function"?receiver!==state2||!f2:!state2.has(receiver))throw new TypeError("Cannot read private member from an object whose class did not declare it");return kind==="m"?f2:kind==="a"?f2.call(receiver):f2?f2.value:state2.get(receiver)}function __classPrivateFieldSet(receiver,state2,value,kind,f2){if(kind==="m")throw new TypeError("Private method is not writable");if(kind==="a"&&!f2)throw new TypeError("Private accessor was defined without a setter");if(typeof state2=="function"?receiver!==state2||!f2:!state2.has(receiver))throw new TypeError("Cannot write private member to an object whose class did not declare it");return kind==="a"?f2.call(receiver,value):f2?f2.value=value:state2.set(receiver,value),value}function __classPrivateFieldIn(state2,receiver){if(receiver===null||typeof receiver!="object"&&typeof receiver!="function")throw new TypeError("Cannot use 'in' operator on non-object");return typeof state2=="function"?receiver===state2:state2.has(receiver)}function __addDisposableResource(env,value,async){if(value!=null){if(typeof value!="object"&&typeof value!="function")throw new TypeError("Object expected.");var dispose,inner;if(async){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");dispose=value[Symbol.asyncDispose]}if(dispose===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");dispose=value[Symbol.dispose],async&&(inner=dispose)}if(typeof dispose!="function")throw new TypeError("Object not disposable.");inner&&(dispose=function(){try{inner.call(this)}catch(e4){return Promise.reject(e4)}}),env.stack.push({value,dispose,async})}else async&&env.stack.push({async:!0});return value}var _SuppressedError=typeof SuppressedError=="function"?SuppressedError:function(error,suppressed,message){var e4=new Error(message);return e4.name="SuppressedError",e4.error=error,e4.suppressed=suppressed,e4};function __disposeResources(env){function fail(e4){env.error=env.hasError?new _SuppressedError(e4,env.error,"An error was suppressed during disposal."):e4,env.hasError=!0}var r4,s4=0;function next2(){for(;r4=env.stack.pop();)try{if(!r4.async&&s4===1)return s4=0,env.stack.push(r4),Promise.resolve().then(next2);if(r4.dispose){var result=r4.dispose.call(r4.value);if(r4.async)return s4|=2,Promise.resolve(result).then(next2,function(e4){return fail(e4),next2()})}else s4|=1}catch(e4){fail(e4)}if(s4===1)return env.hasError?Promise.reject(env.error):Promise.resolve();if(env.hasError)throw env.error}return next2()}function __rewriteRelativeImportExtension(path,preserveJsx){return typeof path=="string"&&/^\.\.?\//.test(path)?path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(m3,tsx,d2,ext,cm2){return tsx?preserveJsx?".jsx":".js":d2&&(!ext||!cm2)?m3:d2+ext+"."+cm2.toLowerCase()+"js"}):path}var tslib_es6_default={__extends,__assign,__rest,__decorate,__param,__esDecorate,__runInitializers,__propKey,__setFunctionName,__metadata,__awaiter,__generator,__createBinding,__exportStar,__values,__read,__spread,__spreadArrays,__spreadArray,__await,__asyncGenerator,__asyncDelegator,__asyncValues,__makeTemplateObject,__importStar,__importDefault,__classPrivateFieldGet,__classPrivateFieldSet,__classPrivateFieldIn,__addDisposableResource,__disposeResources,__rewriteRelativeImportExtension};var import_debug21=__toESM(require_browser(),1),debug12=(0,import_debug21.default)("tsci:eval:execution-context");function createExecutionContext(webWorkerConfiguration,opts={}){globalThis.React=React;let basePlatform=opts.platform||getPlatformConfig(),platform=opts.projectConfig?{...basePlatform,...opts.projectConfig}:basePlatform;platform.partsEngineDisabled&&(platform.partsEngine=void 0);let circuit=new RootCircuit({platform});opts.name&&(circuit.name=opts.name),opts.debugNamespace&&circuit.enableDebug(opts.debugNamespace);let logs=[];return{fsMap:{},entrypoint:"",logger:{info:message=>{logs.push({msg:message})},getLogs:()=>logs,stringifyLogs:()=>logs.map(log=>log.msg).join(`
604
604
  `)},preSuppliedImports:{"@tscircuit/core":dist_exports5,tscircuit:dist_exports5,"@tscircuit/math-utils":dist_exports2,react:React,"react/jsx-runtime":ReactJsxRuntime,debug:import_debug21.default,tslib:tslib_es6_exports,"@tscircuit/props":{}},circuit,tsConfig:null,importStack:[],currentlyImporting:new Set,...webWorkerConfiguration}}function normalizeFilePath(filePath){let normFilePath=filePath;return normFilePath=normFilePath.replace(/\\/g,"/"),normFilePath=normFilePath.trim(),normFilePath.startsWith("./")&&(normFilePath=normFilePath.slice(2)),normFilePath.startsWith("/")&&(normFilePath=normFilePath.slice(1)),normFilePath}function normalizeFsMap(fsMap){let normalizedFsMap={};for(let[fsPath,fileContent]of Object.entries(fsMap))normalizedFsMap[normalizeFilePath(fsPath)]=fileContent;return normalizedFsMap}function dirname(path){if(!path)return".";let cleanPath=path.replace(/\\/g,"/").replace(/\/+$/,"");return cleanPath.indexOf("/")===-1?".":cleanPath.substring(0,cleanPath.lastIndexOf("/"))||"/"}function resolveRelativePath(importPath,cwd){if(importPath.startsWith("../")){let parentDir=dirname(cwd);return resolveRelativePath(importPath.slice(3),parentDir)}return importPath.startsWith("./")?resolveRelativePath(importPath.slice(2),cwd):importPath.startsWith("/")?importPath.slice(1):`${cwd}/${importPath}`}function getTsConfig(fsMapOrAllFilePaths){if(Array.isArray(fsMapOrAllFilePaths))return null;let tsconfigContent=fsMapOrAllFilePaths["tsconfig.json"];if(!tsconfigContent)return null;try{let sanitizedContent=tsconfigContent.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g,"");return JSON.parse(sanitizedContent)}catch(e4){throw new Error(`Failed to parse tsconfig.json: ${e4.message}`)}}function resolveWithTsconfigPaths(opts){let{importPath,normalizedFilePathMap,extensions,tsConfig,tsconfigDir}=opts,paths=tsConfig?.compilerOptions?.paths;if(!paths)return null;let baseUrl=tsConfig?.compilerOptions?.baseUrl||".",tryResolveCandidate=candidate=>{let normalizedCandidate=normalizeFilePath(candidate);if(normalizedFilePathMap.has(normalizedCandidate))return normalizedFilePathMap.get(normalizedCandidate);for(let ext of extensions){let withExt=`${normalizedCandidate}.${ext}`;if(normalizedFilePathMap.has(withExt))return normalizedFilePathMap.get(withExt)}return null};for(let[alias,targets]of Object.entries(paths))if(alias.includes("*")){let[prefix,suffix]=alias.split("*");if(!importPath.startsWith(prefix)||!importPath.endsWith(suffix||""))continue;let starMatch=importPath.slice(prefix.length,importPath.length-(suffix?suffix.length:0));for(let target of targets){let replaced=target.replace("*",starMatch),candidate=baseUrl&&!replaced.startsWith("./")&&!replaced.startsWith("/")?`${baseUrl}/${replaced}`:replaced,resolved=tryResolveCandidate(candidate);if(resolved)return resolved}}else{if(importPath!==alias)continue;for(let target of targets){let candidate=baseUrl&&!target.startsWith("./")&&!target.startsWith("/")?`${baseUrl}/${target}`:target,resolved=tryResolveCandidate(candidate);if(resolved)return resolved}}let resolvedPathFromBaseUrl=resolveWithBaseUrl({importPath,normalizedFilePathMap,extensions,tsConfig,tsconfigDir});return resolvedPathFromBaseUrl||null}function resolveWithBaseUrl(opts){let{importPath,normalizedFilePathMap,extensions,tsConfig,tsconfigDir}=opts,baseUrl=tsConfig?.compilerOptions?.baseUrl;if(!baseUrl)return null;let filePathToResolve=`${tsconfigDir||"."}/${baseUrl}/${importPath}`;filePathToResolve=filePathToResolve.replace(/\/+/g,"/"),filePathToResolve=filePathToResolve.replace(/\/\.\//g,"/");let normalizedFilePath=normalizeFilePath(filePathToResolve);if(normalizedFilePathMap.has(normalizedFilePath))return normalizedFilePathMap.get(normalizedFilePath);for(let ext of extensions){let withExt=`${normalizedFilePath}.${ext}`;if(normalizedFilePathMap.has(withExt))return normalizedFilePathMap.get(withExt)}return null}function matchesTsconfigPathPattern(importPath,tsConfig){let paths=tsConfig?.compilerOptions?.paths;if(!paths)return!1;for(let[alias]of Object.entries(paths))if(alias.includes("*")){let[prefix,suffix]=alias.split("*");if(importPath.startsWith(prefix)&&importPath.endsWith(suffix||""))return!0}else if(importPath===alias)return!0;return!1}var FILE_EXTENSIONS=["tsx","ts","json","js","jsx","obj","gltf","glb","stl","step","stp"],resolveFilePath=(unknownFilePath,fsMapOrAllFilePaths,cwd,opts={})=>{let tsConfig=opts.tsConfig??null,isRelativeImport=unknownFilePath.startsWith("./")||unknownFilePath.startsWith("../"),hasBaseUrl=!!tsConfig?.compilerOptions?.baseUrl,resolvedPath=cwd&&(isRelativeImport||!hasBaseUrl)?resolveRelativePath(unknownFilePath,cwd):unknownFilePath,filePaths=new Set(Array.isArray(fsMapOrAllFilePaths)?fsMapOrAllFilePaths:Object.keys(fsMapOrAllFilePaths));if(filePaths.has(resolvedPath))return resolvedPath;let normalizedFilePathMap=new Map;for(let filePath of filePaths)normalizedFilePathMap.set(normalizeFilePath(filePath),filePath);let normalizedResolvedPath=normalizeFilePath(resolvedPath);if(isRelativeImport||!hasBaseUrl){if(normalizedFilePathMap.has(normalizedResolvedPath))return normalizedFilePathMap.get(normalizedResolvedPath);for(let ext of FILE_EXTENSIONS){let possibleFilePath=`${normalizedResolvedPath}.${ext}`;if(normalizedFilePathMap.has(possibleFilePath))return normalizedFilePathMap.get(possibleFilePath)}}if(!isRelativeImport){let resolvedPathFromPaths=resolveWithTsconfigPaths({importPath:unknownFilePath,normalizedFilePathMap,extensions:FILE_EXTENSIONS,tsConfig,tsconfigDir:opts.tsconfigDir});if(resolvedPathFromPaths)return resolvedPathFromPaths;let resolvedPathFromBaseUrl=resolveWithBaseUrl({importPath:unknownFilePath,normalizedFilePathMap,extensions:FILE_EXTENSIONS,tsConfig,tsconfigDir:opts.tsconfigDir});if(resolvedPathFromBaseUrl)return resolvedPathFromBaseUrl}if(!isRelativeImport&&!hasBaseUrl){let normalizedUnknownFilePath=normalizeFilePath(unknownFilePath);if(normalizedFilePathMap.has(normalizedUnknownFilePath))return normalizedFilePathMap.get(normalizedUnknownFilePath);for(let ext of FILE_EXTENSIONS){let possibleFilePath=`${normalizedUnknownFilePath}.${ext}`;if(normalizedFilePathMap.has(possibleFilePath))return normalizedFilePathMap.get(possibleFilePath)}}return null},resolveFilePathOrThrow=(unknownFilePath,fsMapOrAllFilePaths,cwd,opts={})=>{let resolvedFilePath=resolveFilePath(unknownFilePath,fsMapOrAllFilePaths,cwd,opts);if(!resolvedFilePath)throw new Error(`File not found "${unknownFilePath}", available paths: