@tscircuit/eval 0.0.459 → 0.0.460
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/blob-url.js +1 -1
- package/dist/eval/index.js +4 -1
- package/dist/lib/index.js +4 -1
- package/dist/webworker/entrypoint.js +1 -1
- package/package.json +1 -1
|
@@ -250,7 +250,7 @@ ${o.stack}`),i.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect
|
|
|
250
250
|
${r}`)}catch(s){oa(`Failed to convert circuit JSON to SPICE: ${s}`);return}for(let s of n){let a=s._parsedProps.spiceEngine??"spicey",c=i[a];if(!c)throw new Error(`SPICE engine "${a}" not found in platform config. Available engines: ${JSON.stringify(Object.keys(i).filter(u=>u!=="spicey"))}`);let l=`spice-simulation-${a}-${s.source_component_id}`;oa(`Queueing simulation for spice engine: ${a} (id: ${l})`),e._queueAsyncEffect(l,async()=>{try{oa(`Running simulation with engine: ${a}`);let u=await c.simulate(r);oa(`Simulation completed, received ${u.simulationResultCircuitJson.length} elements`);let h=t.db.simulation_experiment.list()[0];if(!h){oa("No simulation experiment found, skipping result insertion");return}for(let d of u.simulationResultCircuitJson){d.type==="simulation_transient_voltage_graph"&&(d.simulation_experiment_id=h.simulation_experiment_id);let _=d.type;_&&t.db[_]?(t.db[_].insert(d),oa(`Inserted ${_} into database`)):(oa(`Warning: Unknown element type ${_}, adding to raw db`),t.db._addElement(d))}e._markDirty("SimulationSpiceEngineRender")}catch(u){oa(`Simulation failed for engine ${a}: ${u}`);let h=t.db.simulation_experiment.list()[0];t.db.simulation_unknown_experiment_error.insert({simulation_experiment_id:h?.simulation_experiment_id,error_type:"simulation_unknown_experiment_error",message:u instanceof Error?u.message:String(u)})}})}}function iTt(e){if(e.root?.pcbDisabled||!e.pcb_group_id)return;let t=e._parsedProps?.pcbPositionAnchor;if(!t)return;let n=e._getGlobalPcbPositionBeforeLayout(),{pcbX:i,pcbY:o}=e._parsedProps;if(i===void 0&&o===void 0)return;let{db:r}=e.root,s=r.pcb_group.get(e.pcb_group_id);if(!s)return;let a=s.width,c=s.height,{center:l}=s;if(s.outline&&s.outline.length>0){let g=es(s.outline);g&&(a=g.maxX-g.minX,c=g.maxY-g.minY)}if(!a||!c)return;let u={left:l.x-a/2,right:l.x+a/2,top:l.y+c/2,bottom:l.y-c/2},h={...l},d=null;if(new Set(["center","top_left","top_center","top_right","center_left","center_right","bottom_left","bottom_center","bottom_right"]).has(t))switch(t){case"center":d=h;break;case"top_left":d={x:u.left,y:u.top};break;case"top_center":d={x:h.x,y:u.top};break;case"top_right":d={x:u.right,y:u.top};break;case"center_left":d={x:u.left,y:h.y};break;case"center_right":d={x:u.right,y:h.y};break;case"bottom_left":d={x:u.left,y:u.bottom};break;case"bottom_center":d={x:h.x,y:u.bottom};break;case"bottom_right":d={x:u.right,y:u.bottom};break}if(!d)return;let y={...h};n.x!==void 0&&(y.x+=n.x-d.x),n.y!==void 0&&(y.y+=n.y-d.y),(Math.abs(y.x-h.x)>1e-6||Math.abs(y.y-h.y)>1e-6)&&(e._repositionOnPcb(y),r.pcb_group.update(e.pcb_group_id,{center:y})),r.pcb_group.update(e.pcb_group_id,{anchor_position:n,anchor_alignment:t})}var Ic=class extends On{constructor(){super(...arguments);P(this,"pcb_group_id",null);P(this,"schematic_group_id",null);P(this,"subcircuit_id",null);P(this,"_hasStartedAsyncAutorouting",!1);P(this,"_asyncAutoroutingResult",null);P(this,"unnamedElementCounter",{})}get config(){return{zodProps:lz,componentName:"Group"}}doInitialSourceGroupRender(){let{db:t}=this.root,n=typeof this._parsedProps.name=="string"&&this._parsedProps.name.length>0,i=t.source_group.insert({name:this.name,is_subcircuit:this.isSubcircuit,was_automatically_named:!n});this.source_group_id=i.source_group_id,this.isSubcircuit&&(this.subcircuit_id=`subcircuit_${i.source_group_id}`,t.source_group.update(i.source_group_id,{subcircuit_id:this.subcircuit_id}))}doInitialSourceRender(){let{db:t}=this.root;for(let n of this.children)t.source_component.update(n.source_component_id,{source_group_id:this.source_group_id})}doInitialSourceParentAttachment(){let{db:t}=this.root,n=this.parent?.getGroup?.();if(n?.source_group_id&&t.source_group.update(this.source_group_id,{parent_source_group_id:n.source_group_id}),!this.isSubcircuit)return;let i=this.parent?.getSubcircuit?.()?.subcircuit_id;i&&t.source_group.update(this.source_group_id,{parent_subcircuit_id:i})}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=n,o=i.outline&&i.outline.length>0,r=o?i.outline.map(a=>({x:Y.parse(a.x),y:Y.parse(a.y)})):void 0,s=t.pcb_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id??this.getSubcircuit()?.subcircuit_id,name:this.name,center:this._getGlobalPcbPositionBeforeLayout(),...o?{outline:r}:{width:0,height:0},pcb_component_ids:[],source_group_id:this.source_group_id,autorouter_configuration:n.autorouter?{trace_clearance:n.autorouter.traceClearance}:void 0});this.pcb_group_id=s.pcb_group_id;for(let a of this.children)t.pcb_component.update(a.pcb_component_id,{pcb_group_id:s.pcb_group_id})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,n=this._parsedProps,i=n.outline&&n.outline.length>0;if(this.pcb_group_id){let o=this._parsedProps.pcbX!==void 0||this._parsedProps.pcbY!==void 0;if(i){let h=n.outline.map(x=>({x:Y.parse(x.x),y:Y.parse(x.y)})),d=es(h);if(!d)return;let _=(d.minX+d.maxX)/2,y=(d.minY+d.maxY)/2,g=o?t.pcb_group.get(this.pcb_group_id)?.center??{x:_,y}:{x:_,y};t.pcb_group.update(this.pcb_group_id,{center:g});return}let r=Lx(this.children),s=r.width,a=r.height,c=(r.minX+r.maxX)/2,l=(r.minY+r.maxY)/2;if(this.isSubcircuit){let{padLeft:h,padRight:d,padTop:_,padBottom:y}=this._resolvePcbPadding();s+=h+d,a+=_+y,c+=(d-h)/2,l+=(_-y)/2}let u=o?t.pcb_group.get(this.pcb_group_id)?.center??{x:c,y:l}:{x:c,y:l};t.pcb_group.update(this.pcb_group_id,{width:Number(n.width??s),height:Number(n.height??a),center:u})}}getNextAvailableName(t){var n,i;return(n=this.unnamedElementCounter)[i=t.lowercaseComponentName]??(n[i]=1),`unnamed_${t.lowercaseComponentName}${this.unnamedElementCounter[t.lowercaseComponentName]++}`}_resolvePcbPadding(){let t=this._parsedProps,n=t.pcbLayout,i=h=>{let d=n?.[h],_=t[h];if(typeof d=="number")return d;if(typeof _=="number")return _},o=i("padding")??0,r=i("paddingX"),s=i("paddingY"),a=i("paddingLeft")??r??o,c=i("paddingRight")??r??o,l=i("paddingTop")??s??o,u=i("paddingBottom")??s??o;return{padLeft:a,padRight:c,padTop:l,padBottom:u}}doInitialCreateTraceHintsFromProps(){let{_parsedProps:t}=this,{db:n}=this.root,i=t;if(!this.isSubcircuit)return;let o=i.manualEdits?.manual_trace_hints;if(o)for(let r of o)this.add(new z4({for:r.pcb_port_selector,offsets:r.offsets}))}doInitialSourceAddConnectivityMapKey(){gIt(this)}_areChildSubcircuitsRouted(){let t=this.selectAll("group").filter(n=>n.isSubcircuit);for(let n of t)if(n._shouldRouteAsync()&&!n._asyncAutoroutingResult)return!1;return!0}_shouldRouteAsync(){let t=this._getAutorouterConfig();return t.groupMode==="sequential-trace"?!1:!!(t.local&&t.groupMode==="subcircuit"||!t.local)}_hasTracesToRoute(){let t=(0,zh.default)("tscircuit:core:_hasTracesToRoute"),n=this.selectAll("trace");return t(`[${this.getString()}] has ${n.length} traces to route`),n.length>0}async _runEffectMakeHttpAutoroutingRequest(){let{db:t}=this.root,n=(0,zh.default)("tscircuit:core:_runEffectMakeHttpAutoroutingRequest"),i=this._parsedProps,o=this._getAutorouterConfig(),r=o.serverUrl,s=o.serverMode,a=(u,h)=>(n("fetching",u),h.headers&&(h.headers["Tscircuit-Core-Version"]=this.root?.getCoreVersion()),fetch(u,h)),c=this.root.db.toArray().filter(u=>u.type.startsWith("source_")||u.type.startsWith("pcb_"));if(s==="solve-endpoint"){if(this.props.autorouter?.inputFormat==="simplified"){let{autorouting_result:h}=await a(`${r}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_simple_route_json:E4({db:t,minTraceWidth:this.props.autorouter?.minTraceWidth??.15,subcircuit_id:this.subcircuit_id}).simpleRouteJson,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(d=>d.json());this._asyncAutoroutingResult=h,this._markDirty("PcbTraceRender");return}let{autorouting_result:u}=await a(`${r}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_circuit_json:c,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(h=>h.json());this._asyncAutoroutingResult=u,this._markDirty("PcbTraceRender");return}let{autorouting_job:l}=await a(`${r}/autorouting/jobs/create`,{method:"POST",body:JSON.stringify({input_circuit_json:c,provider:"freerouting",autostart:!0,display_name:this.root?.name,subcircuit_id:this.subcircuit_id,server_cache_enabled:o.serverCacheEnabled}),headers:{"Content-Type":"application/json"}}).then(u=>u.json());for(;;){let{autorouting_job:u}=await a(`${r}/autorouting/jobs/get`,{method:"POST",body:JSON.stringify({autorouting_job_id:l.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(h=>h.json());if(u.is_finished){let{autorouting_job_output:h}=await a(`${r}/autorouting/jobs/get_output`,{method:"POST",body:JSON.stringify({autorouting_job_id:l.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(d=>d.json());this._asyncAutoroutingResult={output_pcb_traces:h.output_pcb_traces},this._markDirty("PcbTraceRender");break}if(u.has_error){let h=new Im(`Autorouting job failed: ${JSON.stringify(u.error)}`);throw t.pcb_autorouting_error.insert({pcb_error_id:l.autorouting_job_id,error_type:"pcb_autorouting_error",message:h.message}),h}await new Promise(h=>setTimeout(h,100))}}async _runLocalAutorouting(){let{db:t}=this.root,n=this._parsedProps,i=(0,zh.default)("tscircuit:core:_runLocalAutorouting");i(`[${this.getString()}] starting local autorouting`);let o=this._getAutorouterConfig(),r=this._isLaserPrefabAutorouter(o),{simpleRouteJson:s}=E4({db:t,minTraceWidth:this.props.autorouter?.minTraceWidth??.15,subcircuit_id:this.subcircuit_id});if(i.enabled&&global.debugOutputArray?.push({name:`simpleroutejson-${this.props.name}.json`,obj:s}),i.enabled){let l=Rf(s);l.title=`autorouting-${this.props.name}`,global.debugGraphics?.push(l)}this.root?.emit("autorouting:start",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),simpleRouteJson:s});let a;o.algorithmFn?a=await o.algorithmFn(s):a=new lIt(s,{capacityDepth:this.props.autorouter?.capacityDepth,targetMinCapacity:this.props.autorouter?.targetMinCapacity,useAssignableViaSolver:r});let c=new Promise((l,u)=>{a.on("complete",h=>{i(`[${this.getString()}] local autorouting complete`),l(h.traces)}),a.on("error",h=>{i(`[${this.getString()}] local autorouting error: ${h.error.message}`),u(h.error)})});a.on("progress",l=>{this.root?.emit("autorouting:progress",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),...l})}),a.start();try{let l=await c;this._asyncAutoroutingResult={output_pcb_traces:l},this._markDirty("PcbTraceRender")}catch(l){let{db:u}=this.root;throw u.pcb_autorouting_error.insert({pcb_error_id:`pcb_autorouter_error_subcircuit_${this.subcircuit_id}`,error_type:"pcb_autorouting_error",message:l instanceof Error?l.message:String(l)}),this.root?.emit("autorouting:error",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),error:{message:l instanceof Error?l.message:String(l)},simpleRouteJson:s}),l}finally{a.stop()}}_startAsyncAutorouting(){this._hasStartedAsyncAutorouting||(this._hasStartedAsyncAutorouting=!0,this._getAutorouterConfig().local?this._queueAsyncEffect("capacity-mesh-autorouting",async()=>this._runLocalAutorouting()):this._queueAsyncEffect("make-http-autorouting-request",async()=>this._runEffectMakeHttpAutoroutingRequest()))}doInitialPcbTraceRender(){let t=(0,zh.default)("tscircuit:core:doInitialPcbTraceRender");if(this.isSubcircuit&&!this.root?.pcbDisabled&&!this.getInheritedProperty("routingDisabled")&&!this._shouldUseTraceByTraceRouting()){if(!this._areChildSubcircuitsRouted()){t(`[${this.getString()}] child subcircuits are not routed, skipping async autorouting until subcircuits routed`);return}t(`[${this.getString()}] no child subcircuits to wait for, initiating async routing`),this._hasTracesToRoute()&&this._startAsyncAutorouting()}}doInitialSchematicTraceRender(){tTt(this)}updatePcbTraceRender(){let t=(0,zh.default)("tscircuit:core:updatePcbTraceRender");if(t(`[${this.getString()}] updating...`),!this.isSubcircuit)return;if(this._shouldRouteAsync()&&this._hasTracesToRoute()&&!this._hasStartedAsyncAutorouting){this._areChildSubcircuitsRouted()&&(t(`[${this.getString()}] child subcircuits are now routed, starting async autorouting`),this._startAsyncAutorouting());return}if(!this._asyncAutoroutingResult||this._shouldUseTraceByTraceRouting())return;let{db:n}=this.root;if(this._asyncAutoroutingResult.output_simple_route_json){t(`[${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){t(`[${this.getString()}] updating PCB traces from ${this._asyncAutoroutingResult.output_pcb_traces.length} traces`),this._updatePcbTraceRenderFromPcbTraces();return}}_updatePcbTraceRenderFromSimpleRouteJson(){let{db:t}=this.root,{traces:n}=this._asyncAutoroutingResult.output_simple_route_json;if(n)for(let i of n){let o=t.pcb_trace.insert({subcircuit_id:this.subcircuit_id,route:i.route})}}_updatePcbTraceRenderFromPcbTraces(){let{output_pcb_traces:t}=this._asyncAutoroutingResult;if(!t)return;let{db:n}=this.root;for(let i of t)if(i.type==="pcb_trace"){if(i.subcircuit_id=this.subcircuit_id,i.connection_name){let o=i.connection_name;i.source_trace_id=o}n.pcb_trace.insert(i)}for(let i of t)if(i.type!=="pcb_via"&&i.type==="pcb_trace")for(let o of i.route)o.route_type==="via"&&n.pcb_via.insert({pcb_trace_id:i.pcb_trace_id,x:o.x,y:o.y,hole_diameter:.3,outer_diameter:.6,layers:[o.from_layer,o.to_layer],from_layer:o.from_layer,to_layer:o.to_layer})}doInitialSchematicComponentRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.schematic_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id,name:this.name,center:this._getGlobalSchematicPositionBeforeLayout(),width:0,height:0,schematic_component_ids:[],source_group_id:this.source_group_id});this.schematic_group_id=i.schematic_group_id;for(let o of this.children)o.schematic_component_id&&t.schematic_component.update(o.schematic_component_id,{schematic_group_id:i.schematic_group_id})}_getSchematicLayoutMode(){let t=this._parsedProps;if(t.schLayout?.layoutMode==="none"||t.schLayout?.layoutMode==="relative")return"relative";if(t.schLayout?.matchAdapt)return"match-adapt";if(t.schLayout?.flex)return"flex";if(t.schLayout?.grid)return"grid";if(t.schMatchAdapt)return"match-adapt";if(t.schFlex)return"flex";if(t.schGrid)return"grid";if(t.matchAdapt)return"match-adapt";if(t.flex)return"flex";if(t.grid)return"grid";if(t.relative||t.schRelative)return"relative";let n=this.children.some(o=>{let r=o._parsedProps;return r?.schX!==void 0||r?.schY!==void 0}),i=(t.manualEdits?.schematic_placements?.length??0)>0;return!n&&!i?"match-adapt":"relative"}doInitialSchematicLayout(){let t=this._getSchematicLayoutMode();t==="match-adapt"&&this._doInitialSchematicLayoutMatchpack(),t==="grid"&&this._doInitialSchematicLayoutGrid(),t==="flex"&&this._doInitialSchematicLayoutFlex(),this._insertSchematicBorder()}_doInitialSchematicLayoutMatchAdapt(){mIt(this)}_doInitialSchematicLayoutMatchpack(){yIt(this)}_doInitialSchematicLayoutGrid(){bIt(this)}_doInitialSchematicLayoutFlex(){xIt(this)}_getPcbLayoutMode(){let t=this._parsedProps;if(t.pcbRelative)return"none";if(t.pcbLayout?.matchAdapt)return"match-adapt";if(t.pcbLayout?.flex)return"flex";if(t.pcbLayout?.grid)return"grid";if(t.pcbLayout?.pack)return"pack";if(t.pcbFlex)return"flex";if(t.pcbGrid)return"grid";if(t.pcbPack||t.pack)return"pack";if(t.matchAdapt)return"match-adapt";if(t.flex)return"flex";if(t.grid)return"grid";let n=t.pcbX!==void 0||t.pcbY!==void 0,i=(t.manualEdits?.pcb_placements?.length??0)>0,o=this.children.reduce((r,s)=>{if(!s.pcb_component_id&&!s.pcb_group_id)return r;let a=s._parsedProps,c=a?.pcbX!==void 0||a?.pcbY!==void 0;return r+(c?0:1)},0);return!n&&!i&&o>1?"pack":"none"}doInitialPcbLayout(){let t=this._getPcbLayoutMode();t==="grid"?this._doInitialPcbLayoutGrid():t==="pack"?this._doInitialPcbLayoutPack():t==="flex"&&this._doInitialPcbLayoutFlex()}_doInitialPcbLayoutGrid(){vIt(this)}_doInitialPcbLayoutPack(){zIt(this)}_doInitialPcbLayoutFlex(){DIt(this)}_insertSchematicBorder(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,n=this._parsedProps;if(!n.border)return;let i=typeof n.schWidth=="number"?n.schWidth:void 0,o=typeof n.schHeight=="number"?n.schHeight:void 0,r=typeof n.schPadding=="number"?n.schPadding:0,s=typeof n.schPaddingLeft=="number"?n.schPaddingLeft:r,a=typeof n.schPaddingRight=="number"?n.schPaddingRight:r,c=typeof n.schPaddingTop=="number"?n.schPaddingTop:r,l=typeof n.schPaddingBottom=="number"?n.schPaddingBottom:r,u=this.schematic_group_id?t.schematic_group.get(this.schematic_group_id):null;if(u&&(i===void 0&&typeof u.width=="number"&&(i=u.width),o===void 0&&typeof u.height=="number"&&(o=u.height)),i===void 0||o===void 0)return;let h=u?.center??this._getGlobalSchematicPositionBeforeLayout(),d=h.x-i/2-s,_=h.y-o/2-l,y=i+s+a,g=o+c+l;t.schematic_box.insert({width:y,height:g,x:d,y:_,is_dashed:n.border?.dashed??!1})}_determineSideFromPosition(t,n){if(!t.center||!n.center)return"left";let i=t.center.x-n.center.x,o=t.center.y-n.center.y;return Math.abs(i)>Math.abs(o)?i>0?"right":"left":o>0?"bottom":"top"}_calculateSchematicBounds(t){if(t.length===0)return{minX:0,maxX:0,minY:0,maxY:0};let n=1/0,i=-1/0,o=1/0,r=-1/0;for(let a of t)n=Math.min(n,a.centerX),i=Math.max(i,a.centerX),o=Math.min(o,a.centerY),r=Math.max(r,a.centerY);let s=2;return{minX:n-s,maxX:i+s,minY:o-s,maxY:r+s}}_getAutorouterConfig(){let t=this._parsedProps.autorouter||this.getInheritedProperty("autorouter");return kIt(t)}_isLaserPrefabAutorouter(t=this._getAutorouterConfig()){let n=this.props.autorouter,i=o=>o?.replace(/-/g,"_")??o;return t.preset==="laser_prefab"?!0:typeof n=="string"?i(n)==="laser_prefab":typeof n=="object"&&n?i(n.preset)==="laser_prefab":!1}_getSubcircuitLayerCount(){let t=this.getInheritedProperty("layers");return typeof t=="number"?t:2}_shouldUseTraceByTraceRouting(){return this._getAutorouterConfig().groupMode==="sequential-trace"}doInitialPcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db:t}=this.root;if(this.isSubcircuit){let n=new Map;for(let i of this.children)if(!i.isSubcircuit&&i._parsedProps.name){let o=n.get(i._parsedProps.name)||[];o.push(i),n.set(i._parsedProps.name,o)}for(let[i,o]of n.entries())o.length>1&&t.pcb_trace_error.insert({error_type:"pcb_trace_error",message:`Multiple components found with name "${i}" in subcircuit "${this.name||"unnamed"}". Component names must be unique within a subcircuit.`,source_trace_id:"",pcb_trace_id:"",pcb_component_ids:o.map(r=>r.pcb_component_id).filter(Boolean),pcb_port_ids:[]})}}doInitialSchematicReplaceNetLabelsWithSymbols(){if(this.root?.schematicDisabled||!this.isSubcircuit)return;let{db:t}=this.root,n=t;for(let i of n.schematic_net_label.list()){let o=n.source_net.get(i.source_net_id),r=i.text||o?.name||"";if(i.anchor_side==="top"&&/^gnd/i.test(r)){n.schematic_net_label.update(i.schematic_net_label_id,{symbol_name:"rail_down"});continue}i.anchor_side==="bottom"&&/^v/i.test(r)&&n.schematic_net_label.update(i.schematic_net_label_id,{symbol_name:"rail_up"})}}doInitialSimulationSpiceEngineRender(){nTt(this)}doInitialPcbComponentAnchorAlignment(){iTt(this)}updatePcbComponentAnchorAlignment(){this.doInitialPcbComponentAnchorAlignment()}_getMinimumFlexContainerSize(){return super._getMinimumFlexContainerSize()}_repositionOnPcb(t){return super._repositionOnPcb(t)}},oTt=.01,pH=(e,t,n)=>{let i=e/2,o=t/2,r=Math.min(n,i,o);if(r<oTt)return[{x:-i,y:-o},{x:i,y:-o},{x:i,y:o},{x:-i,y:o}];let a=Math.max(1,Math.ceil(Math.PI/2*r/.1)),c=Math.PI/2/a,l=[];l.push({x:-i+r,y:-o}),l.push({x:i-r,y:-o});for(let u=1;u<=a;u++){let h=-Math.PI/2+u*c;l.push({x:i-r+r*Math.cos(h),y:-o+r+r*Math.sin(h)})}l.push({x:i,y:o-r});for(let u=1;u<=a;u++){let h=0+u*c;l.push({x:i-r+r*Math.cos(h),y:o-r+r*Math.sin(h)})}l.push({x:-i+r,y:o});for(let u=1;u<=a;u++){let h=Math.PI/2+u*c;l.push({x:-i+r+r*Math.cos(h),y:o-r+r*Math.sin(h)})}l.push({x:-i,y:-o+r});for(let u=1;u<=a;u++){let h=Math.PI+u*c;l.push({x:-i+r+r*Math.cos(h),y:-o+r+r*Math.sin(h)})}return l},XH=class extends Ic{constructor(){super(...arguments);P(this,"pcb_board_id",null);P(this,"source_board_id",null);P(this,"_drcChecksComplete",!1);P(this,"_connectedSchematicPortPairs",new Set)}get isSubcircuit(){return!0}get isGroup(){return!0}get config(){return{componentName:"Board",zodProps:kI}}get boardThickness(){let{_parsedProps:t}=this;return t.thickness??1.4}get allLayers(){return(this._parsedProps.layers??2)===4?["top","bottom","inner1","inner2"]:["top","bottom"]}_getSubcircuitLayerCount(){return this._parsedProps.layers??2}doInitialPcbBoardAutoSize(){if(this.root?.pcbDisabled||!this.pcb_board_id)return;let{db:t}=this.root,{_parsedProps:n}=this;if(n.width&&n.height||n.outline)return;let i=1/0,o=1/0,r=-1/0,s=-1/0,a=LH(t,this.subcircuit_id),c=new Set([this.subcircuit_id,...a]),l=t.pcb_component.list().filter(E=>E.subcircuit_id&&c.has(E.subcircuit_id)),u=t.pcb_group.list().filter(E=>E.subcircuit_id&&c.has(E.subcircuit_id)),h=!1,d=(E,M,k)=>{M===0||k===0||(h=!0,i=Math.min(i,E.x-M/2),o=Math.min(o,E.y-k/2),r=Math.max(r,E.x+M/2),s=Math.max(s,E.y+k/2))};for(let E of l)d(E.center,E.width,E.height);for(let E of u){let M=E.width??0,k=E.height??0;if(E.outline&&E.outline.length>0){let N=es(E.outline);N&&(M=N.maxX-N.minX,k=N.maxY-N.minY)}d(E.center,M,k)}if(n.boardAnchorPosition){let{x:E,y:M}=n.boardAnchorPosition;i=Math.min(i,E),o=Math.min(o,M),r=Math.max(r,E),s=Math.max(s,M)}let _=2,y=h?r-i+_*2:0,g=h?s-o+_*2:0,x={x:h?(i+r)/2+(n.outlineOffsetX??0):n.outlineOffsetX??0,y:h?(o+s)/2+(n.outlineOffsetY??0):n.outlineOffsetY??0},w=n.width??y,S=n.height??g,T=n.outline;!T&&n.borderRadius!=null&&w>0&&S>0&&(T=pH(w,S,n.borderRadius));let I={width:w,height:S,center:x};T&&(I.outline=T.map(E=>({x:E.x+(n.outlineOffsetX??0),y:E.y+(n.outlineOffsetY??0)}))),t.pcb_board.update(this.pcb_board_id,I)}updatePcbBoardAutoSize(){this.doInitialPcbBoardAutoSize()}_addBoardInformationToSilkscreen(){let t=this.root?.platform;if(!t?.printBoardInformationToSilkscreen)return;let n=this.root.db.pcb_board.get(this.pcb_board_id);if(!n)return;let i=[];if(t.projectName&&i.push(t.projectName),t.version&&i.push(`v${t.version}`),t.url&&i.push(t.url),i.length===0)return;let o=i.join(`
|
|
251
251
|
`),a={x:n.center.x+n.width/2-.25,y:n.center.y-n.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:o,ccw_rotation:0,anchor_alignment:"bottom_right",anchor_position:a})}doInitialSourceRender(){super.doInitialSourceRender();let{db:t}=this.root,n=t.source_board.insert({source_group_id:this.source_group_id,title:this.props.title||this.props.name});this.source_board_id=n.source_board_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=n.width??0,o=n.height??0,r={x:(n.pcbX??0)+(n.outlineOffsetX??0),y:(n.pcbY??0)+(n.outlineOffsetY??0)},{boardAnchorPosition:s,boardAnchorAlignment:a}=n;if(s&&(r=cIt({boardAnchorPosition:s,boardAnchorAlignment:a??"center",width:i,height:o})),n.outline){let u=n.outline.map(x=>x.x),h=n.outline.map(x=>x.y),d=Math.min(...u),_=Math.max(...u),y=Math.min(...h),g=Math.max(...h);i=_-d,o=g-y,r={x:(d+_)/2+(n.outlineOffsetX??0),y:(y+g)/2+(n.outlineOffsetY??0)}}let c=n.outline;!c&&n.borderRadius!=null&&i>0&&o>0&&(c=pH(i,o,n.borderRadius));let l=t.pcb_board.insert({center:r,thickness:this.boardThickness,num_layers:this.allLayers.length,width:i,height:o,outline:c?.map(u=>({x:u.x+(n.outlineOffsetX??0),y:u.y+(n.outlineOffsetY??0)})),material:n.material});this.pcb_board_id=l.pcb_board_id,this._addBoardInformationToSilkscreen()}removePcbComponentRender(){let{db:t}=this.root;this.pcb_board_id&&(t.pcb_board.delete(this.pcb_board_id),this.pcb_board_id=null)}_computePcbGlobalTransformBeforeLayout(){return zi()}doInitialPcbDesignRuleChecks(){this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled")||super.doInitialPcbDesignRuleChecks()}updatePcbDesignRuleChecks(){if(this.root?.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;let{db:t}=this.root;if(!this._areChildSubcircuitsRouted()||this._drcChecksComplete)return;this._drcChecksComplete=!0;let n=vX(t.toArray());for(let l of n)t.pcb_trace_error.insert(l);let i=xX(t.toArray());for(let l of i)t.pcb_port_not_connected_error.insert(l);let o=PX(t.toArray());for(let l of o)t.pcb_component_outside_board_error.insert(l);let r=MX(t.toArray());for(let l of r)t.pcb_trace_error.insert(l);let s=TX(t.toArray());for(let l of s)t.pcb_via_clearance_error.insert(l);let a=IX(t.toArray());for(let l of a)t.pcb_via_clearance_error.insert(l);let c=CX(t.toArray());for(let l of c)t.pcb_footprint_overlap_error.insert(l)}_emitRenderLifecycleEvent(t,n){super._emitRenderLifecycleEvent(t,n),n==="start"&&this.root?.emit("board:renderPhaseStarted",{renderId:this._renderId,phase:t})}},VH=class extends Ic{get config(){return{componentName:"Panel",zodProps:uz}}get isGroup(){return!0}add(e){if(e.lowercaseComponentName!=="board")throw new Error("<panel> can only contain <board> elements");super.add(e)}runRenderCycle(){if(!this.children.some(e=>e.componentName==="Board"))throw new Error("<panel> must contain at least one <board>");super.runRenderCycle()}},rTt=new Proxy({},{get:(e,t)=>t}),aa=rTt,Fx="rgba(132, 0, 0)",zx=.12,HH=class extends On{constructor(){super(...arguments);P(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Capacitor",schematicSymbolName:this.props.polarized?"capacitor_polarized":this.props.symbolName??"capacitor",zodProps:xz,sourceFtype:aa.simple_capacitor}}initPorts(){typeof this.props.footprint=="string"?super.initPorts({additionalAliases:{pin1:["anode","pos"],pin2:["cathode","neg"]}}):super.initPorts()}_getSchematicSymbolDisplayValue(){let t=this.props.capacitance,n=typeof t=="string"?t:`${ni(this._parsedProps.capacitance)}F`;return this._parsedProps.schShowRatings&&this._parsedProps.maxVoltageRating?`${n}/${ni(this._parsedProps.maxVoltageRating)}V`:n}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.decouplingFor,this.props.decouplingTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.decouplingFor&&this.props.decouplingTo&&(this.add(new Dr({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.decouplingFor})),this.add(new Dr({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.decouplingTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_capacitor",name:this.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,capacitance:n.capacitance,max_voltage_rating:n.maxVoltageRating,max_decoupling_trace_length:n.maxDecouplingTraceLength,display_capacitance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!n.polarized});this.source_component_id=i.source_component_id}},Rm=class extends On{constructor(t){super(t);P(this,"schematicBoxDimensions",null)}get config(){return{componentName:"Chip",zodProps:Kp,shouldRenderAsSchematicBox:!0}}initPorts(t={}){super.initPorts(t);let{_parsedProps:n}=this;if(n.externallyConnectedPins){let i=new Set;for(let[o,r]of n.externallyConnectedPins)i.add(o),i.add(r);for(let o of i)if(!this.children.find(s=>s instanceof Ni&&s.isMatchingAnyOf([o]))){let s=o.match(/^pin(\d+)$/);if(s){let a=parseInt(s[1]);this.add(new Ni({pinNumber:a,aliases:[o]}))}else this.add(new Ni({name:o,aliases:[o]}))}}}doInitialSchematicComponentRender(){let{_parsedProps:t}=this;t?.noSchematicRepresentation!==!0&&super.doInitialSchematicComponentRender()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=n.layer??"top";if(i!=="top"&&i!=="bottom"){let r=this.getSubcircuit(),s=Ep.parse({type:"pcb_component_invalid_layer_error",message:`Component cannot be placed on layer '${i}'. Components can only be placed on 'top' or 'bottom' layers.`,source_component_id:this.source_component_id,layer:i,subcircuit_id:r.subcircuit_id??void 0});t.pcb_component_invalid_layer_error.insert(s)}let o=t.pcb_component.insert({center:{x:n.pcbX??0,y:n.pcbY??0},width:2,height:3,layer:i==="top"||i==="bottom"?i:"top",rotation:n.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:n.doNotPlace??!1,obstructs_within_bounds:n.obstructsWithinBounds??!0});this.pcb_component_id=o.pcb_component_id}doInitialCreateTracesFromProps(){let{_parsedProps:t}=this;if(t.externallyConnectedPins)for(let[n,i]of t.externallyConnectedPins)this.add(new Dr({from:`${this.getSubcircuitSelector()} > port.${n}`,to:`${this.getSubcircuitSelector()} > port.${i}`}));this._createTracesFromConnectionsProp()}doInitialSimulationRender(){let{db:t}=this.root,{pinAttributes:n}=this.props;if(!n)return;let i=null,o=null,r,s=this.selectAll("port");for(let h of s)for(let d of h.getNameAndAliases())if(n[d]){let _=n[d];_.providesPower&&(i=h,r=_.providesVoltage),_.providesGround&&(o=h)}if(!i||!o||r===void 0)return;let a=t.source_port.get(i.source_port_id);if(!a?.subcircuit_connectivity_map_key)return;let c=t.source_port.get(o.source_port_id);if(!c?.subcircuit_connectivity_map_key)return;let l=t.source_net.getWhere({subcircuit_connectivity_map_key:a.subcircuit_connectivity_map_key}),u=t.source_net.getWhere({subcircuit_connectivity_map_key:c.subcircuit_connectivity_map_key});!l||!u||t.simulation_voltage_source.insert({type:"simulation_voltage_source",positive_source_port_id:i.source_port_id,positive_source_net_id:l.source_net_id,negative_source_port_id:o.source_port_id,negative_source_net_id:u.source_net_id,voltage:r})}},GH=class extends Rm{constructor(e){super(e)}get config(){return{...super.config,componentName:"Pinout",zodProps:pz}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_pinout",name:this.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers});this.source_component_id=n.source_component_id}},UH=class extends On{constructor(){super(...arguments);P(this,"pos",this.portMap.pin1);P(this,"anode",this.portMap.pin1);P(this,"neg",this.portMap.pin2);P(this,"cathode",this.portMap.pin2)}get config(){let t={schottky:"schottky_diode",avalanche:"avalanche_diode",zener:"zener_diode",photodiode:"photodiode"},n=this.props.schottky?"schottky":this.props.avalanche?"avalanche":this.props.zener?"zener":this.props.photo?"photodiode":null;return{schematicSymbolName:n?t[n]:this.props.symbolName??"diode",componentName:"Diode",zodProps:zz,sourceFtype:"simple_diode"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_diode",name:this.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},qH=class extends On{get config(){return{componentName:"fuse",schematicSymbolName:this.props.symbolName??"fuse",zodProps:dz,sourceFtype:aa.simple_fuse}}_getSchematicSymbolDisplayValue(){let e=this._parsedProps.currentRating,t=this._parsedProps.voltageRating,n=typeof e=="string"?parseFloat(e):e,i=typeof t=="string"?parseFloat(t):t;return`${ni(n)}A / ${ni(i)}V`}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=typeof t.currentRating=="string"?parseFloat(t.currentRating):t.currentRating,i=typeof t.voltageRating=="string"?parseFloat(t.voltageRating):t.voltageRating,o=e.source_component.insert({name:this.name,ftype:aa.simple_fuse,current_rating_amps:n,voltage_rating_volts:i,display_current_rating:`${ni(n)}A`,display_voltage_rating:`${ni(i)}V`});this.source_component_id=o.source_component_id}},WH=class extends On{constructor(){super(...arguments);P(this,"schematicDimensions",null)}get config(){return{schematicSymbolName:void 0,componentName:"Jumper",zodProps:AI,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let t=super._getSchematicPortArrangement();if(t&&Object.keys(t).length>0)return t;let n=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length),i=this._parsedProps.schDirection??"right";return{leftSize:i==="left"?n:0,rightSize:i==="right"?n:0}}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.pcb_component.insert({center:{x:n.pcbX??0,y:n.pcbY??0},width:2,height:3,layer:n.layer??"top",rotation:n.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:n.doNotPlace??!1,obstructs_within_bounds:n.obstructsWithinBounds??!0});this.pcb_component_id=i.pcb_component_id}doInitialPcbTraceRender(){let{db:t}=this.root,n=t.pcb_port.list({pcb_component_id:this.pcb_component_id}),i={};for(let s=0;s<n.length;s++){let a=n[s],c=t.source_port.get(a.source_port_id),l="";if(typeof c?.pin_number=="number")l=c.pin_number.toString();else if(Array.isArray(c?.port_hints)){let u=c.port_hints.find(h=>/^(pin)?\d+$/.test(h));u&&(/^pin\d+$/.test(u)?l=u.replace(/^pin/,""):l=u)}i[l]=a.pcb_port_id}let o=t.pcb_trace.list({pcb_component_id:this.pcb_component_id}),r=s=>{if(s&&typeof s=="string"&&s.startsWith("{PIN")){let a=s.replace("{PIN","").replace("}","");return i[a]||s}return s};for(let s of o)if(s.route)for(let a of s.route)a.route_type==="wire"&&(a.start_pcb_port_id=r(a.start_pcb_port_id),a.end_pcb_port_id=r(a.end_pcb_port_id))}},ZH=class extends On{constructor(){super(...arguments);P(this,"schematicDimensions",null)}_getPinNumberFromBridgedPinName(t){return this.selectOne(`port.${t}`,{type:"port"})?._parsedProps.pinNumber??null}get defaultInternallyConnectedPinNames(){if(this._parsedProps.bridged){let t=this.children.filter(n=>n.componentName==="Port").map(n=>n.name);return t.length>0?[t]:[]}return this._parsedProps.bridgedPins??[]}get config(){let t=this._parsedProps??this.props,n=t.pinCount;if(t.pinCount==null&&!t.footprint&&(n=2),t.pinCount==null){let r=(t.bridgedPins??[]).flat().map(l=>this._getPinNumberFromBridgedPinName(l)).filter(l=>l!==null),s=r.length>0?Math.max(...r):0,a=t.pinLabels?Object.keys(t.pinLabels).length:0,c=Math.max(s,a);(c===2||c===3)&&(n=c),n==null&&t.footprint&&[2,3].includes(this.getPortsFromFootprint().length)&&(n=this.getPortsFromFootprint().length)}let i="";n?i+=`solderjumper${n}`:i="solderjumper";let o=[];return Array.isArray(t.bridgedPins)&&t.bridgedPins.length>0?o=Array.from(new Set(t.bridgedPins.flat().map(r=>this._getPinNumberFromBridgedPinName(r)).filter(r=>r!==null))).sort((r,s)=>r-s):t.bridged&&n&&(o=Array.from({length:n},(r,s)=>s+1)),o.length>0&&(i+=`_bridged${o.join("")}`),{schematicSymbolName:t.symbolName??i,componentName:"SolderJumper",zodProps:hz,shouldRenderAsSchematicBox:!0}}_getSchematicPortArrangement(){let t=super._getSchematicPortArrangement();if(t&&Object.keys(t).length>0)return t;let n=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:this.getPortsFromFootprint().length);n==null&&!this._parsedProps.footprint&&(n=2);let i=this._parsedProps.schDirection??"right";return{leftSize:i==="left"?n:0,rightSize:i==="right"?n:0}}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:this.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=t.pcb_component.insert({center:{x:n.pcbX??0,y:n.pcbY??0},width:2,height:3,layer:n.layer??"top",rotation:n.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0,do_not_place:n.doNotPlace??!1,obstructs_within_bounds:n.obstructsWithinBounds??!0});this.pcb_component_id=i.pcb_component_id}doInitialPcbTraceRender(){let{db:t}=this.root,n=t.pcb_port.list({pcb_component_id:this.pcb_component_id}),i={};for(let s=0;s<n.length;s++){let a=n[s],c=t.source_port.get(a.source_port_id),l="";if(typeof c?.pin_number=="number")l=c.pin_number.toString();else if(Array.isArray(c?.port_hints)){let u=c.port_hints.find(h=>/^(pin)?\d+$/.test(h));u&&(/^pin\d+$/.test(u)?l=u.replace(/^pin/,""):l=u)}i[l]=a.pcb_port_id}let o=t.pcb_trace.list({pcb_component_id:this.pcb_component_id}),r=s=>{if(s&&typeof s=="string"&&s.startsWith("{PIN")){let a=s.replace("{PIN","").replace("}","");return i[a]||s}return s};for(let s of o)if(s.route)for(let a of s.route)a.route_type==="wire"&&(a.start_pcb_port_id=r(a.start_pcb_port_id),a.end_pcb_port_id=r(a.end_pcb_port_id))}},KH=class extends On{constructor(){super(...arguments);P(this,"pos",this.portMap.pin1);P(this,"anode",this.portMap.pin1);P(this,"neg",this.portMap.pin2);P(this,"cathode",this.portMap.pin2)}get config(){let t={laser:"laser_diode"},n=this.props.laser?"laser":null;return{schematicSymbolName:n?t[n]:this.props.symbolName??"led",componentName:"Led",zodProps:$z,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 t=super.getFootprinterString();return t&&this.props.color?`${t}_color(${this.props.color})`:t}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_led",name:this.name,wave_length:n.wavelength,color:n.color,symbol_display_value:this._getSchematicSymbolDisplayValue(),manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},JH=class extends On{constructor(){super(...arguments);P(this,"pos",this.portMap.pin1);P(this,"positive",this.portMap.pin1);P(this,"neg",this.portMap.pin2);P(this,"negative",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"power_factor_meter_horz",componentName:"PowerSource",zodProps:Qz,sourceFtype:"simple_power_source"}}initPorts(){this.add(new Ni({name:"pin1",pinNumber:1,aliases:["positive","pos"]})),this.add(new Ni({name:"pin2",pinNumber:2,aliases:["negative","neg"]}))}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_power_source",name:this.name,voltage:n.voltage,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},sTt=Dn.extend({voltage:ai.optional(),frequency:Wi.optional(),peakToPeakVoltage:ai.optional(),waveShape:p.enum(["sinewave","square","triangle","sawtooth"]).optional(),phase:je.optional(),dutyCycle:p.number().optional()}),QH=class extends On{constructor(){super(...arguments);P(this,"terminal1",this.portMap.terminal1);P(this,"terminal2",this.portMap.terminal2)}get config(){return{componentName:"VoltageSource",schematicSymbolName:this.props.waveShape==="square"?"square_wave":"ac_voltmeter",zodProps:sTt,sourceFtype:"simple_voltage_source"}}runRenderPhaseForChildren(t){if(!t.startsWith("Pcb"))for(let n of this.children)n.runRenderPhaseForChildren(t),n.runRenderPhase(t)}doInitialPcbComponentRender(){}initPorts(){super.initPorts({additionalAliases:{pin1:["terminal1"],pin2:["terminal2"]}})}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_voltage_source",name:this.name,voltage:n.voltage,frequency:n.frequency,peak_to_peak_voltage:n.peakToPeakVoltage,wave_shape:n.waveShape,phase:n.phase,duty_cycle:n.dutyCycle,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialSimulationRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=this.portMap.terminal1,o=this.portMap.terminal2;t.simulation_voltage_source.insert({type:"simulation_voltage_source",is_dc_source:!1,terminal1_source_port_id:i.source_port_id,terminal2_source_port_id:o.source_port_id,voltage:n.voltage,frequency:n.frequency,peak_to_peak_voltage:n.peakToPeakVoltage,wave_shape:n.waveShape,phase:n.phase,duty_cycle:n.dutyCycle})}},$4=class extends On{constructor(){super(...arguments);P(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Resistor",schematicSymbolName:this.props.symbolName??"boxresistor",zodProps:mz,sourceFtype:"simple_resistor"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return`${ni(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 Dr({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pullupFor})),this.add(new Dr({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pullupTo}))),this.props.pulldownFor&&this.props.pulldownTo&&(this.add(new Dr({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pulldownFor})),this.add(new Dr({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pulldownTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_resistor",name:this.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers,resistance:n.resistance,display_resistance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}},aTt=["leftedge","rightedge","topedge","bottomedge","center"],tG=class extends ve{get config(){return{componentName:"Constraint",zodProps:Sz}}constructor(e){if(super(e),("xdist"in e||"ydist"in e)&&!("edgeToEdge"in e)&&!("centerToCenter"in e))throw new Error(`edgeToEdge, centerToCenter must be set for xDist or yDist for ${this}`);if("for"in e&&e.for.length<2)throw new Error(`"for" must have at least two selectors for ${this}`)}_getAllReferencedComponents(){let e=[],t=this.getPrimitiveContainer();function n(i){let o=i.split(" ").pop(),r=aTt.includes(o)?o:void 0,s=r?i.replace(` ${r}`,""):i,a=t.selectOne(s,{pcbPrimitive:!0});a&&e.push({selector:i,component:a,componentSelector:s,edge:r})}for(let i of["left","right","top","bottom"])i in this._parsedProps&&n(this._parsedProps[i]);if("for"in this._parsedProps)for(let i of this._parsedProps.for)n(i);return{componentsWithSelectors:e}}},eG=class extends ve{constructor(){super(...arguments);P(this,"fabrication_note_rect_id",null)}get config(){return{componentName:"FabricationNoteRect",zodProps:Xz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),o=i(n.layer??"top");if(o!=="top"&&o!=="bottom")throw new Error(`Invalid layer "${o}" for FabricationNoteRect. Must be "top" or "bottom".`);let r=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,s=this.getSubcircuit(),a=n.hasStroke??(n.strokeWidth!==void 0&&n.strokeWidth!==null),c=t.pcb_fabrication_note_rect.insert({pcb_component_id:r,layer:o,color:n.color,center:{x:n.pcbX??0,y:n.pcbY??0},width:n.width,height:n.height,stroke_width:n.strokeWidth??1,is_filled:n.isFilled??!1,has_stroke:a,is_stroke_dashed:n.isStrokeDashed??!1,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,corner_radius:n.cornerRadius??void 0});this.fabrication_note_rect_id=c.pcb_fabrication_note_rect_id}getPcbSize(){let{_parsedProps:t}=this;return{width:t.width,height:t.height}}},nG=class extends ve{constructor(){super(...arguments);P(this,"fabrication_note_path_id",null)}get config(){return{componentName:"FabricationNotePath",zodProps:Vz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,n=this.getSubcircuit(),{_parsedProps:i}=this,o=i.layer??"top";if(o!=="top"&&o!=="bottom")throw new Error(`Invalid layer "${o}" for SilkscreenPath. Must be "top" or "bottom".`);let r=this._computePcbGlobalTransformBeforeLayout(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=t.pcb_fabrication_note_path.insert({pcb_component_id:s,layer:o,color:i.color,route:i.route.map(c=>{let l=Ne(r,{x:c.x,y:c.y});return{...c,x:l.x,y:l.y}}),stroke_width:i.strokeWidth??.1,subcircuit_id:n?.subcircuit_id??void 0});this.fabrication_note_path_id=a.pcb_fabrication_note_path_id}},iG=class extends ve{get config(){return{componentName:"FabricationNoteText",zodProps:Yz}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:e}=this.root,{_parsedProps:t}=this,n=this.getPrimitiveContainer(),i=this.getSubcircuit();e.pcb_fabrication_note_text.insert({anchor_alignment:t.anchorAlignment,anchor_position:{x:t.pcbX??0,y:t.pcbY??0},font:t.font??"tscircuit2024",font_size:t.fontSize??1,layer:"top",color:t.color,text:t.text??"",pcb_component_id:n.pcb_component_id,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0})}},oG=class extends ve{constructor(){super(...arguments);P(this,"fabrication_note_dimension_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"FabricationNoteDimension",zodProps:Hz}}_resolvePoint(t,n){if(typeof t=="string"){let r=this.getSubcircuit().selectOne(t);return r?r._getGlobalPcbPositionBeforeLayout():(this.renderError(`FabricationNoteDimension could not find selector "${t}"`),Ne(n,{x:0,y:0}))}let i=typeof t.x=="string"?parseFloat(t.x):t.x,o=typeof t.y=="string"?parseFloat(t.y):t.y;return Ne(n,{x:i,y:o})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),o=this._resolvePoint(n.from,i),r=this._resolvePoint(n.to,i),s=this.getSubcircuit(),a=this.getGroup(),{maybeFlipLayer:c}=this._getPcbPrimitiveFlippedHelpers(),l=c(n.layer??"top");if(l!=="top"&&l!=="bottom")throw new Error(`Invalid layer "${l}" for FabricationNoteDimension. Must be "top" or "bottom".`);let u=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,h=n.text??this._formatDistanceText({from:o,to:r,units:n.units??"mm"}),d=t.pcb_fabrication_note_dimension.insert({pcb_component_id:u,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:a?.pcb_group_id??void 0,layer:l,from:o,to:r,text:h,offset:n.offset,font:n.font??"tscircuit2024",font_size:n.fontSize??1,color:n.color,arrow_size:n.arrowSize??1});this.fabrication_note_dimension_id=d.pcb_fabrication_note_dimension_id}getPcbSize(){let t=this._computePcbGlobalTransformBeforeLayout(),n=this._resolvePoint(this._parsedProps.from,t),i=this._resolvePoint(this._parsedProps.to,t);return{width:Math.abs(i.x-n.x),height:Math.abs(i.y-n.y)}}_formatDistanceText({from:t,to:n,units:i}){let o=n.x-t.x,r=n.y-t.y,s=Math.sqrt(o*o+r*r),a=i==="in"?s/25.4:s,c=Math.round(a);if(Math.abs(a-c)<1e-9)return`${c}${i}`;let u=i==="in"?3:2;return`${i==="in"?Number(a.toFixed(u)).toString():a.toFixed(u)}${i}`}},rG=class extends ve{constructor(){super(...arguments);P(this,"pcb_note_line_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteLine",zodProps:bD}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),o=this.getGroup(),r=this._computePcbGlobalTransformBeforeLayout(),s=Ne(r,{x:n.x1,y:n.y1}),a=Ne(r,{x:n.x2,y:n.y2}),c=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,l=t.pcb_note_line.insert({pcb_component_id:c,subcircuit_id:i?.subcircuit_id??void 0,pcb_group_id:o?.pcb_group_id??void 0,x1:s.x,y1:s.y,x2:a.x,y2:a.y,stroke_width:n.strokeWidth??.1,color:n.color,is_dashed:n.isDashed});this.pcb_note_line_id=l.pcb_note_line_id}getPcbSize(){let{_parsedProps:t}=this;return{width:Math.abs(t.x2-t.x1),height:Math.abs(t.y2-t.y1)}}},sG=class extends ve{constructor(){super(...arguments);P(this,"pcb_note_rect_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteRect",zodProps:yD}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),o=Ne(i,{x:0,y:0}),r=this.getSubcircuit(),s=this.getGroup(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,c=t.pcb_note_rect.insert({pcb_component_id:a,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:s?.pcb_group_id??void 0,center:o,width:n.width,height:n.height,stroke_width:n.strokeWidth??.1,is_filled:n.isFilled??!1,has_stroke:n.hasStroke??!0,is_stroke_dashed:n.isStrokeDashed??!1,color:n.color,corner_radius:n.cornerRadius??void 0});this.pcb_note_rect_id=c.pcb_note_rect_id}getPcbSize(){let{_parsedProps:t}=this,n=typeof t.width=="string"?parseFloat(t.width):t.width,i=typeof t.height=="string"?parseFloat(t.height):t.height;return{width:n,height:i}}},aG=class extends ve{constructor(){super(...arguments);P(this,"pcb_note_text_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteText",zodProps:_D}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),o=Ne(i,{x:0,y:0}),r=this.getSubcircuit(),s=this.getGroup(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,c=t.pcb_note_text.insert({pcb_component_id:a,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:s?.pcb_group_id??void 0,font:n.font??"tscircuit2024",font_size:n.fontSize??1,text:n.text,anchor_position:o,anchor_alignment:n.anchorAlignment??"center",color:n.color});this.pcb_note_text_id=c.pcb_note_text_id}getPcbSize(){let{_parsedProps:t}=this,n=typeof t.fontSize=="string"?parseFloat(t.fontSize):t.fontSize??1,i=n*.6;return{width:t.text.length*i,height:n}}},cG=class extends ve{constructor(){super(...arguments);P(this,"pcb_note_path_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNotePath",zodProps:gD}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),o=this.getSubcircuit(),r=this.getGroup(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,a=n.route.map(l=>{let{x:u,y:h,...d}=l,_=typeof u=="string"?parseFloat(u):u,y=typeof h=="string"?parseFloat(h):h,g=Ne(i,{x:_,y});return{...d,x:g.x,y:g.y}}),c=t.pcb_note_path.insert({pcb_component_id:s,subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:r?.pcb_group_id??void 0,route:a,stroke_width:n.strokeWidth??.1,color:n.color});this.pcb_note_path_id=c.pcb_note_path_id}getPcbSize(){let{_parsedProps:t}=this;if(t.route.length===0)return{width:0,height:0};let n=t.route.map(c=>typeof c.x=="string"?parseFloat(c.x):c.x),i=t.route.map(c=>typeof c.y=="string"?parseFloat(c.y):c.y),o=Math.min(...n),r=Math.max(...n),s=Math.min(...i),a=Math.max(...i);return{width:r-o,height:a-s}}},lG=class extends ve{constructor(){super(...arguments);P(this,"pcb_note_dimension_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbNoteDimension",zodProps:xD}}_resolvePoint(t,n){if(typeof t=="string"){let r=this.getSubcircuit().selectOne(`.${t}`);return r?r._getGlobalPcbPositionBeforeLayout():(this.renderError(`PcbNoteDimension could not find selector "${t}"`),Ne(n,{x:0,y:0}))}let i=typeof t.x=="string"?parseFloat(t.x):t.x,o=typeof t.y=="string"?parseFloat(t.y):t.y;return Ne(n,{x:i,y:o})}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._computePcbGlobalTransformBeforeLayout(),o=this._resolvePoint(n.from,i),r=this._resolvePoint(n.to,i),s=this.getSubcircuit(),a=this.getGroup(),c=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id??void 0,l=n.text??this._formatDistanceText({from:o,to:r,units:n.units??"mm"}),u=t.pcb_note_dimension.insert({pcb_component_id:c,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:a?.pcb_group_id??void 0,from:o,to:r,text:l,font:n.font??"tscircuit2024",font_size:n.fontSize??1,color:n.color,arrow_size:n.arrowSize??1});this.pcb_note_dimension_id=u.pcb_note_dimension_id}getPcbSize(){let t=this._computePcbGlobalTransformBeforeLayout(),n=this._resolvePoint(this._parsedProps.from,t),i=this._resolvePoint(this._parsedProps.to,t);return{width:Math.abs(i.x-n.x),height:Math.abs(i.y-n.y)}}_formatDistanceText({from:t,to:n,units:i}){let o=n.x-t.x,r=n.y-t.y,s=Math.sqrt(o*o+r*r),a=i==="in"?s/25.4:s,c=Math.round(a);if(Math.abs(a-c)<1e-9)return`${c}${i}`;let u=i==="in"?3:2;return`${i==="in"?Number(a.toFixed(u)).toString():a.toFixed(u)}${i}`}},uG=(e,t)=>{let{injectionDb:n,normalComponent:i}=t;if(!i)return;let o=jh({componentName:i.name,componentRotation:"0deg"},n.toArray().filter(r=>"pcb_component_id"in r&&r.pcb_component_id===e.pcb_component_id));i.addAll(o)};function cTt(e,t){let{injectionDb:n,subcircuit:i,groupsMap:o}=t,r=n.pcb_component.getWhere({source_component_id:e.source_component_id}),s=n.cad_component.getWhere({source_component_id:e.source_component_id}),a=new $4({name:e.name,resistance:e.resistance});r&&uG(r,{...t,normalComponent:a}),e.source_group_id&&o?.has(e.source_group_id)?o.get(e.source_group_id).add(a):i.add(a)}function lTt(e,t){let{injectionDb:n,subcircuit:i}=t;if(e.source_component_id!==null)return;let o=n.pcb_port.getWhere({source_port_id:e.source_port_id}),r=new Ni({name:e.name,pinNumber:e.pin_number});i.add(r),r.source_port_id=e.source_port_id;let s=i.root;if(s&&o){let{db:a}=s,c=a.pcb_port.insert({pcb_component_id:void 0,layers:o.layers,subcircuit_id:i.subcircuit_id??void 0,pcb_group_id:i.getGroup()?.pcb_group_id??void 0,x:o.x,y:o.y,source_port_id:e.source_port_id,is_board_pinout:!1});r.pcb_port_id=c.pcb_port_id}}function uTt(e,t){let{subcircuit:n,groupsMap:i}=t,o=new Ic({name:e.name});return o.source_group_id=e.source_group_id,n.add(o),i&&i.set(e.source_group_id,o),o}var pTt=(e,t)=>{if(!e||e.length===0)return;let{injectionDb:n}=t,i=e.map(o=>o.map(r=>{let s=n.source_port.get(r);return s?s.pin_number!==void 0&&s.pin_number!==null?`pin${s.pin_number}`:s.name:null}).filter(r=>r!==null)).filter(o=>o.length>0);return i.length>0?i:void 0},hTt=(e,t)=>{let{injectionDb:n,subcircuit:i,groupsMap:o}=t,r=n.pcb_component.getWhere({source_component_id:e.source_component_id}),s=n.schematic_component.getWhere({source_component_id:e.source_component_id}),a=n.cad_component.getWhere({source_component_id:e.source_component_id}),c=pTt(e.internally_connected_source_port_ids,t),l=new Rm({name:e.name,manufacturerPartNumber:e.manufacturer_part_number,supplierPartNumbers:e.supplier_part_numbers??void 0,pinLabels:s?.port_labels??void 0,schWidth:s?.size?.width,schHeight:s?.size?.height,schPinSpacing:s?.pin_spacing,schX:s?.center?.x,schY:s?.center?.y,layer:r?.layer,pcbX:r?.center?.x,pcbY:r?.center?.y,pcbRotation:r?.rotation,doNotPlace:r?.do_not_place,obstructsWithinBounds:r?.obstructs_within_bounds,internallyConnectedPins:c}),u=a?.footprinter_string??"soic8";u&&(Object.assign(l.props,{footprint:u}),Object.assign(l._parsedProps,{footprint:u}),a||l._addChildrenFromStringFootprint?.()),r&&uG(r,{...t,normalComponent:l}),e.source_group_id&&o?.has(e.source_group_id)?o.get(e.source_group_id).add(l):i.add(l)},pG=class extends Ic{constructor(e){super({...e,subcircuit:!0})}doInitialInflateSubcircuitCircuitJson(){let{circuitJson:e,children:t}=this._parsedProps;if(!e)return;let n=Ge(e);if(e&&t?.length>0)throw new Error("Subcircuit cannot have both circuitJson and children");let o={injectionDb:n,subcircuit:this,groupsMap:new Map},r=n.source_group.list();for(let c of r)uTt(c,o);let s=n.source_component.list();for(let c of s)switch(c.ftype){case"simple_resistor":cTt(c,o);break;case"simple_chip":hTt(c,o);break;default:throw new Error(`No inflator implemented for source component ftype: "${c.ftype}"`)}let a=n.source_port.list();for(let c of a)lTt(c,o)}},hG=class extends Ic{constructor(e){super({...e,subcircuit:!0})}doInitialPcbPrimitiveRender(){if(super.doInitialPcbPrimitiveRender(),this.root?.pcbDisabled)return;let{db:e}=this.root,t=this._parsedProps;if(!this.pcb_group_id)return;let n=e.pcb_group.get(this.pcb_group_id),i=t.paddingLeft??t.padding??0,o=t.paddingRight??t.padding??0,r=t.paddingTop??t.padding??0,s=t.paddingBottom??t.padding??0;e.pcb_group.update(this.pcb_group_id,{width:(n.width??0)+i+o,height:(n.height??0)+r+s,center:{x:n.center.x+(o-i)/2,y:n.center.y+(r-s)/2}})}},dG=class extends ve{constructor(){super(...arguments);P(this,"pcb_breakout_point_id",null);P(this,"matchedPort",null);P(this,"matchedNet",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"BreakoutPoint",zodProps:qz}}_matchConnection(){let{connection:t}=this._parsedProps,n=this.getSubcircuit();n&&(this.matchedPort=n.selectOne(t,{type:"port"}),this.matchedPort||(this.matchedNet=n.selectOne(t,{type:"net"})),!this.matchedPort&&!this.matchedNet&&this.renderError(`Could not find connection target "${t}"`))}_getSourceTraceIdForPort(t){let{db:n}=this.root;return n.source_trace.list().find(o=>o.connected_source_port_ids.includes(t.source_port_id))?.source_trace_id}_getSourceNetIdForPort(t){let{db:n}=this.root;return n.source_trace.list().find(o=>o.connected_source_port_ids.includes(t.source_port_id))?.connected_source_net_ids[0]}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root;this._matchConnection();let{pcbX:n=0,pcbY:i=0}=this._parsedProps,o=this.parent?.getGroup(),r=this.getSubcircuit();if(!o||!o.pcb_group_id)return;let s=t.pcb_breakout_point.insert({pcb_group_id:o.pcb_group_id,subcircuit_id:r?.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:n,y:i});this.pcb_breakout_point_id=s.pcb_breakout_point_id}_getPcbCircuitJsonBounds(){let{pcbX:t=0,pcbY:n=0}=this._parsedProps;return{center:{x:t,y:n},bounds:{left:t,top:n,right:t,bottom:n},width:0,height:0}}_setPositionFromLayout(t){let{db:n}=this.root;this.pcb_breakout_point_id&&n.pcb_breakout_point.update(this.pcb_breakout_point_id,{x:t.x,y:t.y})}getPcbSize(){return{width:0,height:0}}},fG=class extends ve{constructor(){super(...arguments);P(this,"source_net_label_id")}get config(){return{componentName:"NetLabel",zodProps:kz}}_getAnchorSide(){let{_parsedProps:t}=this;if(t.anchorSide)return t.anchorSide;if(!this._resolveConnectsTo())return"right";let i=this._getGlobalSchematicPositionBeforeLayout(),o=this._getConnectedPorts();if(o.length===0)return"right";let r=o[0]._getGlobalSchematicPositionBeforeLayout(),s=r.x-i.x,a=r.y-i.y;if(Math.abs(s)>Math.abs(a)){if(s>0)return"right";if(s<0)return"left"}else{if(a>0)return"top";if(a<0)return"bottom"}return"right"}_getConnectedPorts(){let t=this._resolveConnectsTo();if(!t)return[];let n=[];for(let i of t){let o=this.getSubcircuit().selectOne(i);o&&n.push(o)}return n}computeSchematicPropsTransform(){let{_parsedProps:t}=this;if(t.schX===void 0&&t.schY===void 0){let n=this._getConnectedPorts();if(n.length>0){let i=n[0]._getGlobalSchematicPositionBeforeLayout(),o=Ne(this.parent?.computeSchematicGlobalTransform?.()??zi(),{x:0,y:0});return vn(i.x-o.x,i.y-o.y)}}return super.computeSchematicPropsTransform()}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),o=this.getSubcircuit().selectOne(`net.${this._getNetName()}`),r=n.anchorSide??"right",s=Pc({anchor_position:i,anchor_side:r,text:n.net}),a=t.schematic_net_label.insert({text:n.net,source_net_id:o.source_net_id,anchor_position:i,center:s,anchor_side:this._getAnchorSide()});this.source_net_label_id=a.source_net_id}_resolveConnectsTo(){let{_parsedProps:t}=this,n=t.connectsTo??t.connection;if(Array.isArray(n))return n;if(typeof n=="string")return[n]}_getNetName(){let{_parsedProps:t}=this;return t.net}doInitialCreateNetsFromProps(){let{_parsedProps:t}=this;t.net&&Rx(this,[`net.${t.net}`])}doInitialCreateTracesFromNetLabels(){if(this.root?.schematicDisabled)return;let t=this._resolveConnectsTo();if(t)for(let n of t)this.add(new Dr({from:n,to:`net.${this._getNetName()}`}))}doInitialSchematicTraceRender(){if(!this.root?._featureMspSchematicTraceRouting||this.root?.schematicDisabled)return;let{db:t}=this.root,n=this._resolveConnectsTo();if(!n||n.length===0)return;let i=this._getGlobalSchematicPositionBeforeLayout(),o=this._getAnchorSide(),s={left:"x-",right:"x+",top:"y+",bottom:"y-"}[o],a=this.getSubcircuit().selectOne(`net.${this._getNetName()}`);for(let c of n){let l=this.getSubcircuit().selectOne(c,{type:"port"});if(!l||!l.schematic_port_id)continue;let u=!1;if(a?.source_net_id){let w=t.source_trace.list().find(S=>S.connected_source_net_ids?.includes(a.source_net_id)&&S.connected_source_port_ids?.includes(l.source_port_id??""));if(w&&(u=t.schematic_trace.list().some(S=>S.source_trace_id===w.source_trace_id)),u)continue}let h=l._getGlobalSchematicPositionAfterLayout(),d=I4(l.facingDirection??"right")??"x+",_=nc({x:h.x,y:h.y,facingDirection:d},{x:i.x,y:i.y,facingDirection:s});if(!Array.isArray(_)||_.length<2)continue;let y=[];for(let w=0;w<_.length-1;w++)y.push({from:{x:_[w].x,y:_[w].y},to:{x:_[w+1].x,y:_[w+1].y}});let g,x;if(a?.source_net_id&&l.source_port_id){let w=t.source_trace.list().find(S=>S.connected_source_net_ids?.includes(a.source_net_id)&&S.connected_source_port_ids?.includes(l.source_port_id));g=w?.source_trace_id,x=w?.subcircuit_connectivity_map_key||t.source_net.get(a.source_net_id)?.subcircuit_connectivity_map_key}t.schematic_trace.insert({source_trace_id:g,edges:y,junctions:[],subcircuit_connectivity_map_key:x}),t.schematic_port.update(l.schematic_port_id,{is_connected:!0})}}},mG=class extends ve{constructor(){super(...arguments);P(this,"pcb_silkscreen_circle_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenCircle",zodProps:fD}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),o=i(n.layer??"top");if(o!=="top"&&o!=="bottom")throw new Error(`Invalid layer "${o}" for SilkscreenCircle. Must be "top" or "bottom".`);let r=this._computePcbGlobalTransformBeforeLayout(),s=this.getSubcircuit(),a=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,c=t.pcb_silkscreen_circle.insert({pcb_component_id:a,layer:o,center:{x:n.pcbX??0,y:n.pcbY??0},radius:n.radius,subcircuit_id:s?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,stroke_width:n.strokeWidth??.1});this.pcb_silkscreen_circle_id=c.pcb_silkscreen_circle_id}getPcbSize(){let{_parsedProps:t}=this,n=t.radius*2;return{width:n,height:n}}},_G=class extends ve{constructor(){super(...arguments);P(this,"pcb_silkscreen_rect_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenRect",zodProps:dD}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),o=i(n.layer??"top");if(o!=="top"&&o!=="bottom")throw new Error(`Invalid layer "${o}" for SilkscreenRect. Must be "top" or "bottom".`);let r=this.getSubcircuit(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=t.pcb_silkscreen_rect.insert({pcb_component_id:s,layer:o,center:{x:n.pcbX??0,y:n.pcbY??0},width:n.width,height:n.height,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:this?.getGroup()?.pcb_group_id??void 0,stroke_width:n.strokeWidth??.1,is_filled:n.filled??!1,corner_radius:n.cornerRadius??void 0});this.pcb_silkscreen_rect_id=a.pcb_silkscreen_rect_id}getPcbSize(){let{_parsedProps:t}=this;return{width:t.width,height:t.height}}},yG=class extends ve{constructor(){super(...arguments);P(this,"pcb_silkscreen_line_id",null);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenLine",zodProps:hD}}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),o=i(n.layer??"top");if(o!=="top"&&o!=="bottom")throw new Error(`Invalid layer "${o}" for SilkscreenLine. Must be "top" or "bottom".`);let r=this.getSubcircuit(),s=this.parent?.pcb_component_id??this.getPrimitiveContainer()?.pcb_component_id,a=t.pcb_silkscreen_line.insert({pcb_component_id:s,layer:o,x1:n.x1,y1:n.y1,x2:n.x2,y2:n.y2,stroke_width:n.strokeWidth??.1,subcircuit_id:r?.subcircuit_id??void 0,pcb_group_id:r?.getGroup()?.pcb_group_id??void 0});this.pcb_silkscreen_line_id=a.pcb_silkscreen_line_id}getPcbSize(){let{_parsedProps:t}=this,n=Math.abs(t.x2-t.x1),i=Math.abs(t.y2-t.y1);return{width:n,height:i}}},gG=class extends ve{constructor(t){super(t);P(this,"pcb_via_id",null);P(this,"matchedPort",null);P(this,"isPcbPrimitive",!0);P(this,"source_manually_placed_via_id",null);let n=this._getLayers();this._parsedProps.layers=n,this.initPorts()}get config(){return{componentName:"Via",zodProps:Gz}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){let{_parsedProps:t}=this;return{width:t.outerDiameter,height:t.outerDiameter}}_getPcbCircuitJsonBounds(){let{db:t}=this.root,n=t.pcb_via.get(this.pcb_via_id),i=this.getPcbSize();return{center:{x:n.x,y:n.y},bounds:{left:n.x-i.width/2,top:n.y-i.height/2,right:n.x+i.width/2,bottom:n.y+i.height/2},width:i.width,height:i.height}}_setPositionFromLayout(t){let{db:n}=this.root;n.pcb_via.update(this.pcb_via_id,{x:t.x,y:t.y})}_getLayers(){let{fromLayer:t="top",toLayer:n="bottom"}=this._parsedProps;return t===n?[t]:[t,n]}initPorts(){let t=this._parsedProps.layers;for(let i of t){let o=new Ni({name:i,layer:i});o.registerMatch(this),this.add(o)}let n=new Ni({name:"pin1"});n.registerMatch(this),this.add(n)}doInitialPcbComponentRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),o=this.getSubcircuit(),r=t.pcb_component.insert({center:i,width:n.outerDiameter,height:n.outerDiameter,layer:n.fromLayer??"top",rotation:0,source_component_id:this.source_component_id,subcircuit_id:o?.subcircuit_id??void 0,obstructs_within_bounds:!0});this.pcb_component_id=r.pcb_component_id}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=this.getGroup(),o=this.getSubcircuit(),r=t.source_manually_placed_via.insert({source_group_id:i?.source_group_id,source_net_id:n.net??"",subcircuit_id:o?.subcircuit_id??void 0});this.source_component_id=r.source_manually_placed_via_id}doInitialPcbPrimitiveRender(){if(this.root?.pcbDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),o=this.getSubcircuit(),r=t.pcb_via.insert({x:i.x,y:i.y,hole_diameter:n.holeDiameter,outer_diameter:n.outerDiameter,layers:["bottom","top"],from_layer:n.fromLayer||"bottom",to_layer:n.toLayer||"top",subcircuit_id:o?.subcircuit_id??void 0,pcb_group_id:this.getGroup()?.pcb_group_id??void 0,net_is_assignable:n.netIsAssignable??void 0});this.pcb_via_id=r.pcb_via_id}},bG=class extends ve{constructor(){super(...arguments);P(this,"isPcbPrimitive",!0)}get config(){return{componentName:"CopperPour",zodProps:Zz}}getPcbSize(){return{width:0,height:0}}doInitialCreateNetsFromProps(){let{_parsedProps:t}=this;Rx(this,[t.connectsTo])}doInitialPcbCopperPourRender(){this.root?.pcbDisabled||this._queueAsyncEffect("PcbCopperPourRender",async()=>{let{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit().selectOne(n.connectsTo);if(!i||!i.source_net_id){this.renderError(`Net "${n.connectsTo}" not found for copper pour`);return}let o=this.getSubcircuit(),r=t.toArray().filter(h=>h.type==="source_net"&&h.name===i.name)[0]||"",s=n.clearance??.2,a=AX(t.toArray(),{layer:n.layer,pour_connectivity_key:r.subcircuit_connectivity_map_key||"",pad_margin:n.padMargin??s,trace_margin:n.traceMargin??s,board_edge_margin:n.boardEdgeMargin??s,cutout_margin:n.cutoutMargin??s}),c=new kX(a),{brep_shapes:l}=c.getOutput(),u=n.coveredWithSolderMask??!1;for(let h of l)t.pcb_copper_pour.insert({shape:"brep",layer:n.layer,brep_shape:h,source_net_id:i.source_net_id,subcircuit_id:o?.subcircuit_id??void 0,covered_with_solder_mask:u})})}},xG=class extends On{get config(){return{componentName:"Battery",schematicSymbolName:this.props.symbolName??"battery",zodProps:Ez,sourceFtype:"simple_power_source"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:this.name,ftype:"simple_power_source",capacity:t.capacity,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=n.source_component_id}},vG=class extends On{_getPcbRotationBeforeLayout(){let e=this.props.pcbOrientation==="vertical"?-90:0;return(super._getPcbRotationBeforeLayout()??0)+e}get config(){return{componentName:"PinHeader",zodProps:Nz,shouldRenderAsSchematicBox:!0}}_getImpliedFootprintString(){let e=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:0),t=this._parsedProps.holeDiameter,n=this._parsedProps.platedDiameter,i=this._parsedProps.pitch,o=this._parsedProps.showSilkscreenPinLabels;if(e>0){let r;if(i)!t&&!n?r=`pinrow${e}_p${i}`:r=`pinrow${e}_p${i}_id${t}_od${n}`;else if(!t&&!n)r=`pinrow${e}`;else return null;return o!==!0&&(r+="_nopinlabels"),r}return null}initPorts(){let e=this._parsedProps.pinCount??(Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels.length:this._parsedProps.pinLabels?Object.keys(this._parsedProps.pinLabels).length:1);for(let t=1;t<=e;t++){let n=Array.isArray(this._parsedProps.pinLabels)?this._parsedProps.pinLabels[t-1]:this._parsedProps.pinLabels?.[`pin${t}`];if(n){let i=Array.isArray(n)?n[0]:n,o=Array.isArray(n)?n.slice(1):[];this.add(new Ni({pinNumber:t,name:i,aliases:[`pin${t}`,...o]}))}else this.add(new Ni({pinNumber:t,name:`pin${t}`}))}}_getSchematicPortArrangement(){let e=this._parsedProps.pinCount??1,t=this._parsedProps.schFacingDirection??this._parsedProps.facingDirection??"right",n=this._parsedProps.schPinArrangement;return t==="left"?{leftSide:{direction:n?.leftSide?.direction??"top-to-bottom",pins:n?.leftSide?.pins??Array.from({length:e},(i,o)=>`pin${o+1}`)}}:{rightSide:{direction:n?.rightSide?.direction??"top-to-bottom",pins:n?.rightSide?.pins??Array.from({length:e},(i,o)=>`pin${o+1}`)}}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_pin_header",name:this.name,supplier_part_numbers:t.supplierPartNumbers,pin_count:t.pinCount,gender:t.gender,are_pins_interchangeable:!0});this.source_component_id=n.source_component_id}};function dTt(e){switch(e){case"two_ground_pins":return"crystal_4pin";case"ground_pin":return"resonator";case"no_ground":return"crystal";default:return"crystal"}}var SG=class extends On{get config(){return{componentName:"Resonator",schematicSymbolName:this.props.symbolName??dTt(this.props.pinVariant),zodProps:bz,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=t.pinVariant||"no_ground",i=e.source_component.insert({ftype:"simple_resonator",name:this.name,frequency:t.frequency,load_capacitance:t.loadCapacitance,supplier_part_numbers:t.supplierPartNumbers,pin_variant:n,are_pins_interchangeable:n==="no_ground"||n==="ground_pin"});this.source_component_id=i.source_component_id}_getSchematicSymbolDisplayValue(){let e=`${ni(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${e} / ${ni(this._parsedProps.loadCapacitance)}F`:e}},wG=class extends On{constructor(){super(...arguments);P(this,"_adjustSilkscreenTextAutomatically",!0)}get config(){return{componentName:"Inductor",schematicSymbolName:this.props.symbolName??"inductor",zodProps:Fz,sourceFtype:aa.simple_inductor}}_getSchematicSymbolDisplayValue(){return`${ni(this._parsedProps.inductance)}H`}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({name:this.name,ftype:aa.simple_inductor,inductance:n.inductance,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}};function fTt(e){switch(e){case"three_pin":return"potentiometer3";case"two_pin":return"potentiometer2";default:return"potentiometer2"}}var PG=class extends On{get config(){return{componentName:"Potentiometer",schematicSymbolName:this.props.symbolName??fTt(this.props.pinVariant),zodProps:yz,shouldRenderAsSchematicBox:!1}}_getSchematicSymbolDisplayValue(){return`${ni(this._parsedProps.maxResistance)}\u03A9`}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=t.pinVariant||"two_pin",i=e.source_component.insert({ftype:"simple_potentiometer",name:this.name,max_resistance:t.maxResistance,pin_variant:n,are_pins_interchangeable:n==="two_pin"});this.source_component_id=i.source_component_id}},IG=class extends On{get config(){return{componentName:"PushButton",schematicSymbolName:this.props.symbolName??"push_button_normally_open_momentary",zodProps:Az,sourceFtype:aa.simple_push_button}}get defaultInternallyConnectedPinNames(){return[]}initPorts(){super.initPorts({pinCount:2,ignoreSymbolPorts:!0});let e=ti[this._getSchematicSymbolNameOrThrow()],t=e.ports.find(l=>l.labels.includes("1")),n=e.ports.find(l=>l.labels.includes("2")),i=this.selectAll("port"),o=i.find(l=>l.props.pinNumber===1),r=i.find(l=>l.props.pinNumber===2),s=i.find(l=>l.props.pinNumber===3),a=i.find(l=>l.props.pinNumber===4),{internallyConnectedPins:c}=this._parsedProps;o.schematicSymbolPortDef=t,(!c||c.length===0)&&(r.schematicSymbolPortDef=n);for(let[l,u]of[[2,r],[3,s],[4,a]]){let h=c?.find(([_,y])=>_===`pin${l}`||y===`pin${l}`);if(!h){u.schematicSymbolPortDef=n;break}(h?.[0]===`pin${l}`?h[1]:h?.[0])!=="pin1"&&(u.schematicSymbolPortDef=n)}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:this.name,ftype:aa.simple_push_button,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=n.source_component_id}},TG=class extends On{get config(){return{schematicSymbolName:this.props.symbolName??(this.props.pinVariant==="four_pin"?"crystal_4pin":"crystal"),componentName:"Crystal",zodProps:gz,sourceFtype:"simple_crystal"}}initPorts(){let e=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:e})}_getSchematicSymbolDisplayValue(){let e=`${ni(this._parsedProps.frequency)}Hz`;return this._parsedProps.loadCapacitance?`${e} / ${ni(this._parsedProps.loadCapacitance)}F`:e}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:this.name,ftype:"simple_crystal",frequency:t.frequency,load_capacitance:t.loadCapacitance,pin_variant:t.pinVariant||"two_pin",are_pins_interchangeable:(t.pinVariant||"two_pin")==="two_pin"});this.source_component_id=n.source_component_id}},MG=class extends On{constructor(){super(...arguments);P(this,"emitter",this.portMap.pin1);P(this,"collector",this.portMap.pin2);P(this,"base",this.portMap.pin3)}get config(){let t=this.props.type==="npn"?"npn_bipolar_transistor":"pnp_bipolar_transistor";return{componentName:"Transistor",schematicSymbolName:this.props.symbolName??t,zodProps:Oz,sourceFtype:"simple_transistor",shouldRenderAsSchematicBox:!1}}initPorts(){let t={pin1:["collector","c"],pin2:["emitter","e"],pin3:["base","b"]};super.initPorts({pinCount:3,additionalAliases:t})}doInitialCreateNetsFromProps(){this._createNetsFromProps([...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}doInitialSourceRender(){let{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_transistor",name:this.name,transistor_type:n.type});this.source_component_id=i.source_component_id}},CG=class extends On{get config(){let e=this.props.mosfetMode==="depletion"?"d":"e",n=`${this.props.channelType}_channel_${e}_mosfet_transistor`;return{componentName:"Mosfet",schematicSymbolName:this.props.symbolName??n,zodProps:Lz,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_mosfet",name:this.name,mosfet_mode:t.mosfetMode,channel_type:t.channelType});this.source_component_id=n.source_component_id}};function mTt(e){return e.simSwitchFrequency!==void 0||e.simCloseAt!==void 0||e.simOpenAt!==void 0||e.simStartClosed!==void 0||e.simStartOpen!==void 0}var EG=class extends On{_getSwitchType(){let e=this._parsedProps;return e?e.dpdt?"dpdt":e.spst?"spst":e.spdt?"spdt":e.dpst?"dpst":e.type??"spst":"spst"}get config(){let e=this._getSwitchType(),t=this._parsedProps?.isNormallyClosed??!1,n={spst:t?"spst_normally_closed_switch":"spst_switch",spdt:t?"spdt_normally_closed_switch":"spdt_switch",dpst:t?"dpst_normally_closed_switch":"dpst_switch",dpdt:t?"dpdt_normally_closed_switch":"dpdt_switch"};return{componentName:"Switch",schematicSymbolName:this.props.symbolName??n[e],zodProps:Bz,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){let{db:e}=this.root,t=this._parsedProps??{},n=e.source_component.insert({ftype:"simple_switch",name:this.name,are_pins_interchangeable:this._getSwitchType()==="spst"});this.source_component_id=n.source_component_id}doInitialSimulationRender(){let{_parsedProps:e}=this;if(!mTt(e))return;let{db:t}=this.root,n={type:"simulation_switch",source_component_id:this.source_component_id||""};e.simSwitchFrequency!==void 0&&(n.switching_frequency=Wi.parse(e.simSwitchFrequency)),e.simCloseAt!==void 0&&(n.closes_at=qi.parse(e.simCloseAt)),e.simOpenAt!==void 0&&(n.opens_at=qi.parse(e.simOpenAt)),e.simStartOpen!==void 0&&(n.starts_closed=!e.simStartOpen),e.simStartClosed!==void 0&&(n.starts_closed=e.simStartClosed),t.simulation_switch.insert(n)}},S4={HOLE_DIAMETER:.5,SMT_CIRCLE_DIAMETER:1.2,SMT_RECT_SIZE:2},NG=class extends On{get config(){return{componentName:"TestPoint",schematicSymbolName:this.props.symbolName??"testpoint",zodProps:Uz,sourceFtype:aa.simple_test_point}}_getPropsWithDefaults(){let{padShape:e,holeDiameter:t,footprintVariant:n,padDiameter:i,width:o,height:r}=this._parsedProps;return!n&&t&&(n="through_hole"),n??(n="through_hole"),e??(e="circle"),n==="pad"?e==="circle"?i??(i=S4.SMT_CIRCLE_DIAMETER):e==="rect"&&(o??(o=S4.SMT_RECT_SIZE),r??(r=o)):n==="through_hole"&&(t??(t=S4.HOLE_DIAMETER)),{padShape:e,holeDiameter:t,footprintVariant:n,padDiameter:i,width:o,height:r}}_getImpliedFootprintString(){let{padShape:e,holeDiameter:t,footprintVariant:n,padDiameter:i,width:o,height:r}=this._getPropsWithDefaults();if(n==="through_hole")return`platedhole_d${t}`;if(n==="pad"){if(e==="circle")return`smtpad_circle_d${i}`;if(e==="rect")return`smtpad_rect_w${o}_h${r}`}throw new Error(`Footprint variant "${n}" with pad shape "${e}" not implemented`)}doInitialSourceRender(){let{db:e}=this.root,{_parsedProps:t}=this,{padShape:n,holeDiameter:i,footprintVariant:o,padDiameter:r,width:s,height:a}=this._getPropsWithDefaults(),c=e.source_component.insert({ftype:aa.simple_test_point,name:this.name,supplier_part_numbers:t.supplierPartNumbers,footprint_variant:o,pad_shape:n,pad_diameter:r,hole_diameter:i,width:s,height:a,are_pins_interchangeable:!0});this.source_component_id=c.source_component_id}},kG=class extends ve{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicText",zodProps:sD}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout();t.schematic_text.insert({anchor:n.anchor??"center",text:n.text,font_size:n.fontSize,color:n.color||"#000000",position:{x:i.x,y:i.y},rotation:n.schRotation??0})}},AG=class extends ve{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0);P(this,"schematic_line_id")}get config(){return{componentName:"SchematicLine",zodProps:rD}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),o=this.getPrimitiveContainer()?.parent?.schematic_component_id,r=t.schematic_line.insert({schematic_component_id:o,x1:n.x1+i.x,y1:n.y1+i.y,x2:n.x2+i.x,y2:n.y2+i.y,stroke_width:n.strokeWidth??zx,color:n.color??Fx,is_dashed:!1,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_line_id=r.schematic_line_id}},RG=class extends ve{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0);P(this,"schematic_rect_id")}get config(){return{componentName:"SchematicRect",zodProps:oD}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),o=this.getPrimitiveContainer()?.parent?.schematic_component_id,r=t.schematic_rect.insert({center:{x:i.x,y:i.y},width:n.width,height:n.height,stroke_width:n.strokeWidth??zx,color:n.color??Fx,is_filled:n.isFilled,schematic_component_id:o,is_dashed:n.isDashed,rotation:n.rotation??0,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_rect_id=r.schematic_rect_id}},OG=class extends ve{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0);P(this,"schematic_arc_id")}get config(){return{componentName:"SchematicArc",zodProps:eD}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),o=this.getPrimitiveContainer()?.parent?.schematic_component_id,r=t.schematic_arc.insert({schematic_component_id:o,center:{x:n.center.x+i.x,y:n.center.y+i.y},radius:n.radius,start_angle_degrees:n.startAngleDegrees,end_angle_degrees:n.endAngleDegrees,direction:n.direction,stroke_width:n.strokeWidth??zx,color:n.color??Fx,is_dashed:n.isDashed,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_arc_id=r.schematic_arc_id}},LG=class extends ve{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0);P(this,"schematic_circle_id")}get config(){return{componentName:"SchematicCircle",zodProps:iD}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalSchematicPositionBeforeLayout(),o=this.getPrimitiveContainer()?.parent?.schematic_component_id,r=t.schematic_circle.insert({schematic_component_id:o,center:{x:n.center.x+i.x,y:n.center.y+i.y},radius:n.radius,stroke_width:n.strokeWidth??zx,color:n.color??Fx,is_filled:n.isFilled,fill_color:n.fillColor,is_dashed:n.isDashed,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.schematic_circle_id=r.schematic_circle_id}};function _Tt({anchor:e,x:t,y:n,width:i,height:o,isInside:r}){switch(e){case"top_left":return{x:t,y:n+o,textAnchor:r?"top_left":"bottom_left"};case"top_center":return{x:t+i/2,y:n+o,textAnchor:r?"top_center":"bottom_center"};case"top_right":return{x:t+i,y:n+o,textAnchor:r?"top_right":"bottom_right"};case"center_left":return{x:t,y:n+o/2,textAnchor:r?"center_left":"center_right"};case"center":return{x:t+i/2,y:n+o/2,textAnchor:"center"};case"center_right":return{x:t+i,y:n+o/2,textAnchor:r?"center_right":"center_left"};case"bottom_left":return{x:t,y:n,textAnchor:r?"bottom_left":"top_left"};case"bottom_center":return{x:t+i/2,y:n,textAnchor:r?"bottom_center":"top_center"};case"bottom_right":return{x:t+i,y:n,textAnchor:r?"bottom_right":"top_right"};default:return{x:t+i/2,y:n+o,textAnchor:"center"}}}var FG=class extends ve{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicBox",zodProps:nD,shouldRenderAsSchematicBox:!0}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=.6,o=typeof n.padding=="number"?n.padding:0,r=typeof n.paddingTop=="number"?n.paddingTop:o,s=typeof n.paddingBottom=="number"?n.paddingBottom:o,a=typeof n.paddingLeft=="number"?n.paddingLeft:o,c=typeof n.paddingRight=="number"?n.paddingRight:o,l=n.overlay&&n.overlay.length>0,u=typeof n.width=="number"&&typeof n.height=="number",h,d,_,y,g,x;if(l){let S=n.overlay.map(J=>({selector:J,port:this.getSubcircuit().selectOne(J,{type:"port"})})).filter(({port:J})=>J!=null).map(({port:J})=>({position:J._getGlobalSchematicPositionAfterLayout()}));if(S.length===0)return;let T=S.map(J=>J.position.x),I=S.map(J=>J.position.y),E=Math.min(...T),M=Math.max(...T),k=Math.min(...I),N=Math.max(...I),A=M-E,R=N-k,$=A===0?i:0,j=R===0?i:0,H=a+$/2,X=c+$/2,G=r+j/2,Q=s+j/2,tt=E-H,V=M+X,rt=k-Q,et=N+G;h=V-tt,d=et-rt,_=tt+(n.schX??0),y=rt+(n.schY??0),g=_+h/2,x=y+d/2}else if(u){h=n.width,d=n.height;let w=this._getGlobalSchematicPositionBeforeLayout();g=w.x,x=w.y,_=g-h/2,y=x-d/2}else return;if(t.schematic_box.insert({height:d,width:h,x:_,y,is_dashed:n.strokeStyle==="dashed"}),n.title){let w=n.titleInside,S=.1,T=n.titleAlignment,I=_Tt({anchor:T,x:_,y,width:h,height:d,isInside:w}),E,M,k=I.textAnchor;w?(E=T.includes("top")?-S:T.includes("bottom")?S:0,M=T.includes("left")?S:T.includes("right")?-S:0):(E=T.includes("top")?S:T.includes("bottom")?-S:0,M=T.includes("center_left")?-S:T.includes("center_right")?S:0);let N=I.x+M,A=I.y+E;t.schematic_text.insert({anchor:k,text:n.title,font_size:n.titleFontSize??.18,color:n.titleColor??"#000000",position:{x:N,y:A},rotation:0})}}},zG=class extends ve{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0);P(this,"schematic_table_id",null)}get config(){return{componentName:"SchematicTable",zodProps:aD}}doInitialSchematicPrimitiveRender(){if(this.root?.schematicDisabled)return;let{db:t}=this.root,{_parsedProps:n}=this,i=this.children.filter(d=>d.componentName==="SchematicRow");if(i.length===0)return;let o=[],r=0;for(let d of i){let _=d.children.filter(y=>y.componentName==="SchematicCell");r=Math.max(r,_.length)}for(let d=0;d<i.length;d++)o[d]=[];for(let d=0;d<i.length;d++){let y=i[d].children.filter(x=>x.componentName==="SchematicCell"),g=0;for(let x=0;x<y.length;x++){for(;o[d][g];)g++;let w=y[x],S=w._parsedProps.colSpan??1,T=w._parsedProps.rowSpan??1;for(let I=0;I<T;I++)for(let E=0;E<S;E++)o[d+I]||(o[d+I]=[]),o[d+I][g+E]=w;g+=S}}r=Math.max(0,...o.map(d=>d.length));let s=i.map((d,_)=>d._parsedProps.height??1),a=Array.from({length:r},(d,_)=>{let y=0;for(let g=0;g<i.length;g++){let x=o[g]?.[_];if(x){let w=x._parsedProps.text??x._parsedProps.children,S=x._parsedProps.width??(w?.length??2)*.5;S>y&&(y=S)}}return y||10}),c=this._getGlobalSchematicPositionBeforeLayout(),l=t.schematic_table.insert({anchor_position:c,column_widths:a,row_heights:s,cell_padding:n.cellPadding,border_width:n.borderWidth,anchor:n.anchor,subcircuit_id:this.getSubcircuit()?.subcircuit_id||"",schematic_component_id:this.parent?.schematic_component_id||""});this.schematic_table_id=l.schematic_table_id;let u=new Set,h=0;for(let d=0;d<i.length;d++){let _=0;for(let y=0;y<r;y++){let g=o[d]?.[y];if(g&&!u.has(g)){u.add(g);let x=g._parsedProps,w=x.rowSpan??1,S=x.colSpan??1,T=0;for(let E=0;E<S;E++)T+=a[y+E];let I=0;for(let E=0;E<w;E++)I+=s[d+E];t.schematic_table_cell.insert({schematic_table_id:this.schematic_table_id,start_row_index:d,end_row_index:d+w-1,start_column_index:y,end_column_index:y+S-1,text:x.text??x.children,center:{x:c.x+_+T/2,y:c.y-h-I/2},width:T,height:I,horizontal_align:x.horizontalAlign,vertical_align:x.verticalAlign,font_size:x.fontSize??n.fontSize,subcircuit_id:this.getSubcircuit()?.subcircuit_id||""})}a[y]&&(_+=a[y])}h+=s[d]}}},DG=class extends ve{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicRow",zodProps:cD}}},$G=class extends ve{constructor(){super(...arguments);P(this,"isSchematicPrimitive",!0);P(this,"canHaveTextChildren",!0)}get config(){return{componentName:"SchematicCell",zodProps:lD}}},jG=class extends ve{constructor(){super(...arguments);P(this,"isPrimitiveContainer",!0)}get config(){return{componentName:"Symbol",zodProps:Cz}}},BG=class extends ve{get config(){return{componentName:"AnalogSimulation",zodProps:Rz}}doInitialSimulationRender(){let{db:e}=this.root,{duration:t,timePerStep:n}=this._parsedProps,i=t||10,o=n||.01;e.simulation_experiment.insert({name:"spice_transient_analysis",experiment_type:"spice_transient_analysis",end_time_ms:i,time_per_step:o})}},YG=class extends ve{constructor(){super(...arguments);P(this,"simulation_voltage_probe_id",null)}get config(){return{componentName:"VoltageProbe",zodProps:tD}}doInitialSimulationRender(){let{db:t}=this.root,{connectsTo:n,name:i}=this._parsedProps,o=this.getSubcircuit();if(!o){this.renderError("VoltageProbe must be inside a subcircuit");return}let r=Array.isArray(n)?n:[n];if(r.length!==1){this.renderError("VoltageProbe must connect to exactly one port or net");return}let s=r[0],a=o.selectOne(s,{type:"port"}),c=a?null:o.selectOne(s,{type:"net"});if(c&&c.componentName!=="Net"){this.renderError(`VoltageProbe connection target "${s}" resolved to a non-net component "${c.componentName}".`);return}if(!a&&!c){this.renderError(`VoltageProbe could not find connection target "${s}"`);return}let{simulation_voltage_probe_id:l}=t.simulation_voltage_probe.insert({name:i??this.name,source_port_id:a?.source_port_id??void 0,source_net_id:c?.source_net_id??void 0,subcircuit_id:o.subcircuit_id||void 0});this.simulation_voltage_probe_id=l}},yTt={name:"@tscircuit/core",type:"module",version:"0.0.852",types:"dist/index.d.ts",main:"dist/index.js",module:"dist/index.js",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist"],repository:{type:"git",url:"https://github.com/tscircuit/core"},scripts:{build:"tsup-node index.ts --format esm --dts",format:"biome format . --write","measure-bundle":"howfat -r table .","pkg-pr-new-release":"bunx pkg-pr-new publish --comment=off --peerDeps","smoke-test:dist":"bun run scripts/smoke-tests/test-dist-simple-circuit.tsx","build:benchmarking":"bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist","build:benchmarking:watch":`chokidar "./{benchmarking,lib}/**/*.{ts,tsx}" -c 'bun build --experimental-html ./benchmarking/website/index.html --outdir ./benchmarking-dist'`,"start:benchmarking":'concurrently "bun run build:benchmarking:watch" "live-server ./benchmarking-dist"',"generate-test-plan":"bun run scripts/generate-test-plan.ts"},devDependencies:{"@biomejs/biome":"^1.8.3","@resvg/resvg-js":"^2.6.2","@tscircuit/capacity-autorouter":"^0.0.140","@tscircuit/checks":"^0.0.85","@tscircuit/circuit-json-util":"^0.0.72","@tscircuit/common":"^0.0.20","@tscircuit/copper-pour-solver":"^0.0.12","@tscircuit/footprinter":"^0.0.236","@tscircuit/import-snippet":"^0.0.4","@tscircuit/infgrid-ijump-astar":"^0.0.33","@tscircuit/log-soup":"^1.0.2","@tscircuit/matchpack":"^0.0.16","@tscircuit/math-utils":"^0.0.29","@tscircuit/miniflex":"^0.0.4","@tscircuit/ngspice-spice-engine":"^0.0.2","@tscircuit/props":"^0.0.396","@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.302","circuit-json-to-bpc":"^0.0.13","circuit-json-to-connectivity-map":"^0.0.22","circuit-json-to-gltf":"^0.0.31","circuit-json-to-simple-3d":"^0.0.9","circuit-json-to-spice":"^0.0.16","circuit-to-svg":"^0.0.260",concurrently:"^9.1.2","connectivity-map":"^1.0.0",debug:"^4.3.6","eecircuit-engine":"^1.5.6",flatbush:"^4.5.0","graphics-debug":"^0.0.60",howfat:"^0.3.8","live-server":"^1.2.2","looks-same":"^9.0.1",minicssgrid:"^0.0.9","pkg-pr-new":"^0.0.37",poppygl:"^0.0.16",react:"^19.1.0","react-dom":"^19.1.0","schematic-symbols":"^0.0.202",spicey:"^0.0.10","ts-expect":"^1.3.0",tsup:"^8.2.4"},peerDependencies:{"@tscircuit/capacity-autorouter":"*","@tscircuit/checks":"*","@tscircuit/circuit-json-util":"*","@tscircuit/footprinter":"*","@tscircuit/infgrid-ijump-astar":"*","@tscircuit/math-utils":"*","@tscircuit/props":"*","@tscircuit/schematic-autolayout":"*","@tscircuit/schematic-match-adapt":"*","circuit-json-to-bpc":"*","bpc-graph":"*","@tscircuit/matchpack":"*","circuit-json":"*","circuit-json-to-connectivity-map":"*","schematic-symbols":"*",typescript:"^5.0.0"},dependencies:{"@flatten-js/core":"^1.6.2","@lume/kiwi":"^0.4.3","calculate-packing":"0.0.50","css-select":"5.1.0","format-si-unit":"^0.0.3",nanoid:"^5.0.7","performance-now":"^2.1.0","react-reconciler":"^0.32.0","transformation-matrix":"^2.16.1",zod:"^3.25.67"}},Xh=class{constructor({platform:e,projectUrl:t}={}){P(this,"firstChild",null);P(this,"children");P(this,"db");P(this,"root",null);P(this,"isRoot",!0);P(this,"schematicDisabled",!1);P(this,"pcbDisabled",!1);P(this,"pcbRoutingDisabled",!1);P(this,"_featureMspSchematicTraceRouting",!0);P(this,"name");P(this,"platform");P(this,"projectUrl");P(this,"_hasRenderedAtleastOnce",!1);P(this,"_eventListeners",{});this.children=[],this.db=Oe([]),this.root=this,this.platform=e,this.projectUrl=t,this.pcbDisabled=e?.pcbDisabled??!1}add(e){let t;(0,XG.isValidElement)(e)?t=gH(e):t=e,this.children.push(t)}setPlatform(e){this.platform={...this.platform,...e}}_getBoard(){let e=this.children.find(t=>t.componentName==="Board");if(e)return e}_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 e=this.children.filter(n=>n.lowercaseComponentName==="panel");if(e.length>1)throw new Error("Only one <panel> is allowed per circuit");if(e.length===1){if(this.children.length!==1)throw new Error("<panel> must be the root element of the circuit");this.firstChild=e[0];return}if(this.children.length===1&&this.children[0].isGroup){this.firstChild=this.children[0];return}let t=new Ic({subcircuit:!0});t.parent=this,t.addAll(this.children),this.children=[t],this.firstChild=t}render(){this.firstChild||this._guessRootComponent();let{firstChild:e,db:t}=this;if(!e)throw new Error("RootCircuit has no root component");e.parent=this,e.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(t=>setTimeout(t,100)),this.render();this.emit("renderComplete")}_hasIncompleteAsyncEffects(){return this.children.some(e=>e._hasIncompleteAsyncEffects()?!0:e.children.some(t=>t._hasIncompleteAsyncEffects()))}getCircuitJson(){return this._hasRenderedAtleastOnce||this.render(),this.db.toArray()}toJson(){return this.getCircuitJson()}async getSvg(e){let t=await Promise.resolve().then(()=>(jV(),$V)).catch(n=>{throw new Error(`To use circuit.getSvg, you must install the "circuit-to-svg" package.
|
|
252
252
|
|
|
253
|
-
"${n.message}"`)});if(e.view==="pcb")return t.convertCircuitJsonToPcbSvg(this.getCircuitJson());if(e.view==="schematic")return t.convertCircuitJsonToSchematicSvg(this.getCircuitJson());throw new Error(`Invalid view: ${e.view}`)}getCoreVersion(){let[e,t,n]=yTt.version.split(".").map(Number);return`${e}.${t}.${n+1}`}async preview(e){let t=typeof e=="object"?e:{previewName:e};throw new Error("project.preview is not yet implemented")}computeSchematicGlobalTransform(){return zi()}_computePcbGlobalTransformBeforeLayout(){return zi()}selectAll(e){return this._guessRootComponent(),this.firstChild?.selectAll(e)??[]}selectOne(e,t){return this._guessRootComponent(),this.firstChild?.selectOne(e,t)??null}emit(e,...t){if(this._eventListeners[e])for(let n of this._eventListeners[e])n(...t)}on(e,t){this._eventListeners[e]||(this._eventListeners[e]=[]),this._eventListeners[e].push(t)}removeListener(e,t){this._eventListeners[e]&&(this._eventListeners[e]=this._eventListeners[e].filter(n=>n!==t))}enableDebug(e){typeof e=="string"?N4.default.enable(e):(e===null||e===!1)&&N4.default.disable()}getClientOrigin(){return typeof window<"u"&&window.location?window.location.origin:typeof self<"u"&&self.location?self.location.origin:""}},gTt=Xh,bTt=Xh,xTt=e=>{let[t,n]=Dh.default.useState(!0),[i,o]=Dh.default.useState(null),[r,s]=Dh.default.useState(),[a,c]=Dh.default.useState();return Dh.default.useEffect(()=>{n(!0),o(null),e&&setTimeout(()=>{try{let l=new Xh;l.add(e),s(l),c(l.toJson())}catch(l){o(l)}n(!1)},1)},[e]),{isLoading:t,error:i,circuit:r,circuitJson:a}},Vh=(e,t)=>(n,i)=>{let o=[];Array.isArray(t)?o.push(...t.flat()):typeof t=="object"&&o.push(...Object.values(t).flat(),...Object.keys(t));let r=s=>{if(s?.name&&s.name!==n)throw new Error(`Component name mismatch. Hook name: ${n}, Component prop name: ${s.name}`);let a={...i,...s,name:n},c=[];for(let l of o)if(a[l]){let u=`.${n} > .${l}`,h=a[l];c.push({from:u,to:h}),delete a[l]}return(0,fu.jsxs)(fu.Fragment,{children:[(0,fu.jsx)(e,{...a}),c.map((l,u)=>(0,fu.jsx)("trace",{...l},u))]})};for(let s of o)r[s]=`.${n} > .${s}`;return r},vTt=Vh(e=>(0,VG.jsx)("capacitor",{...e}),vz),STt=e=>Vh(t=>(0,HG.jsx)("chip",{pinLabels:e,...t}),e),wTt=Vh(e=>(0,GG.jsx)("diode",{...e}),Dz),PTt=Vh(e=>(0,UG.jsx)("led",{...e}),jz),ITt=Vh(e=>(0,qG.jsx)("resistor",{...e}),_z),TTt=new Proxy(e=>new Proxy({},{get:(t,n)=>`.${e} > .${n}`}),{get:(e,t)=>{let n=(...i)=>{let o=i[0];return new Proxy({},{get:(r,s)=>`.${t} > .${s}`})};return new Proxy(n,{get:(i,o)=>t==="net"?`net.${o}`:t==="subcircuit"?new Proxy({},{get:(r,s)=>new Proxy({},{get:(a,c)=>`subcircuit.${o} > .${s} > .${c}`})}):`.${t} > .${o}`,apply:(i,o,r)=>t==="net"?new Proxy({},{get:(s,a)=>`net.${a}`}):new Proxy({},{get:(s,a)=>{let c=`.${t} > .${a}`;return["U","J","CN"].some(u=>t.startsWith(u))?c:new Proxy(new String(c),{get:(u,h)=>typeof h=="symbol"||h==="toString"?()=>c:`.${t} > .${a} > .${h}`})}})})}});yH(hH);yH({Bug:Rm});var fU=Xt(Tr(),1);var ZG=e=>{let t=e.match(/:[RC]_(\d{4})_/);if(t||(t=e.match(/:(SOIC-\d+|SOT-\d+|SOD-\d+|SSOP-\d+|TSSOP-\d+|QFP-\d+|QFN-\d+)/),t))return t[1]};var j4=e=>e.includes("cap")?e.replace(/cap/g,""):e;var KG=e=>{if(e){if(e.startsWith("kicad:")){let t=ZG(e);return t?j4(t):e}return j4(e)}};var B4=new Map,lo=async(e,t)=>{let n=new URLSearchParams({...t,json:"true"}).toString();if(B4.has(n))return B4.get(n);let o=await(await fetch(`https://jlcsearch.tscircuit.com/${e}/list?${n}`)).json();return B4.set(n,o),o},uo=e=>e?[...e].sort((t,n)=>Number(n.is_basic??!1)-Number(t.is_basic??!1)):[],JG={findPart:async({sourceComponent:e,footprinterString:t})=>{let n=KG(t);if(e.type==="source_component"&&e.ftype==="simple_resistor"){let{resistors:i}=await lo("resistors",{resistance:e.resistance,package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_capacitor"){let{capacitors:i}=await lo("capacitors",{capacitance:e.capacitance,package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_pin_header"){let i;t?.includes("_p")&&(i=Number(t.split("_p")[1]));let{headers:o}=await lo("headers",i?{pitch:i,num_pins:e.pin_count,gender:e.gender}:{num_pins:e.pin_count,gender:e.gender});return{jlcpcb:uo(o).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_potentiometer"){let{potentiometers:i}=await lo("potentiometers",{resistance:e.max_resistance,package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_diode"){let{diodes:i}=await lo("diodes",{package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_chip"){let{chips:i}=await lo("chips",{package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_transistor"){let{transistors:i}=await lo("transistors",{package:n,transistor_type:e.transistor_type});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_power_source"){let{power_sources:i}=await lo("power_sources",{voltage:e.voltage,package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_inductor"){let{inductors:i}=await lo("inductors",{inductance:e.inductance,package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_crystal"){let{crystals:i}=await lo("crystals",{frequency:e.frequency,load_capacitance:e.load_capacitance,package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_mosfet"){let{mosfets:i}=await lo("mosfets",{package:n,mosfet_mode:e.mosfet_mode,channel_type:e.channel_type});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_resonator"){let{resonators:i}=await lo("resonators",{frequency:e.frequency,package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_switch"){let{switches:i}=await lo("switches",{switch_type:e.type,package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_led"){let{leds:i}=await lo("leds",{package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_fuse"){let{fuses:i}=await lo("fuses",{package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}return{}}};var nU=Xt(QG(),1);Z();var aU=Xt(Sn(),1),cU=Xt(Sn(),1),ii=p.tuple([p.coerce.number(),p.coerce.number()]),FTt=p.tuple([p.number(),p.number(),p.number()]),Xx=p.union([ii,FTt]),zTt=p.object({kind:p.literal("arc"),start:ii,mid:ii,end:ii}),DTt=p.union([ii,zTt]),iU=p.object({at:Xx,size:ii,layer:p.string(),layers:p.array(p.string()),roundrect_rratio:p.number(),uuid:p.string()}).partial(),$Tt=p.object({key:p.string(),val:p.string(),attributes:iU}),jx=p.object({oval:p.boolean().default(!1),width:p.number().optional(),height:p.number().optional(),offset:ii.optional()}),oU=p.object({name:p.string(),pad_type:p.enum(["thru_hole","smd","np_thru_hole","connect"]),pad_shape:p.enum(["roundrect","circle","rect","oval","trapezoid","custom"]),at:Xx,drill:p.union([p.number(),p.array(p.any()),jx]).transform(e=>typeof e=="number"?{oval:!1,width:e,height:e}:"oval"in e?e:e.length===2?{oval:!1,width:Number.parseFloat(e[0]),height:Number.parseFloat(e[0]),offset:ii.parse(e[1].slice(1))}:e.length===3||e.length===4?{oval:e[0]==="oval",width:Number.parseFloat(e[1]),height:Number.parseFloat(e[2]),offset:e[3]?ii.parse(e[3].slice(1)):void 0}:e).pipe(jx),size:p.union([p.array(p.number()).length(2).transform(([e,t])=>({width:e,height:t})),p.object({width:p.number(),height:p.number()})]),layers:p.array(p.string()).optional(),roundrect_rratio:p.number().optional(),uuid:p.string().optional()}),rU=p.object({name:p.string(),pad_type:p.enum(["thru_hole","smd","np_thru_hole","connect"]),pad_shape:p.enum(["roundrect","circle","rect","oval","trapezoid","custom"]),at:Xx,size:ii,drill:p.union([p.number(),p.array(p.any()),jx]).transform(e=>typeof e=="number"?{oval:!1,width:e,height:e}:"oval"in e?e:e.length===2?{oval:!1,width:Number.parseFloat(e[0]),height:Number.parseFloat(e[0]),offset:ii.parse(e[1].slice(1))}:e.length===3||e.length===4?{oval:e[0]==="oval",width:Number.parseFloat(e[1]),height:Number.parseFloat(e[2]),offset:e[3]?ii.parse(e[3].slice(1)):void 0}:e).pipe(jx).optional(),layers:p.array(p.string()).optional(),roundrect_rratio:p.number().optional(),chamfer_ratio:p.number().optional(),solder_paste_margin:p.number().optional(),solder_paste_margin_ratio:p.number().optional(),clearance:p.number().optional(),zone_connection:p.union([p.literal(0).describe("Pad is not connect to zone"),p.literal(1).describe("Pad is connected to zone using thermal relief"),p.literal(2).describe("Pad is connected to zone using solid fill")]).optional(),thermal_width:p.number().optional(),thermal_gap:p.number().optional(),uuid:p.string().optional()}),sU=p.object({font:p.object({size:ii,thickness:p.number().optional()})}).partial(),jTt=p.object({fp_text_type:p.literal("user"),text:p.string(),at:Xx,layer:p.string(),uuid:p.string().optional(),effects:sU.partial()}),BTt=p.object({start:ii,mid:ii,end:ii,stroke:p.object({width:p.number(),type:p.string()}),layer:p.string(),uuid:p.string().optional()}),YTt=p.object({center:ii,end:ii,stroke:p.object({width:p.number(),type:p.string()}),fill:p.string().optional(),layer:p.string(),uuid:p.string().optional()}),XTt=p.object({pts:p.array(DTt),stroke:p.object({width:p.number(),type:p.string()}).optional(),width:p.number().optional(),layer:p.string(),uuid:p.string().optional(),fill:p.string().optional()}).transform(e=>({...e,width:void 0,stroke:e.stroke??{width:e.width}})),VTt=p.object({start:ii,end:ii,stroke:p.object({width:p.number(),type:p.string()}).optional(),width:p.number().optional(),layer:p.string(),uuid:p.string().optional()}).transform(e=>({...e,width:void 0,stroke:e.stroke??{width:e.width}})),tU=p.object({footprint_name:p.string(),version:p.string().optional(),generator:p.string().optional(),generator_version:p.string().optional(),layer:p.string(),descr:p.string().default(""),tags:p.array(p.string()).optional(),properties:p.array($Tt),fp_lines:p.array(VTt),fp_texts:p.array(jTt),fp_arcs:p.array(BTt),fp_circles:p.array(YTt).optional(),fp_polys:p.array(XTt).optional(),pads:p.array(rU),holes:p.array(oU).optional()}),Bx=(e,t)=>{if(t==="effects"&&Array.isArray(e)){let n={};for(let i of e)if(i[0]==="font"){let o={};for(let r of i.slice(1))r.length===2?o[r[0].valueOf()]=Number.parseFloat(r[1].valueOf()):o[r[0].valueOf()]=r.slice(1).map(s=>Number.parseFloat(s.valueOf()));n.font=o}return sU.parse(n)}if(t==="pts")return e.map(n=>{let i=n[0]?.valueOf?.()??n[0];if(i==="xy")return n.slice(1).map(o=>Number.parseFloat(o.valueOf()));if(i==="arc"){let o={kind:"arc"};for(let r of n.slice(1)){let s=r[0].valueOf();o[s]=r.slice(1).map(a=>Number.parseFloat(a.valueOf()))}return o}return n});if(t==="stroke"){let n={};for(let i of e){let o=i[0].valueOf();n[o]=Bx(i.slice(1),o)}return n}return t==="at"||t==="size"||t==="start"||t==="mid"||t==="end"?(Array.isArray(e)?e:[e]).map(i=>i?.valueOf?.()??i).filter(i=>typeof i=="number"||typeof i=="string"&&/^[-+]?\d*\.?\d+(e[-+]?\d+)?$/i.test(i)).map(i=>typeof i=="number"?i:Number.parseFloat(i)):t==="tags"?e.map(n=>n.valueOf()):t==="generator_version"||t==="version"?e[0].valueOf():e.length===2?e.valueOf():t==="uuid"?Array.isArray(e)?e[0].valueOf():e.valueOf():/^[\d\.]+$/.test(e)&&!Number.isNaN(Number.parseFloat(e))?Number.parseFloat(e):Array.isArray(e)&&e.length===1?e[0].valueOf():Array.isArray(e)?e.map(n=>n.valueOf()):e},Re=(e,t)=>{for(let n of e)if(Array.isArray(n)&&n[0]===t)return Bx(n.slice(1),t)},Y4=(0,aU.default)("kicad-mod-converter"),HTt=e=>{let t=(0,nU.default)(e),n=t[1].valueOf(),i={},o=Object.entries(tU.shape).filter(([T,I])=>I._def.typeName==="ZodString"||T==="tags").map(([T])=>T);for(let T of t.slice(2)){if(!o.includes(T[0]))continue;let I=T[0].valueOf(),E=Bx(T.slice(1),I);i[I]=E}let r=t.slice(2).filter(T=>T[0]==="property").map(T=>{let I=T[1].valueOf(),E=T[2].valueOf(),M=iU.parse(T.slice(3).reduce((k,N)=>{let A=N[0].valueOf();return k[A]=Bx(N.slice(1),A),k},{}));return{key:I,val:E,attributes:M}}),s=t.slice(2).filter(T=>T[0]==="pad"),a=[];for(let T of s){let I=Re(T,"at"),E=Re(T,"size"),M=Re(T,"drill"),k=Re(T,"layers");if(Array.isArray(k)?k=k.map($=>$.valueOf()):typeof k=="string"?k=[k]:k||(k=[]),!k.includes("F.Cu")){Y4(`Skipping pad without F.Cu layer: layers=${k.join(", ")}`);continue}let N=Re(T,"roundrect_rratio"),A=Re(T,"uuid"),R={name:T[1].valueOf(),pad_type:T[2].valueOf(),pad_shape:T[3].valueOf(),at:I,drill:M,size:E,layers:k,roundrect_rratio:N,uuid:A};Y4(`attempting to parse pad: ${JSON.stringify(R,null," ")}`),a.push(rU.parse(R))}let c=t.slice(2).filter(T=>T[0]==="fp_text"),l=[];for(let T of c){let I=T[2].valueOf(),E=Re(T,"at"),M=Re(T,"layer"),k=Re(T,"uuid"),N=Re(T,"effects");l.push({fp_text_type:"user",text:I,at:E,layer:M,uuid:k,effects:N})}let u=[],h=t.slice(2).filter(T=>T[0]==="fp_line");for(let T of h){let I=Re(T,"start"),E=Re(T,"end"),M=Re(T,"stroke"),k=Re(T,"layer"),N=Re(T,"uuid");u.push({start:I,end:E,stroke:M,layer:k,uuid:N})}let d=[],_=t.slice(2).filter(T=>T[0]==="fp_arc");for(let T of _){let I=Re(T,"start"),E=Re(T,"mid"),M=Re(T,"end"),k=Re(T,"stroke"),N=Re(T,"layer"),A=Re(T,"uuid");!I||!M||!E||!k||!N||d.push({start:I,mid:E,end:M,stroke:k,layer:N,uuid:A})}let y=[],g=t.slice(2).filter(T=>T[0]==="fp_circle");for(let T of g){let I=Re(T,"center"),E=Re(T,"end"),M=Re(T,"stroke"),k=Re(T,"fill"),N=Re(T,"layer"),A=Re(T,"uuid");!I||!E||!M||!N||y.push({center:I,end:E,stroke:M,fill:k,layer:N,uuid:A})}let x=[],w=t.slice(2).filter(T=>T[0]==="fp_poly");for(let T of w){let I=Re(T,"pts"),E=Re(T,"stroke"),M=Re(T,"width"),k=Re(T,"layer"),N=Re(T,"uuid"),A=Re(T,"fill"),R=E;!R&&typeof M=="number"?R={width:M,type:"solid"}:R&&typeof R=="object"&&typeof M=="number"&&R.width===void 0&&(R={...R,width:M}),x.push({pts:I,stroke:R,layer:k,uuid:N,fill:A})}let S=[];for(let T of t.slice(2)){if(T[0]!=="pad"||T[2]?.valueOf?.()!=="thru_hole")continue;let I=T[1]?.valueOf?.(),E=T[2]?.valueOf?.(),M=T[3]?.valueOf?.(),k=Re(T,"at"),N=Re(T,"drill"),A=Re(T,"size");Array.isArray(A)&&(A[0]==="size"&&(A=A.slice(1)),A={width:Number(A[0]),height:Number(A[1])});let R=Re(T,"uuid"),$=Re(T,"roundrect_rratio"),j=Re(T,"layers");Array.isArray(j)?j=j.map(X=>X.valueOf()):typeof j=="string"?j=[j]:j||(j=[]);let H={name:I,pad_type:E,pad_shape:M,at:k,drill:N,size:A,layers:j,roundrect_rratio:$,uuid:R};Y4(`attempting to parse holes: ${JSON.stringify(H,null,2)}`),S.push(oU.parse(H))}return tU.parse({footprint_name:n,...i,properties:r,fp_lines:u,fp_texts:l,fp_arcs:d,fp_circles:y,pads:a,holes:S,fp_polys:x})},Om=Math.PI*2,eU=e=>{let t=e%Om;return t<0&&(t+=Om),t},Yx=(e,t)=>{let n=eU(e),o=eU(t)-n;return o<0&&(o+=Om),o};function lU(e,t,n){let i={x:(e.x+t.x)/2,y:(e.y+t.y)/2},o={x:(t.x+n.x)/2,y:(t.y+n.y)/2},r=-(e.x-t.x)/(e.y-t.y),s=-(t.x-n.x)/(t.y-n.y),a=(i.y-o.y+s*o.x-r*i.x)/(s-r),c=i.y+r*(a-i.x);return{x:a,y:c}}function uU(e,t){return Math.sqrt((e.x-t.x)**2+(e.y-t.y)**2)}function Gh(e,t){return Math.atan2(t.y-e.y,t.x-e.x)}var G4=(e,t,n)=>{let i=lU(e,t,n),o=uU(i,e),r=Gh(i,e),s=Gh(i,t),a=Gh(i,n),c=Yx(r,s),l=Yx(r,a),u=l;return c>l&&(u=l-Om),Math.abs(o*u)};function U4(e,t,n,i){let o=lU(e,t,n),r=uU(o,e),s=Gh(o,e),a=Gh(o,t),c=Gh(o,n),l=Yx(s,a),u=Yx(s,c),h=u;l>u&&(h=u-Om);let d=[];for(let _=0;_<=i;_++){let y=s+_/i*h,g=o.x+r*Math.cos(y),x=o.y+r*Math.sin(y);d.push({x:g,y:x})}return d}var Tc=e=>Array.isArray(e)?{x:e[0],y:e[1]}:e,X4=(e,t,n=1e-4)=>Math.abs(e.x-t.x)<n&&Math.abs(e.y-t.y)<n,GTt=e=>{let t=[],n=new Set;for(let i=0;i<e.length;i++){if(n.has(i))continue;let o=[e[i]];n.add(i);let r=e[i].end,s=!0;for(;s;){if(s=!1,o.length>1&&X4(r,o[0].start)){t.push(o);break}for(let a=0;a<e.length;a++)if(!n.has(a)){if(X4(r,e[a].start)){o.push(e[a]),n.add(a),r=e[a].end,s=!0;break}else if(X4(r,e[a].end)){e[a].type==="arc"?o.push({...e[a],reversed:!0}):o.push({...e[a],start:e[a].end,end:e[a].start}),n.add(a),r=e[a].start,s=!0;break}}if(!s){for(let a=o.length-1;a>=0;a--){let c=e.indexOf(o[a]);c!==-1&&n.delete(c)}break}}}return t},UTt=e=>{let t=[];for(let n of e)if(n.type==="line")t.push(n.start);else if(n.type==="arc"&&n.mid){let i=G4(n.start,n.mid,n.end),o=Math.max(3,Math.ceil(i)),r=U4(n.start,n.mid,n.end,o);n.reversed&&(r=r.reverse()),t.push(...r.slice(0,-1))}return t};function qTt(e){if(!Array.isArray(e))return null;let t=e.find(s=>s.layer?.toLowerCase()==="f.silks"&&(s.text?.includes("${REFERENCE}")||s.fp_text_type?.toLowerCase()==="reference"||s.text?.match(/^R\d+|C\d+|U\d+/))),n=t||e.find(s=>s.layer?.toLowerCase()==="f.fab"&&(s.text?.includes("${REFERENCE}")||s.fp_text_type?.toLowerCase()==="reference")),i=t||n;if(!i?.effects?.font?.size)return null;let[o,r]=i.effects.font.size;return r??o??1}var WTt=e=>e*Math.PI/180,V4=(e,t,n)=>{let i=WTt(n),o=Math.cos(i),r=Math.sin(i);return{x:e*o-t*r,y:e*r+t*o}},ZTt=e=>{let t=[...new Map(e.map(u=>[`${u.x},${u.y}`,u])).values()];if(t.length!==4)return null;let n=t.map(u=>u.x),i=t.map(u=>u.y),o=[...new Set(n)],r=[...new Set(i)];if(o.length!==2||r.length!==2)return null;let[s,a]=o.sort((u,h)=>u-h),[c,l]=r.sort((u,h)=>u-h);return s===void 0||a===void 0||c===void 0||l===void 0?null:{x:(s+a)/2,y:(c+l)/2,width:a-s,height:l-c}},KTt=e=>{if(!e)return!1;let t=e.toLowerCase();return t!=="no"&&t!=="none"&&t!=="outline"},H4=e=>e&&Array.isArray(e)&&e.length>=3&&typeof e[2]=="number"?e[2]:0,Co=e=>{let t=(e%360+360)%360;return t===90||t===270},Hh=(0,cU.default)("kicad-mod-converter"),mr=e=>{switch(e.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"}},JTt=async e=>{let{fp_lines:t,fp_texts:n,fp_arcs:i,fp_circles:o,pads:r,properties:s,holes:a,fp_polys:c}=e,l=[];l.push({type:"source_component",source_component_id:"source_component_0",supplier_part_numbers:{}}),l.push({type:"schematic_component",schematic_component_id:"schematic_component_0",source_component_id:"source_component_0",center:{x:0,y:0},rotation:0,size:{width:0,height:0}});let u=new Set;for(let V of r)V.name&&u.add(V.name);if(a)for(let V of a)V.name&&u.add(V.name);let h=0,d=new Map;for(let V of u){let rt=`source_port_${h++}`;d.set(V,rt),l.push({type:"source_port",source_port_id:rt,source_component_id:"source_component_0",name:V,port_hints:[V]}),l.push({type:"schematic_port",schematic_port_id:`schematic_port_${h++}`,source_port_id:rt,schematic_component_id:"schematic_component_0",center:{x:0,y:0}})}let _=Number.POSITIVE_INFINITY,y=Number.NEGATIVE_INFINITY,g=Number.POSITIVE_INFINITY,x=Number.NEGATIVE_INFINITY;for(let V of r){let rt=V.at[0],et=-V.at[1],J=V.size[0],pt=V.size[1];_=Math.min(_,rt-J/2),y=Math.max(y,rt+J/2),g=Math.min(g,et-pt/2),x=Math.max(x,et+pt/2)}let w="pcb_component_0";l.push({type:"pcb_component",source_component_id:"source_component_0",pcb_component_id:w,layer:"top",center:{x:0,y:0},rotation:0,width:Number.isFinite(_)?y-_:0,height:Number.isFinite(g)?x-g:0});let S=0,T=new Map;for(let V of u){let rt=`pcb_port_${S++}`,et=d.get(V);T.set(V,rt);let J=0,pt=0,dt=["top","bottom"],St=r.find(wt=>wt.name===V);if(St)J=St.at[0],pt=-St.at[1],dt=St.layers?St.layers.map(wt=>mr(wt)).filter(Boolean):["top","bottom"];else if(a){let wt=a.find(lt=>lt.name===V);wt&&(J=wt.at[0],pt=-wt.at[1],dt=wt.layers?wt.layers.map(lt=>mr(lt)).filter(Boolean):["top","bottom"])}l.push({type:"pcb_port",pcb_port_id:rt,source_port_id:et,pcb_component_id:w,x:J,y:pt,layers:dt})}let I=0,E=0,M=0;for(let V of r)if(V.pad_type==="smd"){let rt=H4(V.at),et=Co(rt)?V.size[1]:V.size[0],J=Co(rt)?V.size[0]:V.size[1],pt=V.name?T.get(V.name):void 0;l.push({type:"pcb_smtpad",pcb_smtpad_id:`pcb_smtpad_${I++}`,shape:"rect",x:V.at[0],y:-V.at[1],width:et,height:J,layer:mr(V.layers?.[0]??"F.Cu"),pcb_component_id:w,port_hints:[V.name],pcb_port_id:pt})}else if(V.pad_type==="thru_hole"){if(V.pad_shape==="rect"){let rt=H4(V.at),et=Co(rt)?V.size[1]:V.size[0],J=Co(rt)?V.size[0]:V.size[1],pt=V.drill?.offset?.[0]??0,dt=V.drill?.offset?.[1]??0,St=V4(pt,dt,rt),wt=V.name?T.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"circular_hole_with_rect_pad",hole_shape:"circle",pad_shape:"rect",x:V.at[0],y:-V.at[1],hole_offset_x:St.x,hole_offset_y:-St.y,hole_diameter:V.drill?.width,rect_pad_width:et,rect_pad_height:J,layers:["top","bottom"],pcb_component_id:w,port_hints:[V.name],pcb_port_id:wt})}else if(V.pad_shape==="circle"){let rt=V.name?T.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"circle",x:V.at[0],y:-V.at[1],outer_diameter:V.size[0],hole_diameter:V.drill?.width,layers:["top","bottom"],pcb_component_id:w,port_hints:[V.name],pcb_port_id:rt})}else if(V.pad_shape==="oval"){let rt=V.name?T.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"pill",x:V.at[0],y:-V.at[1],outer_width:V.size[0],outer_height:V.size[1],hole_width:V.drill?.width,hole_height:V.drill?.height,layers:["top","bottom"],pcb_component_id:w,port_hints:[V.name],pcb_port_id:rt})}}else V.pad_type==="np_thru_hole"&&l.push({type:"pcb_hole",pcb_hole_id:`pcb_hole_${M++}`,x:V.at[0],y:-V.at[1],hole_diameter:V.drill?.width,pcb_component_id:w});if(a)for(let V of a){let rt=V.layers?.some(ht=>ht.endsWith(".Cu")||ht==="*.Cu"),et=H4(V.at),J=V.drill?.offset?.[0]??0,pt=V.drill?.offset?.[1]??0,dt=V4(J,pt,et),St=V.at[0]+dt.x,wt=-(V.at[1]+dt.y),lt=V.drill?.width??0,B=V.size?.width??lt,q=V.roundrect_rratio??0,it=q>0?Math.min(Co(et)?V.size?.height??B:V.size?.width??B,Co(et)?V.size?.width??B:V.size?.height??B)/2*q:0;if(rt)if(V.pad_shape==="rect"){let ht=V.name?T.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"circular_hole_with_rect_pad",hole_shape:"circle",pad_shape:"rect",x:V.at[0],y:-V.at[1],hole_offset_x:dt.x,hole_offset_y:-dt.y,hole_diameter:lt,rect_pad_width:Co(et)?V.size?.height??B:V.size?.width??B,rect_pad_height:Co(et)?V.size?.width??B:V.size?.height??B,rect_border_radius:it,port_hints:[V.name],layers:["top","bottom"],pcb_component_id:w,pcb_port_id:ht})}else if(V.pad_shape==="oval"){let ht=V.name?T.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"pill",x:St,y:wt,outer_width:Co(et)?V.size?.height??B:V.size?.width??B,outer_height:Co(et)?V.size?.width??B:V.size?.height??B,hole_width:Co(et)?V.drill?.height??lt:V.drill?.width??lt,hole_height:Co(et)?V.drill?.width??lt:V.drill?.height??lt,port_hints:[V.name],layers:["top","bottom"],pcb_component_id:w,pcb_port_id:ht})}else if(V.pad_shape==="roundrect"){let ht=V.name?T.get(V.name):void 0,at=V.drill?.offset?.[0]??0,K=V.drill?.offset?.[1]??0,ut=V4(at,K,et),Mt=Co(et)?V.size?.height??B:V.size?.width??B,zt=Co(et)?V.size?.width??B:V.size?.height??B;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"circular_hole_with_rect_pad",hole_shape:"circle",pad_shape:"rect",x:St,y:wt,hole_offset_x:ut.x,hole_offset_y:-ut.y,hole_diameter:lt,rect_pad_width:Mt,rect_pad_height:zt,rect_border_radius:it,port_hints:[V.name],layers:["top","bottom"],pcb_component_id:w,pcb_port_id:ht})}else{let ht=V.name?T.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"circle",x:St,y:wt,outer_diameter:B,hole_diameter:lt,port_hints:[V.name],layers:["top","bottom"],pcb_component_id:w,pcb_port_id:ht})}else l.push({type:"pcb_hole",pcb_hole_id:`pcb_hole_${M++}`,x:St,y:wt,hole_diameter:B,hole_shape:"circle",pcb_component_id:w})}let k=[];for(let V of t)V.layer.toLowerCase()==="edge.cuts"&&k.push({type:"line",start:{x:V.start[0],y:V.start[1]},end:{x:V.end[0],y:V.end[1]},strokeWidth:V.stroke.width});for(let V of i)V.layer.toLowerCase()==="edge.cuts"&&k.push({type:"arc",start:{x:V.start[0],y:V.start[1]},mid:{x:V.mid[0],y:V.mid[1]},end:{x:V.end[0],y:V.end[1]},strokeWidth:V.stroke.width});let N=GTt(k),A=0;for(let V of N){let rt=UTt(V);rt.length>=3&&l.push({type:"pcb_cutout",pcb_cutout_id:`pcb_cutout_${A++}`,shape:"polygon",points:rt.map(et=>({x:et.x,y:-et.y})),pcb_component_id:w})}let R=0,$=0,j=0,H=0;for(let V of t){let rt=[{x:V.start[0],y:-V.start[1]},{x:V.end[0],y:-V.end[1]}],et=V.layer.toLowerCase();et==="f.cu"?l.push({type:"pcb_trace",pcb_trace_id:`pcb_trace_${R++}`,pcb_component_id:w,layer:mr(V.layer),route:rt,thickness:V.stroke.width}):et==="f.silks"?l.push({type:"pcb_silkscreen_path",pcb_silkscreen_path_id:`pcb_silkscreen_path_${$++}`,pcb_component_id:w,layer:"top",route:rt,stroke_width:V.stroke.width}):et==="edge.cuts"?Hh("Skipping Edge.Cuts fp_line (converted to pcb_cutout)",V.layer):et==="f.fab"?l.push({type:"pcb_fabrication_note_path",fabrication_note_path_id:`fabrication_note_path_${j++}`,pcb_component_id:w,layer:"top",route:rt,stroke_width:V.stroke.width,port_hints:[]}):et.startsWith("user.")?l.push({type:"pcb_note_line",pcb_note_line_id:`pcb_note_line_${H++}`,pcb_component_id:w,x1:V.start[0],y1:-V.start[1],x2:V.end[0],y2:-V.end[1],stroke_width:V.stroke.width}):Hh("Unhandled layer for fp_line",V.layer)}if(c)for(let V of c){let rt=[],et=wt=>{!Number.isFinite(wt.x)||!Number.isFinite(wt.y)||rt.push(wt)};for(let wt of V.pts){if(Array.isArray(wt)){et({x:wt[0],y:-wt[1]});continue}if(wt&&typeof wt=="object"&&"kind"in wt){if(wt.kind==="arc"){let lt=Tc(wt.start),B=Tc(wt.mid),q=Tc(wt.end),it=G4(lt,B,q),ht=Math.max(8,Math.ceil(it)),at=Math.max(2,Math.ceil(it/.1)),K=U4(lt,B,q,at).map(ut=>({x:ut.x,y:-ut.y}));for(let ut of K)et(ut)}continue}}let J=rt,dt=J.length>2&&J[0].x===J[J.length-1].x&&J[0].y===J[J.length-1].y?J.slice(0,-1):J;if(J.length===0)continue;let St=V.stroke?.width??0;if(V.layer.endsWith(".Cu")){let wt=ZTt(dt);wt?l.push({type:"pcb_smtpad",pcb_smtpad_id:`pcb_smtpad_${I++}`,shape:"rect",x:wt.x,y:wt.y,width:wt.width,height:wt.height,layer:mr(V.layer),pcb_component_id:w}):KTt(V.fill)?dt.length>=3?l.push({type:"pcb_smtpad",pcb_smtpad_id:`pcb_smtpad_${I++}`,shape:"polygon",points:dt,layer:mr(V.layer),pcb_component_id:w}):dt.length>=2&&l.push({type:"pcb_trace",pcb_trace_id:`pcb_trace_${R++}`,pcb_component_id:w,layer:mr(V.layer),route:dt,thickness:St}):dt.length>=2&&l.push({type:"pcb_trace",pcb_trace_id:`pcb_trace_${R++}`,pcb_component_id:w,layer:mr(V.layer),route:dt,thickness:St})}else V.layer.endsWith(".SilkS")?l.push({type:"pcb_silkscreen_path",pcb_silkscreen_path_id:`pcb_silkscreen_path_${$++}`,pcb_component_id:w,layer:mr(V.layer),route:J,stroke_width:St}):V.layer.endsWith(".Fab")?l.push({type:"pcb_fabrication_note_path",fabrication_note_path_id:`fabrication_note_path_${j++}`,pcb_component_id:w,layer:mr(V.layer),route:dt,stroke_width:St,port_hints:[]}):Hh("Unhandled layer for fp_poly",V.layer)}let X=0;for(let V of i){let rt=V.layer.toLowerCase();if(rt==="edge.cuts"){Hh("Skipping Edge.Cuts fp_arc (converted to pcb_cutout)",V.layer);continue}let et=Tc(V.start),J=Tc(V.mid),pt=Tc(V.end),dt=G4(et,J,pt),St=U4(et,J,pt,Math.ceil(dt));if(rt.startsWith("user.")){l.push({type:"pcb_note_path",pcb_note_path_id:`pcb_note_path_${X++}`,pcb_component_id:w,route:St.map(lt=>({x:lt.x,y:-lt.y})),stroke_width:V.stroke.width});continue}let wt=mr(V.layer);if(!wt){Hh("Unable to convert layer for fp_arc",V.layer);continue}l.push({type:"pcb_silkscreen_path",pcb_silkscreen_path_id:`pcb_silkscreen_path_${$++}`,layer:wt,pcb_component_id:w,route:St.map(lt=>({x:lt.x,y:-lt.y})),stroke_width:V.stroke.width})}if(o)for(let V of o){let rt=V.layer.toLowerCase(),et=Tc(V.center),J=Tc(V.end),pt=Math.sqrt((J.x-et.x)**2+(J.y-et.y)**2),dt=Math.max(16,Math.ceil(2*Math.PI*pt)),St=[];for(let wt=0;wt<=dt;wt++){let lt=wt/dt*2*Math.PI;St.push({x:et.x+pt*Math.cos(lt),y:et.y+pt*Math.sin(lt)})}rt.startsWith("user.")&&l.push({type:"pcb_note_path",pcb_note_path_id:`pcb_note_path_${X++}`,pcb_component_id:w,route:St.map(wt=>({x:wt.x,y:-wt.y})),stroke_width:V.stroke.width})}for(let V of n){let rt=mr(V.layer);V.layer.endsWith(".SilkS")?l.push({type:"pcb_silkscreen_text",layer:rt,font:"tscircuit2024",font_size:V.effects?.font?.size[0]??1,pcb_component_id:w,anchor_position:{x:V.at[0],y:-V.at[1]},anchor_alignment:"center",text:V.text}):V.layer.endsWith(".Fab")?l.push({type:"pcb_fabrication_note_text",layer:rt,font:"tscircuit2024",font_size:V.effects?.font?.size[0]??1,pcb_component_id:w,anchor_position:{x:V.at[0],y:-V.at[1]},anchor_alignment:"center",text:V.text}):Hh("Unhandled layer for fp_text",V.layer)}let G=s.find(V=>V.key==="Reference"),Q=s.find(V=>V.key==="Value"),tt=[G,Q].filter(V=>V&&!!V.val);for(let V of tt){let rt=V.attributes.at;if(!rt)continue;let J=V.attributes.layer?.toLowerCase()?.endsWith(".fab"),pt=qTt(n);l.push({type:J?"pcb_fabrication_note_text":"pcb_silkscreen_text",layer:"top",font:"tscircuit2024",font_size:pt,pcb_component_id:w,anchor_position:{x:rt[0],y:-rt[1]},anchor_alignment:"center",text:V.val})}return l},pU=async e=>{let t=HTt(e);return await JTt(t)};var hU=async e=>{try{return(await import(e)).default}catch{console.log(`Failed to load ${e} locally, trying CDN fallback...`);try{let n=await fetch(`https://cdn.jsdelivr.net/npm/${e}/+esm`);if(!n.ok)throw new Error(`Failed to fetch ${e} from CDN: ${n.statusText}`);let i=await n.text(),o=new Blob([i],{type:"application/javascript"}),r=URL.createObjectURL(o);try{let{default:s}=await import(r);return s}finally{URL.revokeObjectURL(r)}}catch(n){throw console.error(`CDN fallback for ${e} also failed:`,n),n}}};var QTt="https://kicad-mod-cache.tscircuit.com",Vx=null,dU=()=>({partsEngine:JG,spiceEngineMap:{ngspice:{simulate:async e=>{if(!Vx){let t=await hU("@tscircuit/ngspice-spice-engine").catch(n=>{throw new Error("Could not load ngspice engine from local node_modules or CDN fallback.",{cause:n})});t&&(Vx=await t())}if(!Vx)throw new Error("Could not load ngspice engine from local node_modules or CDN fallback.");return Vx.simulate(e)}}},footprintLibraryMap:{kicad:async e=>{let t=`${QTt}/${e}`,n=`${t}.circuit.json`,o=await(await fetch(n)).json(),r=Array.isArray(o)?o.filter(a=>a?.type==="pcb_silkscreen_text"?a?.text==="REF**":!0):o,s=`${t}.wrl`;return{footprintCircuitJson:r,cadModel:{wrlUrl:s,modelUnitToMmScale:2.54}}}},footprintFileParserMap:{kicad_mod:{loadFromUrl:async e=>{let t=await fetch(e).then(i=>i.text()),n=await pU(t);return{footprintCircuitJson:Array.isArray(n)?n:[n]}}}}});var q4=Xt(Sn(),1),hoe=(0,q4.default)("tsci:eval:execution-context");function Hx(e,t={}){globalThis.React=fU;let n=t.platform||dU(),i=t.projectConfig?{...n,...t.projectConfig}:n,o=new Xh({platform:i});t.name&&(o.name=t.name),t.debugNamespace&&o.enableDebug(t.debugNamespace);let r=[];return{fsMap:{},entrypoint:"",logger:{info:s=>{r.push({msg:s})},getLogs:()=>r,stringifyLogs:()=>r.map(s=>s.msg).join(`
|
|
253
|
+
"${n.message}"`)});if(e.view==="pcb")return t.convertCircuitJsonToPcbSvg(this.getCircuitJson());if(e.view==="schematic")return t.convertCircuitJsonToSchematicSvg(this.getCircuitJson());throw new Error(`Invalid view: ${e.view}`)}getCoreVersion(){let[e,t,n]=yTt.version.split(".").map(Number);return`${e}.${t}.${n+1}`}async preview(e){let t=typeof e=="object"?e:{previewName:e};throw new Error("project.preview is not yet implemented")}computeSchematicGlobalTransform(){return zi()}_computePcbGlobalTransformBeforeLayout(){return zi()}selectAll(e){return this._guessRootComponent(),this.firstChild?.selectAll(e)??[]}selectOne(e,t){return this._guessRootComponent(),this.firstChild?.selectOne(e,t)??null}emit(e,...t){if(this._eventListeners[e])for(let n of this._eventListeners[e])n(...t)}on(e,t){this._eventListeners[e]||(this._eventListeners[e]=[]),this._eventListeners[e].push(t)}removeListener(e,t){this._eventListeners[e]&&(this._eventListeners[e]=this._eventListeners[e].filter(n=>n!==t))}enableDebug(e){typeof e=="string"?N4.default.enable(e):(e===null||e===!1)&&N4.default.disable()}getClientOrigin(){return typeof window<"u"&&window.location?window.location.origin:typeof self<"u"&&self.location?self.location.origin:""}},gTt=Xh,bTt=Xh,xTt=e=>{let[t,n]=Dh.default.useState(!0),[i,o]=Dh.default.useState(null),[r,s]=Dh.default.useState(),[a,c]=Dh.default.useState();return Dh.default.useEffect(()=>{n(!0),o(null),e&&setTimeout(()=>{try{let l=new Xh;l.add(e),s(l),c(l.toJson())}catch(l){o(l)}n(!1)},1)},[e]),{isLoading:t,error:i,circuit:r,circuitJson:a}},Vh=(e,t)=>(n,i)=>{let o=[];Array.isArray(t)?o.push(...t.flat()):typeof t=="object"&&o.push(...Object.values(t).flat(),...Object.keys(t));let r=s=>{if(s?.name&&s.name!==n)throw new Error(`Component name mismatch. Hook name: ${n}, Component prop name: ${s.name}`);let a={...i,...s,name:n},c=[];for(let l of o)if(a[l]){let u=`.${n} > .${l}`,h=a[l];c.push({from:u,to:h}),delete a[l]}return(0,fu.jsxs)(fu.Fragment,{children:[(0,fu.jsx)(e,{...a}),c.map((l,u)=>(0,fu.jsx)("trace",{...l},u))]})};for(let s of o)r[s]=`.${n} > .${s}`;return r},vTt=Vh(e=>(0,VG.jsx)("capacitor",{...e}),vz),STt=e=>Vh(t=>(0,HG.jsx)("chip",{pinLabels:e,...t}),e),wTt=Vh(e=>(0,GG.jsx)("diode",{...e}),Dz),PTt=Vh(e=>(0,UG.jsx)("led",{...e}),jz),ITt=Vh(e=>(0,qG.jsx)("resistor",{...e}),_z),TTt=new Proxy(e=>new Proxy({},{get:(t,n)=>`.${e} > .${n}`}),{get:(e,t)=>{let n=(...i)=>{let o=i[0];return new Proxy({},{get:(r,s)=>`.${t} > .${s}`})};return new Proxy(n,{get:(i,o)=>t==="net"?`net.${o}`:t==="subcircuit"?new Proxy({},{get:(r,s)=>new Proxy({},{get:(a,c)=>`subcircuit.${o} > .${s} > .${c}`})}):`.${t} > .${o}`,apply:(i,o,r)=>t==="net"?new Proxy({},{get:(s,a)=>`net.${a}`}):new Proxy({},{get:(s,a)=>{let c=`.${t} > .${a}`;return["U","J","CN"].some(u=>t.startsWith(u))?c:new Proxy(new String(c),{get:(u,h)=>typeof h=="symbol"||h==="toString"?()=>c:`.${t} > .${a} > .${h}`})}})})}});yH(hH);yH({Bug:Rm});var fU=Xt(Tr(),1);var ZG=e=>{let t=e.match(/:[RC]_(\d{4})_/);if(t||(t=e.match(/:(SOIC-\d+|SOT-\d+|SOD-\d+|SSOP-\d+|TSSOP-\d+|QFP-\d+|QFN-\d+)/),t))return t[1]};var j4=e=>e.includes("cap")?e.replace(/cap/g,""):e;var KG=e=>{if(e){if(e.startsWith("kicad:")){let t=ZG(e);return t?j4(t):e}return j4(e)}};var B4=new Map,lo=async(e,t)=>{let n=new URLSearchParams({...t,json:"true"}).toString();if(B4.has(n))return B4.get(n);let o=await(await fetch(`https://jlcsearch.tscircuit.com/${e}/list?${n}`)).json();return B4.set(n,o),o},uo=e=>e?[...e].sort((t,n)=>Number(n.is_basic??!1)-Number(t.is_basic??!1)):[],JG={findPart:async({sourceComponent:e,footprinterString:t})=>{let n=KG(t);if(e.type==="source_component"&&e.ftype==="simple_resistor"){let{resistors:i}=await lo("resistors",{resistance:e.resistance,package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_capacitor"){let{capacitors:i}=await lo("capacitors",{capacitance:e.capacitance,package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_pin_header"){let i;t?.includes("_p")&&(i=Number(t.split("_p")[1]));let{headers:o}=await lo("headers",i?{pitch:i,num_pins:e.pin_count,gender:e.gender}:{num_pins:e.pin_count,gender:e.gender});return{jlcpcb:uo(o).map(r=>`C${r.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_potentiometer"){let{potentiometers:i}=await lo("potentiometers",{resistance:e.max_resistance,package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_diode"){let{diodes:i}=await lo("diodes",{package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_chip"){let{chips:i}=await lo("chips",{package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_transistor"){let{transistors:i}=await lo("transistors",{package:n,transistor_type:e.transistor_type});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_power_source"){let{power_sources:i}=await lo("power_sources",{voltage:e.voltage,package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_inductor"){let{inductors:i}=await lo("inductors",{inductance:e.inductance,package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_crystal"){let{crystals:i}=await lo("crystals",{frequency:e.frequency,load_capacitance:e.load_capacitance,package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_mosfet"){let{mosfets:i}=await lo("mosfets",{package:n,mosfet_mode:e.mosfet_mode,channel_type:e.channel_type});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_resonator"){let{resonators:i}=await lo("resonators",{frequency:e.frequency,package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_switch"){let{switches:i}=await lo("switches",{switch_type:e.type,package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_led"){let{leds:i}=await lo("leds",{package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}else if(e.type==="source_component"&&e.ftype==="simple_fuse"){let{fuses:i}=await lo("fuses",{package:n});return{jlcpcb:uo(i).map(o=>`C${o.lcsc}`).slice(0,3)}}return{}}};var nU=Xt(QG(),1);Z();var aU=Xt(Sn(),1),cU=Xt(Sn(),1),ii=p.tuple([p.coerce.number(),p.coerce.number()]),FTt=p.tuple([p.number(),p.number(),p.number()]),Xx=p.union([ii,FTt]),zTt=p.object({kind:p.literal("arc"),start:ii,mid:ii,end:ii}),DTt=p.union([ii,zTt]),iU=p.object({at:Xx,size:ii,layer:p.string(),layers:p.array(p.string()),roundrect_rratio:p.number(),uuid:p.string()}).partial(),$Tt=p.object({key:p.string(),val:p.string(),attributes:iU}),jx=p.object({oval:p.boolean().default(!1),width:p.number().optional(),height:p.number().optional(),offset:ii.optional()}),oU=p.object({name:p.string(),pad_type:p.enum(["thru_hole","smd","np_thru_hole","connect"]),pad_shape:p.enum(["roundrect","circle","rect","oval","trapezoid","custom"]),at:Xx,drill:p.union([p.number(),p.array(p.any()),jx]).transform(e=>typeof e=="number"?{oval:!1,width:e,height:e}:"oval"in e?e:e.length===2?{oval:!1,width:Number.parseFloat(e[0]),height:Number.parseFloat(e[0]),offset:ii.parse(e[1].slice(1))}:e.length===3||e.length===4?{oval:e[0]==="oval",width:Number.parseFloat(e[1]),height:Number.parseFloat(e[2]),offset:e[3]?ii.parse(e[3].slice(1)):void 0}:e).pipe(jx),size:p.union([p.array(p.number()).length(2).transform(([e,t])=>({width:e,height:t})),p.object({width:p.number(),height:p.number()})]),layers:p.array(p.string()).optional(),roundrect_rratio:p.number().optional(),uuid:p.string().optional()}),rU=p.object({name:p.string(),pad_type:p.enum(["thru_hole","smd","np_thru_hole","connect"]),pad_shape:p.enum(["roundrect","circle","rect","oval","trapezoid","custom"]),at:Xx,size:ii,drill:p.union([p.number(),p.array(p.any()),jx]).transform(e=>typeof e=="number"?{oval:!1,width:e,height:e}:"oval"in e?e:e.length===2?{oval:!1,width:Number.parseFloat(e[0]),height:Number.parseFloat(e[0]),offset:ii.parse(e[1].slice(1))}:e.length===3||e.length===4?{oval:e[0]==="oval",width:Number.parseFloat(e[1]),height:Number.parseFloat(e[2]),offset:e[3]?ii.parse(e[3].slice(1)):void 0}:e).pipe(jx).optional(),layers:p.array(p.string()).optional(),roundrect_rratio:p.number().optional(),chamfer_ratio:p.number().optional(),solder_paste_margin:p.number().optional(),solder_paste_margin_ratio:p.number().optional(),clearance:p.number().optional(),zone_connection:p.union([p.literal(0).describe("Pad is not connect to zone"),p.literal(1).describe("Pad is connected to zone using thermal relief"),p.literal(2).describe("Pad is connected to zone using solid fill")]).optional(),thermal_width:p.number().optional(),thermal_gap:p.number().optional(),uuid:p.string().optional()}),sU=p.object({font:p.object({size:ii,thickness:p.number().optional()})}).partial(),jTt=p.object({fp_text_type:p.literal("user"),text:p.string(),at:Xx,layer:p.string(),uuid:p.string().optional(),effects:sU.partial()}),BTt=p.object({start:ii,mid:ii,end:ii,stroke:p.object({width:p.number(),type:p.string()}),layer:p.string(),uuid:p.string().optional()}),YTt=p.object({center:ii,end:ii,stroke:p.object({width:p.number(),type:p.string()}),fill:p.string().optional(),layer:p.string(),uuid:p.string().optional()}),XTt=p.object({pts:p.array(DTt),stroke:p.object({width:p.number(),type:p.string()}).optional(),width:p.number().optional(),layer:p.string(),uuid:p.string().optional(),fill:p.string().optional()}).transform(e=>({...e,width:void 0,stroke:e.stroke??{width:e.width}})),VTt=p.object({start:ii,end:ii,stroke:p.object({width:p.number(),type:p.string()}).optional(),width:p.number().optional(),layer:p.string(),uuid:p.string().optional()}).transform(e=>({...e,width:void 0,stroke:e.stroke??{width:e.width}})),tU=p.object({footprint_name:p.string(),version:p.string().optional(),generator:p.string().optional(),generator_version:p.string().optional(),layer:p.string(),descr:p.string().default(""),tags:p.array(p.string()).optional(),properties:p.array($Tt),fp_lines:p.array(VTt),fp_texts:p.array(jTt),fp_arcs:p.array(BTt),fp_circles:p.array(YTt).optional(),fp_polys:p.array(XTt).optional(),pads:p.array(rU),holes:p.array(oU).optional()}),Bx=(e,t)=>{if(t==="effects"&&Array.isArray(e)){let n={};for(let i of e)if(i[0]==="font"){let o={};for(let r of i.slice(1))r.length===2?o[r[0].valueOf()]=Number.parseFloat(r[1].valueOf()):o[r[0].valueOf()]=r.slice(1).map(s=>Number.parseFloat(s.valueOf()));n.font=o}return sU.parse(n)}if(t==="pts")return e.map(n=>{let i=n[0]?.valueOf?.()??n[0];if(i==="xy")return n.slice(1).map(o=>Number.parseFloat(o.valueOf()));if(i==="arc"){let o={kind:"arc"};for(let r of n.slice(1)){let s=r[0].valueOf();o[s]=r.slice(1).map(a=>Number.parseFloat(a.valueOf()))}return o}return n});if(t==="stroke"){let n={};for(let i of e){let o=i[0].valueOf();n[o]=Bx(i.slice(1),o)}return n}return t==="at"||t==="size"||t==="start"||t==="mid"||t==="end"?(Array.isArray(e)?e:[e]).map(i=>i?.valueOf?.()??i).filter(i=>typeof i=="number"||typeof i=="string"&&/^[-+]?\d*\.?\d+(e[-+]?\d+)?$/i.test(i)).map(i=>typeof i=="number"?i:Number.parseFloat(i)):t==="tags"?e.map(n=>n.valueOf()):t==="generator_version"||t==="version"?e[0].valueOf():e.length===2?e.valueOf():t==="uuid"?Array.isArray(e)?e[0].valueOf():e.valueOf():/^[\d\.]+$/.test(e)&&!Number.isNaN(Number.parseFloat(e))?Number.parseFloat(e):Array.isArray(e)&&e.length===1?e[0].valueOf():Array.isArray(e)?e.map(n=>n.valueOf()):e},Re=(e,t)=>{for(let n of e)if(Array.isArray(n)&&n[0]===t)return Bx(n.slice(1),t)},Y4=(0,aU.default)("kicad-mod-converter"),HTt=e=>{let t=(0,nU.default)(e),n=t[1].valueOf(),i={},o=Object.entries(tU.shape).filter(([T,I])=>I._def.typeName==="ZodString"||T==="tags").map(([T])=>T);for(let T of t.slice(2)){if(!o.includes(T[0]))continue;let I=T[0].valueOf(),E=Bx(T.slice(1),I);i[I]=E}let r=t.slice(2).filter(T=>T[0]==="property").map(T=>{let I=T[1].valueOf(),E=T[2].valueOf(),M=iU.parse(T.slice(3).reduce((k,N)=>{let A=N[0].valueOf();return k[A]=Bx(N.slice(1),A),k},{}));return{key:I,val:E,attributes:M}}),s=t.slice(2).filter(T=>T[0]==="pad"),a=[];for(let T of s){let I=Re(T,"at"),E=Re(T,"size"),M=Re(T,"drill"),k=Re(T,"layers");if(Array.isArray(k)?k=k.map($=>$.valueOf()):typeof k=="string"?k=[k]:k||(k=[]),!k.includes("F.Cu")){Y4(`Skipping pad without F.Cu layer: layers=${k.join(", ")}`);continue}let N=Re(T,"roundrect_rratio"),A=Re(T,"uuid"),R={name:T[1].valueOf(),pad_type:T[2].valueOf(),pad_shape:T[3].valueOf(),at:I,drill:M,size:E,layers:k,roundrect_rratio:N,uuid:A};Y4(`attempting to parse pad: ${JSON.stringify(R,null," ")}`),a.push(rU.parse(R))}let c=t.slice(2).filter(T=>T[0]==="fp_text"),l=[];for(let T of c){let I=T[2].valueOf(),E=Re(T,"at"),M=Re(T,"layer"),k=Re(T,"uuid"),N=Re(T,"effects");l.push({fp_text_type:"user",text:I,at:E,layer:M,uuid:k,effects:N})}let u=[],h=t.slice(2).filter(T=>T[0]==="fp_line");for(let T of h){let I=Re(T,"start"),E=Re(T,"end"),M=Re(T,"stroke"),k=Re(T,"layer"),N=Re(T,"uuid");u.push({start:I,end:E,stroke:M,layer:k,uuid:N})}let d=[],_=t.slice(2).filter(T=>T[0]==="fp_arc");for(let T of _){let I=Re(T,"start"),E=Re(T,"mid"),M=Re(T,"end"),k=Re(T,"stroke"),N=Re(T,"layer"),A=Re(T,"uuid");!I||!M||!E||!k||!N||d.push({start:I,mid:E,end:M,stroke:k,layer:N,uuid:A})}let y=[],g=t.slice(2).filter(T=>T[0]==="fp_circle");for(let T of g){let I=Re(T,"center"),E=Re(T,"end"),M=Re(T,"stroke"),k=Re(T,"fill"),N=Re(T,"layer"),A=Re(T,"uuid");!I||!E||!M||!N||y.push({center:I,end:E,stroke:M,fill:k,layer:N,uuid:A})}let x=[],w=t.slice(2).filter(T=>T[0]==="fp_poly");for(let T of w){let I=Re(T,"pts"),E=Re(T,"stroke"),M=Re(T,"width"),k=Re(T,"layer"),N=Re(T,"uuid"),A=Re(T,"fill"),R=E;!R&&typeof M=="number"?R={width:M,type:"solid"}:R&&typeof R=="object"&&typeof M=="number"&&R.width===void 0&&(R={...R,width:M}),x.push({pts:I,stroke:R,layer:k,uuid:N,fill:A})}let S=[];for(let T of t.slice(2)){if(T[0]!=="pad"||T[2]?.valueOf?.()!=="thru_hole")continue;let I=T[1]?.valueOf?.(),E=T[2]?.valueOf?.(),M=T[3]?.valueOf?.(),k=Re(T,"at"),N=Re(T,"drill"),A=Re(T,"size");Array.isArray(A)&&(A[0]==="size"&&(A=A.slice(1)),A={width:Number(A[0]),height:Number(A[1])});let R=Re(T,"uuid"),$=Re(T,"roundrect_rratio"),j=Re(T,"layers");Array.isArray(j)?j=j.map(X=>X.valueOf()):typeof j=="string"?j=[j]:j||(j=[]);let H={name:I,pad_type:E,pad_shape:M,at:k,drill:N,size:A,layers:j,roundrect_rratio:$,uuid:R};Y4(`attempting to parse holes: ${JSON.stringify(H,null,2)}`),S.push(oU.parse(H))}return tU.parse({footprint_name:n,...i,properties:r,fp_lines:u,fp_texts:l,fp_arcs:d,fp_circles:y,pads:a,holes:S,fp_polys:x})},Om=Math.PI*2,eU=e=>{let t=e%Om;return t<0&&(t+=Om),t},Yx=(e,t)=>{let n=eU(e),o=eU(t)-n;return o<0&&(o+=Om),o};function lU(e,t,n){let i={x:(e.x+t.x)/2,y:(e.y+t.y)/2},o={x:(t.x+n.x)/2,y:(t.y+n.y)/2},r=-(e.x-t.x)/(e.y-t.y),s=-(t.x-n.x)/(t.y-n.y),a=(i.y-o.y+s*o.x-r*i.x)/(s-r),c=i.y+r*(a-i.x);return{x:a,y:c}}function uU(e,t){return Math.sqrt((e.x-t.x)**2+(e.y-t.y)**2)}function Gh(e,t){return Math.atan2(t.y-e.y,t.x-e.x)}var G4=(e,t,n)=>{let i=lU(e,t,n),o=uU(i,e),r=Gh(i,e),s=Gh(i,t),a=Gh(i,n),c=Yx(r,s),l=Yx(r,a),u=l;return c>l&&(u=l-Om),Math.abs(o*u)};function U4(e,t,n,i){let o=lU(e,t,n),r=uU(o,e),s=Gh(o,e),a=Gh(o,t),c=Gh(o,n),l=Yx(s,a),u=Yx(s,c),h=u;l>u&&(h=u-Om);let d=[];for(let _=0;_<=i;_++){let y=s+_/i*h,g=o.x+r*Math.cos(y),x=o.y+r*Math.sin(y);d.push({x:g,y:x})}return d}var Tc=e=>Array.isArray(e)?{x:e[0],y:e[1]}:e,X4=(e,t,n=1e-4)=>Math.abs(e.x-t.x)<n&&Math.abs(e.y-t.y)<n,GTt=e=>{let t=[],n=new Set;for(let i=0;i<e.length;i++){if(n.has(i))continue;let o=[e[i]];n.add(i);let r=e[i].end,s=!0;for(;s;){if(s=!1,o.length>1&&X4(r,o[0].start)){t.push(o);break}for(let a=0;a<e.length;a++)if(!n.has(a)){if(X4(r,e[a].start)){o.push(e[a]),n.add(a),r=e[a].end,s=!0;break}else if(X4(r,e[a].end)){e[a].type==="arc"?o.push({...e[a],reversed:!0}):o.push({...e[a],start:e[a].end,end:e[a].start}),n.add(a),r=e[a].start,s=!0;break}}if(!s){for(let a=o.length-1;a>=0;a--){let c=e.indexOf(o[a]);c!==-1&&n.delete(c)}break}}}return t},UTt=e=>{let t=[];for(let n of e)if(n.type==="line")t.push(n.start);else if(n.type==="arc"&&n.mid){let i=G4(n.start,n.mid,n.end),o=Math.max(3,Math.ceil(i)),r=U4(n.start,n.mid,n.end,o);n.reversed&&(r=r.reverse()),t.push(...r.slice(0,-1))}return t};function qTt(e){if(!Array.isArray(e))return null;let t=e.find(s=>s.layer?.toLowerCase()==="f.silks"&&(s.text?.includes("${REFERENCE}")||s.fp_text_type?.toLowerCase()==="reference"||s.text?.match(/^R\d+|C\d+|U\d+/))),n=t||e.find(s=>s.layer?.toLowerCase()==="f.fab"&&(s.text?.includes("${REFERENCE}")||s.fp_text_type?.toLowerCase()==="reference")),i=t||n;if(!i?.effects?.font?.size)return null;let[o,r]=i.effects.font.size;return r??o??1}var WTt=e=>e*Math.PI/180,V4=(e,t,n)=>{let i=WTt(n),o=Math.cos(i),r=Math.sin(i);return{x:e*o-t*r,y:e*r+t*o}},ZTt=e=>{let t=[...new Map(e.map(u=>[`${u.x},${u.y}`,u])).values()];if(t.length!==4)return null;let n=t.map(u=>u.x),i=t.map(u=>u.y),o=[...new Set(n)],r=[...new Set(i)];if(o.length!==2||r.length!==2)return null;let[s,a]=o.sort((u,h)=>u-h),[c,l]=r.sort((u,h)=>u-h);return s===void 0||a===void 0||c===void 0||l===void 0?null:{x:(s+a)/2,y:(c+l)/2,width:a-s,height:l-c}},KTt=e=>{if(!e)return!1;let t=e.toLowerCase();return t!=="no"&&t!=="none"&&t!=="outline"},H4=e=>e&&Array.isArray(e)&&e.length>=3&&typeof e[2]=="number"?e[2]:0,Co=e=>{let t=(e%360+360)%360;return t===90||t===270},Hh=(0,cU.default)("kicad-mod-converter"),mr=e=>{switch(e.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"}},JTt=async e=>{let{fp_lines:t,fp_texts:n,fp_arcs:i,fp_circles:o,pads:r,properties:s,holes:a,fp_polys:c}=e,l=[];l.push({type:"source_component",source_component_id:"source_component_0",supplier_part_numbers:{}}),l.push({type:"schematic_component",schematic_component_id:"schematic_component_0",source_component_id:"source_component_0",center:{x:0,y:0},rotation:0,size:{width:0,height:0}});let u=new Set;for(let V of r)V.name&&u.add(V.name);if(a)for(let V of a)V.name&&u.add(V.name);let h=0,d=new Map;for(let V of u){let rt=`source_port_${h++}`;d.set(V,rt),l.push({type:"source_port",source_port_id:rt,source_component_id:"source_component_0",name:V,port_hints:[V]}),l.push({type:"schematic_port",schematic_port_id:`schematic_port_${h++}`,source_port_id:rt,schematic_component_id:"schematic_component_0",center:{x:0,y:0}})}let _=Number.POSITIVE_INFINITY,y=Number.NEGATIVE_INFINITY,g=Number.POSITIVE_INFINITY,x=Number.NEGATIVE_INFINITY;for(let V of r){let rt=V.at[0],et=-V.at[1],J=V.size[0],pt=V.size[1];_=Math.min(_,rt-J/2),y=Math.max(y,rt+J/2),g=Math.min(g,et-pt/2),x=Math.max(x,et+pt/2)}let w="pcb_component_0";l.push({type:"pcb_component",source_component_id:"source_component_0",pcb_component_id:w,layer:"top",center:{x:0,y:0},rotation:0,width:Number.isFinite(_)?y-_:0,height:Number.isFinite(g)?x-g:0});let S=0,T=new Map;for(let V of u){let rt=`pcb_port_${S++}`,et=d.get(V);T.set(V,rt);let J=0,pt=0,dt=["top","bottom"],St=r.find(wt=>wt.name===V);if(St)J=St.at[0],pt=-St.at[1],dt=St.layers?St.layers.map(wt=>mr(wt)).filter(Boolean):["top","bottom"];else if(a){let wt=a.find(lt=>lt.name===V);wt&&(J=wt.at[0],pt=-wt.at[1],dt=wt.layers?wt.layers.map(lt=>mr(lt)).filter(Boolean):["top","bottom"])}l.push({type:"pcb_port",pcb_port_id:rt,source_port_id:et,pcb_component_id:w,x:J,y:pt,layers:dt})}let I=0,E=0,M=0;for(let V of r)if(V.pad_type==="smd"){let rt=H4(V.at),et=Co(rt)?V.size[1]:V.size[0],J=Co(rt)?V.size[0]:V.size[1],pt=V.name?T.get(V.name):void 0;l.push({type:"pcb_smtpad",pcb_smtpad_id:`pcb_smtpad_${I++}`,shape:"rect",x:V.at[0],y:-V.at[1],width:et,height:J,layer:mr(V.layers?.[0]??"F.Cu"),pcb_component_id:w,port_hints:[V.name],pcb_port_id:pt})}else if(V.pad_type==="thru_hole"){if(V.pad_shape==="rect"){let rt=H4(V.at),et=Co(rt)?V.size[1]:V.size[0],J=Co(rt)?V.size[0]:V.size[1],pt=V.drill?.offset?.[0]??0,dt=V.drill?.offset?.[1]??0,St=V4(pt,dt,rt),wt=V.name?T.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"circular_hole_with_rect_pad",hole_shape:"circle",pad_shape:"rect",x:V.at[0],y:-V.at[1],hole_offset_x:St.x,hole_offset_y:-St.y,hole_diameter:V.drill?.width,rect_pad_width:et,rect_pad_height:J,layers:["top","bottom"],pcb_component_id:w,port_hints:[V.name],pcb_port_id:wt})}else if(V.pad_shape==="circle"){let rt=V.name?T.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"circle",x:V.at[0],y:-V.at[1],outer_diameter:V.size[0],hole_diameter:V.drill?.width,layers:["top","bottom"],pcb_component_id:w,port_hints:[V.name],pcb_port_id:rt})}else if(V.pad_shape==="oval"){let rt=V.name?T.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"pill",x:V.at[0],y:-V.at[1],outer_width:V.size[0],outer_height:V.size[1],hole_width:V.drill?.width,hole_height:V.drill?.height,layers:["top","bottom"],pcb_component_id:w,port_hints:[V.name],pcb_port_id:rt})}}else V.pad_type==="np_thru_hole"&&l.push({type:"pcb_hole",pcb_hole_id:`pcb_hole_${M++}`,x:V.at[0],y:-V.at[1],hole_diameter:V.drill?.width,pcb_component_id:w});if(a)for(let V of a){let rt=V.layers?.some(ht=>ht.endsWith(".Cu")||ht==="*.Cu"),et=H4(V.at),J=V.drill?.offset?.[0]??0,pt=V.drill?.offset?.[1]??0,dt=V4(J,pt,et),St=V.at[0]+dt.x,wt=-(V.at[1]+dt.y),lt=V.drill?.width??0,B=V.size?.width??lt,q=V.roundrect_rratio??0,it=q>0?Math.min(Co(et)?V.size?.height??B:V.size?.width??B,Co(et)?V.size?.width??B:V.size?.height??B)/2*q:0;if(rt)if(V.pad_shape==="rect"){let ht=V.name?T.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"circular_hole_with_rect_pad",hole_shape:"circle",pad_shape:"rect",x:V.at[0],y:-V.at[1],hole_offset_x:dt.x,hole_offset_y:-dt.y,hole_diameter:lt,rect_pad_width:Co(et)?V.size?.height??B:V.size?.width??B,rect_pad_height:Co(et)?V.size?.width??B:V.size?.height??B,rect_border_radius:it,port_hints:[V.name],layers:["top","bottom"],pcb_component_id:w,pcb_port_id:ht})}else if(V.pad_shape==="oval"){let ht=V.name?T.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"pill",x:St,y:wt,outer_width:Co(et)?V.size?.height??B:V.size?.width??B,outer_height:Co(et)?V.size?.width??B:V.size?.height??B,hole_width:Co(et)?V.drill?.height??lt:V.drill?.width??lt,hole_height:Co(et)?V.drill?.width??lt:V.drill?.height??lt,port_hints:[V.name],layers:["top","bottom"],pcb_component_id:w,pcb_port_id:ht})}else if(V.pad_shape==="roundrect"){let ht=V.name?T.get(V.name):void 0,at=V.drill?.offset?.[0]??0,K=V.drill?.offset?.[1]??0,ut=V4(at,K,et),Mt=Co(et)?V.size?.height??B:V.size?.width??B,zt=Co(et)?V.size?.width??B:V.size?.height??B;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"circular_hole_with_rect_pad",hole_shape:"circle",pad_shape:"rect",x:St,y:wt,hole_offset_x:ut.x,hole_offset_y:-ut.y,hole_diameter:lt,rect_pad_width:Mt,rect_pad_height:zt,rect_border_radius:it,port_hints:[V.name],layers:["top","bottom"],pcb_component_id:w,pcb_port_id:ht})}else{let ht=V.name?T.get(V.name):void 0;l.push({type:"pcb_plated_hole",pcb_plated_hole_id:`pcb_plated_hole_${E++}`,shape:"circle",x:St,y:wt,outer_diameter:B,hole_diameter:lt,port_hints:[V.name],layers:["top","bottom"],pcb_component_id:w,pcb_port_id:ht})}else l.push({type:"pcb_hole",pcb_hole_id:`pcb_hole_${M++}`,x:St,y:wt,hole_diameter:B,hole_shape:"circle",pcb_component_id:w})}let k=[];for(let V of t)V.layer.toLowerCase()==="edge.cuts"&&k.push({type:"line",start:{x:V.start[0],y:V.start[1]},end:{x:V.end[0],y:V.end[1]},strokeWidth:V.stroke.width});for(let V of i)V.layer.toLowerCase()==="edge.cuts"&&k.push({type:"arc",start:{x:V.start[0],y:V.start[1]},mid:{x:V.mid[0],y:V.mid[1]},end:{x:V.end[0],y:V.end[1]},strokeWidth:V.stroke.width});let N=GTt(k),A=0;for(let V of N){let rt=UTt(V);rt.length>=3&&l.push({type:"pcb_cutout",pcb_cutout_id:`pcb_cutout_${A++}`,shape:"polygon",points:rt.map(et=>({x:et.x,y:-et.y})),pcb_component_id:w})}let R=0,$=0,j=0,H=0;for(let V of t){let rt=[{x:V.start[0],y:-V.start[1]},{x:V.end[0],y:-V.end[1]}],et=V.layer.toLowerCase();et==="f.cu"?l.push({type:"pcb_trace",pcb_trace_id:`pcb_trace_${R++}`,pcb_component_id:w,layer:mr(V.layer),route:rt,thickness:V.stroke.width}):et==="f.silks"?l.push({type:"pcb_silkscreen_path",pcb_silkscreen_path_id:`pcb_silkscreen_path_${$++}`,pcb_component_id:w,layer:"top",route:rt,stroke_width:V.stroke.width}):et==="edge.cuts"?Hh("Skipping Edge.Cuts fp_line (converted to pcb_cutout)",V.layer):et==="f.fab"?l.push({type:"pcb_fabrication_note_path",fabrication_note_path_id:`fabrication_note_path_${j++}`,pcb_component_id:w,layer:"top",route:rt,stroke_width:V.stroke.width,port_hints:[]}):et.startsWith("user.")?l.push({type:"pcb_note_line",pcb_note_line_id:`pcb_note_line_${H++}`,pcb_component_id:w,x1:V.start[0],y1:-V.start[1],x2:V.end[0],y2:-V.end[1],stroke_width:V.stroke.width}):Hh("Unhandled layer for fp_line",V.layer)}if(c)for(let V of c){let rt=[],et=wt=>{!Number.isFinite(wt.x)||!Number.isFinite(wt.y)||rt.push(wt)};for(let wt of V.pts){if(Array.isArray(wt)){et({x:wt[0],y:-wt[1]});continue}if(wt&&typeof wt=="object"&&"kind"in wt){if(wt.kind==="arc"){let lt=Tc(wt.start),B=Tc(wt.mid),q=Tc(wt.end),it=G4(lt,B,q),ht=Math.max(8,Math.ceil(it)),at=Math.max(2,Math.ceil(it/.1)),K=U4(lt,B,q,at).map(ut=>({x:ut.x,y:-ut.y}));for(let ut of K)et(ut)}continue}}let J=rt,dt=J.length>2&&J[0].x===J[J.length-1].x&&J[0].y===J[J.length-1].y?J.slice(0,-1):J;if(J.length===0)continue;let St=V.stroke?.width??0;if(V.layer.endsWith(".Cu")){let wt=ZTt(dt);wt?l.push({type:"pcb_smtpad",pcb_smtpad_id:`pcb_smtpad_${I++}`,shape:"rect",x:wt.x,y:wt.y,width:wt.width,height:wt.height,layer:mr(V.layer),pcb_component_id:w}):KTt(V.fill)?dt.length>=3?l.push({type:"pcb_smtpad",pcb_smtpad_id:`pcb_smtpad_${I++}`,shape:"polygon",points:dt,layer:mr(V.layer),pcb_component_id:w}):dt.length>=2&&l.push({type:"pcb_trace",pcb_trace_id:`pcb_trace_${R++}`,pcb_component_id:w,layer:mr(V.layer),route:dt,thickness:St}):dt.length>=2&&l.push({type:"pcb_trace",pcb_trace_id:`pcb_trace_${R++}`,pcb_component_id:w,layer:mr(V.layer),route:dt,thickness:St})}else V.layer.endsWith(".SilkS")?l.push({type:"pcb_silkscreen_path",pcb_silkscreen_path_id:`pcb_silkscreen_path_${$++}`,pcb_component_id:w,layer:mr(V.layer),route:J,stroke_width:St}):V.layer.endsWith(".Fab")?l.push({type:"pcb_fabrication_note_path",fabrication_note_path_id:`fabrication_note_path_${j++}`,pcb_component_id:w,layer:mr(V.layer),route:dt,stroke_width:St,port_hints:[]}):Hh("Unhandled layer for fp_poly",V.layer)}let X=0;for(let V of i){let rt=V.layer.toLowerCase();if(rt==="edge.cuts"){Hh("Skipping Edge.Cuts fp_arc (converted to pcb_cutout)",V.layer);continue}let et=Tc(V.start),J=Tc(V.mid),pt=Tc(V.end),dt=G4(et,J,pt),St=U4(et,J,pt,Math.ceil(dt));if(rt.startsWith("user.")){l.push({type:"pcb_note_path",pcb_note_path_id:`pcb_note_path_${X++}`,pcb_component_id:w,route:St.map(lt=>({x:lt.x,y:-lt.y})),stroke_width:V.stroke.width});continue}let wt=mr(V.layer);if(!wt){Hh("Unable to convert layer for fp_arc",V.layer);continue}l.push({type:"pcb_silkscreen_path",pcb_silkscreen_path_id:`pcb_silkscreen_path_${$++}`,layer:wt,pcb_component_id:w,route:St.map(lt=>({x:lt.x,y:-lt.y})),stroke_width:V.stroke.width})}if(o)for(let V of o){let rt=V.layer.toLowerCase(),et=Tc(V.center),J=Tc(V.end),pt=Math.sqrt((J.x-et.x)**2+(J.y-et.y)**2),dt=Math.max(16,Math.ceil(2*Math.PI*pt)),St=[];for(let wt=0;wt<=dt;wt++){let lt=wt/dt*2*Math.PI;St.push({x:et.x+pt*Math.cos(lt),y:et.y+pt*Math.sin(lt)})}rt.startsWith("user.")&&l.push({type:"pcb_note_path",pcb_note_path_id:`pcb_note_path_${X++}`,pcb_component_id:w,route:St.map(wt=>({x:wt.x,y:-wt.y})),stroke_width:V.stroke.width})}for(let V of n){let rt=mr(V.layer);V.layer.endsWith(".SilkS")?l.push({type:"pcb_silkscreen_text",layer:rt,font:"tscircuit2024",font_size:V.effects?.font?.size[0]??1,pcb_component_id:w,anchor_position:{x:V.at[0],y:-V.at[1]},anchor_alignment:"center",text:V.text}):V.layer.endsWith(".Fab")?l.push({type:"pcb_fabrication_note_text",layer:rt,font:"tscircuit2024",font_size:V.effects?.font?.size[0]??1,pcb_component_id:w,anchor_position:{x:V.at[0],y:-V.at[1]},anchor_alignment:"center",text:V.text}):Hh("Unhandled layer for fp_text",V.layer)}let G=s.find(V=>V.key==="Reference"),Q=s.find(V=>V.key==="Value"),tt=[G,Q].filter(V=>V&&!!V.val);for(let V of tt){let rt=V.attributes.at;if(!rt)continue;let J=V.attributes.layer?.toLowerCase()?.endsWith(".fab"),pt=qTt(n);l.push({type:J?"pcb_fabrication_note_text":"pcb_silkscreen_text",layer:"top",font:"tscircuit2024",font_size:pt,pcb_component_id:w,anchor_position:{x:rt[0],y:-rt[1]},anchor_alignment:"center",text:V.val})}return l},pU=async e=>{let t=HTt(e);return await JTt(t)};var hU=async e=>{try{return(await import(e)).default}catch{console.log(`Failed to load ${e} locally, trying CDN fallback...`);try{let n=await fetch(`https://cdn.jsdelivr.net/npm/${e}/+esm`);if(!n.ok)throw new Error(`Failed to fetch ${e} from CDN: ${n.statusText}`);let i=await n.text(),o=new Blob([i],{type:"application/javascript"}),r=URL.createObjectURL(o);try{let{default:s}=await import(r);return s}finally{URL.revokeObjectURL(r)}}catch(n){throw console.error(`CDN fallback for ${e} also failed:`,n),n}}};var QTt="https://kicad-mod-cache.tscircuit.com",Vx=null,dU=()=>({partsEngine:JG,spiceEngineMap:{ngspice:{simulate:async e=>{if(!Vx){let t=await hU("@tscircuit/ngspice-spice-engine").catch(n=>{throw new Error("Could not load ngspice engine from local node_modules or CDN fallback.",{cause:n})});t&&(Vx=await t())}if(!Vx)throw new Error("Could not load ngspice engine from local node_modules or CDN fallback.");return Vx.simulate(e)}}},footprintLibraryMap:{kicad:async e=>{let t=`${QTt}/${e}`,n=`${t}.circuit.json`,o=await(await fetch(n)).json(),r=Array.isArray(o)?o.filter(a=>a?.type==="pcb_silkscreen_text"?a?.text==="REF**":!0):o,s=`${t}.wrl`;return{footprintCircuitJson:r,cadModel:{wrlUrl:s,modelUnitToMmScale:2.54}}}},footprintFileParserMap:{kicad_mod:{loadFromUrl:async e=>{let t=await fetch(e).then(i=>i.text()),n=await pU(t);return{footprintCircuitJson:Array.isArray(n)?n:[n]}}}}});var q4=Xt(Sn(),1),hoe=(0,q4.default)("tsci:eval:execution-context");function Hx(e,t={}){globalThis.React=fU;let n=t.platform||dU(),i=t.projectConfig?{...n,...t.projectConfig}:n;i.partsEngineDisabled&&(i.partsEngine=void 0);let o=new Xh({platform:i});t.name&&(o.name=t.name),t.debugNamespace&&o.enableDebug(t.debugNamespace);let r=[];return{fsMap:{},entrypoint:"",logger:{info:s=>{r.push({msg:s})},getLogs:()=>r,stringifyLogs:()=>r.map(s=>s.msg).join(`
|
|
254
254
|
`)},preSuppliedImports:{"@tscircuit/core":Dx,tscircuit:Dx,"@tscircuit/math-utils":DI,react:fU,debug:q4.default,"@tscircuit/props":{}},circuit:o,tsConfig:null,importStack:[],currentlyImporting:new Set,...e}}function Mc(e){let t=e;return t=t.replace(/\\/g,"/"),t=t.trim(),t.startsWith("./")&&(t=t.slice(2)),t.startsWith("/")&&(t=t.slice(1)),t}function mU(e){let t={};for(let[n,i]of Object.entries(e))t[Mc(n)]=i;return t}function $r(e){if(!e)return".";let n=e.replace(/\\/g,"/").replace(/\/+$/,"");return n.indexOf("/")===-1?".":n.substring(0,n.lastIndexOf("/"))||"/"}function Gx(e,t){if(e.startsWith("../")){let n=$r(t);return Gx(e.slice(3),n)}return e.startsWith("./")?Gx(e.slice(2),t):e.startsWith("/")?e.slice(1):`${t}/${e}`}function Lm(e){if(Array.isArray(e))return null;let t=e["tsconfig.json"];if(!t)return null;try{let n=t.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g,"");return JSON.parse(n)}catch(n){throw new Error(`Failed to parse tsconfig.json: ${n.message}`)}}function _U(e){let{importPath:t,normalizedFilePathMap:n,extensions:i,tsConfig:o}=e,r=o?.compilerOptions?.paths;if(!r)return null;let s=o?.compilerOptions?.baseUrl||".",a=l=>{let u=Mc(l);if(n.has(u))return n.get(u);for(let h of i){let d=`${u}.${h}`;if(n.has(d))return n.get(d)}return null};for(let[l,u]of Object.entries(r))if(l.includes("*")){let[d,_]=l.split("*");if(!t.startsWith(d)||!t.endsWith(_||""))continue;let y=t.slice(d.length,t.length-(_?_.length:0));for(let g of u){let x=g.replace("*",y),w=s&&!x.startsWith("./")&&!x.startsWith("/")?`${s}/${x}`:x,S=a(w);if(S)return S}}else{if(t!==l)continue;for(let d of u){let _=s&&!d.startsWith("./")&&!d.startsWith("/")?`${s}/${d}`:d,y=a(_);if(y)return y}}let c=W4({importPath:t,normalizedFilePathMap:n,extensions:i,tsConfig:o});return c||null}function W4(e){let{importPath:t,normalizedFilePathMap:n,extensions:i,tsConfig:o}=e,r=o?.compilerOptions?.baseUrl;if(!r)return null;let s=`${r}/${t}`,a=Mc(s);if(n.has(a))return n.get(a);for(let c of i){let l=`${a}.${c}`;if(n.has(l))return n.get(l)}return null}function yU(e,t){let n=t?.compilerOptions?.paths;if(!n)return!1;for(let[i]of Object.entries(n))if(i.includes("*")){let[r,s]=i.split("*");if(e.startsWith(r)&&e.endsWith(s||""))return!0}else if(e===i)return!0;return!1}var Fm=(e,t,n,i={})=>{let o=n?Gx(e,n):e,r=new Set(Array.isArray(t)?t:Object.keys(t));if(r.has(o))return o;let s=new Map;for(let u of r)s.set(Mc(u),u);let a=Mc(o);if(s.has(a))return s.get(a);let c=["tsx","ts","json","js","jsx","obj","gltf","glb"];for(let u of c){let h=`${a}.${u}`;if(s.has(h))return s.get(h)}let l=i.tsConfig??null;if(!e.startsWith("./")&&!e.startsWith("../")){let u=_U({importPath:e,normalizedFilePathMap:s,extensions:c,tsConfig:l});if(u)return u;let h=W4({importPath:e,normalizedFilePathMap:s,extensions:c,tsConfig:l});if(h)return h}if(!e.startsWith("./")&&!e.startsWith("../")){let u=Mc(e);if(s.has(u))return s.get(u);for(let h of c){let d=`${u}.${h}`;if(s.has(d))return s.get(d)}}return null},Ux=(e,t,n,i={})=>{let o=Fm(e,t,n,i);if(!o)throw new Error(`File not found "${e}", available paths:
|
|
255
255
|
|
|
256
256
|
${Object.keys(t).join(", ")}`);return o};var qx=e=>{let t=/^\s*import\s+(?:(?:[\w\s]+,\s*)?(?:\*\s+as\s+[\w\s]+|\{[\s\w,]+\}|\w+)\s+from\s*)?['"](.+?)['"]/gm,n=[],i;for(;(i=t.exec(e))!==null;){let s=i[0];/^\s*import\s+type\b/.test(s)||n.push(i[1])}let o=/^\s*export\s+(?:type\s+)?(?:\*\s+as\s+[\w$]+|\*|\{[^}]+\})\s+from\s*['"](.+?)['"]/gm,r;for(;(r=o.exec(e))!==null;){let s=r[0];/^\s*export\s+type\b/.test(s)||n.push(r[1])}return n};function mu(e,t,n){globalThis.__tscircuit_require=o=>{let r=Fm(o,t,n),s=r&&t[r];if(!t[o]&&!s)throw new Error(`Import "${o}" not found ${n?`in "${n}"`:""}`);let a=t[o]||t[r];return new Proxy(a,{get(c,l){if(!(l in c)){if(l==="default")return c.default!==void 0?c.default:c.__esModule?void 0:typeof c=="function"||typeof c=="object"?c:void 0;if(l==="__esModule")return!0;throw new Error(`Component "${String(l)}" is not exported by "${o}"`)}return c[l]}})};let i=`
|