@tscircuit/runframe 0.0.445 → 0.0.447
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/{chunk-IPPZN2ZX.js → chunk-HTSCVJ3B.js} +17 -9
- package/dist/preview.d.ts +5 -2
- package/dist/preview.js +1 -1
- package/dist/runner.js +1 -4
- package/dist/standalone-preview.min.js +2 -2
- package/dist/standalone.min.js +161 -161
- package/package.json +2 -2
|
@@ -13248,7 +13248,7 @@ ${u.type}: ${u.message}
|
|
|
13248
13248
|
50% { opacity: 0.2; }
|
|
13249
13249
|
100% { opacity: 0.6; }
|
|
13250
13250
|
}
|
|
13251
|
-
`,i.appendChild(O)}})}};a();const o=new MutationObserver(a);return o.observe(i,{childList:!0,subtree:!1,characterData:!1}),()=>{o.disconnect()}},[r,t,e,n])},iVt=E1("schematic-viewer"),aVt=()=>{E1.enable("schematic-viewer*")},oVt=iVt,sVt=r=>{const[e,t]=mt.useState(0),[n,i]=mt.useState(0);return mt.useEffect(()=>{if(!r.current)return;const a=()=>{var l;const s=(l=r.current)==null?void 0:l.getBoundingClientRect();t((s==null?void 0:s.width)||0),i((s==null?void 0:s.height)||0)};a();const o=new ResizeObserver(a);return o.observe(r.current),window.addEventListener("resize",a),()=>{o.disconnect(),window.removeEventListener("resize",a)}},[]),{containerWidth:e,containerHeight:n}},lVt=oVt.extend("useComponentDragging"),cVt=({onEditEvent:r,editEvents:e=[],circuitJson:t,cancelDrag:n,svgToScreenProjection:i,realToSvgProjection:a,enabled:o=!1})=>{const[s,l]=mt.useState(null),c=Tc(a,i),u=mt.useRef(null),f=mt.useRef(null),p=mt.useRef(new Map);mt.useEffect(()=>{e.forEach(E=>{"edit_event_type"in E&&E.edit_event_type==="edit_schematic_component_location"&&!E.in_progress&&p.current.set(E.schematic_component_id,{...E.new_center})})},[e]);const v=mt.useCallback(E=>{if(!o)return;const C=E.target.closest('[data-circuit-json-type="schematic_component"]');if(!C)return;const O=C.getAttribute("data-schematic-component-id");if(!O)return;n&&n();const U=hg(t).schematic_component.get(O);if(!U)return;u.current={x:E.clientX,y:E.clientY};let q;const Y=p.current.get(O);if(Y)q={...Y};else{const K=Qze({editEvents:e,schematic_component_id:O});q={x:U.center.x+K.x,y:U.center.y+K.y},p.current.set(O,{...q})}const Q={edit_event_id:Math.random().toString(36).substr(2,9),edit_event_type:"edit_schematic_component_location",schematic_component_id:O,original_center:q,new_center:{...q},in_progress:!0,created_at:Date.now(),_element:C};f.current=Q,l(Q)},[n,o,t,e]),x=mt.useCallback(E=>{if(!f.current||!u.current)return;const b={x:E.clientX-u.current.x,y:E.clientY-u.current.y},C={x:b.x/c.a,y:b.y/c.d},O={...f.current,new_center:{x:f.current.original_center.x+C.x,y:f.current.original_center.y+C.y}};f.current=O,l(O)},[c]),S=mt.useCallback(()=>{if(!f.current)return;const E={...f.current,in_progress:!1};p.current.set(E.schematic_component_id,{...E.new_center}),lVt("handleMouseUp calling onEditEvent with new edit event",{newEditEvent:E}),r&&r(E),f.current=null,u.current=null,l(null)},[r]);return mt.useEffect(()=>(window.addEventListener("mousemove",x),window.addEventListener("mouseup",S),()=>{window.removeEventListener("mousemove",x),window.removeEventListener("mouseup",S)}),[x,S]),{handleMouseDown:v,isDragging:!!f.current,activeEditEvent:s}},uVt=({onClick:r,active:e})=>ut.jsx("div",{onClick:r,style:{position:"absolute",top:"16px",right:"16px",backgroundColor:e?"#4CAF50":"#fff",color:e?"#fff":"#000",padding:"8px",borderRadius:"4px",cursor:"pointer",boxShadow:"0 2px 4px rgba(0,0,0,0.1)",display:"flex",alignItems:"center",gap:"4px",zIndex:1e3},children:ut.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[ut.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),ut.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})}),fVt=({circuitJson:r,containerStyle:e,editEvents:t=[],onEditEvent:n,defaultEditMode:i=!1,debugGrid:a=!1,editingEnabled:o=!1,debug:s=!1,clickToInteractEnabled:l=!1,colorOverrides:c})=>{s&&aVt();const[u,f]=mt.useState(i),[p,v]=mt.useState(!l),x=mt.useRef(null),S=mt.useRef(null),E=Oe=>{const Ue=Oe.touches[0];S.current={x:Ue.clientX,y:Ue.clientY}},b=Oe=>{const Ue=Oe.changedTouches[0],Ie=S.current;if(!Ie)return;const ke=Math.abs(Ue.clientX-Ie.x),ot=Math.abs(Ue.clientY-Ie.y);ke<10&&ot<10&&(Oe.preventDefault(),v(!0)),S.current=null},[C,O]=mt.useState([]),U=mt.useRef(r),q=Oe=>`${(Oe==null?void 0:Oe.length)||0}_${(Oe==null?void 0:Oe.editCount)||0}`;mt.useEffect(()=>{const Oe=q(r),Ue=q(U.current);Oe!==Ue&&(O([]),U.current=r)},[r]);const{ref:Y,cancelDrag:Q,transform:K}=Zze({onSetTransform(Oe){x.current&&(x.current.style.transform=cw(Oe))},enabled:p}),{containerWidth:te,containerHeight:J}=sVt(Y),fe=mt.useMemo(()=>!te||!J?"":loe(r,{width:te,height:J||720,grid:a?{cellSize:1,labelCells:!0}:void 0,colorOverrides:c}),[r,te,J]),he=mt.useMemo(()=>{var Ue;if(!fe)return Zm();const Oe=(Ue=fe.match(/data-real-to-screen-transform="([^"]+)"/))==null?void 0:Ue[1];try{return rH(Oe)}catch(Ie){return console.error(Ie),Zm()}},[fe]),ve=Oe=>{O(Ue=>[...Ue,Oe]),n&&n(Oe)},Te=mt.useMemo(()=>[...t,...C],[t,C]),{handleMouseDown:Pe,isDragging:Ee,activeEditEvent:Ce}=cVt({onEditEvent:ve,cancelDrag:Q,realToSvgProjection:he,svgToScreenProjection:K,circuitJson:r,editEvents:Te,enabled:u&&p});nVt({svgDivRef:x,editEvents:Te,realToSvgProjection:he,svgToScreenProjection:K,activeEditEvent:Ce}),rVt({svgDivRef:x,circuitJson:r,activeEditEvent:Ce,editEvents:Te});const be=mt.useMemo(()=>ut.jsx("div",{ref:x,style:{pointerEvents:l?p?"auto":"none":"auto",transformOrigin:"0 0"},dangerouslySetInnerHTML:{__html:fe}}),[fe,p,l]);return ut.jsxs("div",{ref:Y,style:{position:"relative",backgroundColor:"transparent",overflow:"hidden",cursor:Ee?"grabbing":l&&!p?"pointer":"grab",minHeight:"300px",...e},onMouseDown:Oe=>{if(l&&!p){Oe.preventDefault(),Oe.stopPropagation();return}Pe(Oe)},onMouseDownCapture:Oe=>{if(l&&!p){Oe.preventDefault(),Oe.stopPropagation();return}},onTouchStart:E,onTouchEnd:b,children:[!p&&l&&ut.jsx("div",{onClick:Oe=>{Oe.preventDefault(),Oe.stopPropagation(),v(!0)},style:{position:"absolute",inset:0,cursor:"pointer",zIndex:10,display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"all",touchAction:"pan-x pan-y pinch-zoom"},children:ut.jsx("div",{style:{backgroundColor:"rgba(0, 0, 0, 0.8)",color:"white",padding:"12px 24px",borderRadius:"8px",fontSize:"16px",fontFamily:"sans-serif",pointerEvents:"none"},children:typeof window<"u"&&("ontouchstart"in window||navigator.maxTouchPoints>0)?"Touch to Interact":"Click to Interact"})}),o&&ut.jsx(uVt,{active:u,onClick:()=>f(!u)}),be]})},dVt=r=>{const[e,t]=mt.useState(0),[n,i]=mt.useState(0);return mt.useEffect(()=>{if(!r.current)return;const a=()=>{var l;const s=(l=r.current)==null?void 0:l.getBoundingClientRect();t((s==null?void 0:s.width)||0),i((s==null?void 0:s.height)||0)};a();const o=new ResizeObserver(a);return o.observe(r.current),window.addEventListener("resize",a),()=>{o.disconnect(),window.removeEventListener("resize",a)}},[]),{containerWidth:e,containerHeight:n}};E1("assembly-viewer");var pVt=()=>{E1.enable("assembly-viewer*")},hVt=({circuitJson:r,containerStyle:e,debugGrid:t=!1,debug:n=!1})=>{n&&pVt();const i=mt.useRef(null),{ref:a}=Zze({onSetTransform(u){i.current&&(i.current.style.transform=cw(u))}}),{containerWidth:o,containerHeight:s}=dVt(a),l=mt.useMemo(()=>!o||!s?"":Vze(r,{width:o,height:s||720}),[r,o,s]);mt.useMemo(()=>{var f;if(!l)return Zm();const u=(f=l.match(/data-real-to-screen-transform="([^"]+)"/))==null?void 0:f[1];try{return rH(u)}catch(p){return console.error(p),Zm()}},[l]);const c=mt.useMemo(()=>ut.jsx("div",{ref:i,style:{pointerEvents:"auto",transformOrigin:"0 0"},dangerouslySetInnerHTML:{__html:l}}),[l]);return ut.jsx("div",{ref:a,style:{position:"relative",backgroundColor:"#F5F1ED",overflow:"hidden",minHeight:"300px",...e},children:c})};const Kze=["Initialize a tscircuit project using [tsci init](https://github.com/tscircuit/cli) before adding components.","Define reusable modules with cached routes using [<subcircuit />](https://docs.tscircuit.com/elements/subcircuit)","Run `tsci dev` on the command line to preview your boards before export",'Use units like mm or mils consistently across your designs (e.g. pcbX="10mm")',"Quickly set footprints with the [footprint prop](https://docs.tscircuit.com/footprints/footprinter-strings)","Check out the guide on [ordering prototypes](https://docs.tscircuit.com/building-electronics/ordering-prototypes)","Use [net labels](https://docs.tscircuit.com/elements/net) and [group elements](https://docs.tscircuit.com/elements/group) to organize complex schematics.","You can manually drag components on the PCB and Schematic using [manual edits](https://docs.tscircuit.com/guides/manual-edits)","Every tscircuit module can export to [Circuit JSON](https://github.com/tscircuit/circuit-json), Gerbers, Pick'n'Place CSV files, Bill of Materials CSV and more","You can import components from [JLCPCB](https://docs.tscircuit.com/guides/importing-modules-and-chips/importing-from-jlcpcb) or [KiCad](https://docs.tscircuit.com/guides/importing-modules-and-chips/importing-from-kicad)","Any module you push to the [registry](https://tscircuit.com/trending) will have [simple image urls](https://docs.tscircuit.com/web-apis/image-generation-api) you can use display images on a website","The default [Parts Engine](https://docs.tscircuit.com/guides/platform-configuration) will automatically find parts from common vendors for your BOM",'[Pin selectors](https://docs.tscircuit.com/guides/using-sel-references) are similar to CSS selectors, ".R1 > .pin1" means "connect to the first pin of the component R1"',"You can use the [sel](https://docs.tscircuit.com/guides/using-sel-references) object to select pins in a type-safe way","Publish modules via the [registry](https://tscircuit.com/trending) for working with a team or sharing your work","[Explore tutorials](https://docs.tscircuit.com/category/tutorials) for real-world circuit design examples.","Upload your Circuit JSON to [circuitjson.com](https://circuitjson.com) for a quick preview.","You can display Circuit JSON in 3D, PCB or Schematic mode with the [<CircuitJsonPreview />](https://docs.tscircuit.com/elements/circuitjsonpreview) React component","Use a [<group />](https://docs.tscircuit.com/elements/group) element to move multiple components at once in a schematic or PCB layout.","Check out the [GitHub Discussions page](https://github.com/tscircuit/tscircuit/discussions) to upvote features","You can customize the autorouter using the [autorouter prop](https://docs.tscircuit.com/elements/board#setting-the-autorouter)","Use the [<constraint />](https://docs.tscircuit.com/footprints/constraint) element to enforce geometric relationships in PCB designs.","Join the [Discord server](https://tscircuit.com/join) to discuss issues and get help directly from the community."],mVt=(()=>{let r=Kze[Math.floor(Math.random()*Kze.length)];return r=r.replace(/</g,"<"),r=r.replace(/>/g,">"),r=r.replace(new RegExp('(?<!href=")(?<!\\()(?<!\\]\\()(https?:\\/\\/[^\\s\\)\\]]+)',"g"),(e,t)=>`<a class="rf-text-blue-500 rf-underline" href="${e}" target="_blank">${e}</a>`),r=r.replace(/\[([^\]]+)\]\((https?:\/\/[^\)]+)\)/g,'<a class="rf-text-blue-500 rf-underline" href="$2" target="_blank">$1</a>'),r})(),L8=({onRunClicked:r})=>ut.jsxs("div",{className:"rf-flex rf-flex-col rf-items-center rf-justify-center rf-h-full rf-bg-gray-50 rf-text-gray-500 rf-p-4",children:[ut.jsx(IDt,{className:"rf-size-14 rf-mb-4"}),ut.jsxs("p",{className:"rf-text-md rf-break-words rf-max-w-xl rf-text-center",children:["Tip: ",ut.jsx("span",{dangerouslySetInnerHTML:{__html:mVt}})]}),r&&ut.jsxs(HE,{className:"rf-mt-4 rf-bg-blue-600 rf-hover:bg-blue-500",onClick:r,children:["Run Code",ut.jsx(FDt,{className:"rf-w-3 rf-h-3 rf-ml-2"})]})]}),Mk=({text:r,onClick:e})=>ut.jsx("span",{className:"rf-cursor-pointer rf-underline rf-text-blue-600 rf-mx-2",onClick:e,children:r}),Ck=r=>{var e;return ut.jsxs("div",{className:"rf-leading-5",children:[ut.jsx("div",{className:"rf-py-2 rf-font-bold",children:r.column.name}),ut.jsx("div",{children:((e=r.field)==null?void 0:e.call(r))??ut.jsx("input",{type:"text",className:"rf-border rf-rounded rf-p-1 rf-w-full",onChange:t=>{var n;(n=r.onTextChange)==null||n.call(r,t.target.value)}})})]})},vVt=({open:r,children:e,title:t,onClose:n})=>r?ut.jsx("div",{className:"rf-fixed rf-inset-0 rf-bg-black rf-bg-opacity-50 rf-flex rf-justify-center rf-items-center rf-z-50",onClick:n,children:ut.jsxs("div",{className:"rf-bg-white rf-p-5 rf-rounded-lg rf-relative rf-w-11/12 rf-max-w-2xl",onClick:i=>{i.preventDefault(),i.stopPropagation()},children:[ut.jsx("h2",{className:"rf-mt-0 rf-text-md rf-pb-4",children:t}),ut.jsx("button",{type:"button",className:"rf-absolute rf-top-2 rf-right-4 rf-text-2xl rf-font-bold",onClick:n,children:"×"}),e]})}):null,yVt=({elements:r})=>{const[e,t]=mt.useState({open:!1}),[n,i]=mt.useReducer((u,f)=>({...u,...f}),{}),a=[...new Set(r.map(u=>u.type))],o=r.map(u=>{const f=u[`${u.type}_id`],p=Object.fromEntries(Object.entries(u).filter(([x])=>!(x===`${u.type}_id`||!x.endsWith("_id")))),v=Object.fromEntries(Object.entries(u).filter(([x])=>!x.endsWith("_id")));return{primary_id:f,other_ids:p,...v,_og_elm:u}}),s=o.map(u=>{let f="";const p=v=>{const x=Object.keys(v.other_ids).find(b=>b.startsWith("source_"));if(!x)return`.${v.name}`;const S=x.slice(0,-3),E=o.find(b=>b.type===S&&b.primary_id===v.other_ids[x]);return E?"name"in E?`${p(E)} > .${v.name}`:`#${E.primary_id} > .${v.name}`:`??? > .${v.name}`};return"name"in u&&(f=p(u)),{...u,selector_path:f}}),l=[{key:"primary_id",name:"primary_id",renderCell:u=>ut.jsxs("div",{className:"rf-flex rf-items-center",children:[ut.jsx(Mk,{text:u.primary_id,onClick:()=>i({focused_id:u.primary_id,id_search:void 0,selector_search:void 0})}),ut.jsx("span",{className:"rf-flex-grow"}),ut.jsx(Mk,{text:"(JSON)",onClick:()=>t({open:!0,element:u._og_elm,title:u.primary_id})})]}),renderHeaderCell:u=>ut.jsx(Ck,{column:u,onTextChange:f=>i({id_search:f}),field:n.focused_id?()=>ut.jsxs("div",{children:["Focus:"," ",ut.jsx("span",{className:"rf-underline",children:n.focused_id}),ut.jsx(Mk,{text:"(unfocus)",onClick:()=>i({focused_id:void 0})})]}):void 0})},{key:"type",name:"type",renderHeaderCell:u=>ut.jsx(Ck,{column:u,field:()=>ut.jsxs("select",{onChange:f=>i({component_type_filter:f.target.value}),className:"rf-border rf-rounded rf-p-1 rf-w-full",children:[ut.jsx("option",{value:"any",children:"any"},"any"),ut.jsx("option",{value:"source",children:"source"},"source"),ut.jsx("option",{value:"source/pcb",children:"source/pcb"},"source/pcb"),ut.jsx("option",{value:"source/schematic",children:"source/schematic"},"source/schematic"),a.map(f=>ut.jsx("option",{value:f,children:f},f))]})})},{key:"name",name:"name",renderHeaderCell:u=>ut.jsx(Ck,{column:u,onTextChange:f=>i({name_search:f})})},{key:"selector_path",name:"selector_path",renderHeaderCell:u=>ut.jsx(Ck,{column:u,onTextChange:f=>i({selector_search:f})})},{key:"other_ids",name:"other_ids",renderCell:u=>ut.jsx("div",{className:"rf-space-x-2",children:Object.entries(u.other_ids).map(([f,p])=>ut.jsx(Mk,{text:p,onClick:()=>i({focused_id:p})},p))})}],c=s.filter(u=>{var f,p;return n.name_search?(p=(f=u.name)==null?void 0:f.toLowerCase())==null?void 0:p.includes(n.name_search.toLowerCase()):!0}).filter(u=>{var f;return!n.component_type_filter||n.component_type_filter==="any"?!0:n.component_type_filter==="source"?u.type.startsWith("source_"):n.component_type_filter==="source/pcb"?u.type.startsWith("source_")||u.type.startsWith("pcb_"):n.component_type_filter==="source/schematic"?u.type.startsWith("source_")||u.type.startsWith("schematic_"):(f=u.type)==null?void 0:f.includes(n.component_type_filter)}).filter(u=>n.selector_search?n.selector_search.split(" ").filter(p=>p.length>0).every(p=>{var v;return(v=u.selector_path)==null?void 0:v.includes(p)}):!0).filter(u=>{var f;return n.id_search?(f=u.primary_id)==null?void 0:f.includes(n.id_search):!0}).filter(u=>!!(!n.focused_id||u.primary_id===n.focused_id||Object.values(u.other_ids).includes(n.focused_id)));return ut.jsxs("div",{className:"rf-font-mono rf-text-xs rf-bg-white",children:[ut.jsx("div",{className:"rf-overflow-x-auto",children:ut.jsxs("table",{className:"rf-table-auto rf-w-full rf-text-left",children:[ut.jsx("thead",{children:ut.jsx("tr",{children:l.map(u=>ut.jsx("th",{className:"rf-px-4 rf-py-2 rf-border-b",children:u.renderHeaderCell?u.renderHeaderCell(u):u.name},u.key))})}),ut.jsx("tbody",{children:c.map((u,f)=>ut.jsx("tr",{className:"rf-hover:bg-gray-100",children:l.map(p=>ut.jsx("td",{className:"rf-px-4 rf-py-2 rf-border-b",children:p.renderCell?p.renderCell(u):u[p.key]},p.key))},f))})]})}),ut.jsx(vVt,{open:e.open,onClose:()=>t({open:!1}),title:e.open?e.title:"",children:ut.jsx("div",{className:"rf-bg-gray-800 rf-p-3 rf-text-white rf-rounded",children:ut.jsx("pre",{className:"rf-whitespace-pre-wrap",children:e.open?JSON.stringify(e.element,null,2):""})})})]})},gVt=(r,e)=>r==="jlcpcb"?ut.jsx("a",{className:"rf-underline rf-text-blue-500",target:"_blank",rel:"noreferrer",href:`https://jlcpcb.com/partdetail/${e}`,children:e}):e,_Vt=({circuitJson:r})=>{const e=r.filter(n=>n.type==="source_component"),t=new Set;for(const n of e)if(n.supplier_part_numbers)for(const i of Object.keys(n.supplier_part_numbers))t.add(i);return ut.jsx("div",{className:"rf-overflow-x-auto",children:ut.jsxs("table",{className:"rf-w-full rf-text-left rf-text-sm",children:[ut.jsx("thead",{children:ut.jsxs("tr",{className:"rf-border-b",children:[ut.jsx("th",{className:"rf-p-2",children:"Name"}),Array.from(t).map(n=>ut.jsx("th",{className:"rf-p-2 rf-capitalize",children:n},n))]})}),ut.jsx("tbody",{children:e.map(n=>ut.jsxs("tr",{className:"rf-border-b",children:[ut.jsx("td",{className:"rf-p-2",children:n.name}),Array.from(t).map(i=>{var a,o;return ut.jsx("td",{className:"rf-p-2",children:gVt(i,((o=(a=n.supplier_part_numbers)==null?void 0:a[i])==null?void 0:o[0])||"")},i)})]},n.source_component_id))})]})})};var xVt=k.enum(["up","down","left","right"]);k.enum(["top-to-bottom","left-to-right","bottom-to-top","right-to-left"]);var YE=k.array(k.string().or(k.number())),Jze=k.object({x:ci,y:ci,z:ci}),bVt=k.object({x:k.union([k.number(),k.string()]),y:k.union([k.number(),k.string()]),z:k.union([k.number(),k.string()])}),doe=k.object({rotationOffset:k.number().or(bVt).optional(),positionOffset:Jze.optional(),size:Jze.optional()}),SVt=doe.extend({stlUrl:k.string()}),EVt=doe.extend({objUrl:k.string(),mtlUrl:k.string().optional()}),wVt=doe.extend({jscad:k.record(k.any())}),TVt=k.union([k.string(),SVt,EVt,wVt]),MVt=k.custom(r=>!0),gx=k.object({pcbX:ci.optional(),pcbY:ci.optional(),pcbRotation:p5.optional(),layer:Zv.optional()}),Rk=k.object({pcbX:ci.optional(),pcbY:ci.optional(),pcbRotation:p5.optional(),schX:ci.optional(),schY:ci.optional(),schRotation:p5.optional(),layer:Zv.optional(),footprint:MVt.optional()}),CVt=k.object({supplierPartNumbers:k.record(SB,k.array(k.string())).optional()}),L2=Rk.merge(CVt).extend({key:k.any().optional(),name:k.string(),cadModel:TVt.optional(),children:k.any().optional(),symbolName:k.string().optional()});ci.or(k.enum(["2x","3x","4x"]));var Ak=k.object({pins:k.array(k.union([k.number(),k.string()])),direction:k.union([k.literal("top-to-bottom"),k.literal("left-to-right"),k.literal("bottom-to-top"),k.literal("right-to-left")])}),poe=k.object({leftSize:k.number().optional().describe("@deprecated, use leftPinCount"),topSize:k.number().optional().describe("@deprecated, use topPinCount"),rightSize:k.number().optional().describe("@deprecated, use rightPinCount"),bottomSize:k.number().optional().describe("@deprecated, use bottomPinCount"),leftPinCount:k.number().optional(),rightPinCount:k.number().optional(),topPinCount:k.number().optional(),bottomPinCount:k.number().optional(),leftSide:Ak.optional(),rightSide:Ak.optional(),topSide:Ak.optional(),bottomSide:Ak.optional()}),eUe=k.record(k.object({marginLeft:ci.optional(),marginRight:ci.optional(),marginTop:ci.optional(),marginBottom:ci.optional(),leftMargin:ci.optional(),rightMargin:ci.optional(),topMargin:ci.optional(),bottomMargin:ci.optional()})),tUe=k.object({x:ci,y:ci}),hoe=k.object({edit_event_id:k.string(),in_progress:k.boolean().optional(),created_at:k.number()}),RVt=hoe.extend({pcb_edit_event_type:k.literal("edit_component_location").describe("deprecated"),edit_event_type:k.literal("edit_pcb_component_location"),pcb_component_id:k.string(),original_center:k.object({x:k.number(),y:k.number()}),new_center:k.object({x:k.number(),y:k.number()})}),AVt=hoe.extend({pcb_edit_event_type:k.literal("edit_trace_hint").describe("deprecated"),edit_event_type:k.literal("edit_pcb_trace_hint").optional(),pcb_port_id:k.string(),pcb_trace_hint_id:k.string().optional(),route:k.array(k.object({x:k.number(),y:k.number(),via:k.boolean().optional()}))}),PVt=hoe.extend({edit_event_type:k.literal("edit_schematic_component_location"),schematic_component_id:k.string(),original_center:k.object({x:k.number(),y:k.number()}),new_center:k.object({x:k.number(),y:k.number()})});k.union([RVt,AVt,PVt]);var NVt=k.object({selector:k.string(),relative_to:k.string().optional().default("group_center").describe("Can be a selector or 'group_center'"),center:K1}),DVt=k.object({pcb_port_selector:k.string(),offsets:k.array(s4)}),LVt=k.object({selector:k.string(),relative_to:k.string().optional().default("group_center").describe("Can be a selector or 'group_center'"),center:K1}),OVt=k.object({pcb_placements:k.array(NVt).optional(),manual_trace_hints:k.array(DVt).optional(),schematic_placements:k.array(LVt).optional()}),moe=k.object({layoutMode:k.enum(["grid","flex","none"]).optional(),position:k.enum(["absolute","relative"]).optional(),grid:k.boolean().optional(),gridCols:k.number().or(k.string()).optional(),gridRows:k.number().or(k.string()).optional(),gridTemplateRows:k.string().optional(),gridTemplateColumns:k.string().optional(),gridTemplate:k.string().optional(),gridGap:k.number().or(k.string()).optional(),flex:k.boolean().or(k.string()).optional(),flexDirection:k.enum(["row","column"]).optional(),alignItems:k.enum(["start","center","end","stretch"]).optional(),justifyContent:k.enum(["start","center","end","stretch"]).optional(),flexRow:k.boolean().optional(),flexColumn:k.boolean().optional(),gap:k.number().or(k.string()).optional()}),zVt=k.object({serverUrl:k.string().optional(),inputFormat:k.enum(["simplified","circuit-json"]).optional(),serverMode:k.enum(["job","solve-endpoint"]).optional(),serverCacheEnabled:k.boolean().optional(),cache:k.custom(r=>!0).optional(),groupMode:k.enum(["sequential-trace","subcircuit"]).optional(),algorithmFn:k.custom(r=>typeof r=="function"||r===void 0).optional(),local:k.boolean().optional()}),nUe=k.union([zVt,k.literal("sequential-trace"),k.literal("subcircuit"),k.literal("auto"),k.literal("auto-local"),k.literal("auto-cloud")]),rUe=Rk.extend({name:k.string().optional(),children:k.any().optional(),key:k.any().optional(),...moe.shape,pcbWidth:mr.optional(),pcbHeight:mr.optional(),schWidth:mr.optional(),schHeight:mr.optional(),pcbLayout:moe.optional(),schLayout:moe.optional()}),iUe=k.custom(r=>"findPart"in r),aUe=rUe.extend({layout:k.custom(r=>!0).optional(),manualEdits:OVt.optional(),schAutoLayoutEnabled:k.boolean().optional(),schTraceAutoLabelEnabled:k.boolean().optional(),routingDisabled:k.boolean().optional(),defaultTraceWidth:mr.optional(),minTraceWidth:mr.optional(),partsEngine:iUe.optional(),pcbRouteCache:k.custom(r=>!0).optional(),autorouter:nUe.optional()}),UVt=aUe.extend({subcircuit:k.literal(!0)}),oUe=k.discriminatedUnion("subcircuit",[rUe.extend({subcircuit:k.literal(!1).optional()}),UVt]),voe=aUe.extend({width:ci.optional(),height:ci.optional(),outline:k.array(tUe).optional(),outlineOffsetX:ci.optional(),outlineOffsetY:ci.optional(),material:k.enum(["fr4","fr1"]).default("fr4")}),IVt=k.string().or(k.array(k.string()).readonly()).or(k.array(k.string())),kVt=k.custom().pipe(k.record(k.string(),IVt)),FVt=k.record(k.string(),k.string().or(k.array(k.string()).readonly()).or(k.array(k.string()))),yoe=L2.extend({manufacturerPartNumber:k.string().optional(),pinLabels:FVt.optional(),internallyConnectedPins:k.array(k.array(k.string())).optional(),externallyConnectedPins:k.array(k.array(k.string())).optional(),schPinArrangement:poe.optional(),schPortArrangement:poe.optional(),schPinStyle:eUe.optional(),schPinSpacing:ci.optional(),schWidth:ci.optional(),schHeight:ci.optional(),noSchematicRepresentation:k.boolean().optional(),connections:kVt.optional()}),sUe=L2.extend({manufacturerPartNumber:k.string().optional(),pinLabels:k.record(k.number().or(k.string()),k.string().or(k.array(k.string()))).optional(),schPinStyle:eUe.optional(),schPinSpacing:ci.optional(),schWidth:ci.optional(),schHeight:ci.optional(),schDirection:k.enum(["left","right"]).optional(),schPortArrangement:poe.optional(),pinCount:k.union([k.literal(2),k.literal(3)]).optional(),internallyConnectedPins:k.array(k.array(k.string())).optional()}),Pk=k.custom().transform(r=>{if(r!==void 0)return ci.parse(r)}),lUe=k.union([gx.omit({pcbRotation:!0,layer:!0}).extend({name:k.string().optional(),shape:k.literal("circle"),holeDiameter:ci,outerDiameter:ci,portHints:YE.optional()}),gx.omit({pcbRotation:!0,layer:!0}).extend({name:k.string().optional(),shape:k.literal("oval"),outerWidth:ci,outerHeight:ci,holeWidth:Pk,holeHeight:Pk,innerWidth:ci.optional().describe("DEPRECATED use holeWidth"),innerHeight:ci.optional().describe("DEPRECATED use holeHeight"),portHints:YE.optional()}),gx.omit({pcbRotation:!0,layer:!0}).extend({name:k.string().optional(),shape:k.literal("pill"),outerWidth:ci,outerHeight:ci,holeWidth:Pk,holeHeight:Pk,innerWidth:ci.optional().describe("DEPRECATED use holeWidth"),innerHeight:ci.optional().describe("DEPRECATED use holeHeight"),portHints:YE.optional()}),gx.omit({pcbRotation:!0,layer:!0}).extend({name:k.string().optional(),holeDiameter:ci,rectPadWidth:ci,rectPadHeight:ci,holeShape:k.literal("circle").optional(),padShape:k.literal("rect").optional(),shape:k.literal("circularHoleWithRectPad").optional(),portHints:YE.optional()}).refine(r=>r.shape==="circularHoleWithRectPad"?r.holeDiameter&&r.rectPadWidth&&r.rectPadHeight:!0,{message:"Missing required fields for circularHoleWithRectPad"})]).refine(r=>("innerWidth"in r&&r.innerWidth!==void 0&&(r.holeWidth??(r.holeWidth=r.innerWidth)),"innerHeight"in r&&r.innerHeight!==void 0&&(r.holeHeight??(r.holeHeight=r.innerHeight)),r)),BVt=k.string().or(k.array(k.string()).readonly()).or(k.array(k.string())),cUe=r=>k.record(k.enum(r),BVt),HVt=["pin1","pin2","pos","neg"],uUe=L2.extend({resistance:d6,pullupFor:k.string().optional(),pullupTo:k.string().optional(),pulldownFor:k.string().optional(),pulldownTo:k.string().optional(),connections:cUe(HVt).optional()}),fUe=L2.extend({maxResistance:d6,pinVariant:k.enum(["two_pin","three_pin"]).optional()}),dUe=L2.extend({frequency:CP,loadCapacitance:p6,pinVariant:k.enum(["two_pin","four_pin"]).optional()}),pUe=L2.extend({frequency:CP,loadCapacitance:p6,pinVariant:k.enum(["no_ground","ground_pin","two_ground_pins"]).optional()});voe.extend({leftPinCount:k.number().optional(),rightPinCount:k.number().optional(),topPinCount:k.number().optional(),bottomPinCount:k.number().optional(),leftPins:k.array(k.string()).optional(),rightPins:k.array(k.string()).optional(),topPins:k.array(k.string()).optional(),bottomPins:k.array(k.string()).optional(),pinPitch:ci.optional(),innerHoles:k.boolean().optional()});var jVt=["pin1","pin2","pos","neg","anode","cathode"],hUe=L2.extend({capacitance:p6,maxVoltageRating:h6.optional(),schShowRatings:k.boolean().optional().default(!1),polarized:k.boolean().optional().default(!1),decouplingFor:k.string().optional(),decouplingTo:k.string().optional(),bypassFor:k.string().optional(),bypassTo:k.string().optional(),maxDecouplingTraceLength:k.number().optional(),connections:cUe(jVt).optional()});k.object({name:k.string()}),k.object({name:k.string().optional(),pcbOnly:k.boolean().optional(),schOnly:k.boolean().optional()});var VVt=k.object({pcb:k.literal(!0).optional(),xDist:ci,left:k.string(),right:k.string(),edgeToEdge:k.literal(!0).optional(),centerToCenter:k.literal(!0).optional()}),GVt=k.object({pcb:k.literal(!0).optional(),yDist:ci,top:k.string(),bottom:k.string(),edgeToEdge:k.literal(!0).optional(),centerToCenter:k.literal(!0).optional()}),qVt=k.object({pcb:k.literal(!0).optional(),sameY:k.literal(!0).optional(),for:k.array(k.string())}),$Vt=k.object({pcb:k.literal(!0).optional(),sameX:k.literal(!0).optional(),for:k.array(k.string())}),mUe=k.union([VVt,GVt,qVt,$Vt]),YVt=gx.omit({pcbRotation:!0}).extend({shape:k.literal("rect"),width:ci,height:ci,portHints:YE.optional()}),XVt=gx.omit({pcbRotation:!0}).extend({shape:k.literal("rotated_rect"),width:ci,height:ci,ccwRotation:k.number(),portHints:YE.optional()}),WVt=gx.omit({pcbRotation:!0}).extend({shape:k.literal("circle"),radius:ci,portHints:YE.optional()}),ZVt=gx.omit({pcbRotation:!0}).extend({shape:k.literal("pill"),width:ci,height:ci,radius:ci,portHints:YE.optional()}),vUe=k.union([WVt,YVt,XVt,ZVt]),QVt=gx.omit({pcbRotation:!0}).extend({shape:k.literal("rect"),width:ci,height:ci}),KVt=gx.omit({pcbRotation:!0}).extend({shape:k.literal("circle"),radius:ci});k.union([KVt,QVt]);var yUe=gx.omit({pcbRotation:!0}).extend({name:k.string().optional(),diameter:ci.optional(),radius:ci.optional()}).transform(r=>({...r,diameter:r.diameter??2*r.radius,radius:r.radius??r.diameter/2})),goe=k.union([k.string(),k.custom(r=>!!r.getPortSelector)]),gUe=k.object({key:k.string().optional(),thickness:ci.optional(),schematicRouteHints:k.array(tUe).optional(),pcbRouteHints:k.array(s4).optional(),schDisplayLabel:k.string().optional(),maxLength:ci.optional()}),_Ue=k.union([gUe.extend({path:k.array(goe)}),gUe.extend({from:goe,to:goe})]),xUe=k.object({originalLayer:Zv.default("top").optional()}),JVt=k.number().or(k.string().endsWith("mAh")).transform(r=>{if(typeof r=="string"){const e=r.replace("mAh",""),t=Number.parseFloat(e);if(Number.isNaN(t))throw new Error("Invalid capacity");return t}return r}).describe("Battery capacity in mAh"),bUe=L2.extend({capacity:JVt.optional()}),SUe=L2.extend({pinCount:k.number(),pitch:ci.optional(),schFacingDirection:k.enum(["up","down","left","right"]).optional(),gender:k.enum(["male","female"]).optional().default("male"),showSilkscreenPinLabels:k.boolean().optional(),doubleRow:k.boolean().optional(),holeDiameter:ci.optional(),platedDiameter:ci.optional(),pinLabels:k.array(k.string()).optional(),facingDirection:k.enum(["left","right"]).optional()}),EUe=k.object({net:k.string().optional(),schX:ci.optional(),schY:ci.optional(),schRotation:p5.optional(),anchorSide:k.enum(["left","up","right","down"]).optional()}),wUe=yoe.extend({}),TUe=L2.extend({type:k.enum(["npn","pnp","bjt","jfet","mosfet"])}),MUe=L2.extend({channelType:k.enum(["n","p"]),mosfetMode:k.enum(["enhancement","depletion"])}),CUe=L2.extend({inductance:xB}),eGt=k.enum(["anode","cathode","pin1","pin2","pos","neg"]),tGt=k.string().or(k.array(k.string()).readonly()).or(k.array(k.string())),nGt=k.record(eGt,tGt),rGt=k.enum(["standard","schottky","zener","photo","tvs"]),RUe=L2.extend({connections:nGt.optional(),variant:rGt.optional().default("standard"),standard:k.boolean().optional(),schottky:k.boolean().optional(),zener:k.boolean().optional(),photo:k.boolean().optional(),tvs:k.boolean().optional()}).superRefine((r,e)=>{if([r.standard,r.schottky,r.zener,r.photo,r.tvs].filter(Boolean).length>1)return e.addIssue({code:k.ZodIssueCode.custom,message:"Exactly one diode variant must be enabled",path:[]}),k.INVALID}).transform(r=>{const e={...r,standard:!1,schottky:!1,zener:!1,photo:!1,tvs:!1};if(r.standard)e.standard=!0;else if(r.schottky)e.schottky=!0;else if(r.zener)e.zener=!0;else if(r.photo)e.photo=!0;else if(r.tvs)e.tvs=!0;else switch(r.variant){case"standard":e.standard=!0;break;case"schottky":e.schottky=!0;break;case"zener":e.zener=!0;break;case"photo":e.photo=!0;break;case"tvs":e.tvs=!0;break;default:e.standard=!0}return e}),AUe=L2.extend({color:k.string().optional()}),PUe=L2.extend({type:k.enum(["spst","spdt","dpst","dpdt"]).optional(),isNormallyClosed:k.boolean().optional().default(!1),spst:k.boolean().optional(),spdt:k.boolean().optional(),dpst:k.boolean().optional(),dpdt:k.boolean().optional()}).transform(r=>{const e={...r};switch(e.dpdt?e.type="dpdt":e.spst?e.type="spst":e.spdt?e.type="spdt":e.dpst&&(e.type="dpst"),e.type){case"spdt":e.spdt=!0;break;case"spst":e.spst=!0;break;case"dpst":e.dpst=!0;break;case"dpdt":e.dpdt=!0;break}return e}),NUe=gx.extend({text:k.string(),anchorAlignment:k.enum(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),font:k.enum(["tscircuit2024"]).optional(),fontSize:mr.optional(),color:k.string().optional()}),DUe=gx.omit({pcbX:!0,pcbY:!0,pcbRotation:!0}).extend({route:k.array(s4),strokeWidth:mr.optional(),color:k.string().optional()});k.object({layer:k.string().optional(),thickness:ci.optional(),route:k.array(s4)});var LUe=Rk.extend({fromLayer:Zv,toLayer:Zv,holeDiameter:ci,outerDiameter:ci}),OUe=k.union([gx.omit({pcbRotation:!0}).extend({shape:k.literal("circle"),radius:ci}),gx.extend({shape:k.literal("rect"),width:ci,height:ci})]),zUe=L2.extend({voltage:h6});k.object({schX:ci,schY:ci,width:ci,height:ci}),k.object({x1:ci,y1:ci,x2:ci,y2:ci});var iGt=k.enum(["top_left","top_center","top_right","center_left","center","center_right","bottom_left","bottom_center","bottom_right"]),aGt=k.enum(["center","left","right","top","bottom"]),UUe=k.object({schX:ci,schY:ci,text:k.string(),anchor:k.union([aGt.describe("legacy"),iGt]),color:k.string().default("#000000"),schRotation:p5.default(0)});k.object({points:k.array(K1),isFilled:k.boolean().optional().default(!1),fillColor:k.enum(["red","blue"]).optional()});var IUe=gx.extend({text:k.string(),anchorAlignment:k.enum(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),font:k.enum(["tscircuit2024"]).optional(),fontSize:mr.optional()}),kUe=gx.omit({pcbX:!0,pcbY:!0,pcbRotation:!0}).extend({route:k.array(s4),strokeWidth:mr.optional()}),FUe=gx.omit({pcbX:!0,pcbY:!0,pcbRotation:!0}).extend({strokeWidth:ci,x1:ci,y1:ci,x2:ci,y2:ci}),BUe=gx.omit({pcbRotation:!0}).extend({isFilled:k.boolean().optional(),isOutline:k.boolean().optional(),strokeWidth:ci.optional(),width:ci,height:ci}),HUe=gx.omit({pcbRotation:!0}).extend({isFilled:k.boolean().optional(),isOutline:k.boolean().optional(),strokeWidth:ci.optional(),radius:ci}),jUe=k.object({x:ci,y:ci,via:k.boolean().optional(),toLayer:Zv.optional()}),VUe=k.object({for:k.string().optional().describe("Selector for the port you're targeting, not required if you're inside a trace"),order:k.number().optional(),offset:s4.or(jUe).optional(),offsets:k.array(s4).or(k.array(jUe)).optional(),traceWidth:k.number().optional()});Rk.extend({name:k.string(),pinNumber:k.number().optional(),aliases:k.array(k.string()).optional(),direction:xVt}),k.object({partsEngine:iUe.optional(),autorouter:nUe.optional(),registryApiUrl:k.string().optional(),cloudAutorouterUrl:k.string().optional()});function Nk([r,e],[t,n],{lineThickness:i=0}={}){return i===0?O8(r,e,t,n):oGt(r,e,t,n)<=i}function O8(r,e,t,n){const i=Dk(r,e,t),a=Dk(r,e,n),o=Dk(t,n,r),s=Dk(t,n,e);return!!(i!==a&&o!==s||i===0&&Lk(r,t,e)||a===0&&Lk(r,n,e)||o===0&&Lk(t,r,n)||s===0&&Lk(t,e,n))}function Dk(r,e,t){const n=(e.y-r.y)*(t.x-e.x)-(e.x-r.x)*(t.y-e.y);return n===0?0:n>0?1:2}function Lk(r,e,t){return e.x<=Math.max(r.x,t.x)&&e.x>=Math.min(r.x,t.x)&&e.y<=Math.max(r.y,t.y)&&e.y>=Math.min(r.y,t.y)}function oGt(r,e,t,n){if(r.x===e.x&&r.y===e.y)return s2(r,t,n);if(t.x===n.x&&t.y===n.y)return s2(t,r,e);if(O8(r,e,t,n))return 0;const i=[s2(r,t,n),s2(e,t,n),s2(t,r,e),s2(n,r,e)];return Math.min(...i)}function s2(r,e,t){const n=(t.x-e.x)**2+(t.y-e.y)**2;if(n===0)return E3(r,e);let i=((r.x-e.x)*(t.x-e.x)+(r.y-e.y)*(t.y-e.y))/n;i=Math.max(0,Math.min(1,i));const a={x:e.x+i*(t.x-e.x),y:e.y+i*(t.y-e.y)};return E3(r,a)}function E3(r,e){const t=r.x-e.x,n=r.y-e.y;return Math.sqrt(t*t+n*n)}function sGt(r,e,t,n){if(r.x===e.x&&r.y===e.y)return s2(r,t,n);if(t.x===n.x&&t.y===n.y)return s2(t,r,e);if(O8(r,e,t,n))return 0;const i=[s2(r,t,n),s2(e,t,n),s2(t,r,e),s2(n,r,e)];return Math.min(...i)}function lGt(r,e,t){const n={x:t.minX,y:t.minY},i={x:t.maxX,y:t.minY},a={x:t.minX,y:t.maxY},o={x:t.maxX,y:t.maxY};if(O8(r,e,n,i)||O8(r,e,i,o)||O8(r,e,o,a)||O8(r,e,a,n)||r.x>=t.minX&&r.x<=t.maxX&&r.y>=t.minY&&r.y<=t.maxY&&e.x>=t.minX&&e.x<=t.maxX&&e.y>=t.minY&&e.y<=t.maxY)return 0;const s=[s2(n,r,e),s2(i,r,e),s2(a,r,e),s2(o,r,e)];if(r.x>=t.minX&&r.x<=t.maxX&&r.y>=t.minY&&r.y<=t.maxY||e.x>=t.minX&&e.x<=t.maxX&&e.y>=t.minY&&e.y<=t.maxY)return 0;if(r.x<t.minX||r.x>t.maxX||r.y<t.minY||r.y>t.maxY){const l=uE(r.x,t.minX,t.maxX),c=uE(r.y,t.minY,t.maxY);s.push(E3(r,{x:l,y:c}))}if(e.x<t.minX||e.x>t.maxX||e.y<t.minY||e.y>t.maxY){const l=uE(e.x,t.minX,t.maxX),c=uE(e.y,t.minY,t.maxY);s.push(E3(e,{x:l,y:c}))}return Math.min(...s)}function cGt(r,e,t){const n={x:t.x,y:t.y};if(r.x===e.x&&r.y===e.y)return Math.max(0,E3(r,n)-t.radius);const i={x:e.x-r.x,y:e.y-r.y},a={x:n.x-r.x,y:n.y-r.y},o=i.x*i.x+i.y*i.y,s=Math.max(0,Math.min(1,(i.x*a.x+i.y*a.y)/o)),l={x:r.x+s*i.x,y:r.y+s*i.y},c=E3(l,n);return Math.max(0,c-t.radius)}var GUe=(r,e)=>{const t={x:e.x-r.x,y:e.y-r.y},n=Math.sqrt(t.x**2+t.y**2);return{x:t.x/n,y:t.y/n}},qUe=r=>{switch(r){case"up":return{x:0,y:1};case"down":return{x:0,y:-1};case"left":return{x:-1,y:0};case"right":return{x:1,y:0}}},uGt=class{constructor({objects:r,getBounds:e,getId:t,CELL_SIZE:n}){Je(this,"buckets");Je(this,"objectsById");Je(this,"getBounds");Je(this,"getId");Je(this,"CELL_SIZE",.4);Je(this,"_idCounter",0);this.buckets=new Map,this.objectsById=new Map,this.getBounds=e,this.getId=t??(()=>this._getNextId()),this.CELL_SIZE=n??this.CELL_SIZE;for(const i of r)this.addObject(i)}_getNextId(){return`${this._idCounter++}`}addObject(r){const e=this.getBounds(r),t=this.getId(r),n={...r,spatialIndexId:t};this.objectsById.set(t,n);const i=Math.floor(e.minX/this.CELL_SIZE),a=Math.floor(e.minY/this.CELL_SIZE),o=Math.floor(e.maxX/this.CELL_SIZE),s=Math.floor(e.maxY/this.CELL_SIZE);for(let l=i;l<=o;l++)for(let c=a;c<=s;c++){const u=`${l}x${c}`,f=this.buckets.get(u);f?f.push(n):this.buckets.set(u,[n])}}removeObject(r){const e=this.objectsById.get(r);if(!e)return!1;this.objectsById.delete(r);const t=this.getBounds(e),n=Math.floor(t.minX/this.CELL_SIZE),i=Math.floor(t.minY/this.CELL_SIZE),a=Math.floor(t.maxX/this.CELL_SIZE),o=Math.floor(t.maxY/this.CELL_SIZE);for(let s=n;s<=a;s++)for(let l=i;l<=o;l++){const c=`${s}x${l}`,u=this.buckets.get(c);if(u){const f=u.findIndex(p=>p.spatialIndexId===r);f!==-1&&(u.splice(f,1),u.length===0&&this.buckets.delete(c))}}return!0}getBucketKey(r,e){return`${Math.floor(r/this.CELL_SIZE)}x${Math.floor(e/this.CELL_SIZE)}`}getObjectsInBounds(r,e=0){const t=[],n=new Set,i=Math.floor((r.minX-e)/this.CELL_SIZE),a=Math.floor((r.minY-e)/this.CELL_SIZE),o=Math.floor((r.maxX+e)/this.CELL_SIZE),s=Math.floor((r.maxY+e)/this.CELL_SIZE);for(let l=i;l<=o;l++)for(let c=a;c<=s;c++){const u=`${l}x${c}`,f=this.buckets.get(u)||[];for(const p of f){const v=p.spatialIndexId;n.has(v)||(n.add(v),t.push(p))}}return t}},lA=r=>r.type==="pcb_trace_segment"?{minX:Math.min(r.x1,r.x2),minY:Math.min(r.y1,r.y2),maxX:Math.max(r.x1,r.x2),maxY:Math.max(r.y1,r.y2)}:Ave([r]),_oe=.1,fGt=.15,xoe=.005;function dGt(r){const e=new Set;for(const t of r.route)t.route_type==="wire"&&(t.start_pcb_port_id&&e.add(t.start_pcb_port_id),t.end_pcb_port_id&&e.add(t.end_pcb_port_id));return Array.from(e)}function boe(r){const e=new Set;for(const t of r)for(const n of dGt(t))e.add(n);return Array.from(e)}var pGt=(r,e)=>{const t={x:r.x1,y:r.y1},n={x:r.x2,y:r.y2},i={x:e.x1,y:e.y1},a={x:e.x2,y:e.y2},o={x:n.x-t.x,y:n.y-t.y},s={x:a.x-i.x,y:a.y-i.y},l=o.x*o.x+o.y*o.y,c=s.x*s.x+s.y*s.y;if(l===0||c===0){if(l===0&&c===0)return{x:(t.x+i.x)/2,y:(t.y+i.y)/2};if(l===0){const K=qS(((t.x-i.x)*s.x+(t.y-i.y)*s.y)/c,0,1),te={x:i.x+K*s.x,y:i.y+K*s.y};return{x:(t.x+te.x)/2,y:(t.y+te.y)/2}}const Y=qS(((i.x-t.x)*o.x+(i.y-t.y)*o.y)/l,0,1),Q={x:t.x+Y*o.x,y:t.y+Y*o.y};return{x:(Q.x+i.x)/2,y:(Q.y+i.y)/2}}const u={x:t.x-i.x,y:t.y-i.y},f=o.x*o.x+o.y*o.y,p=o.x*s.x+o.y*s.y,v=o.x*u.x+o.y*u.y,x=s.x*s.x+s.y*s.y,S=s.x*u.x+s.y*u.y,E=f*x-p*p;if(E<1e-10)return hGt(t,n,i,a,o,s,l,c);let b=(p*S-x*v)/E,C=(f*S-p*v)/E;b=qS(b,0,1),C=qS(C,0,1),C=(b*p+S)/x,C=qS(C,0,1),b=(C*p-v)/f,b=qS(b,0,1);const O={x:t.x+b*o.x,y:t.y+b*o.y},U={x:i.x+C*s.x,y:i.y+C*s.y};return{x:(O.x+U.x)/2,y:(O.y+U.y)/2}},hGt=(r,e,t,n,i,a,o,s)=>{let l=((t.x-r.x)*i.x+(t.y-r.y)*i.y)/o;l=qS(l,0,1);const c={x:r.x+l*i.x,y:r.y+l*i.y};let u=((n.x-r.x)*i.x+(n.y-r.y)*i.y)/o;u=qS(u,0,1);const f={x:r.x+u*i.x,y:r.y+u*i.y};let p=((r.x-t.x)*a.x+(r.y-t.y)*a.y)/s;p=qS(p,0,1);const v={x:t.x+p*a.x,y:t.y+p*a.y};let x=((e.x-t.x)*a.x+(e.y-t.y)*a.y)/s;x=qS(x,0,1);const S={x:t.x+x*a.x,y:t.y+x*a.y},b=[{pointA:c,pointB:t,distance:Math.sqrt((c.x-t.x)**2+(c.y-t.y)**2)},{pointA:f,pointB:n,distance:Math.sqrt((f.x-n.x)**2+(f.y-n.y)**2)},{pointA:r,pointB:v,distance:Math.sqrt((r.x-v.x)**2+(r.y-v.y)**2)},{pointA:e,pointB:S,distance:Math.sqrt((e.x-S.x)**2+(e.y-S.y)**2)}].reduce((C,O)=>O.distance<C.distance?O:C);return{x:(b.pointA.x+b.pointB.x)/2,y:(b.pointA.y+b.pointB.y)/2}},qS=(r,e,t)=>Math.max(e,Math.min(t,r)),mGt=r=>{if(r.type==="pcb_via"||r.type==="pcb_plated_hole"&&r.shape==="circle")return r.outer_diameter/2;if(r.type==="pcb_hole"&&r.hole_shape==="circle")return r.hole_diameter/2;if(r.type==="pcb_smtpad"&&r.shape==="circle")return r.radius;throw new Error(`Could not determine radius of element: ${JSON.stringify(r)}`)},$Ue=(r,e)=>{const t={x:r.x1,y:r.y1},n={x:r.x2,y:r.y2},i=e.minX,a=e.minY,o=e.maxX,s=e.maxY;if(t.x===n.x&&t.y===n.y){const K=Math.max(i,Math.min(o,t.x)),te=Math.max(a,Math.min(s,t.y));return K===t.x&&te===t.y?{x:t.x,y:t.y}:{x:K,y:te}}const l=n.x-t.x,c=n.y-t.y,u=l!==0?(i-t.x)/l:Number.NEGATIVE_INFINITY,f=l!==0?(o-t.x)/l:Number.POSITIVE_INFINITY,p=c!==0?(a-t.y)/c:Number.NEGATIVE_INFINITY,v=c!==0?(s-t.y)/c:Number.POSITIVE_INFINITY,x=Math.max(Math.min(u,f),Math.min(p,v)),S=Math.min(Math.max(u,f),Math.max(p,v));if(x<=S&&S>=0&&x<=1){const K=Math.max(0,Math.min(1,x));return{x:t.x+K*l,y:t.y+K*c}}const E={x:Math.max(i,Math.min(o,t.x)),y:Math.max(a,Math.min(s,t.y))},b={x:Math.max(i,Math.min(o,n.x)),y:Math.max(a,Math.min(s,n.y))},C=(E.x-t.x)**2+(E.y-t.y)**2,O=(b.x-n.x)**2+(b.y-n.y)**2,U=[{start:{x:i,y:a},end:{x:o,y:a}},{start:{x:o,y:a},end:{x:o,y:s}},{start:{x:o,y:s},end:{x:i,y:s}},{start:{x:i,y:s},end:{x:i,y:a}}];let q=Math.min(C,O),Y=C<=O?E:b;const Q=(K,te,J)=>Math.max(te,Math.min(J,K));for(const K of U){const te={x:n.x-t.x,y:n.y-t.y},J={x:K.end.x-K.start.x,y:K.end.y-K.start.y},fe={x:t.x-K.start.x,y:t.y-K.start.y},he=te.x*te.x+te.y*te.y,ve=te.x*J.x+te.y*J.y,Te=te.x*fe.x+te.y*fe.y,Pe=J.x*J.x+J.y*J.y,Ee=J.x*fe.x+J.y*fe.y,Ce=he*Pe-ve*ve;if(Math.abs(Ce)<1e-10)continue;let be=(ve*Ee-Pe*Te)/Ce,Oe=(he*Ee-ve*Te)/Ce;be=Q(be,0,1),Oe=Q(Oe,0,1);const Ue={x:t.x+be*te.x,y:t.y+be*te.y},Ie={x:K.start.x+Oe*J.x,y:K.start.y+Oe*J.y},ke=Ue.x-Ie.x,ot=Ue.y-Ie.y,nt=ke*ke+ot*ot;nt<q&&(q=nt,Y={x:(Ue.x+Ie.x)/2,y:(Ue.y+Ie.y)/2})}return Y};function vGt(r){return r.type==="pcb_trace_segment"?[r.layer]:r.type==="pcb_smtpad"?[r.layer]:r.type==="pcb_plated_hole"?Array.isArray(r.layers)?r.layers:[...iC]:r.type==="pcb_hole"?[...iC]:r.type==="pcb_via"?Array.isArray(r.layers)?r.layers:[...iC]:r.type==="pcb_keepout"?Array.isArray(r.layers)?r.layers:[]:[]}function YUe(r,{connMap:e}={}){const t=[];e??(e=k3(r));const i=u3(r).pcb_trace.list().flatMap(x=>{const S=[];for(let E=0;E<x.route.length-1;E++){const b=x.route[E],C=x.route[E+1];b.route_type==="wire"&&C.route_type==="wire"&&b.layer===C.layer&&S.push({type:"pcb_trace_segment",pcb_trace_id:x.pcb_trace_id,_pcbTrace:x,thickness:"width"in b?b.width:"width"in C?C.width:fGt,layer:b.layer,x1:b.x,y1:b.y,x2:C.x,y2:C.y})}return S}),a=u3(r).pcb_smtpad.list(),o=u3(r).pcb_plated_hole.list(),s=u3(r).pcb_hole.list(),l=u3(r).pcb_via.list(),c=u3(r).pcb_keepout.list(),u=[...i,...a,...o,...s,...l,...c],f=new uGt({objects:u,getBounds:lA}),p=x=>NG(r,x),v=new Set;for(const x of i){const S=_oe,E=lA(x),b=f.getObjectsInBounds(E,S+x.thickness/2);if(!(x.x1===x.x2&&x.y1===x.y2))for(const C of b){if(!vGt(C).includes(x.layer))continue;if(C.type==="pcb_trace_segment"){const Y=C;if(x.layer!==Y.layer||e.areIdsConnected(x.pcb_trace_id,Y.pcb_trace_id))continue;const Q=sGt({x:x.x1,y:x.y1},{x:x.x2,y:x.y2},{x:Y.x1,y:Y.y1},{x:Y.x2,y:Y.y2})-x.thickness/2-Y.thickness/2;if(Q>_oe-xoe)continue;const K=`overlap_${x.pcb_trace_id}_${Y.pcb_trace_id}`,te=`overlap_${Y.pcb_trace_id}_${x.pcb_trace_id}`;if(v.has(K)||v.has(te))continue;v.add(K),t.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${p(x.pcb_trace_id)} overlaps with ${p(Y.pcb_trace_id)} ${Q<0?"(accidental contact)":`(gap: ${Q.toFixed(3)}mm)`}`,pcb_trace_id:x.pcb_trace_id,source_trace_id:"",pcb_trace_error_id:K,pcb_component_ids:[],center:pGt(x,Y),pcb_port_ids:boe([x._pcbTrace,Y._pcbTrace])});continue}const O=D6(C);if(e.areIdsConnected(x.pcb_trace_id,"pcb_trace_id"in C?C.pcb_trace_id:O))continue;if(C.type==="pcb_via"||C.type==="pcb_plated_hole"&&C.shape==="circle"||C.type==="pcb_hole"||C.type==="pcb_smtpad"&&C.shape==="circle"){const Y=mGt(C),K=cGt({x:x.x1,y:x.y1},{x:x.x2,y:x.y2},{x:C.x,y:C.y,radius:Y})-x.thickness/2;if(K>_oe-xoe)continue;const te=`overlap_${x.pcb_trace_id}_${O}`;if(v.has(te))continue;v.add(te),t.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${p(x.pcb_trace_id)} overlaps with ${C.type} "${p(D6(C))}" ${K<0?"(accidental contact)":`(gap: ${K.toFixed(3)}mm)`}`,pcb_trace_id:x.pcb_trace_id,center:$Ue(x,lA(C)),source_trace_id:"",pcb_trace_error_id:te,pcb_component_ids:["pcb_component_id"in C?C.pcb_component_id:void 0].filter(Boolean),pcb_port_ids:[...boe([x._pcbTrace]),"pcb_port_id"in C?C.pcb_port_id:void 0].filter(Boolean)})}const q=lGt({x:x.x1,y:x.y1},{x:x.x2,y:x.y2},lA(C))-x.thickness/2;if(q+xoe<S){const Y=`overlap_${x.pcb_trace_id}_${O}`;if(v.has(Y))continue;v.add(Y),t.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${p(x.pcb_trace_id)} overlaps with ${C.type} "${p(D6(C))}" ${q<0?"(accidental contact)":`(gap: ${q.toFixed(3)}mm)`}`,pcb_trace_id:x.pcb_trace_id,source_trace_id:"",pcb_trace_error_id:Y,pcb_component_ids:["pcb_component_id"in C?C.pcb_component_id:void 0].filter(Boolean),center:$Ue(x,lA(C)),pcb_port_ids:[...boe([x._pcbTrace]),"pcb_port_id"in C?C.pcb_port_id:void 0].filter(Boolean)})}}}return t}var yGt=Object.defineProperty,gGt=(r,e)=>{for(var t in e)yGt(r,t,{get:e[t],enumerable:!0})},XUe={};gGt(XUe,{Battery:()=>Nqt,Board:()=>pqt,Capacitor:()=>mqt,Chip:()=>mIe,Constraint:()=>Sqt,Crystal:()=>Fqt,Diode:()=>vqt,FabricationNotePath:()=>Eqt,FabricationNoteText:()=>wqt,Footprint:()=>HGt,Group:()=>Noe,Hole:()=>oIe,Inductor:()=>zqt,Jumper:()=>yqt,Keepout:()=>Moe,Led:()=>gqt,Mosfet:()=>Hqt,Net:()=>tIe,NetAlias:()=>Mqt,NormalComponent:()=>Xx,PcbTrace:()=>iIe,PinHeader:()=>Dqt,PlatedHole:()=>aIe,Port:()=>q4,Potentiometer:()=>Iqt,PowerSource:()=>_qt,PrimitiveComponent:()=>w_,PushButton:()=>kqt,Renderable:()=>WUe,Resistor:()=>xqt,Resonator:()=>Oqt,SchematicText:()=>Vqt,SilkscreenCircle:()=>Cqt,SilkscreenLine:()=>Aqt,SilkscreenPath:()=>rIe,SilkscreenRect:()=>Rqt,SilkscreenText:()=>Coe,SmtPad:()=>Toe,Subcircuit:()=>Tqt,Switch:()=>jqt,Trace:()=>I8,TraceHint:()=>pIe,Transistor:()=>Bqt,Via:()=>Pqt});var _Gt=E1("tscircuit:renderable"),z8=["ReactSubtreesRender","InitializePortsFromChildren","CreateNetsFromProps","CreateTracesFromProps","CreateTraceHintsFromProps","SourceRender","SourceParentAttachment","PortMatching","OptimizeSelectorCache","SourceTraceRender","SourceAddConnectivityMapKey","SchematicComponentRender","SchematicPrimitiveRender","SchematicPortRender","SchematicLayout","SchematicTraceRender","PcbComponentRender","PcbPrimitiveRender","PcbFootprintLayout","PcbPortRender","PcbPortAttachment","PcbLayout","PcbComponentSizeCalculation","PcbBoardAutoSize","PcbTraceHintRender","PcbTraceRender","PcbRouteNetIslands","PcbDesignRuleChecks","CadModelRender","PartsEngineRender"],xGt=0,WUe=class{constructor(e){Je(this,"renderPhaseStates");Je(this,"shouldBeRemoved",!1);Je(this,"children");Je(this,"isPcbPrimitive",!1);Je(this,"isSchematicPrimitive",!1);Je(this,"_renderId");Je(this,"_currentRenderPhase",null);Je(this,"_asyncEffects",[]);Je(this,"parent",null);this._renderId=`${xGt++}`,this.children=[],this.renderPhaseStates={};for(const t of z8)this.renderPhaseStates[t]={initialized:!1,dirty:!1}}_markDirty(e){var n;this.renderPhaseStates[e].dirty=!0;const t=z8.indexOf(e);for(let i=t+1;i<z8.length;i++)this.renderPhaseStates[z8[i]].dirty=!0;(n=this.parent)!=null&&n._markDirty&&this.parent._markDirty(e)}_queueAsyncEffect(e,t){const n={promise:t(),phase:this._currentRenderPhase,effectName:e,complete:!1};this._asyncEffects.push(n),"root"in this&&this.root&&this.root.emit("asyncEffect:start",{effectName:e,componentDisplayName:this.getString(),phase:n.phase}),n.promise.then(()=>{n.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:e,componentDisplayName:this.getString(),phase:n.phase})}).catch(i=>{console.error(`Async effect error in ${n.phase} "${e}":
|
|
13251
|
+
`,i.appendChild(O)}})}};a();const o=new MutationObserver(a);return o.observe(i,{childList:!0,subtree:!1,characterData:!1}),()=>{o.disconnect()}},[r,t,e,n])},iVt=E1("schematic-viewer"),aVt=()=>{E1.enable("schematic-viewer*")},oVt=iVt,sVt=r=>{const[e,t]=mt.useState(0),[n,i]=mt.useState(0);return mt.useEffect(()=>{if(!r.current)return;const a=()=>{var l;const s=(l=r.current)==null?void 0:l.getBoundingClientRect();t((s==null?void 0:s.width)||0),i((s==null?void 0:s.height)||0)};a();const o=new ResizeObserver(a);return o.observe(r.current),window.addEventListener("resize",a),()=>{o.disconnect(),window.removeEventListener("resize",a)}},[]),{containerWidth:e,containerHeight:n}},lVt=oVt.extend("useComponentDragging"),cVt=({onEditEvent:r,editEvents:e=[],circuitJson:t,cancelDrag:n,svgToScreenProjection:i,realToSvgProjection:a,enabled:o=!1})=>{const[s,l]=mt.useState(null),c=Tc(a,i),u=mt.useRef(null),f=mt.useRef(null),p=mt.useRef(new Map);mt.useEffect(()=>{e.forEach(E=>{"edit_event_type"in E&&E.edit_event_type==="edit_schematic_component_location"&&!E.in_progress&&p.current.set(E.schematic_component_id,{...E.new_center})})},[e]);const v=mt.useCallback(E=>{if(!o)return;const C=E.target.closest('[data-circuit-json-type="schematic_component"]');if(!C)return;const O=C.getAttribute("data-schematic-component-id");if(!O)return;n&&n();const U=hg(t).schematic_component.get(O);if(!U)return;u.current={x:E.clientX,y:E.clientY};let q;const Y=p.current.get(O);if(Y)q={...Y};else{const K=Qze({editEvents:e,schematic_component_id:O});q={x:U.center.x+K.x,y:U.center.y+K.y},p.current.set(O,{...q})}const Q={edit_event_id:Math.random().toString(36).substr(2,9),edit_event_type:"edit_schematic_component_location",schematic_component_id:O,original_center:q,new_center:{...q},in_progress:!0,created_at:Date.now(),_element:C};f.current=Q,l(Q)},[n,o,t,e]),x=mt.useCallback(E=>{if(!f.current||!u.current)return;const b={x:E.clientX-u.current.x,y:E.clientY-u.current.y},C={x:b.x/c.a,y:b.y/c.d},O={...f.current,new_center:{x:f.current.original_center.x+C.x,y:f.current.original_center.y+C.y}};f.current=O,l(O)},[c]),S=mt.useCallback(()=>{if(!f.current)return;const E={...f.current,in_progress:!1};p.current.set(E.schematic_component_id,{...E.new_center}),lVt("handleMouseUp calling onEditEvent with new edit event",{newEditEvent:E}),r&&r(E),f.current=null,u.current=null,l(null)},[r]);return mt.useEffect(()=>(window.addEventListener("mousemove",x),window.addEventListener("mouseup",S),()=>{window.removeEventListener("mousemove",x),window.removeEventListener("mouseup",S)}),[x,S]),{handleMouseDown:v,isDragging:!!f.current,activeEditEvent:s}},uVt=({onClick:r,active:e})=>ut.jsx("div",{onClick:r,style:{position:"absolute",top:"16px",right:"16px",backgroundColor:e?"#4CAF50":"#fff",color:e?"#fff":"#000",padding:"8px",borderRadius:"4px",cursor:"pointer",boxShadow:"0 2px 4px rgba(0,0,0,0.1)",display:"flex",alignItems:"center",gap:"4px",zIndex:1e3},children:ut.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[ut.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),ut.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})}),fVt=({circuitJson:r,containerStyle:e,editEvents:t=[],onEditEvent:n,defaultEditMode:i=!1,debugGrid:a=!1,editingEnabled:o=!1,debug:s=!1,clickToInteractEnabled:l=!1,colorOverrides:c})=>{s&&aVt();const[u,f]=mt.useState(i),[p,v]=mt.useState(!l),x=mt.useRef(null),S=mt.useRef(null),E=Oe=>{const Ue=Oe.touches[0];S.current={x:Ue.clientX,y:Ue.clientY}},b=Oe=>{const Ue=Oe.changedTouches[0],Ie=S.current;if(!Ie)return;const ke=Math.abs(Ue.clientX-Ie.x),ot=Math.abs(Ue.clientY-Ie.y);ke<10&&ot<10&&(Oe.preventDefault(),v(!0)),S.current=null},[C,O]=mt.useState([]),U=mt.useRef(r),q=Oe=>`${(Oe==null?void 0:Oe.length)||0}_${(Oe==null?void 0:Oe.editCount)||0}`;mt.useEffect(()=>{const Oe=q(r),Ue=q(U.current);Oe!==Ue&&(O([]),U.current=r)},[r]);const{ref:Y,cancelDrag:Q,transform:K}=Zze({onSetTransform(Oe){x.current&&(x.current.style.transform=cw(Oe))},enabled:p}),{containerWidth:te,containerHeight:J}=sVt(Y),fe=mt.useMemo(()=>!te||!J?"":loe(r,{width:te,height:J||720,grid:a?{cellSize:1,labelCells:!0}:void 0,colorOverrides:c}),[r,te,J]),he=mt.useMemo(()=>{var Ue;if(!fe)return Zm();const Oe=(Ue=fe.match(/data-real-to-screen-transform="([^"]+)"/))==null?void 0:Ue[1];try{return rH(Oe)}catch(Ie){return console.error(Ie),Zm()}},[fe]),ve=Oe=>{O(Ue=>[...Ue,Oe]),n&&n(Oe)},Te=mt.useMemo(()=>[...t,...C],[t,C]),{handleMouseDown:Pe,isDragging:Ee,activeEditEvent:Ce}=cVt({onEditEvent:ve,cancelDrag:Q,realToSvgProjection:he,svgToScreenProjection:K,circuitJson:r,editEvents:Te,enabled:u&&p});nVt({svgDivRef:x,editEvents:Te,realToSvgProjection:he,svgToScreenProjection:K,activeEditEvent:Ce}),rVt({svgDivRef:x,circuitJson:r,activeEditEvent:Ce,editEvents:Te});const be=mt.useMemo(()=>ut.jsx("div",{ref:x,style:{pointerEvents:l?p?"auto":"none":"auto",transformOrigin:"0 0"},dangerouslySetInnerHTML:{__html:fe}}),[fe,p,l]);return ut.jsxs("div",{ref:Y,style:{position:"relative",backgroundColor:"transparent",overflow:"hidden",cursor:Ee?"grabbing":l&&!p?"pointer":"grab",minHeight:"300px",...e},onMouseDown:Oe=>{if(l&&!p){Oe.preventDefault(),Oe.stopPropagation();return}Pe(Oe)},onMouseDownCapture:Oe=>{if(l&&!p){Oe.preventDefault(),Oe.stopPropagation();return}},onTouchStart:E,onTouchEnd:b,children:[!p&&l&&ut.jsx("div",{onClick:Oe=>{Oe.preventDefault(),Oe.stopPropagation(),v(!0)},style:{position:"absolute",inset:0,cursor:"pointer",zIndex:10,display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"all",touchAction:"pan-x pan-y pinch-zoom"},children:ut.jsx("div",{style:{backgroundColor:"rgba(0, 0, 0, 0.8)",color:"white",padding:"12px 24px",borderRadius:"8px",fontSize:"16px",fontFamily:"sans-serif",pointerEvents:"none"},children:typeof window<"u"&&("ontouchstart"in window||navigator.maxTouchPoints>0)?"Touch to Interact":"Click to Interact"})}),o&&ut.jsx(uVt,{active:u,onClick:()=>f(!u)}),be]})},dVt=r=>{const[e,t]=mt.useState(0),[n,i]=mt.useState(0);return mt.useEffect(()=>{if(!r.current)return;const a=()=>{var l;const s=(l=r.current)==null?void 0:l.getBoundingClientRect();t((s==null?void 0:s.width)||0),i((s==null?void 0:s.height)||0)};a();const o=new ResizeObserver(a);return o.observe(r.current),window.addEventListener("resize",a),()=>{o.disconnect(),window.removeEventListener("resize",a)}},[]),{containerWidth:e,containerHeight:n}};E1("assembly-viewer");var pVt=()=>{E1.enable("assembly-viewer*")},hVt=({circuitJson:r,containerStyle:e,debugGrid:t=!1,debug:n=!1})=>{n&&pVt();const i=mt.useRef(null),{ref:a}=Zze({onSetTransform(u){i.current&&(i.current.style.transform=cw(u))}}),{containerWidth:o,containerHeight:s}=dVt(a),l=mt.useMemo(()=>!o||!s?"":Vze(r,{width:o,height:s||720}),[r,o,s]);mt.useMemo(()=>{var f;if(!l)return Zm();const u=(f=l.match(/data-real-to-screen-transform="([^"]+)"/))==null?void 0:f[1];try{return rH(u)}catch(p){return console.error(p),Zm()}},[l]);const c=mt.useMemo(()=>ut.jsx("div",{ref:i,style:{pointerEvents:"auto",transformOrigin:"0 0"},dangerouslySetInnerHTML:{__html:l}}),[l]);return ut.jsx("div",{ref:a,style:{position:"relative",backgroundColor:"#F5F1ED",overflow:"hidden",minHeight:"300px",...e},children:c})};const Kze=["Initialize a tscircuit project using [tsci init](https://github.com/tscircuit/cli) before adding components.","Define reusable modules with cached routes using [<subcircuit />](https://docs.tscircuit.com/elements/subcircuit)","Run `tsci dev` on the command line to preview your boards before export",'Use units like mm or mils consistently across your designs (e.g. pcbX="10mm")',"Quickly set footprints with the [footprint prop](https://docs.tscircuit.com/footprints/footprinter-strings)","Check out the guide on [ordering prototypes](https://docs.tscircuit.com/building-electronics/ordering-prototypes)","Use [net labels](https://docs.tscircuit.com/elements/net) and [group elements](https://docs.tscircuit.com/elements/group) to organize complex schematics.","You can manually drag components on the PCB and Schematic using [manual edits](https://docs.tscircuit.com/guides/manual-edits)","Every tscircuit module can export to [Circuit JSON](https://github.com/tscircuit/circuit-json), Gerbers, Pick'n'Place CSV files, Bill of Materials CSV and more","You can import components from [JLCPCB](https://docs.tscircuit.com/guides/importing-modules-and-chips/importing-from-jlcpcb) or [KiCad](https://docs.tscircuit.com/guides/importing-modules-and-chips/importing-from-kicad)","Any module you push to the [registry](https://tscircuit.com/trending) will have [simple image urls](https://docs.tscircuit.com/web-apis/image-generation-api) you can use display images on a website","The default [Parts Engine](https://docs.tscircuit.com/guides/platform-configuration) will automatically find parts from common vendors for your BOM",'[Pin selectors](https://docs.tscircuit.com/guides/using-sel-references) are similar to CSS selectors, ".R1 > .pin1" means "connect to the first pin of the component R1"',"You can use the [sel](https://docs.tscircuit.com/guides/using-sel-references) object to select pins in a type-safe way","Publish modules via the [registry](https://tscircuit.com/trending) for working with a team or sharing your work","[Explore tutorials](https://docs.tscircuit.com/category/tutorials) for real-world circuit design examples.","Upload your Circuit JSON to [circuitjson.com](https://circuitjson.com) for a quick preview.","You can display Circuit JSON in 3D, PCB or Schematic mode with the [<CircuitJsonPreview />](https://docs.tscircuit.com/elements/circuitjsonpreview) React component","Use a [<group />](https://docs.tscircuit.com/elements/group) element to move multiple components at once in a schematic or PCB layout.","Check out the [GitHub Discussions page](https://github.com/tscircuit/tscircuit/discussions) to upvote features","You can customize the autorouter using the [autorouter prop](https://docs.tscircuit.com/elements/board#setting-the-autorouter)","Use the [<constraint />](https://docs.tscircuit.com/footprints/constraint) element to enforce geometric relationships in PCB designs.","Join the [Discord server](https://tscircuit.com/join) to discuss issues and get help directly from the community."],mVt=(()=>{let r=Kze[Math.floor(Math.random()*Kze.length)];return r=r.replace(/</g,"<"),r=r.replace(/>/g,">"),r=r.replace(new RegExp('(?<!href=")(?<!\\()(?<!\\]\\()(https?:\\/\\/[^\\s\\)\\]]+)',"g"),(e,t)=>`<a class="rf-text-blue-500 rf-underline" href="${e}" target="_blank">${e}</a>`),r=r.replace(/\[([^\]]+)\]\((https?:\/\/[^\)]+)\)/g,'<a class="rf-text-blue-500 rf-underline" href="$2" target="_blank">$1</a>'),r})(),L8=({onRunClicked:r})=>ut.jsxs("div",{className:"rf-flex rf-flex-col rf-items-center rf-justify-center rf-h-full rf-bg-gray-50 rf-text-gray-500 rf-p-4",children:[ut.jsx(IDt,{className:"rf-size-14 rf-mb-4"}),ut.jsxs("p",{className:"rf-text-md rf-break-words rf-max-w-xl rf-text-center",children:["Tip: ",ut.jsx("span",{dangerouslySetInnerHTML:{__html:mVt}})]}),r&&ut.jsxs(HE,{className:"rf-mt-4 rf-bg-blue-600 rf-hover:bg-blue-500",onClick:r,children:["Run Code",ut.jsx(FDt,{className:"rf-w-3 rf-h-3 rf-ml-2"})]})]}),Mk=({text:r,onClick:e})=>ut.jsx("span",{className:"rf-cursor-pointer rf-underline rf-text-blue-600 rf-mx-2",onClick:e,children:r}),Ck=r=>{var e;return ut.jsxs("div",{className:"rf-leading-5",children:[ut.jsx("div",{className:"rf-py-2 rf-font-bold",children:r.column.name}),ut.jsx("div",{children:((e=r.field)==null?void 0:e.call(r))??ut.jsx("input",{type:"text",className:"rf-border rf-rounded rf-p-1 rf-w-full",onChange:t=>{var n;(n=r.onTextChange)==null||n.call(r,t.target.value)}})})]})},vVt=({open:r,children:e,title:t,onClose:n})=>r?ut.jsx("div",{className:"rf-fixed rf-inset-0 rf-bg-black rf-bg-opacity-50 rf-flex rf-justify-center rf-items-center rf-z-50",onClick:n,children:ut.jsxs("div",{className:"rf-bg-white rf-p-5 rf-rounded-lg rf-relative rf-w-11/12 rf-max-w-2xl",onClick:i=>{i.preventDefault(),i.stopPropagation()},children:[ut.jsx("h2",{className:"rf-mt-0 rf-text-md rf-pb-4",children:t}),ut.jsx("button",{type:"button",className:"rf-absolute rf-top-2 rf-right-4 rf-text-2xl rf-font-bold",onClick:n,children:"×"}),e]})}):null,yVt=({elements:r})=>{const[e,t]=mt.useState({open:!1}),[n,i]=mt.useReducer((u,f)=>({...u,...f}),{}),a=[...new Set(r.map(u=>u.type))],o=r.map(u=>{const f=u[`${u.type}_id`],p=Object.fromEntries(Object.entries(u).filter(([x])=>!(x===`${u.type}_id`||!x.endsWith("_id")))),v=Object.fromEntries(Object.entries(u).filter(([x])=>!x.endsWith("_id")));return{primary_id:f,other_ids:p,...v,_og_elm:u}}),s=o.map(u=>{let f="";const p=v=>{const x=Object.keys(v.other_ids).find(b=>b.startsWith("source_"));if(!x)return`.${v.name}`;const S=x.slice(0,-3),E=o.find(b=>b.type===S&&b.primary_id===v.other_ids[x]);return E?"name"in E?`${p(E)} > .${v.name}`:`#${E.primary_id} > .${v.name}`:`??? > .${v.name}`};return"name"in u&&(f=p(u)),{...u,selector_path:f}}),l=[{key:"primary_id",name:"primary_id",renderCell:u=>ut.jsxs("div",{className:"rf-flex rf-items-center",children:[ut.jsx(Mk,{text:u.primary_id,onClick:()=>i({focused_id:u.primary_id,id_search:void 0,selector_search:void 0})}),ut.jsx("span",{className:"rf-flex-grow"}),ut.jsx(Mk,{text:"(JSON)",onClick:()=>t({open:!0,element:u._og_elm,title:u.primary_id})})]}),renderHeaderCell:u=>ut.jsx(Ck,{column:u,onTextChange:f=>i({id_search:f}),field:n.focused_id?()=>ut.jsxs("div",{children:["Focus:"," ",ut.jsx("span",{className:"rf-underline",children:n.focused_id}),ut.jsx(Mk,{text:"(unfocus)",onClick:()=>i({focused_id:void 0})})]}):void 0})},{key:"type",name:"type",renderHeaderCell:u=>ut.jsx(Ck,{column:u,field:()=>ut.jsxs("select",{onChange:f=>i({component_type_filter:f.target.value}),className:"rf-border rf-rounded rf-p-1 rf-w-full",children:[ut.jsx("option",{value:"any",children:"any"},"any"),ut.jsx("option",{value:"source",children:"source"},"source"),ut.jsx("option",{value:"source/pcb",children:"source/pcb"},"source/pcb"),ut.jsx("option",{value:"source/schematic",children:"source/schematic"},"source/schematic"),a.map(f=>ut.jsx("option",{value:f,children:f},f))]})})},{key:"name",name:"name",renderHeaderCell:u=>ut.jsx(Ck,{column:u,onTextChange:f=>i({name_search:f})})},{key:"selector_path",name:"selector_path",renderHeaderCell:u=>ut.jsx(Ck,{column:u,onTextChange:f=>i({selector_search:f})})},{key:"other_ids",name:"other_ids",renderCell:u=>ut.jsx("div",{className:"rf-space-x-2",children:Object.entries(u.other_ids).map(([f,p])=>ut.jsx(Mk,{text:p,onClick:()=>i({focused_id:p})},p))})}],c=s.filter(u=>{var f,p;return n.name_search?(p=(f=u.name)==null?void 0:f.toLowerCase())==null?void 0:p.includes(n.name_search.toLowerCase()):!0}).filter(u=>{var f;return!n.component_type_filter||n.component_type_filter==="any"?!0:n.component_type_filter==="source"?u.type.startsWith("source_"):n.component_type_filter==="source/pcb"?u.type.startsWith("source_")||u.type.startsWith("pcb_"):n.component_type_filter==="source/schematic"?u.type.startsWith("source_")||u.type.startsWith("schematic_"):(f=u.type)==null?void 0:f.includes(n.component_type_filter)}).filter(u=>n.selector_search?n.selector_search.split(" ").filter(p=>p.length>0).every(p=>{var v;return(v=u.selector_path)==null?void 0:v.includes(p)}):!0).filter(u=>{var f;return n.id_search?(f=u.primary_id)==null?void 0:f.includes(n.id_search):!0}).filter(u=>!!(!n.focused_id||u.primary_id===n.focused_id||Object.values(u.other_ids).includes(n.focused_id)));return ut.jsxs("div",{className:"rf-font-mono rf-text-xs rf-bg-white",children:[ut.jsx("div",{className:"rf-overflow-x-auto",children:ut.jsxs("table",{className:"rf-table-auto rf-w-full rf-text-left",children:[ut.jsx("thead",{children:ut.jsx("tr",{children:l.map(u=>ut.jsx("th",{className:"rf-px-4 rf-py-2 rf-border-b",children:u.renderHeaderCell?u.renderHeaderCell(u):u.name},u.key))})}),ut.jsx("tbody",{children:c.map((u,f)=>ut.jsx("tr",{className:"rf-hover:bg-gray-100",children:l.map(p=>ut.jsx("td",{className:"rf-px-4 rf-py-2 rf-border-b",children:p.renderCell?p.renderCell(u):u[p.key]},p.key))},f))})]})}),ut.jsx(vVt,{open:e.open,onClose:()=>t({open:!1}),title:e.open?e.title:"",children:ut.jsx("div",{className:"rf-bg-gray-800 rf-p-3 rf-text-white rf-rounded",children:ut.jsx("pre",{className:"rf-whitespace-pre-wrap",children:e.open?JSON.stringify(e.element,null,2):""})})})]})},gVt=(r,e)=>r==="jlcpcb"?ut.jsx("a",{className:"rf-underline rf-text-blue-500",target:"_blank",rel:"noreferrer",href:`https://jlcpcb.com/partdetail/${e}`,children:e}):e,_Vt=({circuitJson:r})=>{const e=r.filter(n=>n.type==="source_component"),t=new Set;for(const n of e)if(n.supplier_part_numbers)for(const i of Object.keys(n.supplier_part_numbers))t.add(i);return ut.jsx("div",{className:"rf-overflow-x-auto",children:ut.jsxs("table",{className:"rf-w-full rf-text-left rf-text-sm",children:[ut.jsx("thead",{children:ut.jsxs("tr",{className:"rf-border-b",children:[ut.jsx("th",{className:"rf-p-2",children:"Name"}),Array.from(t).map(n=>ut.jsx("th",{className:"rf-p-2 rf-capitalize",children:n},n))]})}),ut.jsx("tbody",{children:e.map(n=>ut.jsxs("tr",{className:"rf-border-b",children:[ut.jsx("td",{className:"rf-p-2",children:n.name}),Array.from(t).map(i=>{var a,o;return ut.jsx("td",{className:"rf-p-2",children:gVt(i,((o=(a=n.supplier_part_numbers)==null?void 0:a[i])==null?void 0:o[0])||"")},i)})]},n.source_component_id))})]})})};var xVt=k.enum(["up","down","left","right"]);k.enum(["top-to-bottom","left-to-right","bottom-to-top","right-to-left"]);var YE=k.array(k.string().or(k.number())),Jze=k.object({x:ci,y:ci,z:ci}),bVt=k.object({x:k.union([k.number(),k.string()]),y:k.union([k.number(),k.string()]),z:k.union([k.number(),k.string()])}),doe=k.object({rotationOffset:k.number().or(bVt).optional(),positionOffset:Jze.optional(),size:Jze.optional()}),SVt=doe.extend({stlUrl:k.string()}),EVt=doe.extend({objUrl:k.string(),mtlUrl:k.string().optional()}),wVt=doe.extend({jscad:k.record(k.any())}),TVt=k.union([k.null(),k.string(),SVt,EVt,wVt]),MVt=k.custom(r=>!0),gx=k.object({pcbX:ci.optional(),pcbY:ci.optional(),pcbRotation:p5.optional(),layer:Zv.optional()}),Rk=k.object({pcbX:ci.optional(),pcbY:ci.optional(),pcbRotation:p5.optional(),schX:ci.optional(),schY:ci.optional(),schRotation:p5.optional(),layer:Zv.optional(),footprint:MVt.optional()}),CVt=k.object({supplierPartNumbers:k.record(SB,k.array(k.string())).optional()}),L2=Rk.merge(CVt).extend({key:k.any().optional(),name:k.string(),cadModel:TVt.optional(),children:k.any().optional(),symbolName:k.string().optional()});ci.or(k.enum(["2x","3x","4x"]));var Ak=k.object({pins:k.array(k.union([k.number(),k.string()])),direction:k.union([k.literal("top-to-bottom"),k.literal("left-to-right"),k.literal("bottom-to-top"),k.literal("right-to-left")])}),poe=k.object({leftSize:k.number().optional().describe("@deprecated, use leftPinCount"),topSize:k.number().optional().describe("@deprecated, use topPinCount"),rightSize:k.number().optional().describe("@deprecated, use rightPinCount"),bottomSize:k.number().optional().describe("@deprecated, use bottomPinCount"),leftPinCount:k.number().optional(),rightPinCount:k.number().optional(),topPinCount:k.number().optional(),bottomPinCount:k.number().optional(),leftSide:Ak.optional(),rightSide:Ak.optional(),topSide:Ak.optional(),bottomSide:Ak.optional()}),eUe=k.record(k.object({marginLeft:ci.optional(),marginRight:ci.optional(),marginTop:ci.optional(),marginBottom:ci.optional(),leftMargin:ci.optional(),rightMargin:ci.optional(),topMargin:ci.optional(),bottomMargin:ci.optional()})),tUe=k.object({x:ci,y:ci}),hoe=k.object({edit_event_id:k.string(),in_progress:k.boolean().optional(),created_at:k.number()}),RVt=hoe.extend({pcb_edit_event_type:k.literal("edit_component_location").describe("deprecated"),edit_event_type:k.literal("edit_pcb_component_location"),pcb_component_id:k.string(),original_center:k.object({x:k.number(),y:k.number()}),new_center:k.object({x:k.number(),y:k.number()})}),AVt=hoe.extend({pcb_edit_event_type:k.literal("edit_trace_hint").describe("deprecated"),edit_event_type:k.literal("edit_pcb_trace_hint").optional(),pcb_port_id:k.string(),pcb_trace_hint_id:k.string().optional(),route:k.array(k.object({x:k.number(),y:k.number(),via:k.boolean().optional()}))}),PVt=hoe.extend({edit_event_type:k.literal("edit_schematic_component_location"),schematic_component_id:k.string(),original_center:k.object({x:k.number(),y:k.number()}),new_center:k.object({x:k.number(),y:k.number()})});k.union([RVt,AVt,PVt]);var NVt=k.object({selector:k.string(),relative_to:k.string().optional().default("group_center").describe("Can be a selector or 'group_center'"),center:K1}),DVt=k.object({pcb_port_selector:k.string(),offsets:k.array(s4)}),LVt=k.object({selector:k.string(),relative_to:k.string().optional().default("group_center").describe("Can be a selector or 'group_center'"),center:K1}),OVt=k.object({pcb_placements:k.array(NVt).optional(),manual_trace_hints:k.array(DVt).optional(),schematic_placements:k.array(LVt).optional()}),moe=k.object({layoutMode:k.enum(["grid","flex","none"]).optional(),position:k.enum(["absolute","relative"]).optional(),grid:k.boolean().optional(),gridCols:k.number().or(k.string()).optional(),gridRows:k.number().or(k.string()).optional(),gridTemplateRows:k.string().optional(),gridTemplateColumns:k.string().optional(),gridTemplate:k.string().optional(),gridGap:k.number().or(k.string()).optional(),flex:k.boolean().or(k.string()).optional(),flexDirection:k.enum(["row","column"]).optional(),alignItems:k.enum(["start","center","end","stretch"]).optional(),justifyContent:k.enum(["start","center","end","stretch"]).optional(),flexRow:k.boolean().optional(),flexColumn:k.boolean().optional(),gap:k.number().or(k.string()).optional()}),zVt=k.object({serverUrl:k.string().optional(),inputFormat:k.enum(["simplified","circuit-json"]).optional(),serverMode:k.enum(["job","solve-endpoint"]).optional(),serverCacheEnabled:k.boolean().optional(),cache:k.custom(r=>!0).optional(),groupMode:k.enum(["sequential-trace","subcircuit"]).optional(),algorithmFn:k.custom(r=>typeof r=="function"||r===void 0).optional(),local:k.boolean().optional()}),nUe=k.union([zVt,k.literal("sequential-trace"),k.literal("subcircuit"),k.literal("auto"),k.literal("auto-local"),k.literal("auto-cloud")]),rUe=Rk.extend({name:k.string().optional(),children:k.any().optional(),key:k.any().optional(),...moe.shape,pcbWidth:mr.optional(),pcbHeight:mr.optional(),schWidth:mr.optional(),schHeight:mr.optional(),pcbLayout:moe.optional(),schLayout:moe.optional()}),iUe=k.custom(r=>"findPart"in r),aUe=rUe.extend({layout:k.custom(r=>!0).optional(),manualEdits:OVt.optional(),schAutoLayoutEnabled:k.boolean().optional(),schTraceAutoLabelEnabled:k.boolean().optional(),routingDisabled:k.boolean().optional(),defaultTraceWidth:mr.optional(),minTraceWidth:mr.optional(),partsEngine:iUe.optional(),pcbRouteCache:k.custom(r=>!0).optional(),autorouter:nUe.optional()}),UVt=aUe.extend({subcircuit:k.literal(!0)}),oUe=k.discriminatedUnion("subcircuit",[rUe.extend({subcircuit:k.literal(!1).optional()}),UVt]),voe=aUe.extend({width:ci.optional(),height:ci.optional(),outline:k.array(tUe).optional(),outlineOffsetX:ci.optional(),outlineOffsetY:ci.optional(),material:k.enum(["fr4","fr1"]).default("fr4")}),IVt=k.string().or(k.array(k.string()).readonly()).or(k.array(k.string())),kVt=k.custom().pipe(k.record(k.string(),IVt)),FVt=k.record(k.string(),k.string().or(k.array(k.string()).readonly()).or(k.array(k.string()))),yoe=L2.extend({manufacturerPartNumber:k.string().optional(),pinLabels:FVt.optional(),internallyConnectedPins:k.array(k.array(k.string())).optional(),externallyConnectedPins:k.array(k.array(k.string())).optional(),schPinArrangement:poe.optional(),schPortArrangement:poe.optional(),schPinStyle:eUe.optional(),schPinSpacing:ci.optional(),schWidth:ci.optional(),schHeight:ci.optional(),noSchematicRepresentation:k.boolean().optional(),connections:kVt.optional()}),sUe=L2.extend({manufacturerPartNumber:k.string().optional(),pinLabels:k.record(k.number().or(k.string()),k.string().or(k.array(k.string()))).optional(),schPinStyle:eUe.optional(),schPinSpacing:ci.optional(),schWidth:ci.optional(),schHeight:ci.optional(),schDirection:k.enum(["left","right"]).optional(),schPortArrangement:poe.optional(),pinCount:k.union([k.literal(2),k.literal(3)]).optional(),internallyConnectedPins:k.array(k.array(k.string())).optional()}),Pk=k.custom().transform(r=>{if(r!==void 0)return ci.parse(r)}),lUe=k.union([gx.omit({pcbRotation:!0,layer:!0}).extend({name:k.string().optional(),shape:k.literal("circle"),holeDiameter:ci,outerDiameter:ci,portHints:YE.optional()}),gx.omit({pcbRotation:!0,layer:!0}).extend({name:k.string().optional(),shape:k.literal("oval"),outerWidth:ci,outerHeight:ci,holeWidth:Pk,holeHeight:Pk,innerWidth:ci.optional().describe("DEPRECATED use holeWidth"),innerHeight:ci.optional().describe("DEPRECATED use holeHeight"),portHints:YE.optional()}),gx.omit({pcbRotation:!0,layer:!0}).extend({name:k.string().optional(),shape:k.literal("pill"),outerWidth:ci,outerHeight:ci,holeWidth:Pk,holeHeight:Pk,innerWidth:ci.optional().describe("DEPRECATED use holeWidth"),innerHeight:ci.optional().describe("DEPRECATED use holeHeight"),portHints:YE.optional()}),gx.omit({pcbRotation:!0,layer:!0}).extend({name:k.string().optional(),holeDiameter:ci,rectPadWidth:ci,rectPadHeight:ci,holeShape:k.literal("circle").optional(),padShape:k.literal("rect").optional(),shape:k.literal("circularHoleWithRectPad").optional(),portHints:YE.optional()}).refine(r=>r.shape==="circularHoleWithRectPad"?r.holeDiameter&&r.rectPadWidth&&r.rectPadHeight:!0,{message:"Missing required fields for circularHoleWithRectPad"})]).refine(r=>("innerWidth"in r&&r.innerWidth!==void 0&&(r.holeWidth??(r.holeWidth=r.innerWidth)),"innerHeight"in r&&r.innerHeight!==void 0&&(r.holeHeight??(r.holeHeight=r.innerHeight)),r)),BVt=k.string().or(k.array(k.string()).readonly()).or(k.array(k.string())),cUe=r=>k.record(k.enum(r),BVt),HVt=["pin1","pin2","pos","neg"],uUe=L2.extend({resistance:d6,pullupFor:k.string().optional(),pullupTo:k.string().optional(),pulldownFor:k.string().optional(),pulldownTo:k.string().optional(),connections:cUe(HVt).optional()}),fUe=L2.extend({maxResistance:d6,pinVariant:k.enum(["two_pin","three_pin"]).optional()}),dUe=L2.extend({frequency:CP,loadCapacitance:p6,pinVariant:k.enum(["two_pin","four_pin"]).optional()}),pUe=L2.extend({frequency:CP,loadCapacitance:p6,pinVariant:k.enum(["no_ground","ground_pin","two_ground_pins"]).optional()});voe.extend({leftPinCount:k.number().optional(),rightPinCount:k.number().optional(),topPinCount:k.number().optional(),bottomPinCount:k.number().optional(),leftPins:k.array(k.string()).optional(),rightPins:k.array(k.string()).optional(),topPins:k.array(k.string()).optional(),bottomPins:k.array(k.string()).optional(),pinPitch:ci.optional(),innerHoles:k.boolean().optional()});var jVt=["pin1","pin2","pos","neg","anode","cathode"],hUe=L2.extend({capacitance:p6,maxVoltageRating:h6.optional(),schShowRatings:k.boolean().optional().default(!1),polarized:k.boolean().optional().default(!1),decouplingFor:k.string().optional(),decouplingTo:k.string().optional(),bypassFor:k.string().optional(),bypassTo:k.string().optional(),maxDecouplingTraceLength:k.number().optional(),connections:cUe(jVt).optional()});k.object({name:k.string()}),k.object({name:k.string().optional(),pcbOnly:k.boolean().optional(),schOnly:k.boolean().optional()});var VVt=k.object({pcb:k.literal(!0).optional(),xDist:ci,left:k.string(),right:k.string(),edgeToEdge:k.literal(!0).optional(),centerToCenter:k.literal(!0).optional()}),GVt=k.object({pcb:k.literal(!0).optional(),yDist:ci,top:k.string(),bottom:k.string(),edgeToEdge:k.literal(!0).optional(),centerToCenter:k.literal(!0).optional()}),qVt=k.object({pcb:k.literal(!0).optional(),sameY:k.literal(!0).optional(),for:k.array(k.string())}),$Vt=k.object({pcb:k.literal(!0).optional(),sameX:k.literal(!0).optional(),for:k.array(k.string())}),mUe=k.union([VVt,GVt,qVt,$Vt]),YVt=gx.omit({pcbRotation:!0}).extend({shape:k.literal("rect"),width:ci,height:ci,portHints:YE.optional()}),XVt=gx.omit({pcbRotation:!0}).extend({shape:k.literal("rotated_rect"),width:ci,height:ci,ccwRotation:k.number(),portHints:YE.optional()}),WVt=gx.omit({pcbRotation:!0}).extend({shape:k.literal("circle"),radius:ci,portHints:YE.optional()}),ZVt=gx.omit({pcbRotation:!0}).extend({shape:k.literal("pill"),width:ci,height:ci,radius:ci,portHints:YE.optional()}),vUe=k.union([WVt,YVt,XVt,ZVt]),QVt=gx.omit({pcbRotation:!0}).extend({shape:k.literal("rect"),width:ci,height:ci}),KVt=gx.omit({pcbRotation:!0}).extend({shape:k.literal("circle"),radius:ci});k.union([KVt,QVt]);var yUe=gx.omit({pcbRotation:!0}).extend({name:k.string().optional(),diameter:ci.optional(),radius:ci.optional()}).transform(r=>({...r,diameter:r.diameter??2*r.radius,radius:r.radius??r.diameter/2})),goe=k.union([k.string(),k.custom(r=>!!r.getPortSelector)]),gUe=k.object({key:k.string().optional(),thickness:ci.optional(),schematicRouteHints:k.array(tUe).optional(),pcbRouteHints:k.array(s4).optional(),schDisplayLabel:k.string().optional(),maxLength:ci.optional()}),_Ue=k.union([gUe.extend({path:k.array(goe)}),gUe.extend({from:goe,to:goe})]),xUe=k.object({originalLayer:Zv.default("top").optional()}),JVt=k.number().or(k.string().endsWith("mAh")).transform(r=>{if(typeof r=="string"){const e=r.replace("mAh",""),t=Number.parseFloat(e);if(Number.isNaN(t))throw new Error("Invalid capacity");return t}return r}).describe("Battery capacity in mAh"),bUe=L2.extend({capacity:JVt.optional()}),SUe=L2.extend({pinCount:k.number(),pitch:ci.optional(),schFacingDirection:k.enum(["up","down","left","right"]).optional(),gender:k.enum(["male","female"]).optional().default("male"),showSilkscreenPinLabels:k.boolean().optional(),doubleRow:k.boolean().optional(),holeDiameter:ci.optional(),platedDiameter:ci.optional(),pinLabels:k.array(k.string()).optional(),facingDirection:k.enum(["left","right"]).optional()}),EUe=k.object({net:k.string().optional(),schX:ci.optional(),schY:ci.optional(),schRotation:p5.optional(),anchorSide:k.enum(["left","up","right","down"]).optional()}),wUe=yoe.extend({}),TUe=L2.extend({type:k.enum(["npn","pnp","bjt","jfet","mosfet"])}),MUe=L2.extend({channelType:k.enum(["n","p"]),mosfetMode:k.enum(["enhancement","depletion"])}),CUe=L2.extend({inductance:xB}),eGt=k.enum(["anode","cathode","pin1","pin2","pos","neg"]),tGt=k.string().or(k.array(k.string()).readonly()).or(k.array(k.string())),nGt=k.record(eGt,tGt),rGt=k.enum(["standard","schottky","zener","photo","tvs"]),RUe=L2.extend({connections:nGt.optional(),variant:rGt.optional().default("standard"),standard:k.boolean().optional(),schottky:k.boolean().optional(),zener:k.boolean().optional(),photo:k.boolean().optional(),tvs:k.boolean().optional()}).superRefine((r,e)=>{if([r.standard,r.schottky,r.zener,r.photo,r.tvs].filter(Boolean).length>1)return e.addIssue({code:k.ZodIssueCode.custom,message:"Exactly one diode variant must be enabled",path:[]}),k.INVALID}).transform(r=>{const e={...r,standard:!1,schottky:!1,zener:!1,photo:!1,tvs:!1};if(r.standard)e.standard=!0;else if(r.schottky)e.schottky=!0;else if(r.zener)e.zener=!0;else if(r.photo)e.photo=!0;else if(r.tvs)e.tvs=!0;else switch(r.variant){case"standard":e.standard=!0;break;case"schottky":e.schottky=!0;break;case"zener":e.zener=!0;break;case"photo":e.photo=!0;break;case"tvs":e.tvs=!0;break;default:e.standard=!0}return e}),AUe=L2.extend({color:k.string().optional()}),PUe=L2.extend({type:k.enum(["spst","spdt","dpst","dpdt"]).optional(),isNormallyClosed:k.boolean().optional().default(!1),spst:k.boolean().optional(),spdt:k.boolean().optional(),dpst:k.boolean().optional(),dpdt:k.boolean().optional()}).transform(r=>{const e={...r};switch(e.dpdt?e.type="dpdt":e.spst?e.type="spst":e.spdt?e.type="spdt":e.dpst&&(e.type="dpst"),e.type){case"spdt":e.spdt=!0;break;case"spst":e.spst=!0;break;case"dpst":e.dpst=!0;break;case"dpdt":e.dpdt=!0;break}return e}),NUe=gx.extend({text:k.string(),anchorAlignment:k.enum(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),font:k.enum(["tscircuit2024"]).optional(),fontSize:mr.optional(),color:k.string().optional()}),DUe=gx.omit({pcbX:!0,pcbY:!0,pcbRotation:!0}).extend({route:k.array(s4),strokeWidth:mr.optional(),color:k.string().optional()});k.object({layer:k.string().optional(),thickness:ci.optional(),route:k.array(s4)});var LUe=Rk.extend({fromLayer:Zv,toLayer:Zv,holeDiameter:ci,outerDiameter:ci}),OUe=k.union([gx.omit({pcbRotation:!0}).extend({shape:k.literal("circle"),radius:ci}),gx.extend({shape:k.literal("rect"),width:ci,height:ci})]),zUe=L2.extend({voltage:h6});k.object({schX:ci,schY:ci,width:ci,height:ci}),k.object({x1:ci,y1:ci,x2:ci,y2:ci});var iGt=k.enum(["top_left","top_center","top_right","center_left","center","center_right","bottom_left","bottom_center","bottom_right"]),aGt=k.enum(["center","left","right","top","bottom"]),UUe=k.object({schX:ci,schY:ci,text:k.string(),fontSize:k.number().default(1),anchor:k.union([aGt.describe("legacy"),iGt]).default("center"),color:k.string().default("#000000"),schRotation:p5.default(0)});k.object({points:k.array(K1),isFilled:k.boolean().optional().default(!1),fillColor:k.enum(["red","blue"]).optional()});var IUe=gx.extend({text:k.string(),anchorAlignment:k.enum(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),font:k.enum(["tscircuit2024"]).optional(),fontSize:mr.optional()}),kUe=gx.omit({pcbX:!0,pcbY:!0,pcbRotation:!0}).extend({route:k.array(s4),strokeWidth:mr.optional()}),FUe=gx.omit({pcbX:!0,pcbY:!0,pcbRotation:!0}).extend({strokeWidth:ci,x1:ci,y1:ci,x2:ci,y2:ci}),BUe=gx.omit({pcbRotation:!0}).extend({isFilled:k.boolean().optional(),isOutline:k.boolean().optional(),strokeWidth:ci.optional(),width:ci,height:ci}),HUe=gx.omit({pcbRotation:!0}).extend({isFilled:k.boolean().optional(),isOutline:k.boolean().optional(),strokeWidth:ci.optional(),radius:ci}),jUe=k.object({x:ci,y:ci,via:k.boolean().optional(),toLayer:Zv.optional()}),VUe=k.object({for:k.string().optional().describe("Selector for the port you're targeting, not required if you're inside a trace"),order:k.number().optional(),offset:s4.or(jUe).optional(),offsets:k.array(s4).or(k.array(jUe)).optional(),traceWidth:k.number().optional()});Rk.extend({name:k.string(),pinNumber:k.number().optional(),aliases:k.array(k.string()).optional(),direction:xVt}),k.object({partsEngine:iUe.optional(),autorouter:nUe.optional(),registryApiUrl:k.string().optional(),cloudAutorouterUrl:k.string().optional()});function Nk([r,e],[t,n],{lineThickness:i=0}={}){return i===0?O8(r,e,t,n):oGt(r,e,t,n)<=i}function O8(r,e,t,n){const i=Dk(r,e,t),a=Dk(r,e,n),o=Dk(t,n,r),s=Dk(t,n,e);return!!(i!==a&&o!==s||i===0&&Lk(r,t,e)||a===0&&Lk(r,n,e)||o===0&&Lk(t,r,n)||s===0&&Lk(t,e,n))}function Dk(r,e,t){const n=(e.y-r.y)*(t.x-e.x)-(e.x-r.x)*(t.y-e.y);return n===0?0:n>0?1:2}function Lk(r,e,t){return e.x<=Math.max(r.x,t.x)&&e.x>=Math.min(r.x,t.x)&&e.y<=Math.max(r.y,t.y)&&e.y>=Math.min(r.y,t.y)}function oGt(r,e,t,n){if(r.x===e.x&&r.y===e.y)return s2(r,t,n);if(t.x===n.x&&t.y===n.y)return s2(t,r,e);if(O8(r,e,t,n))return 0;const i=[s2(r,t,n),s2(e,t,n),s2(t,r,e),s2(n,r,e)];return Math.min(...i)}function s2(r,e,t){const n=(t.x-e.x)**2+(t.y-e.y)**2;if(n===0)return E3(r,e);let i=((r.x-e.x)*(t.x-e.x)+(r.y-e.y)*(t.y-e.y))/n;i=Math.max(0,Math.min(1,i));const a={x:e.x+i*(t.x-e.x),y:e.y+i*(t.y-e.y)};return E3(r,a)}function E3(r,e){const t=r.x-e.x,n=r.y-e.y;return Math.sqrt(t*t+n*n)}function sGt(r,e,t,n){if(r.x===e.x&&r.y===e.y)return s2(r,t,n);if(t.x===n.x&&t.y===n.y)return s2(t,r,e);if(O8(r,e,t,n))return 0;const i=[s2(r,t,n),s2(e,t,n),s2(t,r,e),s2(n,r,e)];return Math.min(...i)}function lGt(r,e,t){const n={x:t.minX,y:t.minY},i={x:t.maxX,y:t.minY},a={x:t.minX,y:t.maxY},o={x:t.maxX,y:t.maxY};if(O8(r,e,n,i)||O8(r,e,i,o)||O8(r,e,o,a)||O8(r,e,a,n)||r.x>=t.minX&&r.x<=t.maxX&&r.y>=t.minY&&r.y<=t.maxY&&e.x>=t.minX&&e.x<=t.maxX&&e.y>=t.minY&&e.y<=t.maxY)return 0;const s=[s2(n,r,e),s2(i,r,e),s2(a,r,e),s2(o,r,e)];if(r.x>=t.minX&&r.x<=t.maxX&&r.y>=t.minY&&r.y<=t.maxY||e.x>=t.minX&&e.x<=t.maxX&&e.y>=t.minY&&e.y<=t.maxY)return 0;if(r.x<t.minX||r.x>t.maxX||r.y<t.minY||r.y>t.maxY){const l=uE(r.x,t.minX,t.maxX),c=uE(r.y,t.minY,t.maxY);s.push(E3(r,{x:l,y:c}))}if(e.x<t.minX||e.x>t.maxX||e.y<t.minY||e.y>t.maxY){const l=uE(e.x,t.minX,t.maxX),c=uE(e.y,t.minY,t.maxY);s.push(E3(e,{x:l,y:c}))}return Math.min(...s)}function cGt(r,e,t){const n={x:t.x,y:t.y};if(r.x===e.x&&r.y===e.y)return Math.max(0,E3(r,n)-t.radius);const i={x:e.x-r.x,y:e.y-r.y},a={x:n.x-r.x,y:n.y-r.y},o=i.x*i.x+i.y*i.y,s=Math.max(0,Math.min(1,(i.x*a.x+i.y*a.y)/o)),l={x:r.x+s*i.x,y:r.y+s*i.y},c=E3(l,n);return Math.max(0,c-t.radius)}var GUe=(r,e)=>{const t={x:e.x-r.x,y:e.y-r.y},n=Math.sqrt(t.x**2+t.y**2);return{x:t.x/n,y:t.y/n}},qUe=r=>{switch(r){case"up":return{x:0,y:1};case"down":return{x:0,y:-1};case"left":return{x:-1,y:0};case"right":return{x:1,y:0}}},uGt=class{constructor({objects:r,getBounds:e,getId:t,CELL_SIZE:n}){Je(this,"buckets");Je(this,"objectsById");Je(this,"getBounds");Je(this,"getId");Je(this,"CELL_SIZE",.4);Je(this,"_idCounter",0);this.buckets=new Map,this.objectsById=new Map,this.getBounds=e,this.getId=t??(()=>this._getNextId()),this.CELL_SIZE=n??this.CELL_SIZE;for(const i of r)this.addObject(i)}_getNextId(){return`${this._idCounter++}`}addObject(r){const e=this.getBounds(r),t=this.getId(r),n={...r,spatialIndexId:t};this.objectsById.set(t,n);const i=Math.floor(e.minX/this.CELL_SIZE),a=Math.floor(e.minY/this.CELL_SIZE),o=Math.floor(e.maxX/this.CELL_SIZE),s=Math.floor(e.maxY/this.CELL_SIZE);for(let l=i;l<=o;l++)for(let c=a;c<=s;c++){const u=`${l}x${c}`,f=this.buckets.get(u);f?f.push(n):this.buckets.set(u,[n])}}removeObject(r){const e=this.objectsById.get(r);if(!e)return!1;this.objectsById.delete(r);const t=this.getBounds(e),n=Math.floor(t.minX/this.CELL_SIZE),i=Math.floor(t.minY/this.CELL_SIZE),a=Math.floor(t.maxX/this.CELL_SIZE),o=Math.floor(t.maxY/this.CELL_SIZE);for(let s=n;s<=a;s++)for(let l=i;l<=o;l++){const c=`${s}x${l}`,u=this.buckets.get(c);if(u){const f=u.findIndex(p=>p.spatialIndexId===r);f!==-1&&(u.splice(f,1),u.length===0&&this.buckets.delete(c))}}return!0}getBucketKey(r,e){return`${Math.floor(r/this.CELL_SIZE)}x${Math.floor(e/this.CELL_SIZE)}`}getObjectsInBounds(r,e=0){const t=[],n=new Set,i=Math.floor((r.minX-e)/this.CELL_SIZE),a=Math.floor((r.minY-e)/this.CELL_SIZE),o=Math.floor((r.maxX+e)/this.CELL_SIZE),s=Math.floor((r.maxY+e)/this.CELL_SIZE);for(let l=i;l<=o;l++)for(let c=a;c<=s;c++){const u=`${l}x${c}`,f=this.buckets.get(u)||[];for(const p of f){const v=p.spatialIndexId;n.has(v)||(n.add(v),t.push(p))}}return t}},lA=r=>r.type==="pcb_trace_segment"?{minX:Math.min(r.x1,r.x2),minY:Math.min(r.y1,r.y2),maxX:Math.max(r.x1,r.x2),maxY:Math.max(r.y1,r.y2)}:Ave([r]),_oe=.1,fGt=.15,xoe=.005;function dGt(r){const e=new Set;for(const t of r.route)t.route_type==="wire"&&(t.start_pcb_port_id&&e.add(t.start_pcb_port_id),t.end_pcb_port_id&&e.add(t.end_pcb_port_id));return Array.from(e)}function boe(r){const e=new Set;for(const t of r)for(const n of dGt(t))e.add(n);return Array.from(e)}var pGt=(r,e)=>{const t={x:r.x1,y:r.y1},n={x:r.x2,y:r.y2},i={x:e.x1,y:e.y1},a={x:e.x2,y:e.y2},o={x:n.x-t.x,y:n.y-t.y},s={x:a.x-i.x,y:a.y-i.y},l=o.x*o.x+o.y*o.y,c=s.x*s.x+s.y*s.y;if(l===0||c===0){if(l===0&&c===0)return{x:(t.x+i.x)/2,y:(t.y+i.y)/2};if(l===0){const K=qS(((t.x-i.x)*s.x+(t.y-i.y)*s.y)/c,0,1),te={x:i.x+K*s.x,y:i.y+K*s.y};return{x:(t.x+te.x)/2,y:(t.y+te.y)/2}}const Y=qS(((i.x-t.x)*o.x+(i.y-t.y)*o.y)/l,0,1),Q={x:t.x+Y*o.x,y:t.y+Y*o.y};return{x:(Q.x+i.x)/2,y:(Q.y+i.y)/2}}const u={x:t.x-i.x,y:t.y-i.y},f=o.x*o.x+o.y*o.y,p=o.x*s.x+o.y*s.y,v=o.x*u.x+o.y*u.y,x=s.x*s.x+s.y*s.y,S=s.x*u.x+s.y*u.y,E=f*x-p*p;if(E<1e-10)return hGt(t,n,i,a,o,s,l,c);let b=(p*S-x*v)/E,C=(f*S-p*v)/E;b=qS(b,0,1),C=qS(C,0,1),C=(b*p+S)/x,C=qS(C,0,1),b=(C*p-v)/f,b=qS(b,0,1);const O={x:t.x+b*o.x,y:t.y+b*o.y},U={x:i.x+C*s.x,y:i.y+C*s.y};return{x:(O.x+U.x)/2,y:(O.y+U.y)/2}},hGt=(r,e,t,n,i,a,o,s)=>{let l=((t.x-r.x)*i.x+(t.y-r.y)*i.y)/o;l=qS(l,0,1);const c={x:r.x+l*i.x,y:r.y+l*i.y};let u=((n.x-r.x)*i.x+(n.y-r.y)*i.y)/o;u=qS(u,0,1);const f={x:r.x+u*i.x,y:r.y+u*i.y};let p=((r.x-t.x)*a.x+(r.y-t.y)*a.y)/s;p=qS(p,0,1);const v={x:t.x+p*a.x,y:t.y+p*a.y};let x=((e.x-t.x)*a.x+(e.y-t.y)*a.y)/s;x=qS(x,0,1);const S={x:t.x+x*a.x,y:t.y+x*a.y},b=[{pointA:c,pointB:t,distance:Math.sqrt((c.x-t.x)**2+(c.y-t.y)**2)},{pointA:f,pointB:n,distance:Math.sqrt((f.x-n.x)**2+(f.y-n.y)**2)},{pointA:r,pointB:v,distance:Math.sqrt((r.x-v.x)**2+(r.y-v.y)**2)},{pointA:e,pointB:S,distance:Math.sqrt((e.x-S.x)**2+(e.y-S.y)**2)}].reduce((C,O)=>O.distance<C.distance?O:C);return{x:(b.pointA.x+b.pointB.x)/2,y:(b.pointA.y+b.pointB.y)/2}},qS=(r,e,t)=>Math.max(e,Math.min(t,r)),mGt=r=>{if(r.type==="pcb_via"||r.type==="pcb_plated_hole"&&r.shape==="circle")return r.outer_diameter/2;if(r.type==="pcb_hole"&&r.hole_shape==="circle")return r.hole_diameter/2;if(r.type==="pcb_smtpad"&&r.shape==="circle")return r.radius;throw new Error(`Could not determine radius of element: ${JSON.stringify(r)}`)},$Ue=(r,e)=>{const t={x:r.x1,y:r.y1},n={x:r.x2,y:r.y2},i=e.minX,a=e.minY,o=e.maxX,s=e.maxY;if(t.x===n.x&&t.y===n.y){const K=Math.max(i,Math.min(o,t.x)),te=Math.max(a,Math.min(s,t.y));return K===t.x&&te===t.y?{x:t.x,y:t.y}:{x:K,y:te}}const l=n.x-t.x,c=n.y-t.y,u=l!==0?(i-t.x)/l:Number.NEGATIVE_INFINITY,f=l!==0?(o-t.x)/l:Number.POSITIVE_INFINITY,p=c!==0?(a-t.y)/c:Number.NEGATIVE_INFINITY,v=c!==0?(s-t.y)/c:Number.POSITIVE_INFINITY,x=Math.max(Math.min(u,f),Math.min(p,v)),S=Math.min(Math.max(u,f),Math.max(p,v));if(x<=S&&S>=0&&x<=1){const K=Math.max(0,Math.min(1,x));return{x:t.x+K*l,y:t.y+K*c}}const E={x:Math.max(i,Math.min(o,t.x)),y:Math.max(a,Math.min(s,t.y))},b={x:Math.max(i,Math.min(o,n.x)),y:Math.max(a,Math.min(s,n.y))},C=(E.x-t.x)**2+(E.y-t.y)**2,O=(b.x-n.x)**2+(b.y-n.y)**2,U=[{start:{x:i,y:a},end:{x:o,y:a}},{start:{x:o,y:a},end:{x:o,y:s}},{start:{x:o,y:s},end:{x:i,y:s}},{start:{x:i,y:s},end:{x:i,y:a}}];let q=Math.min(C,O),Y=C<=O?E:b;const Q=(K,te,J)=>Math.max(te,Math.min(J,K));for(const K of U){const te={x:n.x-t.x,y:n.y-t.y},J={x:K.end.x-K.start.x,y:K.end.y-K.start.y},fe={x:t.x-K.start.x,y:t.y-K.start.y},he=te.x*te.x+te.y*te.y,ve=te.x*J.x+te.y*J.y,Te=te.x*fe.x+te.y*fe.y,Pe=J.x*J.x+J.y*J.y,Ee=J.x*fe.x+J.y*fe.y,Ce=he*Pe-ve*ve;if(Math.abs(Ce)<1e-10)continue;let be=(ve*Ee-Pe*Te)/Ce,Oe=(he*Ee-ve*Te)/Ce;be=Q(be,0,1),Oe=Q(Oe,0,1);const Ue={x:t.x+be*te.x,y:t.y+be*te.y},Ie={x:K.start.x+Oe*J.x,y:K.start.y+Oe*J.y},ke=Ue.x-Ie.x,ot=Ue.y-Ie.y,nt=ke*ke+ot*ot;nt<q&&(q=nt,Y={x:(Ue.x+Ie.x)/2,y:(Ue.y+Ie.y)/2})}return Y};function vGt(r){return r.type==="pcb_trace_segment"?[r.layer]:r.type==="pcb_smtpad"?[r.layer]:r.type==="pcb_plated_hole"?Array.isArray(r.layers)?r.layers:[...iC]:r.type==="pcb_hole"?[...iC]:r.type==="pcb_via"?Array.isArray(r.layers)?r.layers:[...iC]:r.type==="pcb_keepout"?Array.isArray(r.layers)?r.layers:[]:[]}function YUe(r,{connMap:e}={}){const t=[];e??(e=k3(r));const i=u3(r).pcb_trace.list().flatMap(x=>{const S=[];for(let E=0;E<x.route.length-1;E++){const b=x.route[E],C=x.route[E+1];b.route_type==="wire"&&C.route_type==="wire"&&b.layer===C.layer&&S.push({type:"pcb_trace_segment",pcb_trace_id:x.pcb_trace_id,_pcbTrace:x,thickness:"width"in b?b.width:"width"in C?C.width:fGt,layer:b.layer,x1:b.x,y1:b.y,x2:C.x,y2:C.y})}return S}),a=u3(r).pcb_smtpad.list(),o=u3(r).pcb_plated_hole.list(),s=u3(r).pcb_hole.list(),l=u3(r).pcb_via.list(),c=u3(r).pcb_keepout.list(),u=[...i,...a,...o,...s,...l,...c],f=new uGt({objects:u,getBounds:lA}),p=x=>NG(r,x),v=new Set;for(const x of i){const S=_oe,E=lA(x),b=f.getObjectsInBounds(E,S+x.thickness/2);if(!(x.x1===x.x2&&x.y1===x.y2))for(const C of b){if(!vGt(C).includes(x.layer))continue;if(C.type==="pcb_trace_segment"){const Y=C;if(x.layer!==Y.layer||e.areIdsConnected(x.pcb_trace_id,Y.pcb_trace_id))continue;const Q=sGt({x:x.x1,y:x.y1},{x:x.x2,y:x.y2},{x:Y.x1,y:Y.y1},{x:Y.x2,y:Y.y2})-x.thickness/2-Y.thickness/2;if(Q>_oe-xoe)continue;const K=`overlap_${x.pcb_trace_id}_${Y.pcb_trace_id}`,te=`overlap_${Y.pcb_trace_id}_${x.pcb_trace_id}`;if(v.has(K)||v.has(te))continue;v.add(K),t.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${p(x.pcb_trace_id)} overlaps with ${p(Y.pcb_trace_id)} ${Q<0?"(accidental contact)":`(gap: ${Q.toFixed(3)}mm)`}`,pcb_trace_id:x.pcb_trace_id,source_trace_id:"",pcb_trace_error_id:K,pcb_component_ids:[],center:pGt(x,Y),pcb_port_ids:boe([x._pcbTrace,Y._pcbTrace])});continue}const O=D6(C);if(e.areIdsConnected(x.pcb_trace_id,"pcb_trace_id"in C?C.pcb_trace_id:O))continue;if(C.type==="pcb_via"||C.type==="pcb_plated_hole"&&C.shape==="circle"||C.type==="pcb_hole"||C.type==="pcb_smtpad"&&C.shape==="circle"){const Y=mGt(C),K=cGt({x:x.x1,y:x.y1},{x:x.x2,y:x.y2},{x:C.x,y:C.y,radius:Y})-x.thickness/2;if(K>_oe-xoe)continue;const te=`overlap_${x.pcb_trace_id}_${O}`;if(v.has(te))continue;v.add(te),t.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${p(x.pcb_trace_id)} overlaps with ${C.type} "${p(D6(C))}" ${K<0?"(accidental contact)":`(gap: ${K.toFixed(3)}mm)`}`,pcb_trace_id:x.pcb_trace_id,center:$Ue(x,lA(C)),source_trace_id:"",pcb_trace_error_id:te,pcb_component_ids:["pcb_component_id"in C?C.pcb_component_id:void 0].filter(Boolean),pcb_port_ids:[...boe([x._pcbTrace]),"pcb_port_id"in C?C.pcb_port_id:void 0].filter(Boolean)})}const q=lGt({x:x.x1,y:x.y1},{x:x.x2,y:x.y2},lA(C))-x.thickness/2;if(q+xoe<S){const Y=`overlap_${x.pcb_trace_id}_${O}`;if(v.has(Y))continue;v.add(Y),t.push({type:"pcb_trace_error",error_type:"pcb_trace_error",message:`PCB trace ${p(x.pcb_trace_id)} overlaps with ${C.type} "${p(D6(C))}" ${q<0?"(accidental contact)":`(gap: ${q.toFixed(3)}mm)`}`,pcb_trace_id:x.pcb_trace_id,source_trace_id:"",pcb_trace_error_id:Y,pcb_component_ids:["pcb_component_id"in C?C.pcb_component_id:void 0].filter(Boolean),center:$Ue(x,lA(C)),pcb_port_ids:[...boe([x._pcbTrace]),"pcb_port_id"in C?C.pcb_port_id:void 0].filter(Boolean)})}}}return t}var yGt=Object.defineProperty,gGt=(r,e)=>{for(var t in e)yGt(r,t,{get:e[t],enumerable:!0})},XUe={};gGt(XUe,{Battery:()=>Nqt,Board:()=>pqt,Capacitor:()=>mqt,Chip:()=>mIe,Constraint:()=>Sqt,Crystal:()=>Fqt,Diode:()=>vqt,FabricationNotePath:()=>Eqt,FabricationNoteText:()=>wqt,Footprint:()=>HGt,Group:()=>Noe,Hole:()=>oIe,Inductor:()=>zqt,Jumper:()=>yqt,Keepout:()=>Moe,Led:()=>gqt,Mosfet:()=>Hqt,Net:()=>tIe,NetAlias:()=>Mqt,NormalComponent:()=>Xx,PcbTrace:()=>iIe,PinHeader:()=>Dqt,PlatedHole:()=>aIe,Port:()=>q4,Potentiometer:()=>Iqt,PowerSource:()=>_qt,PrimitiveComponent:()=>w_,PushButton:()=>kqt,Renderable:()=>WUe,Resistor:()=>xqt,Resonator:()=>Oqt,SchematicText:()=>Vqt,SilkscreenCircle:()=>Cqt,SilkscreenLine:()=>Aqt,SilkscreenPath:()=>rIe,SilkscreenRect:()=>Rqt,SilkscreenText:()=>Coe,SmtPad:()=>Toe,Subcircuit:()=>Tqt,Switch:()=>jqt,Trace:()=>I8,TraceHint:()=>pIe,Transistor:()=>Bqt,Via:()=>Pqt});var _Gt=E1("tscircuit:renderable"),z8=["ReactSubtreesRender","InitializePortsFromChildren","CreateNetsFromProps","CreateTracesFromProps","CreateTraceHintsFromProps","SourceRender","SourceParentAttachment","PortMatching","OptimizeSelectorCache","SourceTraceRender","SourceAddConnectivityMapKey","SchematicComponentRender","SchematicPrimitiveRender","SchematicPortRender","SchematicLayout","SchematicTraceRender","PcbComponentRender","PcbPrimitiveRender","PcbFootprintLayout","PcbPortRender","PcbPortAttachment","PcbLayout","PcbComponentSizeCalculation","PcbBoardAutoSize","PcbTraceHintRender","PcbTraceRender","PcbRouteNetIslands","PcbDesignRuleChecks","CadModelRender","PartsEngineRender"],xGt=0,WUe=class{constructor(e){Je(this,"renderPhaseStates");Je(this,"shouldBeRemoved",!1);Je(this,"children");Je(this,"isPcbPrimitive",!1);Je(this,"isSchematicPrimitive",!1);Je(this,"_renderId");Je(this,"_currentRenderPhase",null);Je(this,"_asyncEffects",[]);Je(this,"parent",null);this._renderId=`${xGt++}`,this.children=[],this.renderPhaseStates={};for(const t of z8)this.renderPhaseStates[t]={initialized:!1,dirty:!1}}_markDirty(e){var n;this.renderPhaseStates[e].dirty=!0;const t=z8.indexOf(e);for(let i=t+1;i<z8.length;i++)this.renderPhaseStates[z8[i]].dirty=!0;(n=this.parent)!=null&&n._markDirty&&this.parent._markDirty(e)}_queueAsyncEffect(e,t){const n={promise:t(),phase:this._currentRenderPhase,effectName:e,complete:!1};this._asyncEffects.push(n),"root"in this&&this.root&&this.root.emit("asyncEffect:start",{effectName:e,componentDisplayName:this.getString(),phase:n.phase}),n.promise.then(()=>{n.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:e,componentDisplayName:this.getString(),phase:n.phase})}).catch(i=>{console.error(`Async effect error in ${n.phase} "${e}":
|
|
13252
13252
|
${i.stack}`),n.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:e,componentDisplayName:this.getString(),phase:n.phase,error:i.toString()})})}_emitRenderLifecycleEvent(e,t){_Gt(`${e}:${t} ${this.getString()}`);const n=`renderable:renderLifecycle:${e}:${t}`,i={renderId:this._renderId,componentDisplayName:this.getString(),type:n};"root"in this&&this.root&&(this.root.emit(n,i),this.root.emit("renderable:renderLifecycle:anyEvent",{...i,type:n}))}getString(){return this.constructor.name}_hasIncompleteAsyncEffects(){return this._asyncEffects.some(e=>!e.complete)}getCurrentRenderPhase(){return this._currentRenderPhase}getRenderGraph(){return{id:this._renderId,currentPhase:this._currentRenderPhase,renderPhaseStates:this.renderPhaseStates,shouldBeRemoved:this.shouldBeRemoved,children:this.children.map(e=>e.getRenderGraph())}}runRenderCycle(){for(const e of z8)this.runRenderPhaseForChildren(e),this.runRenderPhase(e)}runRenderPhase(e){var o,s,l;this._currentRenderPhase=e;const t=this.renderPhaseStates[e],n=t.initialized,i=t.dirty;if(!n&&this.shouldBeRemoved)return;if(this.shouldBeRemoved&&n){this._emitRenderLifecycleEvent(e,"start"),(o=this==null?void 0:this[`remove${e}`])==null||o.call(this),t.initialized=!1,t.dirty=!1,this._emitRenderLifecycleEvent(e,"end");return}const a=z8.indexOf(e)-1;if(a>=0){const c=z8[a];if(this._asyncEffects.filter(f=>f.phase===c).some(f=>!f.complete))return}if(this._emitRenderLifecycleEvent(e,"start"),n){i&&((s=this==null?void 0:this[`update${e}`])==null||s.call(this),t.dirty=!1),this._emitRenderLifecycleEvent(e,"end");return}t.dirty=!1,(l=this==null?void 0:this[`doInitial${e}`])==null||l.call(this),t.initialized=!0,this._emitRenderLifecycleEvent(e,"end")}runRenderPhaseForChildren(e){for(const t of this.children)t.runRenderPhaseForChildren(e),t.runRenderPhase(e)}renderError(e){throw typeof e=="string"?new Error(e):new Error(JSON.stringify(e,null,2))}},Ok={},ZUe=r=>{const e=Object.fromEntries(Object.entries(r).map(([t,n])=>[t.toLowerCase(),n]));Object.assign(Ok,r),Object.assign(Ok,e)},bGt=class extends Error{constructor(e,t,n){let i;const o=Object.keys(n).filter(s=>s!=="_errors").map(s=>n[s]._errors[0]?`${s} (${n[s]._errors[0]})`:`${s} (${JSON.stringify(n[s])})`).join(", ");"name"in t?i=`Invalid props for ${e} "${t.name}": ${o}`:"footprint"in t&&typeof t.footprint=="string"?i=`Invalid props for ${e} (unnamed ${t.footprint} component): ${o}`:i=`Invalid props for ${e} (unnamed): ${o}`,super(i),this.componentName=e,this.originalProps=t,this.formattedError=n}};function Soe(r,e){const t=e.match(/^#(\w+)/);if(t)return r.props.id===t[1];const n=e.match(/^\.(\w+)/);if(n)return r.isMatchingNameOrAlias(n[1]);let[i,...a]=e.split(/(?=[#.[])/);return i==="pin"&&(i="port"),i&&i!=="*"&&r.lowercaseComponentName!==i.toLowerCase()?!1:a.every(o=>{if(o.startsWith("#"))return r.props.id===o.slice(1);if(o.startsWith("."))return r.isMatchingNameOrAlias(o.slice(1));const s=o.match(/\[(\w+)=['"]?(.+?)['"]?\]/);if(!s)return!0;const[,l,c]=s;return r.props[l].toString()===c})}var Eoe={isTag:r=>!0,getParent:r=>r.parent,getChildren:r=>r.children,getName:r=>r.lowercaseComponentName,getAttributeValue:(r,e)=>{var t;if(e==="class"&&"getNameAndAliases"in r)return r.getNameAndAliases().join(" ");if(e==="name"&&((t=r._parsedProps)!=null&&t.name))return r._parsedProps.name;if(r._parsedProps&&e in r._parsedProps){const n=r._parsedProps[e];return typeof n=="string"?n:n!=null?String(n):null}return null},hasAttrib:(r,e)=>{var t;return e==="class"?!!((t=r._parsedProps)!=null&&t.name):r._parsedProps&&e in r._parsedProps},getSiblings:r=>r.parent?r.parent.children:[],prevElementSibling:r=>{if(!r.parent)return null;const e=r.parent.children,t=e.indexOf(r);return t>0?e[t-1]:null},getText:()=>"",removeSubsets:r=>r.filter((e,t)=>!r.some((n,i)=>t!==i&&n!==e&&n.getDescendants().includes(e))),existsOne:(r,e)=>e.some(r),findAll:(r,e)=>{const t=[],n=i=>{r(i)&&t.push(i);for(const a of i.children)n(a)};for(const i of e)n(i);return t},findOne:(r,e)=>{for(const t of e){if(r(t))return t;const n=t.children;if(n.length>0){const i=Eoe.findOne(r,n);if(i)return i}}return null},equals:(r,e)=>r._renderId===e._renderId,isHovered:r=>!1,isVisited:r=>!1,isActive:r=>!1},SGt={...Eoe,getChildren:r=>r.children.filter(e=>!e.isSubcircuit)},QUe={...Eoe,getChildren:r=>r.children.filter(e=>e.isSubcircuit)},KUe=r=>r.replace(/ pin/g," port").replace(/ subcircuit\./g," group[isSubcircuit=true]").replace(/([^ ])\>([^ ])/g,"$1 > $2").trim(),woe={adapter:SGt,cacheResults:!0},w_=class extends WUe{constructor(t){super(t);Je(this,"parent",null);Je(this,"children");Je(this,"childrenPendingRemoval");Je(this,"props");Je(this,"_parsedProps");Je(this,"externallyAddedAliases");Je(this,"isPrimitiveContainer",!1);Je(this,"source_group_id",null);Je(this,"source_component_id",null);Je(this,"schematic_component_id",null);Je(this,"pcb_component_id",null);Je(this,"cad_component_id",null);Je(this,"_cachedSelectAllQueries",new Map);Je(this,"_cachedSelectOneQueries",new Map);this.children=[],this.childrenPendingRemoval=[],this.props=t??{},this.externallyAddedAliases=[];const n=this.config.zodProps.safeParse(t??{});if(n.success)this._parsedProps=n.data;else throw new bGt(this.lowercaseComponentName,this.props,n.error.format())}get config(){return{componentName:"",zodProps:k.object({}).passthrough()}}get componentName(){return this.config.componentName}getInheritedProperty(t){var i;let n=this;for(;n;){if(n._parsedProps&&t in n._parsedProps)return n._parsedProps[t];n=n.parent}if((i=this.root)!=null&&i.platform&&t in this.root.platform)return this.root.platform[t]}get lowercaseComponentName(){return this.componentName.toLowerCase()}get isSubcircuit(){var t;return!!this.props.subcircuit||this.lowercaseComponentName==="group"&&((t=this==null?void 0:this.parent)==null?void 0:t.isRoot)}get isGroup(){return this.lowercaseComponentName==="group"}setProps(t){var a,o;const n=this.config.zodProps.parse({...this.props,...t}),i=this.props;this.props=n,this._parsedProps=this.config.zodProps.parse(t),this.onPropsChange({oldProps:i,newProps:n,changedProps:Object.keys(t)}),(o=(a=this.parent)==null?void 0:a.onChildChanged)==null||o.call(a,this)}computePcbPropsTransform(){const{_parsedProps:t}=this;return Tc(Gf(t.pcbX??0,t.pcbY??0),Wb((t.pcbRotation??0)*Math.PI/180))}_computePcbGlobalTransformBeforeLayout(){var i,a,o;const{_parsedProps:t}=this,n=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if(n&&this.props.pcbX===void 0&&this.props.pcbY===void 0)return Tc(((i=this.parent)==null?void 0:i._computePcbGlobalTransformBeforeLayout())??Zm(),Tc(Gf(n.x,n.y),Wb((t.pcbRotation??0)*Math.PI/180)));if(this.isPcbPrimitive){const s=this.getPrimitiveContainer();if(s){const l=s._parsedProps.layer==="bottom",c=s._getGlobalPcbPositionBeforeLayout();if(l)return Tc(Gf(c.x,c.y),fw(),Gf(-c.x,-c.y)),Tc(((a=this.parent)==null?void 0:a._computePcbGlobalTransformBeforeLayout())??Zm(),fw(),this.computePcbPropsTransform())}}return Tc(((o=this.parent)==null?void 0:o._computePcbGlobalTransformBeforeLayout())??Zm(),this.computePcbPropsTransform())}getPrimitiveContainer(){var t,n;return this.isPrimitiveContainer?this:((n=(t=this.parent)==null?void 0:t.getPrimitiveContainer)==null?void 0:n.call(t))??null}_getPcbCircuitJsonBounds(){return{center:{x:0,y:0},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getPcbPrimitiveFlippedHelpers(){const t=this.getPrimitiveContainer(),n=t?t._parsedProps.layer==="bottom":!1;return{isFlipped:n,maybeFlipLayer:a=>n?a==="top"?"bottom":"top":a}}_setPositionFromLayout(t){throw new Error(`_setPositionFromLayout not implemented for ${this.componentName}`)}computeSchematicPropsTransform(){const{_parsedProps:t}=this;return Tc(Gf(t.schX??0,t.schY??0))}computeSchematicGlobalTransform(){var n,i;const t=this._getSchematicGlobalManualPlacementTransform(this);return t||Tc(((i=(n=this.parent)==null?void 0:n.computeSchematicGlobalTransform)==null?void 0:i.call(n))??Zm(),this.computeSchematicPropsTransform())}_getSchematicSymbolName(){const{_parsedProps:t}=this,n=this.config.schematicSymbolName;let i=t.schRotation;if(i===void 0&&(i=0),i=i%360,i<0&&(i+=360),t.schRotation!==void 0&&i%90!==0)throw new Error(`Schematic rotation ${t.schRotation} is not supported for ${this.componentName}`);const a=`${n}_horz`,o=`${n}_vert`,s=`${n}_up`,l=`${n}_down`,c=`${n}_left`,u=`${n}_right`;if(u in u_&&i===0)return u;if(s in u_&&i===90)return s;if(c in u_&&i===180)return c;if(l in u_&&i===270)return l;if(a in u_&&(i===0||i===180))return a;if(o in u_&&(i===90||i===270))return o;if(n in u_)return n}_getSchematicSymbolNameOrThrow(){const t=this._getSchematicSymbolName();if(!t)throw new Error(`No schematic symbol found (given: "${this.config.schematicSymbolName}")`);return t}getSchematicSymbol(){const t=this._getSchematicSymbolName();return t?u_[t]??null:null}_getPcbManualPlacementForComponent(t){var o;if(!this.isSubcircuit)return null;const n=this.props.layout,i=this.props.manualEdits;if(!n&&!i)return null;const a=((o=n==null?void 0:n.manual_pcb_placement_config)==null?void 0:o.positions)||(i==null?void 0:i.pcb_placements);if(!a)return null;for(const s of a)if(n&&Soe(t,s.selector)||t.props.name===s.selector)return Ir(this._computePcbGlobalTransformBeforeLayout(),s.center);return null}_getSchematicManualPlacementForComponent(t){if(!this.isSubcircuit)return null;const n=this.props.manualEdits;if(!n)return null;const i=n.schematic_placements;if(!i)return null;for(const a of i)if(Soe(t,a.selector)||t.props.name===a.selector)return Ir(this.computeSchematicGlobalTransform(),a.center);return null}_getSchematicGlobalManualPlacementTransform(t){var i,a;const n=(i=this.getSubcircuit())==null?void 0:i._parsedProps.manualEdits;if(!n)return null;for(const o of n.schematic_placements??[])if((Soe(t,o.selector)||t.props.name===o.selector)&&o.relative_to==="group_center")return Tc(((a=this.parent)==null?void 0:a._computePcbGlobalTransformBeforeLayout())??Zm(),Gf(o.center.x,o.center.y));return null}_getGlobalPcbPositionBeforeLayout(){return Ir(this._computePcbGlobalTransformBeforeLayout(),{x:0,y:0})}_getGlobalSchematicPositionBeforeLayout(){return Ir(this.computeSchematicGlobalTransform(),{x:0,y:0})}get root(){var t;return((t=this.parent)==null?void 0:t.root)??null}onAddToParent(t){this.parent=t}onPropsChange(t){}onChildChanged(t){var n,i;(i=(n=this.parent)==null?void 0:n.onChildChanged)==null||i.call(n,t)}add(t){if(!t.onAddToParent)throw new Error(`Invalid JSX Element: Expected a React component but received "${JSON.stringify(t)}"`);t.onAddToParent(this),t.parent=this,this.children.push(t)}addAll(t){for(const n of t)this.add(n)}remove(t){this.children=this.children.filter(n=>n!==t),this.childrenPendingRemoval.push(t),t.shouldBeRemoved=!0}getSubcircuitSelector(){const t=this._parsedProps.name,n=t?`${this.lowercaseComponentName}.${t}`:this.lowercaseComponentName;return!this.parent||this.parent.isSubcircuit?n:`${this.parent.getSubcircuitSelector()} > ${n}`}getFullPathSelector(){var a,o;const t=this._parsedProps.name,n=t?`${this.lowercaseComponentName}.${t}`:this.lowercaseComponentName,i=(o=(a=this.parent)==null?void 0:a.getFullPathSelector)==null?void 0:o.call(a);return i?`${i} > ${n}`:n}getNameAndAliases(){return[this._parsedProps.name,...this._parsedProps.portHints??[]].filter(Boolean)}isMatchingNameOrAlias(t){return this.getNameAndAliases().includes(t)}isMatchingAnyOf(t){return this.getNameAndAliases().some(n=>t.map(i=>i.toString()).includes(n))}getPcbSize(){throw new Error(`getPcbSize not implemented for ${this.componentName}`)}doesSelectorMatch(t){const n=[this.componentName,this.lowercaseComponentName],i=[this._parsedProps.name].filter(Boolean),a=t.trim().split(/\> /)[0],o=a[0];return a.length>1?!1:!!(t==="*"||t[0]==="#"&&t.slice(1)===this.props.id||t[0]==="."&&i.includes(t.slice(1))||/^[a-zA-Z0-9_]/.test(o)&&n.includes(o))}getSubcircuit(){var n,i;if(this.isSubcircuit)return this;const t=(i=(n=this.parent)==null?void 0:n.getSubcircuit)==null?void 0:i.call(n);if(!t)throw new Error("Component is not inside an opaque group (no board?)");return t}getGroup(){var t,n;return this.isGroup?this:((n=(t=this.parent)==null?void 0:t.getGroup)==null?void 0:n.call(t))??null}doInitialOptimizeSelectorCache(){var n;if(!this.isSubcircuit)return;const t=this.selectAll("port");for(const i of t){const a=(n=i.parent)==null?void 0:n.getNameAndAliases(),o=i.getNameAndAliases();if(a)for(const s of a)for(const l of o){const c=[`.${s} > .${l}`,`.${s} .${l}`];for(const u of c){const f=this._cachedSelectAllQueries.get(u);f?f.push(i):this._cachedSelectAllQueries.set(u,[i])}}}for(const[i,a]of this._cachedSelectAllQueries.entries())a.length===1&&this._cachedSelectOneQueries.set(i,a[0])}selectAll(t){if(this._cachedSelectAllQueries.has(t))return this._cachedSelectAllQueries.get(t);const n=KUe(t),i=S6(n,this,woe);if(i.length>0)return this._cachedSelectAllQueries.set(t,i),i;const[a,...o]=n.split(" "),s=d4(a,this,{adapter:QUe});if(!s)return[];const l=s.selectAll(o.join(" "));return this._cachedSelectAllQueries.set(t,l),l}selectOne(t,n){if(this._cachedSelectOneQueries.has(t))return this._cachedSelectOneQueries.get(t);const i=KUe(t);n!=null&&n.port&&(n.type="port");let a=null;if(n!=null&&n.type&&(a=S6(i,this,woe).find(u=>u.lowercaseComponentName===n.type)),a??(a=d4(i,this,woe)),a)return this._cachedSelectOneQueries.set(t,a),a;const[o,...s]=i.split(" "),l=d4(o,this,{adapter:QUe});return l?(a=l.selectOne(s.join(" "),n),this._cachedSelectOneQueries.set(t,a),a):null}getAvailablePcbLayers(){var t,n;if(this.isPcbPrimitive){const{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers();return"layer"in this._parsedProps||this.componentName==="SmtPad"?[i(this._parsedProps.layer??"top")]:"layers"in this._parsedProps?this._parsedProps.layers:this.componentName==="PlatedHole"?((n=(t=this.root)==null?void 0:t._getBoard())==null?void 0:n.allLayers)??["top","bottom"]:[]}return[]}getDescendants(){const t=[];for(const n of this.children)t.push(n),t.push(...n.getDescendants());return t}getSelectableDescendants(){const t=[];for(const n of this.children)n.isSubcircuit?t.push(n):(t.push(n),t.push(...n.getSelectableDescendants()));return t}_getPinCount(){return 0}_getSchematicBoxDimensions(){return null}renderError(t){var n;if(typeof t=="string")return super.renderError(t);(n=this.root)==null||n.db.pcb_placement_error.insert(t)}getString(){var a,o;const{lowercaseComponentName:t,_parsedProps:n,parent:i}=this;return(n==null?void 0:n.pinNumber)!==void 0&&((a=i==null?void 0:i.props)!=null&&a.name)&&(n!=null&&n.name)?`<${t}#${this._renderId}(pin:${n.pinNumber} .${i==null?void 0:i.props.name}>.${n.name}) />`:(o=i==null?void 0:i.props)!=null&&o.name&&(n!=null&&n.name)?`<${t}#${this._renderId}(.${i==null?void 0:i.props.name}>.${n==null?void 0:n.name}) />`:n!=null&&n.from&&(n!=null&&n.to)?`<${t}#${this._renderId}(from:${n.from} to:${n==null?void 0:n.to}) />`:n!=null&&n.name?`<${t}#${this._renderId} name=".${n==null?void 0:n.name}" />`:n!=null&&n.portHints?`<${t}#${this._renderId}(${n.portHints.map(s=>`.${s}`).join(", ")}) />`:`<${t}#${this._renderId} />`}get[Symbol.toStringTag](){return this.getString()}[Symbol.for("nodejs.util.inspect.custom")](){return this.getString()}},EGt=class extends w_{constructor(e,t){super(e),this._parsedProps={...e,error:t,type:e.type||"unknown",component_name:e.name,error_type:"source_failed_to_create_component_error",message:t instanceof Error?t.message:String(t),pcb_center:{x:e.pcbX||0,y:e.pcbY||0},schematic_center:{x:e.schX||0,y:e.schY||0}}}get config(){return{componentName:"ErrorPlaceholder",zodProps:k.object({}).passthrough()}}doInitialSourceRender(){var e;(e=this.root)!=null&&e.db&&this.root.db.source_failed_to_create_component_error.insert({component_name:this._parsedProps.component_name,message:this._parsedProps.message,pcb_center:this._parsedProps.pcb_center,schematic_center:this._parsedProps.schematic_center})}};function wGt(r,e){return new EGt(r,e)}function TGt(r,e){const t=r;return t.__tsci={...e},r}var JUe={supportsMutation:!0,createInstance(r,e){const t=Ok[r];if(!t)throw Object.keys(Ok).length===0?new Error("No components registered in catalogue, did you forget to import lib/register-catalogue in your test file?"):new Error(`Unsupported component type (not registered in @tscircuit/core catalogue): "${r}" See CREATING_NEW_COMPONENTS.md`);try{return TGt(new t(e),{})}catch(n){return wGt(e,n)}},createTextInstance(){return{}},appendInitialChild(r,e){r.add(e)},appendChild(r,e){r.add(e)},appendChildToContainer(r,e){r.add(e)},finalizeInitialChildren(){return!1},prepareUpdate(){return null},shouldSetTextContent(){return!1},getRootHostContext(){return{}},getChildHostContext(){return{}},prepareForCommit(){return null},resetAfterCommit(){},commitMount(){},commitUpdate(){},removeChild(){},clearContainer(){},supportsPersistence:!1,getPublicInstance(r){return r},preparePortalMount(r){throw new Error("Function not implemented.")},scheduleTimeout(r,e){throw new Error("Function not implemented.")},cancelTimeout(r){throw new Error("Function not implemented.")},noTimeout:void 0,isPrimaryRenderer:!1,getInstanceFromNode(r){throw new Error("Function not implemented.")},beforeActiveInstanceBlur(){throw new Error("Function not implemented.")},afterActiveInstanceBlur(){throw new Error("Function not implemented.")},prepareScopeUpdate:(r,e)=>{throw new Error("Function not implemented.")},getInstanceFromScope:r=>{throw new Error("Function not implemented.")},detachDeletedInstance:r=>{throw new Error("Function not implemented.")},getCurrentEventPriority:()=>f4.DefaultEventPriority,getCurrentUpdatePriority:()=>f4.DefaultEventPriority,resolveUpdatePriority:()=>f4.DefaultEventPriority,setCurrentUpdatePriority:()=>{},maySuspendCommit:()=>!1,supportsHydration:!1},U8;Yp.version.startsWith("19.")?U8=JB(JUe):U8=nH(JUe);var MGt=r=>{const e={children:[],props:{name:"$root"},add(a){a.parent=this,this.children.push(a)},computePcbGlobalTransform(){return Zm()}},t=[],n=U8.createContainer(e,0,null,!1,null,"tsci",a=>{console.log("Error in createContainer"),console.error(a),t.push(a)},null);if(Yp.version.startsWith("19.")?(U8.updateContainerSync(r,n,null,()=>{}),U8.flushSyncWork()):U8.updateContainer(r,n,null,()=>{}),t.length>0)throw t[0];const i=U8.getPublicRootInstance(n);return i||e.children[0]},cA=(r,e)=>{if(typeof r=="number")return r;if(r.startsWith("pin"))return Number(r.slice(3));if(!e)throw new Error(`No pin labels provided and pin number or label is not a number: "${r}"`);for(const t in e)if((Array.isArray(e[t])?e[t]:[e[t]]).includes(r))return Number(t.replace("pin",""));throw new Error(`No pin labels provided and pin number or label is not a number: "${r}"`)},CGt=(r,e)=>{if(!r)return;const t={},n={};for(const[i,a]of Object.entries(r)){const o=cA(i,e);n[o]={...n[o],...a}}for(const[i,a]of Object.entries(n)){const o=`pin${i}`;t[o]={bottom_margin:a.bottomMargin,left_margin:a.leftMargin,right_margin:a.rightMargin,top_margin:a.topMargin}}return t},RGt=r=>{if(r){if("leftSide"in r||"rightSide"in r||"topSide"in r||"bottomSide"in r)return{left_side:r.leftSide,right_side:r.rightSide,top_side:r.topSide,bottom_side:r.bottomSide};if("leftPinCount"in r||"rightPinCount"in r||"topPinCount"in r||"bottomPinCount"in r)return{left_size:r.leftPinCount,right_size:r.rightPinCount,top_size:r.topPinCount,bottom_size:r.bottomPinCount};if("leftSize"in r||"rightSize"in r||"topSize"in r||"bottomSize"in r)return{left_size:r.leftSize,right_size:r.rightSize,top_size:r.topSize,bottom_size:r.bottomSize}}};function eIe(r){const e=[];for(let t=0;t<r.length-1;t++)e.push([r[t],r[t+1]]);return e}var AGt=k.object({name:k.string()}),tIe=class extends w_{constructor(){super(...arguments);Je(this,"source_net_id")}get config(){return{componentName:"Net",zodProps:AGt}}getPortSelector(){return`net.${this.props.name}`}doInitialSourceRender(){const{db:t}=this.root,{_parsedProps:n}=this,i=t.source_net.insert({name:n.name,member_source_group_ids:[]});this.source_net_id=i.source_net_id}doInitialSourceParentAttachment(){const t=this.getSubcircuit();if(!t)return;const{db:n}=this.root;n.source_net.update(this.source_net_id,{subcircuit_id:t.subcircuit_id})}getAllConnectedPorts(){const t=this.getSubcircuit().selectAll("port"),n=[];for(const i of t){const a=i._getDirectlyConnectedTraces();for(const o of a)if(o._isExplicitlyConnectedToNet(this)){n.push(i);break}}return n}_getAllDirectlyConnectedTraces(){const t=this.getSubcircuit().selectAll("trace"),n=[];for(const i of t)i._isExplicitlyConnectedToNet(this)&&n.push(i);return n}doInitialPcbRouteNetIslands(){var s;if((s=this.root)!=null&&s.pcbDisabled||this.getSubcircuit()._parsedProps.routingDisabled||this.getSubcircuit()._getAutorouterConfig().groupMode!=="sequential-trace")return;const{db:t}=this.root,{_parsedProps:n}=this,i=this._getAllDirectlyConnectedTraces().filter(l=>{var c;return(((c=l._portsRoutedOnPcb)==null?void 0:c.length)??0)>0}),a=[];for(const l of i){const c=l._portsRoutedOnPcb,u=a.find(f=>c.some(p=>f.ports.includes(p)));if(!u){a.push({ports:[...c],traces:[l]});continue}u.traces.push(l),u.ports.push(...c)}if(a.length===0)return;const o=eIe(a);for(const[l,c]of o){const u=l.ports.map(O=>O._getGlobalPcbPositionBeforeLayout()),f=c.ports.map(O=>O._getGlobalPcbPositionBeforeLayout());let p=1/0,v=[-1,-1];for(let O=0;O<u.length;O++){const U=u[O];for(let q=0;q<f.length;q++){const Y=f[q],Q=Math.sqrt((U.x-Y.x)**2+(U.y-Y.y)**2);Q<p&&(p=Q,v=[O,q])}}const x=l.ports[v[0]],S=c.ports[v[1]],E=t.toArray().filter(O=>O.type==="pcb_smtpad"||O.type==="pcb_trace"||O.type==="pcb_plated_hole"||O.type==="pcb_hole"||O.type==="source_port"||O.type==="pcb_port"),{solution:b}=sG(E.concat([{type:"source_trace",source_trace_id:"__net_trace_tmp",connected_source_port_ids:[x.source_port_id,S.source_port_id]}])),C=b[0];if(!C){this.renderError({pcb_trace_error_id:"",pcb_trace_id:"__net_trace_tmp",pcb_component_ids:[x.pcb_component_id,S.pcb_component_id].filter(Boolean),pcb_port_ids:[x.pcb_port_id,S.pcb_port_id].filter(Boolean),type:"pcb_trace_error",error_type:"pcb_trace_error",message:`Failed to route net islands for "${this.getString()}"`,source_trace_id:"__net_trace_tmp"});return}t.pcb_trace.insert(C)}}renderError(t){var n;if(typeof t=="string")return super.renderError(t);(n=this.root)==null||n.db.pcb_trace_error.insert(t)}},nIe=(r,e)=>{for(const t of e)if(typeof t=="string"&&t.startsWith("net.")){const n=r.getSubcircuit();if(!n.selectOne(t)){const i=new tIe({name:t.split("net.")[1]});n.add(i)}}},Toe=class extends w_{constructor(){super(...arguments);Je(this,"pcb_smtpad_id",null);Je(this,"matchedPort",null);Je(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SmtPad",zodProps:vUe}}getPcbSize(){const{_parsedProps:t}=this;if(t.shape==="circle")return{width:t.radius*2,height:t.radius*2};if(t.shape==="rect")return{width:t.width,height:t.height};throw new Error(`getPcbSize for shape "${t.shape}" not implemented for ${this.componentName}`)}doInitialPortMatching(){var n;const t=(n=this.getPrimitiveContainer())==null?void 0:n.selectAll("port");if(this.props.portHints){for(const i of t)if(i.isMatchingAnyOf(this.props.portHints)){this.matchedPort=i,i.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){var v,x,S,E,b,C,O,U,q,Y;if((v=this.root)!=null&&v.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this;if(!n.portHints)return;const i=this.getPrimitiveContainer(),a=this.getSubcircuit(),o=this._getGlobalPcbPositionBeforeLayout();i==null||i._getGlobalPcbPositionBeforeLayout();const s=uw(this._computePcbGlobalTransformBeforeLayout()),l=Math.abs(s.rotation.angle*(180/Math.PI)-90)%180<.01,{maybeFlipLayer:c}=this._getPcbPrimitiveFlippedHelpers(),u=(i==null?void 0:i._parsedProps.pcbRotation)??0;let f=null;const p=((x=this.parent)==null?void 0:x.pcb_component_id)??((S=this.getPrimitiveContainer())==null?void 0:S.pcb_component_id);n.shape==="circle"?(f=t.pcb_smtpad.insert({pcb_component_id:p,pcb_port_id:(E=this.matchedPort)==null?void 0:E.pcb_port_id,layer:c(n.layer??"top"),shape:"circle",radius:n.radius,port_hints:n.portHints.map(Q=>Q.toString()),x:o.x,y:o.y,subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0}),t.pcb_solder_paste.insert({layer:f.layer,shape:"circle",radius:f.radius*.7,x:f.x,y:f.y,pcb_component_id:f.pcb_component_id,pcb_smtpad_id:f.pcb_smtpad_id,subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((b=this.getGroup())==null?void 0:b.pcb_group_id)??void 0})):n.shape==="rect"&&(f=u===0||l?t.pcb_smtpad.insert({pcb_component_id:p,pcb_port_id:(C=this.matchedPort)==null?void 0:C.pcb_port_id,layer:c(n.layer??"top"),shape:"rect",width:l?n.height:n.width,height:l?n.width:n.height,port_hints:n.portHints.map(Q=>Q.toString()),x:o.x,y:o.y,subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((O=this.getGroup())==null?void 0:O.pcb_group_id)??void 0}):t.pcb_smtpad.insert({pcb_component_id:p,layer:n.layer??"top",shape:"rotated_rect",width:n.width,height:n.height,x:o.x,y:o.y,ccw_rotation:u,port_hints:n.portHints.map(Q=>Q.toString()),subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((U=this.getGroup())==null?void 0:U.pcb_group_id)??void 0}),f.shape==="rect"&&t.pcb_solder_paste.insert({layer:f.layer,shape:"rect",width:f.width*.7,height:f.height*.7,x:f.x,y:f.y,pcb_component_id:f.pcb_component_id,pcb_smtpad_id:f.pcb_smtpad_id,subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((q=this.getGroup())==null?void 0:q.pcb_group_id)??void 0}),f.shape==="rotated_rect"&&t.pcb_solder_paste.insert({layer:f.layer,shape:"rotated_rect",width:f.width*.7,height:f.height*.7,x:f.x,y:f.y,ccw_rotation:u,pcb_component_id:f.pcb_component_id,pcb_smtpad_id:f.pcb_smtpad_id,subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((Y=this.getGroup())==null?void 0:Y.pcb_group_id)??void 0})),f&&(this.pcb_smtpad_id=f.pcb_smtpad_id)}doInitialPcbPortAttachment(){var n,i;if((n=this.root)!=null&&n.pcbDisabled)return;const{db:t}=this.root;t.pcb_smtpad.update(this.pcb_smtpad_id,{pcb_port_id:(i=this.matchedPort)==null?void 0:i.pcb_port_id})}_getPcbCircuitJsonBounds(){const{db:t}=this.root,n=t.pcb_smtpad.get(this.pcb_smtpad_id);if(n.shape==="rect")return{center:{x:n.x,y:n.y},bounds:{left:n.x-n.width/2,top:n.y+n.height/2,right:n.x+n.width/2,bottom:n.y-n.height/2},width:n.width,height:n.height};if(n.shape==="rotated_rect"){const i=n.ccw_rotation*Math.PI/180,a=Math.cos(i),o=Math.sin(i),s=n.width/2,l=n.height/2,c=Math.abs(s*a)+Math.abs(l*o),u=Math.abs(s*o)+Math.abs(l*a);return{center:{x:n.x,y:n.y},bounds:{left:n.x-c,right:n.x+c,top:n.y-u,bottom:n.y+u},width:c*2,height:u*2}}if(n.shape==="circle")return{center:{x:n.x,y:n.y},bounds:{left:n.x-n.radius,top:n.y-n.radius,right:n.x+n.radius,bottom:n.y+n.radius},width:n.radius*2,height:n.radius*2};throw new Error(`circuitJson bounds calculation not implemented for shape "${n.shape}"`)}_setPositionFromLayout(t){var a;const{db:n}=this.root;n.pcb_smtpad.update(this.pcb_smtpad_id,{x:t.x,y:t.y});const i=n.pcb_solder_paste.list().find(o=>o.pcb_smtpad_id===this.pcb_smtpad_id);n.pcb_solder_paste.update(i==null?void 0:i.pcb_solder_paste_id,{x:t.x,y:t.y}),(a=this.matchedPort)==null||a._setPositionFromLayout(t)}},rIe=class extends w_{constructor(){super(...arguments);Je(this,"pcb_silkscreen_path_id",null);Je(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenPath",zodProps:kUe}}doInitialPcbPrimitiveRender(){var c,u,f;if((c=this.root)!=null&&c.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),a=i(n.layer??"top");if(a!=="top"&&a!=="bottom")throw new Error(`Invalid layer "${a}" for SilkscreenPath. Must be "top" or "bottom".`);const o=this._computePcbGlobalTransformBeforeLayout(),s=this.getSubcircuit(),l=t.pcb_silkscreen_path.insert({pcb_component_id:(u=this.parent)==null?void 0:u.pcb_component_id,layer:a,route:n.route.map(p=>{const v=Ir(o,{x:p.x,y:p.y});return{...p,x:v.x,y:v.y}}),stroke_width:n.strokeWidth??.1,subcircuit_id:(s==null?void 0:s.subcircuit_id)??void 0,pcb_group_id:((f=this.getGroup())==null?void 0:f.pcb_group_id)??void 0});this.pcb_silkscreen_path_id=l.pcb_silkscreen_path_id}getPcbSize(){const{_parsedProps:t}=this;if(!t.route||t.route.length===0)return{width:0,height:0};let n=1/0,i=-1/0,a=1/0,o=-1/0;for(const s of t.route)n=Math.min(n,s.x),i=Math.max(i,s.x),a=Math.min(a,s.y),o=Math.max(o,s.y);return{width:i-n,height:o-a}}},PGt=k.object({route:k.array(NP),source_trace_id:k.string().optional()}),iIe=class extends w_{constructor(){super(...arguments);Je(this,"pcb_trace_id",null);Je(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbTrace",zodProps:PGt}}doInitialPcbPrimitiveRender(){var u,f;if((u=this.root)!=null&&u.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,i=this.getPrimitiveContainer(),a=this.getSubcircuit(),{maybeFlipLayer:o}=this._getPcbPrimitiveFlippedHelpers(),s=this._computePcbGlobalTransformBeforeLayout(),l=n.route.map(p=>{const{x:v,y:x,...S}=p,E=Ir(s,{x:v,y:x});return p.route_type==="wire"&&p.layer?{...E,...S,layer:o(p.layer)}:{...E,...S}}),c=t.pcb_trace.insert({pcb_component_id:i.pcb_component_id,source_trace_id:n.source_trace_id,route:l,subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((f=this.getGroup())==null?void 0:f.pcb_group_id)??void 0});this.pcb_trace_id=c.pcb_trace_id}getPcbSize(){const{_parsedProps:t}=this;if(!t.route||t.route.length===0)return{width:0,height:0};let n=1/0,i=-1/0,a=1/0,o=-1/0;for(const s of t.route)n=Math.min(n,s.x),i=Math.max(i,s.x),a=Math.min(a,s.y),o=Math.max(o,s.y),s.route_type==="wire"&&(n=Math.min(n,s.x-s.width/2),i=Math.max(i,s.x+s.width/2),a=Math.min(a,s.y-s.width/2),o=Math.max(o,s.y+s.width/2));return n===1/0||i===-1/0||a===1/0||o===-1/0?{width:0,height:0}:{width:i-n,height:o-a}}},aIe=class extends w_{constructor(){super(...arguments);Je(this,"pcb_plated_hole_id",null);Je(this,"matchedPort",null);Je(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PlatedHole",zodProps:lUe}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){const{_parsedProps:t}=this;if(t.shape==="circle")return{width:t.outerDiameter,height:t.outerDiameter};if(t.shape==="oval"||t.shape==="pill")return{width:t.outerWidth,height:t.outerHeight};throw new Error(`getPcbSize for shape "${t.shape}" not implemented for ${this.componentName}`)}_getPcbCircuitJsonBounds(){const{db:t}=this.root,n=t.pcb_plated_hole.get(this.pcb_plated_hole_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){var i;const{db:n}=this.root;n.pcb_plated_hole.update(this.pcb_plated_hole_id,{x:t.x,y:t.y}),(i=this.matchedPort)==null||i._setPositionFromLayout(t)}doInitialPortMatching(){var n;const t=(n=this.getPrimitiveContainer())==null?void 0:n.selectAll("port");if(this.props.portHints){for(const i of t)if(i.isMatchingAnyOf(this.props.portHints)){this.matchedPort=i,i.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){var s,l,c,u,f,p,v,x,S,E,b;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),a=((l=this.parent)==null?void 0:l.pcb_component_id)??((c=this.getPrimitiveContainer())==null?void 0:c.pcb_component_id),o=this.getSubcircuit();if(n.shape==="circle"){const C=t.pcb_plated_hole.insert({pcb_component_id:a,pcb_port_id:(u=this.matchedPort)==null?void 0:u.pcb_port_id,outer_diameter:n.outerDiameter,hole_diameter:n.holeDiameter,shape:"circle",port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:(o==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((f=this.getGroup())==null?void 0:f.pcb_group_id)??void 0});this.pcb_plated_hole_id=C.pcb_plated_hole_id,t.pcb_solder_paste.insert({layer:"top",shape:"circle",radius:n.outerDiameter/2,x:i.x,y:i.y,subcircuit_id:(o==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((p=this.getGroup())==null?void 0:p.pcb_group_id)??void 0}),t.pcb_solder_paste.insert({layer:"bottom",shape:"circle",radius:n.outerDiameter/2,x:i.x,y:i.y,subcircuit_id:(o==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((v=this.getGroup())==null?void 0:v.pcb_group_id)??void 0})}else if(n.shape==="pill"||n.shape==="oval"){const C=t.pcb_plated_hole.insert({pcb_component_id:a,pcb_port_id:(x=this.matchedPort)==null?void 0:x.pcb_port_id,outer_width:n.outerWidth,outer_height:n.outerHeight,hole_width:n.holeWidth,hole_height:n.holeHeight,shape:n.shape,port_hints:this.getNameAndAliases(),x:i.x,y:i.y,layers:["top","bottom"],subcircuit_id:(o==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((S=this.getGroup())==null?void 0:S.pcb_group_id)??void 0});this.pcb_plated_hole_id=C.pcb_plated_hole_id,t.pcb_solder_paste.insert({layer:"top",shape:n.shape,width:n.outerWidth,height:n.outerHeight,x:i.x,y:i.y,subcircuit_id:(o==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((E=this.getGroup())==null?void 0:E.pcb_group_id)??void 0}),t.pcb_solder_paste.insert({layer:"bottom",shape:n.shape,width:n.outerWidth,height:n.outerHeight,x:i.x,y:i.y,subcircuit_id:(o==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((b=this.getGroup())==null?void 0:b.pcb_group_id)??void 0})}}doInitialPcbPortAttachment(){var n,i;if((n=this.root)!=null&&n.pcbDisabled)return;const{db:t}=this.root;t.pcb_plated_hole.update(this.pcb_plated_hole_id,{pcb_port_id:(i=this.matchedPort)==null?void 0:i.pcb_port_id})}},Moe=class extends w_{constructor(){super(...arguments);Je(this,"pcb_keepout_id",null);Je(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Keepout",zodProps:OUe}}doInitialPcbPrimitiveRender(){var c,u,f;if((c=this.root)!=null&&c.pcbDisabled)return;const t=this.getSubcircuit(),{db:n}=this.root,{_parsedProps:i}=this,a=this._getGlobalPcbPositionBeforeLayout(),o=uw(this._computePcbGlobalTransformBeforeLayout()),s=Math.abs(o.rotation.angle*(180/Math.PI)-90)%180<.01;let l=null;i.shape==="circle"?l=n.pcb_keepout.insert({layers:["top"],shape:"circle",radius:i.radius,center:{x:a.x,y:a.y},subcircuit_id:(t==null?void 0:t.subcircuit_id)??void 0,pcb_group_id:((u=t==null?void 0:t.getGroup())==null?void 0:u.pcb_group_id)??void 0}):i.shape==="rect"&&(l=n.pcb_keepout.insert({layers:["top"],shape:"rect",...s?{width:i.height,height:i.width}:{width:i.width,height:i.height},center:{x:a.x,y:a.y},subcircuit_id:(t==null?void 0:t.subcircuit_id)??void 0,pcb_group_id:((f=t==null?void 0:t.getGroup())==null?void 0:f.pcb_group_id)??void 0})),l&&(this.pcb_keepout_id=l.pcb_keepout_id)}},oIe=class extends w_{constructor(){super(...arguments);Je(this,"pcb_hole_id",null);Je(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Hole",zodProps:yUe}}getPcbSize(){const{_parsedProps:t}=this;return{width:t.diameter,height:t.diameter}}doInitialPcbPrimitiveRender(){var s,l;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),a=this._getGlobalPcbPositionBeforeLayout(),o=t.pcb_hole.insert({hole_shape:"circle",hole_diameter:n.diameter,x:a.x,y:a.y,subcircuit_id:(i==null?void 0:i.subcircuit_id)??void 0,pcb_group_id:((l=i==null?void 0:i.getGroup())==null?void 0:l.pcb_group_id)??void 0});this.pcb_hole_id=o.pcb_hole_id}_getPcbCircuitJsonBounds(){const{db:t}=this.root,n=t.pcb_hole.get(this.pcb_hole_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){const{db:n}=this.root;n.pcb_hole.update(this.pcb_hole_id,{x:t.x,y:t.y})}},Coe=class extends w_{constructor(){super(...arguments);Je(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenText",zodProps:IUe}}doInitialPcbPrimitiveRender(){var l,c;if((l=this.root)!=null&&l.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,i=this.getPrimitiveContainer(),a=this._getGlobalPcbPositionBeforeLayout(),{maybeFlipLayer:o}=this._getPcbPrimitiveFlippedHelpers(),s=this.getSubcircuit();t.pcb_silkscreen_text.insert({anchor_alignment:n.anchorAlignment,anchor_position:{x:a.x,y:a.y},font:n.font??"tscircuit2024",font_size:n.fontSize??1,layer:o(n.layer??"top"),text:n.text??"",ccw_rotation:n.pcbRotation,pcb_component_id:i.pcb_component_id,subcircuit_id:(s==null?void 0:s.subcircuit_id)??void 0,pcb_group_id:((c=this.getGroup())==null?void 0:c.pcb_group_id)??void 0})}getPcbSize(){const{_parsedProps:t}=this,n=t.fontSize??1,a=(t.text??"").length*n,o=n;return{width:a*n,height:o*n}}},NGt=({elm:r,pinLabels:e,readableRotation:t})=>{var a;const n=r.text.replace(/[{}]/g,"").toLowerCase();let i=n;if(Array.isArray(e)){const o=parseInt(n.replace(/[^\d]/g,""),10)-1;i=e[o]??n}else typeof e=="object"&&(i=((a=e[n])==null?void 0:a[0])??n);return new Coe({anchorAlignment:"center",text:i??n,fontSize:r.font_size+.2,pcbX:isNaN(r.anchor_position.x)?0:r.anchor_position.x,pcbY:r.anchor_position.y,pcbRotation:t??0})},DGt=({componentName:r,componentRotation:e,footprint:t,pinLabels:n},i)=>{const a=[];for(const o of i)if(o.type==="pcb_smtpad"&&o.shape==="rect")a.push(new Toe({pcbX:o.x,pcbY:o.y,layer:o.layer,shape:"rect",height:o.height,width:o.width,portHints:o.port_hints}));else if(o.type==="pcb_smtpad"&&o.shape==="circle")a.push(new Toe({pcbX:o.x,pcbY:o.y,layer:o.layer,shape:"circle",radius:o.radius,portHints:o.port_hints}));else if(o.type==="pcb_silkscreen_path")a.push(new rIe({layer:o.layer,route:o.route,strokeWidth:o.stroke_width}));else if(o.type==="pcb_plated_hole"&&o.shape==="circle")o.shape==="circle"&&a.push(new aIe({pcbX:o.x,pcbY:o.y,shape:"circle",holeDiameter:o.hole_diameter,outerDiameter:o.outer_diameter,portHints:o.port_hints}));else if(o.type==="pcb_keepout"&&o.shape==="circle")a.push(new Moe({pcbX:o.center.x,pcbY:o.center.y,shape:"circle",radius:o.radius}));else if(o.type==="pcb_keepout"&&o.shape==="rect")a.push(new Moe({pcbX:o.center.x,pcbY:o.center.y,shape:"rect",width:o.width,height:o.height}));else if(o.type==="pcb_hole"&&o.hole_shape==="circle")a.push(new oIe({pcbX:o.x,pcbY:o.y,diameter:o.hole_diameter}));else if(o.type==="pcb_silkscreen_text"){let s=e?parseInt(e):0;const l=(s%360+360)%360;s=l>90&&l<=270?(l+180)%360:l,t.includes("pinrow")&&o.text.includes("PIN")&&n?a.push(NGt({elm:o,pinLabels:n,readableRotation:s})):o.text==="{REF}"&&a.push(new Coe({anchorAlignment:"center",text:r,fontSize:o.font_size+.2,pcbX:isNaN(o.anchor_position.x)?0:o.anchor_position.x,pcbY:o.anchor_position.y,pcbRotation:s??0}))}else o.type==="pcb_trace"&&a.push(new iIe({route:o.route}));return a};function sIe(r){let e=1/0,t=1/0,n=-1/0,i=-1/0;for(const s of r)if(s.isPcbPrimitive&&!s.componentName.startsWith("Silkscreen")){const{x:l,y:c}=s._getGlobalPcbPositionBeforeLayout(),{width:u,height:f}=s.getPcbSize();e=Math.min(e,l-u/2),t=Math.min(t,c-f/2),n=Math.max(n,l+u/2),i=Math.max(i,c+f/2)}else if(s.componentName==="Footprint"){const l=sIe(s.children);e=Math.min(e,l.minX),t=Math.min(t,l.minY),n=Math.max(n,l.maxX),i=Math.max(i,l.maxY)}let a=n-e,o=i-t;return a<0&&(a=0),o<0&&(o=0),{minX:e,minY:t,maxX:n,maxY:i,width:a,height:o}}function LGt(r,e){const t=e.x-r.x,n=e.y-r.y;return Math.abs(t)>Math.abs(n)?t>=0?"right":"left":n>=0?"up":"down"}var OGt=r=>{if(r.length<=1)return!0;const e=r.map(a=>{const o=a._getPcbCircuitJsonBounds();return{left:o.bounds.left,right:o.bounds.right,top:o.bounds.top,bottom:o.bounds.bottom}}),t=Array(e.length).fill(!1).map(()=>Array(e.length).fill(!1));for(let a=0;a<e.length;a++)for(let o=a+1;o<e.length;o++){const s=e[a],l=e[o];t[a][o]=t[o][a]=!(s.right<l.left||s.left>l.right||s.bottom>l.top||s.top<l.bottom)}const n=new Set,i=a=>{n.add(a);for(let o=0;o<e.length;o++)t[a][o]&&!n.has(o)&&i(o)};return i(0),n.size===e.length},zGt=r=>{if(r.length===0)throw new Error("Cannot get center of empty PCB primitives array");const e=r.map(i=>i._getPcbCircuitJsonBounds().center).filter(Boolean),t=e.reduce((i,a)=>i+a.x,0),n=e.reduce((i,a)=>i+a.y,0);return{x:t/e.length,y:n/e.length}},UGt=k.object({name:k.string().optional(),pinNumber:k.number().optional(),aliases:k.array(k.string()).optional()}),q4=class extends w_{constructor(t,n={}){if(!t.name&&t.pinNumber!==void 0&&(t.name=`pin${t.pinNumber}`),!t.name)throw new Error("Port must have a name or a pinNumber");super(t);Je(this,"source_port_id",null);Je(this,"pcb_port_id",null);Je(this,"schematic_port_id",null);Je(this,"schematicSymbolPortDef",null);Je(this,"matchedComponents");Je(this,"facingDirection",null);Je(this,"originDescription",null);n.originDescription&&(this.originDescription=n.originDescription),this.matchedComponents=[]}get config(){return{componentName:"Port",zodProps:UGt}}_getGlobalPcbPositionBeforeLayout(){const t=this.matchedComponents.find(i=>i.isPcbPrimitive),n=this.parent;if(n&&!n.props.footprint)throw new Error(`${n.componentName} "${n.props.name}" does not have a footprint. Add a footprint prop, e.g. <${n.componentName.toLowerCase()} footprint="..." />`);if(!t)throw new Error(`Port ${this} has no matching PCB primitives. This often means the footprint's pads lack matching port hints.`);return(t==null?void 0:t._getGlobalPcbPositionBeforeLayout())??{x:0,y:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_port_id)return super._getPcbCircuitJsonBounds();const{db:t}=this.root,n=t.pcb_port.get(this.pcb_port_id);return{center:{x:n.x,y:n.y},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getGlobalPcbPositionAfterLayout(){return this._getPcbCircuitJsonBounds().center}_getPortsInternallyConnectedToThisPort(){const t=this.parent;if(!t||!t._getInternallyConnectedPins)return[];const n=t._getInternallyConnectedPins();for(const i of n)if(i.some(a=>a===this))return i;return[]}_hasSchematicPort(){var i,a;if((i=this.parent)==null?void 0:i.getSchematicSymbol())return!!(this.schematicSymbolPortDef||this._getPortsInternallyConnectedToThisPort().some(s=>s.schematicSymbolPortDef));const n=(a=this==null?void 0:this.parent)==null?void 0:a._getSchematicBoxDimensions();return!!(n&&this.props.pinNumber!==void 0&&n.getPortPositionByPinNumber(this.props.pinNumber))}_getGlobalSchematicPositionBeforeLayout(){var i,a,o;const t=(i=this.parent)==null?void 0:i.getSchematicSymbol();if(t){let s=this.schematicSymbolPortDef;if(!s&&(s=((a=this._getPortsInternallyConnectedToThisPort().find(c=>c.schematicSymbolPortDef))==null?void 0:a.schematicSymbolPortDef)??null,!s))throw new Error(`Couldn't find schematicSymbolPortDef for port ${this.getString()}, searched internally connected ports and none had a schematicSymbolPortDef. Why are we trying to get the schematic position of this port?`);const l=Tc(this.parent.computeSchematicGlobalTransform(),Gf(-t.center.x,-t.center.y));return Ir(l,s)}const n=(o=this==null?void 0:this.parent)==null?void 0:o._getSchematicBoxDimensions();if(n&&this.props.pinNumber!==void 0){const s=n.getPortPositionByPinNumber(this.props.pinNumber);if(!s)throw new Error(`Couldn't find position for schematic_port for port ${this.getString()} inside of the schematic box`);return Ir(this.parent.computeSchematicGlobalTransform(),s)}throw new Error(`Couldn't find position for schematic_port for port ${this.getString()}`)}_getGlobalSchematicPositionAfterLayout(){const{db:t}=this.root;if(!this.schematic_port_id)throw new Error(`Can't get schematic port position after layout for "${this.getString()}", no schematic_port_id`);const n=t.schematic_port.get(this.schematic_port_id);if(!n)throw new Error(`Schematic port not found when trying to get post-layout position: ${this.schematic_port_id}`);return n.center}registerMatch(t){this.matchedComponents.push(t)}getNameAndAliases(){const{_parsedProps:t}=this;return Array.from(new Set([...t.aliases??[],...t.name?[t.name]:[],...typeof t.pinNumber=="number"?[`pin${t.pinNumber}`,t.pinNumber.toString()]:[],...this.externallyAddedAliases??[]]))}isMatchingPort(t){return this.isMatchingAnyOf(t.getNameAndAliases())}getPortSelector(){var t;return`.${(t=this.parent)==null?void 0:t.props.name} > port.${this.props.name}`}getAvailablePcbLayers(){return Array.from(new Set(this.matchedComponents.flatMap(t=>t.getAvailablePcbLayers())))}_getDirectlyConnectedTraces(){return this.getSubcircuit().selectAll("trace").filter(i=>i._isExplicitlyConnectedToPort(this))}doInitialSourceRender(){var o,s;const{db:t}=this.root,{_parsedProps:n}=this,i=this.getNameAndAliases(),a=t.source_port.insert({name:n.name,pin_number:n.pinNumber,port_hints:i,source_component_id:(o=this.parent)==null?void 0:o.source_component_id,subcircuit_id:(s=this.getSubcircuit())==null?void 0:s.subcircuit_id});this.source_port_id=a.source_port_id}doInitialSourceParentAttachment(){var n,i,a,o,s;const{db:t}=this.root;if(!((n=this.parent)!=null&&n.source_component_id))throw new Error(`${this.getString()} has no parent source component (parent: ${(i=this.parent)==null?void 0:i.getString()})`);t.source_port.update(this.source_port_id,{source_component_id:(a=this.parent)==null?void 0:a.source_component_id,subcircuit_id:(o=this.getSubcircuit())==null?void 0:o.subcircuit_id}),this.source_component_id=(s=this.parent)==null?void 0:s.source_component_id}doInitialPcbPortRender(){var o,s,l,c,u;if((o=this.root)!=null&&o.pcbDisabled)return;const{db:t}=this.root,{matchedComponents:n}=this;if(!((s=this.parent)!=null&&s.pcb_component_id))throw new Error(`${this.getString()} has no parent pcb component, cannot render pcb_port (parent: ${(l=this.parent)==null?void 0:l.getString()})`);const i=n.filter(f=>f.isPcbPrimitive);if(i.length===0)return;let a=null;if(i.length===1&&(a=i[0]._getPcbCircuitJsonBounds().center),i.length>1){if(!OGt(i))throw new Error(`${this.getString()} has multiple non-overlapping pcb matches, unclear how to place pcb_port: ${i.map(f=>f.getString()).join(", ")}. (Note: tscircuit core does not currently allow you to specify internally connected pcb primitives with the same port hints, try giving them different port hints and specifying they are connected externally- or file an issue)`);a=zGt(i)}if(a){const f=this.getSubcircuit(),p=t.pcb_port.insert({pcb_component_id:(c=this.parent)==null?void 0:c.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:(f==null?void 0:f.subcircuit_id)??void 0,pcb_group_id:((u=this.getGroup())==null?void 0:u.pcb_group_id)??void 0,...a,source_port_id:this.source_port_id});this.pcb_port_id=p.pcb_port_id}else{const f=i[0];throw new Error(`${f.getString()} does not have a center or _getGlobalPcbPositionBeforeLayout method (needed for pcb_port placement)`)}}doInitialSchematicPortRender(){var p;const{db:t}=this.root,{_parsedProps:n}=this,i=this.getPrimitiveContainer();if(!i||!this._hasSchematicPort())return;const a=i._getGlobalSchematicPositionBeforeLayout(),o=this._getGlobalSchematicPositionBeforeLayout();let s=null;const l=i._getSchematicBoxDimensions();l&&n.pinNumber!==void 0&&(s=l.getPortPositionByPinNumber(n.pinNumber)),this.getSubcircuit().props._schDebugObjectsEnabled&&t.schematic_debug_object.insert({shape:"rect",center:o,size:{width:.1,height:.1},label:"obstacle"}),s!=null&&s.side?this.facingDirection={left:"left",right:"right",top:"up",bottom:"down"}[s.side]:this.facingDirection=LGt(a,o);const c=t.source_port.get(this.source_port_id);let u;for(const v of(c==null?void 0:c.port_hints)??[])v.match(/^(pin)?\d+$/)||v.match(/^(left|right)/)&&!(c!=null&&c.name.match(/^(left|right)/))||(u=v);const f=t.schematic_port.insert({schematic_component_id:(p=this.parent)==null?void 0:p.schematic_component_id,center:o,source_port_id:this.source_port_id,facing_direction:this.facingDirection,distance_from_component_edge:.4,side_of_component:s==null?void 0:s.side,pin_number:n.pinNumber,true_ccw_index:s==null?void 0:s.trueIndex,display_pin_label:u});this.schematic_port_id=f.schematic_port_id}_setPositionFromLayout(t){const{db:n}=this.root;this.pcb_port_id&&n.pcb_port.update(this.pcb_port_id,{x:t.x,y:t.y})}_hasMatchedPcbPrimitive(){return this.matchedComponents.some(t=>t.isPcbPrimitive)}},lIe=r=>{const e=r.find(t=>/^(pin)?\d+$/.test(t));return e?Number.parseInt(e.replace(/^pin/,"")):null};function uA(r,e){var a;const t=lIe(r);if(!t)return null;const i=[...r.filter(o=>o.toString()!==t.toString()&&o!==`pin${t}`),...((a=e==null?void 0:e.additionalAliases)==null?void 0:a[`pin${t}`])??[]];return new q4({pinNumber:t,aliases:i})}var IGt=r=>{for(const e of["leftSide","rightSide","topSide","bottomSide"])if(e in r&&typeof r[e]=="number")throw new Error(`A number was specified for "${e}", you probably meant to use "size" not "side"`);return"leftSide"in r||"rightSide"in r||"topSide"in r||"bottomSide"in r},kGt=r=>{var a,o,s,l;if(IGt(r))return{leftSize:((a=r.leftSide)==null?void 0:a.pins.length)??0,rightSize:((o=r.rightSide)==null?void 0:o.pins.length)??0,topSize:((s=r.topSide)==null?void 0:s.pins.length)??0,bottomSize:((l=r.bottomSide)==null?void 0:l.pins.length)??0};const{leftSize:e=0,rightSize:t=0,topSize:n=0,bottomSize:i=0}=r;return{leftSize:e,rightSize:t,topSize:n,bottomSize:i}};function cIe(r){return r.leftSide!==void 0}var FGt=r=>{var E,b,C,O,U,q,Y,Q;const e=r.portDistanceFromEdge??.4;let t=r.schPortArrangement?kGt(r.schPortArrangement):null;const n={left:0,right:0,top:0,bottom:0};let i=r.pinCount??null;if(i===null)if(t)i=t.leftSize+t.rightSize+t.topSize;else throw new Error("Could not determine pin count for the schematic box");if(i&&!t){const K=Math.floor(i/2);t={leftSize:i-K,rightSize:K,topSize:0,bottomSize:0}}t||(t={leftSize:0,rightSize:0,topSize:0,bottomSize:0});const a=({side:K,sideIndex:te,truePinIndex:J})=>{var Pe,Ee,Ce,be;if(!r.schPortArrangement||!cIe(r.schPortArrangement))return J+1;const fe={left:"top-to-bottom",bottom:"left-to-right",right:"bottom-to-top",top:"right-to-left"}[K],he=((Ee=(Pe=r.schPortArrangement)==null?void 0:Pe[`${K}Side`])==null?void 0:Ee.direction)??fe,ve=(be=(Ce=r.schPortArrangement)==null?void 0:Ce[`${K}Side`])==null?void 0:be.pins;let Te=te;return he!==fe&&(Te=ve.length-te-1),cA(ve[Te],r.pinLabels)},o=[];let s=0,l=0;for(let K=0;K<t.leftSize;K++){const te=a({side:"left",sideIndex:K,truePinIndex:l}),J=((E=r.numericSchPinStyle)==null?void 0:E[`pin${te}`])??((b=r.numericSchPinStyle)==null?void 0:b[te]);J!=null&&J.topMargin&&(s+=J.topMargin),o.push({trueIndex:l,pinNumber:te,side:"left",distanceFromOrthogonalEdge:s}),J!=null&&J.bottomMargin&&(s+=J.bottomMargin),K===t.leftSize-1?n.left=s:s+=r.schPinSpacing,l++}s=0;for(let K=0;K<t.bottomSize;K++){const te=a({side:"bottom",sideIndex:K,truePinIndex:l}),J=((C=r.numericSchPinStyle)==null?void 0:C[`pin${te}`])??((O=r.numericSchPinStyle)==null?void 0:O[te]);J!=null&&J.leftMargin&&(s+=J.leftMargin),o.push({trueIndex:l,pinNumber:te,side:"bottom",distanceFromOrthogonalEdge:s}),J!=null&&J.rightMargin&&(s+=J.rightMargin),K===t.bottomSize-1?n.bottom=s:s+=r.schPinSpacing,l++}s=0;for(let K=0;K<t.rightSize;K++){const te=a({side:"right",sideIndex:K,truePinIndex:l}),J=((U=r.numericSchPinStyle)==null?void 0:U[`pin${te}`])??((q=r.numericSchPinStyle)==null?void 0:q[te]);J!=null&&J.bottomMargin&&(s+=J.bottomMargin),o.push({trueIndex:l,pinNumber:te,side:"right",distanceFromOrthogonalEdge:s}),J!=null&&J.topMargin&&(s+=J.topMargin),K===t.rightSize-1?n.right=s:s+=r.schPinSpacing,l++}s=0;for(let K=0;K<t.topSize;K++){const te=a({side:"top",sideIndex:K,truePinIndex:l}),J=((Y=r.numericSchPinStyle)==null?void 0:Y[`pin${te}`])??((Q=r.numericSchPinStyle)==null?void 0:Q[te]);J!=null&&J.rightMargin&&(s+=J.rightMargin),o.push({trueIndex:l,pinNumber:te,side:"top",distanceFromOrthogonalEdge:s}),J!=null&&J.leftMargin&&(s+=J.leftMargin),K===t.topSize-1?n.top=s:s+=r.schPinSpacing,l++}let c=r.schWidth;c||(c=Math.max(n.top+r.schPinSpacing*2,n.bottom+r.schPinSpacing*2));const u=r.pinLabels?Math.max(...Object.values(r.pinLabels).map(K=>K.length*.1)):0,f=u>0?1.1:0;c=Math.max(c,u+f);let p=r.schHeight;p||(p=Math.max(n.left+r.schPinSpacing*2,n.right+r.schPinSpacing*2));const v={left:{x:-c/2-e,y:n.left/2},bottom:{x:-n.bottom/2,y:-p/2-e},right:{x:c/2+e,y:-n.right/2},top:{x:n.top/2,y:p/2+e}},x={left:{x:0,y:-1},right:{x:0,y:1},top:{x:-1,y:0},bottom:{x:1,y:0}},S=o.map(K=>{const{distanceFromOrthogonalEdge:te,side:J}=K,fe=v[J],he=x[J];return{x:fe.x+te*he.x,y:fe.y+te*he.y,...K}});return{getPortPositionByPinNumber(K){const te=S.find(J=>J.pinNumber.toString()===K.toString());return te||null},getSize(){return{width:c,height:p}},getSizeIncludingPins(){return{width:c+(t.leftSize||t.rightSize?.4:0),height:p+(t.topSize||t.bottomSize?.4:0)}},pinCount:i}},BGt=E1("tscircuit:core:footprint"),HGt=class extends w_{get config(){return{componentName:"Footprint",zodProps:xUe}}doInitialPcbFootprintLayout(){var p,v,x,S,E;if((p=this.root)!=null&&p.pcbDisabled)return;const e=this.children.filter(b=>b.componentName==="Constraint");if(e.length===0)return;const{isFlipped:t}=this._getPcbPrimitiveFlippedHelpers(),n=b=>t&&"left"in b&&"right"in b?{...b,left:b.right,right:b.left}:b,i=e.flatMap(b=>b._getAllReferencedComponents().componentsWithSelectors).map(({component:b,selector:C,componentSelector:O,edge:U})=>({component:b,selector:C,componentSelector:O,edge:U,bounds:b._getPcbCircuitJsonBounds()}));if(i.some(b=>b.edge))throw new Error("edge constraints not implemented yet for footprint layout, contributions welcome!");function a(b){return i.find(({selector:C})=>C===b)}const o=new hG,s={};function l(b){return b in s||(s[b]=new yC(b),o.addEditVariable(s[b],J1.weak)),s[b]}for(const{selector:b,bounds:C}of i){const O=l(`${b}_x`),U=l(`${b}_y`);o.suggestValue(O,C.center.x),o.suggestValue(U,C.center.y)}for(const b of e){const C=b._parsedProps;if("xDist"in C){const{xDist:O,left:U,right:q,edgeToEdge:Y,centerToCenter:Q}=n(C),K=l(`${U}_x`),te=l(`${q}_x`),J=(v=a(U))==null?void 0:v.bounds,fe=(x=a(q))==null?void 0:x.bounds;if(Q){const he=new w1(te,[-1,K]);o.addConstraint(new px(he,s_.Eq,C.xDist,J1.required))}else if(Y){const he=new w1(te,-fe.width/2,[-1,K],-J.width/2);o.addConstraint(new px(he,s_.Eq,C.xDist,J1.required))}}else if("yDist"in C){const{yDist:O,top:U,bottom:q,edgeToEdge:Y,centerToCenter:Q}=C,K=l(`${U}_y`),te=l(`${q}_y`),J=(S=a(U))==null?void 0:S.bounds,fe=(E=a(q))==null?void 0:E.bounds;if(Q){const he=new w1(K,[-1,te]);o.addConstraint(new px(he,s_.Eq,C.yDist,J1.required))}else if(Y){const he=new w1(K,J.height/2,[-1,te],-fe.height/2);o.addConstraint(new px(he,s_.Eq,C.yDist,J1.required))}}else if("sameY"in C){const{for:O}=C;if(O.length<2)continue;const U=O.map(Y=>l(`${Y}_y`)),q=new w1(...U.slice(1));o.addConstraint(new px(q,s_.Eq,U[0],J1.required))}else if("sameX"in C){const{for:O}=C;if(O.length<2)continue;const U=O.map(Y=>l(`${Y}_x`)),q=new w1(...U.slice(1));o.addConstraint(new px(q,s_.Eq,U[0],J1.required))}}o.updateVariables(),BGt.enabled&&(console.log("Solution to layout constraints:"),console.table(Object.entries(s).map(([b,C])=>({var:b,val:C.value()}))));const c={left:1/0,right:-1/0,top:-1/0,bottom:1/0};for(const{selector:b,bounds:{width:C,height:O}}of i){const U=l(`${b}_x`),q=l(`${b}_y`),Y=U.value()-C/2,Q=U.value()+C/2,K=q.value()+O/2,te=q.value()-O/2;c.left=Math.min(c.left,Y),c.right=Math.max(c.right,Q),c.top=Math.max(c.top,K),c.bottom=Math.min(c.bottom,te)}const u={x:-(c.right+c.left)/2,y:-(c.top+c.bottom)/2},f=this.getPrimitiveContainer()._getGlobalPcbPositionBeforeLayout();u.x+=f.x,u.y+=f.y;for(const{component:b,selector:C}of i){const O=l(`${C}_x`),U=l(`${C}_y`);b._setPositionFromLayout({x:O.value()+u.x,y:U.value()+u.y})}}},jGt=(r,e)=>{if(!r)return;const t={};for(const[n,i]of Object.entries(r)){const a=cA(n,e),o={leftMargin:i.marginLeft??i.leftMargin,rightMargin:i.marginRight??i.rightMargin,topMargin:i.marginTop??i.topMargin,bottomMargin:i.marginBottom??i.bottomMargin};t[`pin${a}`]={...t[`pin${a}`],...o}}return t},uIe=class{constructor({input:e}){Je(this,"input");this.input=e}solveAndMapToTraces(){const e=[];for(const t of this.input.connections){if(t.pointsToConnect.length!==2)continue;const[n,i]=t.pointsToConnect,a={type:"pcb_trace",pcb_trace_id:"",connection_name:t.name,route:[{route_type:"wire",x:n.x,y:n.y,layer:"top",width:.1},{route_type:"wire",x:i.x,y:i.y,layer:"top",width:.1}]};e.push(a)}return e}},VGt=r=>{const e=Math.min(...r.map(a=>a.center.x)),t=Math.max(...r.map(a=>a.center.x)),n=Math.min(...r.map(a=>a.center.y)),i=Math.max(...r.map(a=>a.center.y));return{minX:e,maxX:t,minY:n,maxY:i}},fIe=["top","bottom","inner1","inner2"],zk=(r,e=[])=>{var s;const t=[];if(e.length===0){const l=r[0].layers;for(const c of l)t.push(...zk(r.slice(1),[c]));return t}if(r.length===0)return[];const n=r[0],i=n.via||n.optional_via,a=e[e.length-1];if(r.length===1){const l=n;return l.layers&&i?l.layers.map(c=>({layer_path:[...e,c]})):(s=l.layers)!=null&&s.includes(a)?[{layer_path:[...e,a]}]:[]}if(!i)return n.layers&&!n.layers.includes(a)?[]:zk(r.slice(1),e.concat([a]));const o=(n.optional_via?fIe:fIe.filter(l=>l!==a)).filter(l=>{var c;return!n.layers||((c=n.layers)==null?void 0:c.includes(l))});for(const l of o)t.push(...zk(r.slice(1),e.concat(l)));return t};function dIe(r){const e={x:r.to.x-r.from.x,y:r.to.y-r.from.y},t=Math.abs(e.x),n=Math.abs(e.y);return t>n?e.x>0?"right":"left":e.y>0?"down":"up"}function iM(r,e){return Math.hypot(r.x-e.x,r.y-e.y)}var GGt=r=>{if(r.length===1)return r[0];if(r.some(l=>l.length===0))throw new Error("Cannot merge routes with zero length");const e=[],t=r[0][0],n=r[0][r[0].length-1],i=r[1][0],a=r[1][r[1].length-1],o=Math.min(iM(t,i),iM(t,a)),s=Math.min(iM(n,i),iM(n,a));o<s?e.push(...r[0].reverse()):e.push(...r[0]);for(let l=1;l<r.length;l++){const c=e[e.length-1],u=r[l],f=u[0],p=u[u.length-1],v=iM(c,f),x=iM(c,p);v<x?e.push(...u):e.push(...u.reverse())}for(let l=1;l<e.length-1;l++){const c=e[l-1],u=e[l];c.route_type==="wire"&&u.route_type==="wire"&&c.layer!==u.layer&&e.splice(l,0,{x:c.x,y:c.y,from_layer:c.layer,to_layer:u.layer,route_type:"via"})}return e},qGt=(r,e)=>{const t="_getGlobalPcbPositionBeforeLayout"in r?r._getGlobalPcbPositionBeforeLayout():r,n="_getGlobalPcbPositionBeforeLayout"in e?e._getGlobalPcbPositionBeforeLayout():e;return Math.sqrt((t.x-n.x)**2+(t.y-n.y)**2)};function $Gt(r,e){if(e.length===0)throw new Error("No candidates given to getClosest method");let t=e[0],n=1/0;for(const i of e){const a=qGt(r,i);a<n&&(t=i,n=a)}return t}var YGt=(r,e)=>{let t=0;t+=r.length??0,t+=e.filter(n=>n.is_crossing).length;for(let n=1;n<e.length;n++){const i=e[n-1],a=e[n],o=Math.abs(i.from.x-i.to.x)<.01,s=Math.abs(a.from.x-a.to.x)<.01;o!==s&&t++}return t},Roe=r=>({up:"bottom",down:"top",left:"right",right:"left"})[r]??null,Aoe=({firstEdge:r,firstEdgePort:e,firstDominantDirection:t,lastEdge:n,lastEdgePort:i,lastDominantDirection:a})=>{if(r&&e)return Aoe({lastEdge:{from:r.to,to:r.from},lastEdgePort:e,lastDominantDirection:t}).reverse().map(s=>({from:s.to,to:s.from}));let o=[];if(n&&i){const s={x:n.to.x,y:n.to.y};a==="left"||a==="right"?(s.x=i.position.x,o.push({from:n.to,to:{...s}}),o.push({from:s,to:{...i.position}})):(s.y=i.position.y,o.push({from:n.to,to:{...s}}),o.push({from:s,to:{...i.position}}))}return o=o.filter(s=>E3(s.from,s.to)>.01),o};function XGt(r){try{return[r(),null]}catch(e){return[null,e]}}function WGt(r){let e=0;for(let t=0;t<r.length;t++){const n=r[t];if(n.route_type==="wire"){const i=r[t+1];if(i){const a=i.x-n.x,o=i.y-n.y;e+=Math.sqrt(a*a+o*o)}}else n.route_type==="via"&&(e+=1.6)}return e}var ZGt=r=>{var s,l;const e={left:{x:-.5,y:0},up:{x:.5,y:.5},right:{x:.5,y:0},down:{x:0,y:-.5}}[r.facingDirection],t=(s=r.parent)!=null&&s.config.shouldRenderAsSchematicBox?3:1,n=(l=r.parent)!=null&&l.config.shouldRenderAsSchematicBox&&(r.facingDirection==="left"||r.facingDirection==="right")?3:1,i=e.x,a=e.y,o=r.facingDirection==="up"?.5:0;return{schBoxVertOffset:t,schBoxHorzOffset:n,horzPortDirection:i,vertPortDirectionOffset:a,handleUp:o}},Uk=({port:r,anchorPos:e,schDisplayLabel:t,source_trace_id:n},{db:i})=>{const a=ZGt(r);i.schematic_net_label.insert({anchor_side:"top",center:{x:e.x+a.horzPortDirection*a.schBoxHorzOffset,y:e.y+a.vertPortDirectionOffset*a.schBoxVertOffset},source_net_id:r.source_port_id,text:t,anchor_position:{x:e.x+a.horzPortDirection*a.schBoxHorzOffset,y:e.y+a.vertPortDirectionOffset*a.schBoxVertOffset},symbol_name:"ground_horz"}),i.schematic_trace.insert({edges:[{from:{x:e.x,y:e.y},to:{x:e.x,y:e.y+a.handleUp*a.schBoxVertOffset}},{from:{x:e.x,y:e.y},to:{x:e.x+a.horzPortDirection*a.schBoxHorzOffset,y:e.y+a.vertPortDirectionOffset*a.schBoxVertOffset}}],junctions:[{x:e.x+a.horzPortDirection*a.schBoxHorzOffset,y:e.y+a.vertPortDirectionOffset*a.schBoxVertOffset}],source_trace_id:n})},Poe=({db:r,source_trace_id:e,sameNetOnly:t,differentNetOnly:n})=>{!t&&!n&&(n=!0);const i=r.source_trace.get(e),a=[];for(const o of r.schematic_trace.list()){if(o.source_trace_id===e)continue;const s=r.source_trace.get(o.source_trace_id),l=(s==null?void 0:s.subcircuit_connectivity_map_key)===i.subcircuit_connectivity_map_key;n&&l||t&&!l||a.push(o)}return a},QGt=({edges:r,otherEdges:e})=>{const t=[...r];for(let n=0;n<t.length;n++){if(n>2e3)throw new Error("Over 2000 iterations spent inside createSchematicTraceCrossingSegments, you have triggered an infinite loop, please report this!");const i=t[n],a=Math.abs(i.from.x-i.to.x)<.01?"vertical":i.from.y===i.to.y?"horizontal":"not-orthogonal";if(a==="not-orthogonal")continue;const o=[];for(const S of e){const E=S.from.x===S.to.x?"vertical":S.from.y===S.to.y?"horizontal":"not-orthogonal";if(E==="not-orthogonal"||a===E)continue;if(Nk([i.from,i.to],[S.from,S.to],{lineThickness:.01})){const C=a==="vertical"?i.from.x:S.from.x,O=a==="vertical"?S.from.y:i.from.y,U={x:C,y:O};o.push({otherEdge:S,crossingPoint:U,distanceFromEdgeFrom:E3(i.from,U)})}}if(o.length===0)continue;let s=o[0];for(const S of o)S.distanceFromEdgeFrom<s.distanceFromEdgeFrom&&(s=S);const l=s.crossingPoint,c=.075;if(l.x===i.from.x&&l.y===i.from.y)continue;const u=GUe(i.from,l),f={x:l.x-u.x*c/2,y:l.y-u.y*c/2},p={x:l.x+u.x*c/2,y:l.y+u.y*c/2},v=E3(p,i.to)<c,x=[{from:i.from,to:f},{from:f,to:p,is_crossing:!0},{from:p,to:i.to}];t.splice(n,1,...x),n+=x.length-2,v&&n++}return t},KGt=(r,e)=>{if(r.from.x===r.to.x&&e.from.x===e.to.x)return null;if(r.from.x===r.to.x){const u=r.from.x,f=(e.to.y-e.from.y)/(e.to.x-e.from.x),p=e.from.y-f*e.from.x,v=f*u+p;return u>=Math.min(e.from.x,e.to.x)&&u<=Math.max(e.from.x,e.to.x)&&v>=Math.min(e.from.y,e.to.y)&&v<=Math.max(e.from.y,e.to.y)?{x:u,y:v}:null}if(e.from.x===e.to.x){const u=e.from.x,f=(r.to.y-r.from.y)/(r.to.x-r.from.x),p=r.from.y-f*r.from.x,v=f*u+p;return u>=Math.min(r.from.x,r.to.x)&&u<=Math.max(r.from.x,r.to.x)&&v>=Math.min(r.from.y,r.to.y)&&v<=Math.max(r.from.y,r.to.y)?{x:u,y:v}:null}const t=(r.to.y-r.from.y)/(r.to.x-r.from.x),n=r.from.y-t*r.from.x,i=(e.to.y-e.from.y)/(e.to.x-e.from.x),a=e.from.y-i*e.from.x;if(t===i)return null;const o=(a-n)/(t-i),s=t*o+n,l=o>=Math.min(r.from.x,r.to.x)&&o<=Math.max(r.from.x,r.to.x)&&s>=Math.min(r.from.y,r.to.y)&&s<=Math.max(r.from.y,r.to.y),c=o>=Math.min(e.from.x,e.to.x)&&o<=Math.max(e.from.x,e.to.x)&&s>=Math.min(e.from.y,e.to.y)&&s<=Math.max(e.from.y,e.to.y);return l&&c?{x:o,y:s}:null},JGt=({edges:r,db:e,source_trace_id:t})=>{const n=Poe({db:e,source_trace_id:t,sameNetOnly:!0}).flatMap(i=>i.edges);for(const i of r)for(const a of n){const o=KGt(i,a);if(o)return`${o.x}${o.y}`,[{x:o.x,y:o.y}]}return[]},eqt=(r,{db:e})=>{const t=r.map(n=>{const i=e.source_port.get(n.source_port_id);if(!(i!=null&&i.source_component_id))return null;const a=e.source_component.get(i.source_component_id);return(a==null?void 0:a.ftype)==="simple_capacitor"?a.max_decoupling_trace_length:null}).filter(n=>n!==null);if(t.length!==0)return Math.min(...t)};function tqt(r){var a,o,s,l,c,u,f,p,v;let e=1/0,t=1/0,n=-1/0,i=-1/0;for(const x of r){let S,E,b,C;x.type==="schematic_component"?(S=(a=x.center)==null?void 0:a.x,E=(o=x.center)==null?void 0:o.y,b=(s=x.size)==null?void 0:s.width,C=(l=x.size)==null?void 0:l.height):x.type==="schematic_box"?(S=x.x,E=x.y,b=x.width,C=x.height):x.type==="schematic_port"?(S=(c=x.center)==null?void 0:c.x,E=(u=x.center)==null?void 0:u.y,b=.2,C=.2):x.type==="schematic_text"&&(S=(f=x.position)==null?void 0:f.x,E=(p=x.position)==null?void 0:p.y,b=(((v=x.text)==null?void 0:v.length)??0)*.1,C=.2),typeof S=="number"&&typeof E=="number"&&typeof b=="number"&&typeof C=="number"&&(e=Math.min(e,S-b/2),n=Math.max(n,S+b/2),t=Math.min(t,E-C/2),i=Math.max(i,E+C/2))}return{minX:e,maxX:n,minY:t,maxY:i}}function nqt(r,e={}){const{minX:t,maxX:n,minY:i,maxY:a}=r,o=e.padding??1;if(!isFinite(t)||!isFinite(n)||!isFinite(i)||!isFinite(a))return[];const s=t-o,l=n+o,c=a+o,u=i-o,f=.01;return[{type:"rect",layers:["top"],center:{x:(s+l)/2,y:c},width:l-s,height:f,connectedTo:[]},{type:"rect",layers:["top"],center:{x:(s+l)/2,y:u},width:l-s,height:f,connectedTo:[]},{type:"rect",layers:["top"],center:{x:s,y:(c+u)/2},width:f,height:c-u,connectedTo:[]},{type:"rect",layers:["top"],center:{x:l,y:(c+u)/2},width:f,height:c-u,connectedTo:[]}]}var rqt=r=>{var o;const e=r.root.db,t=r._findConnectedPorts().ports??[],n=new Set(t.map(s=>s.schematic_port_id)),i=[];for(const s of e.toArray()){if(s.type==="schematic_component"){const l=!!s.symbol_name,c=s.size.width>s.size.height?"horz":"vert";i.push({type:"rect",layers:["top"],center:s.center,width:s.size.width+(l&&c==="horz"?-.5:0),height:s.size.height+(l&&c==="vert"?-.5:0),connectedTo:[]})}if(s.type==="schematic_port"){if(n.has(s.schematic_port_id))continue;const l=s.facing_direction?qUe(s.facing_direction):{x:0,y:0};i.push({type:"rect",layers:["top"],center:{x:s.center.x-l.x*.1,y:s.center.y-l.y*.1},width:.1+Math.abs(l.x)*.3,height:.1+Math.abs(l.y)*.3,connectedTo:[]})}s.type==="schematic_text"&&i.push({type:"rect",layers:["top"],center:s.position,width:(((o=s.text)==null?void 0:o.length)??0)*.1,height:.2,connectedTo:[]}),s.type==="schematic_box"&&i.push({type:"rect",layers:["top"],center:{x:s.x,y:s.y},width:s.width,height:s.height,connectedTo:[]})}const a=tqt(e.toArray());return i.push(...nqt(a,{padding:1})),i};function iqt({ports:r,nets:e}){var t,n,i;if(r.length>=2)return`${(t=r[0])==null?void 0:t.selector} to ${(n=r[1])==null?void 0:n.selector}`;if(r.length===1&&e.length===1)return`${(i=r[0])==null?void 0:i.selector} to net.${e[0]._parsedProps.name}`}var aqt=({edges:r,db:e,source_trace_id:t})=>{e.source_trace.get(t);const n=Poe({db:e,source_trace_id:t,differentNetOnly:!0}).flatMap(a=>a.edges),i=a=>{const{from:o,to:s}=a;return o.x===s.x?"vertical":"horizontal"};for(const a of r){const o=i(a),s=()=>n.find(c=>i(c)===o&&Nk([a.from,a.to],[c.from,c.to],{lineThickness:.05}));let l=s();for(;l;)o==="horizontal"?(a.from.y+=.1,a.to.y+=.1):(a.from.x+=.1,a.to.x+=.1),l=s()}},oqt=(r,{db:e})=>{const t=e.pcb_board.list()[0];if(t.outline){const l=t.outline,c=(u,f)=>{let p=!1;for(let v=0,x=f.length-1;v<f.length;x=v++){const S=f[v].x,E=f[v].y,b=f[x].x,C=f[x].y;E>u.y!=C>u.y&&u.x<(b-S)*(u.y-E)/(C-E)+S&&(p=!p)}return p};return r.some(u=>!c(u,l))}const n=t.width,i=t.height,a=t.center.x,o=t.center.y;return r.some(l=>l.x<a-n/2||l.y<o-i/2||l.x>a+n/2||l.y>o+i/2)},Ik=r=>({...r._getGlobalPcbPositionAfterLayout(),layers:r.getAvailablePcbLayers()}),I8=class extends w_{constructor(t){super(t);Je(this,"source_trace_id",null);Je(this,"pcb_trace_id",null);Je(this,"schematic_trace_id",null);Je(this,"_portsRoutedOnPcb");Je(this,"subcircuit_connectivity_map_key",null);Je(this,"_traceConnectionHash",null);this._portsRoutedOnPcb=[]}get config(){return{zodProps:_Ue,componentName:"Trace"}}_getTracePortOrNetSelectorListFromProps(){return"from"in this.props&&"to"in this.props?[typeof this.props.from=="string"?this.props.from:this.props.from.getPortSelector(),typeof this.props.to=="string"?this.props.to:this.props.to.getPortSelector()]:"path"in this.props?this.props.path.map(t=>typeof t=="string"?t:t.getPortSelector()):[]}getTracePortPathSelectors(){return this._getTracePortOrNetSelectorListFromProps().filter(t=>!t.includes("net."))}getTracePathNetSelectors(){return this._getTracePortOrNetSelectorListFromProps().filter(t=>t.includes("net."))}_findConnectedPorts(){const{db:t}=this.root,{_parsedProps:n,parent:i}=this;if(!i)throw new Error("Trace has no parent");const o=this.getTracePortPathSelectors().map(s=>({selector:s,port:this.getSubcircuit().selectOne(s,{type:"port"})??null}));for(const{selector:s,port:l}of o)if(!l){const c=s.replace(/(\> )?[^ ]+$/,""),u=this.getSubcircuit().selectOne(c);u?this.renderError(`Could not find port for selector "${s}" (did you forget to include the pin name?)
|
|
13253
13253
|
searched component ${u.getString()}, which has ports: ${u.children.filter(f=>f.componentName==="Port").map(f=>`${f.getString()}(${f.getNameAndAliases().join(",")})`).join(" & ")}`):this.renderError(`Could not find port for selector "${s}"`)}return o.some(s=>!s.port)?{allPortsFound:!1}:{allPortsFound:!0,portsWithSelectors:o,ports:o.map(({port:s})=>s)}}_findConnectedNets(){const t=this.getTracePathNetSelectors().map(i=>({selector:i,net:this.getSubcircuit().selectOne(i,{type:"net"})})),n=t.filter(i=>!i.net);return n.length>0&&this.renderError(`Could not find net for selector "${n[0].selector}" inside ${this}`),{netsWithSelectors:t,nets:t.map(i=>i.net)}}_getAllTracesConnectedToSameNet(){const t=this.getSubcircuit().selectAll("trace"),n=this._findConnectedNets().nets,i=this._findConnectedPorts().ports??[];return t.filter(a=>{if(a===this)return!1;const o=a._findConnectedNets().nets,s=a._findConnectedPorts().ports??[];return o.some(l=>n.includes(l))||s.some(l=>i.includes(l))})}_isExplicitlyConnectedToPort(t){const{allPortsFound:n,portsWithSelectors:i}=this._findConnectedPorts();return n?i.map(o=>o.port).includes(t):!1}_isExplicitlyConnectedToNet(t){return this._findConnectedNets().nets.includes(t)}doInitialCreateNetsFromProps(){nIe(this,this.getTracePathNetSelectors())}_computeTraceConnectionHash(){const{allPortsFound:t,ports:n}=this._findConnectedPorts();return!t||!n?null:[...n].sort((o,s)=>(o.pcb_port_id||"").localeCompare(s.pcb_port_id||"")).map(o=>o.pcb_port_id).join(",")}doInitialSourceTraceRender(){var p;const{db:t}=this.root,{_parsedProps:n,parent:i}=this;if(!i){this.renderError("Trace has no parent");return}const{allPortsFound:a,portsWithSelectors:o}=this._findConnectedPorts();if(!a)return;this._traceConnectionHash=this._computeTraceConnectionHash();const l=t.source_trace.list().find(v=>v.subcircuit_connectivity_map_key===this.subcircuit_connectivity_map_key&&v.connected_source_port_ids.sort().join(",")===this._traceConnectionHash);if(l){this.source_trace_id=l.source_trace_id;return}const c=this._findConnectedNets().nets,u=iqt({ports:o,nets:c}),f=t.source_trace.insert({connected_source_port_ids:o.map(v=>v.port.source_port_id),connected_source_net_ids:c.map(v=>v.source_net_id),subcircuit_id:(p=this.getSubcircuit())==null?void 0:p.subcircuit_id,max_length:eqt(o.map(v=>v.port),{db:t})??n.maxLength,display_name:u,min_trace_thickness:n.thickness});this.source_trace_id=f.source_trace_id}_insertErrorIfTraceIsOutsideBoard(t,n){const{db:i}=this.root;oqt(t,{db:i})&&i.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:this.source_trace_id,message:`Trace ${this.getString()} routed outside the board boundaries.`,pcb_trace_id:this.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:n.map(o=>o.pcb_port_id)})}doInitialPcbTraceRender(){var te,J,fe,he;if((te=this.root)!=null&&te.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n,parent:i}=this,a=this.getSubcircuit();if(!i)throw new Error("Trace has no parent");if(a._parsedProps.routingDisabled)return;const o=(J=a._parsedProps.pcbRouteCache)==null?void 0:J.pcbTraces;if(o){const ve=t.pcb_trace.insert({route:o.flatMap(Te=>Te.route),source_trace_id:this.source_trace_id,subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((fe=this.getGroup())==null?void 0:fe.pcb_group_id)??void 0});this.pcb_trace_id=ve.pcb_trace_id;return}if(!a._shouldUseTraceByTraceRouting())return;const{allPortsFound:s,ports:l}=this._findConnectedPorts();if(!s)return;const c=[];for(const ve of l)ve._hasMatchedPcbPrimitive()||c.push(ve);if(c.length>0){t.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:this.source_trace_id,message:`Some ports did not have a matching PCB primitive (e.g. a pad or plated hole), this can happen if a footprint is missing. As a result, ${this} wasn't routed. Missing ports: ${c.map(ve=>ve.getString()).join(", ")}`,pcb_trace_id:this.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:c.map(ve=>ve.pcb_port_id).filter(Boolean)});return}const u=this._findConnectedNets().netsWithSelectors;if(l.length===0&&u.length===2){this.renderError("Trace connects two nets, we haven't implemented a way to route this yet");return}else if(l.length===1&&u.length===1){const ve=l[0],Pe=u[0].net.getAllConnectedPorts().filter(Ce=>Ce!==ve);if(Pe.length===0){console.log("Nothing to connect this port to, the net is empty. TODO should emit a warning!");return}const Ee=$Gt(ve,Pe);l.push(Ee)}else if(l.length>1&&u.length>=1){this.renderError("Trace has more than one port and one or more nets, we don't currently support this type of complex trace routing");return}const f=l.flatMap(ve=>ve.matchedComponents.filter(Te=>Te.componentName==="TraceHint")),p=(this._parsedProps.pcbRouteHints??[]).concat(f.flatMap(ve=>ve.getPcbRouteHints()));if(l.length>2){this.renderError(`Trace has more than two ports (${l.map(ve=>ve.getString()).join(", ")}), routing between more than two ports for a single trace is not implemented`);return}if(this.getSubcircuit().selectAll("trace").filter(ve=>ve.renderPhaseStates.PcbTraceRender.initialized).some(ve=>ve._portsRoutedOnPcb.length===l.length&&ve._portsRoutedOnPcb.every(Te=>l.includes(Te))))return;let S=[];p.length===0?S=[Ik(l[0]),Ik(l[1])]:S=[Ik(l[0]),...p,Ik(l[1])];const E=zk(S),b=k3(this.root.db.toArray()),[C,O]=XGt(()=>M6(this.root.db.toArray()));if(O){this.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:this.pcb_trace_id,message:`Error getting obstacles for autorouting: ${O.message}`,source_trace_id:this.source_trace_id,center:{x:0,y:0},pcb_port_ids:l.map(ve=>ve.pcb_port_id),pcb_trace_id:this.pcb_trace_id,pcb_component_ids:[]});return}for(const ve of C)if(ve.connectedTo.length>0){const Pe=b.getNetConnectedToId(ve.connectedTo[0]);Pe&&ve.connectedTo.push(Pe)}let U=[];if(E.length===0)U=S;else{const ve=E[0].layer_path;U=S.map((Te,Pe)=>Te.via?{...Te,via_to_layer:ve[Pe]}:{...Te,layers:[ve[Pe]]})}U[0].pcb_port_id=l[0].pcb_port_id,U[U.length-1].pcb_port_id=l[1].pcb_port_id;const q=[];for(const[ve,Te]of eIe(U)){const Pe="via_to_layer"in ve?ve.via_to_layer:null,Ee=2,Ce="layers"in ve&&ve.layers.length===1?ve.layers[0]:Pe??"top",be="layers"in Te&&Te.layers.length===1?Te.layers[0]:Pe??"top",Oe="pcb_port_id"in ve?ve.pcb_port_id:null,Ue="pcb_port_id"in Te?Te.pcb_port_id:null,Ie=this.getSubcircuit()._parsedProps.minTraceWidth??.16,ke=new T6({OBSTACLE_MARGIN:Ie*2,isRemovePathLoopsEnabled:!0,optimizeWithGoalBoxes:!!(Oe&&Ue),connMap:b,input:{obstacles:C,minTraceWidth:Ie,connections:[{name:this.source_trace_id,pointsToConnect:[{...ve,layer:Ce,pcb_port_id:Oe},{...Te,layer:be,pcb_port_id:Ue}]}],layerCount:2,bounds:{minX:Math.min(ve.x,Te.x)-Ee,maxX:Math.max(ve.x,Te.x)+Ee,minY:Math.min(ve.y,Te.y)-Ee,maxY:Math.max(ve.y,Te.y)+Ee}}});let ot=null;try{ot=ke.solveAndMapToTraces()}catch(Et){this.renderError({type:"pcb_trace_error",pcb_trace_error_id:this.source_trace_id,error_type:"pcb_trace_error",message:`error solving route: ${Et.message}`,source_trace_id:this.pcb_trace_id,center:{x:(ve.x+Te.x)/2,y:(ve.y+Te.y)/2},pcb_port_ids:l.map(Ot=>Ot.pcb_port_id),pcb_trace_id:this.pcb_trace_id,pcb_component_ids:l.map(Ot=>Ot.pcb_component_id)})}if(!ot)return;if(ot.length===0){this.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:this.pcb_trace_id,message:`Could not find a route for ${this}`,source_trace_id:this.source_trace_id,center:{x:(ve.x+Te.x)/2,y:(ve.y+Te.y)/2},pcb_port_ids:l.map(Et=>Et.pcb_port_id),pcb_trace_id:this.pcb_trace_id,pcb_component_ids:l.map(Et=>Et.pcb_component_id)});return}const[nt]=ot;Pe&&(nt.route=nt.route.map(Et=>(Et.route_type==="wire"&&!Et.layer&&(Et.layer=Pe),Et))),Oe&&nt.route[0].route_type==="wire"&&(nt.route[0].start_pcb_port_id=Oe);const gt=nt.route[nt.route.length-1];Ue&>.route_type==="wire"&&(gt.end_pcb_port_id=Ue),q.push(nt.route)}const Y=GGt(q),Q=WGt(Y),K=t.pcb_trace.insert({route:Y,source_trace_id:this.source_trace_id,subcircuit_id:(he=this.getSubcircuit())==null?void 0:he.subcircuit_id,trace_length:Q});this._portsRoutedOnPcb=l,this.pcb_trace_id=K.pcb_trace_id;for(const ve of Y)ve.route_type==="via"&&t.pcb_via.insert({pcb_trace_id:K.pcb_trace_id,x:ve.x,y:ve.y,hole_diameter:.3,outer_diameter:.6,layers:[ve.from_layer,ve.to_layer],from_layer:ve.from_layer,to_layer:ve.to_layer});this._insertErrorIfTraceIsOutsideBoard(Y,l)}_doInitialSchematicTraceRenderWithDisplayLabel(){var q,Y,Q,K;if((q=this.root)!=null&&q.schematicDisabled)return;const{db:t}=this.root,{_parsedProps:n,parent:i}=this;if(!i)throw new Error("Trace has no parent");const{allPortsFound:a,portsWithSelectors:o}=this._findConnectedPorts();if(!a)return;const s=o.map(({port:te})=>({port:te,position:te._getGlobalSchematicPositionAfterLayout(),schematic_port_id:te.schematic_port_id,facingDirection:te.facingDirection}));if(s.length<2)throw new Error("Expected at least two ports in portsWithPosition.");let l,c;const u=s[0].position,f=s[0].port;if("path"in this.props){if(this.props.path.length!==2)throw new Error("Invalid 'path': Must contain exactly two elements.");[l,c]=this.props.path}else{if(!("from"in this.props&&"to"in this.props))throw new Error("Missing 'from' or 'to' properties in props.");l=this.props.from,c=this.props.to}if(!f.source_port_id)throw new Error(`Missing source_port_id for the 'from' port (${l}).`);const p=s[1].position,v=s[1].port;if(!v.source_port_id)throw new Error(`Missing source_port_id for the 'to' port (${c}).`);const x=t.schematic_net_label.list().find(te=>te.source_net_id===f.source_port_id),S=t.schematic_net_label.list().find(te=>te.source_net_id===v.source_port_id),[E,b]=o.map(({port:te})=>te),O=((Y=E.parent)==null?void 0:Y.config.shouldRenderAsSchematicBox)?`${(Q=E==null?void 0:E.parent)==null?void 0:Q.props.name}_${E==null?void 0:E.props.name}`:`${(K=b==null?void 0:b.parent)==null?void 0:K.props.name}_${b==null?void 0:b.props.name}`,U=this.props.schDisplayLabel??O;if(x&&x.text!==U&&(x.text=`${U} / ${x.text}`),S&&(S==null?void 0:S.text)!==U&&(S.text=`${U} / ${S.text}`),U!=null&&U.toLocaleLowerCase().includes("gnd")||U!=null&&U.toLocaleLowerCase().includes("ground")){!x&&!S?(Uk({port:f,anchorPos:u,schDisplayLabel:this.props.schDisplayLabel,source_trace_id:this.source_trace_id},{db:t}),Uk({port:v,anchorPos:p,schDisplayLabel:this.props.schDisplayLabel,source_trace_id:this.source_trace_id},{db:t})):x?S||Uk({port:v,anchorPos:p,schDisplayLabel:this.props.schDisplayLabel,source_trace_id:this.source_trace_id},{db:t}):Uk({port:f,anchorPos:u,schDisplayLabel:this.props.schDisplayLabel,source_trace_id:this.source_trace_id},{db:t});return}S||t.schematic_net_label.insert({text:this.props.schDisplayLabel??O,source_net_id:v.source_port_id,anchor_position:p,center:p,anchor_side:Roe(v.facingDirection)??"bottom"}),x||t.schematic_net_label.insert({text:this.props.schDisplayLabel??O,source_net_id:f.source_port_id,anchor_position:u,center:u,anchor_side:Roe(f.facingDirection)??"bottom"})}_isSymbolToChipConnection(){const{allPortsFound:t,ports:n}=this._findConnectedPorts();if(!t||n.length!==2)return!1;const[i,a]=n;if(!(i!=null&&i.parent)||!(a!=null&&a.parent))return!1;const o=i.parent.config.shouldRenderAsSchematicBox,s=a.parent.config.shouldRenderAsSchematicBox;return o&&!s||!o&&s}_isSymbolToSymbolConnection(){const{allPortsFound:t,ports:n}=this._findConnectedPorts();if(!t||n.length!==2)return!1;const[i,a]=n;if(!(i!=null&&i.parent)||!(a!=null&&a.parent))return!1;const o=!i.parent.config.shouldRenderAsSchematicBox,s=!a.parent.config.shouldRenderAsSchematicBox;return o&&s}_isChipToChipConnection(){const{allPortsFound:t,ports:n}=this._findConnectedPorts();if(!t||n.length!==2)return!1;const[i,a]=n;if(!(i!=null&&i.parent)||!(a!=null&&a.parent))return!1;const o=i.parent.config.shouldRenderAsSchematicBox,s=a.parent.config.shouldRenderAsSchematicBox;return o&&s}doInitialSchematicTraceRender(){var Ce,be;if((Ce=this.root)!=null&&Ce.schematicDisabled)return;const{db:t}=this.root,{_parsedProps:n,parent:i}=this;if(!i)throw new Error("Trace has no parent");const{allPortsFound:a,portsWithSelectors:o}=this._findConnectedPorts(),{netsWithSelectors:s}=this._findConnectedNets();if(!a)return;const c=o.map(Oe=>Oe.port.schematic_port_id).sort().join(","),u=(be=this.root)==null?void 0:be._getBoard();if(u!=null&&u._connectedSchematicPortPairs&&u._connectedSchematicPortPairs.has(c))return;if(this.props.schDisplayLabel&&("from"in this.props&&"to"in this.props||"path"in this.props)){this._doInitialSchematicTraceRenderWithDisplayLabel();return}const f={name:this.source_trace_id,pointsToConnect:[]},p=rqt(this),v=o.map(({port:Oe})=>({port:Oe,position:Oe._getGlobalSchematicPositionAfterLayout(),schematic_port_id:Oe.schematic_port_id??void 0,facingDirection:Oe.facingDirection}));if(v.length===1&&s.length===1){const Oe=s[0].net,{port:Ue,position:Ie}=v[0];t.schematic_net_label.insert({text:Oe._parsedProps.name,source_net_id:Oe.source_net_id,anchor_position:Ie,center:Ie,anchor_side:Roe(Ue.facingDirection)??"bottom"});return}if(v.length<2)return;f.pointsToConnect=v.map(({position:Oe})=>({...Oe,layer:"top"}));const S=VGt(p),E=2,b={minTraceWidth:.1,obstacles:p,connections:[f],bounds:{minX:S.minX-E,maxX:S.maxX+E,minY:S.minY-E,maxY:S.maxY+E},layerCount:1};let C=T6,O=!1;this.getSubcircuit().props._schDirectLineRoutingEnabled&&(C=uIe,O=!0);let q=new C({input:b,MAX_ITERATIONS:100,OBSTACLE_MARGIN:.1,isRemovePathLoopsEnabled:!0,isShortenPathWithShortcutsEnabled:!0,marginsWithCosts:[{margin:1,enterCost:0,travelCostFactor:1},{margin:.3,enterCost:0,travelCostFactor:1},{margin:.2,enterCost:0,travelCostFactor:2},{margin:.1,enterCost:0,travelCostFactor:3}]}).solveAndMapToTraces();if(q.length===0){if(this._isSymbolToChipConnection()||this._isSymbolToSymbolConnection()||this._isChipToChipConnection()){this._doInitialSchematicTraceRenderWithDisplayLabel();return}q=new uIe({input:b}).solveAndMapToTraces(),O=!0}const[{route:Y}]=q;let Q=[];for(let Oe=0;Oe<Y.length-1;Oe++)Q.push({from:Y[Oe],to:Y[Oe+1]});const K=this.source_trace_id;let te=[];if(!O){aqt({edges:Q,db:t,source_trace_id:K});const Oe=Poe({db:t,source_trace_id:K,differentNetOnly:!0}).flatMap(Ue=>Ue.edges);Q=QGt({edges:Q,otherEdges:Oe}),te=JGt({edges:Q,db:t,source_trace_id:this.source_trace_id})}const J=Q[Q.length-1],fe=v[v.length-1],he=dIe(J);Q.push(...Aoe({lastEdge:J,lastEdgePort:fe,lastDominantDirection:he}));const ve=Q[0],Te=v[0],Pe=dIe(ve);if(Q.unshift(...Aoe({firstEdge:ve,firstEdgePort:Te,firstDominantDirection:Pe})),!this.source_trace_id)throw new Error("Missing source_trace_id for schematic trace insertion.");if(this.getSubcircuit()._parsedProps.schTraceAutoLabelEnabled&&YGt(te,Q)>=5&&(this._isSymbolToChipConnection()||this._isSymbolToSymbolConnection()||this._isChipToChipConnection())){this._doInitialSchematicTraceRenderWithDisplayLabel();return}const Ee=t.schematic_trace.insert({source_trace_id:this.source_trace_id,edges:Q,junctions:te});this.schematic_trace_id=Ee.schematic_trace_id,u!=null&&u._connectedSchematicPortPairs&&u._connectedSchematicPortPairs.add(c)}},sqt=E1("tscircuit:core"),lqt=k.object({x:p5,y:p5,z:p5}),Xx=class extends w_{constructor(t){super(t);Je(this,"reactSubtrees",[]);Je(this,"_impliedFootprint");Je(this,"isPrimitiveContainer",!0);Je(this,"_asyncSupplierPartNumbers");Je(this,"pcb_missing_footprint_error_id");this._addChildrenFromStringFootprint(),this.initPorts()}get defaultInternallyConnectedPinNames(){return[]}get internallyConnectedPinNames(){return this._parsedProps.internallyConnectedPins??this.defaultInternallyConnectedPinNames}initPorts(t={}){var s,l,c,u,f,p,v,x,S,E;if((s=this.root)!=null&&s.schematicDisabled)return;const{config:n}=this,i=[],a=this._getSchematicPortArrangement();if(a&&!this._parsedProps.pinLabels){for(const O in a){const U=a[O].pins;if(Array.isArray(U))for(const q of U){const Y=cA(q,this._parsedProps.pinLabels);i.push(new q4({pinNumber:Y,aliases:((l=t.additionalAliases)==null?void 0:l[`pin${Y}`])??[]},{originDescription:`schPortArrangement:${O}`}))}}const b=["left","right","top","bottom"];let C=1;for(const O of b){const U=a[`${O}Size`];for(let q=0;q<U;q++)i.push(new q4({pinNumber:C++,aliases:((c=t.additionalAliases)==null?void 0:c[`pin${C}`])??[]},{originDescription:`schPortArrangement:${O}`}))}}const o=this._parsedProps.pinLabels;if(o)for(let[b,C]of Object.entries(o)){b=b.replace("pin","");let O=i.find(Y=>Y._parsedProps.pinNumber===Number(b));const U=Array.isArray(C)?C[0]:C,q=Array.isArray(C)?C.slice(1):[];O?(O.externallyAddedAliases.push(U,...q),O.props.name=U):(O=new q4({pinNumber:parseInt(b),name:U,aliases:[...q,...((u=t.additionalAliases)==null?void 0:u[`pin${parseInt(b)}`])??[]]},{originDescription:`pinLabels:pin${b}`}),i.push(O))}if(n.schematicSymbolName){const b=u_[this._getSchematicSymbolNameOrThrow()];if(!b)return;for(const C of b.ports){const O=lIe(C.labels);if(!O)continue;const U=i.find(q=>q._parsedProps.pinNumber===Number(O));if(U)U.schematicSymbolPortDef=C;else{const q=uA(C.labels.concat(((f=t.additionalAliases)==null?void 0:f[`pin${O}`])??[]));q&&(q.originDescription=`schematicSymbol:labels[0]:${C.labels[0]}`,q.schematicSymbolPortDef=C,i.push(q))}}this.addAll(i)}if(!this._getSchematicPortArrangement()){const b=this.getPortsFromFootprint(t);for(const C of b)i.some(O=>O.isMatchingAnyOf(C.getNameAndAliases()))||i.push(C)}for(let b=1;b<=(t.pinCount??this._getPinCount());b++){if(!a||i.find(O=>O._parsedProps.pinNumber===b))continue;let C=[...((p=a.leftSide)==null?void 0:p.pins)??[],...((v=a.rightSide)==null?void 0:v.pins)??[],...((x=a.topSide)==null?void 0:x.pins)??[],...((S=a.bottomSide)==null?void 0:S.pins)??[]].map(O=>cA(O,this._parsedProps.pinLabels));["leftSize","rightSize","topSize","bottomSize","leftPinCount","rightPinCount","topPinCount","bottomPinCount"].some(O=>O in a)&&(C=Array.from({length:this._getPinCount()},(O,U)=>U+1)),C.includes(b)&&i.push(new q4({pinNumber:b,aliases:((E=t.additionalAliases)==null?void 0:E[`pin${b}`])??[]},{originDescription:`notOtherwiseAddedButDeducedFromPinCount:${b}`}))}i.length>0&&this.addAll(i)}_getImpliedFootprintString(){return null}_addChildrenFromStringFootprint(){var o;const{name:t,pcbRotation:n,pinLabels:i}=this.props;let{footprint:a}=this.props;if(a??(a=(o=this._getImpliedFootprintString)==null?void 0:o.call(this)),!!a&&typeof a=="string"){const s=y6.string(a).soup(),l=DGt({componentName:t,componentRotation:n,footprint:a,pinLabels:i},s);this.addAll(l)}}get portMap(){return new Proxy({},{get:(t,n)=>{const i=this.children.find(a=>a.componentName==="Port"&&a.isMatchingNameOrAlias(n));if(!i)throw new Error(`There was an issue finding the port "${n.toString()}" inside of a ${this.componentName} component with name: "${this.props.name}". This is a bug in @tscircuit/core`);return i}})}getInstanceForReactElement(t){for(const n of this.reactSubtrees)if(n.element===t)return n.component;return null}doInitialSourceRender(){const t=this.config.sourceFtype;if(!t)return;const{db:n}=this.root,{_parsedProps:i}=this,a=n.source_component.insert({ftype:t,name:i.name,manufacturer_part_number:i.manufacturerPartNumber??i.mfn,supplier_part_numbers:i.supplierPartNumbers});this.source_component_id=a.source_component_id}doInitialSchematicComponentRender(){var a,o,s;if((a=this.root)!=null&&a.schematicDisabled)return;const{db:t}=this.root,{schematicSymbolName:n}=this.config;n?this._doInitialSchematicComponentRenderWithSymbol():this._getSchematicBoxDimensions()&&this._doInitialSchematicComponentRenderWithSchematicBoxDimensions();const i=(o=this.getSubcircuit())==null?void 0:o._getSchematicManualPlacementForComponent(this);if(this.schematic_component_id&&(this.props.schX!==void 0||this.props.schY!==void 0)&&i){if(!this.schematic_component_id)return;const l=PP.parse({type:"schematic_manual_edit_conflict_warning",schematic_manual_edit_conflict_warning_id:`schematic_manual_edit_conflict_${this.source_component_id}`,message:`${this.getString()} has both manual placement and prop coordinates. schX and schY will be used. Remove schX/schY or clear the manual placement.`,schematic_component_id:this.schematic_component_id,source_component_id:this.source_component_id,subcircuit_id:(s=this.getSubcircuit())==null?void 0:s.subcircuit_id});t.schematic_manual_edit_conflict_warning.insert(l)}}_getSchematicSymbolDisplayValue(){}_getInternallyConnectedPins(){if(this.internallyConnectedPinNames.length===0)return[];const t=[];for(const n of this.internallyConnectedPinNames){const i=[];for(const a of n)i.push(this.portMap[a]);t.push(i)}return t}_doInitialSchematicComponentRenderWithSymbol(){var s;if((s=this.root)!=null&&s.schematicDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,i=this._getSchematicSymbolNameOrThrow(),a=u_[i],o=this._getGlobalSchematicPositionBeforeLayout();if(a){const l=t.schematic_component.insert({center:o,size:a.size,source_component_id:this.source_component_id,symbol_name:i,symbol_display_value:this._getSchematicSymbolDisplayValue()});this.schematic_component_id=l.schematic_component_id}}_doInitialSchematicComponentRenderWithSchematicBoxDimensions(){var p;if((p=this.root)!=null&&p.schematicDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,i=this._getSchematicBoxDimensions(),a={};if(Array.isArray(n.pinLabels))n.pinLabels.forEach((v,x)=>{a[String(x+1)]=v});else for(const[v,x]of Object.entries(n.pinLabels??{}))a[v]=Array.isArray(x)?x[0]:x;const o=this._getGlobalSchematicPositionBeforeLayout(),s=this._getSchematicPortArrangement(),l=t.schematic_component.insert({center:o,rotation:n.schRotation??0,size:i.getSize(),port_arrangement:RGt(s),pin_spacing:n.schPinSpacing??.2,pin_styles:CGt(n.schPinStyle,n.pinLabels),port_labels:a,source_component_id:this.source_component_id}),c=(s==null?void 0:s.topSide)!==void 0||(s==null?void 0:s.bottomSide)!==void 0,u=i==null?void 0:i.getSize().width,f=i==null?void 0:i.getSize().height;t.schematic_text.insert({text:n.manufacturerPartNumber??"",schematic_component_id:l.schematic_component_id,anchor:"left",rotation:0,position:{x:c?o.x+(u??0)/2+.1:o.x-(u??0)/2,y:c?o.y+(f??0)/2+.35:o.y-(f??0)/2-.13},color:"#006464",font_size:.05}),t.schematic_text.insert({text:n.name??"",schematic_component_id:l.schematic_component_id,anchor:"left",rotation:0,position:{x:c?o.x+(u??0)/2+.1:o.x-(u??0)/2,y:c?o.y+(f??0)/2+.55:o.y+(f??0)/2+.13},color:"#006464",font_size:.05}),this.schematic_component_id=l.schematic_component_id}doInitialPcbComponentRender(){var s;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,i=this.getSubcircuit(),a=t.pcb_component.insert({center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,layer:n.layer??"top",rotation:n.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:i.subcircuit_id??void 0});if(!n.footprint&&!this.isGroup){const l=t.pcb_missing_footprint_error.insert({message:`No footprint found for component: ${this.getString()}`,source_component_id:`${this.source_component_id}`,error_type:"pcb_missing_footprint_error"});this.pcb_missing_footprint_error_id=l.pcb_missing_footprint_error_id}this.pcb_component_id=a.pcb_component_id;const o=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if((this.props.pcbX!==void 0||this.props.pcbY!==void 0)&&o){const l=DP.parse({type:"pcb_manual_edit_conflict_warning",pcb_manual_edit_conflict_warning_id:`pcb_manual_edit_conflict_${this.source_component_id}`,message:`${this.getString()} has both manual placement and prop coordinates. pcbX and pcbY will be used. Remove pcbX/pcbY or clear the manual placement.`,pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,subcircuit_id:i.subcircuit_id??void 0});t.pcb_manual_edit_conflict_warning.insert(l)}}doInitialPcbComponentSizeCalculation(){var o;if((o=this.root)!=null&&o.pcbDisabled||!this.pcb_component_id)return;const{db:t}=this.root,{_parsedProps:n}=this,i=sIe(this.children);if(i.width===0||i.height===0)return;const a={x:(i.minX+i.maxX)/2,y:(i.minY+i.maxY)/2};t.pcb_component.update(this.pcb_component_id,{center:a,width:i.width,height:i.height})}_renderReactSubtree(t){return{element:t,component:MGt(t)}}doInitialInitializePortsFromChildren(){this.initPorts()}doInitialReactSubtreesRender(){if(mt.isValidElement(this.props.footprint)){if(this.reactSubtrees.some(n=>n.element===this.props.footprint))return;const t=this._renderReactSubtree(this.props.footprint);this.reactSubtrees.push(t),this.add(t.component)}}_hasExistingPortExactly(t){return this.children.filter(i=>i.componentName==="Port").some(i=>{const a=t.getNameAndAliases(),o=i.getNameAndAliases();return a.length===o.length&&a.every(s=>o.includes(s))})}add(t){let n;if(mt.isValidElement(t)){const i=this._renderReactSubtree(t);this.reactSubtrees.push(i),n=i.component}else n=t;if(n.componentName==="Port"){if(this._hasExistingPortExactly(n))return;const a=this.children.filter(o=>o.componentName==="Port").find(o=>o.isMatchingAnyOf(n.getNameAndAliases()));a&&sqt(`Similar ports added. Port 1: ${a}, Port 2: ${n}`)}super.add(n)}getPortsFromFootprint(t){let{footprint:n}=this.props;if((!n||mt.isValidElement(n))&&(n=this.children.find(a=>a.componentName==="Footprint")),typeof n=="string"){const a=y6.string(n).soup(),o=[];for(const s of a)if("port_hints"in s&&s.port_hints){const l=uA(s.port_hints,t);if(!l)continue;l.originDescription=`footprint:string:${n}:port_hints[0]:${s.port_hints[0]}`,o.push(l)}return o}if(!mt.isValidElement(n)&&n&&n.componentName==="Footprint"){const a=n;let o=1;const s=[];for(const l of a.children){if(!l.props.portHints)continue;let c=l.props.portHints;c.some(p=>p.startsWith("pin"))||(c=[...c,`pin${o}`]),o++;const f=uA(c);f&&(f.originDescription=`footprint:${n}`,s.push(f))}return s}const i=[];if(!n){for(const a of this.children)if(a.props.portHints&&a.isPcbPrimitive){const o=uA(a.props.portHints);o&&i.push(o)}}return i}getPortsFromSchematicSymbol(){var a;if((a=this.root)!=null&&a.schematicDisabled)return[];const{config:t}=this;if(!t.schematicSymbolName)return[];const n=u_[t.schematicSymbolName];if(!n)return[];const i=[];for(const o of n.ports){const s=uA(o.labels);s&&(s.schematicSymbolPortDef=o,i.push(s))}return i}doInitialCreateNetsFromProps(){this._createNetsFromProps(this._getNetsFromConnectionsProp())}_getNetsFromConnectionsProp(){const{_parsedProps:t}=this,n=[];if(t.connections)for(const[i,a]of Object.entries(t.connections)){const o=Array.isArray(a)?a:[a];for(const s of o)n.push(s)}return n}_createNetsFromProps(t){nIe(this,t)}_getPcbCircuitJsonBounds(){const{db:t}=this.root;if(!this.pcb_component_id)return super._getPcbCircuitJsonBounds();const n=t.pcb_component.get(this.pcb_component_id);return{center:{x:n.center.x,y:n.center.y},bounds:{left:n.center.x-n.width/2,top:n.center.y-n.height/2,right:n.center.x+n.width/2,bottom:n.center.y+n.height/2},width:n.width,height:n.height}}_getPinCountFromSchematicPortArrangement(){const t=this._getSchematicPortArrangement();if(!t)return 0;if(!cIe(t))return(t.leftSize??t.leftPinCount??0)+(t.rightSize??t.rightPinCount??0)+(t.topSize??t.topPinCount??0)+(t.bottomSize??t.bottomPinCount??0);const{leftSide:i,rightSide:a,topSide:o,bottomSide:s}=t;return Math.max(...(i==null?void 0:i.pins)??[],...(a==null?void 0:a.pins)??[],...(o==null?void 0:o.pins)??[],...(s==null?void 0:s.pins)??[])}_getPinCount(){return this._getSchematicPortArrangement()?this._getPinCountFromSchematicPortArrangement():this.getPortsFromFootprint().length}_getSchematicPortArrangement(){return this._parsedProps.schPinArrangement??this._parsedProps.schPortArrangement}_getSchematicBoxDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;const{_parsedProps:t}=this,n=this._getPinCount(),i=t.schPinSpacing??.2;return FGt({schWidth:t.schWidth,schHeight:t.schHeight,schPinSpacing:i,numericSchPinStyle:jGt(t.schPinStyle,t.pinLabels),pinCount:n,schPortArrangement:this._getSchematicPortArrangement(),pinLabels:t.pinLabels})}doInitialCadModelRender(){var u;const{db:t}=this.root,{boardThickness:n=0}=((u=this.root)==null?void 0:u._getBoard())??{},i=this._parsedProps.cadModel;if(!this.pcb_component_id||!i&&!this.props.footprint)return;const a=this._getPcbCircuitJsonBounds(),o=t.pcb_component.get(this.pcb_component_id);if(typeof i=="string")throw new Error("String cadModel not yet implemented");const s=lqt.parse({x:0,y:0,z:typeof(i==null?void 0:i.rotationOffset)=="number"?i.rotationOffset:0,...typeof(i==null?void 0:i.rotationOffset)=="object"?i.rotationOffset??{}:{}}),l=lw.parse({x:0,y:0,z:0,...typeof(i==null?void 0:i.positionOffset)=="object"?i.positionOffset:{}}),c=this.props.layer==="bottom"?"bottom":"top";t.cad_component.insert({position:{x:a.center.x+l.x,y:a.center.y+l.y,z:(c==="bottom"?-n/2:n/2)+l.z},rotation:{x:s.x,y:(c==="top"?0:180)+s.y,z:((o==null?void 0:o.rotation)??0)+(c==="bottom"?180:0)+s.z},pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,model_stl_url:"stlUrl"in(i??{})?this._addCachebustToModelUrl(i.stlUrl):void 0,model_obj_url:"objUrl"in(i??{})?this._addCachebustToModelUrl(i.objUrl):void 0,model_jscad:"jscad"in(i??{})?i.jscad:void 0,footprinter_string:typeof this.props.footprint=="string"&&!i?this.props.footprint:void 0})}_addCachebustToModelUrl(t){var i;if(!t||!t.includes("modelcdn.tscircuit.com"))return t;const n=((i=this.root)==null?void 0:i.getClientOrigin())??"";return`${t}${t.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(n)}`}doInitialPartsEngineRender(){const t=this.getInheritedProperty("partsEngine");if(!t)return;const{db:n}=this.root,i=n.source_component.get(this.source_component_id);if(!i||i.supplier_part_numbers)return;let a;this.props.footprint&&typeof this.props.footprint=="string"&&(a=this.props.footprint);const o=t.findPart({sourceComponent:i,footprinterString:a});if(!(o instanceof Promise)){n.source_component.update(this.source_component_id,{supplier_part_numbers:o});return}this._queueAsyncEffect("get-supplier-part-numbers",async()=>{this._asyncSupplierPartNumbers=await o,this._markDirty("PartsEngineRender")})}updatePartsEngineRender(){const{db:t}=this.root,n=t.source_component.get(this.source_component_id);if(n&&!n.supplier_part_numbers&&this._asyncSupplierPartNumbers){t.source_component.update(this.source_component_id,{supplier_part_numbers:this._asyncSupplierPartNumbers});return}}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}_createTracesFromConnectionsProp(){const{_parsedProps:t}=this;if(t.connections)for(const[n,i]of Object.entries(t.connections)){const a=Array.isArray(i)?i:[i];for(const o of a)this.add(new I8({from:`${this.getSubcircuitSelector()} > port.${n}`,to:o}))}}},cqt=class{constructor(e,t={}){Je(this,"input");Je(this,"isRouting",!1);Je(this,"solver");Je(this,"eventHandlers",{complete:[],error:[],progress:[]});Je(this,"cycleCount",0);Je(this,"stepDelay");Je(this,"timeoutId");this.input=e;const{capacityDepth:n,targetMinCapacity:i,stepDelay:a=0}=t;this.solver=new AG(e,{capacityDepth:n,targetMinCapacity:i}),this.stepDelay=a}start(){this.isRouting||(this.isRouting=!0,this.cycleCount=0,this.runCycleAndQueueNextCycle())}runCycleAndQueueNextCycle(){var e;if(this.isRouting)try{if(this.solver.solved||this.solver.failed){this.solver.failed?this.emitEvent({type:"error",error:new Error(this.solver.error||"Routing failed")}):this.emitEvent({type:"complete",traces:this.solver.getOutputSimpleRouteJson().traces||[]}),this.isRouting=!1;return}const t=Date.now(),n=this.solver.iterations;for(;Date.now()-t<250&&!this.solver.failed&&!this.solver.solved;)this.solver.step();const i=(this.solver.iterations-n)/(Date.now()-t)*1e3;this.cycleCount++;const a=((e=this.solver)==null?void 0:e.preview())||void 0,o=this.solver.progress;this.emitEvent({type:"progress",steps:this.cycleCount,iterationsPerSecond:i,progress:o,phase:this.solver.getCurrentPhase(),debugGraphics:a}),this.stepDelay>0?this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),this.stepDelay):this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),0)}catch(t){this.emitEvent({type:"error",error:t instanceof Error?t:new Error(String(t))}),this.isRouting=!1}}stop(){this.isRouting&&(this.isRouting=!1,this.timeoutId!==void 0&&(clearTimeout(this.timeoutId),this.timeoutId=void 0))}on(e,t){e==="complete"?this.eventHandlers.complete.push(t):e==="error"?this.eventHandlers.error.push(t):e==="progress"&&this.eventHandlers.progress.push(t)}emitEvent(e){if(e.type==="complete")for(const t of this.eventHandlers.complete)t(e);else if(e.type==="error")for(const t of this.eventHandlers.error)t(e);else if(e.type==="progress")for(const t of this.eventHandlers.progress)t(e)}solveSync(){if(this.solver.solve(),this.solver.failed)throw new Error(this.solver.error||"Routing failed");return this.solver.getOutputSimpleRouteJson().traces||[]}},pIe=class extends w_{constructor(){super(...arguments);Je(this,"matchedPort",null)}get config(){return{componentName:"TraceHint",zodProps:VUe}}doInitialPortMatching(){const{db:t}=this.root,{_parsedProps:n,parent:i}=this;if(!i)return;if(i.componentName==="Trace"){this.renderError(`Port inference inside trace is not yet supported (${this})`);return}if(!i)throw new Error("TraceHint has no parent");if(!n.for){this.renderError(`TraceHint has no for property (${this})`);return}const a=i.selectOne(n.for,{type:"port"});a||this.renderError(`${this} could not find port for selector "${n.for}"`),this.matchedPort=a,a.registerMatch(this)}getPcbRouteHints(){const{_parsedProps:t}=this,n=t.offset?[t.offset]:t.offsets;if(!n)return[];const i=this._computePcbGlobalTransformBeforeLayout();return n.map(a=>({...Ir(i,a),via:a.via,to_layer:a.to_layer,trace_width:a.trace_width}))}doInitialPcbTraceHintRender(){var i,a,o;if((i=this.root)!=null&&i.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this;t.pcb_trace_hint.insert({pcb_component_id:(a=this.matchedPort)==null?void 0:a.pcb_component_id,pcb_port_id:(o=this.matchedPort)==null?void 0:o.pcb_port_id,route:this.getPcbRouteHints()})}},uqt=(r,e)=>{if(p4(r).pcb_trace_hint.get(e.pcb_trace_hint_id))r=r.map(n=>n.pcb_trace_hint_id===e.pcb_trace_hint_id?{...n,route:e.route}:n);else{const n=p4(r).pcb_port.get(e.pcb_port_id);r=r.filter(i=>!(i.type==="pcb_trace_hint"&&i.pcb_port_id===e.pcb_port_id)).concat([{type:"pcb_trace_hint",pcb_trace_hint_id:e.pcb_trace_hint_id,route:e.route,pcb_port_id:e.pcb_port_id,pcb_component_id:n==null?void 0:n.pcb_component_id}])}return r},fqt=({circuitJson:r,editEvents:e})=>{r=JSON.parse(JSON.stringify(r));for(const t of e)if(t.edit_event_type==="edit_pcb_component_location"){const n=r.find(a=>a.type==="pcb_component"&&a.pcb_component_id===t.pcb_component_id);if((!n||n.center.x!==t.new_center.x||n.center.y!==t.new_center.y)&&t.original_center){const a=Gf(t.new_center.x-t.original_center.x,t.new_center.y-t.original_center.y);r=r.map(o=>o.pcb_component_id!==t.pcb_component_id?o:Hlt(o,a))}}else t.edit_event_type==="edit_schematic_component_location"?r=r.map(n=>n.type==="schematic_component"&&n.schematic_component_id===t.schematic_component_id?{...n,center:t.new_center}:n):t.edit_event_type==="edit_pcb_trace_hint"&&(r=uqt(r,t));return r},dqt=(r,e)=>{const t=r.source_group.list(),n=[],i=a=>{const o=t.filter(s=>s.parent_subcircuit_id===a);for(const s of o)s.subcircuit_id&&(n.push(s.subcircuit_id),i(s.subcircuit_id))};return i(e),n},hIe=({db:r,circuitJson:e,subcircuit_id:t,minTraceWidth:n=.1})=>{if(!r&&e&&(r=p4(e)),!r)throw new Error("db or circuitJson is required");const i=r.pcb_trace_hint.list(),a=t?new Set([t]):null;if(t){const S=dqt(r,t);for(const E of S)a.add(E)}const o=(e??r.toArray()).filter(S=>!t||"subcircuit_id"in S&&a.has(S.subcircuit_id)),s=r.pcb_board.list()[0];r=p4(o);const l=k3(o),c=M6([...r.pcb_component.list(),...r.pcb_smtpad.list(),...r.pcb_plated_hole.list(),...r.pcb_hole.list(),...r.pcb_via.list()].filter(S=>!t||(a==null?void 0:a.has(S.subcircuit_id))),l);for(const S of c){const E=S.connectedTo.flatMap(b=>l.getIdsConnectedToNet(b));S.connectedTo.push(...E)}const u=c.flatMap(S=>[{x:S.center.x-S.width/2,y:S.center.y-S.height/2},{x:S.center.x+S.width/2,y:S.center.y+S.height/2}]);let f;s?f={minX:s.center.x-s.width/2,maxX:s.center.x+s.width/2,minY:s.center.y-s.height/2,maxY:s.center.y+s.height/2}:f={minX:Math.min(...u.map(S=>S.x))-1,maxX:Math.max(...u.map(S=>S.x))+1,minY:Math.min(...u.map(S=>S.y))-1,maxY:Math.max(...u.map(S=>S.y))+1};const p=r.source_trace.list().map(S=>{var Q,K,te;const E=S.connected_source_port_ids.map(J=>{const fe=r.source_port.get(J),he=r.pcb_port.getWhere({source_port_id:J});return{...fe,...he}});if(E.length<2)return null;const[b,C]=E,O=((Q=b.layers)==null?void 0:Q[0])??"top",U=((K=C.layers)==null?void 0:K[0])??"top",q=i.filter(J=>J.pcb_port_id===b.pcb_port_id||J.pcb_port_id===C.pcb_port_id),Y=[];for(const J of q){const fe=r.pcb_port.get(J.pcb_port_id),he=((te=fe==null?void 0:fe.layers)==null?void 0:te[0])??"top";for(const ve of J.route)Y.push({x:ve.x,y:ve.y,layer:he})}return{name:S.source_trace_id??l.getNetConnectedToId(S.source_trace_id)??"",source_trace_id:S.source_trace_id,pointsToConnect:[{x:b.x,y:b.y,layer:O},...Y,{x:C.x,y:C.y,layer:U}]}}).filter(S=>S!==null),v=r.source_net.list().filter(S=>!t||(a==null?void 0:a.has(S.subcircuit_id))),x=[];for(const S of v){const E=r.source_trace.list().filter(b=>{var C;return(C=b.connected_source_net_ids)==null?void 0:C.includes(S.source_net_id)});x.push({name:S.source_net_id??l.getNetConnectedToId(S.source_net_id),pointsToConnect:E.flatMap(b=>r.pcb_port.list().filter(O=>b.connected_source_port_ids.includes(O.source_port_id)).map(O=>{var U;return{x:O.x,y:O.y,layer:((U=O.layers)==null?void 0:U[0])??"top",pcb_port_id:O.pcb_port_id}}))})}return{simpleRouteJson:{bounds:f,obstacles:c,connections:[...p,...x],layerCount:2,minTraceWidth:n},connMap:l}},Noe=class extends Xx{constructor(){super(...arguments);Je(this,"pcb_group_id",null);Je(this,"subcircuit_id",null);Je(this,"_hasStartedAsyncAutorouting",!1);Je(this,"_asyncAutoroutingResult",null)}get config(){return{zodProps:oUe,componentName:"Group"}}doInitialSourceRender(){const{db:t}=this.root,n=t.source_group.insert({name:this._parsedProps.name,is_subcircuit:this.isSubcircuit});this.subcircuit_id=`subcircuit_${n.source_group_id}`,this.source_group_id=n.source_group_id,t.source_group.update(n.source_group_id,{subcircuit_id:this.subcircuit_id})}doInitialSourceParentAttachment(){var i,a,o;const{db:t}=this.root;if(!this.isSubcircuit)return;const n=(o=(a=(i=this.parent)==null?void 0:i.getSubcircuit)==null?void 0:a.call(i))==null?void 0:o.subcircuit_id;n&&t.source_group.update(this.source_group_id,{parent_subcircuit_id:n})}doInitialPcbComponentRender(){var a;if((a=this.root)!=null&&a.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,i=t.pcb_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id,name:this._parsedProps.name,center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,pcb_component_ids:[],source_group_id:this.source_group_id});this.pcb_group_id=i.pcb_group_id}doInitialCreateTraceHintsFromProps(){var o;const{_parsedProps:t}=this,{db:n}=this.root,i=t;if(!this.isSubcircuit)return;const a=(o=i.layout)==null?void 0:o.manual_trace_hints;if(a)for(const s of a)this.add(new pIe({for:s.pcb_port_selector,offsets:s.offsets}))}doInitialSourceAddConnectivityMapKey(){if(!this.isSubcircuit)return;const{db:t}=this.root,n=this.selectAll("trace"),i=new w6({});i.addConnections(n.map(a=>{const o=t.source_trace.get(a.source_trace_id);return o?[o.source_trace_id,...o.connected_source_port_ids,...o.connected_source_net_ids]:null}).filter(a=>a!==null));for(const a of n){if(!a.source_trace_id)continue;const o=i.getNetConnectedToId(a.source_trace_id);if(!o)continue;const{name:s}=this._parsedProps;a.subcircuit_connectivity_map_key=`${s??`unnamedsubcircuit${this._renderId}`}_${o}`,t.source_trace.update(a.source_trace_id,{subcircuit_connectivity_map_key:a.subcircuit_connectivity_map_key})}}_areChildSubcircuitsRouted(){const t=this.selectAll("group").filter(n=>n.isSubcircuit);for(const n of t)if(n._shouldRouteAsync()&&!n._asyncAutoroutingResult)return!1;return!0}_shouldRouteAsync(){const t=this._getAutorouterConfig();return t.groupMode==="sequential-trace"?!1:!!(t.local&&t.groupMode==="subcircuit"||!t.local)}_hasTracesToRoute(){const t=E1("tscircuit:core:_hasTracesToRoute"),n=this.selectAll("trace");return t(`[${this.getString()}] has ${n.length} traces to route`),n.length>0}async _runEffectMakeHttpAutoroutingRequest(){var u,f,p,v;const{db:t}=this.root,n=E1("tscircuit:core:_runEffectMakeHttpAutoroutingRequest");this._parsedProps;const i=this._getAutorouterConfig(),a=i.serverUrl,o=i.serverMode,s=(x,S)=>{var E;return n("fetching",x),S.headers&&(S.headers["Tscircuit-Core-Version"]=(E=this.root)==null?void 0:E.getCoreVersion()),fetch(x,S)},l=this.root.db.toArray().filter(x=>x.type.startsWith("source_")||x.type.startsWith("pcb_"));if(o==="solve-endpoint"){if(((u=this.props.autorouter)==null?void 0:u.inputFormat)==="simplified"){const{autorouting_result:S}=await s(`${a}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_simple_route_json:hIe({db:t,minTraceWidth:((f=this.props.autorouter)==null?void 0:f.minTraceWidth)??.15,subcircuit_id:this.subcircuit_id}).simpleRouteJson,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(E=>E.json());this._asyncAutoroutingResult=S,this._markDirty("PcbTraceRender");return}const{autorouting_result:x}=await s(`${a}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_circuit_json:l,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(S=>S.json());this._asyncAutoroutingResult=x,this._markDirty("PcbTraceRender");return}const{autorouting_job:c}=await s(`${a}/autorouting/jobs/create`,{method:"POST",body:JSON.stringify({input_circuit_json:l,provider:"freerouting",autostart:!0,display_name:(p=this.root)==null?void 0:p.name,subcircuit_id:this.subcircuit_id,server_cache_enabled:i.serverCacheEnabled}),headers:{"Content-Type":"application/json"}}).then(x=>x.json());for(;;){const{autorouting_job:x}=await s(`${a}/autorouting/jobs/get`,{method:"POST",body:JSON.stringify({autorouting_job_id:c.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(S=>S.json());if(x.is_finished){const{autorouting_job_output:S}=await s(`${a}/autorouting/jobs/get_output`,{method:"POST",body:JSON.stringify({autorouting_job_id:c.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(E=>E.json());this._asyncAutoroutingResult={output_pcb_traces:S.output_pcb_traces},this._markDirty("PcbTraceRender");break}if(x.has_error)throw t.pcb_autorouting_error.insert({pcb_error_id:c.autorouting_job_id,message:((v=x.error)==null?void 0:v.message)??JSON.stringify(x.error)}),new Error(`Autorouting job failed: ${JSON.stringify(x.error)}`);await new Promise(S=>setTimeout(S,100))}}async _runLocalAutorouting(){var l,c,u,f,p;const{db:t}=this.root;this._parsedProps;const n=E1("tscircuit:core:_runLocalAutorouting");n(`[${this.getString()}] starting local autorouting`);const i=this._getAutorouterConfig(),{simpleRouteJson:a}=hIe({db:t,minTraceWidth:((l=this.props.autorouter)==null?void 0:l.minTraceWidth)??.15,subcircuit_id:this.subcircuit_id});(c=this.root)==null||c.emit("autorouting:start",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),simpleRouteJson:a});let o;i.algorithmFn?o=await i.algorithmFn(a):o=new cqt(a,{capacityDepth:(u=this.props.autorouter)==null?void 0:u.capacityDepth,targetMinCapacity:(f=this.props.autorouter)==null?void 0:f.targetMinCapacity});const s=new Promise((v,x)=>{o.on("complete",S=>{n(`[${this.getString()}] local autorouting complete`),v(S.traces)}),o.on("error",S=>{n(`[${this.getString()}] local autorouting error: ${S.error.message}`),x(S.error)})});o.on("progress",v=>{var x;(x=this.root)==null||x.emit("autorouting:progress",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),...v})}),o.start();try{const v=await s;this._asyncAutoroutingResult={output_pcb_traces:v},this._markDirty("PcbTraceRender")}catch(v){const{db:x}=this.root;throw x.pcb_autorouting_error.insert({pcb_error_id:`pcb_autorouter_error_subcircuit_${this.subcircuit_id}`,message:v instanceof Error?v.message:String(v)}),(p=this.root)==null||p.emit("autorouting:error",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),error:{message:v instanceof Error?v.message:String(v)},simpleRouteJson:a}),v}finally{o.stop()}}_startAsyncAutorouting(){this._hasStartedAsyncAutorouting||(this._hasStartedAsyncAutorouting=!0,this._getAutorouterConfig().local?this._queueAsyncEffect("capacity-mesh-autorouting",async()=>this._runLocalAutorouting()):this._queueAsyncEffect("make-http-autorouting-request",async()=>this._runEffectMakeHttpAutoroutingRequest()))}doInitialPcbTraceRender(){var n;const t=E1("tscircuit:core:doInitialPcbTraceRender");if(this.isSubcircuit&&!((n=this.root)!=null&&n.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()}}updatePcbTraceRender(){var i;const t=E1("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;const{db:n}=this.root;if(this._asyncAutoroutingResult.output_simple_route_json){t(`[${this.getString()}] updating PCB traces from simple route json (${(i=this._asyncAutoroutingResult.output_simple_route_json.traces)==null?void 0:i.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(){const{db:t}=this.root,{traces:n}=this._asyncAutoroutingResult.output_simple_route_json;if(n)for(const i of n)t.pcb_trace.insert({subcircuit_id:this.subcircuit_id,route:i.route})}_updatePcbTraceRenderFromPcbTraces(){const{output_pcb_traces:t}=this._asyncAutoroutingResult;if(!t)return;const{db:n}=this.root;for(const i of t)if(i.type==="pcb_trace"){if(i.subcircuit_id=this.subcircuit_id,i.connection_name){const a=i.connection_name;i.source_trace_id=a}n.pcb_trace.insert(i)}for(const i of t)if(i.type!=="pcb_via"&&i.type==="pcb_trace")for(const a of i.route)a.route_type==="via"&&n.pcb_via.insert({pcb_trace_id:i.pcb_trace_id,x:a.x,y:a.y,hole_diameter:.3,outer_diameter:.6,layers:[a.from_layer,a.to_layer],from_layer:a.from_layer,to_layer:a.to_layer})}doInitialSchematicLayout(){if(!this.isSubcircuit||!this._parsedProps.schAutoLayoutEnabled)return;const{db:n}=this.root,i=this.getDescendants(),a=[];for(const l of i)if("schematic_component_id"in l){const c=n.schematic_component.get(l.schematic_component_id);if(c){const u=n.schematic_port.list().filter(f=>f.schematic_component_id===c.schematic_component_id);a.push(...u)}}const o=vG(n.toArray()),s=yG(o);mG(n.toArray(),s)}_getAutorouterConfig(){const t={serverUrl:"https://registry-api.tscircuit.com",serverMode:"job",serverCacheEnabled:!0},n=this._parsedProps.autorouter??this.getInheritedProperty("autorouter");return typeof n=="object"?{local:!(n.serverUrl||n.serverMode||n.serverCacheEnabled),...t,...n}:n==="auto-local"?{local:!0,groupMode:"subcircuit"}:n==="sequential-trace"?{local:!0,groupMode:"sequential-trace"}:n==="subcircuit"?{local:!0,groupMode:"subcircuit"}:n==="auto-cloud"?{local:!1,groupMode:"subcircuit",serverUrl:t.serverUrl,serverMode:t.serverMode,serverCacheEnabled:!0}:{local:!0,groupMode:"subcircuit"}}_shouldUseTraceByTraceRouting(){return this._getAutorouterConfig().groupMode==="sequential-trace"}doInitialPcbDesignRuleChecks(){var n;if((n=this.root)!=null&&n.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;const{db:t}=this.root;if(this.isSubcircuit){const i=new Map;for(const a of this.children)if(!a.isSubcircuit&&a._parsedProps.name){const o=i.get(a._parsedProps.name)||[];o.push(a),i.set(a._parsedProps.name,o)}for(const[a,o]of i.entries())o.length>1&&t.pcb_trace_error.insert({error_type:"pcb_trace_error",message:`Multiple components found with name "${a}" in subcircuit "${this._parsedProps.name||"unnamed"}". Component names must be unique within a subcircuit.`,source_trace_id:"",pcb_trace_id:"",pcb_component_ids:o.map(s=>s.pcb_component_id).filter(Boolean),pcb_port_ids:[]})}}},pqt=class extends Noe{constructor(){super(...arguments);Je(this,"pcb_board_id",null);Je(this,"_drcChecksComplete",!1);Je(this,"_connectedSchematicPortPairs",new Set)}get isSubcircuit(){return!0}get config(){return{componentName:"Board",zodProps:voe}}get boardThickness(){const{_parsedProps:t}=this;return 1.4}get allLayers(){return["top","bottom","inner1","inner2"]}doInitialPcbBoardAutoSize(){var x;if((x=this.root)!=null&&x.pcbDisabled||!this.pcb_board_id)return;const{db:t}=this.root,{_parsedProps:n}=this;if(n.width&&n.height)return;let i=1/0,a=1/0,o=-1/0,s=-1/0;const l=t.pcb_component.list();let c=!1;for(const S of l){const{width:E,height:b,center:C}=S;E===0||b===0||(c=!0,i=Math.min(i,C.x-E/2),a=Math.min(a,C.y-b/2),o=Math.max(o,C.x+E/2),s=Math.max(s,C.y+b/2))}const u=2,f=c?o-i+u*2:0,p=c?s-a+u*2:0,v={x:c?(i+o)/2+(n.outlineOffsetX??0):n.outlineOffsetX??0,y:c?(a+s)/2+(n.outlineOffsetY??0):n.outlineOffsetY??0};t.pcb_board.update(this.pcb_board_id,{width:f,height:p,center:v})}doInitialPcbComponentRender(){var s,l;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this;let i=n.width??0,a=n.height??0;if(n.outline){const c=n.outline.map(S=>S.x),u=n.outline.map(S=>S.y),f=Math.min(...c),p=Math.max(...c),v=Math.min(...u),x=Math.max(...u);i=p-f,a=x-v}const o=t.pcb_board.insert({center:{x:(n.pcbX??0)+(n.outlineOffsetX??0),y:(n.pcbY??0)+(n.outlineOffsetY??0)},thickness:this.boardThickness,num_layers:this.allLayers.length,width:i,height:a,outline:(l=n.outline)==null?void 0:l.map(c=>({x:c.x+(n.outlineOffsetX??0),y:c.y+(n.outlineOffsetY??0)})),material:n.material});this.pcb_board_id=o.pcb_board_id}removePcbComponentRender(){const{db:t}=this.root;this.pcb_board_id&&(t.pcb_board.delete(this.pcb_board_id),this.pcb_board_id=null)}_computePcbGlobalTransformBeforeLayout(){return Zm()}doInitialPcbDesignRuleChecks(){var t;(t=this.root)!=null&&t.pcbDisabled||this.getInheritedProperty("routingDisabled")||super.doInitialPcbDesignRuleChecks()}updatePcbDesignRuleChecks(){var i;if((i=this.root)!=null&&i.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;const{db:t}=this.root;if(!this._areChildSubcircuitsRouted()||this._drcChecksComplete)return;this._drcChecksComplete=!0;const n=YUe(t.toArray());for(const a of n)t.pcb_trace_error.insert(a)}_emitRenderLifecycleEvent(t,n){var i;super._emitRenderLifecycleEvent(t,n),n==="start"&&((i=this.root)==null||i.emit("board:renderPhaseStarted",{renderId:this._renderId,phase:t}))}},hqt=new Proxy({},{get:(r,e)=>e}),fA=hqt,mqt=class extends Xx{get config(){return{componentName:"Capacitor",schematicSymbolName:this.props.polarized?"capacitor_polarized":this.props.symbolName??"capacitor",zodProps:hUe,sourceFtype:fA.simple_capacitor}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){const e=`${f3(this._parsedProps.capacitance)}F`;return this._parsedProps.schShowRatings&&this._parsedProps.maxVoltageRating?`${e}/${f3(this._parsedProps.maxVoltageRating)}V`:e}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.decouplingFor,this.props.decouplingTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.decouplingFor&&this.props.decouplingTo&&(this.add(new I8({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.decouplingFor})),this.add(new I8({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.decouplingTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_capacitor",name:t.name,manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,capacitance:t.capacitance,max_voltage_rating:t.maxVoltageRating,max_decoupling_trace_length:t.maxDecouplingTraceLength,display_capacitance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!t.polarized});this.source_component_id=n.source_component_id}},mIe=class extends Xx{constructor(){super(...arguments);Je(this,"schematicBoxDimensions",null)}get config(){return{componentName:"Chip",zodProps:yoe,shouldRenderAsSchematicBox:!0}}doInitialSchematicComponentRender(){const{_parsedProps:t}=this;(t==null?void 0:t.noSchematicRepresentation)!==!0&&super.doInitialSchematicComponentRender()}doInitialSourceRender(){const{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:n.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){var a;if((a=this.root)!=null&&a.pcbDisabled)return;const{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});this.pcb_component_id=i.pcb_component_id}doInitialCreateTracesFromProps(){const{_parsedProps:t}=this;if(t.externallyConnectedPins)for(const[n,i]of t.externallyConnectedPins)this.add(new I8({from:`${this.getSubcircuitSelector()} > port.${n}`,to:`${this.getSubcircuitSelector()} > port.${i}`}));this._createTracesFromConnectionsProp()}},vqt=class extends Xx{constructor(){super(...arguments);Je(this,"pos",this.portMap.pin1);Je(this,"anode",this.portMap.pin1);Je(this,"neg",this.portMap.pin2);Je(this,"cathode",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"diode",componentName:"Diode",zodProps:RUe,sourceFtype:"simple_diode"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){const{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_diode",name:n.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}},yqt=class extends Xx{constructor(){super(...arguments);Je(this,"schematicDimensions",null)}get config(){let t="";if(this.props.pinCount&&(t+=`solderjumper${this.props.pinCount||2}`),Array.isArray(this.props.internallyConnectedPins)&&this.props.internallyConnectedPins.length>0){const n=Array.from(new Set(this.props.internallyConnectedPins.flat())).sort().join("");t+=`_bridged${n}`}return{schematicSymbolName:t,componentName:"Jumper",zodProps:sUe,shouldRenderAsSchematicBox:!0}}doInitialSourceRender(){const{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_chip",name:n.name,manufacturer_part_number:n.manufacturerPartNumber,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=i.source_component_id}doInitialPcbComponentRender(){var a;if((a=this.root)!=null&&a.pcbDisabled)return;const{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});this.pcb_component_id=i.pcb_component_id}doInitialPcbTraceRender(){const{db:t}=this.root,n=t.pcb_port.list({pcb_component_id:this.pcb_component_id}),i={};for(const s of n){const l=s.source_port_id&&s.source_port_id.match(/(\d+)$/);if(l){const c=(parseInt(l[1],10)+1).toString();i[c]=s.pcb_port_id}}const a=t.pcb_trace.list(),o=s=>{if(s&&typeof s=="string"&&s.startsWith("{PIN")){const l=s.replace("{PIN","").replace("}","");return i[l]||s}return s};for(const s of a)if(s.route)for(const l of s.route)l.route_type==="wire"&&(l.start_pcb_port_id=o(l.start_pcb_port_id),l.end_pcb_port_id=o(l.end_pcb_port_id))}},gqt=class extends Xx{constructor(){super(...arguments);Je(this,"pos",this.portMap.pin1);Je(this,"anode",this.portMap.pin1);Je(this,"neg",this.portMap.pin2);Je(this,"cathode",this.portMap.pin2)}get config(){return{componentName:"Led",schematicSymbolName:this.props.symbolName??"led",zodProps:AUe,sourceFtype:"simple_diode"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){const{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_diode",name:n.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}},_qt=class extends Xx{constructor(){super(...arguments);Je(this,"pos",this.portMap.pin1);Je(this,"positive",this.portMap.pin1);Je(this,"neg",this.portMap.pin2);Je(this,"negative",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"power_factor_meter_horz",componentName:"PowerSource",zodProps:zUe,sourceFtype:"simple_power_source"}}initPorts(){this.add(new q4({name:"pin1",pinNumber:1,aliases:["positive","pos"]})),this.add(new q4({name:"pin2",pinNumber:2,aliases:["negative","neg"]}))}doInitialSourceRender(){const{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_power_source",name:n.name,voltage:n.voltage,supplier_part_numbers:n.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=i.source_component_id}},xqt=class extends Xx{get config(){return{componentName:"Resistor",schematicSymbolName:this.props.symbolName??"boxresistor",zodProps:uUe,sourceFtype:"simple_resistor"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return`${f3(this._parsedProps.resistance)}Ω`}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.pullupFor,this.props.pullupTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.pullupFor&&this.props.pullupTo&&(this.add(new I8({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pullupFor})),this.add(new I8({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pullupTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_resistor",name:t.name,manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,resistance:t.resistance,display_resistance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!0});this.source_component_id=n.source_component_id}},bqt=["leftedge","rightedge","topedge","bottomedge","center"],Sqt=class extends w_{get config(){return{componentName:"Constraint",zodProps:mUe}}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(){const e=[],t=this.getPrimitiveContainer();function n(i){const a=i.split(" ").pop(),o=bqt.includes(a)?a:void 0,s=o?i.replace(` ${o}`,""):i,l=t.selectOne(s,{pcbPrimitive:!0});l&&e.push({selector:i,component:l,componentSelector:s,edge:o})}for(const i of["left","right","top","bottom"])i in this._parsedProps&&n(this._parsedProps[i]);if("for"in this._parsedProps)for(const i of this._parsedProps.for)n(i);return{componentsWithSelectors:e}}},Eqt=class extends w_{constructor(){super(...arguments);Je(this,"fabrication_note_path_id",null)}get config(){return{componentName:"FabricationNotePath",zodProps:DUe}}doInitialPcbPrimitiveRender(){var l,c;if((l=this.root)!=null&&l.pcbDisabled)return;const{db:t}=this.root,n=this.getSubcircuit(),{_parsedProps:i}=this,a=i.layer??"top";if(a!=="top"&&a!=="bottom")throw new Error(`Invalid layer "${a}" for SilkscreenPath. Must be "top" or "bottom".`);const o=this._computePcbGlobalTransformBeforeLayout(),s=t.pcb_fabrication_note_path.insert({pcb_component_id:(c=this.parent)==null?void 0:c.pcb_component_id,layer:a,color:i.color,route:i.route.map(u=>{const f=Ir(o,{x:u.x,y:u.y});return{...u,x:f.x,y:f.y}}),stroke_width:i.strokeWidth??.1,subcircuit_id:(n==null?void 0:n.subcircuit_id)??void 0});this.fabrication_note_path_id=s.pcb_fabrication_note_path_id}},wqt=class extends w_{get config(){return{componentName:"FabricationNoteText",zodProps:NUe}}doInitialPcbPrimitiveRender(){var a,o;if((a=this.root)!=null&&a.pcbDisabled)return;const{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==null?void 0:i.subcircuit_id)??void 0,pcb_group_id:((o=this.getGroup())==null?void 0:o.pcb_group_id)??void 0})}},Tqt=class extends Noe{constructor(e){super({...e,subcircuit:!0})}},Mqt=class extends w_{constructor(){super(...arguments);Je(this,"source_net_alias_id")}get config(){return{componentName:"NetAlias",zodProps:EUe}}doInitialSchematicComponentRender(){var o;if((o=this.root)!=null&&o.schematicDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,i={x:n.schX??0,y:n.schY??0},a=t.schematic_net_label.insert({text:n.net,source_net_id:n.net,anchor_position:i,center:i,anchor_side:"bottom"});this.source_net_alias_id=a.source_net_id}},Cqt=class extends w_{constructor(){super(...arguments);Je(this,"pcb_silkscreen_circle_id",null);Je(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenCircle",zodProps:HUe}}doInitialPcbPrimitiveRender(){var l,c,u;if((l=this.root)!=null&&l.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),a=i(n.layer??"top");if(a!=="top"&&a!=="bottom")throw new Error(`Invalid layer "${a}" for SilkscreenCircle. Must be "top" or "bottom".`);this._computePcbGlobalTransformBeforeLayout();const o=this.getSubcircuit(),s=t.pcb_silkscreen_circle.insert({pcb_component_id:(c=this.parent)==null?void 0:c.pcb_component_id,layer:a,center:{x:n.pcbX??0,y:n.pcbY??0},radius:n.radius,subcircuit_id:(o==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((u=this.getGroup())==null?void 0:u.pcb_group_id)??void 0,stroke_width:n.strokeWidth??.1});this.pcb_silkscreen_circle_id=s.pcb_silkscreen_circle_id}getPcbSize(){const{_parsedProps:t}=this,n=t.radius*2;return{width:n,height:n}}},Rqt=class extends w_{constructor(){super(...arguments);Je(this,"pcb_silkscreen_rect_id",null);Je(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenRect",zodProps:BUe}}doInitialPcbPrimitiveRender(){var l,c,u;if((l=this.root)!=null&&l.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),a=i(n.layer??"top");if(a!=="top"&&a!=="bottom")throw new Error(`Invalid layer "${a}" for SilkscreenRect. Must be "top" or "bottom".`);const o=this.getSubcircuit(),s=t.pcb_silkscreen_rect.insert({pcb_component_id:(c=this.parent)==null?void 0:c.pcb_component_id,layer:a,center:{x:n.pcbX??0,y:n.pcbY??0},width:n.width,height:n.height,subcircuit_id:(o==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((u=this==null?void 0:this.getGroup())==null?void 0:u.pcb_group_id)??void 0,stroke_width:n.strokeWidth??.1});this.pcb_silkscreen_rect_id=s.pcb_silkscreen_rect_id}getPcbSize(){const{_parsedProps:t}=this;return{width:t.width,height:t.height}}},Aqt=class extends w_{constructor(){super(...arguments);Je(this,"pcb_silkscreen_line_id",null);Je(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenLine",zodProps:FUe}}doInitialPcbPrimitiveRender(){var l,c,u;if((l=this.root)!=null&&l.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,{maybeFlipLayer:i}=this._getPcbPrimitiveFlippedHelpers(),a=i(n.layer??"top");if(a!=="top"&&a!=="bottom")throw new Error(`Invalid layer "${a}" for SilkscreenLine. Must be "top" or "bottom".`);const o=this.getSubcircuit(),s=t.pcb_silkscreen_line.insert({pcb_component_id:(c=this.parent)==null?void 0:c.pcb_component_id,layer:a,x1:n.x1,y1:n.y1,x2:n.x2,y2:n.y2,stroke_width:n.strokeWidth??.1,subcircuit_id:(o==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((u=o==null?void 0:o.getGroup())==null?void 0:u.pcb_group_id)??void 0});this.pcb_silkscreen_line_id=s.pcb_silkscreen_line_id}getPcbSize(){const{_parsedProps:t}=this,n=Math.abs(t.x2-t.x1),i=Math.abs(t.y2-t.y1);return{width:n,height:i}}},Pqt=class extends w_{constructor(){super(...arguments);Je(this,"pcb_via_id",null);Je(this,"matchedPort",null);Je(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Via",zodProps:LUe}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){const{_parsedProps:t}=this;return{width:t.outerDiameter,height:t.outerDiameter}}_getPcbCircuitJsonBounds(){const{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){const{db:n}=this.root;n.pcb_via.update(this.pcb_via_id,{x:t.x,y:t.y})}doInitialPcbPrimitiveRender(){var s,l;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),a=this.getSubcircuit(),o=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:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((l=this.getGroup())==null?void 0:l.pcb_group_id)??void 0});this.pcb_via_id=o.pcb_via_id}},Nqt=class extends Xx{get config(){return{componentName:"Battery",schematicSymbolName:this.props.symbolName??"battery",zodProps:bUe,sourceFtype:"simple_power_source"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:t.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}},Dqt=class extends Xx{get config(){return{componentName:"PinHeader",zodProps:SUe,shouldRenderAsSchematicBox:!0}}_getImpliedFootprintString(){var a;const e=this._parsedProps.pinCount??((a=this._parsedProps.pinLabels)==null?void 0:a.length)??0,t=this._parsedProps.holeDiameter,n=this._parsedProps.platedDiameter,i=this._parsedProps.pitch;return e>0&&i?!t&&!n?`pinrow${e}_p${i}`:`pinrow${e}_p${i}_id${t}_od${n}`:null}initPorts(){var t,n;const e=this._parsedProps.pinCount??((t=this._parsedProps.pinLabels)==null?void 0:t.length)??1;for(let i=1;i<=e;i++)this.add(new q4({name:`pin${i}`,pinNumber:i,aliases:[(n=this._parsedProps.pinLabels)==null?void 0:n[i-1]].filter(Boolean)}))}_getSchematicPortArrangement(){const e=this._parsedProps.pinCount??1,t=this._parsedProps.facingDirection??"right";return{leftSize:t==="left"?e:0,rightSize:t==="right"?e:0}}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_pin_header",name:t.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 Lqt(r){switch(r){case"two_ground_pins":return"crystal_4pin";case"ground_pin":return"resonator";case"no_ground":return"crystal";default:return"crystal"}}var Oqt=class extends Xx{get config(){return{componentName:"Resonator",schematicSymbolName:this.props.symbolName??Lqt(this.props.pinVariant),zodProps:pUe,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=t.pinVariant||"no_ground",i=e.source_component.insert({ftype:"simple_resonator",name:t.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}},zqt=class extends Xx{get config(){return{componentName:"Inductor",schematicSymbolName:this.props.symbolName??"inductor",zodProps:CUe,sourceFtype:fA.simple_inductor}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:t.name,ftype:fA.simple_inductor,inductance:t.inductance,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=n.source_component_id}};function Uqt(r){switch(r){case"three_pin":return"potentiometer3";case"two_pin":return"potentiometer2";default:return"potentiometer2"}}var Iqt=class extends Xx{get config(){return{componentName:"Potentiometer",schematicSymbolName:this.props.symbolName??Uqt(this.props.pinVariant),zodProps:fUe,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=t.pinVariant||"two_pin",i=e.source_component.insert({ftype:"simple_potentiometer",name:t.name,max_resistance:t.maxResistance,pin_variant:n,are_pins_interchangeable:n==="two_pin"});this.source_component_id=i.source_component_id}},kqt=class extends Xx{get config(){return{componentName:"PushButton",schematicSymbolName:this.props.symbolName??"push_button_normally_open_momentary",zodProps:wUe,sourceFtype:fA.simple_push_button}}get defaultInternallyConnectedPinNames(){return[["pin1","pin4"],["pin2","pin3"]]}initPorts(){super.initPorts({pinCount:4,additionalAliases:{pin1:["side1"],pin3:["side2"]}})}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:t.name,ftype:fA.simple_push_button,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=n.source_component_id}},Fqt=class extends Xx{get config(){return{schematicSymbolName:this.props.symbolName??(this.props.pinVariant==="four_pin"?"crystal_4pin":"crystal"),componentName:"Crystal",zodProps:dUe,sourceFtype:"simple_crystal"}}initPorts(){const 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(){return`${f3(this._parsedProps.frequency)}Hz`}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({name:t.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}},Bqt=class extends Xx{constructor(){super(...arguments);Je(this,"emitter",this.portMap.pin1);Je(this,"collector",this.portMap.pin2);Je(this,"base",this.portMap.pin3)}get config(){return{componentName:"Transistor",schematicSymbolName:this.props.type==="npn"?"npn_bipolar_transistor":"pnp_bipolar_transistor",zodProps:TUe,sourceFtype:"simple_transistor",shouldRenderAsSchematicBox:!1}}initPorts(){const t=this.props.type==="npn"?{pin1:["emitter","e"],pin2:["collector","c"],pin3:["base","b"]}:{pin1:["collector","c"],pin2:["emitter","e"],pin3:["base","b"]};super.initPorts({pinCount:3,additionalAliases:t})}doInitialSourceRender(){const{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:"simple_transistor",name:n.name,transistor_type:n.type});this.source_component_id=i.source_component_id}},Hqt=class extends Xx{get config(){const e=this.props.mosfetMode==="depletion"?"d":"e";return{componentName:"Mosfet",schematicSymbolName:`${this.props.channelType}_channel_${e}_mosfet_transistor`,zodProps:MUe,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_mosfet",name:t.name,mosfet_mode:t.mosfetMode,channel_type:t.channelType});this.source_component_id=n.source_component_id}},jqt=class extends Xx{_getSwitchType(){const{spst:e,spdt:t,dpst:n,dpdt:i,type:a}=this._parsedProps??{};return i?"dpdt":e?"spst":t?"spdt":n?"dpst":a??"spst"}get config(){const e=this._getSwitchType(),{isNormallyClosed:t}=this._parsedProps??{};return{componentName:"Switch",schematicSymbolName:{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"}[e]??"spst_switch",zodProps:PUe,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_switch",name:t.name,switch_type:t.type,is_normally_closed:t.isNormallyClosed??!1,are_pins_interchangeable:this._getSwitchType()==="spst"});this.source_component_id=n.source_component_id}},Vqt=class extends w_{constructor(){super(...arguments);Je(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicText",zodProps:UUe}}doInitialSchematicPrimitiveRender(){var i;if((i=this.root)!=null&&i.schematicDisabled)return;const{db:t}=this.root,{_parsedProps:n}=this;t.schematic_text.insert({anchor:n.anchor??"center",text:n.text,font_size:n.fontSize,color:n.color||"#000000",position:{x:n.schX,y:n.schY},rotation:n.schRotation??0})}};new Proxy({},{get:(r,e)=>{const t=(...n)=>(n[0],new Proxy({},{get:(i,a)=>`.${e} > .${a}`}));return new Proxy(t,{get:(n,i)=>e==="net"?`net.${i}`:e==="subcircuit"?new Proxy({},{get:(a,o)=>new Proxy({},{get:(s,l)=>`subcircuit.${i} > .${o} > .${l}`})}):`.${e} > .${i}`,apply:(n,i,a)=>new Proxy({},{get:(o,s)=>{const l=`.${e} > .${s}`;return e.startsWith("U")?l:new Proxy(new String(l),{get:(c,u)=>typeof u=="symbol"||u==="toString"?()=>l:`.${e} > .${s} > .${u}`})}})})}}),ZUe(XUe),ZUe({Bug:mIe});const dA=r=>typeof r=="number"&&!isNaN(r),k8=r=>typeof r=="string",Q5=r=>typeof r=="function",kk=r=>k8(r)||Q5(r)?r:null,Doe=r=>mt.isValidElement(r)||k8(r)||Q5(r)||dA(r);function Gqt(r,e,t){t===void 0&&(t=300);const{scrollHeight:n,style:i}=r;requestAnimationFrame(()=>{i.minHeight="initial",i.height=n+"px",i.transition=`all ${t}ms`,requestAnimationFrame(()=>{i.height="0",i.padding="0",i.margin="0",setTimeout(e,t)})})}function Fk(r){let{enter:e,exit:t,appendPosition:n=!1,collapse:i=!0,collapseDuration:a=300}=r;return function(o){let{children:s,position:l,preventExitTransition:c,done:u,nodeRef:f,isIn:p,playToast:v}=o;const x=n?`${e}--${l}`:e,S=n?`${t}--${l}`:t,E=mt.useRef(0);return mt.useLayoutEffect(()=>{const b=f.current,C=x.split(" "),O=U=>{U.target===f.current&&(v(),b.removeEventListener("animationend",O),b.removeEventListener("animationcancel",O),E.current===0&&U.type!=="animationcancel"&&b.classList.remove(...C))};b.classList.add(...C),b.addEventListener("animationend",O),b.addEventListener("animationcancel",O)},[]),mt.useEffect(()=>{const b=f.current,C=()=>{b.removeEventListener("animationend",C),i?Gqt(b,u,a):u()};p||(c?C():(E.current=1,b.className+=` ${S}`,b.addEventListener("animationend",C)))},[p]),Yp.createElement(Yp.Fragment,null,s)}}function vIe(r,e){return r!=null?{content:r.content,containerId:r.props.containerId,id:r.props.toastId,theme:r.props.theme,type:r.props.type,data:r.props.data||{},isLoading:r.props.isLoading,icon:r.props.icon,status:e}:{}}const Z2=new Map;let pA=[];const Loe=new Set,qqt=r=>Loe.forEach(e=>e(r)),yIe=()=>Z2.size>0;function gIe(r,e){var t;if(e)return!((t=Z2.get(e))==null||!t.isToastActive(r));let n=!1;return Z2.forEach(i=>{i.isToastActive(r)&&(n=!0)}),n}function _Ie(r,e){Doe(r)&&(yIe()||pA.push({content:r,options:e}),Z2.forEach(t=>{t.buildToast(r,e)}))}function xIe(r,e){Z2.forEach(t=>{e!=null&&e!=null&&e.containerId?(e==null?void 0:e.containerId)===t.id&&t.toggle(r,e==null?void 0:e.id):t.toggle(r,e==null?void 0:e.id)})}function $qt(r){const{subscribe:e,getSnapshot:t,setProps:n}=mt.useRef(function(a){const o=a.containerId||1;return{subscribe(s){const l=function(u,f,p){let v=1,x=0,S=[],E=[],b=[],C=f;const O=new Map,U=new Set,q=()=>{b=Array.from(O.values()),U.forEach(K=>K())},Y=K=>{E=K==null?[]:E.filter(te=>te!==K),q()},Q=K=>{const{toastId:te,onOpen:J,updateId:fe,children:he}=K.props,ve=fe==null;K.staleId&&O.delete(K.staleId),O.set(te,K),E=[...E,K.props.toastId].filter(Te=>Te!==K.staleId),q(),p(vIe(K,ve?"added":"updated")),ve&&Q5(J)&&J(mt.isValidElement(he)&&he.props)};return{id:u,props:C,observe:K=>(U.add(K),()=>U.delete(K)),toggle:(K,te)=>{O.forEach(J=>{te!=null&&te!==J.props.toastId||Q5(J.toggle)&&J.toggle(K)})},removeToast:Y,toasts:O,clearQueue:()=>{x-=S.length,S=[]},buildToast:(K,te)=>{if((ke=>{let{containerId:ot,toastId:nt,updateId:gt}=ke;const Et=ot?ot!==u:u!==1,Ot=O.has(nt)&>==null;return Et||Ot})(te))return;const{toastId:J,updateId:fe,data:he,staleId:ve,delay:Te}=te,Pe=()=>{Y(J)},Ee=fe==null;Ee&&x++;const Ce={...C,style:C.toastStyle,key:v++,...Object.fromEntries(Object.entries(te).filter(ke=>{let[ot,nt]=ke;return nt!=null})),toastId:J,updateId:fe,data:he,closeToast:Pe,isIn:!1,className:kk(te.className||C.toastClassName),bodyClassName:kk(te.bodyClassName||C.bodyClassName),progressClassName:kk(te.progressClassName||C.progressClassName),autoClose:!te.isLoading&&(be=te.autoClose,Oe=C.autoClose,be===!1||dA(be)&&be>0?be:Oe),deleteToast(){const ke=O.get(J),{onClose:ot,children:nt}=ke.props;Q5(ot)&&ot(mt.isValidElement(nt)&&nt.props),p(vIe(ke,"removed")),O.delete(J),x--,x<0&&(x=0),S.length>0?Q(S.shift()):q()}};var be,Oe;Ce.closeButton=C.closeButton,te.closeButton===!1||Doe(te.closeButton)?Ce.closeButton=te.closeButton:te.closeButton===!0&&(Ce.closeButton=!Doe(C.closeButton)||C.closeButton);let Ue=K;mt.isValidElement(K)&&!k8(K.type)?Ue=mt.cloneElement(K,{closeToast:Pe,toastProps:Ce,data:he}):Q5(K)&&(Ue=K({closeToast:Pe,toastProps:Ce,data:he}));const Ie={content:Ue,props:Ce,staleId:ve};C.limit&&C.limit>0&&x>C.limit&&Ee?S.push(Ie):dA(Te)?setTimeout(()=>{Q(Ie)},Te):Q(Ie)},setProps(K){C=K},setToggle:(K,te)=>{O.get(K).toggle=te},isToastActive:K=>E.some(te=>te===K),getSnapshot:()=>b}}(o,a,qqt);Z2.set(o,l);const c=l.observe(s);return pA.forEach(u=>_Ie(u.content,u.options)),pA=[],()=>{c(),Z2.delete(o)}},setProps(s){var l;(l=Z2.get(o))==null||l.setProps(s)},getSnapshot(){var s;return(s=Z2.get(o))==null?void 0:s.getSnapshot()}}}(r)).current;n(r);const i=mt.useSyncExternalStore(e,t,t);return{getToastToRender:function(a){if(!i)return[];const o=new Map;return r.newestOnTop&&i.reverse(),i.forEach(s=>{const{position:l}=s.props;o.has(l)||o.set(l,[]),o.get(l).push(s)}),Array.from(o,s=>a(s[0],s[1]))},isToastActive:gIe,count:i==null?void 0:i.length}}function Yqt(r){const[e,t]=mt.useState(!1),[n,i]=mt.useState(!1),a=mt.useRef(null),o=mt.useRef({start:0,delta:0,removalDistance:0,canCloseOnClick:!0,canDrag:!1,didMove:!1}).current,{autoClose:s,pauseOnHover:l,closeToast:c,onClick:u,closeOnClick:f}=r;var p,v;function x(){t(!0)}function S(){t(!1)}function E(O){const U=a.current;o.canDrag&&U&&(o.didMove=!0,e&&S(),o.delta=r.draggableDirection==="x"?O.clientX-o.start:O.clientY-o.start,o.start!==O.clientX&&(o.canCloseOnClick=!1),U.style.transform=`translate3d(${r.draggableDirection==="x"?`${o.delta}px, var(--y)`:`0, calc(${o.delta}px + var(--y))`},0)`,U.style.opacity=""+(1-Math.abs(o.delta/o.removalDistance)))}function b(){document.removeEventListener("pointermove",E),document.removeEventListener("pointerup",b);const O=a.current;if(o.canDrag&&o.didMove&&O){if(o.canDrag=!1,Math.abs(o.delta)>o.removalDistance)return i(!0),r.closeToast(),void r.collapseAll();O.style.transition="transform 0.2s, opacity 0.2s",O.style.removeProperty("transform"),O.style.removeProperty("opacity")}}(v=Z2.get((p={id:r.toastId,containerId:r.containerId,fn:t}).containerId||1))==null||v.setToggle(p.id,p.fn),mt.useEffect(()=>{if(r.pauseOnFocusLoss)return document.hasFocus()||S(),window.addEventListener("focus",x),window.addEventListener("blur",S),()=>{window.removeEventListener("focus",x),window.removeEventListener("blur",S)}},[r.pauseOnFocusLoss]);const C={onPointerDown:function(O){if(r.draggable===!0||r.draggable===O.pointerType){o.didMove=!1,document.addEventListener("pointermove",E),document.addEventListener("pointerup",b);const U=a.current;o.canCloseOnClick=!0,o.canDrag=!0,U.style.transition="none",r.draggableDirection==="x"?(o.start=O.clientX,o.removalDistance=U.offsetWidth*(r.draggablePercent/100)):(o.start=O.clientY,o.removalDistance=U.offsetHeight*(r.draggablePercent===80?1.5*r.draggablePercent:r.draggablePercent)/100)}},onPointerUp:function(O){const{top:U,bottom:q,left:Y,right:Q}=a.current.getBoundingClientRect();O.nativeEvent.type!=="touchend"&&r.pauseOnHover&&O.clientX>=Y&&O.clientX<=Q&&O.clientY>=U&&O.clientY<=q?S():x()}};return s&&l&&(C.onMouseEnter=S,r.stacked||(C.onMouseLeave=x)),f&&(C.onClick=O=>{u&&u(O),o.canCloseOnClick&&c()}),{playToast:x,pauseToast:S,isRunning:e,preventExitTransition:n,toastRef:a,eventHandlers:C}}function Xqt(r){let{delay:e,isRunning:t,closeToast:n,type:i="default",hide:a,className:o,style:s,controlledProgress:l,progress:c,rtl:u,isIn:f,theme:p}=r;const v=a||l&&c===0,x={...s,animationDuration:`${e}ms`,animationPlayState:t?"running":"paused"};l&&(x.transform=`scaleX(${c})`);const S=cS("Toastify__progress-bar",l?"Toastify__progress-bar--controlled":"Toastify__progress-bar--animated",`Toastify__progress-bar-theme--${p}`,`Toastify__progress-bar--${i}`,{"Toastify__progress-bar--rtl":u}),E=Q5(o)?o({rtl:u,type:i,defaultClassName:S}):cS(S,o),b={[l&&c>=1?"onTransitionEnd":"onAnimationEnd"]:l&&c<1?null:()=>{f&&n()}};return Yp.createElement("div",{className:"Toastify__progress-bar--wrp","data-hidden":v},Yp.createElement("div",{className:`Toastify__progress-bar--bg Toastify__progress-bar-theme--${p} Toastify__progress-bar--${i}`}),Yp.createElement("div",{role:"progressbar","aria-hidden":v?"true":"false","aria-label":"notification timer",className:E,style:x,...b}))}let Wqt=1;const bIe=()=>""+Wqt++;function Zqt(r){return r&&(k8(r.toastId)||dA(r.toastId))?r.toastId:bIe()}function hA(r,e){return _Ie(r,e),e.toastId}function Bk(r,e){return{...e,type:e&&e.type||r,toastId:Zqt(e)}}function Hk(r){return(e,t)=>hA(e,Bk(r,t))}function Jy(r,e){return hA(r,Bk("default",e))}Jy.loading=(r,e)=>hA(r,Bk("default",{isLoading:!0,autoClose:!1,closeOnClick:!1,closeButton:!1,draggable:!1,...e})),Jy.promise=function(r,e,t){let n,{pending:i,error:a,success:o}=e;i&&(n=k8(i)?Jy.loading(i,t):Jy.loading(i.render,{...t,...i}));const s={isLoading:null,autoClose:null,closeOnClick:null,closeButton:null,draggable:null},l=(u,f,p)=>{if(f==null)return void Jy.dismiss(n);const v={type:u,...s,...t,data:p},x=k8(f)?{render:f}:f;return n?Jy.update(n,{...v,...x}):Jy(x.render,{...v,...x}),p},c=Q5(r)?r():r;return c.then(u=>l("success",o,u)).catch(u=>l("error",a,u)),c},Jy.success=Hk("success"),Jy.info=Hk("info"),Jy.error=Hk("error"),Jy.warning=Hk("warning"),Jy.warn=Jy.warning,Jy.dark=(r,e)=>hA(r,Bk("default",{theme:"dark",...e})),Jy.dismiss=function(r){(function(e){var t;if(yIe()){if(e==null||k8(t=e)||dA(t))Z2.forEach(n=>{n.removeToast(e)});else if(e&&("containerId"in e||"id"in e)){const n=Z2.get(e.containerId);n?n.removeToast(e.id):Z2.forEach(i=>{i.removeToast(e.id)})}}else pA=pA.filter(n=>e!=null&&n.options.toastId!==e)})(r)},Jy.clearWaitingQueue=function(r){r===void 0&&(r={}),Z2.forEach(e=>{!e.props.limit||r.containerId&&e.id!==r.containerId||e.clearQueue()})},Jy.isActive=gIe,Jy.update=function(r,e){e===void 0&&(e={});const t=((n,i)=>{var a;let{containerId:o}=i;return(a=Z2.get(o||1))==null?void 0:a.toasts.get(n)})(r,e);if(t){const{props:n,content:i}=t,a={delay:100,...n,...e,toastId:e.toastId||r,updateId:bIe()};a.toastId!==r&&(a.staleId=r);const o=a.render||i;delete a.render,hA(o,a)}},Jy.done=r=>{Jy.update(r,{progress:1})},Jy.onChange=function(r){return Loe.add(r),()=>{Loe.delete(r)}},Jy.play=r=>xIe(!0,r),Jy.pause=r=>xIe(!1,r);const Qqt=typeof window<"u"?mt.useLayoutEffect:mt.useEffect,jk=r=>{let{theme:e,type:t,isLoading:n,...i}=r;return Yp.createElement("svg",{viewBox:"0 0 24 24",width:"100%",height:"100%",fill:e==="colored"?"currentColor":`var(--toastify-icon-color-${t})`,...i})},Ooe={info:function(r){return Yp.createElement(jk,{...r},Yp.createElement("path",{d:"M12 0a12 12 0 1012 12A12.013 12.013 0 0012 0zm.25 5a1.5 1.5 0 11-1.5 1.5 1.5 1.5 0 011.5-1.5zm2.25 13.5h-4a1 1 0 010-2h.75a.25.25 0 00.25-.25v-4.5a.25.25 0 00-.25-.25h-.75a1 1 0 010-2h1a2 2 0 012 2v4.75a.25.25 0 00.25.25h.75a1 1 0 110 2z"}))},warning:function(r){return Yp.createElement(jk,{...r},Yp.createElement("path",{d:"M23.32 17.191L15.438 2.184C14.728.833 13.416 0 11.996 0c-1.42 0-2.733.833-3.443 2.184L.533 17.448a4.744 4.744 0 000 4.368C1.243 23.167 2.555 24 3.975 24h16.05C22.22 24 24 22.044 24 19.632c0-.904-.251-1.746-.68-2.44zm-9.622 1.46c0 1.033-.724 1.823-1.698 1.823s-1.698-.79-1.698-1.822v-.043c0-1.028.724-1.822 1.698-1.822s1.698.79 1.698 1.822v.043zm.039-12.285l-.84 8.06c-.057.581-.408.943-.897.943-.49 0-.84-.367-.896-.942l-.84-8.065c-.057-.624.25-1.095.779-1.095h1.91c.528.005.84.476.784 1.1z"}))},success:function(r){return Yp.createElement(jk,{...r},Yp.createElement("path",{d:"M12 0a12 12 0 1012 12A12.014 12.014 0 0012 0zm6.927 8.2l-6.845 9.289a1.011 1.011 0 01-1.43.188l-4.888-3.908a1 1 0 111.25-1.562l4.076 3.261 6.227-8.451a1 1 0 111.61 1.183z"}))},error:function(r){return Yp.createElement(jk,{...r},Yp.createElement("path",{d:"M11.983 0a12.206 12.206 0 00-8.51 3.653A11.8 11.8 0 000 12.207 11.779 11.779 0 0011.8 24h.214A12.111 12.111 0 0024 11.791 11.766 11.766 0 0011.983 0zM10.5 16.542a1.476 1.476 0 011.449-1.53h.027a1.527 1.527 0 011.523 1.47 1.475 1.475 0 01-1.449 1.53h-.027a1.529 1.529 0 01-1.523-1.47zM11 12.5v-6a1 1 0 012 0v6a1 1 0 11-2 0z"}))},spinner:function(){return Yp.createElement("div",{className:"Toastify__spinner"})}},Kqt=r=>{const{isRunning:e,preventExitTransition:t,toastRef:n,eventHandlers:i,playToast:a}=Yqt(r),{closeButton:o,children:s,autoClose:l,onClick:c,type:u,hideProgressBar:f,closeToast:p,transition:v,position:x,className:S,style:E,bodyClassName:b,bodyStyle:C,progressClassName:O,progressStyle:U,updateId:q,role:Y,progress:Q,rtl:K,toastId:te,deleteToast:J,isIn:fe,isLoading:he,closeOnClick:ve,theme:Te}=r,Pe=cS("Toastify__toast",`Toastify__toast-theme--${Te}`,`Toastify__toast--${u}`,{"Toastify__toast--rtl":K},{"Toastify__toast--close-on-click":ve}),Ee=Q5(S)?S({rtl:K,position:x,type:u,defaultClassName:Pe}):cS(Pe,S),Ce=function(Ie){let{theme:ke,type:ot,isLoading:nt,icon:gt}=Ie,Et=null;const Ot={theme:ke,type:ot};return gt===!1||(Q5(gt)?Et=gt({...Ot,isLoading:nt}):mt.isValidElement(gt)?Et=mt.cloneElement(gt,Ot):nt?Et=Ooe.spinner():(Kt=>Kt in Ooe)(ot)&&(Et=Ooe[ot](Ot))),Et}(r),be=!!Q||!l,Oe={closeToast:p,type:u,theme:Te};let Ue=null;return o===!1||(Ue=Q5(o)?o(Oe):mt.isValidElement(o)?mt.cloneElement(o,Oe):function(Ie){let{closeToast:ke,theme:ot,ariaLabel:nt="close"}=Ie;return Yp.createElement("button",{className:`Toastify__close-button Toastify__close-button--${ot}`,type:"button",onClick:gt=>{gt.stopPropagation(),ke(gt)},"aria-label":nt},Yp.createElement("svg",{"aria-hidden":"true",viewBox:"0 0 14 16"},Yp.createElement("path",{fillRule:"evenodd",d:"M7.71 8.23l3.75 3.75-1.48 1.48-3.75-3.75-3.75 3.75L1 11.98l3.75-3.75L1 4.48 2.48 3l3.75 3.75L9.98 3l1.48 1.48-3.75 3.75z"})))}(Oe)),Yp.createElement(v,{isIn:fe,done:J,position:x,preventExitTransition:t,nodeRef:n,playToast:a},Yp.createElement("div",{id:te,onClick:c,"data-in":fe,className:Ee,...i,style:E,ref:n},Yp.createElement("div",{...fe&&{role:Y},className:Q5(b)?b({type:u}):cS("Toastify__toast-body",b),style:C},Ce!=null&&Yp.createElement("div",{className:cS("Toastify__toast-icon",{"Toastify--animate-icon Toastify__zoom-enter":!he})},Ce),Yp.createElement("div",null,s)),Ue,Yp.createElement(Xqt,{...q&&!be?{key:`pb-${q}`}:{},rtl:K,theme:Te,delay:l,isRunning:e,isIn:fe,closeToast:p,hide:f,type:u,style:U,className:O,controlledProgress:be,progress:Q||0})))},Vk=function(r,e){return e===void 0&&(e=!1),{enter:`Toastify--animate Toastify__${r}-enter`,exit:`Toastify--animate Toastify__${r}-exit`,appendPosition:e}},Jqt=Fk(Vk("bounce",!0));Fk(Vk("slide",!0)),Fk(Vk("zoom")),Fk(Vk("flip"));const e$t={position:"top-right",transition:Jqt,autoClose:5e3,closeButton:!0,pauseOnHover:!0,pauseOnFocusLoss:!0,draggable:"touch",draggablePercent:80,draggableDirection:"x",role:"alert",theme:"light"};function t$t(r){let e={...e$t,...r};const t=r.stacked,[n,i]=mt.useState(!0),a=mt.useRef(null),{getToastToRender:o,isToastActive:s,count:l}=$qt(e),{className:c,style:u,rtl:f,containerId:p}=e;function v(S){const E=cS("Toastify__toast-container",`Toastify__toast-container--${S}`,{"Toastify__toast-container--rtl":f});return Q5(c)?c({position:S,rtl:f,defaultClassName:E}):cS(E,kk(c))}function x(){t&&(i(!0),Jy.play())}return Qqt(()=>{if(t){var S;const E=a.current.querySelectorAll('[data-in="true"]'),b=12,C=(S=e.position)==null?void 0:S.includes("top");let O=0,U=0;Array.from(E).reverse().forEach((q,Y)=>{const Q=q;Q.classList.add("Toastify__toast--stacked"),Y>0&&(Q.dataset.collapsed=`${n}`),Q.dataset.pos||(Q.dataset.pos=C?"top":"bot");const K=O*(n?.2:1)+(n?0:b*Y);Q.style.setProperty("--y",`${C?K:-1*K}px`),Q.style.setProperty("--g",`${b}`),Q.style.setProperty("--s",""+(1-(n?U:0))),O+=Q.offsetHeight,U+=.025})}},[n,l,t]),Yp.createElement("div",{ref:a,className:"Toastify",id:p,onMouseEnter:()=>{t&&(i(!1),Jy.pause())},onMouseLeave:x},o((S,E)=>{const b=E.length?{...u}:{...u,pointerEvents:"none"};return Yp.createElement("div",{className:v(S),style:b,key:`container-${S}`},E.map(C=>{let{content:O,props:U}=C;return Yp.createElement(Kqt,{...U,stacked:t,collapseAll:x,isIn:s(U.toastId,U.containerId),style:U.style,key:`toast-${U.key}`},O)}))}))}function n$t(){var r=':root{--toastify-color-light:#fff;--toastify-color-dark:#121212;--toastify-color-info:#3498db;--toastify-color-success:#07bc0c;--toastify-color-warning:#f1c40f;--toastify-color-error:#e74c3c;--toastify-color-transparent:hsla(0,0%,100%,.7);--toastify-icon-color-info:var(--toastify-color-info);--toastify-icon-color-success:var(--toastify-color-success);--toastify-icon-color-warning:var(--toastify-color-warning);--toastify-icon-color-error:var(--toastify-color-error);--toastify-toast-width:320px;--toastify-toast-offset:16px;--toastify-toast-top:max(var(--toastify-toast-offset),env(safe-area-inset-top));--toastify-toast-right:max(var(--toastify-toast-offset),env(safe-area-inset-right));--toastify-toast-left:max(var(--toastify-toast-offset),env(safe-area-inset-left));--toastify-toast-bottom:max(var(--toastify-toast-offset),env(safe-area-inset-bottom));--toastify-toast-background:#fff;--toastify-toast-min-height:64px;--toastify-toast-max-height:800px;--toastify-toast-bd-radius:6px;--toastify-font-family:sans-serif;--toastify-z-index:9999;--toastify-text-color-light:#757575;--toastify-text-color-dark:#fff;--toastify-text-color-info:#fff;--toastify-text-color-success:#fff;--toastify-text-color-warning:#fff;--toastify-text-color-error:#fff;--toastify-spinner-color:#616161;--toastify-spinner-color-empty-area:#e0e0e0;--toastify-color-progress-light:linear-gradient(90deg,#4cd964,#5ac8fa,#007aff,#34aadc,#5856d6,#ff2d55);--toastify-color-progress-dark:#bb86fc;--toastify-color-progress-info:var(--toastify-color-info);--toastify-color-progress-success:var(--toastify-color-success);--toastify-color-progress-warning:var(--toastify-color-warning);--toastify-color-progress-error:var(--toastify-color-error);--toastify-color-progress-bgo:0.2}.Toastify__toast-container{z-index:var(--toastify-z-index);-webkit-transform:translateZ(var(--toastify-z-index));position:fixed;padding:4px;width:var(--toastify-toast-width);box-sizing:border-box;color:#fff}.Toastify__toast-container--top-left{top:var(--toastify-toast-top);left:var(--toastify-toast-left)}.Toastify__toast-container--top-center{top:var(--toastify-toast-top);left:50%;transform:translateX(-50%)}.Toastify__toast-container--top-right{top:var(--toastify-toast-top);right:var(--toastify-toast-right)}.Toastify__toast-container--bottom-left{bottom:var(--toastify-toast-bottom);left:var(--toastify-toast-left)}.Toastify__toast-container--bottom-center{bottom:var(--toastify-toast-bottom);left:50%;transform:translateX(-50%)}.Toastify__toast-container--bottom-right{bottom:var(--toastify-toast-bottom);right:var(--toastify-toast-right)}@media only screen and (max-width:480px){.Toastify__toast-container{width:100vw;padding:0;left:env(safe-area-inset-left);margin:0}.Toastify__toast-container--top-center,.Toastify__toast-container--top-left,.Toastify__toast-container--top-right{top:env(safe-area-inset-top);transform:translateX(0)}.Toastify__toast-container--bottom-center,.Toastify__toast-container--bottom-left,.Toastify__toast-container--bottom-right{bottom:env(safe-area-inset-bottom);transform:translateX(0)}.Toastify__toast-container--rtl{right:env(safe-area-inset-right);left:auto}}.Toastify__toast{--y:0;position:relative;-ms-touch-action:none;touch-action:none;min-height:var(--toastify-toast-min-height);box-sizing:border-box;margin-bottom:1rem;padding:8px;border-radius:var(--toastify-toast-bd-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);display:-ms-flexbox;display:flex;-ms-flex-pack:justify;justify-content:space-between;max-height:var(--toastify-toast-max-height);font-family:var(--toastify-font-family);cursor:default;direction:ltr;z-index:0;overflow:hidden}.Toastify__toast--stacked{position:absolute;width:100%;transform:translate3d(0,var(--y),0) scale(var(--s));transition:transform .3s}.Toastify__toast--stacked[data-collapsed] .Toastify__close-button,.Toastify__toast--stacked[data-collapsed] .Toastify__toast-body{transition:opacity .1s}.Toastify__toast--stacked[data-collapsed=false]{overflow:visible}.Toastify__toast--stacked[data-collapsed=true]:not(:last-child)>*{opacity:0}.Toastify__toast--stacked:after{content:"";position:absolute;left:0;right:0;height:calc(var(--g) * 1px);bottom:100%}.Toastify__toast--stacked[data-pos=top]{top:0}.Toastify__toast--stacked[data-pos=bot]{bottom:0}.Toastify__toast--stacked[data-pos=bot].Toastify__toast--stacked:before{transform-origin:top}.Toastify__toast--stacked[data-pos=top].Toastify__toast--stacked:before{transform-origin:bottom}.Toastify__toast--stacked:before{content:"";position:absolute;left:0;right:0;bottom:0;height:100%;transform:scaleY(3);z-index:-1}.Toastify__toast--rtl{direction:rtl}.Toastify__toast--close-on-click{cursor:pointer}.Toastify__toast-body{margin:auto 0;-ms-flex:1 1 auto;flex:1 1 auto;padding:6px;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center}.Toastify__toast-body>div:last-child{word-break:break-word;-ms-flex:1;flex:1}.Toastify__toast-icon{-webkit-margin-end:10px;margin-inline-end:10px;width:20px;-ms-flex-negative:0;flex-shrink:0;display:-ms-flexbox;display:flex}.Toastify--animate{animation-fill-mode:both;animation-duration:.5s}.Toastify--animate-icon{animation-fill-mode:both;animation-duration:.3s}@media only screen and (max-width:480px){.Toastify__toast{margin-bottom:0;border-radius:0}}.Toastify__toast-theme--dark{background:var(--toastify-color-dark);color:var(--toastify-text-color-dark)}.Toastify__toast-theme--colored.Toastify__toast--default,.Toastify__toast-theme--light{background:var(--toastify-color-light);color:var(--toastify-text-color-light)}.Toastify__toast-theme--colored.Toastify__toast--info{color:var(--toastify-text-color-info);background:var(--toastify-color-info)}.Toastify__toast-theme--colored.Toastify__toast--success{color:var(--toastify-text-color-success);background:var(--toastify-color-success)}.Toastify__toast-theme--colored.Toastify__toast--warning{color:var(--toastify-text-color-warning);background:var(--toastify-color-warning)}.Toastify__toast-theme--colored.Toastify__toast--error{color:var(--toastify-text-color-error);background:var(--toastify-color-error)}.Toastify__progress-bar-theme--light{background:var(--toastify-color-progress-light)}.Toastify__progress-bar-theme--dark{background:var(--toastify-color-progress-dark)}.Toastify__progress-bar--info{background:var(--toastify-color-progress-info)}.Toastify__progress-bar--success{background:var(--toastify-color-progress-success)}.Toastify__progress-bar--warning{background:var(--toastify-color-progress-warning)}.Toastify__progress-bar--error{background:var(--toastify-color-progress-error)}.Toastify__progress-bar-theme--colored.Toastify__progress-bar--error,.Toastify__progress-bar-theme--colored.Toastify__progress-bar--info,.Toastify__progress-bar-theme--colored.Toastify__progress-bar--success,.Toastify__progress-bar-theme--colored.Toastify__progress-bar--warning{background:var(--toastify-color-transparent)}.Toastify__close-button{color:#fff;background:transparent;outline:none;border:none;padding:0;cursor:pointer;opacity:.7;transition:.3s ease;-ms-flex-item-align:start;align-self:flex-start;z-index:1}.Toastify__close-button--light{color:#000;opacity:.3}.Toastify__close-button>svg{fill:currentColor;height:16px;width:14px}.Toastify__close-button:focus,.Toastify__close-button:hover{opacity:1}@keyframes Toastify__trackProgress{0%{transform:scaleX(1)}to{transform:scaleX(0)}}.Toastify__progress-bar{position:absolute;bottom:0;left:0;width:100%;height:100%;z-index:var(--toastify-z-index);opacity:.7;transform-origin:left;border-bottom-left-radius:var(--toastify-toast-bd-radius)}.Toastify__progress-bar--animated{animation:Toastify__trackProgress linear 1 forwards}.Toastify__progress-bar--controlled{transition:transform .2s}.Toastify__progress-bar--rtl{right:0;left:auto;transform-origin:right;border-bottom-left-radius:0;border-bottom-right-radius:var(--toastify-toast-bd-radius)}.Toastify__progress-bar--wrp{position:absolute;bottom:0;left:0;width:100%;height:5px;border-bottom-left-radius:var(--toastify-toast-bd-radius)}.Toastify__progress-bar--wrp[data-hidden=true]{opacity:0}.Toastify__progress-bar--bg{opacity:var(--toastify-color-progress-bgo);width:100%;height:100%}.Toastify__spinner{width:20px;height:20px;box-sizing:border-box;border:2px solid;border-radius:100%;border-color:var(--toastify-spinner-color-empty-area);border-right-color:var(--toastify-spinner-color);animation:Toastify__spin .65s linear infinite}@keyframes Toastify__bounceInRight{0%,60%,75%,90%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;transform:translate3d(3000px,0,0)}60%{opacity:1;transform:translate3d(-25px,0,0)}75%{transform:translate3d(10px,0,0)}90%{transform:translate3d(-5px,0,0)}to{transform:none}}@keyframes Toastify__bounceOutRight{20%{opacity:1;transform:translate3d(-20px,var(--y),0)}to{opacity:0;transform:translate3d(2000px,var(--y),0)}}@keyframes Toastify__bounceInLeft{0%,60%,75%,90%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;transform:translate3d(-3000px,0,0)}60%{opacity:1;transform:translate3d(25px,0,0)}75%{transform:translate3d(-10px,0,0)}90%{transform:translate3d(5px,0,0)}to{transform:none}}@keyframes Toastify__bounceOutLeft{20%{opacity:1;transform:translate3d(20px,var(--y),0)}to{opacity:0;transform:translate3d(-2000px,var(--y),0)}}@keyframes Toastify__bounceInUp{0%,60%,75%,90%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;transform:translate3d(0,3000px,0)}60%{opacity:1;transform:translate3d(0,-20px,0)}75%{transform:translate3d(0,10px,0)}90%{transform:translate3d(0,-5px,0)}to{transform:translateZ(0)}}@keyframes Toastify__bounceOutUp{20%{transform:translate3d(0,calc(var(--y) - 10px),0)}40%,45%{opacity:1;transform:translate3d(0,calc(var(--y) + 20px),0)}to{opacity:0;transform:translate3d(0,-2000px,0)}}@keyframes Toastify__bounceInDown{0%,60%,75%,90%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;transform:translate3d(0,-3000px,0)}60%{opacity:1;transform:translate3d(0,25px,0)}75%{transform:translate3d(0,-10px,0)}90%{transform:translate3d(0,5px,0)}to{transform:none}}@keyframes Toastify__bounceOutDown{20%{transform:translate3d(0,calc(var(--y) - 10px),0)}40%,45%{opacity:1;transform:translate3d(0,calc(var(--y) + 20px),0)}to{opacity:0;transform:translate3d(0,2000px,0)}}.Toastify__bounce-enter--bottom-left,.Toastify__bounce-enter--top-left{animation-name:Toastify__bounceInLeft}.Toastify__bounce-enter--bottom-right,.Toastify__bounce-enter--top-right{animation-name:Toastify__bounceInRight}.Toastify__bounce-enter--top-center{animation-name:Toastify__bounceInDown}.Toastify__bounce-enter--bottom-center{animation-name:Toastify__bounceInUp}.Toastify__bounce-exit--bottom-left,.Toastify__bounce-exit--top-left{animation-name:Toastify__bounceOutLeft}.Toastify__bounce-exit--bottom-right,.Toastify__bounce-exit--top-right{animation-name:Toastify__bounceOutRight}.Toastify__bounce-exit--top-center{animation-name:Toastify__bounceOutUp}.Toastify__bounce-exit--bottom-center{animation-name:Toastify__bounceOutDown}@keyframes Toastify__zoomIn{0%{opacity:0;transform:scale3d(.3,.3,.3)}50%{opacity:1}}@keyframes Toastify__zoomOut{0%{opacity:1}50%{opacity:0;transform:translate3d(0,var(--y),0) scale3d(.3,.3,.3)}to{opacity:0}}.Toastify__zoom-enter{animation-name:Toastify__zoomIn}.Toastify__zoom-exit{animation-name:Toastify__zoomOut}@keyframes Toastify__flipIn{0%{transform:perspective(400px) rotateX(90deg);animation-timing-function:ease-in;opacity:0}40%{transform:perspective(400px) rotateX(-20deg);animation-timing-function:ease-in}60%{transform:perspective(400px) rotateX(10deg);opacity:1}80%{transform:perspective(400px) rotateX(-5deg)}to{transform:perspective(400px)}}@keyframes Toastify__flipOut{0%{transform:translate3d(0,var(--y),0) perspective(400px)}30%{transform:translate3d(0,var(--y),0) perspective(400px) rotateX(-20deg);opacity:1}to{transform:translate3d(0,var(--y),0) perspective(400px) rotateX(90deg);opacity:0}}.Toastify__flip-enter{animation-name:Toastify__flipIn}.Toastify__flip-exit{animation-name:Toastify__flipOut}@keyframes Toastify__slideInRight{0%{transform:translate3d(110%,0,0);visibility:visible}to{transform:translate3d(0,var(--y),0)}}@keyframes Toastify__slideInLeft{0%{transform:translate3d(-110%,0,0);visibility:visible}to{transform:translate3d(0,var(--y),0)}}@keyframes Toastify__slideInUp{0%{transform:translate3d(0,110%,0);visibility:visible}to{transform:translate3d(0,var(--y),0)}}@keyframes Toastify__slideInDown{0%{transform:translate3d(0,-110%,0);visibility:visible}to{transform:translate3d(0,var(--y),0)}}@keyframes Toastify__slideOutRight{0%{transform:translate3d(0,var(--y),0)}to{visibility:hidden;transform:translate3d(110%,var(--y),0)}}@keyframes Toastify__slideOutLeft{0%{transform:translate3d(0,var(--y),0)}to{visibility:hidden;transform:translate3d(-110%,var(--y),0)}}@keyframes Toastify__slideOutDown{0%{transform:translate3d(0,var(--y),0)}to{visibility:hidden;transform:translate3d(0,500px,0)}}@keyframes Toastify__slideOutUp{0%{transform:translate3d(0,var(--y),0)}to{visibility:hidden;transform:translate3d(0,-500px,0)}}.Toastify__slide-enter--bottom-left,.Toastify__slide-enter--top-left{animation-name:Toastify__slideInLeft}.Toastify__slide-enter--bottom-right,.Toastify__slide-enter--top-right{animation-name:Toastify__slideInRight}.Toastify__slide-enter--top-center{animation-name:Toastify__slideInDown}.Toastify__slide-enter--bottom-center{animation-name:Toastify__slideInUp}.Toastify__slide-exit--bottom-left,.Toastify__slide-exit--top-left{animation-name:Toastify__slideOutLeft;animation-timing-function:ease-in;animation-duration:.3s}.Toastify__slide-exit--bottom-right,.Toastify__slide-exit--top-right{animation-name:Toastify__slideOutRight;animation-timing-function:ease-in;animation-duration:.3s}.Toastify__slide-exit--top-center{animation-name:Toastify__slideOutUp;animation-timing-function:ease-in;animation-duration:.3s}.Toastify__slide-exit--bottom-center{animation-name:Toastify__slideOutDown;animation-timing-function:ease-in;animation-duration:.3s}@keyframes Toastify__spin{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}}',e=document.createElement("style");e.innerText=r,document.head.appendChild(e)}const r$t=K8(PZe);var zoe,SIe;function i$t(){if(SIe)return zoe;SIe=1;var r=Object.defineProperty,e=Object.getOwnPropertyDescriptor,t=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,i=(E,b)=>{for(var C in b)r(E,C,{get:b[C],enumerable:!0})},a=(E,b,C,O)=>{if(b&&typeof b=="object"||typeof b=="function")for(let U of t(b))!n.call(E,U)&&U!==C&&r(E,U,{get:()=>b[U],enumerable:!(O=e(b,U))||O.enumerable});return E},o=E=>a(r({},"__esModule",{value:!0}),E),s={};i(s,{SuperGrid:()=>S,toMMSI:()=>x,toMeterSI:()=>v}),zoe=o(s);var l=Tb(),c=r$t,u=bce(),f=(E,b,C)=>{const O=[];if(b<E)for(let U=E;U>=b;U-=Math.abs(C))O.push(U);else for(let U=E;U<=b;U+=Math.abs(C))O.push(U);return O};function p(E,b){return{x:Math.round(b.x/E)*E,y:Math.round(b.y/E)*E}}function v(E,b=1){return E<0?"-"+v(-E):E<1e-6?"0m":E>1e3?Math.floor(E/1e3)+"km":E>1&&b>1?Math.round(E)+"m":E>1&&b<=1?E.toFixed(Math.ceil(-Math.log10(b)))+"m":E<1&&b>=1/1e3?Math.round(E*1e3)+"mm":E<1&&b<1/1e3?(E*1e3).toFixed(Math.ceil(-Math.log10(b*1e3)))+"mm":""}function x(E,b=1){return v(E/1e3,b/1e3)}var S=E=>{var b;const C=(0,l.useRef)(null),[O,U]=(0,l.useState)({x:0,y:0}),{majorColor:q="rgba(0,0,0,0.2)",minorColor:Y="rgba(0,0,0,0.1)",textColor:Q=(b=E.majorColor)!=null?b:"rgba(0,0,0,0.5)",width:K,height:te,screenSpaceCellSize:J=200,stringifyCoord:fe=(Pe,Ee,Ce)=>`${v(Pe,Ce)}, ${v(Ee,Ce)}`}=E,he=Math.ceil(K/J)+2,ve=Math.ceil(te/J)+2;(0,l.useEffect)(()=>{if(!C.current)return;const Pe=C.current.getContext("2d");if(!Pe)return;const Ee=J/10**Math.floor(Math.log10(E.transform.a)),Ce=E.transform.d<0?-1:1,Oe=J/10**Math.log10(E.transform.a)/Ee;function Ue(Bn,_n,dn){const Tn=Bn;let Xt,_r,Jn;for(Xt=_n.x;Xt<=dn.x;Xt+=Tn)_r=(0,c.applyToPoint)(E.transform,{x:Xt,y:_n.y}),Jn=(0,c.applyToPoint)(E.transform,{x:Xt,y:dn.y}),Pe.beginPath(),Pe.moveTo(_r.x,_r.y),Pe.lineTo(Jn.x,Jn.y),Pe.stroke();const sn=f(_n.y,dn.y,Tn*Ce);for(const lr of sn)_r=(0,c.applyToPoint)(E.transform,{x:_n.x,y:lr}),Jn=(0,c.applyToPoint)(E.transform,{x:dn.x,y:lr}),Pe.beginPath(),Pe.moveTo(_r.x,_r.y),Pe.lineTo(Jn.x,Jn.y),Pe.stroke()}function Ie(Bn,_n,dn){const Tn=Bn;let Xt;for(Xt=_n.x;Xt<=dn.x;Xt+=Tn)for(const _r of f(_n.y,dn.y,Tn*Ce)){const Jn=(0,c.applyToPoint)(E.transform,{x:Xt,y:_r});Pe.fillStyle=Q,Pe.font="12px sans-serif",Pe.fillText(fe(Xt,_r,Bn),Jn.x+2,Jn.y-2)}}Pe.clearRect(0,0,K,te);const ke=(0,c.applyToPoint)((0,c.inverse)(E.transform),{x:0,y:0}),ot={x:Math.floor((ke.x-Ee)/Ee)*Ee,y:Math.floor((ke.y-Ee)/Ee+(Ce==-1?2:0))*Ee},nt={x:ot.x+Ee*he,y:ot.y+Ee*ve*Ce},Et=Ee*5,Ot={x:Math.floor((ke.x-Et)/Et)*Et,y:Math.floor((ke.y-Et)/Et+(Ce==-1?2:0))*Et},Kt={x:Ot.x+Et*he,y:Ot.y+Et*ve*Ce};Pe.globalAlpha=1,Pe.strokeStyle=q,Ue(Ee,ot,nt),Ie(Et,Ot,Kt),Pe.globalAlpha=1-Oe,Ue(Et/10,Ot,Kt),Pe.globalAlpha=1-Oe,Pe.strokeStyle=Y,Ue(Ee/10,ot,nt),Pe.globalAlpha=Math.max(((1-Oe)*10-5)/5,0),Ie(Et/10,Ot,Kt),Pe.globalAlpha=1;const rn=(0,c.applyToPoint)(E.transform,O);Pe.font="12px sans-serif",Pe.fillStyle=Q,Pe.fillText(fe(O.x,O.y,Ee),rn.x+2,rn.y-2),Pe.strokeStyle=q,Pe.strokeRect(rn.x-5,rn.y-5,10,10)},[C,E.transform,O,K,te]);const Te=Pe=>{if(!C.current)return;const Ee=J/10/10**Math.floor(Math.log10(E.transform.a)),Ce=C.current.getBoundingClientRect(),be=(0,c.applyToPoint)((0,c.inverse)(E.transform),{x:Pe.clientX-Ce.left,y:Pe.clientY-Ce.top}),Oe=p(Ee,be);U(Oe)};return(0,u.jsx)("canvas",{onMouseUp:Pe=>{Pe.button===1&&Te(Pe)},onDoubleClick:Te,ref:C,width:E.width,height:E.height})};return zoe}var Uoe=i$t(),Ioe={exports:{}},mA={},Gk={exports:{}},koe={},Foe={},EIe;function Boe(){if(EIe)return Foe;EIe=1;function r(n){this.__parent=n,this.__character_count=0,this.__indent_count=-1,this.__alignment_count=0,this.__wrap_point_index=0,this.__wrap_point_character_count=0,this.__wrap_point_indent_count=-1,this.__wrap_point_alignment_count=0,this.__items=[]}r.prototype.clone_empty=function(){var n=new r(this.__parent);return n.set_indent(this.__indent_count,this.__alignment_count),n},r.prototype.item=function(n){return n<0?this.__items[this.__items.length+n]:this.__items[n]},r.prototype.has_match=function(n){for(var i=this.__items.length-1;i>=0;i--)if(this.__items[i].match(n))return!0;return!1},r.prototype.set_indent=function(n,i){this.is_empty()&&(this.__indent_count=n||0,this.__alignment_count=i||0,this.__character_count=this.__parent.get_indent_size(this.__indent_count,this.__alignment_count))},r.prototype._set_wrap_point=function(){this.__parent.wrap_line_length&&(this.__wrap_point_index=this.__items.length,this.__wrap_point_character_count=this.__character_count,this.__wrap_point_indent_count=this.__parent.next_line.__indent_count,this.__wrap_point_alignment_count=this.__parent.next_line.__alignment_count)},r.prototype._should_wrap=function(){return this.__wrap_point_index&&this.__character_count>this.__parent.wrap_line_length&&this.__wrap_point_character_count>this.__parent.next_line.__character_count},r.prototype._allow_wrap=function(){if(this._should_wrap()){this.__parent.add_new_line();var n=this.__parent.current_line;return n.set_indent(this.__wrap_point_indent_count,this.__wrap_point_alignment_count),n.__items=this.__items.slice(this.__wrap_point_index),this.__items=this.__items.slice(0,this.__wrap_point_index),n.__character_count+=this.__character_count-this.__wrap_point_character_count,this.__character_count=this.__wrap_point_character_count,n.__items[0]===" "&&(n.__items.splice(0,1),n.__character_count-=1),!0}return!1},r.prototype.is_empty=function(){return this.__items.length===0},r.prototype.last=function(){return this.is_empty()?null:this.__items[this.__items.length-1]},r.prototype.push=function(n){this.__items.push(n);var i=n.lastIndexOf(`
|
|
13254
13254
|
`);i!==-1?this.__character_count=n.length-i:this.__character_count+=n.length},r.prototype.pop=function(){var n=null;return this.is_empty()||(n=this.__items.pop(),this.__character_count-=n.length),n},r.prototype._remove_indent=function(){this.__indent_count>0&&(this.__indent_count-=1,this.__character_count-=this.__parent.indent_size)},r.prototype._remove_wrap_indent=function(){this.__wrap_point_indent_count>0&&(this.__wrap_point_indent_count-=1)},r.prototype.trim=function(){for(;this.last()===" ";)this.__items.pop(),this.__character_count-=1},r.prototype.toString=function(){var n="";return this.is_empty()?this.__parent.indent_empty_lines&&(n=this.__parent.get_indent_string(this.__indent_count)):(n=this.__parent.get_indent_string(this.__indent_count,this.__alignment_count),n+=this.__items.join("")),n};function e(n,i){this.__cache=[""],this.__indent_size=n.indent_size,this.__indent_string=n.indent_char,n.indent_with_tabs||(this.__indent_string=new Array(n.indent_size+1).join(n.indent_char)),i=i||"",n.indent_level>0&&(i=new Array(n.indent_level+1).join(this.__indent_string)),this.__base_string=i,this.__base_string_length=i.length}e.prototype.get_indent_size=function(n,i){var a=this.__base_string_length;return i=i||0,n<0&&(a=0),a+=n*this.__indent_size,a+=i,a},e.prototype.get_indent_string=function(n,i){var a=this.__base_string;return i=i||0,n<0&&(n=0,a=""),i+=n*this.__indent_size,this.__ensure_cache(i),a+=this.__cache[i],a},e.prototype.__ensure_cache=function(n){for(;n>=this.__cache.length;)this.__add_column()},e.prototype.__add_column=function(){var n=this.__cache.length,i=0,a="";this.__indent_size&&n>=this.__indent_size&&(i=Math.floor(n/this.__indent_size),n-=i*this.__indent_size,a=new Array(i+1).join(this.__indent_string)),n&&(a+=new Array(n+1).join(" ")),this.__cache.push(a)};function t(n,i){this.__indent_cache=new e(n,i),this.raw=!1,this._end_with_newline=n.end_with_newline,this.indent_size=n.indent_size,this.wrap_line_length=n.wrap_line_length,this.indent_empty_lines=n.indent_empty_lines,this.__lines=[],this.previous_line=null,this.current_line=null,this.next_line=new r(this),this.space_before_token=!1,this.non_breaking_space=!1,this.previous_token_wrapped=!1,this.__add_outputline()}return t.prototype.__add_outputline=function(){this.previous_line=this.current_line,this.current_line=this.next_line.clone_empty(),this.__lines.push(this.current_line)},t.prototype.get_line_number=function(){return this.__lines.length},t.prototype.get_indent_string=function(n,i){return this.__indent_cache.get_indent_string(n,i)},t.prototype.get_indent_size=function(n,i){return this.__indent_cache.get_indent_size(n,i)},t.prototype.is_empty=function(){return!this.previous_line&&this.current_line.is_empty()},t.prototype.add_new_line=function(n){return this.is_empty()||!n&&this.just_added_newline()?!1:(this.raw||this.__add_outputline(),!0)},t.prototype.get_code=function(n){this.trim(!0);var i=this.current_line.pop();i&&(i[i.length-1]===`
|
|
@@ -13422,4 +13422,4 @@ $1`).replace(/>(\s*)(?=<!--\s*\/)/g,"> ")}return sse}g$t();function oke(r,e,t,n=
|
|
|
13422
13422
|
}
|
|
13423
13423
|
`,onClick:n=>{n.stopPropagation(),t()},children:[ut.jsx("input",{type:"checkbox",checked:e}),ut.jsx("span",{style:{color:"#eee"},children:r})]}),HWt=({children:r,elements:e})=>{const[t,n]=xx(K=>[K.is_mouse_over_container,K.setIsMouseOverContainer]),[i,a]=mt.useState(!1),[o,s]=mt.useState(!1),[l,c]=mt.useState(!1),[u,f]=xx(K=>[K.selected_layer,K.selectLayer]),[p,v,x,S,E,b]=xx(K=>[K.in_move_footprint_mode,K.in_draw_trace_mode,K.is_showing_rats_nest,K.is_showing_multiple_traces_length,K.is_showing_autorouting,K.is_showing_drc_errors]),C=xx(K=>K.setEditMode),O=xx(K=>K.setIsShowingRatsNest),U=xx(K=>K.setIsShowingMultipleTracesLength),q=xx(K=>K.setIsShowingAutorouting),Y=xx(K=>K.setIsShowingDrcErrors);KE("1",()=>f("top")),KE("2",()=>f("bottom")),KE("3",()=>f("inner1")),KE("4",()=>f("inner2")),KE("5",()=>f("inner3")),KE("6",()=>f("inner4")),KE("7",()=>f("inner5")),KE("8",()=>f("inner6"));const Q=(e==null?void 0:e.filter(K=>K.type.includes("error")).length)??0;return ut.jsxs("div",{style:{position:"relative"},onMouseEnter:()=>{n(!0)},onMouseLeave:K=>{n(!1),s(!1)},children:[r,ut.jsxs("div",{style:{position:"absolute",bottom:4,right:8,pointerEvents:"none",color:"white",fontSize:11,opacity:t?.5:0,transition:"opacity 1s",transitionDelay:"2s",fontFamily:"sans-serif"},children:["@tscircuit/pcb-viewer@",FWt.version]}),ut.jsxs("div",{style:{position:"absolute",opacity:t?1:0,top:16,left:16,transition:t?"opacity 100ms linear":"opacity 1s linear",zIndex:z2.toolbarOverlay,color:"red",display:"flex",fontSize:12,height:100,fontFamily:"sans-serif"},children:[ut.jsxs(yM,{onClick:()=>{s(!o)},onMouseLeave:()=>{o&&s(!1)},children:[ut.jsxs("div",{children:["layer:"," ",ut.jsx("span",{style:{marginLeft:2,fontWeight:500,color:vM[u]},children:u})]}),o&&ut.jsx("div",{style:{marginTop:4,minWidth:120},children:jse.map(K=>K.replace(/-/g,"")).map(K=>ut.jsx(BWt,{name:K,selected:K===u,onClick:()=>{f(K.replace(/-/,""))}},K))})]}),ut.jsxs(yM,{style:Q>0?{color:"red"}:{},onClick:()=>c(!l),onMouseLeave:()=>c(!1),children:[ut.jsxs("div",{children:[Q," errors"]}),l&&ut.jsx("div",{style:{display:"grid",gridTemplateColumns:"100px 300px"},children:e==null?void 0:e.filter(K=>K.type.includes("error")).map((K,te)=>ut.jsxs(mt.Fragment,{children:[ut.jsx("div",{children:K.error_type}),ut.jsx("div",{children:K.message})]},te))})]}),ut.jsx(yM,{style:{},onClick:()=>{C(v?"off":"draw_trace")},children:ut.jsxs("div",{children:[v?"✖ ":"","Edit Traces"]})}),ut.jsx(yM,{style:{},onClick:()=>{C(p?"off":"move_footprint")},children:ut.jsxs("div",{children:[p?"✖ ":"","Move Components"]})}),ut.jsx(yM,{style:{},onClick:()=>{O(!x)},children:ut.jsxs("div",{children:[x?"✖ ":"","Rats Nest"]})}),ut.jsx(yM,{onClick:()=>{a(!i)},children:ut.jsxs("div",{children:[ut.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:["View"," ",ut.jsx("span",{style:{fontSize:"8px",transform:i?"rotate(180deg)":"rotate(0)",transition:"transform 0.1s ease",display:"inline-block"},children:"▼"})]}),i&&ut.jsxs("div",{style:{marginTop:4,minWidth:120},children:[ut.jsx(Yse,{label:"Show All Trace Lengths",checked:S,onClick:()=>{U(!S)}}),ut.jsx(Yse,{label:"Show Autorouting Animation",checked:E,onClick:()=>{q(!E)}}),ut.jsx(Yse,{label:"Show DRC Errors",checked:b,onClick:()=>{Y(!b)}})]})]})})]})]})},jWt=r=>{const{transform:e,elements:t}=r,[n,i]=mt.useMemo(()=>{const c=r.elements.flatMap(f=>JXt(f,r.elements)),u=k3(r.elements);return[c,u]},[r.elements]),[a,o]=mt.useState({drawingObjectIdsWithMouseOver:new Set,primitiveIdsInMousedOverNet:[]}),s=mt.useMemo(()=>ZXt({primitivesWithoutInteractionMetadata:n,drawingObjectIdsWithMouseOver:a.drawingObjectIdsWithMouseOver,primitiveIdsInMousedOverNet:a.primitiveIdsInMousedOverNet}),[n,a]),l=mt.useCallback(c=>{var p,v;const u=[];for(const x of c)if(x._element){const S=i.getNetConnectedToId("pcb_port_id"in x._element?(p=x._element)==null?void 0:p.pcb_port_id:"pcb_trace_id"in x._element?(v=x._element)==null?void 0:v.pcb_trace_id:"");u.push(...i.getIdsConnectedToNet(S))}const f=new Set(c.map(x=>x._pcb_drawing_object_id));o({drawingObjectIdsWithMouseOver:f,primitiveIdsInMousedOverNet:u})},[i]);return ut.jsx(IWt,{elements:t,transform:e,primitives:n,onMouseHoverOverPrimitives:l,children:ut.jsx(xWt,{disabled:!r.allowEditing,transform:e,soup:t,cancelPanDrag:r.cancelPanDrag,onCreateEditEvent:r.onCreateEditEvent,onModifyEditEvent:r.onModifyEditEvent,children:ut.jsx(wWt,{disabled:!r.allowEditing,transform:e,soup:t,cancelPanDrag:r.cancelPanDrag,onCreateEditEvent:r.onCreateEditEvent,onModifyEditEvent:r.onModifyEditEvent,children:ut.jsx(gWt,{transform:e,focusOnHover:r.focusOnHover,children:ut.jsx(HWt,{elements:t,children:ut.jsx(CWt,{transform:e,elements:t,children:ut.jsx(kWt,{transform:e,soup:t,children:ut.jsx(vWt,{transform:e,debugGraphics:r.debugGraphics,children:ut.jsx(yWt,{transform:e,elements:t,children:ut.jsx(mWt,{transform:e,primitives:s,width:r.width,height:r.height,grid:r.grid})})})})})})})})})})},VWt=Tc(Gf(400,300),Cb(40,-40)),GWt=({circuitJson:r,debugGraphics:e,height:t=600,initialState:n,allowEditing:i=!0,editEvents:a,onEditEventsChanged:o,focusOnHover:s=!1,clickToInteractEnabled:l=!1})=>{const[c,u]=mt.useState(!l),[f,p]=qse(),[v,x]=mt.useState(VWt),{ref:S,setTransform:E,cancelDrag:b}=WXt({transform:v,onSetTransform:x,enabled:c});let[C,O]=mt.useState([]);C=a??C;const U=mt.useRef(!1),q=mt.useRef(null),Y=`${(r==null?void 0:r.length)||0}_${(r==null?void 0:r.editCount)||0}`,Q=()=>{const he=(p==null?void 0:p.width)>0?p:{width:500,height:500},{center:ve,width:Te,height:Pe}=te.some(be=>be.type.startsWith("pcb_"))?FXt(te.filter(be=>be.type.startsWith("pcb_"))):{center:{x:0,y:0},width:.001,height:.001},Ee=Math.min((he.width??0)/Te,(he.height??0)/Pe,100)*.75,Ce=Tc(Gf((he.width??0)/2,(he.height??0)/2),Cb(Ee,-Ee,0,0),Gf(-ve.x,-ve.y));E(Ce)};mt.useEffect(()=>{p!=null&&p.width&&r&&r.length!==0&&(U.current||(Q(),U.current=!0))},[r,p]);const K=mt.useMemo(()=>(r==null?void 0:r.filter(he=>he.type.startsWith("pcb_")||he.type.startsWith("source_")))??[],[Y]),te=mt.useMemo(()=>fqt({circuitJson:K,editEvents:C}),[K,C]),J=he=>{O([...C,he]),o==null||o([...C,he])},fe=he=>{const ve=C.map(Te=>Te.edit_event_id===he.edit_event_id?{...Te,...he}:Te);O(ve),o==null||o(ve)};return ut.jsxs("div",{ref:S,style:{position:"relative"},children:[ut.jsx("div",{ref:f,children:ut.jsxs(HXt,{initialState:n,children:[ut.jsx(jWt,{transform:v,height:t,width:p.width,allowEditing:i,focusOnHover:s,cancelPanDrag:b,onCreateEditEvent:J,onModifyEditEvent:fe,grid:{spacing:1,view_window:{left:0,right:p.width||500,top:t,bottom:0}},elements:te,debugGraphics:e},p.width),ut.jsx(VXt,{})]})}),l&&!c&&ut.jsx("div",{onClick:()=>{u(!0),Q()},onTouchStart:he=>{const ve=he.touches[0];q.current={x:ve.clientX,y:ve.clientY}},onTouchEnd:he=>{const ve=he.changedTouches[0],Te=q.current;if(!Te)return;const Pe=Math.abs(ve.clientX-Te.x),Ee=Math.abs(ve.clientY-Te.y);Pe<10&&Ee<10&&(he.preventDefault(),u(!0),Q()),q.current=null},style:{position:"absolute",inset:0,cursor:"pointer",zIndex:z2.clickToInteractOverlay,display:"flex",alignItems:"center",justifyContent:"center",touchAction:"pan-x pan-y pinch-zoom"},children:ut.jsx("div",{style:{backgroundColor:"rgba(0, 0, 0, 0.8)",color:"white",padding:"12px 24px",borderRadius:"8px",fontSize:"16px",pointerEvents:"none"},children:typeof window<"u"&&("ontouchstart"in window||navigator.maxTouchPoints>0)?"Touch to Interact":"Click to Interact"})})]})};const qWt=({containerClassName:r,...e})=>{const t=mt.useRef(null),[n,i]=mt.useState(620);return mt.useLayoutEffect(()=>{const a=()=>{if(t.current){const s=t.current.clientHeight,l=window.innerHeight;i(Math.min(Math.max(s,620),l))}};a();const o=new ResizeObserver(a);return t.current&&o.observe(t.current),window.addEventListener("resize",a),()=>{o.disconnect(),window.removeEventListener("resize",a)}},[]),ut.jsx("div",{ref:t,className:r||"rf-w-full rf-h-full",children:ut.jsx(GWt,{...e,height:n})})},$Wt='*,:after,:before{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }/*! tailwindcss v3.4.17 | MIT License | https://tailwindcss.com*/*,:after,:before{border:0 solid #e5e7eb;box-sizing:border-box}:after,:before{--tw-content:""}:host,html{line-height:1.5;-webkit-text-size-adjust:100%;font-family:ui-sans-serif,system-ui,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;font-feature-settings:normal;font-variation-settings:normal;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-tap-highlight-color:transparent}body{line-height:inherit;margin:0}hr{border-top-width:1px;color:inherit;height:0}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,pre,samp{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-size:1em;font-variation-settings:normal}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{border-collapse:collapse;border-color:inherit;text-indent:0}button,input,optgroup,select,textarea{color:inherit;font-family:inherit;font-feature-settings:inherit;font-size:100%;font-variation-settings:inherit;font-weight:inherit;letter-spacing:inherit;line-height:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dd,dl,figure,h1,h2,h3,h4,h5,h6,hr,p,pre{margin:0}fieldset{margin:0}fieldset,legend{padding:0}menu,ol,ul{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{color:#9ca3af;opacity:1}input::placeholder,textarea::placeholder{color:#9ca3af;opacity:1}[role=button],button{cursor:pointer}:disabled{cursor:default}audio,canvas,embed,iframe,img,object,svg,video{display:block;vertical-align:middle}img,video{height:auto;max-width:100%}[hidden]:where(:not([hidden=until-found])){display:none}:root{--radius:0.5rem}.rf-pointer-events-none{pointer-events:none}.rf-invisible{visibility:hidden}.rf-fixed{position:fixed}.rf-absolute{position:absolute}.rf-relative{position:relative}.rf-inset-0{inset:0}.-rf-left-2{left:-.5rem}.-rf-right-10{right:-2.5rem}.-rf-right-2{right:-.5rem}.-rf-right-4{right:-1rem}.-rf-right-6{right:-1.5rem}.-rf-right-7{right:-1.75rem}.-rf-right-8{right:-2rem}.-rf-right-9{right:-2.25rem}.rf-bottom-full{bottom:100%}.rf-left-0{left:0}.rf-left-1{left:.25rem}.rf-left-1\\/2{left:50%}.rf-left-2{left:.5rem}.rf-left-\\[50\\%\\]{left:50%}.rf-right-0{right:0}.rf-right-4{right:1rem}.rf-right-\\[4px\\]{right:4px}.rf-top-0{top:0}.rf-top-1{top:.25rem}.rf-top-2{top:.5rem}.rf-top-2\\.5{top:.625rem}.rf-top-\\[50\\%\\]{top:50%}.rf-top-\\[6px\\]{top:6px}.rf-z-50{z-index:50}.rf-z-\\[100\\]{z-index:100}.-rf-mx-1,.rf--mx-1{margin-left:-.25rem;margin-right:-.25rem}.rf-mx-1{margin-left:.25rem;margin-right:.25rem}.rf-mx-2{margin-left:.5rem;margin-right:.5rem}.rf-mx-auto{margin-left:auto;margin-right:auto}.rf-my-1{margin-bottom:.25rem;margin-top:.25rem}.rf-my-12{margin-bottom:3rem;margin-top:3rem}.rf-my-4{margin-bottom:1rem;margin-top:1rem}.rf-my-auto{margin-bottom:auto;margin-top:auto}.rf-mb-1{margin-bottom:.25rem}.rf-mb-12{margin-bottom:3rem}.rf-mb-2{margin-bottom:.5rem}.rf-mb-3{margin-bottom:.75rem}.rf-mb-4{margin-bottom:1rem}.rf-mb-6{margin-bottom:1.5rem}.rf-mb-8{margin-bottom:2rem}.rf-ml-1{margin-left:.25rem}.rf-ml-2{margin-left:.5rem}.rf-ml-auto{margin-left:auto}.rf-mr-1{margin-right:.25rem}.rf-mr-2{margin-right:.5rem}.rf-mt-0{margin-top:0}.rf-mt-0\\.5{margin-top:.125rem}.rf-mt-1{margin-top:.25rem}.rf-mt-2{margin-top:.5rem}.rf-mt-3{margin-top:.75rem}.rf-mt-4{margin-top:1rem}.rf-mt-5{margin-top:1.25rem}.rf-mt-auto{margin-top:auto}.rf-block{display:block}.rf-inline{display:inline}.rf-flex{display:flex}.rf-inline-flex{display:inline-flex}.rf-grid{display:grid}.rf-hidden{display:none}.rf-aspect-square{aspect-ratio:1/1}.rf-aspect-video{aspect-ratio:16/9}.rf-size-14{height:3.5rem;width:3.5rem}.rf-size-4{height:1rem;width:1rem}.\\!rf-h-2{height:.5rem!important}.\\!rf-h-2\\.5{height:.625rem!important}.\\!rf-h-3{height:.75rem!important}.\\!rf-h-full{height:100%!important}.rf-h-1{height:.25rem}.rf-h-10{height:2.5rem}.rf-h-12{height:3rem}.rf-h-2{height:.5rem}.rf-h-2\\.5{height:.625rem}.rf-h-3{height:.75rem}.rf-h-3\\.5{height:.875rem}.rf-h-4{height:1rem}.rf-h-5{height:1.25rem}.rf-h-6{height:1.5rem}.rf-h-60{height:15rem}.rf-h-64{height:16rem}.rf-h-8{height:2rem}.rf-h-9{height:2.25rem}.rf-h-\\[620px\\]{height:620px}.rf-h-\\[calc\\(100vh-52px\\)\\]{height:calc(100vh - 52px)}.rf-h-\\[calc\\(100vh-96px\\)\\]{height:calc(100vh - 96px)}.rf-h-\\[var\\(--radix-select-trigger-height\\)\\]{height:var(--radix-select-trigger-height)}.rf-h-fit{height:-moz-fit-content;height:fit-content}.rf-h-full{height:100%}.rf-h-px{height:1px}.\\!rf-max-h-\\[40vh\\]{max-height:40vh!important}.\\!rf-max-h-\\[70\\%\\]{max-height:70%!important}.rf-max-h-32{max-height:8rem}.rf-max-h-96{max-height:24rem}.rf-max-h-\\[500px\\]{max-height:500px}.rf-max-h-\\[90vh\\]{max-height:90vh}.rf-min-h-0{min-height:0}.rf-min-h-\\[200px\\]{min-height:200px}.rf-min-h-\\[620px\\]{min-height:620px}.rf-min-h-\\[calc\\(100vh-240px\\)\\]{min-height:calc(100vh - 240px)}.\\!rf-w-2{width:.5rem!important}.\\!rf-w-2\\.5{width:.625rem!important}.rf-w-1{width:.25rem}.rf-w-1\\/2{width:50%}.rf-w-11{width:2.75rem}.rf-w-11\\/12{width:91.666667%}.rf-w-12{width:3rem}.rf-w-16{width:4rem}.rf-w-2{width:.5rem}.rf-w-2\\.5{width:.625rem}.rf-w-3{width:.75rem}.rf-w-3\\.5{width:.875rem}.rf-w-32{width:8rem}.rf-w-4{width:1rem}.rf-w-5{width:1.25rem}.rf-w-6{width:1.5rem}.rf-w-64{width:16rem}.rf-w-72{width:18rem}.rf-w-8{width:2rem}.rf-w-9{width:2.25rem}.rf-w-96{width:24rem}.rf-w-\\[95\\%\\]{width:95%}.rf-w-fit{width:-moz-fit-content;width:fit-content}.rf-w-full{width:100%}.rf-min-w-10{min-width:2.5rem}.rf-min-w-16{min-width:4rem}.rf-min-w-\\[148px\\]{min-width:148px}.rf-min-w-\\[8rem\\]{min-width:8rem}.rf-min-w-\\[var\\(--radix-select-trigger-width\\)\\]{min-width:var(--radix-select-trigger-width)}.\\!rf-max-w-\\[60vw\\]{max-width:60vw!important}.\\!rf-max-w-\\[660px\\]{max-width:660px!important}.rf-max-w-2xl{max-width:42rem}.rf-max-w-3xl{max-width:48rem}.rf-max-w-5xl{max-width:64rem}.rf-max-w-full{max-width:100%}.rf-max-w-lg{max-width:32rem}.rf-max-w-md{max-width:28rem}.rf-max-w-xl{max-width:36rem}.rf-flex-1{flex:1 1 0%}.rf-flex-shrink-0,.rf-shrink-0{flex-shrink:0}.rf-flex-grow{flex-grow:1}.rf-table-auto{table-layout:auto}.-rf-translate-x-1{--tw-translate-x:-0.25rem}.-rf-translate-x-1,.-rf-translate-x-1\\/2{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-rf-translate-x-1\\/2{--tw-translate-x:-50%}.-rf-translate-y-1{--tw-translate-y:-0.25rem}.-rf-translate-y-1,.rf--translate-x-1{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rf--translate-x-1{--tw-translate-x:-0.25rem}.rf-translate-x-\\[-50\\%\\]{--tw-translate-x:-50%}.rf-translate-x-\\[-50\\%\\],.rf-translate-y-\\[-50\\%\\]{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rf-translate-y-\\[-50\\%\\]{--tw-translate-y:-50%}.rf-transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes rf-pulse{50%{opacity:.5}}.rf-animate-pulse{animation:rf-pulse 2s cubic-bezier(.4,0,.6,1) infinite}@keyframes rf-spin{to{transform:rotate(1turn)}}.rf-animate-spin{animation:rf-spin 1s linear infinite}.rf-cursor-default{cursor:default}.rf-cursor-not-allowed{cursor:not-allowed}.rf-cursor-pointer{cursor:pointer}.rf-select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.rf-grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.rf-grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.rf-flex-row{flex-direction:row}.rf-flex-col{flex-direction:column}.rf-flex-col-reverse{flex-direction:column-reverse}.rf-flex-wrap{flex-wrap:wrap}.rf-place-items-center{place-items:center}.rf-items-start{align-items:flex-start}.rf-items-end{align-items:flex-end}.rf-items-center{align-items:center}.rf-justify-end{justify-content:flex-end}.rf-justify-center{justify-content:center}.rf-justify-between{justify-content:space-between}.rf-gap-0{gap:0}.rf-gap-1{gap:.25rem}.rf-gap-2{gap:.5rem}.rf-gap-3{gap:.75rem}.rf-gap-4{gap:1rem}.rf-gap-5{gap:1.25rem}.rf-gap-6{gap:1.5rem}.rf-gap-8{gap:2rem}.rf-space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse:0;margin-left:calc(.5rem*(1 - var(--tw-space-x-reverse)));margin-right:calc(.5rem*var(--tw-space-x-reverse))}.rf-space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(.5rem*var(--tw-space-y-reverse));margin-top:calc(.5rem*(1 - var(--tw-space-y-reverse)))}.rf-space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(1rem*var(--tw-space-y-reverse));margin-top:calc(1rem*(1 - var(--tw-space-y-reverse)))}.rf-space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(1.5rem*var(--tw-space-y-reverse));margin-top:calc(1.5rem*(1 - var(--tw-space-y-reverse)))}.rf-divide-y>:not([hidden])~:not([hidden]){--tw-divide-y-reverse:0;border-bottom-width:calc(1px*var(--tw-divide-y-reverse));border-top-width:calc(1px*(1 - var(--tw-divide-y-reverse)))}.rf-overflow-auto{overflow:auto}.rf-overflow-hidden{overflow:hidden}.rf-overflow-visible{overflow:visible}.rf-overflow-x-auto{overflow-x:auto}.\\!rf-overflow-y-auto{overflow-y:auto!important}.rf-overflow-y-auto{overflow-y:auto}.\\!rf-overflow-x-hidden{overflow-x:hidden!important}.rf-overflow-x-hidden{overflow-x:hidden}.rf-overflow-x-clip{overflow-x:clip}.rf-truncate{overflow:hidden;text-overflow:ellipsis}.rf-truncate,.rf-whitespace-nowrap{white-space:nowrap}.rf-whitespace-pre-wrap{white-space:pre-wrap}.rf-break-words{overflow-wrap:break-word}.rf-rounded{border-radius:.25rem}.rf-rounded-2xl{border-radius:1rem}.rf-rounded-full{border-radius:9999px}.rf-rounded-lg{border-radius:var(--radius)}.rf-rounded-md{border-radius:calc(var(--radius) - 2px)}.rf-rounded-sm{border-radius:calc(var(--radius) - 4px)}.rf-rounded-xl{border-radius:.75rem}.rf-border{border-width:1px}.rf-border-b{border-bottom-width:1px}.rf-border-t{border-top-width:1px}.rf-border-blue-200{--tw-border-opacity:1;border-color:rgb(191 219 254/var(--tw-border-opacity,1))}.rf-border-blue-500{--tw-border-opacity:1;border-color:rgb(59 130 246/var(--tw-border-opacity,1))}.rf-border-blue-600{--tw-border-opacity:1;border-color:rgb(37 99 235/var(--tw-border-opacity,1))}.rf-border-gray-200{--tw-border-opacity:1;border-color:rgb(229 231 235/var(--tw-border-opacity,1))}.rf-border-gray-300{--tw-border-opacity:1;border-color:rgb(209 213 219/var(--tw-border-opacity,1))}.rf-border-green-200{--tw-border-opacity:1;border-color:rgb(187 247 208/var(--tw-border-opacity,1))}.rf-border-input{border-color:hsl(var(--input))}.rf-border-neutral-200{--tw-border-opacity:1;border-color:rgb(229 229 229/var(--tw-border-opacity,1))}.rf-border-primary{border-color:hsl(var(--primary))}.rf-border-red-200{--tw-border-opacity:1;border-color:rgb(254 202 202/var(--tw-border-opacity,1))}.rf-border-red-500{--tw-border-opacity:1;border-color:rgb(239 68 68/var(--tw-border-opacity,1))}.rf-border-zinc-200{--tw-border-opacity:1;border-color:rgb(228 228 231/var(--tw-border-opacity,1))}.rf-border-zinc-900{--tw-border-opacity:1;border-color:rgb(24 24 27/var(--tw-border-opacity,1))}.rf-bg-background{background-color:hsl(var(--background))}.rf-bg-black{--tw-bg-opacity:1;background-color:rgb(0 0 0/var(--tw-bg-opacity,1))}.rf-bg-black\\/80{background-color:rgba(0,0,0,.8)}.rf-bg-blue-100{--tw-bg-opacity:1;background-color:rgb(219 234 254/var(--tw-bg-opacity,1))}.rf-bg-blue-50{--tw-bg-opacity:1;background-color:rgb(239 246 255/var(--tw-bg-opacity,1))}.rf-bg-blue-500{--tw-bg-opacity:1;background-color:rgb(59 130 246/var(--tw-bg-opacity,1))}.rf-bg-blue-600{--tw-bg-opacity:1;background-color:rgb(37 99 235/var(--tw-bg-opacity,1))}.rf-bg-gray-100{--tw-bg-opacity:1;background-color:rgb(243 244 246/var(--tw-bg-opacity,1))}.rf-bg-gray-200{--tw-bg-opacity:1;background-color:rgb(229 231 235/var(--tw-bg-opacity,1))}.rf-bg-gray-300{--tw-bg-opacity:1;background-color:rgb(209 213 219/var(--tw-bg-opacity,1))}.rf-bg-gray-400{--tw-bg-opacity:1;background-color:rgb(156 163 175/var(--tw-bg-opacity,1))}.rf-bg-gray-50{--tw-bg-opacity:1;background-color:rgb(249 250 251/var(--tw-bg-opacity,1))}.rf-bg-gray-500{--tw-bg-opacity:1;background-color:rgb(107 114 128/var(--tw-bg-opacity,1))}.rf-bg-gray-700{--tw-bg-opacity:1;background-color:rgb(55 65 81/var(--tw-bg-opacity,1))}.rf-bg-gray-800{--tw-bg-opacity:1;background-color:rgb(31 41 55/var(--tw-bg-opacity,1))}.rf-bg-gray-900{--tw-bg-opacity:1;background-color:rgb(17 24 39/var(--tw-bg-opacity,1))}.rf-bg-green-100{--tw-bg-opacity:1;background-color:rgb(220 252 231/var(--tw-bg-opacity,1))}.rf-bg-green-50{--tw-bg-opacity:1;background-color:rgb(240 253 244/var(--tw-bg-opacity,1))}.rf-bg-muted{background-color:hsl(var(--muted))}.rf-bg-neutral-100{--tw-bg-opacity:1;background-color:rgb(245 245 245/var(--tw-bg-opacity,1))}.rf-bg-neutral-50{--tw-bg-opacity:1;background-color:rgb(250 250 250/var(--tw-bg-opacity,1))}.rf-bg-neutral-800{--tw-bg-opacity:1;background-color:rgb(38 38 38/var(--tw-bg-opacity,1))}.rf-bg-neutral-900{--tw-bg-opacity:1;background-color:rgb(23 23 23/var(--tw-bg-opacity,1))}.rf-bg-orange-400{--tw-bg-opacity:1;background-color:rgb(251 146 60/var(--tw-bg-opacity,1))}.rf-bg-popover{background-color:hsl(var(--popover))}.rf-bg-red-100{--tw-bg-opacity:1;background-color:rgb(254 226 226/var(--tw-bg-opacity,1))}.rf-bg-red-50{--tw-bg-opacity:1;background-color:rgb(254 242 242/var(--tw-bg-opacity,1))}.rf-bg-red-500{--tw-bg-opacity:1;background-color:rgb(239 68 68/var(--tw-bg-opacity,1))}.rf-bg-red-900{--tw-bg-opacity:1;background-color:rgb(127 29 29/var(--tw-bg-opacity,1))}.rf-bg-white{--tw-bg-opacity:1;background-color:rgb(255 255 255/var(--tw-bg-opacity,1))}.rf-bg-yellow-100{--tw-bg-opacity:1;background-color:rgb(254 249 195/var(--tw-bg-opacity,1))}.rf-bg-zinc-100{--tw-bg-opacity:1;background-color:rgb(244 244 245/var(--tw-bg-opacity,1))}.rf-bg-zinc-200{--tw-bg-opacity:1;background-color:rgb(228 228 231/var(--tw-bg-opacity,1))}.rf-bg-zinc-50{--tw-bg-opacity:1;background-color:rgb(250 250 250/var(--tw-bg-opacity,1))}.rf-bg-zinc-800{--tw-bg-opacity:1;background-color:rgb(39 39 42/var(--tw-bg-opacity,1))}.rf-bg-zinc-900{--tw-bg-opacity:1;background-color:rgb(24 24 27/var(--tw-bg-opacity,1))}.rf-bg-opacity-50{--tw-bg-opacity:0.5}.rf-fill-current{fill:currentColor}.rf-object-contain{-o-object-fit:contain;object-fit:contain}.\\!rf-p-0{padding:0!important}.rf-p-0{padding:0}.rf-p-1{padding:.25rem}.rf-p-2{padding:.5rem}.rf-p-3{padding:.75rem}.rf-p-4{padding:1rem}.rf-p-5{padding:1.25rem}.rf-p-6{padding:1.5rem}.rf-p-8{padding:2rem}.rf-px-1{padding-left:.25rem;padding-right:.25rem}.rf-px-2{padding-left:.5rem;padding-right:.5rem}.rf-px-3{padding-left:.75rem;padding-right:.75rem}.rf-px-4{padding-left:1rem;padding-right:1rem}.rf-px-6{padding-left:1.5rem;padding-right:1.5rem}.rf-px-8{padding-left:2rem;padding-right:2rem}.rf-py-0{padding-bottom:0;padding-top:0}.rf-py-0\\.5{padding-bottom:.125rem;padding-top:.125rem}.rf-py-1{padding-bottom:.25rem;padding-top:.25rem}.rf-py-1\\.5{padding-bottom:.375rem;padding-top:.375rem}.rf-py-10{padding-bottom:2.5rem;padding-top:2.5rem}.rf-py-12{padding-bottom:3rem;padding-top:3rem}.rf-py-2{padding-bottom:.5rem;padding-top:.5rem}.rf-py-3{padding-bottom:.75rem;padding-top:.75rem}.rf-py-4{padding-bottom:1rem;padding-top:1rem}.rf-py-8{padding-bottom:2rem;padding-top:2rem}.rf-pb-0{padding-bottom:0}.rf-pb-2{padding-bottom:.5rem}.rf-pb-3{padding-bottom:.75rem}.rf-pb-4{padding-bottom:1rem}.rf-pl-2{padding-left:.5rem}.rf-pl-4{padding-left:1rem}.rf-pl-8{padding-left:2rem}.rf-pr-2{padding-right:.5rem}.rf-pt-2{padding-top:.5rem}.rf-pt-4{padding-top:1rem}.rf-text-left{text-align:left}.rf-text-center{text-align:center}.rf-text-right{text-align:right}.rf-font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.rf-text-2xl{font-size:1.5rem;line-height:2rem}.rf-text-3xl{font-size:1.875rem;line-height:2.25rem}.rf-text-\\[8px\\]{font-size:8px}.rf-text-base{font-size:1rem;line-height:1.5rem}.rf-text-lg{font-size:1.125rem;line-height:1.75rem}.rf-text-sm{font-size:.875rem;line-height:1.25rem}.rf-text-xl{font-size:1.25rem;line-height:1.75rem}.rf-text-xs{font-size:.75rem;line-height:1rem}.rf-font-bold{font-weight:700}.rf-font-medium{font-weight:500}.rf-font-semibold{font-weight:600}.rf-capitalize{text-transform:capitalize}.rf-tabular-nums{--tw-numeric-spacing:tabular-nums;font-variant-numeric:var(--tw-ordinal) var(--tw-slashed-zero) var(--tw-numeric-figure) var(--tw-numeric-spacing) var(--tw-numeric-fraction)}.rf-leading-5{line-height:1.25rem}.rf-leading-none{line-height:1}.rf-leading-tight{line-height:1.25}.rf-tracking-widest{letter-spacing:.1em}.rf-text-black{--tw-text-opacity:1;color:rgb(0 0 0/var(--tw-text-opacity,1))}.rf-text-blue-500{--tw-text-opacity:1;color:rgb(59 130 246/var(--tw-text-opacity,1))}.rf-text-blue-600{--tw-text-opacity:1;color:rgb(37 99 235/var(--tw-text-opacity,1))}.rf-text-blue-700{--tw-text-opacity:1;color:rgb(29 78 216/var(--tw-text-opacity,1))}.rf-text-blue-800{--tw-text-opacity:1;color:rgb(30 64 175/var(--tw-text-opacity,1))}.rf-text-blue-900{--tw-text-opacity:1;color:rgb(30 58 138/var(--tw-text-opacity,1))}.rf-text-current{color:currentColor}.rf-text-gray-400{--tw-text-opacity:1;color:rgb(156 163 175/var(--tw-text-opacity,1))}.rf-text-gray-500{--tw-text-opacity:1;color:rgb(107 114 128/var(--tw-text-opacity,1))}.rf-text-gray-600{--tw-text-opacity:1;color:rgb(75 85 99/var(--tw-text-opacity,1))}.rf-text-gray-700{--tw-text-opacity:1;color:rgb(55 65 81/var(--tw-text-opacity,1))}.rf-text-gray-800{--tw-text-opacity:1;color:rgb(31 41 55/var(--tw-text-opacity,1))}.rf-text-gray-900{--tw-text-opacity:1;color:rgb(17 24 39/var(--tw-text-opacity,1))}.rf-text-green-500{--tw-text-opacity:1;color:rgb(34 197 94/var(--tw-text-opacity,1))}.rf-text-green-600{--tw-text-opacity:1;color:rgb(22 163 74/var(--tw-text-opacity,1))}.rf-text-green-700{--tw-text-opacity:1;color:rgb(21 128 61/var(--tw-text-opacity,1))}.rf-text-green-800{--tw-text-opacity:1;color:rgb(22 101 52/var(--tw-text-opacity,1))}.rf-text-green-900{--tw-text-opacity:1;color:rgb(20 83 45/var(--tw-text-opacity,1))}.rf-text-muted-foreground{color:hsl(var(--muted-foreground))}.rf-text-neutral-50{--tw-text-opacity:1;color:rgb(250 250 250/var(--tw-text-opacity,1))}.rf-text-neutral-500{--tw-text-opacity:1;color:rgb(115 115 115/var(--tw-text-opacity,1))}.rf-text-neutral-900{--tw-text-opacity:1;color:rgb(23 23 23/var(--tw-text-opacity,1))}.rf-text-neutral-950{--tw-text-opacity:1;color:rgb(10 10 10/var(--tw-text-opacity,1))}.rf-text-popover-foreground{color:hsl(var(--popover-foreground))}.rf-text-red-200{--tw-text-opacity:1;color:rgb(254 202 202/var(--tw-text-opacity,1))}.rf-text-red-300{--tw-text-opacity:1;color:rgb(252 165 165/var(--tw-text-opacity,1))}.rf-text-red-400{--tw-text-opacity:1;color:rgb(248 113 113/var(--tw-text-opacity,1))}.rf-text-red-500{--tw-text-opacity:1;color:rgb(239 68 68/var(--tw-text-opacity,1))}.rf-text-red-600{--tw-text-opacity:1;color:rgb(220 38 38/var(--tw-text-opacity,1))}.rf-text-red-700{--tw-text-opacity:1;color:rgb(185 28 28/var(--tw-text-opacity,1))}.rf-text-red-800{--tw-text-opacity:1;color:rgb(153 27 27/var(--tw-text-opacity,1))}.rf-text-red-900{--tw-text-opacity:1;color:rgb(127 29 29/var(--tw-text-opacity,1))}.rf-text-white{--tw-text-opacity:1;color:rgb(255 255 255/var(--tw-text-opacity,1))}.rf-text-yellow-400{--tw-text-opacity:1;color:rgb(250 204 21/var(--tw-text-opacity,1))}.rf-text-yellow-500{--tw-text-opacity:1;color:rgb(234 179 8/var(--tw-text-opacity,1))}.rf-text-yellow-900{--tw-text-opacity:1;color:rgb(113 63 18/var(--tw-text-opacity,1))}.rf-text-zinc-200{--tw-text-opacity:1;color:rgb(228 228 231/var(--tw-text-opacity,1))}.rf-text-zinc-300{--tw-text-opacity:1;color:rgb(212 212 216/var(--tw-text-opacity,1))}.rf-text-zinc-400{--tw-text-opacity:1;color:rgb(161 161 170/var(--tw-text-opacity,1))}.rf-text-zinc-50{--tw-text-opacity:1;color:rgb(250 250 250/var(--tw-text-opacity,1))}.rf-text-zinc-500{--tw-text-opacity:1;color:rgb(113 113 122/var(--tw-text-opacity,1))}.rf-text-zinc-900{--tw-text-opacity:1;color:rgb(24 24 27/var(--tw-text-opacity,1))}.rf-text-zinc-950{--tw-text-opacity:1;color:rgb(9 9 11/var(--tw-text-opacity,1))}.rf-underline{text-decoration-line:underline}.rf-line-through{text-decoration-line:line-through}.rf-underline-offset-4{text-underline-offset:4px}.rf-opacity-0{opacity:0}.rf-opacity-25{opacity:.25}.rf-opacity-30{opacity:.3}.rf-opacity-50{opacity:.5}.rf-opacity-60{opacity:.6}.rf-opacity-75{opacity:.75}.rf-shadow{--tw-shadow:0 1px 3px 0 rgba(0,0,0,.1),0 1px 2px -1px rgba(0,0,0,.1);--tw-shadow-colored:0 1px 3px 0 var(--tw-shadow-color),0 1px 2px -1px var(--tw-shadow-color)}.rf-shadow,.rf-shadow-lg{box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.rf-shadow-lg{--tw-shadow:0 10px 15px -3px rgba(0,0,0,.1),0 4px 6px -4px rgba(0,0,0,.1);--tw-shadow-colored:0 10px 15px -3px var(--tw-shadow-color),0 4px 6px -4px var(--tw-shadow-color)}.rf-shadow-md{--tw-shadow:0 4px 6px -1px rgba(0,0,0,.1),0 2px 4px -2px rgba(0,0,0,.1);--tw-shadow-colored:0 4px 6px -1px var(--tw-shadow-color),0 2px 4px -2px var(--tw-shadow-color)}.rf-shadow-md,.rf-shadow-sm{box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.rf-shadow-sm{--tw-shadow:0 1px 2px 0 rgba(0,0,0,.05);--tw-shadow-colored:0 1px 2px 0 var(--tw-shadow-color)}.rf-outline-none{outline:2px solid transparent;outline-offset:2px}.rf-ring-2{--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow,0 0 #0000)}.rf-ring-blue-500{--tw-ring-opacity:1;--tw-ring-color:rgb(59 130 246/var(--tw-ring-opacity,1))}.rf-ring-primary{--tw-ring-color:hsl(var(--primary))}.rf-ring-offset-background{--tw-ring-offset-color:hsl(var(--background))}.rf-ring-offset-white{--tw-ring-offset-color:#fff}.rf-transition{transition-duration:.15s;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,-webkit-backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter,-webkit-backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1)}.rf-transition-all{transition-duration:.15s;transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1)}.rf-transition-colors{transition-duration:.15s;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1)}.rf-transition-opacity{transition-duration:.15s;transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1)}.rf-duration-200{transition-duration:.2s}.rf-ease-in-out{transition-timing-function:cubic-bezier(.4,0,.2,1)}@keyframes enter{0%{opacity:var(--tw-enter-opacity,1);transform:translate3d(var(--tw-enter-translate-x,0),var(--tw-enter-translate-y,0),0) scale3d(var(--tw-enter-scale,1),var(--tw-enter-scale,1),var(--tw-enter-scale,1)) rotate(var(--tw-enter-rotate,0))}}@keyframes exit{to{opacity:var(--tw-exit-opacity,1);transform:translate3d(var(--tw-exit-translate-x,0),var(--tw-exit-translate-y,0),0) scale3d(var(--tw-exit-scale,1),var(--tw-exit-scale,1),var(--tw-exit-scale,1)) rotate(var(--tw-exit-rotate,0))}}.rf-slide-in-from-left-1{--tw-enter-translate-x:-0.25rem}.rf-slide-out-to-left-1{--tw-exit-translate-x:-0.25rem}.rf-duration-200{animation-duration:.2s}.rf-ease-in-out{animation-timing-function:cubic-bezier(.4,0,.2,1)}.file\\:rf-border-0::file-selector-button{border-width:0}.file\\:rf-bg-transparent::file-selector-button{background-color:transparent}.file\\:rf-text-sm::file-selector-button{font-size:.875rem;line-height:1.25rem}.file\\:rf-font-medium::file-selector-button{font-weight:500}.placeholder\\:rf-text-zinc-500::-moz-placeholder{--tw-text-opacity:1;color:rgb(113 113 122/var(--tw-text-opacity,1))}.placeholder\\:rf-text-zinc-500::placeholder{--tw-text-opacity:1;color:rgb(113 113 122/var(--tw-text-opacity,1))}.hover\\:rf-border-blue-300:hover{--tw-border-opacity:1;border-color:rgb(147 197 253/var(--tw-border-opacity,1))}.hover\\:\\!rf-bg-transparent:hover{background-color:transparent!important}.hover\\:rf-bg-blue-700:hover{--tw-bg-opacity:1;background-color:rgb(29 78 216/var(--tw-bg-opacity,1))}.hover\\:rf-bg-red-500\\/90:hover{background-color:rgba(239,68,68,.9)}.hover\\:rf-bg-zinc-100:hover{--tw-bg-opacity:1;background-color:rgb(244 244 245/var(--tw-bg-opacity,1))}.hover\\:rf-bg-zinc-100\\/80:hover{background-color:hsla(240,5%,96%,.8)}.hover\\:rf-bg-zinc-900\\/90:hover{background-color:rgba(24,24,27,.9)}.hover\\:rf-text-red-400:hover{--tw-text-opacity:1;color:rgb(248 113 113/var(--tw-text-opacity,1))}.hover\\:rf-text-zinc-900:hover{--tw-text-opacity:1;color:rgb(24 24 27/var(--tw-text-opacity,1))}.hover\\:rf-underline:hover{text-decoration-line:underline}.focus\\:rf-bg-gray-100:focus{--tw-bg-opacity:1;background-color:rgb(243 244 246/var(--tw-bg-opacity,1))}.focus\\:rf-bg-zinc-100:focus{--tw-bg-opacity:1;background-color:rgb(244 244 245/var(--tw-bg-opacity,1))}.focus\\:rf-text-gray-900:focus{--tw-text-opacity:1;color:rgb(17 24 39/var(--tw-text-opacity,1))}.focus\\:rf-text-zinc-900:focus{--tw-text-opacity:1;color:rgb(24 24 27/var(--tw-text-opacity,1))}.focus\\:rf-outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\\:rf-ring-2:focus{--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow,0 0 #0000)}.focus\\:rf-ring-ring:focus{--tw-ring-color:hsl(var(--ring))}.focus\\:rf-ring-offset-2:focus{--tw-ring-offset-width:2px}.focus-visible\\:rf-outline-none:focus-visible{outline:2px solid transparent;outline-offset:2px}.focus-visible\\:rf-ring-1:focus-visible{--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow,0 0 #0000)}.focus-visible\\:rf-ring-2:focus-visible{--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow,0 0 #0000)}.focus-visible\\:rf-ring-zinc-950:focus-visible{--tw-ring-opacity:1;--tw-ring-color:rgb(9 9 11/var(--tw-ring-opacity,1))}.focus-visible\\:rf-ring-offset-2:focus-visible{--tw-ring-offset-width:2px}.disabled\\:rf-pointer-events-none:disabled{pointer-events:none}.disabled\\:rf-cursor-not-allowed:disabled{cursor:not-allowed}.disabled\\:rf-opacity-50:disabled{opacity:.5}.rf-group\\/bar:hover .group-hover\\/bar\\:rf-opacity-100{opacity:1}.data-\\[disabled\\]\\:rf-pointer-events-none[data-disabled]{pointer-events:none}.data-\\[side\\=bottom\\]\\:rf-translate-y-1[data-side=bottom]{--tw-translate-y:0.25rem}.data-\\[side\\=bottom\\]\\:rf-translate-y-1[data-side=bottom],.data-\\[side\\=left\\]\\:-rf-translate-x-1[data-side=left]{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\\[side\\=left\\]\\:-rf-translate-x-1[data-side=left]{--tw-translate-x:-0.25rem}.data-\\[side\\=right\\]\\:rf-translate-x-1[data-side=right]{--tw-translate-x:0.25rem}.data-\\[side\\=right\\]\\:rf-translate-x-1[data-side=right],.data-\\[side\\=top\\]\\:-rf-translate-y-1[data-side=top]{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\\[side\\=top\\]\\:-rf-translate-y-1[data-side=top]{--tw-translate-y:-0.25rem}.data-\\[state\\=active\\]\\:rf-bg-white[data-state=active]{--tw-bg-opacity:1;background-color:rgb(255 255 255/var(--tw-bg-opacity,1))}.data-\\[state\\=checked\\]\\:rf-bg-zinc-900[data-state=checked]{--tw-bg-opacity:1;background-color:rgb(24 24 27/var(--tw-bg-opacity,1))}.data-\\[state\\=open\\]\\:rf-bg-zinc-100[data-state=open]{--tw-bg-opacity:1;background-color:rgb(244 244 245/var(--tw-bg-opacity,1))}.data-\\[state\\=active\\]\\:rf-text-zinc-950[data-state=active]{--tw-text-opacity:1;color:rgb(9 9 11/var(--tw-text-opacity,1))}.data-\\[state\\=checked\\]\\:rf-text-zinc-50[data-state=checked]{--tw-text-opacity:1;color:rgb(250 250 250/var(--tw-text-opacity,1))}.data-\\[disabled\\]\\:rf-opacity-50[data-disabled]{opacity:.5}.data-\\[state\\=active\\]\\:rf-shadow[data-state=active]{--tw-shadow:0 1px 3px 0 rgba(0,0,0,.1),0 1px 2px -1px rgba(0,0,0,.1);--tw-shadow-colored:0 1px 3px 0 var(--tw-shadow-color),0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.data-\\[state\\=open\\]\\:rf-animate-in[data-state=open]{animation-duration:.15s;animation-name:enter;--tw-enter-opacity:initial;--tw-enter-scale:initial;--tw-enter-rotate:initial;--tw-enter-translate-x:initial;--tw-enter-translate-y:initial}.data-\\[state\\=closed\\]\\:rf-animate-out[data-state=closed]{animation-duration:.15s;animation-name:exit;--tw-exit-opacity:initial;--tw-exit-scale:initial;--tw-exit-rotate:initial;--tw-exit-translate-x:initial;--tw-exit-translate-y:initial}.data-\\[state\\=closed\\]\\:rf-fade-out-0[data-state=closed]{--tw-exit-opacity:0}.data-\\[state\\=open\\]\\:rf-fade-in-0[data-state=open]{--tw-enter-opacity:0}.data-\\[state\\=closed\\]\\:rf-zoom-out-95[data-state=closed]{--tw-exit-scale:.95}.data-\\[state\\=open\\]\\:rf-zoom-in-95[data-state=open]{--tw-enter-scale:.95}.data-\\[side\\=bottom\\]\\:rf-slide-in-from-top-2[data-side=bottom]{--tw-enter-translate-y:-0.5rem}.data-\\[side\\=left\\]\\:rf-slide-in-from-right-2[data-side=left]{--tw-enter-translate-x:0.5rem}.data-\\[side\\=right\\]\\:rf-slide-in-from-left-2[data-side=right]{--tw-enter-translate-x:-0.5rem}.data-\\[side\\=top\\]\\:rf-slide-in-from-bottom-2[data-side=top]{--tw-enter-translate-y:0.5rem}.data-\\[state\\=closed\\]\\:rf-slide-out-to-left-1\\/2[data-state=closed]{--tw-exit-translate-x:-50%}.data-\\[state\\=closed\\]\\:rf-slide-out-to-top-\\[48\\%\\][data-state=closed]{--tw-exit-translate-y:-48%}.data-\\[state\\=open\\]\\:rf-slide-in-from-left-1\\/2[data-state=open]{--tw-enter-translate-x:-50%}.data-\\[state\\=open\\]\\:rf-slide-in-from-top-\\[48\\%\\][data-state=open]{--tw-enter-translate-y:-48%}.dark\\:rf-border-zinc-50:is(.rf-dark *){--tw-border-opacity:1;border-color:rgb(250 250 250/var(--tw-border-opacity,1))}.dark\\:rf-border-zinc-800:is(.rf-dark *){--tw-border-opacity:1;border-color:rgb(39 39 42/var(--tw-border-opacity,1))}.dark\\:rf-bg-red-900:is(.rf-dark *){--tw-bg-opacity:1;background-color:rgb(127 29 29/var(--tw-bg-opacity,1))}.dark\\:rf-bg-zinc-50:is(.rf-dark *){--tw-bg-opacity:1;background-color:rgb(250 250 250/var(--tw-bg-opacity,1))}.dark\\:rf-bg-zinc-800:is(.rf-dark *){--tw-bg-opacity:1;background-color:rgb(39 39 42/var(--tw-bg-opacity,1))}.dark\\:rf-bg-zinc-950:is(.rf-dark *){--tw-bg-opacity:1;background-color:rgb(9 9 11/var(--tw-bg-opacity,1))}.dark\\:rf-text-zinc-400:is(.rf-dark *){--tw-text-opacity:1;color:rgb(161 161 170/var(--tw-text-opacity,1))}.dark\\:rf-text-zinc-50:is(.rf-dark *){--tw-text-opacity:1;color:rgb(250 250 250/var(--tw-text-opacity,1))}.dark\\:rf-text-zinc-900:is(.rf-dark *){--tw-text-opacity:1;color:rgb(24 24 27/var(--tw-text-opacity,1))}.dark\\:rf-placeholder-zinc-400:is(.rf-dark *)::-moz-placeholder{--tw-placeholder-opacity:1;color:rgb(161 161 170/var(--tw-placeholder-opacity,1))}.dark\\:rf-placeholder-zinc-400:is(.rf-dark *)::placeholder{--tw-placeholder-opacity:1;color:rgb(161 161 170/var(--tw-placeholder-opacity,1))}.dark\\:rf-ring-offset-zinc-950:is(.rf-dark *){--tw-ring-offset-color:#09090b}.dark\\:hover\\:rf-bg-red-900\\/90:hover:is(.rf-dark *){background-color:rgba(127,29,29,.9)}.dark\\:hover\\:rf-bg-zinc-50\\/90:hover:is(.rf-dark *){background-color:hsla(0,0%,98%,.9)}.dark\\:hover\\:rf-bg-zinc-800:hover:is(.rf-dark *){--tw-bg-opacity:1;background-color:rgb(39 39 42/var(--tw-bg-opacity,1))}.dark\\:hover\\:rf-bg-zinc-800\\/80:hover:is(.rf-dark *){background-color:rgba(39,39,42,.8)}.dark\\:hover\\:rf-text-zinc-50:hover:is(.rf-dark *){--tw-text-opacity:1;color:rgb(250 250 250/var(--tw-text-opacity,1))}.dark\\:focus\\:rf-bg-zinc-800:focus:is(.rf-dark *){--tw-bg-opacity:1;background-color:rgb(39 39 42/var(--tw-bg-opacity,1))}.dark\\:focus\\:rf-text-zinc-50:focus:is(.rf-dark *){--tw-text-opacity:1;color:rgb(250 250 250/var(--tw-text-opacity,1))}.dark\\:focus-visible\\:rf-ring-zinc-300:focus-visible:is(.rf-dark *){--tw-ring-opacity:1;--tw-ring-color:rgb(212 212 216/var(--tw-ring-opacity,1))}.dark\\:data-\\[state\\=active\\]\\:rf-bg-zinc-950[data-state=active]:is(.rf-dark *){--tw-bg-opacity:1;background-color:rgb(9 9 11/var(--tw-bg-opacity,1))}.dark\\:data-\\[state\\=checked\\]\\:rf-bg-zinc-50[data-state=checked]:is(.rf-dark *){--tw-bg-opacity:1;background-color:rgb(250 250 250/var(--tw-bg-opacity,1))}.dark\\:data-\\[state\\=open\\]\\:rf-bg-zinc-800[data-state=open]:is(.rf-dark *){--tw-bg-opacity:1;background-color:rgb(39 39 42/var(--tw-bg-opacity,1))}.dark\\:data-\\[state\\=active\\]\\:rf-text-zinc-50[data-state=active]:is(.rf-dark *){--tw-text-opacity:1;color:rgb(250 250 250/var(--tw-text-opacity,1))}.dark\\:data-\\[state\\=checked\\]\\:rf-text-zinc-900[data-state=checked]:is(.rf-dark *){--tw-text-opacity:1;color:rgb(24 24 27/var(--tw-text-opacity,1))}@media (min-width:640px){.sm\\:rf-mt-0{margin-top:0}.sm\\:rf-flex-row{flex-direction:row}.sm\\:rf-justify-end{justify-content:flex-end}.sm\\:rf-space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse:0;margin-left:calc(.5rem*(1 - var(--tw-space-x-reverse)));margin-right:calc(.5rem*var(--tw-space-x-reverse))}.sm\\:rf-rounded-lg{border-radius:var(--radius)}.sm\\:rf-text-left{text-align:left}}@media (min-width:768px){.md\\:rf-grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}}.\\[\\&\\>span\\]\\:rf-line-clamp-1>span{display:-webkit-box;overflow:hidden;-webkit-box-orient:vertical;-webkit-line-clamp:1}.\\[\\&\\>svg\\]\\:rf-size-4>svg{height:1rem;width:1rem}.\\[\\&\\>svg\\]\\:rf-shrink-0>svg{flex-shrink:0}.\\[\\&\\>svg\\]\\:rf-text-red-300>svg{--tw-text-opacity:1;color:rgb(252 165 165/var(--tw-text-opacity,1))}.\\[\\&\\>svg\\]\\:hover\\:rf-text-red-400:hover>svg{--tw-text-opacity:1;color:rgb(248 113 113/var(--tw-text-opacity,1))}.\\[\\&_svg\\]\\:rf-pointer-events-none svg{pointer-events:none}.\\[\\&_svg\\]\\:rf-size-4 svg{height:1rem;width:1rem}.\\[\\&_svg\\]\\:rf-shrink-0 svg{flex-shrink:0}',YWt=()=>{mt.useEffect(()=>{if(document.querySelector('style[data-styles="tscircuit-runframe"]'))return;const e=document.createElement("style");e.setAttribute("data-styles","tscircuit-runframe"),e.textContent=$Wt,document.head.appendChild(e)},[])};var XWt=Object.defineProperty,WWt=(r,e)=>{for(var t in e)XWt(r,t,{get:e[t],enumerable:!0})},fBe={};WWt(fBe,{Battery:()=>oQt,Board:()=>jZt,Capacitor:()=>GZt,Chip:()=>DBe,Constraint:()=>QZt,Crystal:()=>hQt,Diode:()=>qZt,FabricationNotePath:()=>KZt,FabricationNoteText:()=>JZt,Footprint:()=>gZt,Group:()=>rle,Hole:()=>EBe,Inductor:()=>uQt,Jumper:()=>$Zt,Keepout:()=>Kse,Led:()=>YZt,Mosfet:()=>vQt,Net:()=>gBe,NetAlias:()=>tQt,NormalComponent:()=>Wx,PcbTrace:()=>bBe,PinHeader:()=>sQt,PlatedHole:()=>SBe,Port:()=>W4,Potentiometer:()=>dQt,PowerSource:()=>XZt,PrimitiveComponent:()=>M_,PushButton:()=>pQt,Renderable:()=>dBe,Resistor:()=>WZt,Resonator:()=>cQt,SchematicText:()=>gQt,SilkscreenCircle:()=>nQt,SilkscreenLine:()=>iQt,SilkscreenPath:()=>xBe,SilkscreenRect:()=>rQt,SilkscreenText:()=>Jse,SmtPad:()=>Qse,Subcircuit:()=>eQt,Switch:()=>yQt,Trace:()=>q8,TraceHint:()=>PBe,Transistor:()=>mQt,Via:()=>aQt});var ZWt=E1("tscircuit:renderable"),T3=["ReactSubtreesRender","InitializePortsFromChildren","CreateNetsFromProps","CreateTracesFromProps","CreateTraceHintsFromProps","SourceRender","SourceParentAttachment","PortMatching","OptimizeSelectorCache","SourceTraceRender","SourceAddConnectivityMapKey","SchematicComponentRender","SchematicPrimitiveRender","SchematicPortRender","SchematicLayout","SchematicTraceRender","PcbComponentRender","PcbPrimitiveRender","PcbFootprintLayout","PcbPortRender","PcbPortAttachment","PcbLayout","PcbComponentSizeCalculation","PcbBoardAutoSize","PcbTraceHintRender","PcbTraceRender","PcbRouteNetIslands","PcbDesignRuleChecks","CadModelRender","PartsEngineRender"],QWt=0,dBe=class{constructor(r){Je(this,"renderPhaseStates");Je(this,"shouldBeRemoved",!1);Je(this,"children");Je(this,"isPcbPrimitive",!1);Je(this,"isSchematicPrimitive",!1);Je(this,"_renderId");Je(this,"_currentRenderPhase",null);Je(this,"_asyncEffects",[]);Je(this,"parent",null);this._renderId=`${QWt++}`,this.children=[],this.renderPhaseStates={};for(const e of T3)this.renderPhaseStates[e]={initialized:!1,dirty:!1}}_markDirty(r){var t;this.renderPhaseStates[r].dirty=!0;const e=T3.indexOf(r);for(let n=e+1;n<T3.length;n++)this.renderPhaseStates[T3[n]].dirty=!0;(t=this.parent)!=null&&t._markDirty&&this.parent._markDirty(r)}_queueAsyncEffect(r,e){const t={promise:e(),phase:this._currentRenderPhase,effectName:r,complete:!1};this._asyncEffects.push(t),"root"in this&&this.root&&this.root.emit("asyncEffect:start",{effectName:r,componentDisplayName:this.getString(),phase:t.phase}),t.promise.then(()=>{t.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:r,componentDisplayName:this.getString(),phase:t.phase})}).catch(n=>{console.error(`Async effect error in ${t.phase} "${r}":
|
|
13424
13424
|
${n.stack}`),t.complete=!0,"root"in this&&this.root&&this.root.emit("asyncEffect:end",{effectName:r,componentDisplayName:this.getString(),phase:t.phase,error:n.toString()})})}_emitRenderLifecycleEvent(r,e){ZWt(`${r}:${e} ${this.getString()}`);const t=`renderable:renderLifecycle:${r}:${e}`,n={renderId:this._renderId,componentDisplayName:this.getString(),type:t};"root"in this&&this.root&&(this.root.emit(t,n),this.root.emit("renderable:renderLifecycle:anyEvent",{...n,type:t}))}getString(){return this.constructor.name}_hasIncompleteAsyncEffects(){return this._asyncEffects.some(r=>!r.complete)}getCurrentRenderPhase(){return this._currentRenderPhase}getRenderGraph(){return{id:this._renderId,currentPhase:this._currentRenderPhase,renderPhaseStates:this.renderPhaseStates,shouldBeRemoved:this.shouldBeRemoved,children:this.children.map(r=>r.getRenderGraph())}}runRenderCycle(){for(const r of T3)this.runRenderPhaseForChildren(r),this.runRenderPhase(r)}runRenderPhase(r){var a,o,s;this._currentRenderPhase=r;const e=this.renderPhaseStates[r],t=e.initialized,n=e.dirty;if(!t&&this.shouldBeRemoved)return;if(this.shouldBeRemoved&&t){this._emitRenderLifecycleEvent(r,"start"),(a=this==null?void 0:this[`remove${r}`])==null||a.call(this),e.initialized=!1,e.dirty=!1,this._emitRenderLifecycleEvent(r,"end");return}const i=T3.indexOf(r)-1;if(i>=0){const l=T3[i];if(this._asyncEffects.filter(u=>u.phase===l).some(u=>!u.complete))return}if(this._emitRenderLifecycleEvent(r,"start"),t){n&&((o=this==null?void 0:this[`update${r}`])==null||o.call(this),e.dirty=!1),this._emitRenderLifecycleEvent(r,"end");return}e.dirty=!1,(s=this==null?void 0:this[`doInitial${r}`])==null||s.call(this),e.initialized=!0,this._emitRenderLifecycleEvent(r,"end")}runRenderPhaseForChildren(r){for(const e of this.children)e.runRenderPhaseForChildren(r),e.runRenderPhase(r)}renderError(r){throw typeof r=="string"?new Error(r):new Error(JSON.stringify(r,null,2))}},_F={},pBe=r=>{const e=Object.fromEntries(Object.entries(r).map(([t,n])=>[t.toLowerCase(),n]));Object.assign(_F,r),Object.assign(_F,e)},KWt=class extends Error{constructor(r,e,t){let n;const a=Object.keys(t).filter(o=>o!=="_errors").map(o=>t[o]._errors[0]?`${o} (${t[o]._errors[0]})`:`${o} (${JSON.stringify(t[o])})`).join(", ");"name"in e?n=`Invalid props for ${r} "${e.name}": ${a}`:"footprint"in e&&typeof e.footprint=="string"?n=`Invalid props for ${r} (unnamed ${e.footprint} component): ${a}`:n=`Invalid props for ${r} (unnamed): ${a}`,super(n),this.componentName=r,this.originalProps=e,this.formattedError=t}};function Xse(r,e){const t=e.match(/^#(\w+)/);if(t)return r.props.id===t[1];const n=e.match(/^\.(\w+)/);if(n)return r.isMatchingNameOrAlias(n[1]);let[i,...a]=e.split(/(?=[#.[])/);return i==="pin"&&(i="port"),i&&i!=="*"&&r.lowercaseComponentName!==i.toLowerCase()?!1:a.every(o=>{if(o.startsWith("#"))return r.props.id===o.slice(1);if(o.startsWith("."))return r.isMatchingNameOrAlias(o.slice(1));const s=o.match(/\[(\w+)=['"]?(.+?)['"]?\]/);if(!s)return!0;const[,l,c]=s;return r.props[l].toString()===c})}var Wse={isTag:r=>!0,getParent:r=>r.parent,getChildren:r=>r.children,getName:r=>r.lowercaseComponentName,getAttributeValue:(r,e)=>{var t;if(e==="class"&&"getNameAndAliases"in r)return r.getNameAndAliases().join(" ");if(e==="name"&&((t=r._parsedProps)!=null&&t.name))return r._parsedProps.name;if(r._parsedProps&&e in r._parsedProps){const n=r._parsedProps[e];return typeof n=="string"?n:n!=null?String(n):null}return null},hasAttrib:(r,e)=>{var t;return e==="class"?!!((t=r._parsedProps)!=null&&t.name):r._parsedProps&&e in r._parsedProps},getSiblings:r=>r.parent?r.parent.children:[],prevElementSibling:r=>{if(!r.parent)return null;const e=r.parent.children,t=e.indexOf(r);return t>0?e[t-1]:null},getText:()=>"",removeSubsets:r=>r.filter((e,t)=>!r.some((n,i)=>t!==i&&n!==e&&n.getDescendants().includes(e))),existsOne:(r,e)=>e.some(r),findAll:(r,e)=>{const t=[],n=i=>{r(i)&&t.push(i);for(const a of i.children)n(a)};for(const i of e)n(i);return t},findOne:(r,e)=>{for(const t of e){if(r(t))return t;const n=t.children;if(n.length>0){const i=Wse.findOne(r,n);if(i)return i}}return null},equals:(r,e)=>r._renderId===e._renderId,isHovered:r=>!1,isVisited:r=>!1,isActive:r=>!1},JWt={...Wse,getChildren:r=>r.children.filter(e=>!e.isSubcircuit)},hBe={...Wse,getChildren:r=>r.children.filter(e=>e.isSubcircuit)},mBe=r=>r.replace(/ pin/g," port").replace(/ subcircuit\./g," group[isSubcircuit=true]").replace(/([^ ])\>([^ ])/g,"$1 > $2").trim(),Zse={adapter:JWt,cacheResults:!0},M_=class extends dBe{constructor(e){super(e);Je(this,"parent",null);Je(this,"children");Je(this,"childrenPendingRemoval");Je(this,"props");Je(this,"_parsedProps");Je(this,"externallyAddedAliases");Je(this,"isPrimitiveContainer",!1);Je(this,"source_group_id",null);Je(this,"source_component_id",null);Je(this,"schematic_component_id",null);Je(this,"pcb_component_id",null);Je(this,"cad_component_id",null);Je(this,"_cachedSelectAllQueries",new Map);Je(this,"_cachedSelectOneQueries",new Map);this.children=[],this.childrenPendingRemoval=[],this.props=e??{},this.externallyAddedAliases=[];const t=this.config.zodProps.safeParse(e??{});if(t.success)this._parsedProps=t.data;else throw new KWt(this.lowercaseComponentName,this.props,t.error.format())}get config(){return{componentName:"",zodProps:k.object({}).passthrough()}}get componentName(){return this.config.componentName}getInheritedProperty(e){var n;let t=this;for(;t;){if(t._parsedProps&&e in t._parsedProps)return t._parsedProps[e];t=t.parent}if((n=this.root)!=null&&n.platform&&e in this.root.platform)return this.root.platform[e]}get lowercaseComponentName(){return this.componentName.toLowerCase()}get isSubcircuit(){var e;return!!this.props.subcircuit||this.lowercaseComponentName==="group"&&((e=this==null?void 0:this.parent)==null?void 0:e.isRoot)}get isGroup(){return this.lowercaseComponentName==="group"}setProps(e){var i,a;const t=this.config.zodProps.parse({...this.props,...e}),n=this.props;this.props=t,this._parsedProps=this.config.zodProps.parse(e),this.onPropsChange({oldProps:n,newProps:t,changedProps:Object.keys(e)}),(a=(i=this.parent)==null?void 0:i.onChildChanged)==null||a.call(i,this)}computePcbPropsTransform(){const{_parsedProps:e}=this;return Tc(Gf(e.pcbX??0,e.pcbY??0),Wb((e.pcbRotation??0)*Math.PI/180))}_computePcbGlobalTransformBeforeLayout(){var n,i,a;const{_parsedProps:e}=this,t=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if(t&&this.props.pcbX===void 0&&this.props.pcbY===void 0)return Tc(((n=this.parent)==null?void 0:n._computePcbGlobalTransformBeforeLayout())??Zm(),Tc(Gf(t.x,t.y),Wb((e.pcbRotation??0)*Math.PI/180)));if(this.isPcbPrimitive){const o=this.getPrimitiveContainer();if(o){const s=o._parsedProps.layer==="bottom",l=o._getGlobalPcbPositionBeforeLayout();if(s)return Tc(Gf(l.x,l.y),fw(),Gf(-l.x,-l.y)),Tc(((i=this.parent)==null?void 0:i._computePcbGlobalTransformBeforeLayout())??Zm(),fw(),this.computePcbPropsTransform())}}return Tc(((a=this.parent)==null?void 0:a._computePcbGlobalTransformBeforeLayout())??Zm(),this.computePcbPropsTransform())}getPrimitiveContainer(){var e,t;return this.isPrimitiveContainer?this:((t=(e=this.parent)==null?void 0:e.getPrimitiveContainer)==null?void 0:t.call(e))??null}_getPcbCircuitJsonBounds(){return{center:{x:0,y:0},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getPcbPrimitiveFlippedHelpers(){const e=this.getPrimitiveContainer(),t=e?e._parsedProps.layer==="bottom":!1;return{isFlipped:t,maybeFlipLayer:i=>t?i==="top"?"bottom":"top":i}}_setPositionFromLayout(e){throw new Error(`_setPositionFromLayout not implemented for ${this.componentName}`)}computeSchematicPropsTransform(){const{_parsedProps:e}=this;return Tc(Gf(e.schX??0,e.schY??0))}computeSchematicGlobalTransform(){var t,n;const e=this._getSchematicGlobalManualPlacementTransform(this);return e||Tc(((n=(t=this.parent)==null?void 0:t.computeSchematicGlobalTransform)==null?void 0:n.call(t))??Zm(),this.computeSchematicPropsTransform())}_getSchematicSymbolName(){const{_parsedProps:e}=this,t=this.config.schematicSymbolName;let n=e.schRotation;if(n===void 0&&(n=0),n=n%360,n<0&&(n+=360),e.schRotation!==void 0&&n%90!==0)throw new Error(`Schematic rotation ${e.schRotation} is not supported for ${this.componentName}`);const i=`${t}_horz`,a=`${t}_vert`,o=`${t}_up`,s=`${t}_down`,l=`${t}_left`,c=`${t}_right`;if(c in u_&&n===0)return c;if(o in u_&&n===90)return o;if(l in u_&&n===180)return l;if(s in u_&&n===270)return s;if(i in u_&&(n===0||n===180))return i;if(a in u_&&(n===90||n===270))return a;if(t in u_)return t}_getSchematicSymbolNameOrThrow(){const e=this._getSchematicSymbolName();if(!e)throw new Error(`No schematic symbol found (given: "${this.config.schematicSymbolName}")`);return e}getSchematicSymbol(){const e=this._getSchematicSymbolName();return e?u_[e]??null:null}_getPcbManualPlacementForComponent(e){var a;if(!this.isSubcircuit)return null;const t=this.props.layout,n=this.props.manualEdits;if(!t&&!n)return null;const i=((a=t==null?void 0:t.manual_pcb_placement_config)==null?void 0:a.positions)||(n==null?void 0:n.pcb_placements);if(!i)return null;for(const o of i)if(t&&Xse(e,o.selector)||e.props.name===o.selector)return Ir(this._computePcbGlobalTransformBeforeLayout(),o.center);return null}_getSchematicManualPlacementForComponent(e){if(!this.isSubcircuit)return null;const t=this.props.manualEdits;if(!t)return null;const n=t.schematic_placements;if(!n)return null;for(const i of n)if(Xse(e,i.selector)||e.props.name===i.selector)return Ir(this.computeSchematicGlobalTransform(),i.center);return null}_getSchematicGlobalManualPlacementTransform(e){var n,i;const t=(n=this.getSubcircuit())==null?void 0:n._parsedProps.manualEdits;if(!t)return null;for(const a of t.schematic_placements??[])if((Xse(e,a.selector)||e.props.name===a.selector)&&a.relative_to==="group_center")return Tc(((i=this.parent)==null?void 0:i._computePcbGlobalTransformBeforeLayout())??Zm(),Gf(a.center.x,a.center.y));return null}_getGlobalPcbPositionBeforeLayout(){return Ir(this._computePcbGlobalTransformBeforeLayout(),{x:0,y:0})}_getGlobalSchematicPositionBeforeLayout(){return Ir(this.computeSchematicGlobalTransform(),{x:0,y:0})}get root(){var e;return((e=this.parent)==null?void 0:e.root)??null}onAddToParent(e){this.parent=e}onPropsChange(e){}onChildChanged(e){var t,n;(n=(t=this.parent)==null?void 0:t.onChildChanged)==null||n.call(t,e)}add(e){if(!e.onAddToParent)throw new Error(`Invalid JSX Element: Expected a React component but received "${JSON.stringify(e)}"`);e.onAddToParent(this),e.parent=this,this.children.push(e)}addAll(e){for(const t of e)this.add(t)}remove(e){this.children=this.children.filter(t=>t!==e),this.childrenPendingRemoval.push(e),e.shouldBeRemoved=!0}getSubcircuitSelector(){const e=this._parsedProps.name,t=e?`${this.lowercaseComponentName}.${e}`:this.lowercaseComponentName;return!this.parent||this.parent.isSubcircuit?t:`${this.parent.getSubcircuitSelector()} > ${t}`}getFullPathSelector(){var i,a;const e=this._parsedProps.name,t=e?`${this.lowercaseComponentName}.${e}`:this.lowercaseComponentName,n=(a=(i=this.parent)==null?void 0:i.getFullPathSelector)==null?void 0:a.call(i);return n?`${n} > ${t}`:t}getNameAndAliases(){return[this._parsedProps.name,...this._parsedProps.portHints??[]].filter(Boolean)}isMatchingNameOrAlias(e){return this.getNameAndAliases().includes(e)}isMatchingAnyOf(e){return this.getNameAndAliases().some(t=>e.map(n=>n.toString()).includes(t))}getPcbSize(){throw new Error(`getPcbSize not implemented for ${this.componentName}`)}doesSelectorMatch(e){const t=[this.componentName,this.lowercaseComponentName],n=[this._parsedProps.name].filter(Boolean),i=e.trim().split(/\> /)[0],a=i[0];return i.length>1?!1:!!(e==="*"||e[0]==="#"&&e.slice(1)===this.props.id||e[0]==="."&&n.includes(e.slice(1))||/^[a-zA-Z0-9_]/.test(a)&&t.includes(a))}getSubcircuit(){var t,n;if(this.isSubcircuit)return this;const e=(n=(t=this.parent)==null?void 0:t.getSubcircuit)==null?void 0:n.call(t);if(!e)throw new Error("Component is not inside an opaque group (no board?)");return e}getGroup(){var e,t;return this.isGroup?this:((t=(e=this.parent)==null?void 0:e.getGroup)==null?void 0:t.call(e))??null}doInitialOptimizeSelectorCache(){var t;if(!this.isSubcircuit)return;const e=this.selectAll("port");for(const n of e){const i=(t=n.parent)==null?void 0:t.getNameAndAliases(),a=n.getNameAndAliases();if(i)for(const o of i)for(const s of a){const l=[`.${o} > .${s}`,`.${o} .${s}`];for(const c of l){const u=this._cachedSelectAllQueries.get(c);u?u.push(n):this._cachedSelectAllQueries.set(c,[n])}}}for(const[n,i]of this._cachedSelectAllQueries.entries())i.length===1&&this._cachedSelectOneQueries.set(n,i[0])}selectAll(e){if(this._cachedSelectAllQueries.has(e))return this._cachedSelectAllQueries.get(e);const t=mBe(e),n=S6(t,this,Zse);if(n.length>0)return this._cachedSelectAllQueries.set(e,n),n;const[i,...a]=t.split(" "),o=d4(i,this,{adapter:hBe});if(!o)return[];const s=o.selectAll(a.join(" "));return this._cachedSelectAllQueries.set(e,s),s}selectOne(e,t){if(this._cachedSelectOneQueries.has(e))return this._cachedSelectOneQueries.get(e);const n=mBe(e);t!=null&&t.port&&(t.type="port");let i=null;if(t!=null&&t.type&&(i=S6(n,this,Zse).find(c=>c.lowercaseComponentName===t.type)),i??(i=d4(n,this,Zse)),i)return this._cachedSelectOneQueries.set(e,i),i;const[a,...o]=n.split(" "),s=d4(a,this,{adapter:hBe});return s?(i=s.selectOne(o.join(" "),t),this._cachedSelectOneQueries.set(e,i),i):null}getAvailablePcbLayers(){var e,t;if(this.isPcbPrimitive){const{maybeFlipLayer:n}=this._getPcbPrimitiveFlippedHelpers();return"layer"in this._parsedProps||this.componentName==="SmtPad"?[n(this._parsedProps.layer??"top")]:"layers"in this._parsedProps?this._parsedProps.layers:this.componentName==="PlatedHole"?((t=(e=this.root)==null?void 0:e._getBoard())==null?void 0:t.allLayers)??["top","bottom"]:[]}return[]}getDescendants(){const e=[];for(const t of this.children)e.push(t),e.push(...t.getDescendants());return e}getSelectableDescendants(){const e=[];for(const t of this.children)t.isSubcircuit?e.push(t):(e.push(t),e.push(...t.getSelectableDescendants()));return e}_getPinCount(){return 0}_getSchematicBoxDimensions(){return null}renderError(e){var t;if(typeof e=="string")return super.renderError(e);(t=this.root)==null||t.db.pcb_placement_error.insert(e)}getString(){var i,a;const{lowercaseComponentName:e,_parsedProps:t,parent:n}=this;return(t==null?void 0:t.pinNumber)!==void 0&&((i=n==null?void 0:n.props)!=null&&i.name)&&(t!=null&&t.name)?`<${e}#${this._renderId}(pin:${t.pinNumber} .${n==null?void 0:n.props.name}>.${t.name}) />`:(a=n==null?void 0:n.props)!=null&&a.name&&(t!=null&&t.name)?`<${e}#${this._renderId}(.${n==null?void 0:n.props.name}>.${t==null?void 0:t.name}) />`:t!=null&&t.from&&(t!=null&&t.to)?`<${e}#${this._renderId}(from:${t.from} to:${t==null?void 0:t.to}) />`:t!=null&&t.name?`<${e}#${this._renderId} name=".${t==null?void 0:t.name}" />`:t!=null&&t.portHints?`<${e}#${this._renderId}(${t.portHints.map(o=>`.${o}`).join(", ")}) />`:`<${e}#${this._renderId} />`}get[Symbol.toStringTag](){return this.getString()}[Symbol.for("nodejs.util.inspect.custom")](){return this.getString()}},eZt=class extends M_{constructor(r,e){super(r),this._parsedProps={...r,error:e,type:r.type||"unknown",component_name:r.name,error_type:"source_failed_to_create_component_error",message:e instanceof Error?e.message:String(e),pcb_center:{x:r.pcbX||0,y:r.pcbY||0},schematic_center:{x:r.schX||0,y:r.schY||0}}}get config(){return{componentName:"ErrorPlaceholder",zodProps:k.object({}).passthrough()}}doInitialSourceRender(){var r;(r=this.root)!=null&&r.db&&this.root.db.source_failed_to_create_component_error.insert({component_name:this._parsedProps.component_name,message:this._parsedProps.message,pcb_center:this._parsedProps.pcb_center,schematic_center:this._parsedProps.schematic_center})}};function tZt(r,e){return new eZt(r,e)}function nZt(r,e){const t=r;return t.__tsci={...e},r}var vBe={supportsMutation:!0,createInstance(r,e){const t=_F[r];if(!t)throw Object.keys(_F).length===0?new Error("No components registered in catalogue, did you forget to import lib/register-catalogue in your test file?"):new Error(`Unsupported component type (not registered in @tscircuit/core catalogue): "${r}" See CREATING_NEW_COMPONENTS.md`);try{return nZt(new t(e),{})}catch(n){return tZt(e,n)}},createTextInstance(){return{}},appendInitialChild(r,e){r.add(e)},appendChild(r,e){r.add(e)},appendChildToContainer(r,e){r.add(e)},finalizeInitialChildren(){return!1},prepareUpdate(){return null},shouldSetTextContent(){return!1},getRootHostContext(){return{}},getChildHostContext(){return{}},prepareForCommit(){return null},resetAfterCommit(){},commitMount(){},commitUpdate(){},removeChild(){},clearContainer(){},supportsPersistence:!1,getPublicInstance(r){return r},preparePortalMount(r){throw new Error("Function not implemented.")},scheduleTimeout(r,e){throw new Error("Function not implemented.")},cancelTimeout(r){throw new Error("Function not implemented.")},noTimeout:void 0,isPrimaryRenderer:!1,getInstanceFromNode(r){throw new Error("Function not implemented.")},beforeActiveInstanceBlur(){throw new Error("Function not implemented.")},afterActiveInstanceBlur(){throw new Error("Function not implemented.")},prepareScopeUpdate:(r,e)=>{throw new Error("Function not implemented.")},getInstanceFromScope:r=>{throw new Error("Function not implemented.")},detachDeletedInstance:r=>{throw new Error("Function not implemented.")},getCurrentEventPriority:()=>f4.DefaultEventPriority,getCurrentUpdatePriority:()=>f4.DefaultEventPriority,resolveUpdatePriority:()=>f4.DefaultEventPriority,setCurrentUpdatePriority:()=>{},maySuspendCommit:()=>!1,supportsHydration:!1},G8;Yp.version.startsWith("19.")?G8=JB(vBe):G8=nH(vBe);var rZt=r=>{const e={children:[],props:{name:"$root"},add(a){a.parent=this,this.children.push(a)},computePcbGlobalTransform(){return Zm()}},t=[],n=G8.createContainer(e,0,null,!1,null,"tsci",a=>{console.log("Error in createContainer"),console.error(a),t.push(a)},null);if(Yp.version.startsWith("19.")?(G8.updateContainerSync(r,n,null,()=>{}),G8.flushSyncWork()):G8.updateContainer(r,n,null,()=>{}),t.length>0)throw t[0];const i=G8.getPublicRootInstance(n);return i||e.children[0]},BA=(r,e)=>{if(typeof r=="number")return r;if(r.startsWith("pin"))return Number(r.slice(3));if(!e)throw new Error(`No pin labels provided and pin number or label is not a number: "${r}"`);for(const t in e)if((Array.isArray(e[t])?e[t]:[e[t]]).includes(r))return Number(t.replace("pin",""));throw new Error(`No pin labels provided and pin number or label is not a number: "${r}"`)},iZt=(r,e)=>{if(!r)return;const t={},n={};for(const[i,a]of Object.entries(r)){const o=BA(i,e);n[o]={...n[o],...a}}for(const[i,a]of Object.entries(n)){const o=`pin${i}`;t[o]={bottom_margin:a.bottomMargin,left_margin:a.leftMargin,right_margin:a.rightMargin,top_margin:a.topMargin}}return t},aZt=r=>{if(r){if("leftSide"in r||"rightSide"in r||"topSide"in r||"bottomSide"in r)return{left_side:r.leftSide,right_side:r.rightSide,top_side:r.topSide,bottom_side:r.bottomSide};if("leftPinCount"in r||"rightPinCount"in r||"topPinCount"in r||"bottomPinCount"in r)return{left_size:r.leftPinCount,right_size:r.rightPinCount,top_size:r.topPinCount,bottom_size:r.bottomPinCount};if("leftSize"in r||"rightSize"in r||"topSize"in r||"bottomSize"in r)return{left_size:r.leftSize,right_size:r.rightSize,top_size:r.topSize,bottom_size:r.bottomSize}}};function yBe(r){const e=[];for(let t=0;t<r.length-1;t++)e.push([r[t],r[t+1]]);return e}var oZt=k.object({name:k.string()}),gBe=class extends M_{constructor(){super(...arguments);Je(this,"source_net_id")}get config(){return{componentName:"Net",zodProps:oZt}}getPortSelector(){return`net.${this.props.name}`}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_net.insert({name:t.name,member_source_group_ids:[]});this.source_net_id=n.source_net_id}doInitialSourceParentAttachment(){const e=this.getSubcircuit();if(!e)return;const{db:t}=this.root;t.source_net.update(this.source_net_id,{subcircuit_id:e.subcircuit_id})}getAllConnectedPorts(){const e=this.getSubcircuit().selectAll("port"),t=[];for(const n of e){const i=n._getDirectlyConnectedTraces();for(const a of i)if(a._isExplicitlyConnectedToNet(this)){t.push(n);break}}return t}_getAllDirectlyConnectedTraces(){const e=this.getSubcircuit().selectAll("trace"),t=[];for(const n of e)n._isExplicitlyConnectedToNet(this)&&t.push(n);return t}doInitialPcbRouteNetIslands(){var o;if((o=this.root)!=null&&o.pcbDisabled||this.getSubcircuit()._parsedProps.routingDisabled||this.getSubcircuit()._getAutorouterConfig().groupMode!=="sequential-trace")return;const{db:e}=this.root,{_parsedProps:t}=this,n=this._getAllDirectlyConnectedTraces().filter(s=>{var l;return(((l=s._portsRoutedOnPcb)==null?void 0:l.length)??0)>0}),i=[];for(const s of n){const l=s._portsRoutedOnPcb,c=i.find(u=>l.some(f=>u.ports.includes(f)));if(!c){i.push({ports:[...l],traces:[s]});continue}c.traces.push(s),c.ports.push(...l)}if(i.length===0)return;const a=yBe(i);for(const[s,l]of a){const c=s.ports.map(C=>C._getGlobalPcbPositionBeforeLayout()),u=l.ports.map(C=>C._getGlobalPcbPositionBeforeLayout());let f=1/0,p=[-1,-1];for(let C=0;C<c.length;C++){const O=c[C];for(let U=0;U<u.length;U++){const q=u[U],Y=Math.sqrt((O.x-q.x)**2+(O.y-q.y)**2);Y<f&&(f=Y,p=[C,U])}}const v=s.ports[p[0]],x=l.ports[p[1]],S=e.toArray().filter(C=>C.type==="pcb_smtpad"||C.type==="pcb_trace"||C.type==="pcb_plated_hole"||C.type==="pcb_hole"||C.type==="source_port"||C.type==="pcb_port"),{solution:E}=sG(S.concat([{type:"source_trace",source_trace_id:"__net_trace_tmp",connected_source_port_ids:[v.source_port_id,x.source_port_id]}])),b=E[0];if(!b){this.renderError({pcb_trace_error_id:"",pcb_trace_id:"__net_trace_tmp",pcb_component_ids:[v.pcb_component_id,x.pcb_component_id].filter(Boolean),pcb_port_ids:[v.pcb_port_id,x.pcb_port_id].filter(Boolean),type:"pcb_trace_error",error_type:"pcb_trace_error",message:`Failed to route net islands for "${this.getString()}"`,source_trace_id:"__net_trace_tmp"});return}e.pcb_trace.insert(b)}}renderError(e){var t;if(typeof e=="string")return super.renderError(e);(t=this.root)==null||t.db.pcb_trace_error.insert(e)}},_Be=(r,e)=>{for(const t of e)if(typeof t=="string"&&t.startsWith("net.")){const n=r.getSubcircuit();if(!n.selectOne(t)){const i=new gBe({name:t.split("net.")[1]});n.add(i)}}},Qse=class extends M_{constructor(){super(...arguments);Je(this,"pcb_smtpad_id",null);Je(this,"matchedPort",null);Je(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SmtPad",zodProps:vUe}}getPcbSize(){const{_parsedProps:e}=this;if(e.shape==="circle")return{width:e.radius*2,height:e.radius*2};if(e.shape==="rect")return{width:e.width,height:e.height};throw new Error(`getPcbSize for shape "${e.shape}" not implemented for ${this.componentName}`)}doInitialPortMatching(){var t;const e=(t=this.getPrimitiveContainer())==null?void 0:t.selectAll("port");if(this.props.portHints){for(const n of e)if(n.isMatchingAnyOf(this.props.portHints)){this.matchedPort=n,n.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){var p,v,x,S,E,b,C,O,U,q;if((p=this.root)!=null&&p.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this;if(!t.portHints)return;const n=this.getPrimitiveContainer(),i=this.getSubcircuit(),a=this._getGlobalPcbPositionBeforeLayout();n==null||n._getGlobalPcbPositionBeforeLayout();const o=uw(this._computePcbGlobalTransformBeforeLayout()),s=Math.abs(o.rotation.angle*(180/Math.PI)-90)%180<.01,{maybeFlipLayer:l}=this._getPcbPrimitiveFlippedHelpers(),c=(n==null?void 0:n._parsedProps.pcbRotation)??0;let u=null;const f=((v=this.parent)==null?void 0:v.pcb_component_id)??((x=this.getPrimitiveContainer())==null?void 0:x.pcb_component_id);t.shape==="circle"?(u=e.pcb_smtpad.insert({pcb_component_id:f,pcb_port_id:(S=this.matchedPort)==null?void 0:S.pcb_port_id,layer:l(t.layer??"top"),shape:"circle",radius:t.radius,port_hints:t.portHints.map(Y=>Y.toString()),x:a.x,y:a.y,subcircuit_id:(i==null?void 0:i.subcircuit_id)??void 0}),e.pcb_solder_paste.insert({layer:u.layer,shape:"circle",radius:u.radius*.7,x:u.x,y:u.y,pcb_component_id:u.pcb_component_id,pcb_smtpad_id:u.pcb_smtpad_id,subcircuit_id:(i==null?void 0:i.subcircuit_id)??void 0,pcb_group_id:((E=this.getGroup())==null?void 0:E.pcb_group_id)??void 0})):t.shape==="rect"&&(u=c===0||s?e.pcb_smtpad.insert({pcb_component_id:f,pcb_port_id:(b=this.matchedPort)==null?void 0:b.pcb_port_id,layer:l(t.layer??"top"),shape:"rect",width:s?t.height:t.width,height:s?t.width:t.height,port_hints:t.portHints.map(Y=>Y.toString()),x:a.x,y:a.y,subcircuit_id:(i==null?void 0:i.subcircuit_id)??void 0,pcb_group_id:((C=this.getGroup())==null?void 0:C.pcb_group_id)??void 0}):e.pcb_smtpad.insert({pcb_component_id:f,layer:t.layer??"top",shape:"rotated_rect",width:t.width,height:t.height,x:a.x,y:a.y,ccw_rotation:c,port_hints:t.portHints.map(Y=>Y.toString()),subcircuit_id:(i==null?void 0:i.subcircuit_id)??void 0,pcb_group_id:((O=this.getGroup())==null?void 0:O.pcb_group_id)??void 0}),u.shape==="rect"&&e.pcb_solder_paste.insert({layer:u.layer,shape:"rect",width:u.width*.7,height:u.height*.7,x:u.x,y:u.y,pcb_component_id:u.pcb_component_id,pcb_smtpad_id:u.pcb_smtpad_id,subcircuit_id:(i==null?void 0:i.subcircuit_id)??void 0,pcb_group_id:((U=this.getGroup())==null?void 0:U.pcb_group_id)??void 0}),u.shape==="rotated_rect"&&e.pcb_solder_paste.insert({layer:u.layer,shape:"rotated_rect",width:u.width*.7,height:u.height*.7,x:u.x,y:u.y,ccw_rotation:c,pcb_component_id:u.pcb_component_id,pcb_smtpad_id:u.pcb_smtpad_id,subcircuit_id:(i==null?void 0:i.subcircuit_id)??void 0,pcb_group_id:((q=this.getGroup())==null?void 0:q.pcb_group_id)??void 0})),u&&(this.pcb_smtpad_id=u.pcb_smtpad_id)}doInitialPcbPortAttachment(){var t,n;if((t=this.root)!=null&&t.pcbDisabled)return;const{db:e}=this.root;e.pcb_smtpad.update(this.pcb_smtpad_id,{pcb_port_id:(n=this.matchedPort)==null?void 0:n.pcb_port_id})}_getPcbCircuitJsonBounds(){const{db:e}=this.root,t=e.pcb_smtpad.get(this.pcb_smtpad_id);if(t.shape==="rect")return{center:{x:t.x,y:t.y},bounds:{left:t.x-t.width/2,top:t.y+t.height/2,right:t.x+t.width/2,bottom:t.y-t.height/2},width:t.width,height:t.height};if(t.shape==="rotated_rect"){const n=t.ccw_rotation*Math.PI/180,i=Math.cos(n),a=Math.sin(n),o=t.width/2,s=t.height/2,l=Math.abs(o*i)+Math.abs(s*a),c=Math.abs(o*a)+Math.abs(s*i);return{center:{x:t.x,y:t.y},bounds:{left:t.x-l,right:t.x+l,top:t.y-c,bottom:t.y+c},width:l*2,height:c*2}}if(t.shape==="circle")return{center:{x:t.x,y:t.y},bounds:{left:t.x-t.radius,top:t.y-t.radius,right:t.x+t.radius,bottom:t.y+t.radius},width:t.radius*2,height:t.radius*2};throw new Error(`circuitJson bounds calculation not implemented for shape "${t.shape}"`)}_setPositionFromLayout(e){var i;const{db:t}=this.root;t.pcb_smtpad.update(this.pcb_smtpad_id,{x:e.x,y:e.y});const n=t.pcb_solder_paste.list().find(a=>a.pcb_smtpad_id===this.pcb_smtpad_id);t.pcb_solder_paste.update(n==null?void 0:n.pcb_solder_paste_id,{x:e.x,y:e.y}),(i=this.matchedPort)==null||i._setPositionFromLayout(e)}},xBe=class extends M_{constructor(){super(...arguments);Je(this,"pcb_silkscreen_path_id",null);Je(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenPath",zodProps:kUe}}doInitialPcbPrimitiveRender(){var l,c,u;if((l=this.root)!=null&&l.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,{maybeFlipLayer:n}=this._getPcbPrimitiveFlippedHelpers(),i=n(t.layer??"top");if(i!=="top"&&i!=="bottom")throw new Error(`Invalid layer "${i}" for SilkscreenPath. Must be "top" or "bottom".`);const a=this._computePcbGlobalTransformBeforeLayout(),o=this.getSubcircuit(),s=e.pcb_silkscreen_path.insert({pcb_component_id:(c=this.parent)==null?void 0:c.pcb_component_id,layer:i,route:t.route.map(f=>{const p=Ir(a,{x:f.x,y:f.y});return{...f,x:p.x,y:p.y}}),stroke_width:t.strokeWidth??.1,subcircuit_id:(o==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((u=this.getGroup())==null?void 0:u.pcb_group_id)??void 0});this.pcb_silkscreen_path_id=s.pcb_silkscreen_path_id}getPcbSize(){const{_parsedProps:e}=this;if(!e.route||e.route.length===0)return{width:0,height:0};let t=1/0,n=-1/0,i=1/0,a=-1/0;for(const o of e.route)t=Math.min(t,o.x),n=Math.max(n,o.x),i=Math.min(i,o.y),a=Math.max(a,o.y);return{width:n-t,height:a-i}}},sZt=k.object({route:k.array(NP),source_trace_id:k.string().optional()}),bBe=class extends M_{constructor(){super(...arguments);Je(this,"pcb_trace_id",null);Je(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PcbTrace",zodProps:sZt}}doInitialPcbPrimitiveRender(){var c,u;if((c=this.root)!=null&&c.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=this.getPrimitiveContainer(),i=this.getSubcircuit(),{maybeFlipLayer:a}=this._getPcbPrimitiveFlippedHelpers(),o=this._computePcbGlobalTransformBeforeLayout(),s=t.route.map(f=>{const{x:p,y:v,...x}=f,S=Ir(o,{x:p,y:v});return f.route_type==="wire"&&f.layer?{...S,...x,layer:a(f.layer)}:{...S,...x}}),l=e.pcb_trace.insert({pcb_component_id:n.pcb_component_id,source_trace_id:t.source_trace_id,route:s,subcircuit_id:(i==null?void 0:i.subcircuit_id)??void 0,pcb_group_id:((u=this.getGroup())==null?void 0:u.pcb_group_id)??void 0});this.pcb_trace_id=l.pcb_trace_id}getPcbSize(){const{_parsedProps:e}=this;if(!e.route||e.route.length===0)return{width:0,height:0};let t=1/0,n=-1/0,i=1/0,a=-1/0;for(const o of e.route)t=Math.min(t,o.x),n=Math.max(n,o.x),i=Math.min(i,o.y),a=Math.max(a,o.y),o.route_type==="wire"&&(t=Math.min(t,o.x-o.width/2),n=Math.max(n,o.x+o.width/2),i=Math.min(i,o.y-o.width/2),a=Math.max(a,o.y+o.width/2));return t===1/0||n===-1/0||i===1/0||a===-1/0?{width:0,height:0}:{width:n-t,height:a-i}}},SBe=class extends M_{constructor(){super(...arguments);Je(this,"pcb_plated_hole_id",null);Je(this,"matchedPort",null);Je(this,"isPcbPrimitive",!0)}get config(){return{componentName:"PlatedHole",zodProps:lUe}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){const{_parsedProps:e}=this;if(e.shape==="circle")return{width:e.outerDiameter,height:e.outerDiameter};if(e.shape==="oval"||e.shape==="pill")return{width:e.outerWidth,height:e.outerHeight};throw new Error(`getPcbSize for shape "${e.shape}" not implemented for ${this.componentName}`)}_getPcbCircuitJsonBounds(){const{db:e}=this.root,t=e.pcb_plated_hole.get(this.pcb_plated_hole_id),n=this.getPcbSize();return{center:{x:t.x,y:t.y},bounds:{left:t.x-n.width/2,top:t.y+n.height/2,right:t.x+n.width/2,bottom:t.y-n.height/2},width:n.width,height:n.height}}_setPositionFromLayout(e){var n;const{db:t}=this.root;t.pcb_plated_hole.update(this.pcb_plated_hole_id,{x:e.x,y:e.y}),(n=this.matchedPort)==null||n._setPositionFromLayout(e)}doInitialPortMatching(){var t;const e=(t=this.getPrimitiveContainer())==null?void 0:t.selectAll("port");if(this.props.portHints){for(const n of e)if(n.isMatchingAnyOf(this.props.portHints)){this.matchedPort=n,n.registerMatch(this);return}}}doInitialPcbPrimitiveRender(){var o,s,l,c,u,f,p,v,x,S,E;if((o=this.root)!=null&&o.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=this._getGlobalPcbPositionBeforeLayout(),i=((s=this.parent)==null?void 0:s.pcb_component_id)??((l=this.getPrimitiveContainer())==null?void 0:l.pcb_component_id),a=this.getSubcircuit();if(t.shape==="circle"){const b=e.pcb_plated_hole.insert({pcb_component_id:i,pcb_port_id:(c=this.matchedPort)==null?void 0:c.pcb_port_id,outer_diameter:t.outerDiameter,hole_diameter:t.holeDiameter,shape:"circle",port_hints:this.getNameAndAliases(),x:n.x,y:n.y,layers:["top","bottom"],subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((u=this.getGroup())==null?void 0:u.pcb_group_id)??void 0});this.pcb_plated_hole_id=b.pcb_plated_hole_id,e.pcb_solder_paste.insert({layer:"top",shape:"circle",radius:t.outerDiameter/2,x:n.x,y:n.y,subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((f=this.getGroup())==null?void 0:f.pcb_group_id)??void 0}),e.pcb_solder_paste.insert({layer:"bottom",shape:"circle",radius:t.outerDiameter/2,x:n.x,y:n.y,subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((p=this.getGroup())==null?void 0:p.pcb_group_id)??void 0})}else if(t.shape==="pill"||t.shape==="oval"){const b=e.pcb_plated_hole.insert({pcb_component_id:i,pcb_port_id:(v=this.matchedPort)==null?void 0:v.pcb_port_id,outer_width:t.outerWidth,outer_height:t.outerHeight,hole_width:t.holeWidth,hole_height:t.holeHeight,shape:t.shape,port_hints:this.getNameAndAliases(),x:n.x,y:n.y,layers:["top","bottom"],subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((x=this.getGroup())==null?void 0:x.pcb_group_id)??void 0});this.pcb_plated_hole_id=b.pcb_plated_hole_id,e.pcb_solder_paste.insert({layer:"top",shape:t.shape,width:t.outerWidth,height:t.outerHeight,x:n.x,y:n.y,subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((S=this.getGroup())==null?void 0:S.pcb_group_id)??void 0}),e.pcb_solder_paste.insert({layer:"bottom",shape:t.shape,width:t.outerWidth,height:t.outerHeight,x:n.x,y:n.y,subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((E=this.getGroup())==null?void 0:E.pcb_group_id)??void 0})}}doInitialPcbPortAttachment(){var t,n;if((t=this.root)!=null&&t.pcbDisabled)return;const{db:e}=this.root;e.pcb_plated_hole.update(this.pcb_plated_hole_id,{pcb_port_id:(n=this.matchedPort)==null?void 0:n.pcb_port_id})}},Kse=class extends M_{constructor(){super(...arguments);Je(this,"pcb_keepout_id",null);Je(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Keepout",zodProps:OUe}}doInitialPcbPrimitiveRender(){var l,c,u;if((l=this.root)!=null&&l.pcbDisabled)return;const e=this.getSubcircuit(),{db:t}=this.root,{_parsedProps:n}=this,i=this._getGlobalPcbPositionBeforeLayout(),a=uw(this._computePcbGlobalTransformBeforeLayout()),o=Math.abs(a.rotation.angle*(180/Math.PI)-90)%180<.01;let s=null;n.shape==="circle"?s=t.pcb_keepout.insert({layers:["top"],shape:"circle",radius:n.radius,center:{x:i.x,y:i.y},subcircuit_id:(e==null?void 0:e.subcircuit_id)??void 0,pcb_group_id:((c=e==null?void 0:e.getGroup())==null?void 0:c.pcb_group_id)??void 0}):n.shape==="rect"&&(s=t.pcb_keepout.insert({layers:["top"],shape:"rect",...o?{width:n.height,height:n.width}:{width:n.width,height:n.height},center:{x:i.x,y:i.y},subcircuit_id:(e==null?void 0:e.subcircuit_id)??void 0,pcb_group_id:((u=e==null?void 0:e.getGroup())==null?void 0:u.pcb_group_id)??void 0})),s&&(this.pcb_keepout_id=s.pcb_keepout_id)}},EBe=class extends M_{constructor(){super(...arguments);Je(this,"pcb_hole_id",null);Je(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Hole",zodProps:yUe}}getPcbSize(){const{_parsedProps:e}=this;return{width:e.diameter,height:e.diameter}}doInitialPcbPrimitiveRender(){var o,s;if((o=this.root)!=null&&o.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=this.getSubcircuit(),i=this._getGlobalPcbPositionBeforeLayout(),a=e.pcb_hole.insert({hole_shape:"circle",hole_diameter:t.diameter,x:i.x,y:i.y,subcircuit_id:(n==null?void 0:n.subcircuit_id)??void 0,pcb_group_id:((s=n==null?void 0:n.getGroup())==null?void 0:s.pcb_group_id)??void 0});this.pcb_hole_id=a.pcb_hole_id}_getPcbCircuitJsonBounds(){const{db:e}=this.root,t=e.pcb_hole.get(this.pcb_hole_id),n=this.getPcbSize();return{center:{x:t.x,y:t.y},bounds:{left:t.x-n.width/2,top:t.y-n.height/2,right:t.x+n.width/2,bottom:t.y+n.height/2},width:n.width,height:n.height}}_setPositionFromLayout(e){const{db:t}=this.root;t.pcb_hole.update(this.pcb_hole_id,{x:e.x,y:e.y})}},Jse=class extends M_{constructor(){super(...arguments);Je(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenText",zodProps:IUe}}doInitialPcbPrimitiveRender(){var s,l;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=this.getPrimitiveContainer(),i=this._getGlobalPcbPositionBeforeLayout(),{maybeFlipLayer:a}=this._getPcbPrimitiveFlippedHelpers(),o=this.getSubcircuit();e.pcb_silkscreen_text.insert({anchor_alignment:t.anchorAlignment,anchor_position:{x:i.x,y:i.y},font:t.font??"tscircuit2024",font_size:t.fontSize??1,layer:a(t.layer??"top"),text:t.text??"",ccw_rotation:t.pcbRotation,pcb_component_id:n.pcb_component_id,subcircuit_id:(o==null?void 0:o.subcircuit_id)??void 0,pcb_group_id:((l=this.getGroup())==null?void 0:l.pcb_group_id)??void 0})}getPcbSize(){const{_parsedProps:e}=this,t=e.fontSize??1,i=(e.text??"").length*t,a=t;return{width:i*t,height:a*t}}},lZt=({elm:r,pinLabels:e,readableRotation:t})=>{var a;const n=r.text.replace(/[{}]/g,"").toLowerCase();let i=n;if(Array.isArray(e)){const o=parseInt(n.replace(/[^\d]/g,""),10)-1;i=e[o]??n}else typeof e=="object"&&(i=((a=e[n])==null?void 0:a[0])??n);return new Jse({anchorAlignment:"center",text:i??n,fontSize:r.font_size+.2,pcbX:isNaN(r.anchor_position.x)?0:r.anchor_position.x,pcbY:r.anchor_position.y,pcbRotation:t??0})},cZt=({componentName:r,componentRotation:e,footprint:t,pinLabels:n},i)=>{const a=[];for(const o of i)if(o.type==="pcb_smtpad"&&o.shape==="rect")a.push(new Qse({pcbX:o.x,pcbY:o.y,layer:o.layer,shape:"rect",height:o.height,width:o.width,portHints:o.port_hints}));else if(o.type==="pcb_smtpad"&&o.shape==="circle")a.push(new Qse({pcbX:o.x,pcbY:o.y,layer:o.layer,shape:"circle",radius:o.radius,portHints:o.port_hints}));else if(o.type==="pcb_silkscreen_path")a.push(new xBe({layer:o.layer,route:o.route,strokeWidth:o.stroke_width}));else if(o.type==="pcb_plated_hole"&&o.shape==="circle")o.shape==="circle"&&a.push(new SBe({pcbX:o.x,pcbY:o.y,shape:"circle",holeDiameter:o.hole_diameter,outerDiameter:o.outer_diameter,portHints:o.port_hints}));else if(o.type==="pcb_keepout"&&o.shape==="circle")a.push(new Kse({pcbX:o.center.x,pcbY:o.center.y,shape:"circle",radius:o.radius}));else if(o.type==="pcb_keepout"&&o.shape==="rect")a.push(new Kse({pcbX:o.center.x,pcbY:o.center.y,shape:"rect",width:o.width,height:o.height}));else if(o.type==="pcb_hole"&&o.hole_shape==="circle")a.push(new EBe({pcbX:o.x,pcbY:o.y,diameter:o.hole_diameter}));else if(o.type==="pcb_silkscreen_text"){let s=e?parseInt(e):0;const l=(s%360+360)%360;s=l>90&&l<=270?(l+180)%360:l,t.includes("pinrow")&&o.text.includes("PIN")&&n?a.push(lZt({elm:o,pinLabels:n,readableRotation:s})):o.text==="{REF}"&&a.push(new Jse({anchorAlignment:"center",text:r,fontSize:o.font_size+.2,pcbX:isNaN(o.anchor_position.x)?0:o.anchor_position.x,pcbY:o.anchor_position.y,pcbRotation:s??0}))}else o.type==="pcb_trace"&&a.push(new bBe({route:o.route}));return a};function wBe(r){let e=1/0,t=1/0,n=-1/0,i=-1/0;for(const s of r)if(s.isPcbPrimitive&&!s.componentName.startsWith("Silkscreen")){const{x:l,y:c}=s._getGlobalPcbPositionBeforeLayout(),{width:u,height:f}=s.getPcbSize();e=Math.min(e,l-u/2),t=Math.min(t,c-f/2),n=Math.max(n,l+u/2),i=Math.max(i,c+f/2)}else if(s.componentName==="Footprint"){const l=wBe(s.children);e=Math.min(e,l.minX),t=Math.min(t,l.minY),n=Math.max(n,l.maxX),i=Math.max(i,l.maxY)}let a=n-e,o=i-t;return a<0&&(a=0),o<0&&(o=0),{minX:e,minY:t,maxX:n,maxY:i,width:a,height:o}}function uZt(r,e){const t=e.x-r.x,n=e.y-r.y;return Math.abs(t)>Math.abs(n)?t>=0?"right":"left":n>=0?"up":"down"}var fZt=r=>{if(r.length<=1)return!0;const e=r.map(a=>{const o=a._getPcbCircuitJsonBounds();return{left:o.bounds.left,right:o.bounds.right,top:o.bounds.top,bottom:o.bounds.bottom}}),t=Array(e.length).fill(!1).map(()=>Array(e.length).fill(!1));for(let a=0;a<e.length;a++)for(let o=a+1;o<e.length;o++){const s=e[a],l=e[o];t[a][o]=t[o][a]=!(s.right<l.left||s.left>l.right||s.bottom>l.top||s.top<l.bottom)}const n=new Set,i=a=>{n.add(a);for(let o=0;o<e.length;o++)t[a][o]&&!n.has(o)&&i(o)};return i(0),n.size===e.length},dZt=r=>{if(r.length===0)throw new Error("Cannot get center of empty PCB primitives array");const e=r.map(i=>i._getPcbCircuitJsonBounds().center).filter(Boolean),t=e.reduce((i,a)=>i+a.x,0),n=e.reduce((i,a)=>i+a.y,0);return{x:t/e.length,y:n/e.length}},pZt=k.object({name:k.string().optional(),pinNumber:k.number().optional(),aliases:k.array(k.string()).optional()}),W4=class extends M_{constructor(e,t={}){if(!e.name&&e.pinNumber!==void 0&&(e.name=`pin${e.pinNumber}`),!e.name)throw new Error("Port must have a name or a pinNumber");super(e);Je(this,"source_port_id",null);Je(this,"pcb_port_id",null);Je(this,"schematic_port_id",null);Je(this,"schematicSymbolPortDef",null);Je(this,"matchedComponents");Je(this,"facingDirection",null);Je(this,"originDescription",null);t.originDescription&&(this.originDescription=t.originDescription),this.matchedComponents=[]}get config(){return{componentName:"Port",zodProps:pZt}}_getGlobalPcbPositionBeforeLayout(){const e=this.matchedComponents.find(n=>n.isPcbPrimitive),t=this.parent;if(t&&!t.props.footprint)throw new Error(`${t.componentName} "${t.props.name}" does not have a footprint. Add a footprint prop, e.g. <${t.componentName.toLowerCase()} footprint="..." />`);if(!e)throw new Error(`Port ${this} has no matching PCB primitives. This often means the footprint's pads lack matching port hints.`);return(e==null?void 0:e._getGlobalPcbPositionBeforeLayout())??{x:0,y:0}}_getPcbCircuitJsonBounds(){if(!this.pcb_port_id)return super._getPcbCircuitJsonBounds();const{db:e}=this.root,t=e.pcb_port.get(this.pcb_port_id);return{center:{x:t.x,y:t.y},bounds:{left:0,top:0,right:0,bottom:0},width:0,height:0}}_getGlobalPcbPositionAfterLayout(){return this._getPcbCircuitJsonBounds().center}_getPortsInternallyConnectedToThisPort(){const e=this.parent;if(!e||!e._getInternallyConnectedPins)return[];const t=e._getInternallyConnectedPins();for(const n of t)if(n.some(i=>i===this))return n;return[]}_hasSchematicPort(){var n,i;if((n=this.parent)==null?void 0:n.getSchematicSymbol())return!!(this.schematicSymbolPortDef||this._getPortsInternallyConnectedToThisPort().some(o=>o.schematicSymbolPortDef));const t=(i=this==null?void 0:this.parent)==null?void 0:i._getSchematicBoxDimensions();return!!(t&&this.props.pinNumber!==void 0&&t.getPortPositionByPinNumber(this.props.pinNumber))}_getGlobalSchematicPositionBeforeLayout(){var n,i,a;const e=(n=this.parent)==null?void 0:n.getSchematicSymbol();if(e){let o=this.schematicSymbolPortDef;if(!o&&(o=((i=this._getPortsInternallyConnectedToThisPort().find(l=>l.schematicSymbolPortDef))==null?void 0:i.schematicSymbolPortDef)??null,!o))throw new Error(`Couldn't find schematicSymbolPortDef for port ${this.getString()}, searched internally connected ports and none had a schematicSymbolPortDef. Why are we trying to get the schematic position of this port?`);const s=Tc(this.parent.computeSchematicGlobalTransform(),Gf(-e.center.x,-e.center.y));return Ir(s,o)}const t=(a=this==null?void 0:this.parent)==null?void 0:a._getSchematicBoxDimensions();if(t&&this.props.pinNumber!==void 0){const o=t.getPortPositionByPinNumber(this.props.pinNumber);if(!o)throw new Error(`Couldn't find position for schematic_port for port ${this.getString()} inside of the schematic box`);return Ir(this.parent.computeSchematicGlobalTransform(),o)}throw new Error(`Couldn't find position for schematic_port for port ${this.getString()}`)}_getGlobalSchematicPositionAfterLayout(){const{db:e}=this.root;if(!this.schematic_port_id)throw new Error(`Can't get schematic port position after layout for "${this.getString()}", no schematic_port_id`);const t=e.schematic_port.get(this.schematic_port_id);if(!t)throw new Error(`Schematic port not found when trying to get post-layout position: ${this.schematic_port_id}`);return t.center}registerMatch(e){this.matchedComponents.push(e)}getNameAndAliases(){const{_parsedProps:e}=this;return Array.from(new Set([...e.aliases??[],...e.name?[e.name]:[],...typeof e.pinNumber=="number"?[`pin${e.pinNumber}`,e.pinNumber.toString()]:[],...this.externallyAddedAliases??[]]))}isMatchingPort(e){return this.isMatchingAnyOf(e.getNameAndAliases())}getPortSelector(){var e;return`.${(e=this.parent)==null?void 0:e.props.name} > port.${this.props.name}`}getAvailablePcbLayers(){return Array.from(new Set(this.matchedComponents.flatMap(e=>e.getAvailablePcbLayers())))}_getDirectlyConnectedTraces(){return this.getSubcircuit().selectAll("trace").filter(n=>n._isExplicitlyConnectedToPort(this))}doInitialSourceRender(){var a,o;const{db:e}=this.root,{_parsedProps:t}=this,n=this.getNameAndAliases(),i=e.source_port.insert({name:t.name,pin_number:t.pinNumber,port_hints:n,source_component_id:(a=this.parent)==null?void 0:a.source_component_id,subcircuit_id:(o=this.getSubcircuit())==null?void 0:o.subcircuit_id});this.source_port_id=i.source_port_id}doInitialSourceParentAttachment(){var t,n,i,a,o;const{db:e}=this.root;if(!((t=this.parent)!=null&&t.source_component_id))throw new Error(`${this.getString()} has no parent source component (parent: ${(n=this.parent)==null?void 0:n.getString()})`);e.source_port.update(this.source_port_id,{source_component_id:(i=this.parent)==null?void 0:i.source_component_id,subcircuit_id:(a=this.getSubcircuit())==null?void 0:a.subcircuit_id}),this.source_component_id=(o=this.parent)==null?void 0:o.source_component_id}doInitialPcbPortRender(){var a,o,s,l,c;if((a=this.root)!=null&&a.pcbDisabled)return;const{db:e}=this.root,{matchedComponents:t}=this;if(!((o=this.parent)!=null&&o.pcb_component_id))throw new Error(`${this.getString()} has no parent pcb component, cannot render pcb_port (parent: ${(s=this.parent)==null?void 0:s.getString()})`);const n=t.filter(u=>u.isPcbPrimitive);if(n.length===0)return;let i=null;if(n.length===1&&(i=n[0]._getPcbCircuitJsonBounds().center),n.length>1){if(!fZt(n))throw new Error(`${this.getString()} has multiple non-overlapping pcb matches, unclear how to place pcb_port: ${n.map(u=>u.getString()).join(", ")}. (Note: tscircuit core does not currently allow you to specify internally connected pcb primitives with the same port hints, try giving them different port hints and specifying they are connected externally- or file an issue)`);i=dZt(n)}if(i){const u=this.getSubcircuit(),f=e.pcb_port.insert({pcb_component_id:(l=this.parent)==null?void 0:l.pcb_component_id,layers:this.getAvailablePcbLayers(),subcircuit_id:(u==null?void 0:u.subcircuit_id)??void 0,pcb_group_id:((c=this.getGroup())==null?void 0:c.pcb_group_id)??void 0,...i,source_port_id:this.source_port_id});this.pcb_port_id=f.pcb_port_id}else{const u=n[0];throw new Error(`${u.getString()} does not have a center or _getGlobalPcbPositionBeforeLayout method (needed for pcb_port placement)`)}}doInitialSchematicPortRender(){var f;const{db:e}=this.root,{_parsedProps:t}=this,n=this.getPrimitiveContainer();if(!n||!this._hasSchematicPort())return;const i=n._getGlobalSchematicPositionBeforeLayout(),a=this._getGlobalSchematicPositionBeforeLayout();let o=null;const s=n._getSchematicBoxDimensions();s&&t.pinNumber!==void 0&&(o=s.getPortPositionByPinNumber(t.pinNumber)),this.getSubcircuit().props._schDebugObjectsEnabled&&e.schematic_debug_object.insert({shape:"rect",center:a,size:{width:.1,height:.1},label:"obstacle"}),o!=null&&o.side?this.facingDirection={left:"left",right:"right",top:"up",bottom:"down"}[o.side]:this.facingDirection=uZt(i,a);const l=e.source_port.get(this.source_port_id);let c;for(const p of(l==null?void 0:l.port_hints)??[])p.match(/^(pin)?\d+$/)||p.match(/^(left|right)/)&&!(l!=null&&l.name.match(/^(left|right)/))||(c=p);const u=e.schematic_port.insert({schematic_component_id:(f=this.parent)==null?void 0:f.schematic_component_id,center:a,source_port_id:this.source_port_id,facing_direction:this.facingDirection,distance_from_component_edge:.4,side_of_component:o==null?void 0:o.side,pin_number:t.pinNumber,true_ccw_index:o==null?void 0:o.trueIndex,display_pin_label:c});this.schematic_port_id=u.schematic_port_id}_setPositionFromLayout(e){const{db:t}=this.root;this.pcb_port_id&&t.pcb_port.update(this.pcb_port_id,{x:e.x,y:e.y})}_hasMatchedPcbPrimitive(){return this.matchedComponents.some(e=>e.isPcbPrimitive)}},TBe=r=>{const e=r.find(t=>/^(pin)?\d+$/.test(t));return e?Number.parseInt(e.replace(/^pin/,"")):null};function HA(r,e){var a;const t=TBe(r);if(!t)return null;const i=[...r.filter(o=>o.toString()!==t.toString()&&o!==`pin${t}`),...((a=e==null?void 0:e.additionalAliases)==null?void 0:a[`pin${t}`])??[]];return new W4({pinNumber:t,aliases:i})}var hZt=r=>{for(const e of["leftSide","rightSide","topSide","bottomSide"])if(e in r&&typeof r[e]=="number")throw new Error(`A number was specified for "${e}", you probably meant to use "size" not "side"`);return"leftSide"in r||"rightSide"in r||"topSide"in r||"bottomSide"in r},mZt=r=>{var a,o,s,l;if(hZt(r))return{leftSize:((a=r.leftSide)==null?void 0:a.pins.length)??0,rightSize:((o=r.rightSide)==null?void 0:o.pins.length)??0,topSize:((s=r.topSide)==null?void 0:s.pins.length)??0,bottomSize:((l=r.bottomSide)==null?void 0:l.pins.length)??0};const{leftSize:e=0,rightSize:t=0,topSize:n=0,bottomSize:i=0}=r;return{leftSize:e,rightSize:t,topSize:n,bottomSize:i}};function MBe(r){return r.leftSide!==void 0}var vZt=r=>{var E,b,C,O,U,q,Y,Q;const e=r.portDistanceFromEdge??.4;let t=r.schPortArrangement?mZt(r.schPortArrangement):null;const n={left:0,right:0,top:0,bottom:0};let i=r.pinCount??null;if(i===null)if(t)i=t.leftSize+t.rightSize+t.topSize;else throw new Error("Could not determine pin count for the schematic box");if(i&&!t){const K=Math.floor(i/2);t={leftSize:i-K,rightSize:K,topSize:0,bottomSize:0}}t||(t={leftSize:0,rightSize:0,topSize:0,bottomSize:0});const a=({side:K,sideIndex:te,truePinIndex:J})=>{var Pe,Ee,Ce,be;if(!r.schPortArrangement||!MBe(r.schPortArrangement))return J+1;const fe={left:"top-to-bottom",bottom:"left-to-right",right:"bottom-to-top",top:"right-to-left"}[K],he=((Ee=(Pe=r.schPortArrangement)==null?void 0:Pe[`${K}Side`])==null?void 0:Ee.direction)??fe,ve=(be=(Ce=r.schPortArrangement)==null?void 0:Ce[`${K}Side`])==null?void 0:be.pins;let Te=te;return he!==fe&&(Te=ve.length-te-1),BA(ve[Te],r.pinLabels)},o=[];let s=0,l=0;for(let K=0;K<t.leftSize;K++){const te=a({side:"left",sideIndex:K,truePinIndex:l}),J=((E=r.numericSchPinStyle)==null?void 0:E[`pin${te}`])??((b=r.numericSchPinStyle)==null?void 0:b[te]);J!=null&&J.topMargin&&(s+=J.topMargin),o.push({trueIndex:l,pinNumber:te,side:"left",distanceFromOrthogonalEdge:s}),J!=null&&J.bottomMargin&&(s+=J.bottomMargin),K===t.leftSize-1?n.left=s:s+=r.schPinSpacing,l++}s=0;for(let K=0;K<t.bottomSize;K++){const te=a({side:"bottom",sideIndex:K,truePinIndex:l}),J=((C=r.numericSchPinStyle)==null?void 0:C[`pin${te}`])??((O=r.numericSchPinStyle)==null?void 0:O[te]);J!=null&&J.leftMargin&&(s+=J.leftMargin),o.push({trueIndex:l,pinNumber:te,side:"bottom",distanceFromOrthogonalEdge:s}),J!=null&&J.rightMargin&&(s+=J.rightMargin),K===t.bottomSize-1?n.bottom=s:s+=r.schPinSpacing,l++}s=0;for(let K=0;K<t.rightSize;K++){const te=a({side:"right",sideIndex:K,truePinIndex:l}),J=((U=r.numericSchPinStyle)==null?void 0:U[`pin${te}`])??((q=r.numericSchPinStyle)==null?void 0:q[te]);J!=null&&J.bottomMargin&&(s+=J.bottomMargin),o.push({trueIndex:l,pinNumber:te,side:"right",distanceFromOrthogonalEdge:s}),J!=null&&J.topMargin&&(s+=J.topMargin),K===t.rightSize-1?n.right=s:s+=r.schPinSpacing,l++}s=0;for(let K=0;K<t.topSize;K++){const te=a({side:"top",sideIndex:K,truePinIndex:l}),J=((Y=r.numericSchPinStyle)==null?void 0:Y[`pin${te}`])??((Q=r.numericSchPinStyle)==null?void 0:Q[te]);J!=null&&J.rightMargin&&(s+=J.rightMargin),o.push({trueIndex:l,pinNumber:te,side:"top",distanceFromOrthogonalEdge:s}),J!=null&&J.leftMargin&&(s+=J.leftMargin),K===t.topSize-1?n.top=s:s+=r.schPinSpacing,l++}let c=r.schWidth;c||(c=Math.max(n.top+r.schPinSpacing*2,n.bottom+r.schPinSpacing*2));const u=r.pinLabels?Math.max(...Object.values(r.pinLabels).map(K=>K.length*.1)):0,f=u>0?1.1:0;c=Math.max(c,u+f);let p=r.schHeight;p||(p=Math.max(n.left+r.schPinSpacing*2,n.right+r.schPinSpacing*2));const v={left:{x:-c/2-e,y:n.left/2},bottom:{x:-n.bottom/2,y:-p/2-e},right:{x:c/2+e,y:-n.right/2},top:{x:n.top/2,y:p/2+e}},x={left:{x:0,y:-1},right:{x:0,y:1},top:{x:-1,y:0},bottom:{x:1,y:0}},S=o.map(K=>{const{distanceFromOrthogonalEdge:te,side:J}=K,fe=v[J],he=x[J];return{x:fe.x+te*he.x,y:fe.y+te*he.y,...K}});return{getPortPositionByPinNumber(K){const te=S.find(J=>J.pinNumber.toString()===K.toString());return te||null},getSize(){return{width:c,height:p}},getSizeIncludingPins(){return{width:c+(t.leftSize||t.rightSize?.4:0),height:p+(t.topSize||t.bottomSize?.4:0)}},pinCount:i}},yZt=E1("tscircuit:core:footprint"),gZt=class extends M_{get config(){return{componentName:"Footprint",zodProps:xUe}}doInitialPcbFootprintLayout(){var f,p,v,x,S;if((f=this.root)!=null&&f.pcbDisabled)return;const r=this.children.filter(E=>E.componentName==="Constraint");if(r.length===0)return;const{isFlipped:e}=this._getPcbPrimitiveFlippedHelpers(),t=E=>e&&"left"in E&&"right"in E?{...E,left:E.right,right:E.left}:E,n=r.flatMap(E=>E._getAllReferencedComponents().componentsWithSelectors).map(({component:E,selector:b,componentSelector:C,edge:O})=>({component:E,selector:b,componentSelector:C,edge:O,bounds:E._getPcbCircuitJsonBounds()}));if(n.some(E=>E.edge))throw new Error("edge constraints not implemented yet for footprint layout, contributions welcome!");function i(E){return n.find(({selector:b})=>b===E)}const a=new hG,o={};function s(E){return E in o||(o[E]=new yC(E),a.addEditVariable(o[E],J1.weak)),o[E]}for(const{selector:E,bounds:b}of n){const C=s(`${E}_x`),O=s(`${E}_y`);a.suggestValue(C,b.center.x),a.suggestValue(O,b.center.y)}for(const E of r){const b=E._parsedProps;if("xDist"in b){const{xDist:C,left:O,right:U,edgeToEdge:q,centerToCenter:Y}=t(b),Q=s(`${O}_x`),K=s(`${U}_x`),te=(p=i(O))==null?void 0:p.bounds,J=(v=i(U))==null?void 0:v.bounds;if(Y){const fe=new w1(K,[-1,Q]);a.addConstraint(new px(fe,s_.Eq,b.xDist,J1.required))}else if(q){const fe=new w1(K,-J.width/2,[-1,Q],-te.width/2);a.addConstraint(new px(fe,s_.Eq,b.xDist,J1.required))}}else if("yDist"in b){const{yDist:C,top:O,bottom:U,edgeToEdge:q,centerToCenter:Y}=b,Q=s(`${O}_y`),K=s(`${U}_y`),te=(x=i(O))==null?void 0:x.bounds,J=(S=i(U))==null?void 0:S.bounds;if(Y){const fe=new w1(Q,[-1,K]);a.addConstraint(new px(fe,s_.Eq,b.yDist,J1.required))}else if(q){const fe=new w1(Q,te.height/2,[-1,K],-J.height/2);a.addConstraint(new px(fe,s_.Eq,b.yDist,J1.required))}}else if("sameY"in b){const{for:C}=b;if(C.length<2)continue;const O=C.map(q=>s(`${q}_y`)),U=new w1(...O.slice(1));a.addConstraint(new px(U,s_.Eq,O[0],J1.required))}else if("sameX"in b){const{for:C}=b;if(C.length<2)continue;const O=C.map(q=>s(`${q}_x`)),U=new w1(...O.slice(1));a.addConstraint(new px(U,s_.Eq,O[0],J1.required))}}a.updateVariables(),yZt.enabled&&(console.log("Solution to layout constraints:"),console.table(Object.entries(o).map(([E,b])=>({var:E,val:b.value()}))));const l={left:1/0,right:-1/0,top:-1/0,bottom:1/0};for(const{selector:E,bounds:{width:b,height:C}}of n){const O=s(`${E}_x`),U=s(`${E}_y`),q=O.value()-b/2,Y=O.value()+b/2,Q=U.value()+C/2,K=U.value()-C/2;l.left=Math.min(l.left,q),l.right=Math.max(l.right,Y),l.top=Math.max(l.top,Q),l.bottom=Math.min(l.bottom,K)}const c={x:-(l.right+l.left)/2,y:-(l.top+l.bottom)/2},u=this.getPrimitiveContainer()._getGlobalPcbPositionBeforeLayout();c.x+=u.x,c.y+=u.y;for(const{component:E,selector:b}of n){const C=s(`${b}_x`),O=s(`${b}_y`);E._setPositionFromLayout({x:C.value()+c.x,y:O.value()+c.y})}}},_Zt=(r,e)=>{if(!r)return;const t={};for(const[n,i]of Object.entries(r)){const a=BA(n,e),o={leftMargin:i.marginLeft??i.leftMargin,rightMargin:i.marginRight??i.rightMargin,topMargin:i.marginTop??i.topMargin,bottomMargin:i.marginBottom??i.bottomMargin};t[`pin${a}`]={...t[`pin${a}`],...o}}return t},CBe=class{constructor({input:r}){Je(this,"input");this.input=r}solveAndMapToTraces(){const r=[];for(const e of this.input.connections){if(e.pointsToConnect.length!==2)continue;const[t,n]=e.pointsToConnect,i={type:"pcb_trace",pcb_trace_id:"",connection_name:e.name,route:[{route_type:"wire",x:t.x,y:t.y,layer:"top",width:.1},{route_type:"wire",x:n.x,y:n.y,layer:"top",width:.1}]};r.push(i)}return r}},xZt=r=>{const e=Math.min(...r.map(a=>a.center.x)),t=Math.max(...r.map(a=>a.center.x)),n=Math.min(...r.map(a=>a.center.y)),i=Math.max(...r.map(a=>a.center.y));return{minX:e,maxX:t,minY:n,maxY:i}},RBe=["top","bottom","inner1","inner2"],xF=(r,e=[])=>{var s;const t=[];if(e.length===0){const l=r[0].layers;for(const c of l)t.push(...xF(r.slice(1),[c]));return t}if(r.length===0)return[];const n=r[0],i=n.via||n.optional_via,a=e[e.length-1];if(r.length===1){const l=n;return l.layers&&i?l.layers.map(c=>({layer_path:[...e,c]})):(s=l.layers)!=null&&s.includes(a)?[{layer_path:[...e,a]}]:[]}if(!i)return n.layers&&!n.layers.includes(a)?[]:xF(r.slice(1),e.concat([a]));const o=(n.optional_via?RBe:RBe.filter(l=>l!==a)).filter(l=>{var c;return!n.layers||((c=n.layers)==null?void 0:c.includes(l))});for(const l of o)t.push(...xF(r.slice(1),e.concat(l)));return t};function ABe(r){const e={x:r.to.x-r.from.x,y:r.to.y-r.from.y},t=Math.abs(e.x),n=Math.abs(e.y);return t>n?e.x>0?"right":"left":e.y>0?"down":"up"}function gM(r,e){return Math.hypot(r.x-e.x,r.y-e.y)}var bZt=r=>{if(r.length===1)return r[0];if(r.some(l=>l.length===0))throw new Error("Cannot merge routes with zero length");const e=[],t=r[0][0],n=r[0][r[0].length-1],i=r[1][0],a=r[1][r[1].length-1],o=Math.min(gM(t,i),gM(t,a)),s=Math.min(gM(n,i),gM(n,a));o<s?e.push(...r[0].reverse()):e.push(...r[0]);for(let l=1;l<r.length;l++){const c=e[e.length-1],u=r[l],f=u[0],p=u[u.length-1],v=gM(c,f),x=gM(c,p);v<x?e.push(...u):e.push(...u.reverse())}for(let l=1;l<e.length-1;l++){const c=e[l-1],u=e[l];c.route_type==="wire"&&u.route_type==="wire"&&c.layer!==u.layer&&e.splice(l,0,{x:c.x,y:c.y,from_layer:c.layer,to_layer:u.layer,route_type:"via"})}return e},SZt=(r,e)=>{const t="_getGlobalPcbPositionBeforeLayout"in r?r._getGlobalPcbPositionBeforeLayout():r,n="_getGlobalPcbPositionBeforeLayout"in e?e._getGlobalPcbPositionBeforeLayout():e;return Math.sqrt((t.x-n.x)**2+(t.y-n.y)**2)};function EZt(r,e){if(e.length===0)throw new Error("No candidates given to getClosest method");let t=e[0],n=1/0;for(const i of e){const a=SZt(r,i);a<n&&(t=i,n=a)}return t}var wZt=(r,e)=>{let t=0;t+=r.length??0,t+=e.filter(n=>n.is_crossing).length;for(let n=1;n<e.length;n++){const i=e[n-1],a=e[n],o=Math.abs(i.from.x-i.to.x)<.01,s=Math.abs(a.from.x-a.to.x)<.01;o!==s&&t++}return t},ele=r=>({up:"bottom",down:"top",left:"right",right:"left"})[r]??null,tle=({firstEdge:r,firstEdgePort:e,firstDominantDirection:t,lastEdge:n,lastEdgePort:i,lastDominantDirection:a})=>{if(r&&e)return tle({lastEdge:{from:r.to,to:r.from},lastEdgePort:e,lastDominantDirection:t}).reverse().map(s=>({from:s.to,to:s.from}));let o=[];if(n&&i){const s={x:n.to.x,y:n.to.y};a==="left"||a==="right"?(s.x=i.position.x,o.push({from:n.to,to:{...s}}),o.push({from:s,to:{...i.position}})):(s.y=i.position.y,o.push({from:n.to,to:{...s}}),o.push({from:s,to:{...i.position}}))}return o=o.filter(s=>E3(s.from,s.to)>.01),o};function TZt(r){try{return[r(),null]}catch(e){return[null,e]}}function MZt(r){let e=0;for(let t=0;t<r.length;t++){const n=r[t];if(n.route_type==="wire"){const i=r[t+1];if(i){const a=i.x-n.x,o=i.y-n.y;e+=Math.sqrt(a*a+o*o)}}else n.route_type==="via"&&(e+=1.6)}return e}var CZt=r=>{var s,l;const e={left:{x:-.5,y:0},up:{x:.5,y:.5},right:{x:.5,y:0},down:{x:0,y:-.5}}[r.facingDirection],t=(s=r.parent)!=null&&s.config.shouldRenderAsSchematicBox?3:1,n=(l=r.parent)!=null&&l.config.shouldRenderAsSchematicBox&&(r.facingDirection==="left"||r.facingDirection==="right")?3:1,i=e.x,a=e.y,o=r.facingDirection==="up"?.5:0;return{schBoxVertOffset:t,schBoxHorzOffset:n,horzPortDirection:i,vertPortDirectionOffset:a,handleUp:o}},bF=({port:r,anchorPos:e,schDisplayLabel:t,source_trace_id:n},{db:i})=>{const a=CZt(r);i.schematic_net_label.insert({anchor_side:"top",center:{x:e.x+a.horzPortDirection*a.schBoxHorzOffset,y:e.y+a.vertPortDirectionOffset*a.schBoxVertOffset},source_net_id:r.source_port_id,text:t,anchor_position:{x:e.x+a.horzPortDirection*a.schBoxHorzOffset,y:e.y+a.vertPortDirectionOffset*a.schBoxVertOffset},symbol_name:"ground_horz"}),i.schematic_trace.insert({edges:[{from:{x:e.x,y:e.y},to:{x:e.x,y:e.y+a.handleUp*a.schBoxVertOffset}},{from:{x:e.x,y:e.y},to:{x:e.x+a.horzPortDirection*a.schBoxHorzOffset,y:e.y+a.vertPortDirectionOffset*a.schBoxVertOffset}}],junctions:[{x:e.x+a.horzPortDirection*a.schBoxHorzOffset,y:e.y+a.vertPortDirectionOffset*a.schBoxVertOffset}],source_trace_id:n})},nle=({db:r,source_trace_id:e,sameNetOnly:t,differentNetOnly:n})=>{!t&&!n&&(n=!0);const i=r.source_trace.get(e),a=[];for(const o of r.schematic_trace.list()){if(o.source_trace_id===e)continue;const s=r.source_trace.get(o.source_trace_id),l=(s==null?void 0:s.subcircuit_connectivity_map_key)===i.subcircuit_connectivity_map_key;n&&l||t&&!l||a.push(o)}return a},RZt=({edges:r,otherEdges:e})=>{const t=[...r];for(let n=0;n<t.length;n++){if(n>2e3)throw new Error("Over 2000 iterations spent inside createSchematicTraceCrossingSegments, you have triggered an infinite loop, please report this!");const i=t[n],a=Math.abs(i.from.x-i.to.x)<.01?"vertical":i.from.y===i.to.y?"horizontal":"not-orthogonal";if(a==="not-orthogonal")continue;const o=[];for(const S of e){const E=S.from.x===S.to.x?"vertical":S.from.y===S.to.y?"horizontal":"not-orthogonal";if(E==="not-orthogonal"||a===E)continue;if(Nk([i.from,i.to],[S.from,S.to],{lineThickness:.01})){const C=a==="vertical"?i.from.x:S.from.x,O=a==="vertical"?S.from.y:i.from.y,U={x:C,y:O};o.push({otherEdge:S,crossingPoint:U,distanceFromEdgeFrom:E3(i.from,U)})}}if(o.length===0)continue;let s=o[0];for(const S of o)S.distanceFromEdgeFrom<s.distanceFromEdgeFrom&&(s=S);const l=s.crossingPoint,c=.075;if(l.x===i.from.x&&l.y===i.from.y)continue;const u=GUe(i.from,l),f={x:l.x-u.x*c/2,y:l.y-u.y*c/2},p={x:l.x+u.x*c/2,y:l.y+u.y*c/2},v=E3(p,i.to)<c,x=[{from:i.from,to:f},{from:f,to:p,is_crossing:!0},{from:p,to:i.to}];t.splice(n,1,...x),n+=x.length-2,v&&n++}return t},AZt=(r,e)=>{if(r.from.x===r.to.x&&e.from.x===e.to.x)return null;if(r.from.x===r.to.x){const u=r.from.x,f=(e.to.y-e.from.y)/(e.to.x-e.from.x),p=e.from.y-f*e.from.x,v=f*u+p;return u>=Math.min(e.from.x,e.to.x)&&u<=Math.max(e.from.x,e.to.x)&&v>=Math.min(e.from.y,e.to.y)&&v<=Math.max(e.from.y,e.to.y)?{x:u,y:v}:null}if(e.from.x===e.to.x){const u=e.from.x,f=(r.to.y-r.from.y)/(r.to.x-r.from.x),p=r.from.y-f*r.from.x,v=f*u+p;return u>=Math.min(r.from.x,r.to.x)&&u<=Math.max(r.from.x,r.to.x)&&v>=Math.min(r.from.y,r.to.y)&&v<=Math.max(r.from.y,r.to.y)?{x:u,y:v}:null}const t=(r.to.y-r.from.y)/(r.to.x-r.from.x),n=r.from.y-t*r.from.x,i=(e.to.y-e.from.y)/(e.to.x-e.from.x),a=e.from.y-i*e.from.x;if(t===i)return null;const o=(a-n)/(t-i),s=t*o+n,l=o>=Math.min(r.from.x,r.to.x)&&o<=Math.max(r.from.x,r.to.x)&&s>=Math.min(r.from.y,r.to.y)&&s<=Math.max(r.from.y,r.to.y),c=o>=Math.min(e.from.x,e.to.x)&&o<=Math.max(e.from.x,e.to.x)&&s>=Math.min(e.from.y,e.to.y)&&s<=Math.max(e.from.y,e.to.y);return l&&c?{x:o,y:s}:null},PZt=({edges:r,db:e,source_trace_id:t})=>{const n=nle({db:e,source_trace_id:t,sameNetOnly:!0}).flatMap(i=>i.edges);for(const i of r)for(const a of n){const o=AZt(i,a);if(o)return`${o.x}${o.y}`,[{x:o.x,y:o.y}]}return[]},NZt=(r,{db:e})=>{const t=r.map(n=>{const i=e.source_port.get(n.source_port_id);if(!(i!=null&&i.source_component_id))return null;const a=e.source_component.get(i.source_component_id);return(a==null?void 0:a.ftype)==="simple_capacitor"?a.max_decoupling_trace_length:null}).filter(n=>n!==null);if(t.length!==0)return Math.min(...t)};function DZt(r){var a,o,s,l,c,u,f,p,v;let e=1/0,t=1/0,n=-1/0,i=-1/0;for(const x of r){let S,E,b,C;x.type==="schematic_component"?(S=(a=x.center)==null?void 0:a.x,E=(o=x.center)==null?void 0:o.y,b=(s=x.size)==null?void 0:s.width,C=(l=x.size)==null?void 0:l.height):x.type==="schematic_box"?(S=x.x,E=x.y,b=x.width,C=x.height):x.type==="schematic_port"?(S=(c=x.center)==null?void 0:c.x,E=(u=x.center)==null?void 0:u.y,b=.2,C=.2):x.type==="schematic_text"&&(S=(f=x.position)==null?void 0:f.x,E=(p=x.position)==null?void 0:p.y,b=(((v=x.text)==null?void 0:v.length)??0)*.1,C=.2),typeof S=="number"&&typeof E=="number"&&typeof b=="number"&&typeof C=="number"&&(e=Math.min(e,S-b/2),n=Math.max(n,S+b/2),t=Math.min(t,E-C/2),i=Math.max(i,E+C/2))}return{minX:e,maxX:n,minY:t,maxY:i}}function LZt(r,e={}){const{minX:t,maxX:n,minY:i,maxY:a}=r,o=e.padding??1;if(!isFinite(t)||!isFinite(n)||!isFinite(i)||!isFinite(a))return[];const s=t-o,l=n+o,c=a+o,u=i-o,f=.01;return[{type:"rect",layers:["top"],center:{x:(s+l)/2,y:c},width:l-s,height:f,connectedTo:[]},{type:"rect",layers:["top"],center:{x:(s+l)/2,y:u},width:l-s,height:f,connectedTo:[]},{type:"rect",layers:["top"],center:{x:s,y:(c+u)/2},width:f,height:c-u,connectedTo:[]},{type:"rect",layers:["top"],center:{x:l,y:(c+u)/2},width:f,height:c-u,connectedTo:[]}]}var OZt=r=>{var o;const e=r.root.db,t=r._findConnectedPorts().ports??[],n=new Set(t.map(s=>s.schematic_port_id)),i=[];for(const s of e.toArray()){if(s.type==="schematic_component"){const l=!!s.symbol_name,c=s.size.width>s.size.height?"horz":"vert";i.push({type:"rect",layers:["top"],center:s.center,width:s.size.width+(l&&c==="horz"?-.5:0),height:s.size.height+(l&&c==="vert"?-.5:0),connectedTo:[]})}if(s.type==="schematic_port"){if(n.has(s.schematic_port_id))continue;const l=s.facing_direction?qUe(s.facing_direction):{x:0,y:0};i.push({type:"rect",layers:["top"],center:{x:s.center.x-l.x*.1,y:s.center.y-l.y*.1},width:.1+Math.abs(l.x)*.3,height:.1+Math.abs(l.y)*.3,connectedTo:[]})}s.type==="schematic_text"&&i.push({type:"rect",layers:["top"],center:s.position,width:(((o=s.text)==null?void 0:o.length)??0)*.1,height:.2,connectedTo:[]}),s.type==="schematic_box"&&i.push({type:"rect",layers:["top"],center:{x:s.x,y:s.y},width:s.width,height:s.height,connectedTo:[]})}const a=DZt(e.toArray());return i.push(...LZt(a,{padding:1})),i};function zZt({ports:r,nets:e}){var t,n,i;if(r.length>=2)return`${(t=r[0])==null?void 0:t.selector} to ${(n=r[1])==null?void 0:n.selector}`;if(r.length===1&&e.length===1)return`${(i=r[0])==null?void 0:i.selector} to net.${e[0]._parsedProps.name}`}var UZt=({edges:r,db:e,source_trace_id:t})=>{e.source_trace.get(t);const n=nle({db:e,source_trace_id:t,differentNetOnly:!0}).flatMap(a=>a.edges),i=a=>{const{from:o,to:s}=a;return o.x===s.x?"vertical":"horizontal"};for(const a of r){const o=i(a),s=()=>n.find(c=>i(c)===o&&Nk([a.from,a.to],[c.from,c.to],{lineThickness:.05}));let l=s();for(;l;)o==="horizontal"?(a.from.y+=.1,a.to.y+=.1):(a.from.x+=.1,a.to.x+=.1),l=s()}},IZt=(r,{db:e})=>{const t=e.pcb_board.list()[0];if(t.outline){const l=t.outline,c=(u,f)=>{let p=!1;for(let v=0,x=f.length-1;v<f.length;x=v++){const S=f[v].x,E=f[v].y,b=f[x].x,C=f[x].y;E>u.y!=C>u.y&&u.x<(b-S)*(u.y-E)/(C-E)+S&&(p=!p)}return p};return r.some(u=>!c(u,l))}const n=t.width,i=t.height,a=t.center.x,o=t.center.y;return r.some(l=>l.x<a-n/2||l.y<o-i/2||l.x>a+n/2||l.y>o+i/2)},SF=r=>({...r._getGlobalPcbPositionAfterLayout(),layers:r.getAvailablePcbLayers()}),q8=class extends M_{constructor(e){super(e);Je(this,"source_trace_id",null);Je(this,"pcb_trace_id",null);Je(this,"schematic_trace_id",null);Je(this,"_portsRoutedOnPcb");Je(this,"subcircuit_connectivity_map_key",null);Je(this,"_traceConnectionHash",null);this._portsRoutedOnPcb=[]}get config(){return{zodProps:_Ue,componentName:"Trace"}}_getTracePortOrNetSelectorListFromProps(){return"from"in this.props&&"to"in this.props?[typeof this.props.from=="string"?this.props.from:this.props.from.getPortSelector(),typeof this.props.to=="string"?this.props.to:this.props.to.getPortSelector()]:"path"in this.props?this.props.path.map(e=>typeof e=="string"?e:e.getPortSelector()):[]}getTracePortPathSelectors(){return this._getTracePortOrNetSelectorListFromProps().filter(e=>!e.includes("net."))}getTracePathNetSelectors(){return this._getTracePortOrNetSelectorListFromProps().filter(e=>e.includes("net."))}_findConnectedPorts(){const{db:e}=this.root,{_parsedProps:t,parent:n}=this;if(!n)throw new Error("Trace has no parent");const a=this.getTracePortPathSelectors().map(o=>({selector:o,port:this.getSubcircuit().selectOne(o,{type:"port"})??null}));for(const{selector:o,port:s}of a)if(!s){const l=o.replace(/(\> )?[^ ]+$/,""),c=this.getSubcircuit().selectOne(l);c?this.renderError(`Could not find port for selector "${o}" (did you forget to include the pin name?)
|
|
13425
|
-
searched component ${c.getString()}, which has ports: ${c.children.filter(u=>u.componentName==="Port").map(u=>`${u.getString()}(${u.getNameAndAliases().join(",")})`).join(" & ")}`):this.renderError(`Could not find port for selector "${o}"`)}return a.some(o=>!o.port)?{allPortsFound:!1}:{allPortsFound:!0,portsWithSelectors:a,ports:a.map(({port:o})=>o)}}_findConnectedNets(){const e=this.getTracePathNetSelectors().map(n=>({selector:n,net:this.getSubcircuit().selectOne(n,{type:"net"})})),t=e.filter(n=>!n.net);return t.length>0&&this.renderError(`Could not find net for selector "${t[0].selector}" inside ${this}`),{netsWithSelectors:e,nets:e.map(n=>n.net)}}_getAllTracesConnectedToSameNet(){const e=this.getSubcircuit().selectAll("trace"),t=this._findConnectedNets().nets,n=this._findConnectedPorts().ports??[];return e.filter(i=>{if(i===this)return!1;const a=i._findConnectedNets().nets,o=i._findConnectedPorts().ports??[];return a.some(s=>t.includes(s))||o.some(s=>n.includes(s))})}_isExplicitlyConnectedToPort(e){const{allPortsFound:t,portsWithSelectors:n}=this._findConnectedPorts();return t?n.map(a=>a.port).includes(e):!1}_isExplicitlyConnectedToNet(e){return this._findConnectedNets().nets.includes(e)}doInitialCreateNetsFromProps(){_Be(this,this.getTracePathNetSelectors())}_computeTraceConnectionHash(){const{allPortsFound:e,ports:t}=this._findConnectedPorts();return!e||!t?null:[...t].sort((a,o)=>(a.pcb_port_id||"").localeCompare(o.pcb_port_id||"")).map(a=>a.pcb_port_id).join(",")}doInitialSourceTraceRender(){var f;const{db:e}=this.root,{_parsedProps:t,parent:n}=this;if(!n){this.renderError("Trace has no parent");return}const{allPortsFound:i,portsWithSelectors:a}=this._findConnectedPorts();if(!i)return;this._traceConnectionHash=this._computeTraceConnectionHash();const s=e.source_trace.list().find(p=>p.subcircuit_connectivity_map_key===this.subcircuit_connectivity_map_key&&p.connected_source_port_ids.sort().join(",")===this._traceConnectionHash);if(s){this.source_trace_id=s.source_trace_id;return}const l=this._findConnectedNets().nets,c=zZt({ports:a,nets:l}),u=e.source_trace.insert({connected_source_port_ids:a.map(p=>p.port.source_port_id),connected_source_net_ids:l.map(p=>p.source_net_id),subcircuit_id:(f=this.getSubcircuit())==null?void 0:f.subcircuit_id,max_length:NZt(a.map(p=>p.port),{db:e})??t.maxLength,display_name:c,min_trace_thickness:t.thickness});this.source_trace_id=u.source_trace_id}_insertErrorIfTraceIsOutsideBoard(e,t){const{db:n}=this.root;IZt(e,{db:n})&&n.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:this.source_trace_id,message:`Trace ${this.getString()} routed outside the board boundaries.`,pcb_trace_id:this.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:t.map(a=>a.pcb_port_id)})}doInitialPcbTraceRender(){var K,te,J,fe;if((K=this.root)!=null&&K.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t,parent:n}=this,i=this.getSubcircuit();if(!n)throw new Error("Trace has no parent");if(i._parsedProps.routingDisabled)return;const a=(te=i._parsedProps.pcbRouteCache)==null?void 0:te.pcbTraces;if(a){const he=e.pcb_trace.insert({route:a.flatMap(ve=>ve.route),source_trace_id:this.source_trace_id,subcircuit_id:(i==null?void 0:i.subcircuit_id)??void 0,pcb_group_id:((J=this.getGroup())==null?void 0:J.pcb_group_id)??void 0});this.pcb_trace_id=he.pcb_trace_id;return}if(!i._shouldUseTraceByTraceRouting())return;const{allPortsFound:o,ports:s}=this._findConnectedPorts();if(!o)return;const l=[];for(const he of s)he._hasMatchedPcbPrimitive()||l.push(he);if(l.length>0){e.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:this.source_trace_id,message:`Some ports did not have a matching PCB primitive (e.g. a pad or plated hole), this can happen if a footprint is missing. As a result, ${this} wasn't routed. Missing ports: ${l.map(he=>he.getString()).join(", ")}`,pcb_trace_id:this.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:l.map(he=>he.pcb_port_id).filter(Boolean)});return}const c=this._findConnectedNets().netsWithSelectors;if(s.length===0&&c.length===2){this.renderError("Trace connects two nets, we haven't implemented a way to route this yet");return}else if(s.length===1&&c.length===1){const he=s[0],Te=c[0].net.getAllConnectedPorts().filter(Ee=>Ee!==he);if(Te.length===0){console.log("Nothing to connect this port to, the net is empty. TODO should emit a warning!");return}const Pe=EZt(he,Te);s.push(Pe)}else if(s.length>1&&c.length>=1){this.renderError("Trace has more than one port and one or more nets, we don't currently support this type of complex trace routing");return}const u=s.flatMap(he=>he.matchedComponents.filter(ve=>ve.componentName==="TraceHint")),f=(this._parsedProps.pcbRouteHints??[]).concat(u.flatMap(he=>he.getPcbRouteHints()));if(s.length>2){this.renderError(`Trace has more than two ports (${s.map(he=>he.getString()).join(", ")}), routing between more than two ports for a single trace is not implemented`);return}if(this.getSubcircuit().selectAll("trace").filter(he=>he.renderPhaseStates.PcbTraceRender.initialized).some(he=>he._portsRoutedOnPcb.length===s.length&&he._portsRoutedOnPcb.every(ve=>s.includes(ve))))return;let x=[];f.length===0?x=[SF(s[0]),SF(s[1])]:x=[SF(s[0]),...f,SF(s[1])];const S=xF(x),E=k3(this.root.db.toArray()),[b,C]=TZt(()=>M6(this.root.db.toArray()));if(C){this.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:this.pcb_trace_id,message:`Error getting obstacles for autorouting: ${C.message}`,source_trace_id:this.source_trace_id,center:{x:0,y:0},pcb_port_ids:s.map(he=>he.pcb_port_id),pcb_trace_id:this.pcb_trace_id,pcb_component_ids:[]});return}for(const he of b)if(he.connectedTo.length>0){const Te=E.getNetConnectedToId(he.connectedTo[0]);Te&&he.connectedTo.push(Te)}let O=[];if(S.length===0)O=x;else{const he=S[0].layer_path;O=x.map((ve,Te)=>ve.via?{...ve,via_to_layer:he[Te]}:{...ve,layers:[he[Te]]})}O[0].pcb_port_id=s[0].pcb_port_id,O[O.length-1].pcb_port_id=s[1].pcb_port_id;const U=[];for(const[he,ve]of yBe(O)){const Te="via_to_layer"in he?he.via_to_layer:null,Pe=2,Ee="layers"in he&&he.layers.length===1?he.layers[0]:Te??"top",Ce="layers"in ve&&ve.layers.length===1?ve.layers[0]:Te??"top",be="pcb_port_id"in he?he.pcb_port_id:null,Oe="pcb_port_id"in ve?ve.pcb_port_id:null,Ue=this.getSubcircuit()._parsedProps.minTraceWidth??.16,Ie=new T6({OBSTACLE_MARGIN:Ue*2,isRemovePathLoopsEnabled:!0,optimizeWithGoalBoxes:!!(be&&Oe),connMap:E,input:{obstacles:b,minTraceWidth:Ue,connections:[{name:this.source_trace_id,pointsToConnect:[{...he,layer:Ee,pcb_port_id:be},{...ve,layer:Ce,pcb_port_id:Oe}]}],layerCount:2,bounds:{minX:Math.min(he.x,ve.x)-Pe,maxX:Math.max(he.x,ve.x)+Pe,minY:Math.min(he.y,ve.y)-Pe,maxY:Math.max(he.y,ve.y)+Pe}}});let ke=null;try{ke=Ie.solveAndMapToTraces()}catch(gt){this.renderError({type:"pcb_trace_error",pcb_trace_error_id:this.source_trace_id,error_type:"pcb_trace_error",message:`error solving route: ${gt.message}`,source_trace_id:this.pcb_trace_id,center:{x:(he.x+ve.x)/2,y:(he.y+ve.y)/2},pcb_port_ids:s.map(Et=>Et.pcb_port_id),pcb_trace_id:this.pcb_trace_id,pcb_component_ids:s.map(Et=>Et.pcb_component_id)})}if(!ke)return;if(ke.length===0){this.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:this.pcb_trace_id,message:`Could not find a route for ${this}`,source_trace_id:this.source_trace_id,center:{x:(he.x+ve.x)/2,y:(he.y+ve.y)/2},pcb_port_ids:s.map(gt=>gt.pcb_port_id),pcb_trace_id:this.pcb_trace_id,pcb_component_ids:s.map(gt=>gt.pcb_component_id)});return}const[ot]=ke;Te&&(ot.route=ot.route.map(gt=>(gt.route_type==="wire"&&!gt.layer&&(gt.layer=Te),gt))),be&&ot.route[0].route_type==="wire"&&(ot.route[0].start_pcb_port_id=be);const nt=ot.route[ot.route.length-1];Oe&&nt.route_type==="wire"&&(nt.end_pcb_port_id=Oe),U.push(ot.route)}const q=bZt(U),Y=MZt(q),Q=e.pcb_trace.insert({route:q,source_trace_id:this.source_trace_id,subcircuit_id:(fe=this.getSubcircuit())==null?void 0:fe.subcircuit_id,trace_length:Y});this._portsRoutedOnPcb=s,this.pcb_trace_id=Q.pcb_trace_id;for(const he of q)he.route_type==="via"&&e.pcb_via.insert({pcb_trace_id:Q.pcb_trace_id,x:he.x,y:he.y,hole_diameter:.3,outer_diameter:.6,layers:[he.from_layer,he.to_layer],from_layer:he.from_layer,to_layer:he.to_layer});this._insertErrorIfTraceIsOutsideBoard(q,s)}_doInitialSchematicTraceRenderWithDisplayLabel(){var U,q,Y,Q;if((U=this.root)!=null&&U.schematicDisabled)return;const{db:e}=this.root,{_parsedProps:t,parent:n}=this;if(!n)throw new Error("Trace has no parent");const{allPortsFound:i,portsWithSelectors:a}=this._findConnectedPorts();if(!i)return;const o=a.map(({port:K})=>({port:K,position:K._getGlobalSchematicPositionAfterLayout(),schematic_port_id:K.schematic_port_id,facingDirection:K.facingDirection}));if(o.length<2)throw new Error("Expected at least two ports in portsWithPosition.");let s,l;const c=o[0].position,u=o[0].port;if("path"in this.props){if(this.props.path.length!==2)throw new Error("Invalid 'path': Must contain exactly two elements.");[s,l]=this.props.path}else{if(!("from"in this.props&&"to"in this.props))throw new Error("Missing 'from' or 'to' properties in props.");s=this.props.from,l=this.props.to}if(!u.source_port_id)throw new Error(`Missing source_port_id for the 'from' port (${s}).`);const f=o[1].position,p=o[1].port;if(!p.source_port_id)throw new Error(`Missing source_port_id for the 'to' port (${l}).`);const v=e.schematic_net_label.list().find(K=>K.source_net_id===u.source_port_id),x=e.schematic_net_label.list().find(K=>K.source_net_id===p.source_port_id),[S,E]=a.map(({port:K})=>K),C=((q=S.parent)==null?void 0:q.config.shouldRenderAsSchematicBox)?`${(Y=S==null?void 0:S.parent)==null?void 0:Y.props.name}_${S==null?void 0:S.props.name}`:`${(Q=E==null?void 0:E.parent)==null?void 0:Q.props.name}_${E==null?void 0:E.props.name}`,O=this.props.schDisplayLabel??C;if(v&&v.text!==O&&(v.text=`${O} / ${v.text}`),x&&(x==null?void 0:x.text)!==O&&(x.text=`${O} / ${x.text}`),O!=null&&O.toLocaleLowerCase().includes("gnd")||O!=null&&O.toLocaleLowerCase().includes("ground")){!v&&!x?(bF({port:u,anchorPos:c,schDisplayLabel:this.props.schDisplayLabel,source_trace_id:this.source_trace_id},{db:e}),bF({port:p,anchorPos:f,schDisplayLabel:this.props.schDisplayLabel,source_trace_id:this.source_trace_id},{db:e})):v?x||bF({port:p,anchorPos:f,schDisplayLabel:this.props.schDisplayLabel,source_trace_id:this.source_trace_id},{db:e}):bF({port:u,anchorPos:c,schDisplayLabel:this.props.schDisplayLabel,source_trace_id:this.source_trace_id},{db:e});return}x||e.schematic_net_label.insert({text:this.props.schDisplayLabel??C,source_net_id:p.source_port_id,anchor_position:f,center:f,anchor_side:ele(p.facingDirection)??"bottom"}),v||e.schematic_net_label.insert({text:this.props.schDisplayLabel??C,source_net_id:u.source_port_id,anchor_position:c,center:c,anchor_side:ele(u.facingDirection)??"bottom"})}_isSymbolToChipConnection(){const{allPortsFound:e,ports:t}=this._findConnectedPorts();if(!e||t.length!==2)return!1;const[n,i]=t;if(!(n!=null&&n.parent)||!(i!=null&&i.parent))return!1;const a=n.parent.config.shouldRenderAsSchematicBox,o=i.parent.config.shouldRenderAsSchematicBox;return a&&!o||!a&&o}_isSymbolToSymbolConnection(){const{allPortsFound:e,ports:t}=this._findConnectedPorts();if(!e||t.length!==2)return!1;const[n,i]=t;if(!(n!=null&&n.parent)||!(i!=null&&i.parent))return!1;const a=!n.parent.config.shouldRenderAsSchematicBox,o=!i.parent.config.shouldRenderAsSchematicBox;return a&&o}_isChipToChipConnection(){const{allPortsFound:e,ports:t}=this._findConnectedPorts();if(!e||t.length!==2)return!1;const[n,i]=t;if(!(n!=null&&n.parent)||!(i!=null&&i.parent))return!1;const a=n.parent.config.shouldRenderAsSchematicBox,o=i.parent.config.shouldRenderAsSchematicBox;return a&&o}doInitialSchematicTraceRender(){var Ee,Ce;if((Ee=this.root)!=null&&Ee.schematicDisabled)return;const{db:e}=this.root,{_parsedProps:t,parent:n}=this;if(!n)throw new Error("Trace has no parent");const{allPortsFound:i,portsWithSelectors:a}=this._findConnectedPorts(),{netsWithSelectors:o}=this._findConnectedNets();if(!i)return;const l=a.map(be=>be.port.schematic_port_id).sort().join(","),c=(Ce=this.root)==null?void 0:Ce._getBoard();if(c!=null&&c._connectedSchematicPortPairs&&c._connectedSchematicPortPairs.has(l))return;if(this.props.schDisplayLabel&&("from"in this.props&&"to"in this.props||"path"in this.props)){this._doInitialSchematicTraceRenderWithDisplayLabel();return}const u={name:this.source_trace_id,pointsToConnect:[]},f=OZt(this),p=a.map(({port:be})=>({port:be,position:be._getGlobalSchematicPositionAfterLayout(),schematic_port_id:be.schematic_port_id??void 0,facingDirection:be.facingDirection}));if(p.length===1&&o.length===1){const be=o[0].net,{port:Oe,position:Ue}=p[0];e.schematic_net_label.insert({text:be._parsedProps.name,source_net_id:be.source_net_id,anchor_position:Ue,center:Ue,anchor_side:ele(Oe.facingDirection)??"bottom"});return}if(p.length<2)return;u.pointsToConnect=p.map(({position:be})=>({...be,layer:"top"}));const x=xZt(f),S=2,E={minTraceWidth:.1,obstacles:f,connections:[u],bounds:{minX:x.minX-S,maxX:x.maxX+S,minY:x.minY-S,maxY:x.maxY+S},layerCount:1};let b=T6,C=!1;this.getSubcircuit().props._schDirectLineRoutingEnabled&&(b=CBe,C=!0);let U=new b({input:E,MAX_ITERATIONS:100,OBSTACLE_MARGIN:.1,isRemovePathLoopsEnabled:!0,isShortenPathWithShortcutsEnabled:!0,marginsWithCosts:[{margin:1,enterCost:0,travelCostFactor:1},{margin:.3,enterCost:0,travelCostFactor:1},{margin:.2,enterCost:0,travelCostFactor:2},{margin:.1,enterCost:0,travelCostFactor:3}]}).solveAndMapToTraces();if(U.length===0){if(this._isSymbolToChipConnection()||this._isSymbolToSymbolConnection()||this._isChipToChipConnection()){this._doInitialSchematicTraceRenderWithDisplayLabel();return}U=new CBe({input:E}).solveAndMapToTraces(),C=!0}const[{route:q}]=U;let Y=[];for(let be=0;be<q.length-1;be++)Y.push({from:q[be],to:q[be+1]});const Q=this.source_trace_id;let K=[];if(!C){UZt({edges:Y,db:e,source_trace_id:Q});const be=nle({db:e,source_trace_id:Q,differentNetOnly:!0}).flatMap(Oe=>Oe.edges);Y=RZt({edges:Y,otherEdges:be}),K=PZt({edges:Y,db:e,source_trace_id:this.source_trace_id})}const te=Y[Y.length-1],J=p[p.length-1],fe=ABe(te);Y.push(...tle({lastEdge:te,lastEdgePort:J,lastDominantDirection:fe}));const he=Y[0],ve=p[0],Te=ABe(he);if(Y.unshift(...tle({firstEdge:he,firstEdgePort:ve,firstDominantDirection:Te})),!this.source_trace_id)throw new Error("Missing source_trace_id for schematic trace insertion.");if(this.getSubcircuit()._parsedProps.schTraceAutoLabelEnabled&&wZt(K,Y)>=5&&(this._isSymbolToChipConnection()||this._isSymbolToSymbolConnection()||this._isChipToChipConnection())){this._doInitialSchematicTraceRenderWithDisplayLabel();return}const Pe=e.schematic_trace.insert({source_trace_id:this.source_trace_id,edges:Y,junctions:K});this.schematic_trace_id=Pe.schematic_trace_id,c!=null&&c._connectedSchematicPortPairs&&c._connectedSchematicPortPairs.add(l)}},kZt=E1("tscircuit:core"),FZt=k.object({x:p5,y:p5,z:p5}),Wx=class extends M_{constructor(e){super(e);Je(this,"reactSubtrees",[]);Je(this,"_impliedFootprint");Je(this,"isPrimitiveContainer",!0);Je(this,"_asyncSupplierPartNumbers");Je(this,"pcb_missing_footprint_error_id");this._addChildrenFromStringFootprint(),this.initPorts()}get defaultInternallyConnectedPinNames(){return[]}get internallyConnectedPinNames(){return this._parsedProps.internallyConnectedPins??this.defaultInternallyConnectedPinNames}initPorts(e={}){var o,s,l,c,u,f,p,v,x,S;if((o=this.root)!=null&&o.schematicDisabled)return;const{config:t}=this,n=[],i=this._getSchematicPortArrangement();if(i&&!this._parsedProps.pinLabels){for(const C in i){const O=i[C].pins;if(Array.isArray(O))for(const U of O){const q=BA(U,this._parsedProps.pinLabels);n.push(new W4({pinNumber:q,aliases:((s=e.additionalAliases)==null?void 0:s[`pin${q}`])??[]},{originDescription:`schPortArrangement:${C}`}))}}const E=["left","right","top","bottom"];let b=1;for(const C of E){const O=i[`${C}Size`];for(let U=0;U<O;U++)n.push(new W4({pinNumber:b++,aliases:((l=e.additionalAliases)==null?void 0:l[`pin${b}`])??[]},{originDescription:`schPortArrangement:${C}`}))}}const a=this._parsedProps.pinLabels;if(a)for(let[E,b]of Object.entries(a)){E=E.replace("pin","");let C=n.find(q=>q._parsedProps.pinNumber===Number(E));const O=Array.isArray(b)?b[0]:b,U=Array.isArray(b)?b.slice(1):[];C?(C.externallyAddedAliases.push(O,...U),C.props.name=O):(C=new W4({pinNumber:parseInt(E),name:O,aliases:[...U,...((c=e.additionalAliases)==null?void 0:c[`pin${parseInt(E)}`])??[]]},{originDescription:`pinLabels:pin${E}`}),n.push(C))}if(t.schematicSymbolName){const E=u_[this._getSchematicSymbolNameOrThrow()];if(!E)return;for(const b of E.ports){const C=TBe(b.labels);if(!C)continue;const O=n.find(U=>U._parsedProps.pinNumber===Number(C));if(O)O.schematicSymbolPortDef=b;else{const U=HA(b.labels.concat(((u=e.additionalAliases)==null?void 0:u[`pin${C}`])??[]));U&&(U.originDescription=`schematicSymbol:labels[0]:${b.labels[0]}`,U.schematicSymbolPortDef=b,n.push(U))}}this.addAll(n)}if(!this._getSchematicPortArrangement()){const E=this.getPortsFromFootprint(e);for(const b of E)n.some(C=>C.isMatchingAnyOf(b.getNameAndAliases()))||n.push(b)}for(let E=1;E<=(e.pinCount??this._getPinCount());E++){if(!i||n.find(C=>C._parsedProps.pinNumber===E))continue;let b=[...((f=i.leftSide)==null?void 0:f.pins)??[],...((p=i.rightSide)==null?void 0:p.pins)??[],...((v=i.topSide)==null?void 0:v.pins)??[],...((x=i.bottomSide)==null?void 0:x.pins)??[]].map(C=>BA(C,this._parsedProps.pinLabels));["leftSize","rightSize","topSize","bottomSize","leftPinCount","rightPinCount","topPinCount","bottomPinCount"].some(C=>C in i)&&(b=Array.from({length:this._getPinCount()},(C,O)=>O+1)),b.includes(E)&&n.push(new W4({pinNumber:E,aliases:((S=e.additionalAliases)==null?void 0:S[`pin${E}`])??[]},{originDescription:`notOtherwiseAddedButDeducedFromPinCount:${E}`}))}n.length>0&&this.addAll(n)}_getImpliedFootprintString(){return null}_addChildrenFromStringFootprint(){var a;const{name:e,pcbRotation:t,pinLabels:n}=this.props;let{footprint:i}=this.props;if(i??(i=(a=this._getImpliedFootprintString)==null?void 0:a.call(this)),!!i&&typeof i=="string"){const o=y6.string(i).soup(),s=cZt({componentName:e,componentRotation:t,footprint:i,pinLabels:n},o);this.addAll(s)}}get portMap(){return new Proxy({},{get:(e,t)=>{const n=this.children.find(i=>i.componentName==="Port"&&i.isMatchingNameOrAlias(t));if(!n)throw new Error(`There was an issue finding the port "${t.toString()}" inside of a ${this.componentName} component with name: "${this.props.name}". This is a bug in @tscircuit/core`);return n}})}getInstanceForReactElement(e){for(const t of this.reactSubtrees)if(t.element===e)return t.component;return null}doInitialSourceRender(){const e=this.config.sourceFtype;if(!e)return;const{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:e,name:n.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers});this.source_component_id=i.source_component_id}doInitialSchematicComponentRender(){var i,a,o;if((i=this.root)!=null&&i.schematicDisabled)return;const{db:e}=this.root,{schematicSymbolName:t}=this.config;t?this._doInitialSchematicComponentRenderWithSymbol():this._getSchematicBoxDimensions()&&this._doInitialSchematicComponentRenderWithSchematicBoxDimensions();const n=(a=this.getSubcircuit())==null?void 0:a._getSchematicManualPlacementForComponent(this);if(this.schematic_component_id&&(this.props.schX!==void 0||this.props.schY!==void 0)&&n){if(!this.schematic_component_id)return;const s=PP.parse({type:"schematic_manual_edit_conflict_warning",schematic_manual_edit_conflict_warning_id:`schematic_manual_edit_conflict_${this.source_component_id}`,message:`${this.getString()} has both manual placement and prop coordinates. schX and schY will be used. Remove schX/schY or clear the manual placement.`,schematic_component_id:this.schematic_component_id,source_component_id:this.source_component_id,subcircuit_id:(o=this.getSubcircuit())==null?void 0:o.subcircuit_id});e.schematic_manual_edit_conflict_warning.insert(s)}}_getSchematicSymbolDisplayValue(){}_getInternallyConnectedPins(){if(this.internallyConnectedPinNames.length===0)return[];const e=[];for(const t of this.internallyConnectedPinNames){const n=[];for(const i of t)n.push(this.portMap[i]);e.push(n)}return e}_doInitialSchematicComponentRenderWithSymbol(){var o;if((o=this.root)!=null&&o.schematicDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=this._getSchematicSymbolNameOrThrow(),i=u_[n],a=this._getGlobalSchematicPositionBeforeLayout();if(i){const s=e.schematic_component.insert({center:a,size:i.size,source_component_id:this.source_component_id,symbol_name:n,symbol_display_value:this._getSchematicSymbolDisplayValue()});this.schematic_component_id=s.schematic_component_id}}_doInitialSchematicComponentRenderWithSchematicBoxDimensions(){var f;if((f=this.root)!=null&&f.schematicDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=this._getSchematicBoxDimensions(),i={};if(Array.isArray(t.pinLabels))t.pinLabels.forEach((p,v)=>{i[String(v+1)]=p});else for(const[p,v]of Object.entries(t.pinLabels??{}))i[p]=Array.isArray(v)?v[0]:v;const a=this._getGlobalSchematicPositionBeforeLayout(),o=this._getSchematicPortArrangement(),s=e.schematic_component.insert({center:a,rotation:t.schRotation??0,size:n.getSize(),port_arrangement:aZt(o),pin_spacing:t.schPinSpacing??.2,pin_styles:iZt(t.schPinStyle,t.pinLabels),port_labels:i,source_component_id:this.source_component_id}),l=(o==null?void 0:o.topSide)!==void 0||(o==null?void 0:o.bottomSide)!==void 0,c=n==null?void 0:n.getSize().width,u=n==null?void 0:n.getSize().height;e.schematic_text.insert({text:t.manufacturerPartNumber??"",schematic_component_id:s.schematic_component_id,anchor:"left",rotation:0,position:{x:l?a.x+(c??0)/2+.1:a.x-(c??0)/2,y:l?a.y+(u??0)/2+.35:a.y-(u??0)/2-.13},color:"#006464",font_size:.05}),e.schematic_text.insert({text:t.name??"",schematic_component_id:s.schematic_component_id,anchor:"left",rotation:0,position:{x:l?a.x+(c??0)/2+.1:a.x-(c??0)/2,y:l?a.y+(u??0)/2+.55:a.y+(u??0)/2+.13},color:"#006464",font_size:.05}),this.schematic_component_id=s.schematic_component_id}doInitialPcbComponentRender(){var o;if((o=this.root)!=null&&o.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=this.getSubcircuit(),i=e.pcb_component.insert({center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,layer:t.layer??"top",rotation:t.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:n.subcircuit_id??void 0});if(!t.footprint&&!this.isGroup){const s=e.pcb_missing_footprint_error.insert({message:`No footprint found for component: ${this.getString()}`,source_component_id:`${this.source_component_id}`,error_type:"pcb_missing_footprint_error"});this.pcb_missing_footprint_error_id=s.pcb_missing_footprint_error_id}this.pcb_component_id=i.pcb_component_id;const a=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if((this.props.pcbX!==void 0||this.props.pcbY!==void 0)&&a){const s=DP.parse({type:"pcb_manual_edit_conflict_warning",pcb_manual_edit_conflict_warning_id:`pcb_manual_edit_conflict_${this.source_component_id}`,message:`${this.getString()} has both manual placement and prop coordinates. pcbX and pcbY will be used. Remove pcbX/pcbY or clear the manual placement.`,pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,subcircuit_id:n.subcircuit_id??void 0});e.pcb_manual_edit_conflict_warning.insert(s)}}doInitialPcbComponentSizeCalculation(){var a;if((a=this.root)!=null&&a.pcbDisabled||!this.pcb_component_id)return;const{db:e}=this.root,{_parsedProps:t}=this,n=wBe(this.children);if(n.width===0||n.height===0)return;const i={x:(n.minX+n.maxX)/2,y:(n.minY+n.maxY)/2};e.pcb_component.update(this.pcb_component_id,{center:i,width:n.width,height:n.height})}_renderReactSubtree(e){return{element:e,component:rZt(e)}}doInitialInitializePortsFromChildren(){this.initPorts()}doInitialReactSubtreesRender(){if(mt.isValidElement(this.props.footprint)){if(this.reactSubtrees.some(t=>t.element===this.props.footprint))return;const e=this._renderReactSubtree(this.props.footprint);this.reactSubtrees.push(e),this.add(e.component)}}_hasExistingPortExactly(e){return this.children.filter(n=>n.componentName==="Port").some(n=>{const i=e.getNameAndAliases(),a=n.getNameAndAliases();return i.length===a.length&&i.every(o=>a.includes(o))})}add(e){let t;if(mt.isValidElement(e)){const n=this._renderReactSubtree(e);this.reactSubtrees.push(n),t=n.component}else t=e;if(t.componentName==="Port"){if(this._hasExistingPortExactly(t))return;const i=this.children.filter(a=>a.componentName==="Port").find(a=>a.isMatchingAnyOf(t.getNameAndAliases()));i&&kZt(`Similar ports added. Port 1: ${i}, Port 2: ${t}`)}super.add(t)}getPortsFromFootprint(e){let{footprint:t}=this.props;if((!t||mt.isValidElement(t))&&(t=this.children.find(i=>i.componentName==="Footprint")),typeof t=="string"){const i=y6.string(t).soup(),a=[];for(const o of i)if("port_hints"in o&&o.port_hints){const s=HA(o.port_hints,e);if(!s)continue;s.originDescription=`footprint:string:${t}:port_hints[0]:${o.port_hints[0]}`,a.push(s)}return a}if(!mt.isValidElement(t)&&t&&t.componentName==="Footprint"){const i=t;let a=1;const o=[];for(const s of i.children){if(!s.props.portHints)continue;let l=s.props.portHints;l.some(f=>f.startsWith("pin"))||(l=[...l,`pin${a}`]),a++;const u=HA(l);u&&(u.originDescription=`footprint:${t}`,o.push(u))}return o}const n=[];if(!t){for(const i of this.children)if(i.props.portHints&&i.isPcbPrimitive){const a=HA(i.props.portHints);a&&n.push(a)}}return n}getPortsFromSchematicSymbol(){var i;if((i=this.root)!=null&&i.schematicDisabled)return[];const{config:e}=this;if(!e.schematicSymbolName)return[];const t=u_[e.schematicSymbolName];if(!t)return[];const n=[];for(const a of t.ports){const o=HA(a.labels);o&&(o.schematicSymbolPortDef=a,n.push(o))}return n}doInitialCreateNetsFromProps(){this._createNetsFromProps(this._getNetsFromConnectionsProp())}_getNetsFromConnectionsProp(){const{_parsedProps:e}=this,t=[];if(e.connections)for(const[n,i]of Object.entries(e.connections)){const a=Array.isArray(i)?i:[i];for(const o of a)t.push(o)}return t}_createNetsFromProps(e){_Be(this,e)}_getPcbCircuitJsonBounds(){const{db:e}=this.root;if(!this.pcb_component_id)return super._getPcbCircuitJsonBounds();const t=e.pcb_component.get(this.pcb_component_id);return{center:{x:t.center.x,y:t.center.y},bounds:{left:t.center.x-t.width/2,top:t.center.y-t.height/2,right:t.center.x+t.width/2,bottom:t.center.y+t.height/2},width:t.width,height:t.height}}_getPinCountFromSchematicPortArrangement(){const e=this._getSchematicPortArrangement();if(!e)return 0;if(!MBe(e))return(e.leftSize??e.leftPinCount??0)+(e.rightSize??e.rightPinCount??0)+(e.topSize??e.topPinCount??0)+(e.bottomSize??e.bottomPinCount??0);const{leftSide:n,rightSide:i,topSide:a,bottomSide:o}=e;return Math.max(...(n==null?void 0:n.pins)??[],...(i==null?void 0:i.pins)??[],...(a==null?void 0:a.pins)??[],...(o==null?void 0:o.pins)??[])}_getPinCount(){return this._getSchematicPortArrangement()?this._getPinCountFromSchematicPortArrangement():this.getPortsFromFootprint().length}_getSchematicPortArrangement(){return this._parsedProps.schPinArrangement??this._parsedProps.schPortArrangement}_getSchematicBoxDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;const{_parsedProps:e}=this,t=this._getPinCount(),n=e.schPinSpacing??.2;return vZt({schWidth:e.schWidth,schHeight:e.schHeight,schPinSpacing:n,numericSchPinStyle:_Zt(e.schPinStyle,e.pinLabels),pinCount:t,schPortArrangement:this._getSchematicPortArrangement(),pinLabels:e.pinLabels})}doInitialCadModelRender(){var c;const{db:e}=this.root,{boardThickness:t=0}=((c=this.root)==null?void 0:c._getBoard())??{},n=this._parsedProps.cadModel;if(!this.pcb_component_id||!n&&!this.props.footprint)return;const i=this._getPcbCircuitJsonBounds(),a=e.pcb_component.get(this.pcb_component_id);if(typeof n=="string")throw new Error("String cadModel not yet implemented");const o=FZt.parse({x:0,y:0,z:typeof(n==null?void 0:n.rotationOffset)=="number"?n.rotationOffset:0,...typeof(n==null?void 0:n.rotationOffset)=="object"?n.rotationOffset??{}:{}}),s=lw.parse({x:0,y:0,z:0,...typeof(n==null?void 0:n.positionOffset)=="object"?n.positionOffset:{}}),l=this.props.layer==="bottom"?"bottom":"top";e.cad_component.insert({position:{x:i.center.x+s.x,y:i.center.y+s.y,z:(l==="bottom"?-t/2:t/2)+s.z},rotation:{x:o.x,y:(l==="top"?0:180)+o.y,z:((a==null?void 0:a.rotation)??0)+(l==="bottom"?180:0)+o.z},pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,model_stl_url:"stlUrl"in(n??{})?this._addCachebustToModelUrl(n.stlUrl):void 0,model_obj_url:"objUrl"in(n??{})?this._addCachebustToModelUrl(n.objUrl):void 0,model_jscad:"jscad"in(n??{})?n.jscad:void 0,footprinter_string:typeof this.props.footprint=="string"&&!n?this.props.footprint:void 0})}_addCachebustToModelUrl(e){var n;if(!e||!e.includes("modelcdn.tscircuit.com"))return e;const t=((n=this.root)==null?void 0:n.getClientOrigin())??"";return`${e}${e.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(t)}`}doInitialPartsEngineRender(){const e=this.getInheritedProperty("partsEngine");if(!e)return;const{db:t}=this.root,n=t.source_component.get(this.source_component_id);if(!n||n.supplier_part_numbers)return;let i;this.props.footprint&&typeof this.props.footprint=="string"&&(i=this.props.footprint);const a=e.findPart({sourceComponent:n,footprinterString:i});if(!(a instanceof Promise)){t.source_component.update(this.source_component_id,{supplier_part_numbers:a});return}this._queueAsyncEffect("get-supplier-part-numbers",async()=>{this._asyncSupplierPartNumbers=await a,this._markDirty("PartsEngineRender")})}updatePartsEngineRender(){const{db:e}=this.root,t=e.source_component.get(this.source_component_id);if(t&&!t.supplier_part_numbers&&this._asyncSupplierPartNumbers){e.source_component.update(this.source_component_id,{supplier_part_numbers:this._asyncSupplierPartNumbers});return}}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}_createTracesFromConnectionsProp(){const{_parsedProps:e}=this;if(e.connections)for(const[t,n]of Object.entries(e.connections)){const i=Array.isArray(n)?n:[n];for(const a of i)this.add(new q8({from:`${this.getSubcircuitSelector()} > port.${t}`,to:a}))}}},BZt=class{constructor(r,e={}){Je(this,"input");Je(this,"isRouting",!1);Je(this,"solver");Je(this,"eventHandlers",{complete:[],error:[],progress:[]});Je(this,"cycleCount",0);Je(this,"stepDelay");Je(this,"timeoutId");this.input=r;const{capacityDepth:t,targetMinCapacity:n,stepDelay:i=0}=e;this.solver=new AG(r,{capacityDepth:t,targetMinCapacity:n}),this.stepDelay=i}start(){this.isRouting||(this.isRouting=!0,this.cycleCount=0,this.runCycleAndQueueNextCycle())}runCycleAndQueueNextCycle(){var r;if(this.isRouting)try{if(this.solver.solved||this.solver.failed){this.solver.failed?this.emitEvent({type:"error",error:new Error(this.solver.error||"Routing failed")}):this.emitEvent({type:"complete",traces:this.solver.getOutputSimpleRouteJson().traces||[]}),this.isRouting=!1;return}const e=Date.now(),t=this.solver.iterations;for(;Date.now()-e<250&&!this.solver.failed&&!this.solver.solved;)this.solver.step();const n=(this.solver.iterations-t)/(Date.now()-e)*1e3;this.cycleCount++;const i=((r=this.solver)==null?void 0:r.preview())||void 0,a=this.solver.progress;this.emitEvent({type:"progress",steps:this.cycleCount,iterationsPerSecond:n,progress:a,phase:this.solver.getCurrentPhase(),debugGraphics:i}),this.stepDelay>0?this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),this.stepDelay):this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),0)}catch(e){this.emitEvent({type:"error",error:e instanceof Error?e:new Error(String(e))}),this.isRouting=!1}}stop(){this.isRouting&&(this.isRouting=!1,this.timeoutId!==void 0&&(clearTimeout(this.timeoutId),this.timeoutId=void 0))}on(r,e){r==="complete"?this.eventHandlers.complete.push(e):r==="error"?this.eventHandlers.error.push(e):r==="progress"&&this.eventHandlers.progress.push(e)}emitEvent(r){if(r.type==="complete")for(const e of this.eventHandlers.complete)e(r);else if(r.type==="error")for(const e of this.eventHandlers.error)e(r);else if(r.type==="progress")for(const e of this.eventHandlers.progress)e(r)}solveSync(){if(this.solver.solve(),this.solver.failed)throw new Error(this.solver.error||"Routing failed");return this.solver.getOutputSimpleRouteJson().traces||[]}},PBe=class extends M_{constructor(){super(...arguments);Je(this,"matchedPort",null)}get config(){return{componentName:"TraceHint",zodProps:VUe}}doInitialPortMatching(){const{db:e}=this.root,{_parsedProps:t,parent:n}=this;if(!n)return;if(n.componentName==="Trace"){this.renderError(`Port inference inside trace is not yet supported (${this})`);return}if(!n)throw new Error("TraceHint has no parent");if(!t.for){this.renderError(`TraceHint has no for property (${this})`);return}const i=n.selectOne(t.for,{type:"port"});i||this.renderError(`${this} could not find port for selector "${t.for}"`),this.matchedPort=i,i.registerMatch(this)}getPcbRouteHints(){const{_parsedProps:e}=this,t=e.offset?[e.offset]:e.offsets;if(!t)return[];const n=this._computePcbGlobalTransformBeforeLayout();return t.map(i=>({...Ir(n,i),via:i.via,to_layer:i.to_layer,trace_width:i.trace_width}))}doInitialPcbTraceHintRender(){var n,i,a;if((n=this.root)!=null&&n.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this;e.pcb_trace_hint.insert({pcb_component_id:(i=this.matchedPort)==null?void 0:i.pcb_component_id,pcb_port_id:(a=this.matchedPort)==null?void 0:a.pcb_port_id,route:this.getPcbRouteHints()})}},HZt=(r,e)=>{const t=r.source_group.list(),n=[],i=a=>{const o=t.filter(s=>s.parent_subcircuit_id===a);for(const s of o)s.subcircuit_id&&(n.push(s.subcircuit_id),i(s.subcircuit_id))};return i(e),n},NBe=({db:r,circuitJson:e,subcircuit_id:t,minTraceWidth:n=.1})=>{if(!r&&e&&(r=p4(e)),!r)throw new Error("db or circuitJson is required");const i=r.pcb_trace_hint.list(),a=t?new Set([t]):null;if(t){const S=HZt(r,t);for(const E of S)a.add(E)}const o=(e??r.toArray()).filter(S=>!t||"subcircuit_id"in S&&a.has(S.subcircuit_id)),s=r.pcb_board.list()[0];r=p4(o);const l=k3(o),c=M6([...r.pcb_component.list(),...r.pcb_smtpad.list(),...r.pcb_plated_hole.list(),...r.pcb_hole.list(),...r.pcb_via.list()].filter(S=>!t||(a==null?void 0:a.has(S.subcircuit_id))),l);for(const S of c){const E=S.connectedTo.flatMap(b=>l.getIdsConnectedToNet(b));S.connectedTo.push(...E)}const u=c.flatMap(S=>[{x:S.center.x-S.width/2,y:S.center.y-S.height/2},{x:S.center.x+S.width/2,y:S.center.y+S.height/2}]);let f;s?f={minX:s.center.x-s.width/2,maxX:s.center.x+s.width/2,minY:s.center.y-s.height/2,maxY:s.center.y+s.height/2}:f={minX:Math.min(...u.map(S=>S.x))-1,maxX:Math.max(...u.map(S=>S.x))+1,minY:Math.min(...u.map(S=>S.y))-1,maxY:Math.max(...u.map(S=>S.y))+1};const p=r.source_trace.list().map(S=>{var Q,K,te;const E=S.connected_source_port_ids.map(J=>{const fe=r.source_port.get(J),he=r.pcb_port.getWhere({source_port_id:J});return{...fe,...he}});if(E.length<2)return null;const[b,C]=E,O=((Q=b.layers)==null?void 0:Q[0])??"top",U=((K=C.layers)==null?void 0:K[0])??"top",q=i.filter(J=>J.pcb_port_id===b.pcb_port_id||J.pcb_port_id===C.pcb_port_id),Y=[];for(const J of q){const fe=r.pcb_port.get(J.pcb_port_id),he=((te=fe==null?void 0:fe.layers)==null?void 0:te[0])??"top";for(const ve of J.route)Y.push({x:ve.x,y:ve.y,layer:he})}return{name:S.source_trace_id??l.getNetConnectedToId(S.source_trace_id)??"",source_trace_id:S.source_trace_id,pointsToConnect:[{x:b.x,y:b.y,layer:O},...Y,{x:C.x,y:C.y,layer:U}]}}).filter(S=>S!==null),v=r.source_net.list().filter(S=>!t||(a==null?void 0:a.has(S.subcircuit_id))),x=[];for(const S of v){const E=r.source_trace.list().filter(b=>{var C;return(C=b.connected_source_net_ids)==null?void 0:C.includes(S.source_net_id)});x.push({name:S.source_net_id??l.getNetConnectedToId(S.source_net_id),pointsToConnect:E.flatMap(b=>r.pcb_port.list().filter(O=>b.connected_source_port_ids.includes(O.source_port_id)).map(O=>{var U;return{x:O.x,y:O.y,layer:((U=O.layers)==null?void 0:U[0])??"top",pcb_port_id:O.pcb_port_id}}))})}return{simpleRouteJson:{bounds:f,obstacles:c,connections:[...p,...x],layerCount:2,minTraceWidth:n},connMap:l}},rle=class extends Wx{constructor(){super(...arguments);Je(this,"pcb_group_id",null);Je(this,"subcircuit_id",null);Je(this,"_hasStartedAsyncAutorouting",!1);Je(this,"_asyncAutoroutingResult",null)}get config(){return{zodProps:oUe,componentName:"Group"}}doInitialSourceRender(){const{db:e}=this.root,t=e.source_group.insert({name:this._parsedProps.name,is_subcircuit:this.isSubcircuit});this.subcircuit_id=`subcircuit_${t.source_group_id}`,this.source_group_id=t.source_group_id,e.source_group.update(t.source_group_id,{subcircuit_id:this.subcircuit_id})}doInitialSourceParentAttachment(){var n,i,a;const{db:e}=this.root;if(!this.isSubcircuit)return;const t=(a=(i=(n=this.parent)==null?void 0:n.getSubcircuit)==null?void 0:i.call(n))==null?void 0:a.subcircuit_id;t&&e.source_group.update(this.source_group_id,{parent_subcircuit_id:t})}doInitialPcbComponentRender(){var i;if((i=this.root)!=null&&i.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=e.pcb_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id,name:this._parsedProps.name,center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,pcb_component_ids:[],source_group_id:this.source_group_id});this.pcb_group_id=n.pcb_group_id}doInitialCreateTraceHintsFromProps(){var a;const{_parsedProps:e}=this,{db:t}=this.root,n=e;if(!this.isSubcircuit)return;const i=(a=n.layout)==null?void 0:a.manual_trace_hints;if(i)for(const o of i)this.add(new PBe({for:o.pcb_port_selector,offsets:o.offsets}))}doInitialSourceAddConnectivityMapKey(){if(!this.isSubcircuit)return;const{db:e}=this.root,t=this.selectAll("trace"),n=new w6({});n.addConnections(t.map(i=>{const a=e.source_trace.get(i.source_trace_id);return a?[a.source_trace_id,...a.connected_source_port_ids,...a.connected_source_net_ids]:null}).filter(i=>i!==null));for(const i of t){if(!i.source_trace_id)continue;const a=n.getNetConnectedToId(i.source_trace_id);if(!a)continue;const{name:o}=this._parsedProps;i.subcircuit_connectivity_map_key=`${o??`unnamedsubcircuit${this._renderId}`}_${a}`,e.source_trace.update(i.source_trace_id,{subcircuit_connectivity_map_key:i.subcircuit_connectivity_map_key})}}_areChildSubcircuitsRouted(){const e=this.selectAll("group").filter(t=>t.isSubcircuit);for(const t of e)if(t._shouldRouteAsync()&&!t._asyncAutoroutingResult)return!1;return!0}_shouldRouteAsync(){const e=this._getAutorouterConfig();return e.groupMode==="sequential-trace"?!1:!!(e.local&&e.groupMode==="subcircuit"||!e.local)}_hasTracesToRoute(){const e=E1("tscircuit:core:_hasTracesToRoute"),t=this.selectAll("trace");return e(`[${this.getString()}] has ${t.length} traces to route`),t.length>0}async _runEffectMakeHttpAutoroutingRequest(){var c,u,f,p;const{db:e}=this.root,t=E1("tscircuit:core:_runEffectMakeHttpAutoroutingRequest");this._parsedProps;const n=this._getAutorouterConfig(),i=n.serverUrl,a=n.serverMode,o=(v,x)=>{var S;return t("fetching",v),x.headers&&(x.headers["Tscircuit-Core-Version"]=(S=this.root)==null?void 0:S.getCoreVersion()),fetch(v,x)},s=this.root.db.toArray().filter(v=>v.type.startsWith("source_")||v.type.startsWith("pcb_"));if(a==="solve-endpoint"){if(((c=this.props.autorouter)==null?void 0:c.inputFormat)==="simplified"){const{autorouting_result:x}=await o(`${i}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_simple_route_json:NBe({db:e,minTraceWidth:((u=this.props.autorouter)==null?void 0:u.minTraceWidth)??.15,subcircuit_id:this.subcircuit_id}).simpleRouteJson,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(S=>S.json());this._asyncAutoroutingResult=x,this._markDirty("PcbTraceRender");return}const{autorouting_result:v}=await o(`${i}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_circuit_json:s,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(x=>x.json());this._asyncAutoroutingResult=v,this._markDirty("PcbTraceRender");return}const{autorouting_job:l}=await o(`${i}/autorouting/jobs/create`,{method:"POST",body:JSON.stringify({input_circuit_json:s,provider:"freerouting",autostart:!0,display_name:(f=this.root)==null?void 0:f.name,subcircuit_id:this.subcircuit_id,server_cache_enabled:n.serverCacheEnabled}),headers:{"Content-Type":"application/json"}}).then(v=>v.json());for(;;){const{autorouting_job:v}=await o(`${i}/autorouting/jobs/get`,{method:"POST",body:JSON.stringify({autorouting_job_id:l.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(x=>x.json());if(v.is_finished){const{autorouting_job_output:x}=await o(`${i}/autorouting/jobs/get_output`,{method:"POST",body:JSON.stringify({autorouting_job_id:l.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(S=>S.json());this._asyncAutoroutingResult={output_pcb_traces:x.output_pcb_traces},this._markDirty("PcbTraceRender");break}if(v.has_error)throw e.pcb_autorouting_error.insert({pcb_error_id:l.autorouting_job_id,message:((p=v.error)==null?void 0:p.message)??JSON.stringify(v.error)}),new Error(`Autorouting job failed: ${JSON.stringify(v.error)}`);await new Promise(x=>setTimeout(x,100))}}async _runLocalAutorouting(){var s,l,c,u,f;const{db:e}=this.root;this._parsedProps;const t=E1("tscircuit:core:_runLocalAutorouting");t(`[${this.getString()}] starting local autorouting`);const n=this._getAutorouterConfig(),{simpleRouteJson:i}=NBe({db:e,minTraceWidth:((s=this.props.autorouter)==null?void 0:s.minTraceWidth)??.15,subcircuit_id:this.subcircuit_id});(l=this.root)==null||l.emit("autorouting:start",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),simpleRouteJson:i});let a;n.algorithmFn?a=await n.algorithmFn(i):a=new BZt(i,{capacityDepth:(c=this.props.autorouter)==null?void 0:c.capacityDepth,targetMinCapacity:(u=this.props.autorouter)==null?void 0:u.targetMinCapacity});const o=new Promise((p,v)=>{a.on("complete",x=>{t(`[${this.getString()}] local autorouting complete`),p(x.traces)}),a.on("error",x=>{t(`[${this.getString()}] local autorouting error: ${x.error.message}`),v(x.error)})});a.on("progress",p=>{var v;(v=this.root)==null||v.emit("autorouting:progress",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),...p})}),a.start();try{const p=await o;this._asyncAutoroutingResult={output_pcb_traces:p},this._markDirty("PcbTraceRender")}catch(p){const{db:v}=this.root;throw v.pcb_autorouting_error.insert({pcb_error_id:`pcb_autorouter_error_subcircuit_${this.subcircuit_id}`,message:p instanceof Error?p.message:String(p)}),(f=this.root)==null||f.emit("autorouting:error",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),error:{message:p instanceof Error?p.message:String(p)},simpleRouteJson:i}),p}finally{a.stop()}}_startAsyncAutorouting(){this._hasStartedAsyncAutorouting||(this._hasStartedAsyncAutorouting=!0,this._getAutorouterConfig().local?this._queueAsyncEffect("capacity-mesh-autorouting",async()=>this._runLocalAutorouting()):this._queueAsyncEffect("make-http-autorouting-request",async()=>this._runEffectMakeHttpAutoroutingRequest()))}doInitialPcbTraceRender(){var t;const e=E1("tscircuit:core:doInitialPcbTraceRender");if(this.isSubcircuit&&!((t=this.root)!=null&&t.pcbDisabled)&&!this.getInheritedProperty("routingDisabled")&&!this._shouldUseTraceByTraceRouting()){if(!this._areChildSubcircuitsRouted()){e(`[${this.getString()}] child subcircuits are not routed, skipping async autorouting until subcircuits routed`);return}e(`[${this.getString()}] no child subcircuits to wait for, initiating async routing`),this._hasTracesToRoute()&&this._startAsyncAutorouting()}}updatePcbTraceRender(){var n;const e=E1("tscircuit:core:updatePcbTraceRender");if(e(`[${this.getString()}] updating...`),!this.isSubcircuit)return;if(this._shouldRouteAsync()&&this._hasTracesToRoute()&&!this._hasStartedAsyncAutorouting){this._areChildSubcircuitsRouted()&&(e(`[${this.getString()}] child subcircuits are now routed, starting async autorouting`),this._startAsyncAutorouting());return}if(!this._asyncAutoroutingResult||this._shouldUseTraceByTraceRouting())return;const{db:t}=this.root;if(this._asyncAutoroutingResult.output_simple_route_json){e(`[${this.getString()}] updating PCB traces from simple route json (${(n=this._asyncAutoroutingResult.output_simple_route_json.traces)==null?void 0:n.length} traces)`),this._updatePcbTraceRenderFromSimpleRouteJson();return}if(this._asyncAutoroutingResult.output_pcb_traces){e(`[${this.getString()}] updating PCB traces from ${this._asyncAutoroutingResult.output_pcb_traces.length} traces`),this._updatePcbTraceRenderFromPcbTraces();return}}_updatePcbTraceRenderFromSimpleRouteJson(){const{db:e}=this.root,{traces:t}=this._asyncAutoroutingResult.output_simple_route_json;if(t)for(const n of t)e.pcb_trace.insert({subcircuit_id:this.subcircuit_id,route:n.route})}_updatePcbTraceRenderFromPcbTraces(){const{output_pcb_traces:e}=this._asyncAutoroutingResult;if(!e)return;const{db:t}=this.root;for(const n of e)if(n.type==="pcb_trace"){if(n.subcircuit_id=this.subcircuit_id,n.connection_name){const i=n.connection_name;n.source_trace_id=i}t.pcb_trace.insert(n)}for(const n of e)if(n.type!=="pcb_via"&&n.type==="pcb_trace")for(const i of n.route)i.route_type==="via"&&t.pcb_via.insert({pcb_trace_id:n.pcb_trace_id,x:i.x,y:i.y,hole_diameter:.3,outer_diameter:.6,layers:[i.from_layer,i.to_layer],from_layer:i.from_layer,to_layer:i.to_layer})}doInitialSchematicLayout(){if(!this.isSubcircuit||!this._parsedProps.schAutoLayoutEnabled)return;const{db:t}=this.root,n=this.getDescendants(),i=[];for(const s of n)if("schematic_component_id"in s){const l=t.schematic_component.get(s.schematic_component_id);if(l){const c=t.schematic_port.list().filter(u=>u.schematic_component_id===l.schematic_component_id);i.push(...c)}}const a=vG(t.toArray()),o=yG(a);mG(t.toArray(),o)}_getAutorouterConfig(){const e={serverUrl:"https://registry-api.tscircuit.com",serverMode:"job",serverCacheEnabled:!0},t=this._parsedProps.autorouter??this.getInheritedProperty("autorouter");return typeof t=="object"?{local:!(t.serverUrl||t.serverMode||t.serverCacheEnabled),...e,...t}:t==="auto-local"?{local:!0,groupMode:"subcircuit"}:t==="sequential-trace"?{local:!0,groupMode:"sequential-trace"}:t==="subcircuit"?{local:!0,groupMode:"subcircuit"}:t==="auto-cloud"?{local:!1,groupMode:"subcircuit",serverUrl:e.serverUrl,serverMode:e.serverMode,serverCacheEnabled:!0}:{local:!0,groupMode:"subcircuit"}}_shouldUseTraceByTraceRouting(){return this._getAutorouterConfig().groupMode==="sequential-trace"}doInitialPcbDesignRuleChecks(){var t;if((t=this.root)!=null&&t.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;const{db:e}=this.root;if(this.isSubcircuit){const n=new Map;for(const i of this.children)if(!i.isSubcircuit&&i._parsedProps.name){const a=n.get(i._parsedProps.name)||[];a.push(i),n.set(i._parsedProps.name,a)}for(const[i,a]of n.entries())a.length>1&&e.pcb_trace_error.insert({error_type:"pcb_trace_error",message:`Multiple components found with name "${i}" in subcircuit "${this._parsedProps.name||"unnamed"}". Component names must be unique within a subcircuit.`,source_trace_id:"",pcb_trace_id:"",pcb_component_ids:a.map(o=>o.pcb_component_id).filter(Boolean),pcb_port_ids:[]})}}},jZt=class extends rle{constructor(){super(...arguments);Je(this,"pcb_board_id",null);Je(this,"_drcChecksComplete",!1);Je(this,"_connectedSchematicPortPairs",new Set)}get isSubcircuit(){return!0}get config(){return{componentName:"Board",zodProps:voe}}get boardThickness(){const{_parsedProps:e}=this;return 1.4}get allLayers(){return["top","bottom","inner1","inner2"]}doInitialPcbBoardAutoSize(){var v;if((v=this.root)!=null&&v.pcbDisabled||!this.pcb_board_id)return;const{db:e}=this.root,{_parsedProps:t}=this;if(t.width&&t.height)return;let n=1/0,i=1/0,a=-1/0,o=-1/0;const s=e.pcb_component.list();let l=!1;for(const x of s){const{width:S,height:E,center:b}=x;S===0||E===0||(l=!0,n=Math.min(n,b.x-S/2),i=Math.min(i,b.y-E/2),a=Math.max(a,b.x+S/2),o=Math.max(o,b.y+E/2))}const c=2,u=l?a-n+c*2:0,f=l?o-i+c*2:0,p={x:l?(n+a)/2+(t.outlineOffsetX??0):t.outlineOffsetX??0,y:l?(i+o)/2+(t.outlineOffsetY??0):t.outlineOffsetY??0};e.pcb_board.update(this.pcb_board_id,{width:u,height:f,center:p})}doInitialPcbComponentRender(){var o,s;if((o=this.root)!=null&&o.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this;let n=t.width??0,i=t.height??0;if(t.outline){const l=t.outline.map(x=>x.x),c=t.outline.map(x=>x.y),u=Math.min(...l),f=Math.max(...l),p=Math.min(...c),v=Math.max(...c);n=f-u,i=v-p}const a=e.pcb_board.insert({center:{x:(t.pcbX??0)+(t.outlineOffsetX??0),y:(t.pcbY??0)+(t.outlineOffsetY??0)},thickness:this.boardThickness,num_layers:this.allLayers.length,width:n,height:i,outline:(s=t.outline)==null?void 0:s.map(l=>({x:l.x+(t.outlineOffsetX??0),y:l.y+(t.outlineOffsetY??0)})),material:t.material});this.pcb_board_id=a.pcb_board_id}removePcbComponentRender(){const{db:e}=this.root;this.pcb_board_id&&(e.pcb_board.delete(this.pcb_board_id),this.pcb_board_id=null)}_computePcbGlobalTransformBeforeLayout(){return Zm()}doInitialPcbDesignRuleChecks(){var e;(e=this.root)!=null&&e.pcbDisabled||this.getInheritedProperty("routingDisabled")||super.doInitialPcbDesignRuleChecks()}updatePcbDesignRuleChecks(){var n;if((n=this.root)!=null&&n.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;const{db:e}=this.root;if(!this._areChildSubcircuitsRouted()||this._drcChecksComplete)return;this._drcChecksComplete=!0;const t=YUe(e.toArray());for(const i of t)e.pcb_trace_error.insert(i)}_emitRenderLifecycleEvent(e,t){var n;super._emitRenderLifecycleEvent(e,t),t==="start"&&((n=this.root)==null||n.emit("board:renderPhaseStarted",{renderId:this._renderId,phase:e}))}},VZt=new Proxy({},{get:(r,e)=>e}),jA=VZt,GZt=class extends Wx{get config(){return{componentName:"Capacitor",schematicSymbolName:this.props.polarized?"capacitor_polarized":this.props.symbolName??"capacitor",zodProps:hUe,sourceFtype:jA.simple_capacitor}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){const r=`${f3(this._parsedProps.capacitance)}F`;return this._parsedProps.schShowRatings&&this._parsedProps.maxVoltageRating?`${r}/${f3(this._parsedProps.maxVoltageRating)}V`:r}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.decouplingFor,this.props.decouplingTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.decouplingFor&&this.props.decouplingTo&&(this.add(new q8({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.decouplingFor})),this.add(new q8({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.decouplingTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({ftype:"simple_capacitor",name:e.name,manufacturer_part_number:e.manufacturerPartNumber??e.mfn,supplier_part_numbers:e.supplierPartNumbers,capacitance:e.capacitance,max_voltage_rating:e.maxVoltageRating,max_decoupling_trace_length:e.maxDecouplingTraceLength,display_capacitance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!e.polarized});this.source_component_id=t.source_component_id}},DBe=class extends Wx{constructor(){super(...arguments);Je(this,"schematicBoxDimensions",null)}get config(){return{componentName:"Chip",zodProps:yoe,shouldRenderAsSchematicBox:!0}}doInitialSchematicComponentRender(){const{_parsedProps:e}=this;(e==null?void 0:e.noSchematicRepresentation)!==!0&&super.doInitialSchematicComponentRender()}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_chip",name:t.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers});this.source_component_id=n.source_component_id}doInitialPcbComponentRender(){var i;if((i=this.root)!=null&&i.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=e.pcb_component.insert({center:{x:t.pcbX??0,y:t.pcbY??0},width:2,height:3,layer:t.layer??"top",rotation:t.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.pcb_component_id=n.pcb_component_id}doInitialCreateTracesFromProps(){const{_parsedProps:e}=this;if(e.externallyConnectedPins)for(const[t,n]of e.externallyConnectedPins)this.add(new q8({from:`${this.getSubcircuitSelector()} > port.${t}`,to:`${this.getSubcircuitSelector()} > port.${n}`}));this._createTracesFromConnectionsProp()}},qZt=class extends Wx{constructor(){super(...arguments);Je(this,"pos",this.portMap.pin1);Je(this,"anode",this.portMap.pin1);Je(this,"neg",this.portMap.pin2);Je(this,"cathode",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"diode",componentName:"Diode",zodProps:RUe,sourceFtype:"simple_diode"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_diode",name:t.name,manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=n.source_component_id}},$Zt=class extends Wx{constructor(){super(...arguments);Je(this,"schematicDimensions",null)}get config(){let e="";if(this.props.pinCount&&(e+=`solderjumper${this.props.pinCount||2}`),Array.isArray(this.props.internallyConnectedPins)&&this.props.internallyConnectedPins.length>0){const t=Array.from(new Set(this.props.internallyConnectedPins.flat())).sort().join("");e+=`_bridged${t}`}return{schematicSymbolName:e,componentName:"Jumper",zodProps:sUe,shouldRenderAsSchematicBox:!0}}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_chip",name:t.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=n.source_component_id}doInitialPcbComponentRender(){var i;if((i=this.root)!=null&&i.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=e.pcb_component.insert({center:{x:t.pcbX??0,y:t.pcbY??0},width:2,height:3,layer:t.layer??"top",rotation:t.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.pcb_component_id=n.pcb_component_id}doInitialPcbTraceRender(){const{db:e}=this.root,t=e.pcb_port.list({pcb_component_id:this.pcb_component_id}),n={};for(let o=0;o<t.length;o++){const s=t[o],l=e.source_port.get(s.source_port_id);let c="";if(typeof(l==null?void 0:l.pin_number)=="number")c=l.pin_number.toString();else if(Array.isArray(l==null?void 0:l.port_hints)){let u=l.port_hints.find(f=>/^(pin)?\d+$/.test(f));u&&(/^pin\d+$/.test(u)?c=u.replace(/^pin/,""):c=u)}n[c]=s.pcb_port_id}const i=e.pcb_trace.list(),a=o=>{if(o&&typeof o=="string"&&o.startsWith("{PIN")){const s=o.replace("{PIN","").replace("}","");return n[s]||o}return o};for(const o of i)if(o.route)for(const s of o.route)s.route_type==="wire"&&(s.start_pcb_port_id=a(s.start_pcb_port_id),s.end_pcb_port_id=a(s.end_pcb_port_id))}},YZt=class extends Wx{constructor(){super(...arguments);Je(this,"pos",this.portMap.pin1);Je(this,"anode",this.portMap.pin1);Je(this,"neg",this.portMap.pin2);Je(this,"cathode",this.portMap.pin2)}get config(){return{componentName:"Led",schematicSymbolName:this.props.symbolName??"led",zodProps:AUe,sourceFtype:"simple_diode"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_diode",name:t.name,manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=n.source_component_id}},XZt=class extends Wx{constructor(){super(...arguments);Je(this,"pos",this.portMap.pin1);Je(this,"positive",this.portMap.pin1);Je(this,"neg",this.portMap.pin2);Je(this,"negative",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"power_factor_meter_horz",componentName:"PowerSource",zodProps:zUe,sourceFtype:"simple_power_source"}}initPorts(){this.add(new W4({name:"pin1",pinNumber:1,aliases:["positive","pos"]})),this.add(new W4({name:"pin2",pinNumber:2,aliases:["negative","neg"]}))}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_power_source",name:t.name,voltage:t.voltage,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=n.source_component_id}},WZt=class extends Wx{get config(){return{componentName:"Resistor",schematicSymbolName:this.props.symbolName??"boxresistor",zodProps:uUe,sourceFtype:"simple_resistor"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return`${f3(this._parsedProps.resistance)}Ω`}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.pullupFor,this.props.pullupTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.pullupFor&&this.props.pullupTo&&(this.add(new q8({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pullupFor})),this.add(new q8({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pullupTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({ftype:"simple_resistor",name:e.name,manufacturer_part_number:e.manufacturerPartNumber??e.mfn,supplier_part_numbers:e.supplierPartNumbers,resistance:e.resistance,display_resistance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!0});this.source_component_id=t.source_component_id}},ZZt=["leftedge","rightedge","topedge","bottomedge","center"],QZt=class extends M_{get config(){return{componentName:"Constraint",zodProps:mUe}}constructor(r){if(super(r),("xdist"in r||"ydist"in r)&&!("edgeToEdge"in r)&&!("centerToCenter"in r))throw new Error(`edgeToEdge, centerToCenter must be set for xDist or yDist for ${this}`);if("for"in r&&r.for.length<2)throw new Error(`"for" must have at least two selectors for ${this}`)}_getAllReferencedComponents(){const r=[],e=this.getPrimitiveContainer();function t(n){const i=n.split(" ").pop(),a=ZZt.includes(i)?i:void 0,o=a?n.replace(` ${a}`,""):n,s=e.selectOne(o,{pcbPrimitive:!0});s&&r.push({selector:n,component:s,componentSelector:o,edge:a})}for(const n of["left","right","top","bottom"])n in this._parsedProps&&t(this._parsedProps[n]);if("for"in this._parsedProps)for(const n of this._parsedProps.for)t(n);return{componentsWithSelectors:r}}},KZt=class extends M_{constructor(){super(...arguments);Je(this,"fabrication_note_path_id",null)}get config(){return{componentName:"FabricationNotePath",zodProps:DUe}}doInitialPcbPrimitiveRender(){var s,l;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:e}=this.root,t=this.getSubcircuit(),{_parsedProps:n}=this,i=n.layer??"top";if(i!=="top"&&i!=="bottom")throw new Error(`Invalid layer "${i}" for SilkscreenPath. Must be "top" or "bottom".`);const a=this._computePcbGlobalTransformBeforeLayout(),o=e.pcb_fabrication_note_path.insert({pcb_component_id:(l=this.parent)==null?void 0:l.pcb_component_id,layer:i,color:n.color,route:n.route.map(c=>{const u=Ir(a,{x:c.x,y:c.y});return{...c,x:u.x,y:u.y}}),stroke_width:n.strokeWidth??.1,subcircuit_id:(t==null?void 0:t.subcircuit_id)??void 0});this.fabrication_note_path_id=o.pcb_fabrication_note_path_id}},JZt=class extends M_{get config(){return{componentName:"FabricationNoteText",zodProps:NUe}}doInitialPcbPrimitiveRender(){var i,a;if((i=this.root)!=null&&i.pcbDisabled)return;const{db:r}=this.root,{_parsedProps:e}=this,t=this.getPrimitiveContainer(),n=this.getSubcircuit();r.pcb_fabrication_note_text.insert({anchor_alignment:e.anchorAlignment,anchor_position:{x:e.pcbX??0,y:e.pcbY??0},font:e.font??"tscircuit2024",font_size:e.fontSize??1,layer:"top",color:e.color,text:e.text??"",pcb_component_id:t.pcb_component_id,subcircuit_id:(n==null?void 0:n.subcircuit_id)??void 0,pcb_group_id:((a=this.getGroup())==null?void 0:a.pcb_group_id)??void 0})}},eQt=class extends rle{constructor(r){super({...r,subcircuit:!0})}},tQt=class extends M_{constructor(){super(...arguments);Je(this,"source_net_alias_id")}get config(){return{componentName:"NetAlias",zodProps:EUe}}doInitialSchematicComponentRender(){var a;if((a=this.root)!=null&&a.schematicDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n={x:t.schX??0,y:t.schY??0},i=e.schematic_net_label.insert({text:t.net,source_net_id:t.net,anchor_position:n,center:n,anchor_side:"bottom"});this.source_net_alias_id=i.source_net_id}},nQt=class extends M_{constructor(){super(...arguments);Je(this,"pcb_silkscreen_circle_id",null);Je(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenCircle",zodProps:HUe}}doInitialPcbPrimitiveRender(){var s,l,c;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,{maybeFlipLayer:n}=this._getPcbPrimitiveFlippedHelpers(),i=n(t.layer??"top");if(i!=="top"&&i!=="bottom")throw new Error(`Invalid layer "${i}" for SilkscreenCircle. Must be "top" or "bottom".`);this._computePcbGlobalTransformBeforeLayout();const a=this.getSubcircuit(),o=e.pcb_silkscreen_circle.insert({pcb_component_id:(l=this.parent)==null?void 0:l.pcb_component_id,layer:i,center:{x:t.pcbX??0,y:t.pcbY??0},radius:t.radius,subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((c=this.getGroup())==null?void 0:c.pcb_group_id)??void 0,stroke_width:t.strokeWidth??.1});this.pcb_silkscreen_circle_id=o.pcb_silkscreen_circle_id}getPcbSize(){const{_parsedProps:e}=this,t=e.radius*2;return{width:t,height:t}}},rQt=class extends M_{constructor(){super(...arguments);Je(this,"pcb_silkscreen_rect_id",null);Je(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenRect",zodProps:BUe}}doInitialPcbPrimitiveRender(){var s,l,c;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,{maybeFlipLayer:n}=this._getPcbPrimitiveFlippedHelpers(),i=n(t.layer??"top");if(i!=="top"&&i!=="bottom")throw new Error(`Invalid layer "${i}" for SilkscreenRect. Must be "top" or "bottom".`);const a=this.getSubcircuit(),o=e.pcb_silkscreen_rect.insert({pcb_component_id:(l=this.parent)==null?void 0:l.pcb_component_id,layer:i,center:{x:t.pcbX??0,y:t.pcbY??0},width:t.width,height:t.height,subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((c=this==null?void 0:this.getGroup())==null?void 0:c.pcb_group_id)??void 0,stroke_width:t.strokeWidth??.1});this.pcb_silkscreen_rect_id=o.pcb_silkscreen_rect_id}getPcbSize(){const{_parsedProps:e}=this;return{width:e.width,height:e.height}}},iQt=class extends M_{constructor(){super(...arguments);Je(this,"pcb_silkscreen_line_id",null);Je(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenLine",zodProps:FUe}}doInitialPcbPrimitiveRender(){var s,l,c;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,{maybeFlipLayer:n}=this._getPcbPrimitiveFlippedHelpers(),i=n(t.layer??"top");if(i!=="top"&&i!=="bottom")throw new Error(`Invalid layer "${i}" for SilkscreenLine. Must be "top" or "bottom".`);const a=this.getSubcircuit(),o=e.pcb_silkscreen_line.insert({pcb_component_id:(l=this.parent)==null?void 0:l.pcb_component_id,layer:i,x1:t.x1,y1:t.y1,x2:t.x2,y2:t.y2,stroke_width:t.strokeWidth??.1,subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((c=a==null?void 0:a.getGroup())==null?void 0:c.pcb_group_id)??void 0});this.pcb_silkscreen_line_id=o.pcb_silkscreen_line_id}getPcbSize(){const{_parsedProps:e}=this,t=Math.abs(e.x2-e.x1),n=Math.abs(e.y2-e.y1);return{width:t,height:n}}},aQt=class extends M_{constructor(){super(...arguments);Je(this,"pcb_via_id",null);Je(this,"matchedPort",null);Je(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Via",zodProps:LUe}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){const{_parsedProps:e}=this;return{width:e.outerDiameter,height:e.outerDiameter}}_getPcbCircuitJsonBounds(){const{db:e}=this.root,t=e.pcb_via.get(this.pcb_via_id),n=this.getPcbSize();return{center:{x:t.x,y:t.y},bounds:{left:t.x-n.width/2,top:t.y-n.height/2,right:t.x+n.width/2,bottom:t.y+n.height/2},width:n.width,height:n.height}}_setPositionFromLayout(e){const{db:t}=this.root;t.pcb_via.update(this.pcb_via_id,{x:e.x,y:e.y})}doInitialPcbPrimitiveRender(){var o,s;if((o=this.root)!=null&&o.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=this._getGlobalPcbPositionBeforeLayout(),i=this.getSubcircuit(),a=e.pcb_via.insert({x:n.x,y:n.y,hole_diameter:t.holeDiameter,outer_diameter:t.outerDiameter,layers:["bottom","top"],from_layer:t.fromLayer||"bottom",to_layer:t.toLayer||"top",subcircuit_id:(i==null?void 0:i.subcircuit_id)??void 0,pcb_group_id:((s=this.getGroup())==null?void 0:s.pcb_group_id)??void 0});this.pcb_via_id=a.pcb_via_id}},oQt=class extends Wx{get config(){return{componentName:"Battery",schematicSymbolName:this.props.symbolName??"battery",zodProps:bUe,sourceFtype:"simple_power_source"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({name:e.name,ftype:"simple_power_source",capacity:e.capacity,supplier_part_numbers:e.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=t.source_component_id}},sQt=class extends Wx{get config(){return{componentName:"PinHeader",zodProps:SUe,shouldRenderAsSchematicBox:!0}}_getImpliedFootprintString(){var i;const r=this._parsedProps.pinCount??((i=this._parsedProps.pinLabels)==null?void 0:i.length)??0,e=this._parsedProps.holeDiameter,t=this._parsedProps.platedDiameter,n=this._parsedProps.pitch;return r>0&&n?!e&&!t?`pinrow${r}_p${n}`:`pinrow${r}_p${n}_id${e}_od${t}`:null}initPorts(){var e,t;const r=this._parsedProps.pinCount??((e=this._parsedProps.pinLabels)==null?void 0:e.length)??1;for(let n=1;n<=r;n++)this.add(new W4({name:`pin${n}`,pinNumber:n,aliases:[(t=this._parsedProps.pinLabels)==null?void 0:t[n-1]].filter(Boolean)}))}_getSchematicPortArrangement(){const r=this._parsedProps.pinCount??1,e=this._parsedProps.facingDirection??"right";return{leftSize:e==="left"?r:0,rightSize:e==="right"?r:0}}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({ftype:"simple_pin_header",name:e.name,supplier_part_numbers:e.supplierPartNumbers,pin_count:e.pinCount,gender:e.gender,are_pins_interchangeable:!0});this.source_component_id=t.source_component_id}};function lQt(r){switch(r){case"two_ground_pins":return"crystal_4pin";case"ground_pin":return"resonator";case"no_ground":return"crystal";default:return"crystal"}}var cQt=class extends Wx{get config(){return{componentName:"Resonator",schematicSymbolName:this.props.symbolName??lQt(this.props.pinVariant),zodProps:pUe,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=e.pinVariant||"no_ground",n=r.source_component.insert({ftype:"simple_resonator",name:e.name,frequency:e.frequency,load_capacitance:e.loadCapacitance,supplier_part_numbers:e.supplierPartNumbers,pin_variant:t,are_pins_interchangeable:t==="no_ground"||t==="ground_pin"});this.source_component_id=n.source_component_id}},uQt=class extends Wx{get config(){return{componentName:"Inductor",schematicSymbolName:this.props.symbolName??"inductor",zodProps:CUe,sourceFtype:jA.simple_inductor}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({name:e.name,ftype:jA.simple_inductor,inductance:e.inductance,supplier_part_numbers:e.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=t.source_component_id}};function fQt(r){switch(r){case"three_pin":return"potentiometer3";case"two_pin":return"potentiometer2";default:return"potentiometer2"}}var dQt=class extends Wx{get config(){return{componentName:"Potentiometer",schematicSymbolName:this.props.symbolName??fQt(this.props.pinVariant),zodProps:fUe,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=e.pinVariant||"two_pin",n=r.source_component.insert({ftype:"simple_potentiometer",name:e.name,max_resistance:e.maxResistance,pin_variant:t,are_pins_interchangeable:t==="two_pin"});this.source_component_id=n.source_component_id}},pQt=class extends Wx{get config(){return{componentName:"PushButton",schematicSymbolName:this.props.symbolName??"push_button_normally_open_momentary",zodProps:wUe,sourceFtype:jA.simple_push_button}}get defaultInternallyConnectedPinNames(){return[["pin1","pin4"],["pin2","pin3"]]}initPorts(){super.initPorts({pinCount:4,additionalAliases:{pin1:["side1"],pin3:["side2"]}})}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({name:e.name,ftype:jA.simple_push_button,supplier_part_numbers:e.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=t.source_component_id}},hQt=class extends Wx{get config(){return{schematicSymbolName:this.props.symbolName??(this.props.pinVariant==="four_pin"?"crystal_4pin":"crystal"),componentName:"Crystal",zodProps:dUe,sourceFtype:"simple_crystal"}}initPorts(){const r=this.props.pinVariant==="four_pin"?{pin1:["left1","1"],pin2:["top1","2","gnd1"],pin3:["right1","3"],pin4:["bottom1","4","gnd2"]}:{pin1:["pos","left"],pin2:["neg","right"]};super.initPorts({additionalAliases:r})}_getSchematicSymbolDisplayValue(){return`${f3(this._parsedProps.frequency)}Hz`}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({name:e.name,ftype:"simple_crystal",frequency:e.frequency,load_capacitance:e.loadCapacitance,pin_variant:e.pinVariant||"two_pin",are_pins_interchangeable:(e.pinVariant||"two_pin")==="two_pin"});this.source_component_id=t.source_component_id}},mQt=class extends Wx{constructor(){super(...arguments);Je(this,"emitter",this.portMap.pin1);Je(this,"collector",this.portMap.pin2);Je(this,"base",this.portMap.pin3)}get config(){return{componentName:"Transistor",schematicSymbolName:this.props.type==="npn"?"npn_bipolar_transistor":"pnp_bipolar_transistor",zodProps:TUe,sourceFtype:"simple_transistor",shouldRenderAsSchematicBox:!1}}initPorts(){const e=this.props.type==="npn"?{pin1:["emitter","e"],pin2:["collector","c"],pin3:["base","b"]}:{pin1:["collector","c"],pin2:["emitter","e"],pin3:["base","b"]};super.initPorts({pinCount:3,additionalAliases:e})}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_transistor",name:t.name,transistor_type:t.type});this.source_component_id=n.source_component_id}},vQt=class extends Wx{get config(){const r=this.props.mosfetMode==="depletion"?"d":"e";return{componentName:"Mosfet",schematicSymbolName:`${this.props.channelType}_channel_${r}_mosfet_transistor`,zodProps:MUe,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({ftype:"simple_mosfet",name:e.name,mosfet_mode:e.mosfetMode,channel_type:e.channelType});this.source_component_id=t.source_component_id}},yQt=class extends Wx{_getSwitchType(){const{spst:r,spdt:e,dpst:t,dpdt:n,type:i}=this._parsedProps??{};return n?"dpdt":r?"spst":e?"spdt":t?"dpst":i??"spst"}get config(){const r=this._getSwitchType(),{isNormallyClosed:e}=this._parsedProps??{};return{componentName:"Switch",schematicSymbolName:{spst:e?"spst_normally_closed_switch":"spst_switch",spdt:e?"spdt_normally_closed_switch":"spdt_switch",dpst:e?"dpst_normally_closed_switch":"dpst_switch",dpdt:e?"dpdt_normally_closed_switch":"dpdt_switch"}[r]??"spst_switch",zodProps:PUe,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({ftype:"simple_switch",name:e.name,switch_type:e.type,is_normally_closed:e.isNormallyClosed??!1,are_pins_interchangeable:this._getSwitchType()==="spst"});this.source_component_id=t.source_component_id}},gQt=class extends M_{constructor(){super(...arguments);Je(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicText",zodProps:UUe}}doInitialSchematicPrimitiveRender(){var n;if((n=this.root)!=null&&n.schematicDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this;e.schematic_text.insert({anchor:t.anchor??"center",text:t.text,font_size:t.fontSize,color:t.color||"#000000",position:{x:t.schX,y:t.schY},rotation:t.schRotation??0})}};new Proxy({},{get:(r,e)=>{const t=(...n)=>(n[0],new Proxy({},{get:(i,a)=>`.${e} > .${a}`}));return new Proxy(t,{get:(n,i)=>e==="net"?`net.${i}`:e==="subcircuit"?new Proxy({},{get:(a,o)=>new Proxy({},{get:(s,l)=>`subcircuit.${i} > .${o} > .${l}`})}):`.${e} > .${i}`,apply:(n,i,a)=>new Proxy({},{get:(o,s)=>{const l=`.${e} > .${s}`;return e.startsWith("U")?l:new Proxy(new String(l),{get:(c,u)=>typeof u=="symbol"||u==="toString"?()=>l:`.${e} > .${s} > .${u}`})}})})}}),pBe(fBe),pBe({Bug:DBe});const LBe=r=>`hsl(${T3.indexOf(r)*137.5%360}, 70%, 50%)`,_Qt=({phaseTimings:r})=>{if(!r)return null;const e=Object.values(r).reduce((t,n)=>t+n,0);return ut.jsxs("div",{className:"rf-space-y-2 rf-w-full rf-px-4",children:[ut.jsx("div",{className:"rf-relative rf-h-8 rf-flex rf-rounded-sm",children:T3.map(t=>{const n=r[t]||0,i=n/e*100;return ut.jsx("div",{className:"rf-group/bar rf-relative rf-overflow-visible",style:{width:`${i}%`,backgroundColor:LBe(t)},children:ut.jsxs("div",{className:"rf-opacity-0 group-hover/bar:rf-opacity-100 rf-transition-opacity rf-absolute rf-bottom-full rf-left-1/2 rf-transform -rf-translate-x-1/2 rf-mb-2 rf-px-2 rf-py-1 rf-text-xs rf-whitespace-nowrap rf-rounded rf-bg-gray-900 rf-text-white rf-pointer-events-none",children:[t,": ",n.toFixed(1),"ms"]})},t)})}),ut.jsxs("div",{className:"rf-text-xs rf-text-gray-500",children:["Total: ",e.toFixed(2),"ms"]})]})},xQt=({renderLog:r})=>{const[e,t]=mt.useState("chronological");if(!r)return ut.jsx("div",{className:"rf-p-4 rf-bg-gray-100 rf-rounded-md",children:"No render log, make sure this tab is open when you render (TODO add a rerender button here)"});const n=Object.entries((r==null?void 0:r.phaseTimings)??{});e==="chronological"?n.sort((a,o)=>T3.indexOf(a[0])-T3.indexOf(o[0])):n.sort((a,o)=>o[1]-a[1]);const i=n.reduce((a,[o,s])=>a+s,0);return ut.jsxs("div",{className:"rf-bg-white",children:[ut.jsxs("div",{className:"rf-flex rf-justify-between rf-items-center",children:[ut.jsx("div",{children:"Render Logs"}),ut.jsxs("div",{className:"rf-mb-4 rf-pr-2 rf-flex rf-text-xs rf-items-center",children:[ut.jsx("div",{className:"rf-mr-2",children:"Sort by:"}),ut.jsxs("select",{value:e,onChange:a=>t(a.target.value),className:"rf-px-2 rf-py-1 rf-border rf-rounded rf-text-xs",children:[ut.jsx("option",{value:"chronological",children:"Phase Order"}),ut.jsx("option",{value:"longest",children:"Duration"})]})]})]}),ut.jsx(_Qt,{phaseTimings:r.phaseTimings}),ut.jsxs("table",{className:"rf-w-full rf-text-xs",children:[ut.jsx("thead",{children:ut.jsxs("tr",{children:[ut.jsx("th",{className:"rf-text-left rf-p-2",children:"Phase Order"}),ut.jsx("th",{className:"rf-text-left rf-p-2",children:"Phase"}),ut.jsx("th",{className:"rf-text-left rf-p-2",children:"Duration (ms)"})]})}),ut.jsx("tbody",{children:n.map(([a,o])=>ut.jsxs("tr",{children:[ut.jsx("td",{className:"rf-p-2",children:T3.indexOf(a)}),ut.jsx("td",{className:"rf-p-2",children:a}),ut.jsx("td",{className:"rf-p-2",children:ut.jsx("div",{className:"rf-w-8",children:ut.jsx("div",{className:"rf-h-2 rf-rounded-sm",style:{backgroundColor:LBe(a),width:`${o/i*100}%`}})})}),ut.jsx("td",{className:"rf-p-2",children:ut.jsxs("div",{className:"rf-flex w-full",children:[ut.jsxs("span",{className:"rf-flex-grow",children:[o,"ms"]}),ut.jsxs("span",{className:"rf-text-gray-500 rf-pr-2",children:[(o/i*100).toFixed(1),"%"]})]})})]},a))})]})]})},bQt="0.0.444",SQt=["assembly","bom","circuit_json","errors","render_log"],EQt=({code:r,onRunClicked:e=void 0,errorMessage:t,circuitJson:n,autoroutingGraphics:i,showRightHeaderContent:a=!0,showCodeTab:o=!1,codeTabContent:s,showJsonTab:l=!0,showRenderLogTab:c=!0,onActiveTabChange:u,renderLog:f,showImportAndFormatButtons:p=!0,className:v,headerClassName:x,leftHeaderContent:S,readOnly:E,isStreaming:b,autoroutingLog:C,onReportAutoroutingLog:O,isRunningCode:U,hasCodeChangedSinceLastRun:q,onEditEvent:Y,editEvents:Q,defaultActiveTab:K,autoRotate3dViewerDisabled:te,showSchematicDebugGrid:J=!1,showToggleFullScreen:fe=!0,defaultToFullScreen:he=!1})=>{var Ue;YWt();const ve=mt.useMemo(()=>n?n.filter(Ie=>Ie&&"error_type"in Ie):null,[n]),[Te,Pe]=mt.useState(K??"pcb"),[Ee,Ce]=mt.useState(he),be=mt.useCallback(Ie=>{Pe(Ie),u==null||u(Ie)},[u]),Oe=()=>{Ce(!Ee)};return mt.useEffect(()=>{t&&be("errors")},[t]),mt.useEffect(()=>{(Te==="code"||Te==="errors")&&n&&!t&&be(K??"pcb")},[n]),ut.jsx("div",{className:Hg("flex flex-col relative rf-overflow-x-hidden",v),children:ut.jsx("div",{className:Hg("rf-md:sticky rf-md:top-2",Ee&&"rf-fixed rf-top-0 rf-left-0 rf-w-full rf-bg-white"),children:ut.jsxs(kGe,{value:Te,onValueChange:be,className:"rf-flex-grow rf-flex rf-flex-col",children:[ut.jsxs("div",{className:Hg("rf-flex rf-items-center rf-gap-2 rf-p-2 rf-pb-0",x),children:[S,S&&ut.jsx("div",{className:"rf-flex-grow"}),!S&&U&&ut.jsx(dPe,{className:"rf-w-4 rf-h-4 rf-animate-spin"}),!S&&ut.jsx("div",{className:"rf-flex-grow"}),f&&f.progress!==1&&ut.jsxs("div",{className:"rf-flex rf-items-center rf-gap-2",children:[f.lastRenderEvent&&ut.jsx("div",{className:"rf-text-xs rf-text-gray-500",children:((Ue=f.lastRenderEvent)==null?void 0:Ue.phase)??""}),ut.jsx("div",{className:"rf-w-4 rf-h-4 rf-bg-blue-500 rf-opacity-50 rf-rounded-full rf-text-white",children:ut.jsx(dPe,{className:"rf-w-4 rf-h-4 rf-animate-spin"})}),ut.jsxs("div",{className:"rf-text-xs rf-font-bold rf-text-gray-700 rf-tabular-nums",children:[((f.progress??0)*100).toFixed(1),"%"]})]}),a&&ut.jsxs(uue,{children:[o&&ut.jsx(a6,{value:"code",children:"Code"}),ut.jsxs(a6,{value:"pcb",className:"rf-whitespace-nowrap",children:[n&&ut.jsx("span",{className:Hg("rf-inline-flex rf-items-center rf-justify-center rf-w-2 rf-h-2 rf-mr-1 rf-text-xs rf-font-bold rf-text-white rf-rounded-full",q?"rf-bg-gray-500":"rf-bg-blue-500")}),"PCB"]}),ut.jsxs(a6,{value:"schematic",className:"rf-whitespace-nowrap",children:[n&&ut.jsx("span",{className:Hg("rf-inline-flex rf-items-center rf-justify-center rf-w-2 rf-h-2 rf-mr-1 rf-text-xs rf-font-bold rf-text-white rf-rounded-full",q?"rf-bg-gray-500":"rf-bg-blue-500")}),"Schematic"]}),ut.jsxs(a6,{value:"cad",children:[n&&ut.jsx("span",{className:Hg("inline-flex items-center justify-center w-2 h-2 mr-1 text-xs font-bold text-white rounded-full",q?"rf-bg-gray-500":"rf-bg-blue-500")}),"3D"]}),!["pcb","cad","schematic"].includes(Te)&&ut.jsx(a6,{value:Te,children:cue(Te)}),ut.jsxs(SDe,{children:[ut.jsx(EDe,{asChild:!0,children:ut.jsxs("div",{className:"rf-whitespace-nowrap rf-p-2 rf-mr-1 rf-cursor-pointer rf-relative",children:[ut.jsx(zDt,{className:"rf-w-4 rf-h-4"}),(ve&&ve.length>0||t)&&ut.jsx("span",{className:"rf-inline-flex rf-absolute rf-top-[6px] rf-right-[4px] rf-items-center rf-justify-center rf-w-1 rf-h-1 rf-ml-2 rf-text-[8px] rf-font-bold rf-text-white rf-bg-red-500 rf-rounded-full"})]})}),ut.jsxs(Iie,{className:"rf-*:text-xs",children:[SQt.map(Ie=>ut.jsxs(bI,{onSelect:()=>be(Ie),children:[Te!==Ie&&ut.jsx(fPe,{className:"rf-w-3 rf-h-3 rf-opacity-30"}),Te===Ie&&ut.jsx(cPe,{className:"rf-w-3 rf-h-3"}),ut.jsx("div",{className:"rf-pr-2",children:cue(Ie)}),Ie==="errors"&&(ve&&ve.length>0||t)&&ut.jsx("span",{className:"rf-inline-flex rf-items-center rf-justify-center rf-w-3 rf-h-3 rf-ml-2 rf-text-[8px] rf-font-bold rf-text-white rf-bg-red-500 rf-rounded-full",children:t?1:ve==null?void 0:ve.length})]},Ie)),ut.jsx(bI,{disabled:!0,className:"rf-opacity-60 rf-cursor-default rf-select-none",children:ut.jsxs("div",{className:"rf-pr-2 rf-text-xs rf-text-gray-500",children:["@tscircuit/runframe@",bQt.split(".").map((Ie,ke)=>ke===2?parseInt(Ie)+1:Ie).join(".")]})})]})]})]}),fe&&ut.jsx(HE,{onClick:Oe,variant:"ghost",children:Ee?ut.jsx(kDt,{size:16}):ut.jsx(UDt,{size:16})})]}),o&&ut.jsx(uS,{value:"code",className:"rf-flex-grow rf-overflow-hidden",children:ut.jsx("div",{className:"rf-h-full",children:s})}),ut.jsx(uS,{value:"pcb",children:ut.jsx("div",{className:Hg("rf-overflow-hidden",Ee?"rf-h-[calc(100vh-52px)]":"rf-h-[620px]"),children:ut.jsx(YT,{fallbackRender:({error:Ie})=>ut.jsx("div",{className:"rf-mt-4 rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200",children:ut.jsxs("div",{className:"rf-p-4",children:[ut.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-3",children:"Error loading PCB viewer"}),ut.jsx("p",{className:"rf-text-xs rf-font-mono rf-whitespace-pre-wrap rf-text-red-600 rf-mt-2",children:(Ie==null?void 0:Ie.message)||"An unknown error occurred"})]})}),children:n?ut.jsx(qWt,{focusOnHover:!1,circuitJson:n,debugGraphics:i,containerClassName:Hg("rf-h-full rf-w-full",Ee?"rf-min-h-[calc(100vh-240px)]":"rf-min-h-[620px]"),onEditEventsChanged:Ie=>{Y&&Ie.forEach(ke=>Y(ke))}}):ut.jsx(L8,{onRunClicked:e})})})}),ut.jsx(uS,{value:"assembly",children:ut.jsx("div",{className:Hg("rf-overflow-auto",Ee?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:ut.jsx(YT,{fallback:ut.jsx("div",{children:"Error loading Assembly"}),children:n?ut.jsx(hVt,{circuitJson:n,containerStyle:{height:"100%"},editingEnabled:!0,debugGrid:!0}):ut.jsx(L8,{onRunClicked:e})})})}),ut.jsx(uS,{value:"schematic",children:ut.jsx("div",{className:Hg("rf-overflow-auto rf-bg-white",Ee?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:ut.jsx(YT,{fallbackRender:({error:Ie})=>ut.jsx("div",{className:"rf-mt-4 rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200",children:ut.jsxs("div",{className:"rf-p-4",children:[ut.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-3",children:"Error loading Schematic"}),ut.jsx("p",{className:"rf-text-xs rf-font-mono rf-whitespace-pre-wrap rf-text-red-600 rf-mt-2",children:(Ie==null?void 0:Ie.message)||"An unknown error occurred"})]})}),children:n?ut.jsx(fVt,{circuitJson:n,containerStyle:{height:"100%"},editingEnabled:!0,onEditEvent:Ie=>{Y==null||Y(Ie)},debugGrid:J,colorOverrides:{schematic:{background:"transparent"}}}):ut.jsx(L8,{onRunClicked:e})})})}),ut.jsx(uS,{value:"cad",children:ut.jsx("div",{className:Hg("rf-overflow-auto",Ee?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:ut.jsx(YT,{FallbackComponent:bDt,children:n?ut.jsx(_Dt,{soup:n,autoRotateDisabled:te}):ut.jsx(L8,{onRunClicked:e})})})}),ut.jsx(uS,{value:"bom",children:ut.jsx("div",{className:Hg("rf-overflow-auto",Ee?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:ut.jsx(YT,{fallbackRender:({error:Ie})=>ut.jsx("div",{className:"rf-mt-4 rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200",children:ut.jsxs("div",{className:"rf-p-4",children:[ut.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-3",children:"Error loading Bill of Materials"}),ut.jsx("p",{className:"rf-text-xs rf-font-mono rf-whitespace-pre-wrap rf-text-red-600 rf-mt-2",children:(Ie==null?void 0:Ie.message)||"An unknown error occurred"})]})}),children:n?ut.jsx(_Vt,{circuitJson:n}):ut.jsx(L8,{onRunClicked:e})})})}),ut.jsx(uS,{value:"circuit_json",children:ut.jsx("div",{className:Hg("rf-overflow-auto",Ee?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:ut.jsx(YT,{fallback:ut.jsx("div",{children:"Error loading JSON viewer"}),children:n?ut.jsx(yVt,{elements:n}):ut.jsx(L8,{onRunClicked:e})})})}),ut.jsx(uS,{value:"errors",children:ut.jsx("div",{className:Hg("rf-overflow-auto",Ee?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:Array.isArray(ve)&&ve.length>0||t?ut.jsx(zUt,{code:r,circuitJsonErrors:ve,errorMessage:t,autoroutingLog:C,onReportAutoroutingLog:O}):ut.jsx(L8,{onRunClicked:e})})}),c&&ut.jsx(uS,{value:"render_log",children:ut.jsx(xQt,{renderLog:f})})]})})})};Pce.createRoot(document.getElementById("root")).render(ut.jsx(EQt,{defaultActiveTab:"cad",autoRotate3dViewerDisabled:!0,showRightHeaderContent:!1,circuitJson:window.CIRCUIT_JSON||{},...window.CIRCUIT_JSON_PREVIEW_PROPS||{}}))});
|
|
13425
|
+
searched component ${c.getString()}, which has ports: ${c.children.filter(u=>u.componentName==="Port").map(u=>`${u.getString()}(${u.getNameAndAliases().join(",")})`).join(" & ")}`):this.renderError(`Could not find port for selector "${o}"`)}return a.some(o=>!o.port)?{allPortsFound:!1}:{allPortsFound:!0,portsWithSelectors:a,ports:a.map(({port:o})=>o)}}_findConnectedNets(){const e=this.getTracePathNetSelectors().map(n=>({selector:n,net:this.getSubcircuit().selectOne(n,{type:"net"})})),t=e.filter(n=>!n.net);return t.length>0&&this.renderError(`Could not find net for selector "${t[0].selector}" inside ${this}`),{netsWithSelectors:e,nets:e.map(n=>n.net)}}_getAllTracesConnectedToSameNet(){const e=this.getSubcircuit().selectAll("trace"),t=this._findConnectedNets().nets,n=this._findConnectedPorts().ports??[];return e.filter(i=>{if(i===this)return!1;const a=i._findConnectedNets().nets,o=i._findConnectedPorts().ports??[];return a.some(s=>t.includes(s))||o.some(s=>n.includes(s))})}_isExplicitlyConnectedToPort(e){const{allPortsFound:t,portsWithSelectors:n}=this._findConnectedPorts();return t?n.map(a=>a.port).includes(e):!1}_isExplicitlyConnectedToNet(e){return this._findConnectedNets().nets.includes(e)}doInitialCreateNetsFromProps(){_Be(this,this.getTracePathNetSelectors())}_computeTraceConnectionHash(){const{allPortsFound:e,ports:t}=this._findConnectedPorts();return!e||!t?null:[...t].sort((a,o)=>(a.pcb_port_id||"").localeCompare(o.pcb_port_id||"")).map(a=>a.pcb_port_id).join(",")}doInitialSourceTraceRender(){var f;const{db:e}=this.root,{_parsedProps:t,parent:n}=this;if(!n){this.renderError("Trace has no parent");return}const{allPortsFound:i,portsWithSelectors:a}=this._findConnectedPorts();if(!i)return;this._traceConnectionHash=this._computeTraceConnectionHash();const s=e.source_trace.list().find(p=>p.subcircuit_connectivity_map_key===this.subcircuit_connectivity_map_key&&p.connected_source_port_ids.sort().join(",")===this._traceConnectionHash);if(s){this.source_trace_id=s.source_trace_id;return}const l=this._findConnectedNets().nets,c=zZt({ports:a,nets:l}),u=e.source_trace.insert({connected_source_port_ids:a.map(p=>p.port.source_port_id),connected_source_net_ids:l.map(p=>p.source_net_id),subcircuit_id:(f=this.getSubcircuit())==null?void 0:f.subcircuit_id,max_length:NZt(a.map(p=>p.port),{db:e})??t.maxLength,display_name:c,min_trace_thickness:t.thickness});this.source_trace_id=u.source_trace_id}_insertErrorIfTraceIsOutsideBoard(e,t){const{db:n}=this.root;IZt(e,{db:n})&&n.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:this.source_trace_id,message:`Trace ${this.getString()} routed outside the board boundaries.`,pcb_trace_id:this.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:t.map(a=>a.pcb_port_id)})}doInitialPcbTraceRender(){var K,te,J,fe;if((K=this.root)!=null&&K.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t,parent:n}=this,i=this.getSubcircuit();if(!n)throw new Error("Trace has no parent");if(i._parsedProps.routingDisabled)return;const a=(te=i._parsedProps.pcbRouteCache)==null?void 0:te.pcbTraces;if(a){const he=e.pcb_trace.insert({route:a.flatMap(ve=>ve.route),source_trace_id:this.source_trace_id,subcircuit_id:(i==null?void 0:i.subcircuit_id)??void 0,pcb_group_id:((J=this.getGroup())==null?void 0:J.pcb_group_id)??void 0});this.pcb_trace_id=he.pcb_trace_id;return}if(!i._shouldUseTraceByTraceRouting())return;const{allPortsFound:o,ports:s}=this._findConnectedPorts();if(!o)return;const l=[];for(const he of s)he._hasMatchedPcbPrimitive()||l.push(he);if(l.length>0){e.pcb_trace_error.insert({error_type:"pcb_trace_error",source_trace_id:this.source_trace_id,message:`Some ports did not have a matching PCB primitive (e.g. a pad or plated hole), this can happen if a footprint is missing. As a result, ${this} wasn't routed. Missing ports: ${l.map(he=>he.getString()).join(", ")}`,pcb_trace_id:this.pcb_trace_id,pcb_component_ids:[],pcb_port_ids:l.map(he=>he.pcb_port_id).filter(Boolean)});return}const c=this._findConnectedNets().netsWithSelectors;if(s.length===0&&c.length===2){this.renderError("Trace connects two nets, we haven't implemented a way to route this yet");return}else if(s.length===1&&c.length===1){const he=s[0],Te=c[0].net.getAllConnectedPorts().filter(Ee=>Ee!==he);if(Te.length===0){console.log("Nothing to connect this port to, the net is empty. TODO should emit a warning!");return}const Pe=EZt(he,Te);s.push(Pe)}else if(s.length>1&&c.length>=1){this.renderError("Trace has more than one port and one or more nets, we don't currently support this type of complex trace routing");return}const u=s.flatMap(he=>he.matchedComponents.filter(ve=>ve.componentName==="TraceHint")),f=(this._parsedProps.pcbRouteHints??[]).concat(u.flatMap(he=>he.getPcbRouteHints()));if(s.length>2){this.renderError(`Trace has more than two ports (${s.map(he=>he.getString()).join(", ")}), routing between more than two ports for a single trace is not implemented`);return}if(this.getSubcircuit().selectAll("trace").filter(he=>he.renderPhaseStates.PcbTraceRender.initialized).some(he=>he._portsRoutedOnPcb.length===s.length&&he._portsRoutedOnPcb.every(ve=>s.includes(ve))))return;let x=[];f.length===0?x=[SF(s[0]),SF(s[1])]:x=[SF(s[0]),...f,SF(s[1])];const S=xF(x),E=k3(this.root.db.toArray()),[b,C]=TZt(()=>M6(this.root.db.toArray()));if(C){this.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:this.pcb_trace_id,message:`Error getting obstacles for autorouting: ${C.message}`,source_trace_id:this.source_trace_id,center:{x:0,y:0},pcb_port_ids:s.map(he=>he.pcb_port_id),pcb_trace_id:this.pcb_trace_id,pcb_component_ids:[]});return}for(const he of b)if(he.connectedTo.length>0){const Te=E.getNetConnectedToId(he.connectedTo[0]);Te&&he.connectedTo.push(Te)}let O=[];if(S.length===0)O=x;else{const he=S[0].layer_path;O=x.map((ve,Te)=>ve.via?{...ve,via_to_layer:he[Te]}:{...ve,layers:[he[Te]]})}O[0].pcb_port_id=s[0].pcb_port_id,O[O.length-1].pcb_port_id=s[1].pcb_port_id;const U=[];for(const[he,ve]of yBe(O)){const Te="via_to_layer"in he?he.via_to_layer:null,Pe=2,Ee="layers"in he&&he.layers.length===1?he.layers[0]:Te??"top",Ce="layers"in ve&&ve.layers.length===1?ve.layers[0]:Te??"top",be="pcb_port_id"in he?he.pcb_port_id:null,Oe="pcb_port_id"in ve?ve.pcb_port_id:null,Ue=this.getSubcircuit()._parsedProps.minTraceWidth??.16,Ie=new T6({OBSTACLE_MARGIN:Ue*2,isRemovePathLoopsEnabled:!0,optimizeWithGoalBoxes:!!(be&&Oe),connMap:E,input:{obstacles:b,minTraceWidth:Ue,connections:[{name:this.source_trace_id,pointsToConnect:[{...he,layer:Ee,pcb_port_id:be},{...ve,layer:Ce,pcb_port_id:Oe}]}],layerCount:2,bounds:{minX:Math.min(he.x,ve.x)-Pe,maxX:Math.max(he.x,ve.x)+Pe,minY:Math.min(he.y,ve.y)-Pe,maxY:Math.max(he.y,ve.y)+Pe}}});let ke=null;try{ke=Ie.solveAndMapToTraces()}catch(gt){this.renderError({type:"pcb_trace_error",pcb_trace_error_id:this.source_trace_id,error_type:"pcb_trace_error",message:`error solving route: ${gt.message}`,source_trace_id:this.pcb_trace_id,center:{x:(he.x+ve.x)/2,y:(he.y+ve.y)/2},pcb_port_ids:s.map(Et=>Et.pcb_port_id),pcb_trace_id:this.pcb_trace_id,pcb_component_ids:s.map(Et=>Et.pcb_component_id)})}if(!ke)return;if(ke.length===0){this.renderError({type:"pcb_trace_error",error_type:"pcb_trace_error",pcb_trace_error_id:this.pcb_trace_id,message:`Could not find a route for ${this}`,source_trace_id:this.source_trace_id,center:{x:(he.x+ve.x)/2,y:(he.y+ve.y)/2},pcb_port_ids:s.map(gt=>gt.pcb_port_id),pcb_trace_id:this.pcb_trace_id,pcb_component_ids:s.map(gt=>gt.pcb_component_id)});return}const[ot]=ke;Te&&(ot.route=ot.route.map(gt=>(gt.route_type==="wire"&&!gt.layer&&(gt.layer=Te),gt))),be&&ot.route[0].route_type==="wire"&&(ot.route[0].start_pcb_port_id=be);const nt=ot.route[ot.route.length-1];Oe&&nt.route_type==="wire"&&(nt.end_pcb_port_id=Oe),U.push(ot.route)}const q=bZt(U),Y=MZt(q),Q=e.pcb_trace.insert({route:q,source_trace_id:this.source_trace_id,subcircuit_id:(fe=this.getSubcircuit())==null?void 0:fe.subcircuit_id,trace_length:Y});this._portsRoutedOnPcb=s,this.pcb_trace_id=Q.pcb_trace_id;for(const he of q)he.route_type==="via"&&e.pcb_via.insert({pcb_trace_id:Q.pcb_trace_id,x:he.x,y:he.y,hole_diameter:.3,outer_diameter:.6,layers:[he.from_layer,he.to_layer],from_layer:he.from_layer,to_layer:he.to_layer});this._insertErrorIfTraceIsOutsideBoard(q,s)}_doInitialSchematicTraceRenderWithDisplayLabel(){var U,q,Y,Q;if((U=this.root)!=null&&U.schematicDisabled)return;const{db:e}=this.root,{_parsedProps:t,parent:n}=this;if(!n)throw new Error("Trace has no parent");const{allPortsFound:i,portsWithSelectors:a}=this._findConnectedPorts();if(!i)return;const o=a.map(({port:K})=>({port:K,position:K._getGlobalSchematicPositionAfterLayout(),schematic_port_id:K.schematic_port_id,facingDirection:K.facingDirection}));if(o.length<2)throw new Error("Expected at least two ports in portsWithPosition.");let s,l;const c=o[0].position,u=o[0].port;if("path"in this.props){if(this.props.path.length!==2)throw new Error("Invalid 'path': Must contain exactly two elements.");[s,l]=this.props.path}else{if(!("from"in this.props&&"to"in this.props))throw new Error("Missing 'from' or 'to' properties in props.");s=this.props.from,l=this.props.to}if(!u.source_port_id)throw new Error(`Missing source_port_id for the 'from' port (${s}).`);const f=o[1].position,p=o[1].port;if(!p.source_port_id)throw new Error(`Missing source_port_id for the 'to' port (${l}).`);const v=e.schematic_net_label.list().find(K=>K.source_net_id===u.source_port_id),x=e.schematic_net_label.list().find(K=>K.source_net_id===p.source_port_id),[S,E]=a.map(({port:K})=>K),C=((q=S.parent)==null?void 0:q.config.shouldRenderAsSchematicBox)?`${(Y=S==null?void 0:S.parent)==null?void 0:Y.props.name}_${S==null?void 0:S.props.name}`:`${(Q=E==null?void 0:E.parent)==null?void 0:Q.props.name}_${E==null?void 0:E.props.name}`,O=this.props.schDisplayLabel??C;if(v&&v.text!==O&&(v.text=`${O} / ${v.text}`),x&&(x==null?void 0:x.text)!==O&&(x.text=`${O} / ${x.text}`),O!=null&&O.toLocaleLowerCase().includes("gnd")||O!=null&&O.toLocaleLowerCase().includes("ground")){!v&&!x?(bF({port:u,anchorPos:c,schDisplayLabel:this.props.schDisplayLabel,source_trace_id:this.source_trace_id},{db:e}),bF({port:p,anchorPos:f,schDisplayLabel:this.props.schDisplayLabel,source_trace_id:this.source_trace_id},{db:e})):v?x||bF({port:p,anchorPos:f,schDisplayLabel:this.props.schDisplayLabel,source_trace_id:this.source_trace_id},{db:e}):bF({port:u,anchorPos:c,schDisplayLabel:this.props.schDisplayLabel,source_trace_id:this.source_trace_id},{db:e});return}x||e.schematic_net_label.insert({text:this.props.schDisplayLabel??C,source_net_id:p.source_port_id,anchor_position:f,center:f,anchor_side:ele(p.facingDirection)??"bottom"}),v||e.schematic_net_label.insert({text:this.props.schDisplayLabel??C,source_net_id:u.source_port_id,anchor_position:c,center:c,anchor_side:ele(u.facingDirection)??"bottom"})}_isSymbolToChipConnection(){const{allPortsFound:e,ports:t}=this._findConnectedPorts();if(!e||t.length!==2)return!1;const[n,i]=t;if(!(n!=null&&n.parent)||!(i!=null&&i.parent))return!1;const a=n.parent.config.shouldRenderAsSchematicBox,o=i.parent.config.shouldRenderAsSchematicBox;return a&&!o||!a&&o}_isSymbolToSymbolConnection(){const{allPortsFound:e,ports:t}=this._findConnectedPorts();if(!e||t.length!==2)return!1;const[n,i]=t;if(!(n!=null&&n.parent)||!(i!=null&&i.parent))return!1;const a=!n.parent.config.shouldRenderAsSchematicBox,o=!i.parent.config.shouldRenderAsSchematicBox;return a&&o}_isChipToChipConnection(){const{allPortsFound:e,ports:t}=this._findConnectedPorts();if(!e||t.length!==2)return!1;const[n,i]=t;if(!(n!=null&&n.parent)||!(i!=null&&i.parent))return!1;const a=n.parent.config.shouldRenderAsSchematicBox,o=i.parent.config.shouldRenderAsSchematicBox;return a&&o}doInitialSchematicTraceRender(){var Ee,Ce;if((Ee=this.root)!=null&&Ee.schematicDisabled)return;const{db:e}=this.root,{_parsedProps:t,parent:n}=this;if(!n)throw new Error("Trace has no parent");const{allPortsFound:i,portsWithSelectors:a}=this._findConnectedPorts(),{netsWithSelectors:o}=this._findConnectedNets();if(!i)return;const l=a.map(be=>be.port.schematic_port_id).sort().join(","),c=(Ce=this.root)==null?void 0:Ce._getBoard();if(c!=null&&c._connectedSchematicPortPairs&&c._connectedSchematicPortPairs.has(l))return;if(this.props.schDisplayLabel&&("from"in this.props&&"to"in this.props||"path"in this.props)){this._doInitialSchematicTraceRenderWithDisplayLabel();return}const u={name:this.source_trace_id,pointsToConnect:[]},f=OZt(this),p=a.map(({port:be})=>({port:be,position:be._getGlobalSchematicPositionAfterLayout(),schematic_port_id:be.schematic_port_id??void 0,facingDirection:be.facingDirection}));if(p.length===1&&o.length===1){const be=o[0].net,{port:Oe,position:Ue}=p[0];e.schematic_net_label.insert({text:be._parsedProps.name,source_net_id:be.source_net_id,anchor_position:Ue,center:Ue,anchor_side:ele(Oe.facingDirection)??"bottom"});return}if(p.length<2)return;u.pointsToConnect=p.map(({position:be})=>({...be,layer:"top"}));const x=xZt(f),S=2,E={minTraceWidth:.1,obstacles:f,connections:[u],bounds:{minX:x.minX-S,maxX:x.maxX+S,minY:x.minY-S,maxY:x.maxY+S},layerCount:1};let b=T6,C=!1;this.getSubcircuit().props._schDirectLineRoutingEnabled&&(b=CBe,C=!0);let U=new b({input:E,MAX_ITERATIONS:100,OBSTACLE_MARGIN:.1,isRemovePathLoopsEnabled:!0,isShortenPathWithShortcutsEnabled:!0,marginsWithCosts:[{margin:1,enterCost:0,travelCostFactor:1},{margin:.3,enterCost:0,travelCostFactor:1},{margin:.2,enterCost:0,travelCostFactor:2},{margin:.1,enterCost:0,travelCostFactor:3}]}).solveAndMapToTraces();if(U.length===0){if(this._isSymbolToChipConnection()||this._isSymbolToSymbolConnection()||this._isChipToChipConnection()){this._doInitialSchematicTraceRenderWithDisplayLabel();return}U=new CBe({input:E}).solveAndMapToTraces(),C=!0}const[{route:q}]=U;let Y=[];for(let be=0;be<q.length-1;be++)Y.push({from:q[be],to:q[be+1]});const Q=this.source_trace_id;let K=[];if(!C){UZt({edges:Y,db:e,source_trace_id:Q});const be=nle({db:e,source_trace_id:Q,differentNetOnly:!0}).flatMap(Oe=>Oe.edges);Y=RZt({edges:Y,otherEdges:be}),K=PZt({edges:Y,db:e,source_trace_id:this.source_trace_id})}const te=Y[Y.length-1],J=p[p.length-1],fe=ABe(te);Y.push(...tle({lastEdge:te,lastEdgePort:J,lastDominantDirection:fe}));const he=Y[0],ve=p[0],Te=ABe(he);if(Y.unshift(...tle({firstEdge:he,firstEdgePort:ve,firstDominantDirection:Te})),!this.source_trace_id)throw new Error("Missing source_trace_id for schematic trace insertion.");if(this.getSubcircuit()._parsedProps.schTraceAutoLabelEnabled&&wZt(K,Y)>=5&&(this._isSymbolToChipConnection()||this._isSymbolToSymbolConnection()||this._isChipToChipConnection())){this._doInitialSchematicTraceRenderWithDisplayLabel();return}const Pe=e.schematic_trace.insert({source_trace_id:this.source_trace_id,edges:Y,junctions:K});this.schematic_trace_id=Pe.schematic_trace_id,c!=null&&c._connectedSchematicPortPairs&&c._connectedSchematicPortPairs.add(l)}},kZt=E1("tscircuit:core"),FZt=k.object({x:p5,y:p5,z:p5}),Wx=class extends M_{constructor(e){super(e);Je(this,"reactSubtrees",[]);Je(this,"_impliedFootprint");Je(this,"isPrimitiveContainer",!0);Je(this,"_asyncSupplierPartNumbers");Je(this,"pcb_missing_footprint_error_id");this._addChildrenFromStringFootprint(),this.initPorts()}get defaultInternallyConnectedPinNames(){return[]}get internallyConnectedPinNames(){return this._parsedProps.internallyConnectedPins??this.defaultInternallyConnectedPinNames}initPorts(e={}){var o,s,l,c,u,f,p,v,x,S;if((o=this.root)!=null&&o.schematicDisabled)return;const{config:t}=this,n=[],i=this._getSchematicPortArrangement();if(i&&!this._parsedProps.pinLabels){for(const C in i){const O=i[C].pins;if(Array.isArray(O))for(const U of O){const q=BA(U,this._parsedProps.pinLabels);n.push(new W4({pinNumber:q,aliases:((s=e.additionalAliases)==null?void 0:s[`pin${q}`])??[]},{originDescription:`schPortArrangement:${C}`}))}}const E=["left","right","top","bottom"];let b=1;for(const C of E){const O=i[`${C}Size`];for(let U=0;U<O;U++)n.push(new W4({pinNumber:b++,aliases:((l=e.additionalAliases)==null?void 0:l[`pin${b}`])??[]},{originDescription:`schPortArrangement:${C}`}))}}const a=this._parsedProps.pinLabels;if(a)for(let[E,b]of Object.entries(a)){E=E.replace("pin","");let C=n.find(q=>q._parsedProps.pinNumber===Number(E));const O=Array.isArray(b)?b[0]:b,U=Array.isArray(b)?b.slice(1):[];C?(C.externallyAddedAliases.push(O,...U),C.props.name=O):(C=new W4({pinNumber:parseInt(E),name:O,aliases:[...U,...((c=e.additionalAliases)==null?void 0:c[`pin${parseInt(E)}`])??[]]},{originDescription:`pinLabels:pin${E}`}),n.push(C))}if(t.schematicSymbolName){const E=u_[this._getSchematicSymbolNameOrThrow()];if(!E)return;for(const b of E.ports){const C=TBe(b.labels);if(!C)continue;const O=n.find(U=>U._parsedProps.pinNumber===Number(C));if(O)O.schematicSymbolPortDef=b;else{const U=HA(b.labels.concat(((u=e.additionalAliases)==null?void 0:u[`pin${C}`])??[]));U&&(U.originDescription=`schematicSymbol:labels[0]:${b.labels[0]}`,U.schematicSymbolPortDef=b,n.push(U))}}this.addAll(n)}if(!this._getSchematicPortArrangement()){const E=this.getPortsFromFootprint(e);for(const b of E)n.some(C=>C.isMatchingAnyOf(b.getNameAndAliases()))||n.push(b)}for(let E=1;E<=(e.pinCount??this._getPinCount());E++){if(!i||n.find(C=>C._parsedProps.pinNumber===E))continue;let b=[...((f=i.leftSide)==null?void 0:f.pins)??[],...((p=i.rightSide)==null?void 0:p.pins)??[],...((v=i.topSide)==null?void 0:v.pins)??[],...((x=i.bottomSide)==null?void 0:x.pins)??[]].map(C=>BA(C,this._parsedProps.pinLabels));["leftSize","rightSize","topSize","bottomSize","leftPinCount","rightPinCount","topPinCount","bottomPinCount"].some(C=>C in i)&&(b=Array.from({length:this._getPinCount()},(C,O)=>O+1)),b.includes(E)&&n.push(new W4({pinNumber:E,aliases:((S=e.additionalAliases)==null?void 0:S[`pin${E}`])??[]},{originDescription:`notOtherwiseAddedButDeducedFromPinCount:${E}`}))}n.length>0&&this.addAll(n)}_getImpliedFootprintString(){return null}_addChildrenFromStringFootprint(){var a;const{name:e,pcbRotation:t,pinLabels:n}=this.props;let{footprint:i}=this.props;if(i??(i=(a=this._getImpliedFootprintString)==null?void 0:a.call(this)),!!i&&typeof i=="string"){const o=y6.string(i).soup(),s=cZt({componentName:e,componentRotation:t,footprint:i,pinLabels:n},o);this.addAll(s)}}get portMap(){return new Proxy({},{get:(e,t)=>{const n=this.children.find(i=>i.componentName==="Port"&&i.isMatchingNameOrAlias(t));if(!n)throw new Error(`There was an issue finding the port "${t.toString()}" inside of a ${this.componentName} component with name: "${this.props.name}". This is a bug in @tscircuit/core`);return n}})}getInstanceForReactElement(e){for(const t of this.reactSubtrees)if(t.element===e)return t.component;return null}doInitialSourceRender(){const e=this.config.sourceFtype;if(!e)return;const{db:t}=this.root,{_parsedProps:n}=this,i=t.source_component.insert({ftype:e,name:n.name,manufacturer_part_number:n.manufacturerPartNumber??n.mfn,supplier_part_numbers:n.supplierPartNumbers});this.source_component_id=i.source_component_id}doInitialSchematicComponentRender(){var i,a,o;if((i=this.root)!=null&&i.schematicDisabled)return;const{db:e}=this.root,{schematicSymbolName:t}=this.config;t?this._doInitialSchematicComponentRenderWithSymbol():this._getSchematicBoxDimensions()&&this._doInitialSchematicComponentRenderWithSchematicBoxDimensions();const n=(a=this.getSubcircuit())==null?void 0:a._getSchematicManualPlacementForComponent(this);if(this.schematic_component_id&&(this.props.schX!==void 0||this.props.schY!==void 0)&&n){if(!this.schematic_component_id)return;const s=PP.parse({type:"schematic_manual_edit_conflict_warning",schematic_manual_edit_conflict_warning_id:`schematic_manual_edit_conflict_${this.source_component_id}`,message:`${this.getString()} has both manual placement and prop coordinates. schX and schY will be used. Remove schX/schY or clear the manual placement.`,schematic_component_id:this.schematic_component_id,source_component_id:this.source_component_id,subcircuit_id:(o=this.getSubcircuit())==null?void 0:o.subcircuit_id});e.schematic_manual_edit_conflict_warning.insert(s)}}_getSchematicSymbolDisplayValue(){}_getInternallyConnectedPins(){if(this.internallyConnectedPinNames.length===0)return[];const e=[];for(const t of this.internallyConnectedPinNames){const n=[];for(const i of t)n.push(this.portMap[i]);e.push(n)}return e}_doInitialSchematicComponentRenderWithSymbol(){var o;if((o=this.root)!=null&&o.schematicDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=this._getSchematicSymbolNameOrThrow(),i=u_[n],a=this._getGlobalSchematicPositionBeforeLayout();if(i){const s=e.schematic_component.insert({center:a,size:i.size,source_component_id:this.source_component_id,symbol_name:n,symbol_display_value:this._getSchematicSymbolDisplayValue()});this.schematic_component_id=s.schematic_component_id}}_doInitialSchematicComponentRenderWithSchematicBoxDimensions(){var f;if((f=this.root)!=null&&f.schematicDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=this._getSchematicBoxDimensions(),i={};if(Array.isArray(t.pinLabels))t.pinLabels.forEach((p,v)=>{i[String(v+1)]=p});else for(const[p,v]of Object.entries(t.pinLabels??{}))i[p]=Array.isArray(v)?v[0]:v;const a=this._getGlobalSchematicPositionBeforeLayout(),o=this._getSchematicPortArrangement(),s=e.schematic_component.insert({center:a,rotation:t.schRotation??0,size:n.getSize(),port_arrangement:aZt(o),pin_spacing:t.schPinSpacing??.2,pin_styles:iZt(t.schPinStyle,t.pinLabels),port_labels:i,source_component_id:this.source_component_id}),l=(o==null?void 0:o.topSide)!==void 0||(o==null?void 0:o.bottomSide)!==void 0,c=n==null?void 0:n.getSize().width,u=n==null?void 0:n.getSize().height;e.schematic_text.insert({text:t.manufacturerPartNumber??"",schematic_component_id:s.schematic_component_id,anchor:"left",rotation:0,position:{x:l?a.x+(c??0)/2+.1:a.x-(c??0)/2,y:l?a.y+(u??0)/2+.35:a.y-(u??0)/2-.13},color:"#006464",font_size:.05}),e.schematic_text.insert({text:t.name??"",schematic_component_id:s.schematic_component_id,anchor:"left",rotation:0,position:{x:l?a.x+(c??0)/2+.1:a.x-(c??0)/2,y:l?a.y+(u??0)/2+.55:a.y+(u??0)/2+.13},color:"#006464",font_size:.05}),this.schematic_component_id=s.schematic_component_id}doInitialPcbComponentRender(){var o;if((o=this.root)!=null&&o.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=this.getSubcircuit(),i=e.pcb_component.insert({center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,layer:t.layer??"top",rotation:t.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:n.subcircuit_id??void 0});if(!t.footprint&&!this.isGroup){const s=e.pcb_missing_footprint_error.insert({message:`No footprint found for component: ${this.getString()}`,source_component_id:`${this.source_component_id}`,error_type:"pcb_missing_footprint_error"});this.pcb_missing_footprint_error_id=s.pcb_missing_footprint_error_id}this.pcb_component_id=i.pcb_component_id;const a=this.getSubcircuit()._getPcbManualPlacementForComponent(this);if((this.props.pcbX!==void 0||this.props.pcbY!==void 0)&&a){const s=DP.parse({type:"pcb_manual_edit_conflict_warning",pcb_manual_edit_conflict_warning_id:`pcb_manual_edit_conflict_${this.source_component_id}`,message:`${this.getString()} has both manual placement and prop coordinates. pcbX and pcbY will be used. Remove pcbX/pcbY or clear the manual placement.`,pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,subcircuit_id:n.subcircuit_id??void 0});e.pcb_manual_edit_conflict_warning.insert(s)}}doInitialPcbComponentSizeCalculation(){var a;if((a=this.root)!=null&&a.pcbDisabled||!this.pcb_component_id)return;const{db:e}=this.root,{_parsedProps:t}=this,n=wBe(this.children);if(n.width===0||n.height===0)return;const i={x:(n.minX+n.maxX)/2,y:(n.minY+n.maxY)/2};e.pcb_component.update(this.pcb_component_id,{center:i,width:n.width,height:n.height})}_renderReactSubtree(e){return{element:e,component:rZt(e)}}doInitialInitializePortsFromChildren(){this.initPorts()}doInitialReactSubtreesRender(){if(mt.isValidElement(this.props.footprint)){if(this.reactSubtrees.some(t=>t.element===this.props.footprint))return;const e=this._renderReactSubtree(this.props.footprint);this.reactSubtrees.push(e),this.add(e.component)}}_hasExistingPortExactly(e){return this.children.filter(n=>n.componentName==="Port").some(n=>{const i=e.getNameAndAliases(),a=n.getNameAndAliases();return i.length===a.length&&i.every(o=>a.includes(o))})}add(e){let t;if(mt.isValidElement(e)){const n=this._renderReactSubtree(e);this.reactSubtrees.push(n),t=n.component}else t=e;if(t.componentName==="Port"){if(this._hasExistingPortExactly(t))return;const i=this.children.filter(a=>a.componentName==="Port").find(a=>a.isMatchingAnyOf(t.getNameAndAliases()));i&&kZt(`Similar ports added. Port 1: ${i}, Port 2: ${t}`)}super.add(t)}getPortsFromFootprint(e){let{footprint:t}=this.props;if((!t||mt.isValidElement(t))&&(t=this.children.find(i=>i.componentName==="Footprint")),typeof t=="string"){const i=y6.string(t).soup(),a=[];for(const o of i)if("port_hints"in o&&o.port_hints){const s=HA(o.port_hints,e);if(!s)continue;s.originDescription=`footprint:string:${t}:port_hints[0]:${o.port_hints[0]}`,a.push(s)}return a}if(!mt.isValidElement(t)&&t&&t.componentName==="Footprint"){const i=t;let a=1;const o=[];for(const s of i.children){if(!s.props.portHints)continue;let l=s.props.portHints;l.some(f=>f.startsWith("pin"))||(l=[...l,`pin${a}`]),a++;const u=HA(l);u&&(u.originDescription=`footprint:${t}`,o.push(u))}return o}const n=[];if(!t){for(const i of this.children)if(i.props.portHints&&i.isPcbPrimitive){const a=HA(i.props.portHints);a&&n.push(a)}}return n}getPortsFromSchematicSymbol(){var i;if((i=this.root)!=null&&i.schematicDisabled)return[];const{config:e}=this;if(!e.schematicSymbolName)return[];const t=u_[e.schematicSymbolName];if(!t)return[];const n=[];for(const a of t.ports){const o=HA(a.labels);o&&(o.schematicSymbolPortDef=a,n.push(o))}return n}doInitialCreateNetsFromProps(){this._createNetsFromProps(this._getNetsFromConnectionsProp())}_getNetsFromConnectionsProp(){const{_parsedProps:e}=this,t=[];if(e.connections)for(const[n,i]of Object.entries(e.connections)){const a=Array.isArray(i)?i:[i];for(const o of a)t.push(o)}return t}_createNetsFromProps(e){_Be(this,e)}_getPcbCircuitJsonBounds(){const{db:e}=this.root;if(!this.pcb_component_id)return super._getPcbCircuitJsonBounds();const t=e.pcb_component.get(this.pcb_component_id);return{center:{x:t.center.x,y:t.center.y},bounds:{left:t.center.x-t.width/2,top:t.center.y-t.height/2,right:t.center.x+t.width/2,bottom:t.center.y+t.height/2},width:t.width,height:t.height}}_getPinCountFromSchematicPortArrangement(){const e=this._getSchematicPortArrangement();if(!e)return 0;if(!MBe(e))return(e.leftSize??e.leftPinCount??0)+(e.rightSize??e.rightPinCount??0)+(e.topSize??e.topPinCount??0)+(e.bottomSize??e.bottomPinCount??0);const{leftSide:n,rightSide:i,topSide:a,bottomSide:o}=e;return Math.max(...(n==null?void 0:n.pins)??[],...(i==null?void 0:i.pins)??[],...(a==null?void 0:a.pins)??[],...(o==null?void 0:o.pins)??[])}_getPinCount(){return this._getSchematicPortArrangement()?this._getPinCountFromSchematicPortArrangement():this.getPortsFromFootprint().length}_getSchematicPortArrangement(){return this._parsedProps.schPinArrangement??this._parsedProps.schPortArrangement}_getSchematicBoxDimensions(){if(this.getSchematicSymbol()||!this.config.shouldRenderAsSchematicBox)return null;const{_parsedProps:e}=this,t=this._getPinCount(),n=e.schPinSpacing??.2;return vZt({schWidth:e.schWidth,schHeight:e.schHeight,schPinSpacing:n,numericSchPinStyle:_Zt(e.schPinStyle,e.pinLabels),pinCount:t,schPortArrangement:this._getSchematicPortArrangement(),pinLabels:e.pinLabels})}doInitialCadModelRender(){var c;const{db:e}=this.root,{boardThickness:t=0}=((c=this.root)==null?void 0:c._getBoard())??{},n=this._parsedProps.cadModel;if(!this.pcb_component_id||!n&&!this.props.footprint)return;const i=this._getPcbCircuitJsonBounds(),a=e.pcb_component.get(this.pcb_component_id);if(typeof n=="string")throw new Error("String cadModel not yet implemented");const o=FZt.parse({x:0,y:0,z:typeof(n==null?void 0:n.rotationOffset)=="number"?n.rotationOffset:0,...typeof(n==null?void 0:n.rotationOffset)=="object"?n.rotationOffset??{}:{}}),s=lw.parse({x:0,y:0,z:0,...typeof(n==null?void 0:n.positionOffset)=="object"?n.positionOffset:{}}),l=this.props.layer==="bottom"?"bottom":"top";e.cad_component.insert({position:{x:i.center.x+s.x,y:i.center.y+s.y,z:(l==="bottom"?-t/2:t/2)+s.z},rotation:{x:o.x,y:(l==="top"?0:180)+o.y,z:((a==null?void 0:a.rotation)??0)+(l==="bottom"?180:0)+o.z},pcb_component_id:this.pcb_component_id,source_component_id:this.source_component_id,model_stl_url:"stlUrl"in(n??{})?this._addCachebustToModelUrl(n.stlUrl):void 0,model_obj_url:"objUrl"in(n??{})?this._addCachebustToModelUrl(n.objUrl):void 0,model_jscad:"jscad"in(n??{})?n.jscad:void 0,footprinter_string:typeof this.props.footprint=="string"&&!n?this.props.footprint:void 0})}_addCachebustToModelUrl(e){var n;if(!e||!e.includes("modelcdn.tscircuit.com"))return e;const t=((n=this.root)==null?void 0:n.getClientOrigin())??"";return`${e}${e.includes("?")?"&":"?"}cachebust_origin=${encodeURIComponent(t)}`}doInitialPartsEngineRender(){const e=this.getInheritedProperty("partsEngine");if(!e)return;const{db:t}=this.root,n=t.source_component.get(this.source_component_id);if(!n||n.supplier_part_numbers)return;let i;this.props.footprint&&typeof this.props.footprint=="string"&&(i=this.props.footprint);const a=e.findPart({sourceComponent:n,footprinterString:i});if(!(a instanceof Promise)){t.source_component.update(this.source_component_id,{supplier_part_numbers:a});return}this._queueAsyncEffect("get-supplier-part-numbers",async()=>{this._asyncSupplierPartNumbers=await a,this._markDirty("PartsEngineRender")})}updatePartsEngineRender(){const{db:e}=this.root,t=e.source_component.get(this.source_component_id);if(t&&!t.supplier_part_numbers&&this._asyncSupplierPartNumbers){e.source_component.update(this.source_component_id,{supplier_part_numbers:this._asyncSupplierPartNumbers});return}}doInitialCreateTracesFromProps(){this._createTracesFromConnectionsProp()}_createTracesFromConnectionsProp(){const{_parsedProps:e}=this;if(e.connections)for(const[t,n]of Object.entries(e.connections)){const i=Array.isArray(n)?n:[n];for(const a of i)this.add(new q8({from:`${this.getSubcircuitSelector()} > port.${t}`,to:a}))}}},BZt=class{constructor(r,e={}){Je(this,"input");Je(this,"isRouting",!1);Je(this,"solver");Je(this,"eventHandlers",{complete:[],error:[],progress:[]});Je(this,"cycleCount",0);Je(this,"stepDelay");Je(this,"timeoutId");this.input=r;const{capacityDepth:t,targetMinCapacity:n,stepDelay:i=0}=e;this.solver=new AG(r,{capacityDepth:t,targetMinCapacity:n}),this.stepDelay=i}start(){this.isRouting||(this.isRouting=!0,this.cycleCount=0,this.runCycleAndQueueNextCycle())}runCycleAndQueueNextCycle(){var r;if(this.isRouting)try{if(this.solver.solved||this.solver.failed){this.solver.failed?this.emitEvent({type:"error",error:new Error(this.solver.error||"Routing failed")}):this.emitEvent({type:"complete",traces:this.solver.getOutputSimpleRouteJson().traces||[]}),this.isRouting=!1;return}const e=Date.now(),t=this.solver.iterations;for(;Date.now()-e<250&&!this.solver.failed&&!this.solver.solved;)this.solver.step();const n=(this.solver.iterations-t)/(Date.now()-e)*1e3;this.cycleCount++;const i=((r=this.solver)==null?void 0:r.preview())||void 0,a=this.solver.progress;this.emitEvent({type:"progress",steps:this.cycleCount,iterationsPerSecond:n,progress:a,phase:this.solver.getCurrentPhase(),debugGraphics:i}),this.stepDelay>0?this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),this.stepDelay):this.timeoutId=setTimeout(()=>this.runCycleAndQueueNextCycle(),0)}catch(e){this.emitEvent({type:"error",error:e instanceof Error?e:new Error(String(e))}),this.isRouting=!1}}stop(){this.isRouting&&(this.isRouting=!1,this.timeoutId!==void 0&&(clearTimeout(this.timeoutId),this.timeoutId=void 0))}on(r,e){r==="complete"?this.eventHandlers.complete.push(e):r==="error"?this.eventHandlers.error.push(e):r==="progress"&&this.eventHandlers.progress.push(e)}emitEvent(r){if(r.type==="complete")for(const e of this.eventHandlers.complete)e(r);else if(r.type==="error")for(const e of this.eventHandlers.error)e(r);else if(r.type==="progress")for(const e of this.eventHandlers.progress)e(r)}solveSync(){if(this.solver.solve(),this.solver.failed)throw new Error(this.solver.error||"Routing failed");return this.solver.getOutputSimpleRouteJson().traces||[]}},PBe=class extends M_{constructor(){super(...arguments);Je(this,"matchedPort",null)}get config(){return{componentName:"TraceHint",zodProps:VUe}}doInitialPortMatching(){const{db:e}=this.root,{_parsedProps:t,parent:n}=this;if(!n)return;if(n.componentName==="Trace"){this.renderError(`Port inference inside trace is not yet supported (${this})`);return}if(!n)throw new Error("TraceHint has no parent");if(!t.for){this.renderError(`TraceHint has no for property (${this})`);return}const i=n.selectOne(t.for,{type:"port"});i||this.renderError(`${this} could not find port for selector "${t.for}"`),this.matchedPort=i,i.registerMatch(this)}getPcbRouteHints(){const{_parsedProps:e}=this,t=e.offset?[e.offset]:e.offsets;if(!t)return[];const n=this._computePcbGlobalTransformBeforeLayout();return t.map(i=>({...Ir(n,i),via:i.via,to_layer:i.to_layer,trace_width:i.trace_width}))}doInitialPcbTraceHintRender(){var n,i,a;if((n=this.root)!=null&&n.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this;e.pcb_trace_hint.insert({pcb_component_id:(i=this.matchedPort)==null?void 0:i.pcb_component_id,pcb_port_id:(a=this.matchedPort)==null?void 0:a.pcb_port_id,route:this.getPcbRouteHints()})}},HZt=(r,e)=>{const t=r.source_group.list(),n=[],i=a=>{const o=t.filter(s=>s.parent_subcircuit_id===a);for(const s of o)s.subcircuit_id&&(n.push(s.subcircuit_id),i(s.subcircuit_id))};return i(e),n},NBe=({db:r,circuitJson:e,subcircuit_id:t,minTraceWidth:n=.1})=>{if(!r&&e&&(r=p4(e)),!r)throw new Error("db or circuitJson is required");const i=r.pcb_trace_hint.list(),a=t?new Set([t]):null;if(t){const S=HZt(r,t);for(const E of S)a.add(E)}const o=(e??r.toArray()).filter(S=>!t||"subcircuit_id"in S&&a.has(S.subcircuit_id)),s=r.pcb_board.list()[0];r=p4(o);const l=k3(o),c=M6([...r.pcb_component.list(),...r.pcb_smtpad.list(),...r.pcb_plated_hole.list(),...r.pcb_hole.list(),...r.pcb_via.list()].filter(S=>!t||(a==null?void 0:a.has(S.subcircuit_id))),l);for(const S of c){const E=S.connectedTo.flatMap(b=>l.getIdsConnectedToNet(b));S.connectedTo.push(...E)}const u=c.flatMap(S=>[{x:S.center.x-S.width/2,y:S.center.y-S.height/2},{x:S.center.x+S.width/2,y:S.center.y+S.height/2}]);let f;s?f={minX:s.center.x-s.width/2,maxX:s.center.x+s.width/2,minY:s.center.y-s.height/2,maxY:s.center.y+s.height/2}:f={minX:Math.min(...u.map(S=>S.x))-1,maxX:Math.max(...u.map(S=>S.x))+1,minY:Math.min(...u.map(S=>S.y))-1,maxY:Math.max(...u.map(S=>S.y))+1};const p=r.source_trace.list().map(S=>{var Q,K,te;const E=S.connected_source_port_ids.map(J=>{const fe=r.source_port.get(J),he=r.pcb_port.getWhere({source_port_id:J});return{...fe,...he}});if(E.length<2)return null;const[b,C]=E,O=((Q=b.layers)==null?void 0:Q[0])??"top",U=((K=C.layers)==null?void 0:K[0])??"top",q=i.filter(J=>J.pcb_port_id===b.pcb_port_id||J.pcb_port_id===C.pcb_port_id),Y=[];for(const J of q){const fe=r.pcb_port.get(J.pcb_port_id),he=((te=fe==null?void 0:fe.layers)==null?void 0:te[0])??"top";for(const ve of J.route)Y.push({x:ve.x,y:ve.y,layer:he})}return{name:S.source_trace_id??l.getNetConnectedToId(S.source_trace_id)??"",source_trace_id:S.source_trace_id,pointsToConnect:[{x:b.x,y:b.y,layer:O},...Y,{x:C.x,y:C.y,layer:U}]}}).filter(S=>S!==null),v=r.source_net.list().filter(S=>!t||(a==null?void 0:a.has(S.subcircuit_id))),x=[];for(const S of v){const E=r.source_trace.list().filter(b=>{var C;return(C=b.connected_source_net_ids)==null?void 0:C.includes(S.source_net_id)});x.push({name:S.source_net_id??l.getNetConnectedToId(S.source_net_id),pointsToConnect:E.flatMap(b=>r.pcb_port.list().filter(O=>b.connected_source_port_ids.includes(O.source_port_id)).map(O=>{var U;return{x:O.x,y:O.y,layer:((U=O.layers)==null?void 0:U[0])??"top",pcb_port_id:O.pcb_port_id}}))})}return{simpleRouteJson:{bounds:f,obstacles:c,connections:[...p,...x],layerCount:2,minTraceWidth:n},connMap:l}},rle=class extends Wx{constructor(){super(...arguments);Je(this,"pcb_group_id",null);Je(this,"subcircuit_id",null);Je(this,"_hasStartedAsyncAutorouting",!1);Je(this,"_asyncAutoroutingResult",null)}get config(){return{zodProps:oUe,componentName:"Group"}}doInitialSourceRender(){const{db:e}=this.root,t=e.source_group.insert({name:this._parsedProps.name,is_subcircuit:this.isSubcircuit});this.subcircuit_id=`subcircuit_${t.source_group_id}`,this.source_group_id=t.source_group_id,e.source_group.update(t.source_group_id,{subcircuit_id:this.subcircuit_id})}doInitialSourceParentAttachment(){var n,i,a;const{db:e}=this.root;if(!this.isSubcircuit)return;const t=(a=(i=(n=this.parent)==null?void 0:n.getSubcircuit)==null?void 0:i.call(n))==null?void 0:a.subcircuit_id;t&&e.source_group.update(this.source_group_id,{parent_subcircuit_id:t})}doInitialPcbComponentRender(){var i;if((i=this.root)!=null&&i.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=e.pcb_group.insert({is_subcircuit:this.isSubcircuit,subcircuit_id:this.subcircuit_id,name:this._parsedProps.name,center:this._getGlobalPcbPositionBeforeLayout(),width:0,height:0,pcb_component_ids:[],source_group_id:this.source_group_id});this.pcb_group_id=n.pcb_group_id}doInitialCreateTraceHintsFromProps(){var a;const{_parsedProps:e}=this,{db:t}=this.root,n=e;if(!this.isSubcircuit)return;const i=(a=n.layout)==null?void 0:a.manual_trace_hints;if(i)for(const o of i)this.add(new PBe({for:o.pcb_port_selector,offsets:o.offsets}))}doInitialSourceAddConnectivityMapKey(){if(!this.isSubcircuit)return;const{db:e}=this.root,t=this.selectAll("trace"),n=new w6({});n.addConnections(t.map(i=>{const a=e.source_trace.get(i.source_trace_id);return a?[a.source_trace_id,...a.connected_source_port_ids,...a.connected_source_net_ids]:null}).filter(i=>i!==null));for(const i of t){if(!i.source_trace_id)continue;const a=n.getNetConnectedToId(i.source_trace_id);if(!a)continue;const{name:o}=this._parsedProps;i.subcircuit_connectivity_map_key=`${o??`unnamedsubcircuit${this._renderId}`}_${a}`,e.source_trace.update(i.source_trace_id,{subcircuit_connectivity_map_key:i.subcircuit_connectivity_map_key})}}_areChildSubcircuitsRouted(){const e=this.selectAll("group").filter(t=>t.isSubcircuit);for(const t of e)if(t._shouldRouteAsync()&&!t._asyncAutoroutingResult)return!1;return!0}_shouldRouteAsync(){const e=this._getAutorouterConfig();return e.groupMode==="sequential-trace"?!1:!!(e.local&&e.groupMode==="subcircuit"||!e.local)}_hasTracesToRoute(){const e=E1("tscircuit:core:_hasTracesToRoute"),t=this.selectAll("trace");return e(`[${this.getString()}] has ${t.length} traces to route`),t.length>0}async _runEffectMakeHttpAutoroutingRequest(){var c,u,f,p;const{db:e}=this.root,t=E1("tscircuit:core:_runEffectMakeHttpAutoroutingRequest");this._parsedProps;const n=this._getAutorouterConfig(),i=n.serverUrl,a=n.serverMode,o=(v,x)=>{var S;return t("fetching",v),x.headers&&(x.headers["Tscircuit-Core-Version"]=(S=this.root)==null?void 0:S.getCoreVersion()),fetch(v,x)},s=this.root.db.toArray().filter(v=>v.type.startsWith("source_")||v.type.startsWith("pcb_"));if(a==="solve-endpoint"){if(((c=this.props.autorouter)==null?void 0:c.inputFormat)==="simplified"){const{autorouting_result:x}=await o(`${i}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_simple_route_json:NBe({db:e,minTraceWidth:((u=this.props.autorouter)==null?void 0:u.minTraceWidth)??.15,subcircuit_id:this.subcircuit_id}).simpleRouteJson,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(S=>S.json());this._asyncAutoroutingResult=x,this._markDirty("PcbTraceRender");return}const{autorouting_result:v}=await o(`${i}/autorouting/solve`,{method:"POST",body:JSON.stringify({input_circuit_json:s,subcircuit_id:this.subcircuit_id}),headers:{"Content-Type":"application/json"}}).then(x=>x.json());this._asyncAutoroutingResult=v,this._markDirty("PcbTraceRender");return}const{autorouting_job:l}=await o(`${i}/autorouting/jobs/create`,{method:"POST",body:JSON.stringify({input_circuit_json:s,provider:"freerouting",autostart:!0,display_name:(f=this.root)==null?void 0:f.name,subcircuit_id:this.subcircuit_id,server_cache_enabled:n.serverCacheEnabled}),headers:{"Content-Type":"application/json"}}).then(v=>v.json());for(;;){const{autorouting_job:v}=await o(`${i}/autorouting/jobs/get`,{method:"POST",body:JSON.stringify({autorouting_job_id:l.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(x=>x.json());if(v.is_finished){const{autorouting_job_output:x}=await o(`${i}/autorouting/jobs/get_output`,{method:"POST",body:JSON.stringify({autorouting_job_id:l.autorouting_job_id}),headers:{"Content-Type":"application/json"}}).then(S=>S.json());this._asyncAutoroutingResult={output_pcb_traces:x.output_pcb_traces},this._markDirty("PcbTraceRender");break}if(v.has_error)throw e.pcb_autorouting_error.insert({pcb_error_id:l.autorouting_job_id,message:((p=v.error)==null?void 0:p.message)??JSON.stringify(v.error)}),new Error(`Autorouting job failed: ${JSON.stringify(v.error)}`);await new Promise(x=>setTimeout(x,100))}}async _runLocalAutorouting(){var s,l,c,u,f;const{db:e}=this.root;this._parsedProps;const t=E1("tscircuit:core:_runLocalAutorouting");t(`[${this.getString()}] starting local autorouting`);const n=this._getAutorouterConfig(),{simpleRouteJson:i}=NBe({db:e,minTraceWidth:((s=this.props.autorouter)==null?void 0:s.minTraceWidth)??.15,subcircuit_id:this.subcircuit_id});(l=this.root)==null||l.emit("autorouting:start",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),simpleRouteJson:i});let a;n.algorithmFn?a=await n.algorithmFn(i):a=new BZt(i,{capacityDepth:(c=this.props.autorouter)==null?void 0:c.capacityDepth,targetMinCapacity:(u=this.props.autorouter)==null?void 0:u.targetMinCapacity});const o=new Promise((p,v)=>{a.on("complete",x=>{t(`[${this.getString()}] local autorouting complete`),p(x.traces)}),a.on("error",x=>{t(`[${this.getString()}] local autorouting error: ${x.error.message}`),v(x.error)})});a.on("progress",p=>{var v;(v=this.root)==null||v.emit("autorouting:progress",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),...p})}),a.start();try{const p=await o;this._asyncAutoroutingResult={output_pcb_traces:p},this._markDirty("PcbTraceRender")}catch(p){const{db:v}=this.root;throw v.pcb_autorouting_error.insert({pcb_error_id:`pcb_autorouter_error_subcircuit_${this.subcircuit_id}`,message:p instanceof Error?p.message:String(p)}),(f=this.root)==null||f.emit("autorouting:error",{subcircuit_id:this.subcircuit_id,componentDisplayName:this.getString(),error:{message:p instanceof Error?p.message:String(p)},simpleRouteJson:i}),p}finally{a.stop()}}_startAsyncAutorouting(){this._hasStartedAsyncAutorouting||(this._hasStartedAsyncAutorouting=!0,this._getAutorouterConfig().local?this._queueAsyncEffect("capacity-mesh-autorouting",async()=>this._runLocalAutorouting()):this._queueAsyncEffect("make-http-autorouting-request",async()=>this._runEffectMakeHttpAutoroutingRequest()))}doInitialPcbTraceRender(){var t;const e=E1("tscircuit:core:doInitialPcbTraceRender");if(this.isSubcircuit&&!((t=this.root)!=null&&t.pcbDisabled)&&!this.getInheritedProperty("routingDisabled")&&!this._shouldUseTraceByTraceRouting()){if(!this._areChildSubcircuitsRouted()){e(`[${this.getString()}] child subcircuits are not routed, skipping async autorouting until subcircuits routed`);return}e(`[${this.getString()}] no child subcircuits to wait for, initiating async routing`),this._hasTracesToRoute()&&this._startAsyncAutorouting()}}updatePcbTraceRender(){var n;const e=E1("tscircuit:core:updatePcbTraceRender");if(e(`[${this.getString()}] updating...`),!this.isSubcircuit)return;if(this._shouldRouteAsync()&&this._hasTracesToRoute()&&!this._hasStartedAsyncAutorouting){this._areChildSubcircuitsRouted()&&(e(`[${this.getString()}] child subcircuits are now routed, starting async autorouting`),this._startAsyncAutorouting());return}if(!this._asyncAutoroutingResult||this._shouldUseTraceByTraceRouting())return;const{db:t}=this.root;if(this._asyncAutoroutingResult.output_simple_route_json){e(`[${this.getString()}] updating PCB traces from simple route json (${(n=this._asyncAutoroutingResult.output_simple_route_json.traces)==null?void 0:n.length} traces)`),this._updatePcbTraceRenderFromSimpleRouteJson();return}if(this._asyncAutoroutingResult.output_pcb_traces){e(`[${this.getString()}] updating PCB traces from ${this._asyncAutoroutingResult.output_pcb_traces.length} traces`),this._updatePcbTraceRenderFromPcbTraces();return}}_updatePcbTraceRenderFromSimpleRouteJson(){const{db:e}=this.root,{traces:t}=this._asyncAutoroutingResult.output_simple_route_json;if(t)for(const n of t)e.pcb_trace.insert({subcircuit_id:this.subcircuit_id,route:n.route})}_updatePcbTraceRenderFromPcbTraces(){const{output_pcb_traces:e}=this._asyncAutoroutingResult;if(!e)return;const{db:t}=this.root;for(const n of e)if(n.type==="pcb_trace"){if(n.subcircuit_id=this.subcircuit_id,n.connection_name){const i=n.connection_name;n.source_trace_id=i}t.pcb_trace.insert(n)}for(const n of e)if(n.type!=="pcb_via"&&n.type==="pcb_trace")for(const i of n.route)i.route_type==="via"&&t.pcb_via.insert({pcb_trace_id:n.pcb_trace_id,x:i.x,y:i.y,hole_diameter:.3,outer_diameter:.6,layers:[i.from_layer,i.to_layer],from_layer:i.from_layer,to_layer:i.to_layer})}doInitialSchematicLayout(){if(!this.isSubcircuit||!this._parsedProps.schAutoLayoutEnabled)return;const{db:t}=this.root,n=this.getDescendants(),i=[];for(const s of n)if("schematic_component_id"in s){const l=t.schematic_component.get(s.schematic_component_id);if(l){const c=t.schematic_port.list().filter(u=>u.schematic_component_id===l.schematic_component_id);i.push(...c)}}const a=vG(t.toArray()),o=yG(a);mG(t.toArray(),o)}_getAutorouterConfig(){const e={serverUrl:"https://registry-api.tscircuit.com",serverMode:"job",serverCacheEnabled:!0},t=this._parsedProps.autorouter??this.getInheritedProperty("autorouter");return typeof t=="object"?{local:!(t.serverUrl||t.serverMode||t.serverCacheEnabled),...e,...t}:t==="auto-local"?{local:!0,groupMode:"subcircuit"}:t==="sequential-trace"?{local:!0,groupMode:"sequential-trace"}:t==="subcircuit"?{local:!0,groupMode:"subcircuit"}:t==="auto-cloud"?{local:!1,groupMode:"subcircuit",serverUrl:e.serverUrl,serverMode:e.serverMode,serverCacheEnabled:!0}:{local:!0,groupMode:"subcircuit"}}_shouldUseTraceByTraceRouting(){return this._getAutorouterConfig().groupMode==="sequential-trace"}doInitialPcbDesignRuleChecks(){var t;if((t=this.root)!=null&&t.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;const{db:e}=this.root;if(this.isSubcircuit){const n=new Map;for(const i of this.children)if(!i.isSubcircuit&&i._parsedProps.name){const a=n.get(i._parsedProps.name)||[];a.push(i),n.set(i._parsedProps.name,a)}for(const[i,a]of n.entries())a.length>1&&e.pcb_trace_error.insert({error_type:"pcb_trace_error",message:`Multiple components found with name "${i}" in subcircuit "${this._parsedProps.name||"unnamed"}". Component names must be unique within a subcircuit.`,source_trace_id:"",pcb_trace_id:"",pcb_component_ids:a.map(o=>o.pcb_component_id).filter(Boolean),pcb_port_ids:[]})}}},jZt=class extends rle{constructor(){super(...arguments);Je(this,"pcb_board_id",null);Je(this,"_drcChecksComplete",!1);Je(this,"_connectedSchematicPortPairs",new Set)}get isSubcircuit(){return!0}get config(){return{componentName:"Board",zodProps:voe}}get boardThickness(){const{_parsedProps:e}=this;return 1.4}get allLayers(){return["top","bottom","inner1","inner2"]}doInitialPcbBoardAutoSize(){var v;if((v=this.root)!=null&&v.pcbDisabled||!this.pcb_board_id)return;const{db:e}=this.root,{_parsedProps:t}=this;if(t.width&&t.height)return;let n=1/0,i=1/0,a=-1/0,o=-1/0;const s=e.pcb_component.list();let l=!1;for(const x of s){const{width:S,height:E,center:b}=x;S===0||E===0||(l=!0,n=Math.min(n,b.x-S/2),i=Math.min(i,b.y-E/2),a=Math.max(a,b.x+S/2),o=Math.max(o,b.y+E/2))}const c=2,u=l?a-n+c*2:0,f=l?o-i+c*2:0,p={x:l?(n+a)/2+(t.outlineOffsetX??0):t.outlineOffsetX??0,y:l?(i+o)/2+(t.outlineOffsetY??0):t.outlineOffsetY??0};e.pcb_board.update(this.pcb_board_id,{width:u,height:f,center:p})}doInitialPcbComponentRender(){var o,s;if((o=this.root)!=null&&o.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this;let n=t.width??0,i=t.height??0;if(t.outline){const l=t.outline.map(x=>x.x),c=t.outline.map(x=>x.y),u=Math.min(...l),f=Math.max(...l),p=Math.min(...c),v=Math.max(...c);n=f-u,i=v-p}const a=e.pcb_board.insert({center:{x:(t.pcbX??0)+(t.outlineOffsetX??0),y:(t.pcbY??0)+(t.outlineOffsetY??0)},thickness:this.boardThickness,num_layers:this.allLayers.length,width:n,height:i,outline:(s=t.outline)==null?void 0:s.map(l=>({x:l.x+(t.outlineOffsetX??0),y:l.y+(t.outlineOffsetY??0)})),material:t.material});this.pcb_board_id=a.pcb_board_id}removePcbComponentRender(){const{db:e}=this.root;this.pcb_board_id&&(e.pcb_board.delete(this.pcb_board_id),this.pcb_board_id=null)}_computePcbGlobalTransformBeforeLayout(){return Zm()}doInitialPcbDesignRuleChecks(){var e;(e=this.root)!=null&&e.pcbDisabled||this.getInheritedProperty("routingDisabled")||super.doInitialPcbDesignRuleChecks()}updatePcbDesignRuleChecks(){var n;if((n=this.root)!=null&&n.pcbDisabled||this.getInheritedProperty("routingDisabled"))return;const{db:e}=this.root;if(!this._areChildSubcircuitsRouted()||this._drcChecksComplete)return;this._drcChecksComplete=!0;const t=YUe(e.toArray());for(const i of t)e.pcb_trace_error.insert(i)}_emitRenderLifecycleEvent(e,t){var n;super._emitRenderLifecycleEvent(e,t),t==="start"&&((n=this.root)==null||n.emit("board:renderPhaseStarted",{renderId:this._renderId,phase:e}))}},VZt=new Proxy({},{get:(r,e)=>e}),jA=VZt,GZt=class extends Wx{get config(){return{componentName:"Capacitor",schematicSymbolName:this.props.polarized?"capacitor_polarized":this.props.symbolName??"capacitor",zodProps:hUe,sourceFtype:jA.simple_capacitor}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){const r=`${f3(this._parsedProps.capacitance)}F`;return this._parsedProps.schShowRatings&&this._parsedProps.maxVoltageRating?`${r}/${f3(this._parsedProps.maxVoltageRating)}V`:r}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.decouplingFor,this.props.decouplingTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.decouplingFor&&this.props.decouplingTo&&(this.add(new q8({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.decouplingFor})),this.add(new q8({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.decouplingTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({ftype:"simple_capacitor",name:e.name,manufacturer_part_number:e.manufacturerPartNumber??e.mfn,supplier_part_numbers:e.supplierPartNumbers,capacitance:e.capacitance,max_voltage_rating:e.maxVoltageRating,max_decoupling_trace_length:e.maxDecouplingTraceLength,display_capacitance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!e.polarized});this.source_component_id=t.source_component_id}},DBe=class extends Wx{constructor(){super(...arguments);Je(this,"schematicBoxDimensions",null)}get config(){return{componentName:"Chip",zodProps:yoe,shouldRenderAsSchematicBox:!0}}doInitialSchematicComponentRender(){const{_parsedProps:e}=this;(e==null?void 0:e.noSchematicRepresentation)!==!0&&super.doInitialSchematicComponentRender()}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_chip",name:t.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers});this.source_component_id=n.source_component_id}doInitialPcbComponentRender(){var i;if((i=this.root)!=null&&i.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=e.pcb_component.insert({center:{x:t.pcbX??0,y:t.pcbY??0},width:2,height:3,layer:t.layer??"top",rotation:t.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.pcb_component_id=n.pcb_component_id}doInitialCreateTracesFromProps(){const{_parsedProps:e}=this;if(e.externallyConnectedPins)for(const[t,n]of e.externallyConnectedPins)this.add(new q8({from:`${this.getSubcircuitSelector()} > port.${t}`,to:`${this.getSubcircuitSelector()} > port.${n}`}));this._createTracesFromConnectionsProp()}},qZt=class extends Wx{constructor(){super(...arguments);Je(this,"pos",this.portMap.pin1);Je(this,"anode",this.portMap.pin1);Je(this,"neg",this.portMap.pin2);Je(this,"cathode",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"diode",componentName:"Diode",zodProps:RUe,sourceFtype:"simple_diode"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_diode",name:t.name,manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=n.source_component_id}},$Zt=class extends Wx{constructor(){super(...arguments);Je(this,"schematicDimensions",null)}get config(){let e="";if(this.props.pinCount&&(e+=`solderjumper${this.props.pinCount||2}`),Array.isArray(this.props.internallyConnectedPins)&&this.props.internallyConnectedPins.length>0){const t=Array.from(new Set(this.props.internallyConnectedPins.flat())).sort().join("");e+=`_bridged${t}`}return{schematicSymbolName:e,componentName:"Jumper",zodProps:sUe,shouldRenderAsSchematicBox:!0}}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_chip",name:t.name,manufacturer_part_number:t.manufacturerPartNumber,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=n.source_component_id}doInitialPcbComponentRender(){var i;if((i=this.root)!=null&&i.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=e.pcb_component.insert({center:{x:t.pcbX??0,y:t.pcbY??0},width:2,height:3,layer:t.layer??"top",rotation:t.pcbRotation??0,source_component_id:this.source_component_id,subcircuit_id:this.getSubcircuit().subcircuit_id??void 0});this.pcb_component_id=n.pcb_component_id}doInitialPcbTraceRender(){const{db:e}=this.root,t=e.pcb_port.list({pcb_component_id:this.pcb_component_id}),n={};for(let o=0;o<t.length;o++){const s=t[o],l=e.source_port.get(s.source_port_id);let c="";if(typeof(l==null?void 0:l.pin_number)=="number")c=l.pin_number.toString();else if(Array.isArray(l==null?void 0:l.port_hints)){let u=l.port_hints.find(f=>/^(pin)?\d+$/.test(f));u&&(/^pin\d+$/.test(u)?c=u.replace(/^pin/,""):c=u)}n[c]=s.pcb_port_id}const i=e.pcb_trace.list(),a=o=>{if(o&&typeof o=="string"&&o.startsWith("{PIN")){const s=o.replace("{PIN","").replace("}","");return n[s]||o}return o};for(const o of i)if(o.route)for(const s of o.route)s.route_type==="wire"&&(s.start_pcb_port_id=a(s.start_pcb_port_id),s.end_pcb_port_id=a(s.end_pcb_port_id))}},YZt=class extends Wx{constructor(){super(...arguments);Je(this,"pos",this.portMap.pin1);Je(this,"anode",this.portMap.pin1);Je(this,"neg",this.portMap.pin2);Je(this,"cathode",this.portMap.pin2)}get config(){return{componentName:"Led",schematicSymbolName:this.props.symbolName??"led",zodProps:AUe,sourceFtype:"simple_diode"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_diode",name:t.name,manufacturer_part_number:t.manufacturerPartNumber??t.mfn,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=n.source_component_id}},XZt=class extends Wx{constructor(){super(...arguments);Je(this,"pos",this.portMap.pin1);Je(this,"positive",this.portMap.pin1);Je(this,"neg",this.portMap.pin2);Je(this,"negative",this.portMap.pin2)}get config(){return{schematicSymbolName:this.props.symbolName??"power_factor_meter_horz",componentName:"PowerSource",zodProps:zUe,sourceFtype:"simple_power_source"}}initPorts(){this.add(new W4({name:"pin1",pinNumber:1,aliases:["positive","pos"]})),this.add(new W4({name:"pin2",pinNumber:2,aliases:["negative","neg"]}))}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_power_source",name:t.name,voltage:t.voltage,supplier_part_numbers:t.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=n.source_component_id}},WZt=class extends Wx{get config(){return{componentName:"Resistor",schematicSymbolName:this.props.symbolName??"boxresistor",zodProps:uUe,sourceFtype:"simple_resistor"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}_getSchematicSymbolDisplayValue(){return`${f3(this._parsedProps.resistance)}Ω`}doInitialCreateNetsFromProps(){this._createNetsFromProps([this.props.pullupFor,this.props.pullupTo,...this._getNetsFromConnectionsProp()])}doInitialCreateTracesFromProps(){this.props.pullupFor&&this.props.pullupTo&&(this.add(new q8({from:`${this.getSubcircuitSelector()} > port.1`,to:this.props.pullupFor})),this.add(new q8({from:`${this.getSubcircuitSelector()} > port.2`,to:this.props.pullupTo}))),this._createTracesFromConnectionsProp()}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({ftype:"simple_resistor",name:e.name,manufacturer_part_number:e.manufacturerPartNumber??e.mfn,supplier_part_numbers:e.supplierPartNumbers,resistance:e.resistance,display_resistance:this._getSchematicSymbolDisplayValue(),are_pins_interchangeable:!0});this.source_component_id=t.source_component_id}},ZZt=["leftedge","rightedge","topedge","bottomedge","center"],QZt=class extends M_{get config(){return{componentName:"Constraint",zodProps:mUe}}constructor(r){if(super(r),("xdist"in r||"ydist"in r)&&!("edgeToEdge"in r)&&!("centerToCenter"in r))throw new Error(`edgeToEdge, centerToCenter must be set for xDist or yDist for ${this}`);if("for"in r&&r.for.length<2)throw new Error(`"for" must have at least two selectors for ${this}`)}_getAllReferencedComponents(){const r=[],e=this.getPrimitiveContainer();function t(n){const i=n.split(" ").pop(),a=ZZt.includes(i)?i:void 0,o=a?n.replace(` ${a}`,""):n,s=e.selectOne(o,{pcbPrimitive:!0});s&&r.push({selector:n,component:s,componentSelector:o,edge:a})}for(const n of["left","right","top","bottom"])n in this._parsedProps&&t(this._parsedProps[n]);if("for"in this._parsedProps)for(const n of this._parsedProps.for)t(n);return{componentsWithSelectors:r}}},KZt=class extends M_{constructor(){super(...arguments);Je(this,"fabrication_note_path_id",null)}get config(){return{componentName:"FabricationNotePath",zodProps:DUe}}doInitialPcbPrimitiveRender(){var s,l;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:e}=this.root,t=this.getSubcircuit(),{_parsedProps:n}=this,i=n.layer??"top";if(i!=="top"&&i!=="bottom")throw new Error(`Invalid layer "${i}" for SilkscreenPath. Must be "top" or "bottom".`);const a=this._computePcbGlobalTransformBeforeLayout(),o=e.pcb_fabrication_note_path.insert({pcb_component_id:(l=this.parent)==null?void 0:l.pcb_component_id,layer:i,color:n.color,route:n.route.map(c=>{const u=Ir(a,{x:c.x,y:c.y});return{...c,x:u.x,y:u.y}}),stroke_width:n.strokeWidth??.1,subcircuit_id:(t==null?void 0:t.subcircuit_id)??void 0});this.fabrication_note_path_id=o.pcb_fabrication_note_path_id}},JZt=class extends M_{get config(){return{componentName:"FabricationNoteText",zodProps:NUe}}doInitialPcbPrimitiveRender(){var i,a;if((i=this.root)!=null&&i.pcbDisabled)return;const{db:r}=this.root,{_parsedProps:e}=this,t=this.getPrimitiveContainer(),n=this.getSubcircuit();r.pcb_fabrication_note_text.insert({anchor_alignment:e.anchorAlignment,anchor_position:{x:e.pcbX??0,y:e.pcbY??0},font:e.font??"tscircuit2024",font_size:e.fontSize??1,layer:"top",color:e.color,text:e.text??"",pcb_component_id:t.pcb_component_id,subcircuit_id:(n==null?void 0:n.subcircuit_id)??void 0,pcb_group_id:((a=this.getGroup())==null?void 0:a.pcb_group_id)??void 0})}},eQt=class extends rle{constructor(r){super({...r,subcircuit:!0})}},tQt=class extends M_{constructor(){super(...arguments);Je(this,"source_net_alias_id")}get config(){return{componentName:"NetAlias",zodProps:EUe}}doInitialSchematicComponentRender(){var a;if((a=this.root)!=null&&a.schematicDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n={x:t.schX??0,y:t.schY??0},i=e.schematic_net_label.insert({text:t.net,source_net_id:t.net,anchor_position:n,center:n,anchor_side:"bottom"});this.source_net_alias_id=i.source_net_id}},nQt=class extends M_{constructor(){super(...arguments);Je(this,"pcb_silkscreen_circle_id",null);Je(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenCircle",zodProps:HUe}}doInitialPcbPrimitiveRender(){var s,l,c;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,{maybeFlipLayer:n}=this._getPcbPrimitiveFlippedHelpers(),i=n(t.layer??"top");if(i!=="top"&&i!=="bottom")throw new Error(`Invalid layer "${i}" for SilkscreenCircle. Must be "top" or "bottom".`);this._computePcbGlobalTransformBeforeLayout();const a=this.getSubcircuit(),o=e.pcb_silkscreen_circle.insert({pcb_component_id:(l=this.parent)==null?void 0:l.pcb_component_id,layer:i,center:{x:t.pcbX??0,y:t.pcbY??0},radius:t.radius,subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((c=this.getGroup())==null?void 0:c.pcb_group_id)??void 0,stroke_width:t.strokeWidth??.1});this.pcb_silkscreen_circle_id=o.pcb_silkscreen_circle_id}getPcbSize(){const{_parsedProps:e}=this,t=e.radius*2;return{width:t,height:t}}},rQt=class extends M_{constructor(){super(...arguments);Je(this,"pcb_silkscreen_rect_id",null);Je(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenRect",zodProps:BUe}}doInitialPcbPrimitiveRender(){var s,l,c;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,{maybeFlipLayer:n}=this._getPcbPrimitiveFlippedHelpers(),i=n(t.layer??"top");if(i!=="top"&&i!=="bottom")throw new Error(`Invalid layer "${i}" for SilkscreenRect. Must be "top" or "bottom".`);const a=this.getSubcircuit(),o=e.pcb_silkscreen_rect.insert({pcb_component_id:(l=this.parent)==null?void 0:l.pcb_component_id,layer:i,center:{x:t.pcbX??0,y:t.pcbY??0},width:t.width,height:t.height,subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((c=this==null?void 0:this.getGroup())==null?void 0:c.pcb_group_id)??void 0,stroke_width:t.strokeWidth??.1});this.pcb_silkscreen_rect_id=o.pcb_silkscreen_rect_id}getPcbSize(){const{_parsedProps:e}=this;return{width:e.width,height:e.height}}},iQt=class extends M_{constructor(){super(...arguments);Je(this,"pcb_silkscreen_line_id",null);Je(this,"isPcbPrimitive",!0)}get config(){return{componentName:"SilkscreenLine",zodProps:FUe}}doInitialPcbPrimitiveRender(){var s,l,c;if((s=this.root)!=null&&s.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,{maybeFlipLayer:n}=this._getPcbPrimitiveFlippedHelpers(),i=n(t.layer??"top");if(i!=="top"&&i!=="bottom")throw new Error(`Invalid layer "${i}" for SilkscreenLine. Must be "top" or "bottom".`);const a=this.getSubcircuit(),o=e.pcb_silkscreen_line.insert({pcb_component_id:(l=this.parent)==null?void 0:l.pcb_component_id,layer:i,x1:t.x1,y1:t.y1,x2:t.x2,y2:t.y2,stroke_width:t.strokeWidth??.1,subcircuit_id:(a==null?void 0:a.subcircuit_id)??void 0,pcb_group_id:((c=a==null?void 0:a.getGroup())==null?void 0:c.pcb_group_id)??void 0});this.pcb_silkscreen_line_id=o.pcb_silkscreen_line_id}getPcbSize(){const{_parsedProps:e}=this,t=Math.abs(e.x2-e.x1),n=Math.abs(e.y2-e.y1);return{width:t,height:n}}},aQt=class extends M_{constructor(){super(...arguments);Je(this,"pcb_via_id",null);Je(this,"matchedPort",null);Je(this,"isPcbPrimitive",!0)}get config(){return{componentName:"Via",zodProps:LUe}}getAvailablePcbLayers(){return["top","inner1","inner2","bottom"]}getPcbSize(){const{_parsedProps:e}=this;return{width:e.outerDiameter,height:e.outerDiameter}}_getPcbCircuitJsonBounds(){const{db:e}=this.root,t=e.pcb_via.get(this.pcb_via_id),n=this.getPcbSize();return{center:{x:t.x,y:t.y},bounds:{left:t.x-n.width/2,top:t.y-n.height/2,right:t.x+n.width/2,bottom:t.y+n.height/2},width:n.width,height:n.height}}_setPositionFromLayout(e){const{db:t}=this.root;t.pcb_via.update(this.pcb_via_id,{x:e.x,y:e.y})}doInitialPcbPrimitiveRender(){var o,s;if((o=this.root)!=null&&o.pcbDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this,n=this._getGlobalPcbPositionBeforeLayout(),i=this.getSubcircuit(),a=e.pcb_via.insert({x:n.x,y:n.y,hole_diameter:t.holeDiameter,outer_diameter:t.outerDiameter,layers:["bottom","top"],from_layer:t.fromLayer||"bottom",to_layer:t.toLayer||"top",subcircuit_id:(i==null?void 0:i.subcircuit_id)??void 0,pcb_group_id:((s=this.getGroup())==null?void 0:s.pcb_group_id)??void 0});this.pcb_via_id=a.pcb_via_id}},oQt=class extends Wx{get config(){return{componentName:"Battery",schematicSymbolName:this.props.symbolName??"battery",zodProps:bUe,sourceFtype:"simple_power_source"}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({name:e.name,ftype:"simple_power_source",capacity:e.capacity,supplier_part_numbers:e.supplierPartNumbers,are_pins_interchangeable:!1});this.source_component_id=t.source_component_id}},sQt=class extends Wx{get config(){return{componentName:"PinHeader",zodProps:SUe,shouldRenderAsSchematicBox:!0}}_getImpliedFootprintString(){var i;const r=this._parsedProps.pinCount??((i=this._parsedProps.pinLabels)==null?void 0:i.length)??0,e=this._parsedProps.holeDiameter,t=this._parsedProps.platedDiameter,n=this._parsedProps.pitch;return r>0&&n?!e&&!t?`pinrow${r}_p${n}`:`pinrow${r}_p${n}_id${e}_od${t}`:null}initPorts(){var e,t;const r=this._parsedProps.pinCount??((e=this._parsedProps.pinLabels)==null?void 0:e.length)??1;for(let n=1;n<=r;n++)this.add(new W4({name:`pin${n}`,pinNumber:n,aliases:[(t=this._parsedProps.pinLabels)==null?void 0:t[n-1]].filter(Boolean)}))}_getSchematicPortArrangement(){const r=this._parsedProps.pinCount??1,e=this._parsedProps.facingDirection??"right";return{leftSize:e==="left"?r:0,rightSize:e==="right"?r:0}}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({ftype:"simple_pin_header",name:e.name,supplier_part_numbers:e.supplierPartNumbers,pin_count:e.pinCount,gender:e.gender,are_pins_interchangeable:!0});this.source_component_id=t.source_component_id}};function lQt(r){switch(r){case"two_ground_pins":return"crystal_4pin";case"ground_pin":return"resonator";case"no_ground":return"crystal";default:return"crystal"}}var cQt=class extends Wx{get config(){return{componentName:"Resonator",schematicSymbolName:this.props.symbolName??lQt(this.props.pinVariant),zodProps:pUe,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=e.pinVariant||"no_ground",n=r.source_component.insert({ftype:"simple_resonator",name:e.name,frequency:e.frequency,load_capacitance:e.loadCapacitance,supplier_part_numbers:e.supplierPartNumbers,pin_variant:t,are_pins_interchangeable:t==="no_ground"||t==="ground_pin"});this.source_component_id=n.source_component_id}},uQt=class extends Wx{get config(){return{componentName:"Inductor",schematicSymbolName:this.props.symbolName??"inductor",zodProps:CUe,sourceFtype:jA.simple_inductor}}initPorts(){super.initPorts({additionalAliases:{pin1:["anode","pos","left"],pin2:["cathode","neg","right"]}})}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({name:e.name,ftype:jA.simple_inductor,inductance:e.inductance,supplier_part_numbers:e.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=t.source_component_id}};function fQt(r){switch(r){case"three_pin":return"potentiometer3";case"two_pin":return"potentiometer2";default:return"potentiometer2"}}var dQt=class extends Wx{get config(){return{componentName:"Potentiometer",schematicSymbolName:this.props.symbolName??fQt(this.props.pinVariant),zodProps:fUe,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=e.pinVariant||"two_pin",n=r.source_component.insert({ftype:"simple_potentiometer",name:e.name,max_resistance:e.maxResistance,pin_variant:t,are_pins_interchangeable:t==="two_pin"});this.source_component_id=n.source_component_id}},pQt=class extends Wx{get config(){return{componentName:"PushButton",schematicSymbolName:this.props.symbolName??"push_button_normally_open_momentary",zodProps:wUe,sourceFtype:jA.simple_push_button}}get defaultInternallyConnectedPinNames(){return[["pin1","pin4"],["pin2","pin3"]]}initPorts(){super.initPorts({pinCount:4,additionalAliases:{pin1:["side1"],pin3:["side2"]}})}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({name:e.name,ftype:jA.simple_push_button,supplier_part_numbers:e.supplierPartNumbers,are_pins_interchangeable:!0});this.source_component_id=t.source_component_id}},hQt=class extends Wx{get config(){return{schematicSymbolName:this.props.symbolName??(this.props.pinVariant==="four_pin"?"crystal_4pin":"crystal"),componentName:"Crystal",zodProps:dUe,sourceFtype:"simple_crystal"}}initPorts(){const r=this.props.pinVariant==="four_pin"?{pin1:["left1","1"],pin2:["top1","2","gnd1"],pin3:["right1","3"],pin4:["bottom1","4","gnd2"]}:{pin1:["pos","left"],pin2:["neg","right"]};super.initPorts({additionalAliases:r})}_getSchematicSymbolDisplayValue(){return`${f3(this._parsedProps.frequency)}Hz`}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({name:e.name,ftype:"simple_crystal",frequency:e.frequency,load_capacitance:e.loadCapacitance,pin_variant:e.pinVariant||"two_pin",are_pins_interchangeable:(e.pinVariant||"two_pin")==="two_pin"});this.source_component_id=t.source_component_id}},mQt=class extends Wx{constructor(){super(...arguments);Je(this,"emitter",this.portMap.pin1);Je(this,"collector",this.portMap.pin2);Je(this,"base",this.portMap.pin3)}get config(){return{componentName:"Transistor",schematicSymbolName:this.props.type==="npn"?"npn_bipolar_transistor":"pnp_bipolar_transistor",zodProps:TUe,sourceFtype:"simple_transistor",shouldRenderAsSchematicBox:!1}}initPorts(){const e=this.props.type==="npn"?{pin1:["emitter","e"],pin2:["collector","c"],pin3:["base","b"]}:{pin1:["collector","c"],pin2:["emitter","e"],pin3:["base","b"]};super.initPorts({pinCount:3,additionalAliases:e})}doInitialSourceRender(){const{db:e}=this.root,{_parsedProps:t}=this,n=e.source_component.insert({ftype:"simple_transistor",name:t.name,transistor_type:t.type});this.source_component_id=n.source_component_id}},vQt=class extends Wx{get config(){const r=this.props.mosfetMode==="depletion"?"d":"e";return{componentName:"Mosfet",schematicSymbolName:`${this.props.channelType}_channel_${r}_mosfet_transistor`,zodProps:MUe,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({ftype:"simple_mosfet",name:e.name,mosfet_mode:e.mosfetMode,channel_type:e.channelType});this.source_component_id=t.source_component_id}},yQt=class extends Wx{_getSwitchType(){const{spst:r,spdt:e,dpst:t,dpdt:n,type:i}=this._parsedProps??{};return n?"dpdt":r?"spst":e?"spdt":t?"dpst":i??"spst"}get config(){const r=this._getSwitchType(),{isNormallyClosed:e}=this._parsedProps??{};return{componentName:"Switch",schematicSymbolName:{spst:e?"spst_normally_closed_switch":"spst_switch",spdt:e?"spdt_normally_closed_switch":"spdt_switch",dpst:e?"dpst_normally_closed_switch":"dpst_switch",dpdt:e?"dpdt_normally_closed_switch":"dpdt_switch"}[r]??"spst_switch",zodProps:PUe,shouldRenderAsSchematicBox:!1}}doInitialSourceRender(){const{db:r}=this.root,{_parsedProps:e}=this,t=r.source_component.insert({ftype:"simple_switch",name:e.name,switch_type:e.type,is_normally_closed:e.isNormallyClosed??!1,are_pins_interchangeable:this._getSwitchType()==="spst"});this.source_component_id=t.source_component_id}},gQt=class extends M_{constructor(){super(...arguments);Je(this,"isSchematicPrimitive",!0)}get config(){return{componentName:"SchematicText",zodProps:UUe}}doInitialSchematicPrimitiveRender(){var n;if((n=this.root)!=null&&n.schematicDisabled)return;const{db:e}=this.root,{_parsedProps:t}=this;e.schematic_text.insert({anchor:t.anchor??"center",text:t.text,font_size:t.fontSize,color:t.color||"#000000",position:{x:t.schX,y:t.schY},rotation:t.schRotation??0})}};new Proxy({},{get:(r,e)=>{const t=(...n)=>(n[0],new Proxy({},{get:(i,a)=>`.${e} > .${a}`}));return new Proxy(t,{get:(n,i)=>e==="net"?`net.${i}`:e==="subcircuit"?new Proxy({},{get:(a,o)=>new Proxy({},{get:(s,l)=>`subcircuit.${i} > .${o} > .${l}`})}):`.${e} > .${i}`,apply:(n,i,a)=>new Proxy({},{get:(o,s)=>{const l=`.${e} > .${s}`;return e.startsWith("U")?l:new Proxy(new String(l),{get:(c,u)=>typeof u=="symbol"||u==="toString"?()=>l:`.${e} > .${s} > .${u}`})}})})}}),pBe(fBe),pBe({Bug:DBe});const LBe=r=>`hsl(${T3.indexOf(r)*137.5%360}, 70%, 50%)`,_Qt=({phaseTimings:r})=>{if(!r)return null;const e=Object.values(r).reduce((t,n)=>t+n,0);return ut.jsxs("div",{className:"rf-space-y-2 rf-w-full rf-px-4",children:[ut.jsx("div",{className:"rf-relative rf-h-8 rf-flex rf-rounded-sm",children:T3.map(t=>{const n=r[t]||0,i=n/e*100;return ut.jsx("div",{className:"rf-group/bar rf-relative rf-overflow-visible",style:{width:`${i}%`,backgroundColor:LBe(t)},children:ut.jsxs("div",{className:"rf-opacity-0 group-hover/bar:rf-opacity-100 rf-transition-opacity rf-absolute rf-bottom-full rf-left-1/2 rf-transform -rf-translate-x-1/2 rf-mb-2 rf-px-2 rf-py-1 rf-text-xs rf-whitespace-nowrap rf-rounded rf-bg-gray-900 rf-text-white rf-pointer-events-none",children:[t,": ",n.toFixed(1),"ms"]})},t)})}),ut.jsxs("div",{className:"rf-text-xs rf-text-gray-500",children:["Total: ",e.toFixed(2),"ms"]})]})},xQt=({renderLog:r})=>{const[e,t]=mt.useState("chronological");if(!r)return ut.jsx("div",{className:"rf-p-4 rf-bg-gray-100 rf-rounded-md",children:"No render log, make sure this tab is open when you render (TODO add a rerender button here)"});const n=Object.entries((r==null?void 0:r.phaseTimings)??{});e==="chronological"?n.sort((a,o)=>T3.indexOf(a[0])-T3.indexOf(o[0])):n.sort((a,o)=>o[1]-a[1]);const i=n.reduce((a,[o,s])=>a+s,0);return ut.jsxs("div",{className:"rf-bg-white",children:[ut.jsxs("div",{className:"rf-flex rf-justify-between rf-items-center",children:[ut.jsx("div",{children:"Render Logs"}),ut.jsxs("div",{className:"rf-mb-4 rf-pr-2 rf-flex rf-text-xs rf-items-center",children:[ut.jsx("div",{className:"rf-mr-2",children:"Sort by:"}),ut.jsxs("select",{value:e,onChange:a=>t(a.target.value),className:"rf-px-2 rf-py-1 rf-border rf-rounded rf-text-xs",children:[ut.jsx("option",{value:"chronological",children:"Phase Order"}),ut.jsx("option",{value:"longest",children:"Duration"})]})]})]}),ut.jsx(_Qt,{phaseTimings:r.phaseTimings}),ut.jsxs("table",{className:"rf-w-full rf-text-xs",children:[ut.jsx("thead",{children:ut.jsxs("tr",{children:[ut.jsx("th",{className:"rf-text-left rf-p-2",children:"Phase Order"}),ut.jsx("th",{className:"rf-text-left rf-p-2",children:"Phase"}),ut.jsx("th",{className:"rf-text-left rf-p-2",children:"Duration (ms)"})]})}),ut.jsx("tbody",{children:n.map(([a,o])=>ut.jsxs("tr",{children:[ut.jsx("td",{className:"rf-p-2",children:T3.indexOf(a)}),ut.jsx("td",{className:"rf-p-2",children:a}),ut.jsx("td",{className:"rf-p-2",children:ut.jsx("div",{className:"rf-w-8",children:ut.jsx("div",{className:"rf-h-2 rf-rounded-sm",style:{backgroundColor:LBe(a),width:`${o/i*100}%`}})})}),ut.jsx("td",{className:"rf-p-2",children:ut.jsxs("div",{className:"rf-flex w-full",children:[ut.jsxs("span",{className:"rf-flex-grow",children:[o,"ms"]}),ut.jsxs("span",{className:"rf-text-gray-500 rf-pr-2",children:[(o/i*100).toFixed(1),"%"]})]})})]},a))})]})]})},bQt="0.0.446",SQt=["assembly","bom","circuit_json","errors","render_log"],EQt=({code:r,onRunClicked:e=void 0,errorMessage:t,circuitJson:n,autoroutingGraphics:i,showRightHeaderContent:a=!0,showCodeTab:o=!1,codeTabContent:s,showJsonTab:l=!0,showRenderLogTab:c=!0,onActiveTabChange:u,renderLog:f,showImportAndFormatButtons:p=!0,className:v,headerClassName:x,leftHeaderContent:S,readOnly:E,isStreaming:b,autoroutingLog:C,onReportAutoroutingLog:O,isRunningCode:U,hasCodeChangedSinceLastRun:q,onEditEvent:Y,editEvents:Q,defaultActiveTab:K,autoRotate3dViewerDisabled:te,showSchematicDebugGrid:J=!1,showToggleFullScreen:fe=!0,defaultToFullScreen:he=!1})=>{var Ue;YWt();const ve=mt.useMemo(()=>n?n.filter(Ie=>Ie&&"error_type"in Ie):null,[n]),[Te,Pe]=mt.useState(K??"pcb"),[Ee,Ce]=mt.useState(he),be=mt.useCallback(Ie=>{Pe(Ie),u==null||u(Ie)},[u]),Oe=()=>{Ce(!Ee)};return mt.useEffect(()=>{t&&be("errors")},[t]),mt.useEffect(()=>{(Te==="code"||Te==="errors")&&n&&!t&&be(K??"pcb")},[n]),ut.jsx("div",{className:Hg("flex flex-col relative rf-overflow-x-hidden",v),children:ut.jsx("div",{className:Hg("rf-md:sticky rf-md:top-2",Ee&&"rf-fixed rf-top-0 rf-left-0 rf-w-full rf-bg-white"),children:ut.jsxs(kGe,{value:Te,onValueChange:be,className:"rf-flex-grow rf-flex rf-flex-col",children:[ut.jsxs("div",{className:Hg("rf-flex rf-items-center rf-gap-2 rf-p-2 rf-pb-0",x),children:[S,S&&ut.jsx("div",{className:"rf-flex-grow"}),!S&&U&&ut.jsx(dPe,{className:"rf-w-4 rf-h-4 rf-animate-spin"}),!S&&ut.jsx("div",{className:"rf-flex-grow"}),f&&f.progress!==1&&ut.jsxs("div",{className:"rf-flex rf-items-center rf-gap-2",children:[f.lastRenderEvent&&ut.jsx("div",{className:"rf-text-xs rf-text-gray-500",children:((Ue=f.lastRenderEvent)==null?void 0:Ue.phase)??""}),ut.jsx("div",{className:"rf-w-4 rf-h-4 rf-bg-blue-500 rf-opacity-50 rf-rounded-full rf-text-white",children:ut.jsx(dPe,{className:"rf-w-4 rf-h-4 rf-animate-spin"})}),ut.jsxs("div",{className:"rf-text-xs rf-font-bold rf-text-gray-700 rf-tabular-nums",children:[((f.progress??0)*100).toFixed(1),"%"]})]}),a&&ut.jsxs(uue,{children:[o&&ut.jsx(a6,{value:"code",children:"Code"}),ut.jsxs(a6,{value:"pcb",className:"rf-whitespace-nowrap",children:[n&&ut.jsx("span",{className:Hg("rf-inline-flex rf-items-center rf-justify-center rf-w-2 rf-h-2 rf-mr-1 rf-text-xs rf-font-bold rf-text-white rf-rounded-full",q?"rf-bg-gray-500":"rf-bg-blue-500")}),"PCB"]}),ut.jsxs(a6,{value:"schematic",className:"rf-whitespace-nowrap",children:[n&&ut.jsx("span",{className:Hg("rf-inline-flex rf-items-center rf-justify-center rf-w-2 rf-h-2 rf-mr-1 rf-text-xs rf-font-bold rf-text-white rf-rounded-full",q?"rf-bg-gray-500":"rf-bg-blue-500")}),"Schematic"]}),ut.jsxs(a6,{value:"cad",children:[n&&ut.jsx("span",{className:Hg("inline-flex items-center justify-center w-2 h-2 mr-1 text-xs font-bold text-white rounded-full",q?"rf-bg-gray-500":"rf-bg-blue-500")}),"3D"]}),!["pcb","cad","schematic"].includes(Te)&&ut.jsx(a6,{value:Te,children:cue(Te)}),ut.jsxs(SDe,{children:[ut.jsx(EDe,{asChild:!0,children:ut.jsxs("div",{className:"rf-whitespace-nowrap rf-p-2 rf-mr-1 rf-cursor-pointer rf-relative",children:[ut.jsx(zDt,{className:"rf-w-4 rf-h-4"}),(ve&&ve.length>0||t)&&ut.jsx("span",{className:"rf-inline-flex rf-absolute rf-top-[6px] rf-right-[4px] rf-items-center rf-justify-center rf-w-1 rf-h-1 rf-ml-2 rf-text-[8px] rf-font-bold rf-text-white rf-bg-red-500 rf-rounded-full"})]})}),ut.jsxs(Iie,{className:"rf-*:text-xs",children:[SQt.map(Ie=>ut.jsxs(bI,{onSelect:()=>be(Ie),children:[Te!==Ie&&ut.jsx(fPe,{className:"rf-w-3 rf-h-3 rf-opacity-30"}),Te===Ie&&ut.jsx(cPe,{className:"rf-w-3 rf-h-3"}),ut.jsx("div",{className:"rf-pr-2",children:cue(Ie)}),Ie==="errors"&&(ve&&ve.length>0||t)&&ut.jsx("span",{className:"rf-inline-flex rf-items-center rf-justify-center rf-w-3 rf-h-3 rf-ml-2 rf-text-[8px] rf-font-bold rf-text-white rf-bg-red-500 rf-rounded-full",children:t?1:ve==null?void 0:ve.length})]},Ie)),ut.jsx(bI,{disabled:!0,className:"rf-opacity-60 rf-cursor-default rf-select-none",children:ut.jsxs("div",{className:"rf-pr-2 rf-text-xs rf-text-gray-500",children:["@tscircuit/runframe@",bQt.split(".").map((Ie,ke)=>ke===2?parseInt(Ie)+1:Ie).join(".")]})})]})]})]}),fe&&ut.jsx(HE,{onClick:Oe,variant:"ghost",children:Ee?ut.jsx(kDt,{size:16}):ut.jsx(UDt,{size:16})})]}),o&&ut.jsx(uS,{value:"code",className:"rf-flex-grow rf-overflow-hidden",children:ut.jsx("div",{className:"rf-h-full",children:s})}),ut.jsx(uS,{value:"pcb",children:ut.jsx("div",{className:Hg("rf-overflow-hidden",Ee?"rf-h-[calc(100vh-52px)]":"rf-h-[620px]"),children:ut.jsx(YT,{fallbackRender:({error:Ie})=>ut.jsx("div",{className:"rf-mt-4 rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200",children:ut.jsxs("div",{className:"rf-p-4",children:[ut.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-3",children:"Error loading PCB viewer"}),ut.jsx("p",{className:"rf-text-xs rf-font-mono rf-whitespace-pre-wrap rf-text-red-600 rf-mt-2",children:(Ie==null?void 0:Ie.message)||"An unknown error occurred"})]})}),children:n?ut.jsx(qWt,{focusOnHover:!1,circuitJson:n,debugGraphics:i,containerClassName:Hg("rf-h-full rf-w-full",Ee?"rf-min-h-[calc(100vh-240px)]":"rf-min-h-[620px]"),onEditEventsChanged:Ie=>{Y&&Ie.forEach(ke=>Y(ke))}}):ut.jsx(L8,{onRunClicked:e})})})}),ut.jsx(uS,{value:"assembly",children:ut.jsx("div",{className:Hg("rf-overflow-auto",Ee?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:ut.jsx(YT,{fallback:ut.jsx("div",{children:"Error loading Assembly"}),children:n?ut.jsx(hVt,{circuitJson:n,containerStyle:{height:"100%"},editingEnabled:!0,debugGrid:!0}):ut.jsx(L8,{onRunClicked:e})})})}),ut.jsx(uS,{value:"schematic",children:ut.jsx("div",{className:Hg("rf-overflow-auto rf-bg-white",Ee?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:ut.jsx(YT,{fallbackRender:({error:Ie})=>ut.jsx("div",{className:"rf-mt-4 rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200",children:ut.jsxs("div",{className:"rf-p-4",children:[ut.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-3",children:"Error loading Schematic"}),ut.jsx("p",{className:"rf-text-xs rf-font-mono rf-whitespace-pre-wrap rf-text-red-600 rf-mt-2",children:(Ie==null?void 0:Ie.message)||"An unknown error occurred"})]})}),children:n?ut.jsx(fVt,{circuitJson:n,containerStyle:{height:"100%"},editingEnabled:!0,onEditEvent:Ie=>{Y==null||Y(Ie)},debugGrid:J,colorOverrides:{schematic:{background:"transparent"}}}):ut.jsx(L8,{onRunClicked:e})})})}),ut.jsx(uS,{value:"cad",children:ut.jsx("div",{className:Hg("rf-overflow-auto",Ee?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:ut.jsx(YT,{FallbackComponent:bDt,children:n?ut.jsx(_Dt,{soup:n,autoRotateDisabled:te}):ut.jsx(L8,{onRunClicked:e})})})}),ut.jsx(uS,{value:"bom",children:ut.jsx("div",{className:Hg("rf-overflow-auto",Ee?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:ut.jsx(YT,{fallbackRender:({error:Ie})=>ut.jsx("div",{className:"rf-mt-4 rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200",children:ut.jsxs("div",{className:"rf-p-4",children:[ut.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-3",children:"Error loading Bill of Materials"}),ut.jsx("p",{className:"rf-text-xs rf-font-mono rf-whitespace-pre-wrap rf-text-red-600 rf-mt-2",children:(Ie==null?void 0:Ie.message)||"An unknown error occurred"})]})}),children:n?ut.jsx(_Vt,{circuitJson:n}):ut.jsx(L8,{onRunClicked:e})})})}),ut.jsx(uS,{value:"circuit_json",children:ut.jsx("div",{className:Hg("rf-overflow-auto",Ee?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:ut.jsx(YT,{fallback:ut.jsx("div",{children:"Error loading JSON viewer"}),children:n?ut.jsx(yVt,{elements:n}):ut.jsx(L8,{onRunClicked:e})})})}),ut.jsx(uS,{value:"errors",children:ut.jsx("div",{className:Hg("rf-overflow-auto",Ee?"rf-h-[calc(100vh-96px)]":"rf-h-[620px]"),children:Array.isArray(ve)&&ve.length>0||t?ut.jsx(zUt,{code:r,circuitJsonErrors:ve,errorMessage:t,autoroutingLog:C,onReportAutoroutingLog:O}):ut.jsx(L8,{onRunClicked:e})})}),c&&ut.jsx(uS,{value:"render_log",children:ut.jsx(xQt,{renderLog:f})})]})})})};Pce.createRoot(document.getElementById("root")).render(ut.jsx(EQt,{defaultActiveTab:"cad",autoRotate3dViewerDisabled:!0,showRightHeaderContent:!1,circuitJson:window.CIRCUIT_JSON||{},...window.CIRCUIT_JSON_PREVIEW_PROPS||{}}))});
|