@tscircuit/runframe 0.0.3047 → 0.0.3048

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.
@@ -5420,7 +5420,7 @@ ${e.svg()}`;return I+=`" >
5420
5420
  `).map(I=>I.match(/\(([^)]+)\)/)[1]).map(teg)}function Wto(g){return g.split(`
5421
5421
  `).map(I=>I.match(/\(([^)]+)\)/)[1]).map(oeg).reduce((I,e)=>[...I,...e],[])}function E2I(g){if(g.startsWith("POINT")){const A=g.replace(/^POINT \(/,"").replace(/\)$/,"");return teg(A)}else if(g.startsWith("MULTIPOINT")){const A=g.replace(/^MULTIPOINT \(/,"").replace(/\)$/,"");return Q2I(A)}else if(g.startsWith("LINESTRING")){const A=g.replace(/^LINESTRING \(/,"").replace(/\)$/,"");return oeg(A)}else if(g.startsWith("MULTILINESTRING")){const A=g.replace(/^MULTILINESTRING /,"");return qto(A)}else{if(g.startsWith("POLYGON")||g.startsWith("MULTIPOLYGON"))return Zto(g);if(g.startsWith("GEOMETRYCOLLECTION")){const A=/(?<type>POINT|LINESTRING|POLYGON|MULTIPOINT|MULTILINESTRING|MULTIPOLYGON) \((?:[^\(\)]|\([^\)]*\))*\)/g,I=g.match(A);return I[0].startsWith("GEOMETRYCOLLECTION")&&(I[0]=I[0].replace("GEOMETRYCOLLECTION (","")),I.map(E2I).map(t=>t instanceof Array?t:[t]).reduce((t,o)=>[...t,...o],[])}else{if(n2I(g))return Oto(g);if(s2I(g))return Wto(g)}}return[]}function n2I(g){return g.split(`
5422
5422
  `)?.every(A=>A.includes("POINT"))}function s2I(g){return g.split(`
5423
- `)?.every(A=>A.includes("LINESTRING"))}function Vto(g){return g.startsWith("POINT")||n2I(g)||g.startsWith("LINESTRING")||s2I(g)||g.startsWith("MULTILINESTRING")||g.startsWith("POLYGON")||g.startsWith("MULTIPOINT")||g.startsWith("MULTIPOLYGON")||g.startsWith("GEOMETRYCOLLECTION")}jA.isWktString=Vto,jA.parseWKT=E2I,jA.BooleanOperations=Ato,jA.Relations=rto;function a2I(g,A,I){if(!A||!I)return;let e=g.get(A);e||(e=new Set,g.set(A,e)),e.add(I);let t=g.get(I);t||(t=new Set,g.set(I,t)),t.add(A)}function r2I(g,A){if(!A.subcircuit_id&&!A.source_group_id)return[...g];let I=A;if(A.subcircuit_id){const C=new Set([A.subcircuit_id]),Q=new Map,i=new Map;for(const n of g)if(n.type==="source_group"){const s=n.source_group_id,r=n.subcircuit_id;r&&i.set(s,r);const a=n.parent_source_group_id;a&&(Q.has(a)||Q.set(a,[]),Q.get(a).push(s))}let E;for(const[n,s]of i)if(s===A.subcircuit_id){E=n;break}if(E){const n=s=>{const r=Q.get(s)||[];for(const a of r){const c=i.get(a);c&&C.add(c),n(a)}};n(E),I={...A,subcircuit_ids:Array.from(C)}}}const e=new Map;for(const C of g){const Q=`${C.type}_id`,i=C[Q];typeof i=="string"&&e.set(i,C)}const t=new Map;for(const C of g){const Q=Object.entries(C);for(const[i,E]of Q)if(i!=="parent_source_group_id"){if(i.endsWith("_id")&&typeof E=="string"){const n=e.get(E);a2I(t,C,n)}else if(i.endsWith("_ids")&&Array.isArray(E)){for(const n of E)if(typeof n=="string"){const s=e.get(n);a2I(t,C,s)}}}}const o=[],B=new Set;for(const C of g){let Q=!1;(I.subcircuit_id&&"subcircuit_id"in C&&C.subcircuit_id===I.subcircuit_id||I.subcircuit_ids&&"subcircuit_id"in C&&C.subcircuit_id&&I.subcircuit_ids.includes(C.subcircuit_id)||I.source_group_id&&"source_group_id"in C&&C.source_group_id===I.source_group_id||I.source_group_id&&"member_source_group_ids"in C&&Array.isArray(C.member_source_group_ids)&&C.member_source_group_ids.includes(I.source_group_id))&&(Q=!0),Q&&(o.push(C),B.add(C))}for(;o.length>0;){const C=o.shift(),Q=t.get(C);if(Q)for(const i of Q)B.has(i)||(B.add(i),o.push(i))}return g.filter(C=>B.has(C))}var HwA=(g,A={})=>{const I=g;let e=I._internal_store;if(!e){e={counts:{},editCount:0},I._internal_store=e;for(const o of I){const B=o.type,C=o[`${B}_id`];if(!C)continue;const Q=Number.parseInt(C.split("_").pop());Number.isNaN(Q)||(e.counts[B]=Math.max(e.counts[B]??0,Q))}}const t=new Proxy({},{get:(o,B)=>{if(B==="toArray")return()=>(I.editCount=e.editCount,I);if(B==="editCount")return e.editCount;if(B==="subtree")return Q=>HwA(r2I(I,Q),A);if(B==="insert")return Q=>{const i=Q.type;if(!i)throw new Error("insert requires an element with a type");e.counts[i]??=-1,e.counts[i]++;const E=e.counts[i],n={...Q,type:i,[`${i}_id`]:`${i}_${E}`};return A.validateInserts&&(wN[i]??mf).parse(n),I.push(n),e.editCount++,n};if(B==="insertAll")return Q=>Q.map(i=>t.insert(i));const C=B;return{get:Q=>I.find(i=>i.type===C&&i[`${C}_id`]===Q),getUsing:Q=>{const i=Object.keys(Q);if(i.length!==1)throw new Error("getUsing requires exactly one key, e.g. { pcb_component_id }");const E=i[0],n=E.replace("_id",""),s=I.find(r=>r.type===n&&r[E]===Q[E]);return s?I.find(r=>r.type===C&&r[`${C}_id`]===s[`${C}_id`]):null},getWhere:Q=>{const i=Object.keys(Q);return I.find(E=>E.type===C&&i.every(n=>E[n]===Q[n]))},list:Q=>{const i=Q?Object.keys(Q):[];return I.filter(E=>E.type===C&&i.every(n=>E[n]===Q[n]))},insert:Q=>{e.counts[C]??=-1,e.counts[C]++;const i=e.counts[C],E={type:C,[`${C}_id`]:`${C}_${i}`,...Q};return A.validateInserts&&(wN[C]??mf).parse(E),I.push(E),e.editCount++,E},delete:Q=>{const i=I.find(E=>E[`${C}_id`]===Q);i&&(I.splice(I.indexOf(i),1),e.editCount++)},update:(Q,i)=>{const E=I.find(n=>n.type===C&&n[`${C}_id`]===Q);return E?(Object.assign(E,i),e.editCount++,E):null},select:Q=>{if(C==="source_component")return I.find(i=>i.type==="source_component"&&i.name===Q.replace(/\./g,""));if(C==="pcb_port"||C==="source_port"||C==="schematic_port"){const[i,E]=Q.replace(/\./g,"").split(/[\s\>]+/),n=I.find(r=>r.type==="source_component"&&r.name===i);if(!n)return null;const s=I.find(r=>r.type==="source_port"&&r.source_component_id===n.source_component_id&&(r.name===E||(r.port_hints??[]).includes(E)));if(!s)return null;if(C==="source_port")return s;if(C==="pcb_port")return I.find(r=>r.type==="pcb_port"&&r.source_port_id===s.source_port_id);if(C==="schematic_port")return I.find(r=>r.type==="schematic_port"&&r.source_port_id===s.source_port_id)}}}}});return t};HwA.unparsed=HwA;var Y5=HwA;function Beg(g){const A=g.type;return`${A}:${g[`${A}_id`]}`}var Ceg=(g,A={})=>{let I=g._internal_store_indexed;if(!I){I={counts:{},editCount:0,indexes:{}};for(const B of g){const C=B.type,Q=B[`${C}_id`];if(!Q)continue;const i=Number.parseInt(Q.split("_").pop()||"");Number.isNaN(i)||(I.counts[C]=Math.max(I.counts[C]??0,i))}const t=A.indexConfig||{},o=I.indexes;if(t.byId&&(o.byId=new Map),t.byType&&(o.byType=new Map),t.byRelation&&(o.byRelation=new Map),t.bySubcircuit&&(o.bySubcircuit=new Map),t.byCustomField&&t.byCustomField.length>0){o.byCustomField=new Map;for(const B of t.byCustomField)o.byCustomField.set(B,new Map)}for(const B of g){if(t.byId){const C=Beg(B);o.byId.set(C,B)}if(t.byType){const C=o.byType.get(B.type)||[];C.push(B),o.byType.set(B.type,C)}if(t.byRelation){const C=Object.entries(B);for(const[Q,i]of C)if(Q.endsWith("_id")&&Q!==`${B.type}_id`&&typeof i=="string"){const E=o.byRelation.get(Q)||new Map,n=E.get(i)||[];n.push(B),E.set(i,n),o.byRelation.set(Q,E)}}if(t.bySubcircuit&&"subcircuit_id"in B){const C=B.subcircuit_id;if(C&&typeof C=="string"){const Q=o.bySubcircuit.get(C)||[];Q.push(B),o.bySubcircuit.set(C,Q)}}if(t.byCustomField&&o.byCustomField){for(const C of t.byCustomField)if(C in B){const Q=B[C];if(Q!==void 0&&(typeof Q=="string"||typeof Q=="number")){const i=String(Q),E=o.byCustomField.get(C),n=E.get(i)||[];n.push(B),E.set(i,n)}}}}g._internal_store_indexed=I}const e=new Proxy({},{get:(t,o)=>{if(o==="toArray")return()=>(g.editCount=I.editCount,g);if(o==="editCount")return I.editCount;if(o==="insert")return C=>{const{type:Q,...i}=C;if(!Q)throw new Error("insert requires an element with a type");return delete i[`${Q}_id`],e[Q].insert(i)};if(o==="insertAll")return C=>C.map(Q=>e.insert(Q));if(o==="subtree")return C=>Ceg(r2I(g,C),A);const B=o;return{get:C=>{const Q=A.indexConfig||{};return Q.byId&&I.indexes.byId?I.indexes.byId.get(`${B}:${C}`)||null:Q.byType&&I.indexes.byType?(I.indexes.byType.get(B)||[]).find(E=>E[`${B}_id`]===C)||null:g.find(i=>i.type===B&&i[`${B}_id`]===C)||null},getUsing:C=>{const Q=A.indexConfig||{},i=Object.keys(C);if(i.length!==1)throw new Error("getUsing requires exactly one key, e.g. { pcb_component_id }");const E=i[0],n=E.replace("_id","");if(Q.byRelation&&I.indexes.byRelation){const r=I.indexes.byRelation.get(E);if(r){const c=(r.get(C[E])||[]).find(l=>l.type===n);if(!c)return null;const h=c[`${B}_id`];return Q.byId&&I.indexes.byId?I.indexes.byId.get(`${B}:${h}`)||null:Q.byType&&I.indexes.byType?(I.indexes.byType.get(B)||[]).find(D=>D[`${B}_id`]===h)||null:g.find(l=>l.type===B&&l[`${B}_id`]===h)||null}}const s=g.find(r=>r.type===n&&r[E]===C[E]);return s&&g.find(r=>r.type===B&&r[`${B}_id`]===s[`${B}_id`])||null},getWhere:C=>{const Q=A.indexConfig||{},i=Object.keys(C);if(i.length===1&&Q.byCustomField&&I.indexes.byCustomField){const E=i[0],n=I.indexes.byCustomField.get(E);if(n){const s=String(C[E]);return(n.get(s)||[]).find(a=>a.type===B)||null}}if("subcircuit_id"in C&&Q.bySubcircuit&&I.indexes.bySubcircuit){const E=C.subcircuit_id;return(I.indexes.bySubcircuit.get(E)||[]).find(s=>s.type===B&&i.every(r=>s[r]===C[r]))||null}return Q.byType&&I.indexes.byType?(I.indexes.byType.get(B)||[]).find(n=>i.every(s=>n[s]===C[s]))||null:g.find(E=>E.type===B&&i.every(n=>E[n]===C[n]))||null},list:C=>{const Q=A.indexConfig||{},i=C?Object.keys(C):[];if(i.length===0&&Q.byType&&I.indexes.byType)return(I.indexes.byType.get(B)||[]).slice();if(i.length===1&&i[0]==="subcircuit_id"&&Q.bySubcircuit&&I.indexes.bySubcircuit){const n=C.subcircuit_id;return(I.indexes.bySubcircuit.get(n)||[]).filter(r=>r.type===B)}let E;return Q.byType&&I.indexes.byType?E=I.indexes.byType.get(B)||[]:E=g.filter(n=>n.type===B),i.length>0?E.filter(n=>i.every(s=>n[s]===C[s])):E.slice()},insert:C=>{I.counts[B]??=-1,I.counts[B]++;const Q=I.counts[B],i={type:B,[`${B}_id`]:`${B}_${Q}`,...C};A.validateInserts&&(wN[B]??mf).parse(i),g.push(i),I.editCount++;const E=A.indexConfig||{};if(E.byId&&I.indexes.byId){const n=Beg(i);I.indexes.byId.set(n,i)}if(E.byType&&I.indexes.byType){const n=I.indexes.byType.get(B)||[];n.push(i),I.indexes.byType.set(B,n)}if(E.byRelation&&I.indexes.byRelation){const n=Object.entries(i);for(const[s,r]of n)if(s.endsWith("_id")&&s!==`${i.type}_id`&&typeof r=="string"){const a=I.indexes.byRelation.get(s)||new Map,c=a.get(r)||[];c.push(i),a.set(r,c),I.indexes.byRelation.set(s,a)}}if(E.bySubcircuit&&I.indexes.bySubcircuit&&"subcircuit_id"in i){const n=i.subcircuit_id;if(n&&typeof n=="string"){const s=I.indexes.bySubcircuit.get(n)||[];s.push(i),I.indexes.bySubcircuit.set(n,s)}}if(E.byCustomField&&I.indexes.byCustomField){for(const n of E.byCustomField)if(n in i){const s=i[n];if(s!==void 0&&(typeof s=="string"||typeof s=="number")){const r=String(s),a=I.indexes.byCustomField.get(n),c=a.get(r)||[];c.push(i),a.set(r,c)}}}return i},delete:C=>{const Q=A.indexConfig||{};let i;if(Q.byId&&I.indexes.byId?i=I.indexes.byId.get(`${B}:${C}`):Q.byType&&I.indexes.byType?i=(I.indexes.byType.get(B)||[]).find(s=>s[`${B}_id`]===C):i=g.find(n=>n[`${B}_id`]===C),!i)return;const E=g.indexOf(i);if(E>=0&&(g.splice(E,1),I.editCount++),Q.byId&&I.indexes.byId){const n=Beg(i);I.indexes.byId.delete(n)}if(Q.byType&&I.indexes.byType){const s=(I.indexes.byType.get(B)||[]).filter(r=>r[`${B}_id`]!==C);I.indexes.byType.set(B,s)}if(Q.byRelation&&I.indexes.byRelation)for(const[n,s]of I.indexes.byRelation.entries())for(const[r,a]of s.entries()){const c=a.filter(h=>h!==i);c.length===0?s.delete(r):s.set(r,c)}if(Q.bySubcircuit&&I.indexes.bySubcircuit&&"subcircuit_id"in i){const n=i.subcircuit_id;if(n){const r=(I.indexes.bySubcircuit.get(n)||[]).filter(a=>a!==i);r.length===0?I.indexes.bySubcircuit.delete(n):I.indexes.bySubcircuit.set(n,r)}}if(Q.byCustomField&&I.indexes.byCustomField)for(const n of I.indexes.byCustomField.values())for(const[s,r]of n.entries()){const a=r.filter(c=>c!==i);a.length===0?n.delete(s):n.set(s,a)}},update:(C,Q)=>{const i=A.indexConfig||{};let E;if(i.byId&&I.indexes.byId?E=I.indexes.byId.get(`${B}:${C}`):i.byType&&I.indexes.byType?E=(I.indexes.byType.get(B)||[]).find(s=>s[`${B}_id`]===C):E=g.find(n=>n.type===B&&n[`${B}_id`]===C),!E)return null;if(i.byRelation&&I.indexes.byRelation){const n=Object.entries(E);for(const[s,r]of n)if(s.endsWith("_id")&&s!==`${E.type}_id`&&typeof r=="string"&&s in Q&&Q[s]!==r){const a=I.indexes.byRelation.get(s);if(a){const h=(a.get(r)||[]).filter(l=>l!==E);h.length===0?a.delete(r):a.set(r,h)}}}if(i.bySubcircuit&&I.indexes.bySubcircuit&&"subcircuit_id"in E&&"subcircuit_id"in Q){const n=E.subcircuit_id,s=Q.subcircuit_id;if(n!==s){const a=(I.indexes.bySubcircuit.get(n)||[]).filter(c=>c!==E);a.length===0?I.indexes.bySubcircuit.delete(n):I.indexes.bySubcircuit.set(n,a)}}if(i.byCustomField&&I.indexes.byCustomField){for(const n of i.byCustomField)if(n in E&&n in Q&&E[n]!==Q[n]){const s=I.indexes.byCustomField.get(n);if(s){const r=String(E[n]),c=(s.get(r)||[]).filter(h=>h!==E);c.length===0?s.delete(r):s.set(r,c)}}}if(Object.assign(E,Q),I.editCount++,i.byRelation&&I.indexes.byRelation){const n=Object.entries(E);for(const[s,r]of n)if(s.endsWith("_id")&&s!==`${E.type}_id`&&typeof r=="string"&&s in Q){const a=I.indexes.byRelation.get(s)||new Map,c=a.get(r)||[];c.includes(E)||(c.push(E),a.set(r,c),I.indexes.byRelation.set(s,a))}}if(i.bySubcircuit&&I.indexes.bySubcircuit&&"subcircuit_id"in E&&"subcircuit_id"in Q){const n=E.subcircuit_id;if(n&&typeof n=="string"){const s=I.indexes.bySubcircuit.get(n)||[];s.includes(E)||(s.push(E),I.indexes.bySubcircuit.set(n,s))}}if(i.byCustomField&&I.indexes.byCustomField){for(const n of i.byCustomField)if(n in E&&n in Q){const s=E[n];if(s!==void 0&&(typeof s=="string"||typeof s=="number")){const r=String(s),a=I.indexes.byCustomField.get(n),c=a.get(r)||[];c.includes(E)||(c.push(E),a.set(r,c))}}}return E},select:C=>{if(B==="source_component")return g.find(Q=>Q.type==="source_component"&&Q.name===C.replace(/\./g,""))||null;if(B==="pcb_port"||B==="source_port"||B==="schematic_port"){const[Q,i]=C.replace(/\./g,"").split(/[\s\>]+/),E=g.find(s=>s.type==="source_component"&&s.name===Q);if(!E)return null;const n=g.find(s=>s.type==="source_port"&&s.source_component_id===E.source_component_id&&(s.name===i||(s.port_hints??[]).includes(i)));if(!n)return null;if(B==="source_port")return n;if(B==="pcb_port")return g.find(s=>s.type==="pcb_port"&&s.source_port_id===n.source_port_id)||null;if(B==="schematic_port")return g.find(s=>s.type==="schematic_port"&&s.source_port_id===n.source_port_id)||null}return null}}}});return e};Ceg.unparsed=Ceg;var jto=g=>Math.round(g/(Math.PI/2)),zto=g=>{switch(g){case"from_left":return{x:-1,y:0};case"from_right":return{x:1,y:0};case"from_top":return{x:0,y:1};case"from_bottom":return{x:0,y:-1}}},Xto=({x:g,y:A})=>g>0?"from_right":g<0?"from_left":A>0?"from_top":"from_bottom",$to=(g,A)=>{if(!g)return g;if(g==="from_above"||g==="from_below")return A.isFlipped?g==="from_above"?"from_below":"from_above":g;let{x:I,y:e}=zto(g),t=Math.round(A.rotationDegrees/90);for(;t>0;)[I,e]=[-e,I],t--;for(;t<0;)[I,e]=[e,-I],t++;return A.isFlipped&&(e=-e),Xto({x:I,y:e})},Aoo=(g,A)=>{if(g.shape==="polygon")return g.points=g.points.map(B=>Mt(A,B)),g;const I=Mt(A,{x:g.x,y:g.y});if(g.x=I.x,g.y=I.y,g.shape==="circle")return g;const e=g.shape==="rotated_rect"?g.ccw_rotation:0,t=A.a*A.d-A.b*A.c<0,o=PMI(bw(A,zgo(e)),!1,t).rotation.angle*180/Math.PI;return Math.abs(o)<1e-8?(Object.assign(g,{shape:"rect"}),Reflect.deleteProperty(g,"ccw_rotation")):Object.assign(g,{shape:"rotated_rect",ccw_rotation:o}),g},goo=(g,A)=>{if(g.type==="pcb_soldermask_opening")return Aoo(g,A);if((g.type==="pcb_smtpad"||g.type==="pcb_solder_paste")&&g.shape==="polygon")return g.points=g.points.map(B=>Mt(A,B)),g.type==="pcb_solder_paste"&&g.holes&&(g.holes=g.holes.map(B=>B.map(C=>Mt(A,C)))),g;const I=PMI(A),e=Math.abs(jto(I.rotation.angle))%2===1,t=I.rotation.angle/Math.PI*180,o=I.scale.sy<0;if(g.type==="pcb_plated_hole"||g.type==="pcb_hole"||g.type==="pcb_via"||g.type==="pcb_smtpad"||g.type==="pcb_solder_paste"||g.type==="pcb_port"){const{x:B,y:C}=Mt(A,{x:g.x,y:g.y});g.x=B,g.y=C}else if(g.type==="pcb_keepout"&&g.shape==="outline")g.outline=g.outline.map(B=>Mt(A,B));else if(g.type==="pcb_keepout"||g.type==="pcb_board")g.center=Mt(A,g.center);else if(g.type==="pcb_silkscreen_text"||g.type==="pcb_fabrication_note_text"||g.type==="pcb_note_text")g.anchor_position=Mt(A,g.anchor_position);else if(g.type==="pcb_copper_text")g.anchor_position&&(g.anchor_position=Mt(A,g.anchor_position));else if(g.type==="pcb_courtyard_rect")g.center=Mt(A,g.center),g.ccw_rotation=((g.ccw_rotation??0)+t)%360;else if(g.type==="pcb_silkscreen_circle"||g.type==="pcb_silkscreen_rect"||g.type==="pcb_silkscreen_pill"||g.type==="pcb_silkscreen_oval"||g.type==="pcb_note_rect"||g.type==="pcb_courtyard_circle")g.center=Mt(A,g.center);else if(g.type==="pcb_component")g.center=Mt(A,g.center),g.rotation=g.rotation+t,g.rotation=g.rotation%360,g.cable_insertion_center&&(g.cable_insertion_center=Mt(A,g.cable_insertion_center)),g.insertion_direction=$to(g.insertion_direction,{rotationDegrees:t,isFlipped:o}),e&&([g.width,g.height]=[g.height,g.width]);else if(g.type==="pcb_courtyard_outline")g.outline=g.outline.map(B=>{const C=Mt(A,B);return B.x=C.x,B.y=C.y,B});else if(g.type==="pcb_courtyard_polygon")g.points=g.points.map(B=>{const C=Mt(A,B);return B.x=C.x,B.y=C.y,B});else if(g.type==="pcb_trace")g.route=g.route.map(B=>{if(!("x"in B))return B.start=Mt(A,B.start),B.end=Mt(A,B.end),B;const C=Mt(A,B);return B.x=C.x,B.y=C.y,B});else if(g.type==="pcb_silkscreen_path"||g.type==="pcb_trace_hint"||g.type==="pcb_fabrication_note_path"||g.type==="pcb_note_path")g.route=g.route.map(B=>{const C=Mt(A,B);return B.x=C.x,B.y=C.y,B});else if(g.type==="pcb_silkscreen_line"||g.type==="pcb_note_line"){const B={x:g.x1,y:g.y1},C={x:g.x2,y:g.y2},Q=Mt(A,B),i=Mt(A,C);g.x1=Q.x,g.y1=Q.y,g.x2=i.x,g.y2=i.y}else if(g.type==="cad_component"){const B=Mt(A,{x:g.position.x,y:g.position.y});g.position.x=B.x,g.position.y=B.y}return g},Ioo=g=>{const A=g.type;return g[`${A}_id`]},Qeg=(g,A)=>({minX:Math.min(g.minX,A.minX),minY:Math.min(g.minY,A.minY),maxX:Math.max(g.maxX,A.maxX),maxY:Math.max(g.maxY,A.maxY)}),CeA=(g,A,I)=>{const e=I/2;return{minX:g-e,minY:A-e,maxX:g+e,maxY:A+e}},c2I=(g,A,I,e,t)=>{const o=I/2,B=e/2,C=t*Math.PI/180,Q=Math.cos(C),i=Math.sin(C),E=[{x:-o,y:-B},{x:o,y:-B},{x:o,y:B},{x:-o,y:B}].map(n=>({x:g+n.x*Q-n.y*i,y:A+n.x*i+n.y*Q}));return{minX:Math.min(...E.map(n=>n.x)),minY:Math.min(...E.map(n=>n.y)),maxX:Math.max(...E.map(n=>n.x)),maxY:Math.max(...E.map(n=>n.y))}},eoo=(g,A,I,e,t)=>{const o=I/2,B=e/2,C=t*Math.PI/180,Q=Math.cos(C),i=Math.sin(C),E=Math.hypot(o*Q,B*i),n=Math.hypot(o*i,B*Q);return{minX:g-E,minY:A-n,maxX:g+E,maxY:A+n}},too=(g,A,I,e,t)=>{const o=Math.min(I,e)/2,B=Math.max(I,e)/2-o,C=t*Math.PI/180,Q=I>=e?{x:B,y:0}:{x:0,y:B},i={x:Q.x*Math.cos(C)-Q.y*Math.sin(C),y:Q.x*Math.sin(C)+Q.y*Math.cos(C)},E=Math.abs(i.x)+o,n=Math.abs(i.y)+o;return{minX:g-E,minY:A-n,maxX:g+E,maxY:A+n}},vwA=g=>g.length===0?null:{minX:Math.min(...g.map(A=>A.x)),minY:Math.min(...g.map(A=>A.y)),maxX:Math.max(...g.map(A=>A.x)),maxY:Math.max(...g.map(A=>A.y))},ieg=g=>Array.isArray(g)?g.flatMap(A=>!A||typeof A!="object"?[]:"x"in A&&"y"in A&&typeof A.x=="number"&&typeof A.y=="number"?[{x:A.x,y:A.y}]:"start"in A&&"end"in A?[A.start,A.end].filter(e=>!!(e&&typeof e=="object"&&"x"in e&&"y"in e&&typeof e.x=="number"&&typeof e.y=="number")):[]):[],h2I=g=>{if(!g.type.startsWith("pcb_"))return null;if(g.type==="pcb_smtpad"&&g.shape==="polygon"&&Array.isArray(g.points))return vwA(g.points);if(g.type==="pcb_hole"&&g.hole_shape==="circle")return CeA(g.x,g.y,g.hole_diameter);if(g.type==="pcb_plated_hole"){let n;if("outer_diameter"in g&&typeof g.outer_diameter=="number"?n=CeA(g.x,g.y,g.outer_diameter):"hole_diameter"in g&&typeof g.hole_diameter=="number"&&(n=CeA(g.x,g.y,g.hole_diameter)),(g.shape==="oval"||g.shape==="pill")&&typeof g.outer_width=="number"&&typeof g.outer_height=="number"&&(n=(g.shape==="pill"?too:eoo)(g.x,g.y,g.outer_width,g.outer_height,g.ccw_rotation??0)),"rect_pad_width"in g&&typeof g.rect_pad_width=="number"&&"rect_pad_height"in g&&typeof g.rect_pad_height=="number"){const s=c2I(g.x,g.y,g.rect_pad_width,g.rect_pad_height,"rect_ccw_rotation"in g?g.rect_ccw_rotation??0:0);n=n?Qeg(n,s):s}if("hole_diameter"in g&&typeof g.hole_diameter=="number"){const s=CeA(g.x+("hole_offset_x"in g?g.hole_offset_x??0:0),g.y+("hole_offset_y"in g?g.hole_offset_y??0:0),g.hole_diameter);n=n?Qeg(n,s):s}if(n)return n}const A=g,I=vwA(ieg(A.route));if(I)return I;const e=vwA(ieg(A.outline));if(e)return e;const t=vwA(ieg(A.points));if(t)return t;let o,B,C,Q;"x"in g&&"y"in g&&(o=Number(g.x),B=Number(g.y)),"outer_diameter"in g&&(C=Number(g.outer_diameter),Q=Number(g.outer_diameter)),"width"in g&&(C=Number(g.width)),"height"in g&&(Q=Number(g.height)),"center"in g&&g.center&&typeof g.center=="object"&&"x"in g.center&&"y"in g.center&&(o=Number(g.center.x),B=Number(g.center.y));let i=0;if("rotation"in g&&typeof g.rotation=="number"&&(i=g.rotation),"ccw_rotation"in g&&typeof g.ccw_rotation=="number"&&(i=g.ccw_rotation),o!==void 0&&B!==void 0)return C!==void 0&&Q!==void 0?i?c2I(o,B,C,Q,i):{minX:o-C/2,minY:B-Q/2,maxX:o+C/2,maxY:B+Q/2}:"radius"in g&&typeof g.radius=="number"?CeA(o,B,g.radius*2):{minX:o,minY:B,maxX:o,maxY:B};const E=[A.anchor_position,A.position].filter(n=>!!(n&&typeof n=="object"&&"x"in n&&"y"in n&&typeof n.x=="number"&&typeof n.y=="number")).at(0);return E?{minX:E.x,minY:E.y,maxX:E.x,maxY:E.y}:null},Eeg=g=>{let A={minX:Number.POSITIVE_INFINITY,minY:Number.POSITIVE_INFINITY,maxX:Number.NEGATIVE_INFINITY,maxY:Number.NEGATIVE_INFINITY};for(const I of g){const e=h2I(I);e&&(A=Qeg(A,e))}return A};function ooo(g){let A=0;if(g.length==0)return A;for(var I=0;I<g.length;I++){var e=g.charCodeAt(I);A=(A<<5)-A+e,A=A&A}return Math.abs(A)}var l2I=[["#69d2e7","#a7dbd8","#e0e4cc","#f38630","#fa6900"],["#fe4365","#fc9d9a","#f9cdad","#c8c8a9","#83af9b"],["#ecd078","#d95b43","#c02942","#542437","#53777a"],["#556270","#4ecdc4","#c7f464","#ff6b6b","#c44d58"],["#774f38","#e08e79","#f1d4af","#ece5ce","#c5e0dc"],["#e8ddcb","#cdb380","#036564","#033649","#031634"],["#490a3d","#bd1550","#e97f02","#f8ca00","#8a9b0f"],["#594f4f","#547980","#45ada8","#9de0ad","#e5fcc2"],["#00a0b0","#6a4a3c","#cc333f","#eb6841","#edc951"],["#e94e77","#d68189","#c6a49a","#c6e5d9","#f4ead5"],["#3fb8af","#7fc7af","#dad8a7","#ff9e9d","#ff3d7f"],["#d9ceb2","#948c75","#d5ded9","#7a6a53","#99b2b7"],["#ffffff","#cbe86b","#f2e9e1","#1c140d","#cbe86b"],["#efffcd","#dce9be","#555152","#2e2633","#99173c"],["#343838","#005f6b","#008c9e","#00b4cc","#00dffc"],["#413e4a","#73626e","#b38184","#f0b49e","#f7e4be"],["#ff4e50","#fc913a","#f9d423","#ede574","#e1f5c4"],["#99b898","#fecea8","#ff847c","#e84a5f","#2a363b"],["#655643","#80bca3","#f6f7bd","#e6ac27","#bf4d28"],["#00a8c6","#40c0cb","#f9f2e7","#aee239","#8fbe00"],["#351330","#424254","#64908a","#e8caa4","#cc2a41"],["#554236","#f77825","#d3ce3d","#f1efa5","#60b99a"],["#5d4157","#838689","#a8caba","#cad7b2","#ebe3aa"],["#8c2318","#5e8c6a","#88a65e","#bfb35a","#f2c45a"],["#fad089","#ff9c5b","#f5634a","#ed303c","#3b8183"],["#ff4242","#f4fad2","#d4ee5e","#e1edb9","#f0f2eb"],["#f8b195","#f67280","#c06c84","#6c5b7b","#355c7d"],["#d1e751","#ffffff","#000000","#4dbce9","#26ade4"],["#1b676b","#519548","#88c425","#bef202","#eafde6"],["#5e412f","#fcebb6","#78c0a8","#f07818","#f0a830"],["#bcbdac","#cfbe27","#f27435","#f02475","#3b2d38"],["#452632","#91204d","#e4844a","#e8bf56","#e2f7ce"],["#eee6ab","#c5bc8e","#696758","#45484b","#36393b"],["#f0d8a8","#3d1c00","#86b8b1","#f2d694","#fa2a00"],["#2a044a","#0b2e59","#0d6759","#7ab317","#a0c55f"],["#f04155","#ff823a","#f2f26f","#fff7bd","#95cfb7"],["#b9d7d9","#668284","#2a2829","#493736","#7b3b3b"],["#bbbb88","#ccc68d","#eedd99","#eec290","#eeaa88"],["#b3cc57","#ecf081","#ffbe40","#ef746f","#ab3e5b"],["#a3a948","#edb92e","#f85931","#ce1836","#009989"],["#300030","#480048","#601848","#c04848","#f07241"],["#67917a","#170409","#b8af03","#ccbf82","#e33258"],["#aab3ab","#c4cbb7","#ebefc9","#eee0b7","#e8caaf"],["#e8d5b7","#0e2430","#fc3a51","#f5b349","#e8d5b9"],["#ab526b","#bca297","#c5ceae","#f0e2a4","#f4ebc3"],["#607848","#789048","#c0d860","#f0f0d8","#604848"],["#b6d8c0","#c8d9bf","#dadabd","#ecdbbc","#fedcba"],["#a8e6ce","#dcedc2","#ffd3b5","#ffaaa6","#ff8c94"],["#3e4147","#fffedf","#dfba69","#5a2e2e","#2a2c31"],["#fc354c","#29221f","#13747d","#0abfbc","#fcf7c5"],["#cc0c39","#e6781e","#c8cf02","#f8fcc1","#1693a7"],["#1c2130","#028f76","#b3e099","#ffeaad","#d14334"],["#a7c5bd","#e5ddcb","#eb7b59","#cf4647","#524656"],["#dad6ca","#1bb0ce","#4f8699","#6a5e72","#563444"],["#5c323e","#a82743","#e15e32","#c0d23e","#e5f04c"],["#edebe6","#d6e1c7","#94c7b6","#403b33","#d3643b"],["#fdf1cc","#c6d6b8","#987f69","#e3ad40","#fcd036"],["#230f2b","#f21d41","#ebebbc","#bce3c5","#82b3ae"],["#b9d3b0","#81bda4","#b28774","#f88f79","#f6aa93"],["#3a111c","#574951","#83988e","#bcdea5","#e6f9bc"],["#5e3929","#cd8c52","#b7d1a3","#dee8be","#fcf7d3"],["#1c0113","#6b0103","#a30006","#c21a01","#f03c02"],["#000000","#9f111b","#b11623","#292c37","#cccccc"],["#382f32","#ffeaf2","#fcd9e5","#fbc5d8","#f1396d"],["#e3dfba","#c8d6bf","#93ccc6","#6cbdb5","#1a1f1e"],["#f6f6f6","#e8e8e8","#333333","#990100","#b90504"],["#1b325f","#9cc4e4","#e9f2f9","#3a89c9","#f26c4f"],["#a1dbb2","#fee5ad","#faca66","#f7a541","#f45d4c"],["#c1b398","#605951","#fbeec2","#61a6ab","#accec0"],["#5e9fa3","#dcd1b4","#fab87f","#f87e7b","#b05574"],["#951f2b","#f5f4d7","#e0dfb1","#a5a36c","#535233"],["#8dccad","#988864","#fea6a2","#f9d6ac","#ffe9af"],["#2d2d29","#215a6d","#3ca2a2","#92c7a3","#dfece6"],["#413d3d","#040004","#c8ff00","#fa023c","#4b000f"],["#eff3cd","#b2d5ba","#61ada0","#248f8d","#605063"],["#ffefd3","#fffee4","#d0ecea","#9fd6d2","#8b7a5e"],["#cfffdd","#b4dec1","#5c5863","#a85163","#ff1f4c"],["#9dc9ac","#fffec7","#f56218","#ff9d2e","#919167"],["#4e395d","#827085","#8ebe94","#ccfc8e","#dc5b3e"],["#a8a7a7","#cc527a","#e8175d","#474747","#363636"],["#f8edd1","#d88a8a","#474843","#9d9d93","#c5cfc6"],["#046d8b","#309292","#2fb8ac","#93a42a","#ecbe13"],["#f38a8a","#55443d","#a0cab5","#cde9ca","#f1edd0"],["#a70267","#f10c49","#fb6b41","#f6d86b","#339194"],["#ff003c","#ff8a00","#fabe28","#88c100","#00c176"],["#ffedbf","#f7803c","#f54828","#2e0d23","#f8e4c1"],["#4e4d4a","#353432","#94ba65","#2790b0","#2b4e72"],["#0ca5b0","#4e3f30","#fefeeb","#f8f4e4","#a5b3aa"],["#4d3b3b","#de6262","#ffb88c","#ffd0b3","#f5e0d3"],["#fffbb7","#a6f6af","#66b6ab","#5b7c8d","#4f2958"],["#edf6ee","#d1c089","#b3204d","#412e28","#151101"],["#9d7e79","#ccac95","#9a947c","#748b83","#5b756c"],["#fcfef5","#e9ffe1","#cdcfb7","#d6e6c3","#fafbe3"],["#9cddc8","#bfd8ad","#ddd9ab","#f7af63","#633d2e"],["#30261c","#403831","#36544f","#1f5f61","#0b8185"],["#aaff00","#ffaa00","#ff00aa","#aa00ff","#00aaff"],["#d1313d","#e5625c","#f9bf76","#8eb2c5","#615375"],["#ffe181","#eee9e5","#fad3b2","#ffba7f","#ff9c97"],["#73c8a9","#dee1b6","#e1b866","#bd5532","#373b44"],["#805841","#dcf7f3","#fffcdd","#ffd8d8","#f5a2a2"]],Boo=g=>{let{x:A,y:I,width:e,height:t}={...g,...g.size,...g.center,...g.position};if(g.x1!==void 0&&g.x2!==void 0&&g.y1!==void 0&&g.y2!==void 0&&(A=(g.x1+g.x2)/2,I=(g.y1+g.y2)/2,e=Math.abs(g.x1-g.x2),t=Math.abs(g.y1-g.y2)),g.points&&Array.isArray(g.points)&&g.points.length>0){const C=g.points.map(r=>r.x),Q=g.points.map(r=>r.y),i=Math.min(...C),E=Math.max(...C),n=Math.min(...Q),s=Math.max(...Q);A=(i+E)/2,I=(n+s)/2,e=E-i,t=s-n}const o=g.text||g.name||g.source?.text||g.source?.name||"?",B=g;return A===void 0||I===void 0?null:(e===void 0&&("radius"in g?(e=g.radius*2,t=g.radius*2):"outer_diameter"in g?(e=g.outer_diameter,t=g.outer_diameter):"rect_pad_width"in g&&"rect_pad_height"in g?(e=g.rect_pad_width,t=g.rect_pad_height,"hole_diameter"in g&&(e=Math.max(e,g.hole_diameter),t=Math.max(t,g.hole_diameter))):"hole_diameter"in g&&(e=g.hole_diameter,t=g.hole_diameter)),(e===void 0||t===void 0)&&(e=.1,t=.1),{x:A,y:I,width:e,height:t,title:o,content:B,bg_color:l2I[ooo(g.type||o)%l2I.length]?.[4]??"#f00"})},Coo=g=>!!g,Qoo=g=>{const A=g.filter(i=>i.type.startsWith("pcb_")||i.type.startsWith("schematic_")).concat(g.filter(i=>i.type==="pcb_trace"||i.type==="schematic_trace").flatMap(i=>i.route)).map(i=>Boo(i)).filter(Coo);if(A.length===0)return{center:{x:0,y:0},width:0,height:0};let I=A[0].x-A[0].width/2,e=A[0].x+A[0].width/2,t=A[0].y-A[0].height/2,o=A[0].y+A[0].height/2;for(const i of A.slice(1))I=Math.min(I,i.x-i.width/2),e=Math.max(e,i.x+i.width/2),t=Math.min(t,i.y-i.height/2),o=Math.max(o,i.y+i.height/2);const B=e-I,C=o-t;return{center:{x:I+B/2,y:t+C/2},width:B,height:C}};function ioo({circuitJson:g,editEvents:A}){if(A.length===0)return g;let I=structuredClone(g);for(const e of A){if(e.edit_event_type==="edit_pcb_component_location"){const C=Y5(I).pcb_component.get(e.pcb_component_id);if(C?.center.x===e.new_center.x&&C.center.y===e.new_center.y)continue;const i=qc(e.new_center.x-e.original_center.x,e.new_center.y-e.original_center.y);I=I.map(E=>"pcb_component_id"in E&&E.pcb_component_id===e.pcb_component_id?goo(E,i):E);continue}if(e.edit_event_type==="edit_schematic_component_location"){I=I.map(C=>C.type==="schematic_component"&&C.schematic_component_id===e.schematic_component_id?{...C,center:e.new_center}:C);continue}if(e.edit_event_type!=="edit_pcb_trace_hint"||!e.pcb_trace_hint_id)continue;if(Y5(I).pcb_trace_hint.get(e.pcb_trace_hint_id)){I=I.map(C=>C.type==="pcb_trace_hint"&&C.pcb_trace_hint_id===e.pcb_trace_hint_id?{...C,route:e.route}:C);continue}const o=Y5(I).pcb_port.get(e.pcb_port_id);if(!o?.pcb_component_id)continue;const B={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:o.pcb_component_id};I=I.filter(C=>C.type!=="pcb_trace_hint"||C.pcb_port_id!==e.pcb_port_id).concat(B)}return I}var Eoo=g=>{if(!g)return"empty";const A=g.find(e=>e.type==="pcb_board");if(!A)return"no-board";const I=e=>Math.round(e*1e3)/1e3;return A.outline?A.outline.map(e=>`${I(e.x)}_${I(e.y)}`).join(","):`${I(A.width)}_${I(A.height)}`},qwA=g=>Number.isFinite(g)?g.toFixed(4):"NaN",noo=g=>{let A=5381;for(let I=0;I<g.length;I++)A=(A<<5)+A+g.charCodeAt(I);return Math.abs(A)},soo=g=>{if(!g?.length)return"0";const A=[];for(const t of g){if(!t?.type?.startsWith("pcb_"))continue;const o=Ioo(t),B=Eeg([t]),C=[qwA(B.minX),qwA(B.minY),qwA(B.maxX),qwA(B.maxY)].join(",");let Q=`${o}:${C}`;if(t.type==="pcb_trace"){const i=(t.route??[]).length;Q+=`:${i}`;for(const E of t.route??[])E.route_type==="via"&&(Q+=`:${E.tented_on_top}:${E.tented_on_bottom}`)}t.type==="pcb_board"&&(Q+=`:${t.default_via_tented_on_top}:${t.default_via_tented_on_bottom}`),t.type==="pcb_via"&&(Q+=`:${t.tented_on_top}:${t.tented_on_bottom}`),A.push(Q)}if(A.length===0)return"0";A.sort();const I=A.join(","),e=noo(I);return`${A.length}_${e.toString(36)}`},D2I=z.createContext(null),aoo=({children:g,initialState:A,disablePcbGroups:I})=>{const e=z.useMemo(()=>coo(A,I),[I]);return q.jsx(D2I.Provider,{value:e,children:g})},Mh={RENDERING_ENGINE:"pcb_viewer_rendering_engine",COPPER_POUR_OPACITY:"pcb_viewer_copper_pour_opacity",HIDDEN_LAYER_OPACITY:"pcb_viewer_hidden_layer_opacity",IS_SHOWING_PCB_GROUPS:"pcb_viewer_is_showing_pcb_groups",PCB_GROUP_VIEW_MODE:"pcb_viewer_group_view_mode",IS_SHOWING_COPPER_POURS:"pcb_viewer_is_showing_copper_pours",IS_SHOWING_COURTYARDS:"pcb_viewer_is_showing_courtyards",IS_SHOWING_GROUP_ANCHOR_OFFSETS:"pcb_viewer_is_showing_group_anchor_offsets",IS_SHOWING_SOLDER_MASK:"pcb_viewer_is_showing_solder_mask",IS_SHOWING_FABRICATION_NOTES:"pcb_viewer_is_showing_fabrication_notes",IS_SHOWING_PCB_NOTES:"pcb_viewer_is_showing_pcb_notes",IS_SHOWING_SILKSCREEN:"pcb_viewer_is_showing_silkscreen"},U3=(g,A)=>{if(typeof window>"u")return A;try{const I=localStorage.getItem(g);return I!==null?JSON.parse(I):A}catch{return A}},J3=(g,A)=>{if(!(typeof window>"u"))try{localStorage.setItem(g,JSON.stringify(A))}catch{}},d2I=(g,A)=>{if(typeof window>"u")return A;try{const I=localStorage.getItem(g);return I!==null?JSON.parse(I):A}catch{return A}},y2I=(g,A)=>{if(!(typeof window>"u"))try{localStorage.setItem(g,JSON.stringify(A))}catch{}},w2I=(g,A)=>{if(typeof window>"u")return A;try{const I=localStorage.getItem(g),e=I!==null?JSON.parse(I):null;return typeof e=="number"&&Number.isFinite(e)?e:A}catch{return A}},u2I=(g,A)=>{if(!(typeof window>"u"))try{localStorage.setItem(g,JSON.stringify(A))}catch{}},roo="named_only",coo=(g={},A=!1)=>_Vg(I=>({copper_pour_opacity:Math.max(0,Math.min(1,w2I(Mh.COPPER_POUR_OPACITY,1))),setCopperPourOpacity:e=>{if(!Number.isFinite(e))return;const t=Math.max(0,Math.min(1,e));u2I(Mh.COPPER_POUR_OPACITY,t),I({copper_pour_opacity:t})},hidden_layer_opacity:Math.max(0,Math.min(1,w2I(Mh.HIDDEN_LAYER_OPACITY,.2))),setHiddenLayerOpacity:e=>{if(!Number.isFinite(e))return;const t=Math.max(0,Math.min(1,e));u2I(Mh.HIDDEN_LAYER_OPACITY,t),I({hidden_layer_opacity:t})},selected_layer:"top",pcb_viewer_id:`pcb_viewer_${Math.random().toString().slice(2,10)}`,in_edit_mode:!1,in_move_footprint_mode:!1,is_moving_component:!1,is_mouse_over_container:!1,is_showing_multiple_traces_length:!1,is_showing_rats_nest:!1,is_showing_autorouting:!0,is_showing_drc_errors:!0,is_showing_drc_warnings:!0,is_showing_copper_pours:U3(Mh.IS_SHOWING_COPPER_POURS,!0),is_showing_courtyards:U3(Mh.IS_SHOWING_COURTYARDS,!0),is_showing_pcb_groups:A?!1:U3(Mh.IS_SHOWING_PCB_GROUPS,!0),is_showing_group_anchor_offsets:U3(Mh.IS_SHOWING_GROUP_ANCHOR_OFFSETS,!1),is_showing_solder_mask:U3(Mh.IS_SHOWING_SOLDER_MASK,!1),is_showing_silkscreen:U3(Mh.IS_SHOWING_SILKSCREEN,!0),is_showing_fabrication_notes:U3(Mh.IS_SHOWING_FABRICATION_NOTES,!1),is_showing_pcb_notes:U3(Mh.IS_SHOWING_PCB_NOTES,!0),pcb_group_view_mode:A?"all":d2I(Mh.PCB_GROUP_VIEW_MODE,roo),hovered_error_id:null,focused_error_id:null,...g,selectLayer:e=>I({selected_layer:e}),setEditMode:e=>I({in_edit_mode:e!=="off",in_move_footprint_mode:e==="move_footprint",is_moving_component:!1}),setIsShowingRatsNest:e=>I({is_showing_rats_nest:e}),setIsMovingComponent:e=>I({is_moving_component:e}),setIsMouseOverContainer:e=>I({is_mouse_over_container:e}),setIsShowingMultipleTracesLength:e=>I({is_showing_multiple_traces_length:e}),setIsShowingAutorouting:e=>I({is_showing_autorouting:e}),setIsShowingDrcErrors:e=>I({is_showing_drc_errors:e}),setIsShowingDrcWarnings:e=>I({is_showing_drc_warnings:e}),setIsShowingCopperPours:e=>{J3(Mh.IS_SHOWING_COPPER_POURS,e),I({is_showing_copper_pours:e})},setIsShowingCourtyards:e=>{J3(Mh.IS_SHOWING_COURTYARDS,e),I({is_showing_courtyards:e})},setIsShowingPcbGroups:e=>{A||(J3(Mh.IS_SHOWING_PCB_GROUPS,e),I({is_showing_pcb_groups:e}))},setIsShowingGroupAnchorOffsets:e=>{J3(Mh.IS_SHOWING_GROUP_ANCHOR_OFFSETS,e),I({is_showing_group_anchor_offsets:e})},setIsShowingSolderMask:e=>{J3(Mh.IS_SHOWING_SOLDER_MASK,e),I({is_showing_solder_mask:e})},setIsShowingSilkscreen:e=>{J3(Mh.IS_SHOWING_SILKSCREEN,e),I({is_showing_silkscreen:e})},setIsShowingFabricationNotes:e=>{J3(Mh.IS_SHOWING_FABRICATION_NOTES,e),I({is_showing_fabrication_notes:e})},setIsShowingPcbNotes:e=>{J3(Mh.IS_SHOWING_PCB_NOTES,e),I({is_showing_pcb_notes:e})},setPcbGroupViewMode:e=>{A||(y2I(Mh.PCB_GROUP_VIEW_MODE,e),I({pcb_group_view_mode:e}))},setHoveredErrorId:e=>I({hovered_error_id:e}),setFocusedErrorId:e=>I({focused_error_id:e})})),ii=g=>{const A=z.useContext(D2I);return jVg(A,g)},hoo=()=>{z.useEffect(()=>{nIo()},[]);const g=ii(A=>A.pcb_viewer_id);return q.jsx(EIo,{position:"top-center",containerId:g})},da={elementOverlay:40,dimensionOverlay:40,errorOverlay:40,pcbGroupOverlay:35,ratsNestOverlay:30,toolbarOverlay:70,warnings:30,topLayer:30,clickToInteractOverlay:100};function loo(){var g=z.useRef(!1),A=z.useCallback(function(){return g.current},[]);return z.useEffect(function(){return g.current=!0,function(){g.current=!1}},[]),A}var Doo=function(g){g===void 0&&(g={});var A=z.useState(g),I=A[0],e=A[1],t=z.useCallback(function(o){e(function(B){return Object.assign({},B,o instanceof Function?o(B):o)})},[]);return[I,t]},doo=Doo,yoo=function(){},G2I=typeof window<"u",woo=lSI(leo()),uoo=function(){var g=loo(),A=doo({value:void 0,error:void 0,noUserInteraction:!0}),I=A[0],e=A[1],t=z.useCallback(function(o){if(g()){var B,C;try{if(typeof o!="string"&&typeof o!="number"){var Q=new Error("Cannot copy typeof "+typeof o+" to clipboard, must be a string");console.error(Q),e({value:o,error:Q,noUserInteraction:!0});return}else if(o===""){var Q=new Error("Cannot copy empty string to clipboard.");console.error(Q),e({value:o,error:Q,noUserInteraction:!0});return}C=o.toString(),B=(0,woo.default)(C),e({value:C,error:void 0,noUserInteraction:B})}catch(i){e({value:C,error:i,noUserInteraction:B})}}},[]);return[I,t]},Goo=uoo,moo=G2I?z.useLayoutEffect:z.useEffect,poo=moo,m2I={x:0,y:0,width:0,height:0,top:0,left:0,bottom:0,right:0};function koo(){var g=z.useState(null),A=g[0],I=g[1],e=z.useState(m2I),t=e[0],o=e[1],B=z.useMemo(function(){return new window.ResizeObserver(function(C){if(C[0]){var Q=C[0].contentRect,i=Q.x,E=Q.y,n=Q.width,s=Q.height,r=Q.top,a=Q.left,c=Q.bottom,h=Q.right;o({x:i,y:E,width:n,height:s,top:r,left:a,bottom:c,right:h})}})},[]);return poo(function(){if(A)return B.observe(A),function(){B.disconnect()}},[A]),[I,t]}var QeA=G2I&&typeof window.ResizeObserver<"u"?koo:function(){return[yoo,m2I]},p2I=({initialTransform:g,initialTouch1:A,initialTouch2:I,finalTouch1:e,finalTouch2:t})=>{if(!e||!t)return g;const o={x:(A.x+I.x)/2,y:(A.y+I.y)/2},B={x:(e.x+t.x)/2,y:(e.y+t.y)/2},C=Math.hypot(I.x-A.x,I.y-A.y),Q=Math.hypot(t.x-e.x,t.y-e.y),i=C===0?1:Q/C,E=B.x-o.x,n=B.y-o.y;return bw(qc(E,n),qc(o.x,o.y),GJ(i,i),qc(-o.x,-o.y),g)},Moo=(g={})=>{const A=z.useRef(null),[I,e]=z.useState(0),t=g.canvasElm??A.current,[o,B]=z.useState(g.initialTransform??uJ()),[C,Q]=z.useState(0),[i,E]=z.useReducer(d=>d+1,0),n=z.useCallback(d=>{g.onSetTransform&&g.onSetTransform(d),g.transform||B(d)},[g.onSetTransform,B]),s=z.useCallback(d=>{n(d),E()},[n]),r=g.transform??o,a=z.useCallback(()=>{e(Date.now())},[]),c=z.useRef("none"),h=z.useRef(null),l=z.useRef(null);z.useEffect(()=>{const d=g.canvasElm??A.current;if(d&&!t){Q(C+1);return}if(!d){const _=setTimeout(()=>{Q(C+1)},100);return()=>clearTimeout(_)}let y=g.transform??o,w={x:0,y:0},u={x:0,y:0},G=!1;const m=_=>({x:_.pageX-d.getBoundingClientRect().left-window.scrollX,y:_.pageY-d.getBoundingClientRect().top-window.scrollY});function p(_){g.enabled!==!1&&(g.shouldDrag&&!g.shouldDrag(_)||(w=m(_),!(Date.now()-I<100)&&(G=!0,_.preventDefault())))}function k(_){if(!G||g.enabled===!1||g.shouldDrag&&!g.shouldDrag(_))return;u=m(_);const b=bw(qc(u.x-w.x,u.y-w.y),y);n(b),y=b,G=!1}function S(_){if(m(_),!G||g.enabled===!1||g.shouldDrag&&!g.shouldDrag(_))return;u=m(_);const b=bw(qc(u.x-w.x,u.y-w.y),y);n(b)}function R(_){if(g.enabled===!1||g.shouldDrag&&!g.shouldDrag(_))return;const b=m(_),T=bw(qc(b.x,b.y),GJ(1-_.deltaY/1e3,1-_.deltaY/1e3),qc(-b.x,-b.y),y);n(T),y=T,_.preventDefault()}function x(_){if(!G||g.shouldDrag&&!g.shouldDrag(_))return;if(d){const T=d.getBoundingClientRect();if(_.clientX>=T.left+10&&_.clientX<=T.right-10&&_.clientY>=T.top+10&&_.clientY<=T.bottom-10)return}G=!1,u=m(_);const b=bw(qc(u.x-w.x,u.y-w.y),y);n(b),y=b}function N(_){if(_.preventDefault(),g.enabled!==!1){if(_.touches.length===1){c.current="drag";const b=_.touches[0];h.current={initialTransform:y,initialTouch:{x:b.clientX,y:b.clientY}}}else if(_.touches.length===2){c.current="pinch";const b=_.touches[0],T=_.touches[1];l.current={initialTransform:y,initialTouch1:{x:b.clientX,y:b.clientY},initialTouch2:{x:T.clientX,y:T.clientY},finalTouch1:null,finalTouch2:null}}}}function U(_){if(_.preventDefault(),g.enabled!==!1){if(c.current==="drag"&&_.touches.length===1&&h.current){const b=_.touches[0],T={x:b.clientX,y:b.clientY},j=T.x-h.current.initialTouch.x,W=T.y-h.current.initialTouch.y,O=bw(qc(j,W),h.current.initialTransform);n(O)}else if(c.current==="pinch"&&_.touches.length===2&&l.current){const b=_.touches[0],T=_.touches[1];l.current.finalTouch1={x:b.clientX,y:b.clientY},l.current.finalTouch2={x:T.clientX,y:T.clientY};const j=p2I(l.current);n(j)}}}function K(_){_.preventDefault();const b=_.changedTouches[0];if(c.current==="drag"&&h.current&&b){const T={x:b.clientX,y:b.clientY},j=T.x-h.current.initialTouch.x,W=T.y-h.current.initialTouch.y,O=bw(qc(j,W),h.current.initialTransform);n(O),y=O}else if(c.current==="pinch"&&l.current){const T=p2I(l.current);n(T),y=T}c.current="none",h.current=null,l.current=null}return d.addEventListener("mousedown",p),d.addEventListener("mouseup",k),window.addEventListener("mousemove",S),d.addEventListener("mouseout",x),d.addEventListener("wheel",R),d.addEventListener("touchstart",N,{passive:!1}),d.addEventListener("touchmove",U,{passive:!1}),d.addEventListener("touchend",K,{passive:!1}),d.addEventListener("touchcancel",K,{passive:!1}),()=>{d.removeEventListener("mousedown",p),d.removeEventListener("mouseup",k),window.removeEventListener("mousemove",S),d.removeEventListener("mouseout",x),d.removeEventListener("wheel",R),d.removeEventListener("touchstart",N),d.removeEventListener("touchmove",U),d.removeEventListener("touchend",K),d.removeEventListener("touchcancel",K)}},[t,C,i,I,g.enabled,g.shouldDrag]);const D=z.useCallback(d=>Mt(r,d),[r]);return{ref:A,transform:r,applyTransformToPoint:D,setTransform:s,cancelDrag:a}},Soo=Moo;function k2I(g){let A=g;for(;A.parent!==null;)A=A.parent;let I=g;for(;I.parent!==null&&I.parent!==A;){const e=I.parent;I.parent=A,I=e}return A}function foo(g,A){const I={nodeId:g,nextMember:null},e={parent:null,networkId:`connectivity_net${A.nextNetworkNumber++}`,firstMember:I,lastMember:I};return A.rootByNodeId.set(g,e),e}function Roo(g,A){const I=A.rootByNodeId.get(g);return I===void 0?foo(g,A):k2I(I)}function Noo({targetRoot:g,sourceRoot:A}){g.lastMember.nextMember=A.firstMember,g.lastMember=A.lastMember,A.parent=g}function xoo(g){const A=[];let I=g.firstMember;for(;I!==null;)A.push(I.nodeId),I=I.nextMember;return A}function Foo(g){const A={rootByNodeId:new Map,nextNetworkNumber:0};for(const e of g){let t=null;for(const o of e){const B=Roo(o,A);if(t===null){t=B;continue}t=k2I(t),B!==t&&Noo({targetRoot:t,sourceRoot:B})}}const I={};for(const e of A.rootByNodeId.values())e.parent===null&&(I[e.networkId]=xoo(e));return I}var Uoo=class{netMap;idToNetMap;constructor(g){this.netMap=g,this.idToNetMap={};for(const[A,I]of Object.entries(g))for(const e of I)this.idToNetMap[e]=A}addConnections(g){for(const A of g){const I=new Set;for(const t of A){const o=this.idToNetMap[t];o&&I.add(o)}let e;if(I.size===0)e=`connectivity_net${Object.keys(this.netMap).length}`,this.netMap[e]=[];else if(I.size===1)e=I.values().next().value??`connectivity_net${Object.keys(this.netMap).length}`;else{e=I.values().next().value??`connectivity_net${Object.keys(this.netMap).length}`;for(const t of I)if(t!==e){this.netMap[e].push(...this.netMap[t]),this.netMap[t]=this.netMap[e];for(const o of this.netMap[e])this.idToNetMap[o]=e}}for(const t of A)this.netMap[e].includes(t)||this.netMap[e].push(t),this.idToNetMap[t]=e}}getIdsConnectedToNet(g){return this.netMap[g]||[]}getNetConnectedToId(g){return this.idToNetMap[g]}areIdsConnected(g,A){if(g===A)return!0;const I=this.getNetConnectedToId(g);if(!I)return!1;const e=this.getNetConnectedToId(A);return e?I===e||e===g||e===g:!1}areAllIdsConnected(g){const A=this.getNetConnectedToId(g[0]);for(const I of g){const e=this.getNetConnectedToId(I);if(e===void 0||e!==A)return!1}return!0}},Joo=g=>{const A=[];for(const e of g)if(e.type==="source_trace")A.push([e.source_trace_id,...e.connected_source_port_ids??[],...e.connected_source_net_ids??[]].filter(Boolean));else if(e.type==="pcb_port"){const{pcb_port_id:t,source_port_id:o}=e;o&&t&&A.push([o,t])}else if(e.type==="pcb_smtpad"){const{pcb_smtpad_id:t,pcb_port_id:o}=e;o&&t&&A.push([t,o])}else if(e.type==="pcb_plated_hole"){const{pcb_plated_hole_id:t,pcb_port_id:o}=e;o&&t&&A.push([t,o])}else if(e.type==="pcb_trace"){const{pcb_trace_id:t,source_trace_id:o}=e,B=Array.isArray(e.route)?e.route.filter(C=>C&&C.route_type==="wire"):[];if(o&&t&&A.push([t,o]),Array.isArray(B)){const C=B.find(i=>i?.start_pcb_port_id)?.start_pcb_port_id,Q=B.find(i=>i?.end_pcb_port_id)?.end_pcb_port_id;C&&t&&A.push([C,t]),t&&Q&&A.push([t,Q])}}else if(e.type==="pcb_via"){const{pcb_via_id:t,pcb_trace_id:o,source_trace_id:B,source_net_id:C}=e,Q=[...e.pcb_port_ids??[],o,B,C].filter(i=>!!i);t&&Q.length>0&&A.push([t,...Q])}else if(e.type==="source_component"&&e.internally_connected_source_port_ids)for(const t of e.internally_connected_source_port_ids)A.push(t);const I=Foo(A);return new Uoo(I)};function Poo(g,A){if(g.length<2)throw new Error("Stroke must have at least two points");const I=g.map(n=>Array.isArray(n)?{x:n[0],y:n[1]}:n),e=[],t=[];function o(n,s){const r=s.x-n.x,a=s.y-n.y,c=Math.sqrt(r*r+a*a);return{x:-a/c,y:r/c}}function B(n,s,r,a){const c=a/2,h={x:n.x+s.x*c*r,y:n.y+s.y*c*r};r>0?e.push(h):t.unshift(h)}const C=o(I[0],I[1]),Q=I[0].trace_width??A;B(I[0],C,1,Q),B(I[0],C,-1,Q);for(let n=1;n<I.length-1;n++){const s=I[n-1],r=I[n],a=I[n+1],c=o(s,r),h=o(r,a),l=c.x+h.x,D=c.y+h.y,d=Math.sqrt(l*l+D*D),y=r.trace_width??A;if(d/2>2*(y/2))B(r,c,1,y),B(r,h,1,y),B(r,c,-1,y),B(r,h,-1,y);else{const u=1/d;B(r,{x:l*u,y:D*u},1,y),B(r,{x:l*u,y:D*u},-1,y)}}const i=o(I[I.length-2],I[I.length-1]),E=I[I.length-1].trace_width??A;return B(I[I.length-1],i,1,E),B(I[I.length-1],i,-1,E),[...e,...t]}var Koo=(g,A)=>{const{x:I,y:e,width:t,height:o,layer:B,rect_border_radius:C}=g,Q=g.corner_radius??C??0,i=[{_pcb_drawing_object_id:LR("rect"),pcb_drawing_type:"rect",x:I,y:e,w:t,h:o,layer:B||"top",_element:g,_parent_pcb_component:A._parent_pcb_component,_parent_source_component:A._parent_source_component,_source_port:A._source_port,roundness:Q,...g.shape==="rotated_rect"&&g.ccw_rotation!==void 0?{ccw_rotation:g.ccw_rotation}:{}}];if(g.is_covered_with_solder_mask){const E=B==="bottom"?"soldermask_with_copper_bottom":"soldermask_with_copper_top",s={...{_pcb_drawing_object_id:LR("rect"),pcb_drawing_type:"rect",x:I,y:e,w:t,h:o,layer:E,_element:g,_parent_pcb_component:A._parent_pcb_component,_parent_source_component:A._parent_source_component,_source_port:A._source_port,roundness:Q,...g.shape==="rotated_rect"&&g.ccw_rotation!==void 0?{ccw_rotation:g.ccw_rotation}:{}},..."solder_mask_color"in g&&g.solder_mask_color?{color:g.solder_mask_color}:{}};i.push(s)}return i},Loo=(g,A)=>{const{x:I,y:e,radius:t,layer:o}=g,B=[{_pcb_drawing_object_id:LR("circle"),pcb_drawing_type:"circle",x:I,y:e,r:t,layer:o||"top",_element:g,_parent_pcb_component:A._parent_pcb_component,_parent_source_component:A._parent_source_component,_source_port:A._source_port}];if(g.is_covered_with_solder_mask){const C=o==="bottom"?"soldermask_with_copper_bottom":"soldermask_with_copper_top",Q={_pcb_drawing_object_id:LR("circle"),pcb_drawing_type:"circle",x:I,y:e,r:t,layer:C,_element:g,_parent_pcb_component:A._parent_pcb_component,_parent_source_component:A._parent_source_component,_source_port:A._source_port,..."solder_mask_color"in g&&g.solder_mask_color?{color:g.solder_mask_color}:{}};B.push(Q)}return B},Yoo=(g,A)=>{const{layer:I,points:e}=g,t=[{_pcb_drawing_object_id:LR("polygon"),pcb_drawing_type:"polygon",points:neg(e),layer:I||"top",_element:g,_parent_pcb_component:A._parent_pcb_component,_parent_source_component:A._parent_source_component,_source_port:A._source_port}];if(g.is_covered_with_solder_mask){const o=I==="bottom"?"soldermask_with_copper_bottom":"soldermask_with_copper_top",B={_pcb_drawing_object_id:LR("polygon"),pcb_drawing_type:"polygon",points:neg(e),layer:o,_element:g,_parent_pcb_component:A._parent_pcb_component,_parent_source_component:A._parent_source_component,_source_port:A._source_port,..."solder_mask_color"in g&&g.solder_mask_color?{color:g.solder_mask_color}:{}};t.push(B)}return t},_oo=(g,A)=>{const{x:I,y:e,width:t,height:o,layer:B}=g,C=[{_pcb_drawing_object_id:LR("pill"),pcb_drawing_type:"pill",x:I,y:e,w:t,h:o,layer:B||"top",_element:g,_parent_pcb_component:A._parent_pcb_component,_parent_source_component:A._parent_source_component,_source_port:A._source_port}];if(g.is_covered_with_solder_mask){const Q=B==="bottom"?"soldermask_with_copper_bottom":"soldermask_with_copper_top",i={_pcb_drawing_object_id:LR("pill"),pcb_drawing_type:"pill",x:I,y:e,w:t,h:o,layer:Q,_element:g,_parent_pcb_component:A._parent_pcb_component,_parent_source_component:A._parent_source_component,_source_port:A._source_port,..."solder_mask_color"in g&&g.solder_mask_color?{color:g.solder_mask_color}:{}};C.push(i)}return C},boo=(g,A)=>{const{x:I,y:e,width:t,height:o,layer:B,ccw_rotation:C}=g,Q=[{_pcb_drawing_object_id:LR("pill"),pcb_drawing_type:"pill",x:I,y:e,w:t,h:o,layer:B||"top",_element:g,_parent_pcb_component:A._parent_pcb_component,_parent_source_component:A._parent_source_component,_source_port:A._source_port,ccw_rotation:C}];if(g.is_covered_with_solder_mask){const i=B==="bottom"?"soldermask_with_copper_bottom":"soldermask_with_copper_top",E={_pcb_drawing_object_id:LR("pill"),pcb_drawing_type:"pill",x:I,y:e,w:t,h:o,layer:i,_element:g,_parent_pcb_component:A._parent_pcb_component,_parent_source_component:A._parent_source_component,_source_port:A._source_port,ccw_rotation:C,..."solder_mask_color"in g&&g.solder_mask_color?{color:g.solder_mask_color}:{}};Q.push(E)}return Q},Oc=0,LR=g=>`${g}_${Oc++}`,neg=g=>(g??[]).map(A=>({x:sg.parse(A.x),y:sg.parse(A.y)}));function Hoo(g){const A=new Map;for(const I of g){const e=I[`${I.type}_id`];e!==void 0&&!A.has(`${I.type}:${e}`)&&A.set(`${I.type}:${e}`,I)}return A}var voo=(g,A,I)=>{const e=(Q,i)=>{if(i!==void 0)return I?I.get(`${Q}:${i}`):A.find(E=>E.type===Q&&E[`${Q}_id`]===i)},t=e("pcb_component","pcb_component_id"in g?g.pcb_component_id:void 0),o=e("source_component",t?.source_component_id),B="source_port_id"in g?g.source_port_id:"pcb_port_id"in g?e("pcb_port",g.pcb_port_id)?.source_port_id:void 0,C=e("source_port",B);switch(g.type){case"pcb_smtpad":{const Q={_parent_pcb_component:t,_parent_source_component:o,_source_port:C};return g.shape==="rect"||g.shape==="rotated_rect"?Koo(g,Q):g.shape==="circle"?Loo(g,Q):g.shape==="polygon"?Yoo(g,Q):g.shape==="pill"?_oo(g,Q):g.shape==="rotated_pill"?boo(g,Q):[]}case"pcb_trace":{const Q=[];if(g.route_thickness_mode==="interpolated"){const n=g.route.flatMap(a=>a.route_type==="through_pad"?[{...a.start,trace_width:a.width},{...a.end,trace_width:a.width}]:[{x:a.x,y:a.y,trace_width:a.route_type==="wire"?a.width:.5}]),s=Poo(n,.5),r=g.route[0].layer;return Q.push({_pcb_drawing_object_id:`polygon_${Oc++}`,_element:g,pcb_drawing_type:"polygon",points:s,layer:r}),g.route.forEach(a=>{a.route_type==="via"&&Q.push({_pcb_drawing_object_id:`circle_${Oc++}`,_element:g,pcb_drawing_type:"circle",x:a.x,y:a.y,r:a.outer_diameter/2,layer:a.from_layer})}),Q}let i=null,E=null;for(const n of g.route)n.route_type==="wire"&&(i!==null&&E!==null&&Q.push({_pcb_drawing_object_id:`line_${Oc++}`,_element:g,pcb_drawing_type:"line",x1:i,y1:E,x2:n.x,y2:n.y,width:n.width,squareCap:!1,layer:n.layer}),i=n.x,E=n.y);return Q}case"pcb_via":{const{x:Q,y:i,outer_diameter:E,hole_diameter:n}=g,s=g.from_layer,r=g.to_layer,a=g.layers,c=[];s&&r?c.push(s,r):a&&Array.isArray(a)?c.push(...a):c.push("top","bottom");const h=[];for(const l of c)h.push({_pcb_drawing_object_id:`circle_${Oc++}`,pcb_drawing_type:"circle",x:Q,y:i,r:E/2,layer:l,_element:g,_parent_pcb_component:t,_parent_source_component:o});return h.push({_pcb_drawing_object_id:`circle_${Oc++}`,pcb_drawing_type:"circle",x:Q,y:i,r:n/2,layer:"drill",_element:g}),h}case"pcb_plated_hole":if(g.shape==="circle"){const{x:Q,y:i,hole_diameter:E,outer_diameter:n}=g;return[{_pcb_drawing_object_id:`circle_${Oc++}`,pcb_drawing_type:"circle",x:Q,y:i,r:n/2,layer:"top",_element:g,_parent_pcb_component:t,_parent_source_component:o,_source_port:C},{_pcb_drawing_object_id:`circle_${Oc++}`,pcb_drawing_type:"circle",x:Q,y:i,r:E/2,layer:"drill",_element:g}]}else if(g.shape==="oval"){const{x:Q,y:i,outer_height:E,outer_width:n,hole_height:s,hole_width:r}=g;return[{_pcb_drawing_object_id:`oval_${Oc++}`,pcb_drawing_type:"oval",x:Q,y:i,rX:n/2,rY:E/2,layer:"top",_element:g,_parent_pcb_component:t,_parent_source_component:o,_source_port:C},{_pcb_drawing_object_id:`oval_${Oc++}`,_element:g,pcb_drawing_type:"oval",x:Q,y:i,rX:r/2,rY:s/2,layer:"drill"}]}else if(g.shape==="pill"){const{x:Q,y:i,outer_height:E,outer_width:n,hole_height:s,hole_width:r}=g;return[{_pcb_drawing_object_id:`pill_${Oc++}`,pcb_drawing_type:"pill",x:Q,y:i,w:n,h:E,layer:"top",_element:g,_parent_pcb_component:t,_parent_source_component:o,_source_port:C,ccw_rotation:g.ccw_rotation},{_pcb_drawing_object_id:`pill_${Oc++}`,_element:g,pcb_drawing_type:"pill",x:Q,y:i,w:r,h:s,layer:"drill",ccw_rotation:g.ccw_rotation}]}else if(g.shape==="circular_hole_with_rect_pad"){const{x:Q,y:i,hole_diameter:E,rect_pad_width:n,rect_pad_height:s,rect_border_radius:r,hole_offset_x:a,hole_offset_y:c}=g,h=sg.parse(a??0),l=sg.parse(c??0);return[{_pcb_drawing_object_id:`rect_${Oc++}`,pcb_drawing_type:"rect",x:Q,y:i,w:n,h:s,layer:"top",_element:g,_parent_pcb_component:t,_parent_source_component:o,_source_port:C,roundness:r},{_pcb_drawing_object_id:`rect_${Oc++}`,pcb_drawing_type:"rect",x:Q,y:i,w:n,h:s,layer:"bottom",_element:g,_parent_pcb_component:t,_parent_source_component:o,_source_port:C,roundness:r,is_hoverable:!1},{_pcb_drawing_object_id:`circle_${Oc++}`,_element:g,pcb_drawing_type:"circle",x:Q+h,y:i+l,r:E/2,layer:"drill",is_hoverable:!1}]}else if(g.shape==="pill_hole_with_rect_pad"){const{x:Q,y:i,hole_width:E,hole_height:n,rect_pad_width:s,rect_pad_height:r,rect_border_radius:a}=g;return[{_pcb_drawing_object_id:`rect_${Oc++}`,pcb_drawing_type:"rect",x:Q,y:i,w:s,h:r,layer:"top",_element:g,_parent_pcb_component:t,_parent_source_component:o,_source_port:C,roundness:a},{_pcb_drawing_object_id:`rect_${Oc++}`,pcb_drawing_type:"rect",x:Q,y:i,w:s,h:r,layer:"bottom",_element:g,_parent_pcb_component:t,_parent_source_component:o,_source_port:C,roundness:a,is_hoverable:!1},{_pcb_drawing_object_id:`pill_${Oc++}`,_element:g,pcb_drawing_type:"pill",x:Q,y:i,w:E,h:n,layer:"drill",is_hoverable:!1}]}else if(g.shape==="rotated_pill_hole_with_rect_pad"){const{x:Q,y:i,hole_width:E,hole_height:n,hole_ccw_rotation:s,rect_pad_width:r,rect_pad_height:a,rect_ccw_rotation:c,rect_border_radius:h}=g;return[{_pcb_drawing_object_id:`rect_${Oc++}`,pcb_drawing_type:"rect",x:Q,y:i,w:r,h:a,layer:"top",_element:g,_parent_pcb_component:t,_parent_source_component:o,_source_port:C,ccw_rotation:c,roundness:h},{_pcb_drawing_object_id:`rect_${Oc++}`,pcb_drawing_type:"rect",x:Q,y:i,w:r,h:a,layer:"bottom",_element:g,_parent_pcb_component:t,_parent_source_component:o,_source_port:C,ccw_rotation:c,roundness:h,is_hoverable:!1},{_pcb_drawing_object_id:`pill_${Oc++}`,_element:g,pcb_drawing_type:"pill",x:Q,y:i,w:E,h:n,layer:"drill",ccw_rotation:s,is_hoverable:!1}]}else if(g.shape==="hole_with_polygon_pad"){const{x:Q,y:i,pad_outline:E,hole_shape:n,hole_diameter:s,hole_width:r,hole_height:a,layers:c,hole_offset_x:h,hole_offset_y:l}=g,D=sg.parse(h??0),d=sg.parse(l??0),y=E,w=[];if(y&&Array.isArray(y)){const m=neg(y).map(p=>({x:p.x+Q,y:p.y+i}));for(const p of c||["top","bottom"])w.push({_pcb_drawing_object_id:`polygon_${Oc++}`,pcb_drawing_type:"polygon",points:m,layer:p,_element:g,_parent_pcb_component:t,_parent_source_component:o,_source_port:C})}const u={x:Q+D,y:i+d},G=[];return n==="circle"?G.push({_pcb_drawing_object_id:`circle_${Oc++}`,pcb_drawing_type:"circle",x:u.x,y:u.y,r:(s??0)/2,layer:"drill",_element:g,_parent_pcb_component:t,_parent_source_component:o}):n==="oval"?G.push({_pcb_drawing_object_id:`oval_${Oc++}`,pcb_drawing_type:"oval",x:u.x,y:u.y,rX:(r??0)/2,rY:(a??0)/2,layer:"drill",_element:g,_parent_pcb_component:t,_parent_source_component:o}):(n==="pill"||n==="rotated_pill")&&G.push({_pcb_drawing_object_id:`pill_${Oc++}`,pcb_drawing_type:"pill",x:u.x,y:u.y,w:r??0,h:a??0,layer:"drill",_element:g,_parent_pcb_component:t,_parent_source_component:o,ccw_rotation:g.ccw_rotation}),[...w,...G]}else return[]}return[]};function qoo(g,A,I){const e=document.createElement("canvas");e.width=e.height=1;const t=e.getContext("2d");return g.filter(o=>o.type!=="pcb_copper_pour"||o.layer!==I?!1:(ndI({ctx:t,pour:o,realToCanvasMat:uJ(),colorMap:Lw}),t.isPointInPath(A.x,A.y,o.shape==="brep"?"evenodd":"nonzero")))}function Too(g){return g.type==="pcb_copper_pour"}function M2I({canvas:g,elements:A,layers:I,realToCanvasMat:e,opacity:t=1}){const o=A.filter(Too);if(o.length===0||t<=0)return;const B=new XE(g);B.configure({colorOverrides:{copper:Object.fromEntries(Object.entries(Lw.copper).map(([C,Q])=>[C,uQ(Q).alpha(t).rgb().string()]))}}),B.realToCanvasMat=e,B.drawElements(o,{layers:I})}var TwA=(g,A,I)=>I(g,A),S2I=(g,A,I,e,t)=>{const o=t*Math.PI/180,B=Math.cos(o),C=Math.sin(o),Q=g-I,i=A-e,E=Q*B-i*C,n=Q*C+i*B;return{x:E+I,y:n+e}},ieA=g=>{if(g.length===0)return null;let A=g[0].x,I=g[0].x,e=g[0].y,t=g[0].y;for(const o of g)A=TwA(A,o.x,Math.min),I=TwA(I,o.x,Math.max),e=TwA(e,o.y,Math.min),t=TwA(t,o.y,Math.max);return{minX:A,maxX:I,minY:e,maxY:t}},Zoo=(g,A)=>({minX:Math.min(g.minX,A.minX),maxX:Math.max(g.maxX,A.maxX),minY:Math.min(g.minY,A.minY),maxY:Math.max(g.maxY,A.maxY)}),Ooo=(g,A)=>g?Zoo(g,A):A,seg=g=>{switch(g.pcb_drawing_type){case"line":{const A=(g.width??0)/2,I=[{x:g.x1,y:g.y1},{x:g.x2,y:g.y2}],e=ieA(I);return e?{minX:e.minX-A,maxX:e.maxX+A,minY:e.minY-A,maxY:e.maxY+A}:null}case"rect":{const A=g.w/2,I=g.h/2,e=[{x:g.x-A,y:g.y-I},{x:g.x+A,y:g.y-I},{x:g.x+A,y:g.y+I},{x:g.x-A,y:g.y+I}],t=g.ccw_rotation??0,o=t===0?e:e.map(B=>S2I(B.x,B.y,g.x,g.y,t));return ieA(o)}case"circle":return{minX:g.x-g.r,maxX:g.x+g.r,minY:g.y-g.r,maxY:g.y+g.r};case"oval":return{minX:g.x-g.rX,maxX:g.x+g.rX,minY:g.y-g.rY,maxY:g.y+g.rY};case"pill":{const A=g.w/2,I=g.h/2,e=[{x:g.x-A,y:g.y-I},{x:g.x+A,y:g.y-I},{x:g.x+A,y:g.y+I},{x:g.x-A,y:g.y+I}],t=g.ccw_rotation??0,o=t===0?e:e.map(B=>S2I(B.x,B.y,g.x,g.y,t));return ieA(o)}case"polygon":return ieA(g.points);case"polygon_with_arcs":{const A=g.brep_shape.outer_ring.vertices.map(I=>({x:I.x,y:I.y}));return ieA(A)}case"text":{const A=g.size??0,I=g.text?g.text.length*A*.6:0,e=A;if(I===0&&e===0)return{minX:g.x,maxX:g.x,minY:g.y,maxY:g.y};const t=I/2,o=e/2;return{minX:g.x-t,maxX:g.x+t,minY:g.y-o,maxY:g.y+o}}default:return null}},Woo=64,Voo=256,joo=8;function f2I({cellX:g,cellY:A}){return`${g}:${A}`}function zoo(g){let A=1/0,I=1/0,e=-1/0,t=-1/0;for(const C of g){const Q=seg(C);Q&&(A=Math.min(A,Q.minX),I=Math.min(I,Q.minY),e=Math.max(e,Q.maxX),t=Math.max(t,Q.maxY))}if(!Number.isFinite(A))return 1;const o=Math.max(e-A,t-I),B=Math.sqrt(Math.max(1,g.length/joo));return Math.max(.5,Math.min(20,o/B))}function R2I(g){const A=zoo(g),I=new Map,e=new Map,t=[];let o=0;for(const[B,C]of g.entries()){e.set(C,B),C.pcb_drawing_type==="line"&&C._element?.type==="pcb_trace"&&(o=Math.max(o,C.width));const Q=seg(C);if(!Q){t.push(C);continue}const i=Math.floor(Q.minX/A),E=Math.floor(Q.maxX/A),n=Math.floor(Q.minY/A),s=Math.floor(Q.maxY/A);if((E-i+1)*(s-n+1)>Woo){t.push(C);continue}for(let a=i;a<=E;a++)for(let c=n;c<=s;c++){const h=f2I({cellX:a,cellY:c}),l=I.get(h)??[];l.push(C),I.set(h,l)}}return{cellSize:A,globalPrimitives:t,maxTraceWidth:o,primitiveIndexByPrimitive:e,primitives:g,primitivesByCell:I}}function N2I({point:g,realToScreenScale:A,spatialIndex:I}){const e=Math.max(Math.abs(A),Number.EPSILON),t=Math.max(I.maxTraceWidth*25,2)/e,o=Math.floor((g.x-t)/I.cellSize),B=Math.floor((g.x+t)/I.cellSize),C=Math.floor((g.y-t)/I.cellSize),Q=Math.floor((g.y+t)/I.cellSize);if((B-o+1)*(Q-C+1)>Voo)return I.primitives;const E=new Set(I.globalPrimitives);for(let n=o;n<=B;n++)for(let s=C;s<=Q;s++){const r=f2I({cellX:n,cellY:s}),a=I.primitivesByCell.get(r);if(a)for(const c of a)E.add(c)}return[...E].sort((n,s)=>(I.primitiveIndexByPrimitive.get(n)??Number.MAX_SAFE_INTEGER)-(I.primitiveIndexByPrimitive.get(s)??Number.MAX_SAFE_INTEGER))}function Xoo({primitivesWithoutInteractionMetadata:g,drawingObjectIdsWithMouseOver:A,primitiveIdsInMousedOverNet:I}){const e=[],t=new Set(I);for(const o of g){const B={...o},C=o._element,Q=o._parent_pcb_component;o?.layer==="drill"?(B.is_in_highlighted_net=!1,B.is_mouse_over=!1):A.has(o._pcb_drawing_object_id)?B.is_mouse_over=!0:C&&("pcb_trace_id"in C&&t.has(C.pcb_trace_id)||"pcb_port_id"in C&&t.has(C.pcb_port_id)||"pcb_via_id"in C&&t.has(C.pcb_via_id)||"pcb_component_id"in C&&t.has(C.pcb_component_id)||Q&&"pcb_component_id"in Q&&t.has(Q.pcb_component_id))?B.is_in_highlighted_net=!0:(B.is_in_highlighted_net=!1,B.is_mouse_over=!1),e.push(B)}return e}var x2I=g=>{const A=new Map,I=new Map,e=new Map,t=new Map,o=new Map;for(const B of g)B.type==="pcb_trace"&&B.pcb_trace_id?A.set(B.pcb_trace_id,B):B.type==="pcb_port"&&B.pcb_port_id?I.set(B.pcb_port_id,B):B.type==="pcb_via"&&B.pcb_via_id?e.set(B.pcb_via_id,B):B.type==="pcb_component"&&B.pcb_component_id?t.set(B.pcb_component_id,B):B.type==="pcb_board"&&B.pcb_board_id&&o.set(B.pcb_board_id,B);return{tracesById:A,portsById:I,viasById:e,componentsById:t,boardsById:o}},j2=(g,A)=>A?g?{minX:Math.min(g.minX,A.minX),maxX:Math.max(g.maxX,A.maxX),minY:Math.min(g.minY,A.minY),maxY:Math.max(g.maxY,A.maxY)}:A:g,_5=(g,A=.45)=>({minX:g.x-A,maxX:g.x+A,minY:g.y-A,maxY:g.y+A}),$oo=g=>{if(g.length===0)return null;let A=null;for(const I of g){const e=Math.max((I.width??.2)/2,.3);A=j2(A,_5(I,e))}return A},F2I=g=>{if(!g?.center)return null;const A=Math.max(g.width??0,1.2),I=Math.max(g.height??0,1.2);return{minX:g.center.x-A/2,maxX:g.center.x+A/2,minY:g.center.y-I/2,maxY:g.center.y+I/2}},ABo=g=>!g?.center||typeof g.width!="number"||typeof g.height!="number"?null:{minX:g.center.x-g.width/2,maxX:g.center.x+g.width/2,minY:g.center.y-g.height/2,maxY:g.center.y+g.height/2},gBo=(g,A)=>({minX:g.minX-A,maxX:g.maxX+A,minY:g.minY-A,maxY:g.maxY+A}),IBo=(g,A=.35)=>{const I=$h(g);return I?gBo(I,A):null},U2I=({error:g,tracesById:A,portsById:I,viasById:e,componentsById:t})=>{if(g.center)return g.center;if(g.pcb_center)return g.pcb_center;if(g.component_center)return g.component_center;if(g.pcb_via_ids?.length){const o=g.pcb_via_ids.map(B=>e.get(B)).filter(Boolean);if(o.length>0)return{x:o.reduce((B,C)=>B+C.x,0)/o.length,y:o.reduce((B,C)=>B+C.y,0)/o.length}}if(g.pcb_port_ids?.length){const o=g.pcb_port_ids.map(B=>I.get(B)).filter(Boolean);if(o.length>0)return{x:o.reduce((B,C)=>B+C.x,0)/o.length,y:o.reduce((B,C)=>B+C.y,0)/o.length}}if(g.pcb_trace_id){const o=A.get(g.pcb_trace_id);if(o?.route?.length){const B=Math.floor(o.route.length/2);return{x:o.route[B].x,y:o.route[B].y}}}return g.pcb_component_id?t.get(g.pcb_component_id)?.center??null:null},eBo=({error:g,indexes:A})=>U2I({error:g,...A}),tBo=({error:g,boardsById:A})=>{if(!g.component_bounds||!g.pcb_board_id)return null;const I=ABo(A.get(g.pcb_board_id));if(!I)return null;const e=g.component_bounds,t=[];return e.min_x<I.minX&&(t.push({x:I.minX,y:Math.max(e.min_y,I.minY)}),t.push({x:I.minX,y:Math.min(e.max_y,I.maxY)})),e.max_x>I.maxX&&(t.push({x:I.maxX,y:Math.max(e.min_y,I.minY)}),t.push({x:I.maxX,y:Math.min(e.max_y,I.maxY)})),e.min_y<I.minY&&(t.push({x:Math.max(e.min_x,I.minX),y:I.minY}),t.push({x:Math.min(e.max_x,I.maxX),y:I.minY})),e.max_y>I.maxY&&(t.push({x:Math.max(e.min_x,I.minX),y:I.maxY}),t.push({x:Math.min(e.max_x,I.maxX),y:I.maxY})),IBo(t,.3)},J2I=new Set(["source_failed_to_create_component_error"]),oBo=({error:g,indexes:A})=>{if(J2I.has(g.error_type)||J2I.has(g.type))return null;let I=null;const e=U2I({error:g,...A});if(e&&(I=j2(I,_5(e,.35))),g.error_type==="pcb_component_outside_board_error"?I=j2(I,tBo({error:g,boardsById:A.boardsById})):g.component_bounds&&!e&&(I=j2(I,{minX:g.component_bounds.min_x,maxX:g.component_bounds.max_x,minY:g.component_bounds.min_y,maxY:g.component_bounds.max_y})),g.center&&!e&&(I=j2(I,_5(g.center))),g.pcb_center&&!e&&(I=j2(I,_5(g.pcb_center))),g.component_center&&!e&&(I=j2(I,_5(g.component_center))),g.pcb_port_ids&&!e)for(const t of g.pcb_port_ids){const o=A.portsById.get(t);o&&(I=j2(I,_5({x:o.x,y:o.y},.4)))}if(g.pcb_trace_id&&!e){const t=A.tracesById.get(g.pcb_trace_id);t?.route&&(I=j2(I,$oo(t.route)))}if(g.pcb_via_ids)for(const t of g.pcb_via_ids){const o=A.viasById.get(t);o&&(I=j2(I,_5({x:o.x,y:o.y},Math.max((o.outer_diameter??.5)/2,.28))))}if(g.pcb_component_id&&!e&&(I=j2(I,F2I(A.componentsById.get(g.pcb_component_id)))),g.pcb_component_ids&&!e)for(const t of g.pcb_component_ids)I=j2(I,F2I(A.componentsById.get(t)));return I},P2I=({bounds:g,width:A,height:I})=>{const e={x:(g.minX+g.maxX)/2,y:(g.minY+g.maxY)/2},t=Math.max(g.maxX-g.minX,.8)+1.4,o=Math.max(g.maxY-g.minY,.8)+1.4,B=Math.min(A/t,I/o,240)*.92;return bw(qc(A/2,I/2),GJ(B,-B,0,0),qc(-e.x,-e.y))},BBo=g=>{const A=new Set;g.pcb_trace_id&&A.add(g.pcb_trace_id);for(const I of g.pcb_port_ids??[])A.add(I);for(const I of g.pcb_via_ids??[])A.add(I);g.pcb_component_id&&A.add(g.pcb_component_id);for(const I of g.pcb_component_ids??[])A.add(I);return[...A]},CZ=(g,A)=>{const I=["pcb_trace_error_id","pcb_via_clearance_error_id","pcb_component_outside_board_error_id","source_failed_to_create_component_error_id","pcb_error_id"];for(const e of I)if(typeof g?.[e]=="string"&&g[e].length>0)return g[e];for(const[e,t]of Object.entries(g??{}))if(e.endsWith("_error_id")&&typeof t=="string"&&t.length>0)return t;return`error_${A}_${g?.error_type}_${g?.message?.slice(0,20)}`},K2I=(g,A)=>A?g.find((I,e)=>I.type?.includes("error")?CZ(I,e)===A:!1)??null:null,CBo=g=>1-(1-g)**3,QBo=(g,A,I)=>({a:g.a+(A.a-g.a)*I,b:g.b+(A.b-g.b)*I,c:g.c+(A.c-g.c)*I,d:g.d+(A.d-g.d)*I,e:g.e+(A.e-g.e)*I,f:g.f+(A.f-g.f)*I}),L2I=g=>{g!==null&&window.cancelAnimationFrame(g)},iBo=({startTransform:g,endTransform:A,durationMs:I,onUpdate:e,setAnimationFrameId:t,onComplete:o})=>{const B=performance.now(),C=i=>{const E=i-B,n=Math.min(1,E/I),s=CBo(n);if(e(QBo(g,A,s)),n<1){t(window.requestAnimationFrame(C));return}t(null),o?.()},Q=window.requestAnimationFrame(C);return t(Q),Q},ZwA=g=>g?.trim()||null;function Y2I(g){const A=new Map,I=new Map;for(const e of g)e.type==="source_net"?A.set(e.source_net_id,e):e.type==="source_trace"&&I.set(e.source_trace_id,e);return{sourceNetById:A,sourceTraceById:I}}function aeg({primitiveElement:g,traceOverlayElementIndex:A}){const I=g.source_trace_id;if(!I)return null;const e=A.sourceTraceById.get(I),t=ZwA(e?.name);if(t)return t;const o=A.sourceNetById.get(I),B=ZwA(o?.name);if(B)return B;for(const C of e?.connected_source_net_ids??[]){const Q=ZwA(A.sourceNetById.get(C)?.name);if(Q)return Q}return null}function _2I({primitiveElement:g,traceOverlayElementIndex:A}){const I=g.source_trace_id,e=I?A.sourceTraceById.get(I):void 0,t=g.trace_length,o=typeof t=="number",B=e?.max_length,C=o?`${t.toFixed(3)}${typeof B=="number"?` / ${B}`:""} mm`:"",Q=aeg({primitiveElement:g,traceOverlayElementIndex:A})??ZwA(e?.display_name);if(!C&&!Q)return null;const i=!!(o&&typeof B=="number"&&t>B);return{text:C,name:Q,isOverLength:i}}function QZ(g,A){if(!g)return;const I=[];for(const e of[`${g.type}_id`,"pcb_port_id","pcb_trace_id","source_trace_id","source_net_id"]){const t=g[e];typeof t=="string"&&I.push(t)}for(const e of I){const t=A.getNetConnectedToId(e);if(t)return t}if("source_net_id"in g)return g.source_net_id}function b2I(g){return g&&["pcb_trace","pcb_smtpad","pcb_plated_hole","pcb_via","pcb_copper_pour"].includes(g.type)}function EBo(g,A,I){const e=Y2I(A),t=g.type==="pcb_trace"?aeg({primitiveElement:g,traceOverlayElementIndex:e}):null;if(t)return t;const o=QZ(g,I),B=o?A.filter(C=>QZ(C,I)===o):[];for(const C of["source_net","source_trace"])for(const Q of B)if(Q.type===C&&"name"in Q&&typeof Q.name=="string"&&Q.name.trim())return Q.name.trim();if(g.type==="pcb_trace"){const C=_2I({primitiveElement:g,traceOverlayElementIndex:e})?.name;if(C)return C}for(const C of B)if(C.type==="source_trace"&&C.display_name?.trim())return C.display_name.trim();return"Net"}function nBo(g,A,I){return A.flatMap(e=>{if(e.type!=="source_bus")return[];const t=[...new Set(e.source_trace_ids.flatMap(o=>{const B=I.getNetConnectedToId(o);return B?[B]:[]}))];return t.includes(g)?[{id:e.source_bus_id,name:e.name?.trim()||"Bus",netIds:t}]:[]})}var sBo=(g,A)=>{if(g?.type!=="pcb_smtpad"&&g?.type!=="pcb_plated_hole")return;const I=A.find(t=>t.type==="pcb_component"&&t.pcb_component_id===g.pcb_component_id);if(I?.type!=="pcb_component")return;const e=A.find(t=>t.type==="source_component"&&t.source_component_id===I.source_component_id);if(e?.type==="source_component")return{source_component_id:e.source_component_id,pcb_component_id:I.pcb_component_id,refdes:e.name,manufacturer_part_number:e.manufacturer_part_number}},ho={board:{anchor:"rgb(255, 38, 226)",aux_items:"rgb(255, 255, 255)",b_adhes:"rgb(0, 0, 132)",b_crtyd:"rgb(38, 233, 255)",b_fab:"rgb(88, 93, 132)",b_mask:"rgba(2, 255, 238, 0.400)",b_paste:"rgb(0, 194, 194)",b_silks:"rgb(242, 237, 161)",background:"rgb(0, 16, 35)",cmts_user:"rgb(89, 148, 220)",copper:{b:"rgb(77, 127, 196)",f:"rgb(200, 52, 52)",in1:"rgb(127, 200, 127)",in10:"rgb(237, 124, 51)",in11:"rgb(91, 195, 235)",in12:"rgb(247, 111, 142)",in13:"rgb(167, 165, 198)",in14:"rgb(40, 204, 217)",in15:"rgb(232, 178, 167)",in16:"rgb(242, 237, 161)",in17:"rgb(237, 124, 51)",in18:"rgb(91, 195, 235)",in19:"rgb(247, 111, 142)",in2:"rgb(206, 125, 44)",in20:"rgb(167, 165, 198)",in21:"rgb(40, 204, 217)",in22:"rgb(232, 178, 167)",in23:"rgb(242, 237, 161)",in24:"rgb(237, 124, 51)",in25:"rgb(91, 195, 235)",in26:"rgb(247, 111, 142)",in27:"rgb(167, 165, 198)",in28:"rgb(40, 204, 217)",in29:"rgb(232, 178, 167)",in3:"rgb(79, 203, 203)",in30:"rgb(242, 237, 161)",in4:"rgb(219, 98, 139)",in5:"rgb(167, 165, 198)",in6:"rgb(40, 204, 217)",in7:"rgb(232, 178, 167)",in8:"rgb(242, 237, 161)",in9:"rgb(141, 203, 129)"},cursor:"rgb(255, 255, 255)",drc:"rgb(194, 194, 194)",drc_error:"rgba(215, 91, 107, 0.800)",drc_exclusion:"rgb(255, 255, 255)",drc_warning:"rgba(255, 208, 66, 0.902)",dwgs_user:"rgb(194, 194, 194)",eco1_user:"rgb(180, 219, 210)",eco2_user:"rgb(216, 200, 82)",edge_cuts:"rgb(208, 210, 205)",f_adhes:"rgb(132, 0, 132)",f_crtyd:"rgb(255, 0, 245)",f_fab:"rgb(175, 175, 175)",f_mask:"rgba(216, 100, 255, 0.400)",f_paste:"rgba(180, 160, 154, 0.902)",f_silks:"rgb(242, 237, 161)",footprint_text_back:"rgb(0, 0, 132)",footprint_text_front:"rgb(194, 194, 194)",footprint_text_invisible:"rgb(132, 132, 132)",grid:"rgb(132, 132, 132)",grid_axes:"rgb(194, 194, 194)",margin:"rgb(255, 38, 226)",microvia:"rgb(0, 132, 132)",no_connect:"rgb(0, 0, 132)",pad_back:"rgb(77, 127, 196)",pad_front:"rgb(200, 52, 52)",pad_plated_hole:"rgb(194, 194, 0)",pad_through_hole:"rgb(227, 183, 46)",plated_hole:"rgb(26, 196, 210)",ratsnest:"rgba(245, 255, 213, 0.702)",select_overlay:"rgb(4, 255, 67)",soldermaskWithCopper:{top:"rgb(18, 82, 50)",bottom:"rgb(77, 127, 196)"},soldermask:{top:"rgb(12, 55, 33)",bottom:"rgb(12, 55, 33)"},through_via:"rgb(236, 236, 236)",user_1:"rgb(194, 194, 194)",user_2:"rgb(89, 148, 220)",user_3:"rgb(180, 219, 210)",user_4:"rgb(216, 200, 82)",user_5:"rgb(194, 194, 194)",user_6:"rgb(89, 148, 220)",user_7:"rgb(180, 219, 210)",user_8:"rgb(216, 200, 82)",user_9:"rgb(232, 178, 167)",via_blind_buried:"rgb(187, 151, 38)",via_hole:"rgb(227, 183, 46)",via_micro:"rgb(0, 132, 132)",via_through:"rgb(236, 236, 236)",worksheet:"rgb(200, 114, 171)"}},yk=(g,A=1)=>{if(Math.abs(g.a)!==Math.abs(g.d))throw new Error("Cannot scale non-uniformly");return A*Math.abs(g.a)},EeA={red:"red",black:"black",green:"green",board:"rgb(255, 255, 255)",other:"#eee",top:ho.board.copper.f,inner1:ho.board.copper.in1,inner2:ho.board.copper.in2,inner3:ho.board.copper.in3,inner4:ho.board.copper.in4,inner5:ho.board.copper.in5,inner6:ho.board.copper.in6,inner7:ho.board.copper.in7,inner8:ho.board.copper.in8,bottom:ho.board.copper.b,drill:ho.board.anchor,keepout:ho.board.background,tkeepout:ho.board.b_crtyd,tplace:ho.board.b_silks,top_courtyard:ho.board.f_crtyd,bottom_courtyard:ho.board.b_crtyd,top_silkscreen:ho.board.f_silks,bottom_silkscreen:ho.board.b_silks,top_fabrication:ho.board.f_fab,bottom_fabrication:ho.board.b_fab,soldermask_top:ho.board.soldermask.top,soldermask_bottom:ho.board.soldermask.bottom,soldermask_with_copper_top:ho.board.soldermaskWithCopper.top,soldermask_with_copper_bottom:ho.board.soldermaskWithCopper.bottom,bottom_notes:ho.board.user_2,top_notes:ho.board.user_2,...ho.board},aBo=["board","bottom","soldermask_bottom","bottom_silkscreen","top","soldermask_top","bottom_courtyard","bottom_fabrication","top_courtyard","top_fabrication","edge_cuts","top_silkscreen"],rBo=class{canvasLayerMap;ctxLayerMap;aperture;transform;foregroundLayer="top";hiddenLayerOpacity=.2;xRayNetActive=!1;lastPoint;constructor(g){this.canvasLayerMap=g,this.ctxLayerMap=Object.fromEntries(Object.entries(g).map(([A,I])=>[A,I.getContext("2d")])),this.transform=uJ(),this.transform.d*=-1,this.transform=bw(this.transform,qc(0,-500)),this.lastPoint={x:0,y:0},this.equip({})}clear(){for(const g of Object.values(this.ctxLayerMap))g.clearRect(0,0,g.canvas.width,g.canvas.height)}equip(g){this.aperture={fontSize:0,shape:"circle",mode:"add",size:0,color:"red",layer:"top",opacity:this.foregroundLayer===g.color?1:.5,...g}}drawMeshPattern(g,A,I,e,t,o=45){const B=this.getLayerCtx(),[C,Q]=Mt(this.transform,[g,A]),[i,E]=Mt(this.transform,[g+I,A+e]),n=yk(this.transform,t);B.lineWidth=1,B.strokeStyle=this.aperture.color;const s=r=>{const a=Math.sin(r),c=Math.cos(r),h=Math.sqrt((i-C)**2+(E-Q)**2);for(let l=-h;l<=h;l+=n)B.beginPath(),B.moveTo(C+l*c-h*a,Q+l*a+h*c),B.lineTo(C+l*c+h*a,Q+l*a-h*c),B.stroke()};s(o*Math.PI/180),s((o+90)*Math.PI/180)}rect({x:g,y:A,w:I,h:e,mesh_fill:t,is_filled:o=!0,has_stroke:B,is_stroke_dashed:C,stroke_width:Q,roundness:i}){const[E,n]=Mt(this.transform,[g-I/2,A-e/2]),[s,r]=Mt(this.transform,[g+I/2,A+e/2]);this.applyAperture();const a=this.getLayerCtx(),c=i?yk(this.transform,i):0,h=B===void 0?o===!1:B;if(t)a.save(),a.beginPath(),c>0&&a.roundRect?a.roundRect(E,n,s-E,r-n,c):a.rect(E,n,s-E,r-n),a.clip(),this.drawMeshPattern(g-I/2,A-e/2,I,e,.15),a.restore(),c>0&&a.roundRect?(a.beginPath(),a.roundRect(E,n,s-E,r-n,c),a.stroke()):a.strokeRect(E,n,s-E,r-n);else if(o!==!1&&(c>0&&a.roundRect?(a.beginPath(),a.roundRect(E,n,s-E,r-n,c),a.fill()):a.fillRect(E,n,s-E,r-n)),h){const l=a.lineWidth;if(Q!==void 0&&(a.lineWidth=yk(this.transform,Q)),C){let D=[];const d=Math.abs(this.transform.a);if(d>0){const w=.1*d,u=w*1.3;w>.5&&(D=[w,u])}a.setLineDash(D)}c>0&&a.roundRect?(a.beginPath(),a.roundRect(E,n,s-E,r-n,c),a.stroke()):a.strokeRect(E,n,s-E,r-n),C&&a.setLineDash([]),Q!==void 0&&(a.lineWidth=l)}}rotatedRect(g,A,I,e,t,o,B){const C=this.getLayerCtx();this.applyAperture();const[Q,i]=Mt(this.transform,[g-I/2,A-e/2]),[E,n]=Mt(this.transform,[g+I/2,A+e/2]),s=o?yk(this.transform,o):0;C.save();const[r,a]=Mt(this.transform,[g,A]);C.translate(r,a);const c=360-t;t&&C.rotate(c*Math.PI/180),C.translate(-r,-a),B?(C.beginPath(),s>0&&C.roundRect?C.roundRect(Q,i,E-Q,n-i,s):C.rect(Q,i,E-Q,n-i),C.clip(),this.drawMeshPattern(g-I/2,A-e/2,I,e,.15),s>0&&C.roundRect?(C.beginPath(),C.roundRect(Q,i,E-Q,n-i,s),C.stroke()):C.strokeRect(Q,i,E-Q,n-i)):s>0&&C.roundRect?(C.beginPath(),C.roundRect(Q,i,E-Q,n-i,s),C.fill()):C.fillRect(Q,i,E-Q,n-i),C.restore()}rotatedPill(g,A,I,e,t){const o=this.getLayerCtx();this.applyAperture(),o.save();const[B,C]=Mt(this.transform,[g,A]);o.translate(B,C);const Q=360-t;t&&o.rotate(Q*Math.PI/180),o.translate(-B,-C),this.pill(g,A,I,e),o.restore()}circle(g,A,I,e,t=!0){const o=yk(this.transform,I),[B,C]=Mt(this.transform,[g,A]);this.applyAperture();const Q=this.getLayerCtx();e?(Q.save(),Q.beginPath(),Q.arc(B,C,o,0,2*Math.PI),Q.clip(),this.drawMeshPattern(g-I,A-I,I*2,I*2,.15),Q.restore(),Q.beginPath(),Q.arc(B,C,o,0,2*Math.PI),Q.stroke()):(Q.beginPath(),Q.arc(B,C,o,0,2*Math.PI),Q.fill())}oval(g,A,I,e){const t=yk(this.transform,I),o=yk(this.transform,e),[B,C]=Mt(this.transform,[g,A]);this.applyAperture();const Q=this.getLayerCtx();Q.beginPath(),Q.ellipse(B,C,t,o,0,0,2*Math.PI),Q.fill(),Q.closePath()}pill(g,A,I,e){const[t,o]=Mt(this.transform,[g-I/2,A+e/2]),B=yk(this.transform,I),C=yk(this.transform,e),Q=Math.min(B,C)/2;this.applyAperture();const i=this.getLayerCtx();i.beginPath(),i.arc(t+Q,o+Q,Q,Math.PI,Math.PI*1.5),i.arc(t+B-Q,o+Q,Q,Math.PI*1.5,0),i.arc(t+B-Q,o+C-Q,Q,0,Math.PI*.5),i.arc(t+Q,o+C-Q,Q,Math.PI*.5,Math.PI),i.fill(),i.closePath()}polygon(g){if(g.length<3)return;this.applyAperture();const A=this.getLayerCtx(),I=g.map(t=>Mt(this.transform,[t.x,t.y]));A.beginPath(),A.moveTo(I[0][0],I[0][1]);for(let t=1;t<I.length;t++)A.lineTo(I[t][0],I[t][1]);A.closePath(),A.fill("evenodd");const e=yk(this.transform,this.aperture.size);e>0&&(A.lineWidth=e,A.stroke())}debugText(g,A,I){const[e,t]=Mt(this.transform,[A,I]);this.applyAperture();const o=this.getLayerCtx();o.font="10px sans-serif",o.fillText(g,e,t)}getLayerCtx(){const g=this.ctxLayerMap[this.aperture.layer];if(!g)throw new Error(`No context for layer "${this.aperture.layer}"`);return g}getLayerOpacity(g){if(this.xRayNetActive)return/^(top|bottom|inner\d+)$/.test(g)?this.hiddenLayerOpacity:0;const A=this.foregroundLayer,I=(A==="top"||A==="bottom")&&(g.startsWith(`${A}_`)||g.endsWith(`_${A}`)),e=["board","drill","edge_cuts","other"].includes(g);return g===A||I||e?1:this.hiddenLayerOpacity}orderAndFadeLayers(){const{canvasLayerMap:g,foregroundLayer:A}=this,e=["board",...Object.keys(g).filter(n=>/^inner\d+$/.test(n)).sort((n,s)=>Number(s.slice(5))-Number(n.slice(5))),...aBo.filter(n=>n!=="board")],t=A==="top"?"soldermask_top":A==="bottom"?"soldermask_bottom":void 0,o=A==="top"?"top_silkscreen":A==="bottom"?"bottom_silkscreen":void 0,B=A==="top"?"top_notes":A==="bottom"?"bottom_notes":void 0,C=A==="top"?"top_fabrication":A==="bottom"?"bottom_fabrication":void 0,Q=A==="top"?"top_courtyard":A==="bottom"?"bottom_courtyard":void 0,i=[A,"edge_cuts",...t?[t]:[],...o?[o]:[],...B?[B]:[],...C?[C]:[],...Q?[Q]:[]],E=[...e.filter(n=>!i.includes(n)),...A==="drill"?[]:[A],...t?[t]:[],"edge_cuts",...o?[o]:[],...B?[B]:[],...C?[C]:[],...Q?[Q]:[],"drill"];E.forEach((n,s)=>{const r=g[n];r&&(r.style.zIndex=`${da.topLayer-(E.length-s)}`)});for(const[n,s]of Object.entries(g)){const r=this.getLayerOpacity(n);s.style.opacity=String(r),s.style.display=r===0?"none":""}}applyAperture(){const{transform:g,aperture:A}=this;let{size:I,mode:e,color:t,fontSize:o,layer:B}=A;B in this.ctxLayerMap||(this.aperture.layer="other");const C=this.getLayerCtx();if(!C)throw new Error(`No context for layer "${this.foregroundLayer}"`);if(t||(t="undefined"),C.lineWidth=yk(g,I),C.lineCap="round",e==="add"){C.globalCompositeOperation="source-over";let Q=EeA[t.toLowerCase()];if(!Q)try{Q=uQ(t).rgb().toString()}catch{console.warn(`Invalid color format: '${t}'`),Q="white"}C.fillStyle=Q,C.strokeStyle=Q}else C.globalCompositeOperation="destination-out",C.fillStyle="rgba(0,0,0,1)",C.strokeStyle="rgba(0,0,0,1)";C.font=`${yk(Nx(g),o)}px sans-serif`}moveTo(g,A){this.lastPoint={x:g,y:A}}lineTo(g,A){const[I,e]=Mt(this.transform,[g,A]),{size:t,shape:o,mode:B}=this.aperture,C=yk(this.transform,t),{lastPoint:Q}=this,i=Mt(this.transform,Q);this.applyAperture();const E=this.getLayerCtx();o==="square"&&E.fillRect(i.x-C/2,i.y-C/2,C,C),E.beginPath(),E.moveTo(i.x,i.y),E.lineTo(I,e),E.stroke(),E.closePath(),o==="square"&&E.fillRect(I-C/2,e-C/2,C,C),this.lastPoint={x:g,y:A}}polygonWithArcs(g){const A=this.getLayerCtx(),I=e=>{if(e.vertices.length===0)return;const t=e.vertices[0],o=Mt(this.transform,[t.x,t.y]);A.moveTo(o[0],o[1]);for(let B=0;B<e.vertices.length;B++){const C=e.vertices[B],Q=e.vertices[(B+1)%e.vertices.length];if(C.bulge&&C.bulge!==0){const i=C.bulge,E=Q.x-C.x,n=Q.y-C.y,s=Math.sqrt(E*E+n*n);if(s<1e-9){const R=Mt(this.transform,[Q.x,Q.y]);A.lineTo(R[0],R[1]);continue}const r=4*Math.atan(i),a=Math.abs(s/(2*Math.sin(r/2))),c=(C.x+Q.x)/2,h=(C.y+Q.y)/2,l=E/s,d=-(n/s),y=l,w=Math.sqrt(Math.max(0,a*a-(s/2)**2)),u=c+w*d*Math.sign(i),G=h+w*y*Math.sign(i),m=Math.atan2(C.y-G,C.x-u);let p=Math.atan2(Q.y-G,Q.x-u);i>0&&p<m?p+=2*Math.PI:i<0&&p>m&&(p-=2*Math.PI);const k=Mt(this.transform,[u,G]),S=yk(this.transform,a);A.arc(k[0],k[1],S,-m,-p,i>0)}else{const i=Mt(this.transform,[Q.x,Q.y]);A.lineTo(i[0],i[1])}}A.closePath()};if(A.beginPath(),I(g.outer_ring),g.inner_rings)for(const e of g.inner_rings)I(e);A.fill("evenodd")}},cBo=(g=2)=>{const A=Math.max(2,Math.min(10,Math.floor(g)));return["top",...Array.from({length:A-2},(I,e)=>`inner${e+1}`),"bottom"]},OwA=g=>{const A=g.find(I=>I.type==="pcb_board");return cBo(A?.num_layers??2)},reg=g=>`${g}_copper`,H2I=g=>g.map(A=>A.endsWith("_copper")?A.slice(0,-7):A),hBo=g=>["board","bottom","soldermask_bottom","bottom_silkscreen","top","soldermask_top","soldermask_with_copper_bottom","soldermask_with_copper_top","top_fabrication","bottom_fabrication",...OwA(g).filter(I=>I.startsWith("inner")),"drill","edge_cuts","bottom_notes","top_notes","top_silkscreen","top_courtyard","bottom_courtyard","other"],lBo=(g,A)=>{const I=OwA(g).reverse();return[...I.filter(e=>e!==A),...I.filter(e=>e===A)]},DBo={...Lw,courtyard:{top:ho.board.f_crtyd,bottom:ho.board.b_crtyd}};function dBo(g){return g.type==="pcb_courtyard_circle"||g.type==="pcb_courtyard_rect"||g.type==="pcb_courtyard_outline"}function v2I({canvas:g,elements:A,layers:I,realToCanvasMat:e}){const t=new XE(g);t.configure({colorOverrides:DBo}),t.realToCanvasMat=e;const o=A.filter(dBo);t.drawElements(o,{layers:I})}var yBo={...Lw,silkscreen:{top:ho.board.f_fab,bottom:ho.board.b_fab}};function wBo(g){return g.type.includes("pcb_fabrication_note")}function q2I({canvas:g,elements:A,layers:I,realToCanvasMat:e}){const t=new XE(g);t.configure({colorOverrides:yBo}),t.realToCanvasMat=e;const o=A.filter(wBo);t.drawElements(o,{layers:I})}function uBo(g){return g.type==="pcb_hole"}function GBo({canvas:g,elements:A,layers:I,realToCanvasMat:e,drawSoldermask:t}){const o=new XE(g);o.realToCanvasMat=e;const B=A.filter(uBo);o.drawElements(B,{layers:I,drawSoldermask:t})}function mBo(g){return g.type==="pcb_board"}function T2I({canvas:g,elements:A,layers:I,realToCanvasMat:e,drawSoldermask:t}){const o=new XE(g);o.realToCanvasMat=e;const B=A.filter(mBo);for(const C of B)o.drawElements([C],{layers:I,drawSoldermask:!1,drawBoardMaterial:t??!1,minBoardOutlineStrokePx:2})}function pBo(g){return g.type==="pcb_copper_text"}function kBo({canvas:g,elements:A,layers:I,realToCanvasMat:e}){const t=A.filter(pBo);if(t.length===0)return;const o=new XE(g);o.realToCanvasMat=e,o.drawElements(t,{layers:I})}function MBo(g){return g.type==="pcb_cutout"}function SBo({canvas:g,elements:A,layers:I,realToCanvasMat:e}){const t=new XE(g);t.realToCanvasMat=e;const o=A.filter(MBo);t.drawElements(o,{layers:I})}function fBo(g){return g.type==="pcb_keepout"}function RBo({elements:g,layer:A}){return g.filter(fBo).filter(I=>I.layers.includes(A))}function NBo(g){return uQ(EeA[g]).lighten(.4).hex()}function xBo({canvas:g,elements:A,layer:I,realToCanvasMat:e}){const t=RBo({elements:A,layer:I});if(t.length===0)return;const o=new XE(g),B=NBo(I);o.configure({colorOverrides:{keepout:{top:B,bottom:B}}}),o.realToCanvasMat=e,o.drawElements(t,{layers:[reg(I)]})}function FBo(g){return g.type.startsWith("pcb_note_")}function Z2I({canvas:g,elements:A,layers:I,realToCanvasMat:e}){const t=new XE(g);t.realToCanvasMat=e;const o=A.filter(FBo);t.drawElements(o,{layers:I})}function UBo(g){return g.type==="pcb_panel"}function JBo({canvas:g,elements:A,layers:I,realToCanvasMat:e,drawSoldermask:t}){const o=new XE(g);o.realToCanvasMat=e;const B=A.filter(UBo);for(const C of B)o.drawElements([C],{layers:I})}var PBo={...Lw,copper:{...Lw.copper,top:uQ(ho.board.pad_front).lighten(.5).toString(),bottom:uQ(ho.board.pad_back).lighten(.5).toString(),inner1:uQ(ho.board.copper.in1).lighten(.5).toString(),inner2:uQ(ho.board.copper.in2).lighten(.5).toString(),inner3:uQ(ho.board.copper.in3).lighten(.5).toString(),inner4:uQ(ho.board.copper.in4).lighten(.5).toString(),inner5:uQ(ho.board.copper.in5).lighten(.5).toString(),inner6:uQ(ho.board.copper.in6).lighten(.5).toString(),inner7:uQ(ho.board.copper.in7).lighten(.5).toString(),inner8:uQ(ho.board.copper.in8).lighten(.5).toString()}};function KBo(g){return g.type==="pcb_smtpad"}function O2I({canvas:g,elements:A,layers:I,realToCanvasMat:e,primitives:t,drawSoldermask:o}){const B=new Set(H2I(I)),C=A.filter(KBo).filter(n=>B.has(n.layer));if(C.length===0)return;const Q=new Set;if(t)for(const n of t)(n.is_mouse_over||n.is_in_highlighted_net)&&n._element?.type==="pcb_smtpad"&&Q.add(n._element.pcb_smtpad_id);const i=C.filter(n=>Q.has(n.pcb_smtpad_id)),E=C.filter(n=>!Q.has(n.pcb_smtpad_id));if(E.length>0){const n=new XE(g);n.realToCanvasMat=e,n.drawElements(E,{layers:I,drawSoldermask:o})}if(i.length>0){const n=new XE(g);n.configure({colorOverrides:PBo}),n.realToCanvasMat=e,n.drawElements(i,{layers:I,drawSoldermask:o})}}var LBo={...Lw,copper:Object.fromEntries(Object.entries(Lw.copper).map(([g,A])=>[g,uQ(A).lighten(.5).toString()]))};function YBo(g){return g.type==="pcb_trace"}var _Bo=(g,A)=>{const I=g.route.filter(o=>o.route_type==="wire"&&"layer"in o&&A.has(o.layer)?!0:o.route_type==="via"?A.has(o.from_layer)||A.has(o.to_layer):!1),e=I.filter(o=>o.route_type==="wire").length,t=I.some(o=>o.route_type==="via");return e<2&&!t?null:{...g,route:I}},bBo=g=>({...g,route:g.route.map(A=>!("is_inside_copper_pour"in A)||A.is_inside_copper_pour!==!0?A:{...A,is_inside_copper_pour:!1})}),HBo=(g,A)=>A?g:g.filter(I=>I.type!=="pcb_copper_pour"),vBo=({primitives:g})=>{const A=new Set;for(const I of g)(I.is_mouse_over||I.is_in_highlighted_net)&&I._element?.type==="pcb_trace"&&A.add(I._element.pcb_trace_id);return A};function W2I({canvas:g,elements:A,layers:I,realToCanvasMat:e,primitives:t,showCopperPours:o}){const B=new Set(H2I(I)),C=A.filter(YBo).map(s=>_Bo(s,B)).filter(s=>s!==null).map(s=>o?s:bBo(s));if(C.length===0)return;const Q=vBo({primitives:t??[]}),i=[],E=[];for(const s of C)Q.has(s.pcb_trace_id)?i.push(s):E.push(s);const n=HBo(A,o);if(E.length>0){const s=new XE(g);s.realToCanvasMat=e,s.drawElements(E,{layers:I,clipContextElements:n})}if(i.length>0){const s=new XE(g);s.configure({colorOverrides:LBo}),s.realToCanvasMat=e,s.drawElements(i,{layers:I,clipContextElements:n})}}var qBo={...Lw,copper:{...Lw.copper,top:uQ(ho.board.pad_front).lighten(.5).toString(),bottom:uQ(ho.board.pad_back).lighten(.5).toString(),inner1:uQ(ho.board.copper.in1).lighten(.5).toString(),inner2:uQ(ho.board.copper.in2).lighten(.5).toString(),inner3:uQ(ho.board.copper.in3).lighten(.5).toString(),inner4:uQ(ho.board.copper.in4).lighten(.5).toString(),inner5:uQ(ho.board.copper.in5).lighten(.5).toString(),inner6:uQ(ho.board.copper.in6).lighten(.5).toString(),inner7:uQ(ho.board.copper.in7).lighten(.5).toString(),inner8:uQ(ho.board.copper.in8).lighten(.5).toString()}};function TBo(g){return g.type==="pcb_plated_hole"}function V2I({canvas:g,elements:A,layers:I,realToCanvasMat:e,primitives:t,drawSoldermask:o}){const B=A.filter(TBo);if(B.length===0)return;const C=new Set;if(t)for(const E of t)(E.is_mouse_over||E.is_in_highlighted_net)&&E._element?.type==="pcb_plated_hole"&&C.add(E._element.pcb_plated_hole_id);const Q=B.filter(E=>C.has(E.pcb_plated_hole_id)),i=B.filter(E=>!C.has(E.pcb_plated_hole_id));if(i.length>0){const E=new XE(g);E.realToCanvasMat=e,E.drawElements(i,{layers:I,drawSoldermask:o})}if(Q.length>0){const E=new XE(g);E.configure({colorOverrides:qBo}),E.realToCanvasMat=e,E.drawElements(Q,{layers:I,drawSoldermask:o})}}function j2I(g){const{lines:A,anchorPoint:I,ccwRotation:e}=g;if(!e)return A;const t=e*Math.PI/180,o=JMI(t),B=bw(qc(I.x,I.y),o,qc(-I.x,-I.y));return Mt(B,I),A.map(C=>({...C,x1:Mt(B,{x:C.x1,y:C.y1}).x,y1:Mt(B,{x:C.x1,y:C.y1}).y,x2:Mt(B,{x:C.x2,y:C.y2}).x,y2:Mt(B,{x:C.x2,y:C.y2}).y}))}var ZBo=.6,z2I=.2,X2I=g=>{const A=g.size*.7,I=A*ZBo,e=A*z2I,t=A*z2I,o=g.text.split(/\r?\n/),B=g.text.length>0&&A>0,C=B?o.length:0,Q=B?o.map(n=>n.length===0?0:n.length*I+(n.length-1)*e):[],i=Q.length>0?Math.max(...Q):0,E=C>0?C*A+(C-1)*t:0;return{text_lines:o,line_count:C,line_widths:Q,target_height:A,target_width_char:I,space_between_chars:e,space_between_lines:t,width:i,height:E}},$2I=g=>{const A=X2I(g);return{width:A.width,height:A.height,lineHeight:A.target_height,lineSpacing:A.space_between_lines,lineCount:A.line_count}},AfI=g=>{const{text_lines:A,line_count:I,line_widths:e,target_height:t,target_width_char:o,space_between_chars:B,space_between_lines:C,width:Q}=X2I(g);if(t<=0||I===0)return[];const i=t/12,E=[];for(let n=0;n<I;n++){const s=-n*(t+C),r=e[n],a=(Q-r)/2;let c=g.x+a;for(let h=0;h<A[n].length;h++){const l=A[n][h],D=nU[l]??nU[l.toUpperCase()];if(!D){c+=o+B;continue}for(const{x1:d,y1:y,x2:w,y2:u}of D)E.push({_pcb_drawing_object_id:LR("line"),pcb_drawing_type:"line",x1:c+o*d,y1:g.y+s+t*y,x2:c+o*w,y2:g.y+s+t*u,width:i,layer:g.layer,unit:g.unit,color:g.color});c+=o+B}}return E};function Lx(g){const I=g.color??EeA[g.layer];let e=uQ(I);return g._element?.type==="pcb_copper_pour"&&(e=e.alpha(.7)),g.is_mouse_over||g.is_in_highlighted_net?e.lighten(.5).rgb().toString():e.rgb().toString()}var gfI=(g,A)=>{g.equip({size:A.zoomIndependent?A.width/g.transform.a:A.width,shape:A.squareCap?"square":"circle",color:Lx(A),layer:A.layer}),g.moveTo(A.x1,A.y1),g.lineTo(A.x2,A.y2)},OBo=(g,A,I)=>{switch(I){case"top_left":return{x:0,y:-A};case"top_center":return{x:-g/2,y:-A};case"top_right":return{x:-g,y:-A};case"center_left":return{x:0,y:-A/2};case"center":return{x:-g/2,y:-A/2};case"center_right":return{x:-g,y:-A/2};case"bottom_left":return{x:0,y:0};case"bottom_center":return{x:-g/2,y:0};case"bottom_right":return{x:-g,y:0};default:return{x:0,y:0}}},IfI=g=>g.layer==="bottom_silkscreen"||g.layer==="bottom"?g.is_mirrored!==!1:g.is_mirrored===!0,WBo=(g,A)=>{g.equip({fontSize:A.size,color:Lx(A),layer:A.layer});const{width:I,height:e}=$2I(A),t=OBo(I,e,A.align);A.x??=0,A.y??=0;const o={x:A.x,y:A.y};let B=AfI({...A,x:A.x+t.x,y:A.y+t.y});if(IfI(A)&&(B=B.map(C=>({...C,x1:2*A.x-C.x1,x2:2*A.x-C.x2}))),A.ccw_rotation){const C={lines:B,anchorPoint:o,ccwRotation:A.ccw_rotation};B=j2I(C)}for(const C of B)gfI(g,C)},VBo=(g,A)=>{const{width:I,height:e,lineHeight:t}=$2I(A);A.x??=0,A.y??=0;const o=A.knockout_padding??{left:A.size*.5,right:A.size*.5,top:A.size*.3,bottom:A.size*.3},B=I+o.left+o.right,C=e+o.top+o.bottom,Q=I/2,i=t-e/2,E=A.x-Q,n=A.y-i,s={x:A.x,y:A.y},r={_pcb_drawing_object_id:`knockout_rect_${A._pcb_drawing_object_id}`,x:A.x,y:A.y,w:B,h:C,layer:A.layer,ccw_rotation:A.ccw_rotation};A.ccw_rotation?tfI(g,r):efI(g,r);let a=AfI({...A,x:E,y:n});if(IfI(A)&&(a=a.map(c=>({...c,x1:2*A.x-c.x1,x2:2*A.x-c.x2}))),A.ccw_rotation){const c={lines:a,anchorPoint:s,ccwRotation:A.ccw_rotation};a=j2I(c)}for(const c of a)g.equip({size:c.width,shape:"circle",color:"black",layer:A.layer,mode:"subtract"}),g.moveTo(c.x1,c.y1),g.lineTo(c.x2,c.y2);g.equip({mode:"add"})},efI=(g,A)=>{g.equip({color:Lx(A),layer:A.layer,size:A.stroke_width}),g.rect({x:A.x,y:A.y,w:A.w,h:A.h,mesh_fill:A.mesh_fill,is_filled:A.is_filled,has_stroke:A.has_stroke,is_stroke_dashed:A.is_stroke_dashed,stroke_width:A.stroke_width,roundness:A.roundness})},tfI=(g,A)=>{g.equip({color:Lx(A),layer:A.layer}),g.rotatedRect(A.x,A.y,A.w,A.h,A.ccw_rotation,A.roundness,A.mesh_fill)},jBo=(g,A)=>{g.equip({color:Lx(A),layer:A.layer}),g.rotatedPill(A.x,A.y,A.w,A.h,A.ccw_rotation)},zBo=(g,A)=>{g.equip({color:Lx(A),layer:A.layer}),g.circle(A.x,A.y,A.r,A.mesh_fill)},XBo=(g,A)=>{g.equip({color:Lx(A),layer:A.layer}),g.oval(A.x,A.y,A.rX,A.rY)},$Bo=(g,A)=>{g.equip({color:Lx(A),layer:A.layer}),g.pill(A.x,A.y,A.w,A.h)},ACo=(g,A)=>{g.equip({color:Lx(A),layer:A.layer}),g.polygon(A.points)},gCo=(g,A)=>{g.equip({color:Lx(A),layer:A.layer}),g.polygonWithArcs(A.brep_shape)},ICo=(g,A)=>{switch(A.pcb_drawing_type){case"line":return gfI(g,A);case"text":return A.is_knockout?VBo(g,A):WBo(g,A);case"rect":return A.ccw_rotation?tfI(g,A):efI(g,A);case"circle":return zBo(g,A);case"oval":return XBo(g,A);case"pill":return A.ccw_rotation?jBo(g,A):$Bo(g,A);case"polygon":return ACo(g,A);case"polygon_with_arcs":return gCo(g,A)}},eCo=(g,A)=>{for(const I of A)ICo(g,I)},tCo={...Lw,silkscreen:{top:ho.board.f_silks,bottom:ho.board.b_silks}};function oCo(g){return g.type.includes("pcb_silkscreen")}function ofI({canvas:g,elements:A,layers:I,realToCanvasMat:e}){const t=new XE(g);t.configure({colorOverrides:tCo}),t.realToCanvasMat=e;const o=A.filter(oCo);t.drawElements(o,{layers:I})}var BCo={...Lw,copper:{...Lw.copper,top:uQ(ho.board.pad_front).lighten(.5).toString(),bottom:uQ(ho.board.pad_back).lighten(.5).toString(),inner1:uQ(ho.board.copper.in1).lighten(.5).toString(),inner2:uQ(ho.board.copper.in2).lighten(.5).toString(),inner3:uQ(ho.board.copper.in3).lighten(.5).toString(),inner4:uQ(ho.board.copper.in4).lighten(.5).toString(),inner5:uQ(ho.board.copper.in5).lighten(.5).toString(),inner6:uQ(ho.board.copper.in6).lighten(.5).toString(),inner7:uQ(ho.board.copper.in7).lighten(.5).toString(),inner8:uQ(ho.board.copper.in8).lighten(.5).toString()},soldermask:{...Lw.soldermask,top:uQ(ho.board.soldermask.top).lighten(.35).toString(),bottom:uQ(ho.board.soldermask.bottom).lighten(.35).toString()}};function BfI({canvas:g,elements:A,layers:I,realToCanvasMat:e,drawSoldermaskTop:t,drawSoldermaskBottom:o,primitives:B}){const C=new XE(g);C.realToCanvasMat=e;const Q=A.filter(s=>s.type==="pcb_board");if(C.drawElements(A,{layers:I,drawSoldermask:!0,drawSoldermaskTop:t,drawSoldermaskBottom:o,drawBoardMaterial:!1}),Q.length>1&&T2I({canvas:g,elements:Q,layers:[],realToCanvasMat:e,drawSoldermask:!1}),!B)return;const i=new Set;for(const s of B){if(!(s.is_mouse_over||s.is_in_highlighted_net))continue;const r=s._element;r?.type==="pcb_smtpad"?i.add(r.pcb_smtpad_id):r?.type==="pcb_plated_hole"?i.add(r.pcb_plated_hole_id):r?.type==="pcb_via"&&i.add(r.pcb_via_id)}if(i.size===0)return;const E=A.filter(s=>s.type==="pcb_smtpad"?i.has(s.pcb_smtpad_id):s.type==="pcb_plated_hole"?i.has(s.pcb_plated_hole_id):s.type==="pcb_via"?i.has(s.pcb_via_id):!1);if(E.length===0)return;const n=new XE(g);n.configure({colorOverrides:BCo}),n.realToCanvasMat=e,n.drawElements(E,{layers:I,clipContextElements:A,drawSoldermask:!0,drawSoldermaskTop:t,drawSoldermaskBottom:o,drawBoardMaterial:!1})}var CCo={...Lw,copper:{...Lw.copper,top:uQ(ho.board.pad_front).lighten(.5).toString(),bottom:uQ(ho.board.pad_back).lighten(.5).toString(),inner1:uQ(ho.board.copper.in1).lighten(.5).toString(),inner2:uQ(ho.board.copper.in2).lighten(.5).toString(),inner3:uQ(ho.board.copper.in3).lighten(.5).toString(),inner4:uQ(ho.board.copper.in4).lighten(.5).toString(),inner5:uQ(ho.board.copper.in5).lighten(.5).toString(),inner6:uQ(ho.board.copper.in6).lighten(.5).toString(),inner7:uQ(ho.board.copper.in7).lighten(.5).toString(),inner8:uQ(ho.board.copper.in8).lighten(.5).toString()}};function QCo(g){return g.type==="pcb_via"}function CfI({canvas:g,elements:A,layers:I,realToCanvasMat:e,primitives:t,drawSoldermask:o}){const B=A.filter(QCo).filter(E=>I.some(n=>n.includes("copper")));if(B.length===0)return;const C=new Set;if(t)for(const E of t)(E.is_mouse_over||E.is_in_highlighted_net)&&E._element?.type==="pcb_via"&&C.add(E._element.pcb_via_id);const Q=B.filter(E=>C.has(E.pcb_via_id)),i=B.filter(E=>!C.has(E.pcb_via_id));if(i.length>0){const E=new XE(g);E.realToCanvasMat=e,E.drawElements(i,{layers:I,drawSoldermask:o,drawSoldermaskTop:I.includes("top_copper"),drawSoldermaskBottom:I.includes("bottom_copper"),clipContextElements:A})}if(Q.length>0){const E=new XE(g);E.configure({colorOverrides:CCo}),E.realToCanvasMat=e,E.drawElements(Q,{layers:I,drawSoldermask:o,drawSoldermaskTop:I.includes("top_copper"),drawSoldermaskBottom:I.includes("bottom_copper"),clipContextElements:A})}}var iCo=({primitives:g,isShowingSolderMask:A,isShowingSilkscreen:I,isShowingFabricationNotes:e})=>g.filter(t=>A||!t.layer?.includes("soldermask")).filter(t=>I||!t.layer?.includes("silkscreen")).filter(t=>e||!t.layer?.includes("fabrication")).filter(t=>t.layer!=="board").filter(t=>t._element?.type!=="pcb_smtpad").filter(t=>t._element?.type!=="pcb_plated_hole"||t.layer==="drill").filter(t=>t._element?.type!=="pcb_via").filter(t=>t._element?.type!=="pcb_trace").filter(t=>t._element?.type!=="pcb_copper_text"),ECo=({primitives:g,elements:A,circuitJson:I,xRayElements:e,transform:t,grid:o,width:B=500,height:C=500,onRenderComplete:Q})=>{const i=z.useRef(null),E=z.useRef({}),n=z.useRef(Q),s=z.useRef(void 0),r=ii(u=>u.hidden_layer_opacity),a=ii(u=>u.selected_layer),c=ii(u=>u.copper_pour_opacity),h=ii(u=>u.is_showing_copper_pours),l=ii(u=>u.is_showing_solder_mask),D=ii(u=>u.is_showing_fabrication_notes),d=ii(u=>u.is_showing_pcb_notes),y=ii(u=>u.is_showing_courtyards),w=ii(u=>u.is_showing_silkscreen);return z.useEffect(()=>{n.current=Q},[Q]),z.useEffect(()=>{if(!E.current||Object.keys(E.current).length===0)return;const u=Object.fromEntries(Object.entries(E.current).filter(([S,R])=>!!R));if(Object.keys(u).length===0)return;const G=new rBo(u);t&&(G.transform=t),G.clear(),G.foregroundLayer=a,G.hiddenLayerOpacity=r,G.xRayNetActive=!!e;const m=Object.fromEntries(Object.entries(u).filter(([S])=>G.getLayerOpacity(S)>0)),p=iCo({primitives:g,isShowingSolderMask:l,isShowingSilkscreen:w,isShowingFabricationNotes:D});if(eCo(G,p.filter(S=>G.getLayerOpacity(S.layer??"other")>0)),t){const S=OwA(A).map(U=>({canvas:m[U],layer:U,copperLayer:reg(U)}));for(const{canvas:U,copperLayer:K}of S)U&&W2I({canvas:U,elements:A,layers:[K],realToCanvasMat:t,primitives:g,showCopperPours:h&&c>0});for(const{canvas:U,copperLayer:K}of S)U&&kBo({canvas:U,elements:A,layers:[K],realToCanvasMat:t});for(const{canvas:U,copperLayer:K,layer:_}of S)U&&V2I({canvas:U,elements:A,layers:[K],realToCanvasMat:t,primitives:g,drawSoldermask:l&&(_==="top"||_==="bottom")});for(const{canvas:U,copperLayer:K}of S)U&&M2I({canvas:U,elements:A,layers:[K],realToCanvasMat:t,opacity:h?c:0});for(const{canvas:U,copperLayer:K}of S)U&&O2I({canvas:U,elements:A,layers:[K],realToCanvasMat:t,primitives:g,drawSoldermask:l});for(const{canvas:U,copperLayer:K,layer:_}of S)U&&CfI({canvas:U,elements:A,layers:[K],realToCanvasMat:t,primitives:g,drawSoldermask:l&&(_==="top"||_==="bottom")});if(l){const U=a==="bottom"?"bottom":"top",K=U==="top",_=U==="bottom",b=m.soldermask_top;b&&U==="top"&&BfI({canvas:b,elements:A,layers:["top_soldermask"],realToCanvasMat:t,drawSoldermaskTop:K,drawSoldermaskBottom:_,primitives:g});const T=m.soldermask_bottom;T&&U==="bottom"&&BfI({canvas:T,elements:A,layers:["bottom_soldermask"],realToCanvasMat:t,drawSoldermaskTop:K,drawSoldermaskBottom:_,primitives:g})}const R=m.drill;if(R&&GBo({canvas:R,elements:A,layers:["drill"],realToCanvasMat:t}),w){const U=m.top_silkscreen;U&&ofI({canvas:U,elements:A,layers:["top_silkscreen"],realToCanvasMat:t});const K=m.bottom_silkscreen;K&&ofI({canvas:K,elements:A,layers:["bottom_silkscreen"],realToCanvasMat:t})}if(D){const U=m.top_fabrication;U&&q2I({canvas:U,elements:A,layers:["top_fabrication_note"],realToCanvasMat:t});const K=m.bottom_fabrication;K&&q2I({canvas:K,elements:A,layers:["bottom_fabrication_note"],realToCanvasMat:t})}if(d){const U=m.bottom_notes;U&&Z2I({canvas:U,elements:A,layers:["bottom_user_note"],realToCanvasMat:t});const K=m.top_notes;K&&Z2I({canvas:K,elements:A,layers:["top_user_note"],realToCanvasMat:t})}if(y){const U=m.top_courtyard;U&&v2I({canvas:U,elements:A,layers:["top_courtyard"],realToCanvasMat:t});const K=m.bottom_courtyard;K&&v2I({canvas:K,elements:A,layers:["bottom_courtyard"],realToCanvasMat:t})}const x=m.board;x&&(JBo({canvas:x,elements:A,layers:[],realToCanvasMat:t,drawSoldermask:l}),T2I({canvas:x,elements:A,layers:[],realToCanvasMat:t,drawSoldermask:l}));const N=m.edge_cuts;N&&SBo({canvas:N,elements:A,layers:["edge_cuts"],realToCanvasMat:t});for(const{canvas:U,layer:K}of S)U&&xBo({canvas:U,elements:A,layer:K,realToCanvasMat:t})}G.orderAndFadeLayers();const k=i.current;if(k&&t&&e){k.getContext("2d").clearRect(0,0,B,C);for(const R of lBo(A,a)){const x={canvas:k,elements:e,layers:[reg(R)],realToCanvasMat:t,drawSoldermask:!1};h&&M2I({...x,opacity:c}),W2I({...x,showCopperPours:!1}),O2I(x),V2I(x),CfI(x)}const S=new XE(k);S.realToCanvasMat=t,S.drawElements(e.filter(R=>R.type==="pcb_via"||R.type==="pcb_plated_hole"),{layers:["drill"],drawSoldermask:!1})}s.current!==I&&(s.current=I,n.current?.())},[g,A,I,e,B,C,t,a,r,c,h,l,D,d,y,w]),q.jsxs("div",{style:{backgroundColor:"black",width:B,height:C,position:"relative"},children:[q.jsx(F5.SuperGrid,{textColor:"rgba(0,255,0,0.8)",majorColor:"rgba(0,255,0,0.4)",minorColor:"rgba(0,255,0,0.2)",screenSpaceCellSize:200,width:B,height:C,transform:t,stringifyCoord:(u,G,m)=>`${F5.toMMSI(u,m)}, ${F5.toMMSI(G,m)}`}),e&&q.jsx("canvas",{ref:i,className:"pcb-x-ray-net",width:B,height:C,style:{position:"absolute",left:0,top:0,zIndex:da.topLayer,pointerEvents:"none"}}),hBo(A).filter(u=>!(!l&&u.includes("soldermask")||!w&&u.includes("silkscreen"))).map(u=>u.replace(/-/g,"")).map((u,G)=>q.jsx("canvas",{className:`pcb-layer-${u}`,ref:m=>{E.current??={},m?E.current[u]=m:delete E.current[u]},style:{position:"absolute",zIndex:G,left:0,top:0,pointerEvents:"none"},width:B,height:C},u))]})};new TextEncoder,(()=>{const g=new Uint8Array(4),A=new Uint32Array(g.buffer);return!((A[0]=1)&g[0])})();var nCo=new Uint16Array([255]),sCo=new Uint8Array(nCo.buffer);sCo[0];var aCo=new Uint16Array([255]),rCo=new Uint8Array(aCo.buffer);rCo[0],new TextDecoder("latin1");var P3=1e-9,WwA=(g,A,I)=>g>=A-P3&&g<=I+P3,cCo=g=>{const A=[];for(const I of g)A.some(e=>Math.abs(e.x-I.x)<P3&&Math.abs(e.y-I.y)<P3)||A.push(I);return A};function hCo(g,A){const{origin:I,directionVector:e}=g;if(Math.abs(e.x)<P3&&Math.abs(e.y)<P3)return null;const t=[];if(Math.abs(e.x)>=P3){const i=(A.minX-I.x)/e.x,E=I.y+i*e.y;WwA(E,A.minY,A.maxY)&&t.push({x:A.minX,y:E});const n=(A.maxX-I.x)/e.x,s=I.y+n*e.y;WwA(s,A.minY,A.maxY)&&t.push({x:A.maxX,y:s})}if(Math.abs(e.y)>=P3){const i=(A.minY-I.y)/e.y,E=I.x+i*e.x;WwA(E,A.minX,A.maxX)&&t.push({x:E,y:A.minY});const n=(A.maxY-I.y)/e.y,s=I.x+n*e.x;WwA(s,A.minX,A.maxX)&&t.push({x:s,y:A.maxY})}const o=cCo(t);if(o.length<2)return null;let B=o[0],C=o[1],Q=(B.x-C.x)**2+(B.y-C.y)**2;for(let i=0;i<o.length;i++)for(let E=i+1;E<o.length;E++){const n=o[i],s=o[E],r=(n.x-s.x)**2+(n.y-s.y)**2;r>Q&&(B=n,C=s,Q=r)}return[B,C]}function lCo(g,A,I){const e=Nx(g),t=[Mt(e,{x:0,y:0}),Mt(e,{x:A,y:0}),Mt(e,{x:0,y:I}),Mt(e,{x:A,y:I})];return{minX:Math.min(...t.map(o=>o.x)),maxX:Math.max(...t.map(o=>o.x)),minY:Math.min(...t.map(o=>o.y)),maxY:Math.max(...t.map(o=>o.y))}}var DCo=.6,dCo=1,QfI=(g,A)=>Math.hypot(g.x-A.x,g.y-A.y),ifI=g=>(g.ccwRotationDegrees??0)*Math.PI/180,yCo=g=>g.a*g.d-g.b*g.c<0?1:-1,wCo=(g,A)=>ifI(g)*yCo(A),uCo=(g,A)=>{const I=Math.cos(A),e=Math.sin(A);return{x:g.x*I-g.y*e,y:g.x*e+g.y*I}},GCo=g=>EfI(g,ifI(g)),mCo=(g,A)=>EfI(g,wCo(g,A)),EfI=(g,A)=>{const I=g.width/2,e=g.height/2;return[{x:-I,y:-e},{x:I,y:-e},{x:I,y:e},{x:-I,y:e}].map(t=>{const o=uCo(t,A);return{x:g.center.x+o.x,y:g.center.y+o.y}})},pCo=(g,A)=>{const I=mCo(g,A).map(i=>Mt(A,i)),e=Mt(A,g.center),t=QfI(I[0],I[1]),o=QfI(I[1],I[2]),B=I.length>=2?Math.atan2(I[1].y-I[0].y,I[1].x-I[0].x):0,C=B*180/Math.PI,Q=I.reduce((i,E)=>({minX:Math.min(i.minX,E.x),maxX:Math.max(i.maxX,E.x),minY:Math.min(i.minY,E.y),maxY:Math.max(i.maxY,E.y)}),{minX:1/0,maxX:-1/0,minY:1/0,maxY:-1/0});return{center:e,corners:I,width:t,height:o,angleRadians:B,angleDegrees:C,bounds:Q}},kCo=2,MCo=12,SCo=12,VwA=g=>({tip:{...g},base:{...g},leftWing:{...g},rightWing:{...g}}),nfI=(g,A,I)=>{const e=g.x-A.x,t=g.y-A.y,o=Math.hypot(e,t);if(o===0)return VwA(g);const B=e/o,Q=-(t/o)*(I/2),i=B*(I/2);return{tip:{...g},base:{...A},leftWing:{x:A.x+Q,y:A.y+i},rightWing:{x:A.x-Q,y:A.y-i}}};function sfI(g){const{start:A,end:I}=g,e=I.x-A.x,t=I.y-A.y,o=Math.hypot(e,t),B=kCo,C=MCo;if(o===0){const D=g.doubleSided?[VwA(A),VwA(A)]:[VwA(A)];return{shaftStart:{...A},shaftEnd:{...A},heads:D,shaftWidth:B,headLength:0,headWidth:C,length:o}}const Q=e/o,i=t/o,E=Math.min(SCo,o*.5),n=Math.max(E,B*2),s=g.doubleSided?o/2:o,r=Math.min(n,s),a={x:I.x-Q*r,y:I.y-i*r},c=[nfI(I,a,C)];let h={...A};const l={...a};if(g.doubleSided){const D={x:A.x+Q*r,y:A.y+i*r};c.unshift(nfI(A,D,C)),h=D}return{shaftStart:h,shaftEnd:l,heads:c,shaftWidth:B,headLength:r,headWidth:C,length:o}}function fCo(g){const A=sfI(g);return[A.shaftStart,A.shaftEnd,...A.heads.flatMap(e=>[e.tip,e.base,e.leftWing,e.rightWing])].reduce((e,t)=>({minX:Math.min(e.minX,t.x),maxX:Math.max(e.maxX,t.x),minY:Math.min(e.minY,t.y),maxY:Math.max(e.maxY,t.y)}),{minX:1/0,maxX:-1/0,minY:1/0,maxY:-1/0})}function afI(g,A,{fontSize:I=12,strokeWidth:e=2,normalPadding:t=6,alongOffset:o=0}={}){const B={x:(g.x+A.x)/2,y:(g.y+A.y)/2},C=A.x-g.x,Q=A.y-g.y,i=Math.hypot(C,Q);if(i===0)return{x:B.x+o,y:B.y-(e/2+I*.65+t),angleRadians:0,angleDegrees:0,direction:{x:1,y:0},normal:{x:0,y:-1}};let E=C/i,n=Q/i,s=-n,r=E;(E<0||E===0&&n<0)&&(E=-E,n=-n,s=-s,r=-r);const c=Math.atan2(n,E),h=e/2+I*.65+t;return{x:B.x+s*h+E*o,y:B.y+r*h+n*o,angleRadians:c,angleDegrees:c*180/Math.PI,direction:{x:E,y:n},normal:{x:s,y:r}}}var K3=["rgba(239, 68, 68, 0.8)","rgba(249, 115, 22, 0.8)","rgba(245, 158, 11, 0.8)","rgba(234, 179, 8, 0.8)","rgba(132, 204, 22, 0.8)","rgba(34, 197, 94, 0.8)","rgba(16, 185, 129, 0.8)","rgba(20, 184, 166, 0.8)","rgba(6, 182, 212, 0.8)","rgba(14, 165, 233, 0.8)","rgba(59, 130, 246, 0.8)","rgba(99, 102, 241, 0.8)","rgba(139, 92, 246, 0.8)","rgba(168, 85, 247, 0.8)","rgba(217, 70, 239, 0.8)","rgba(236, 72, 153, 0.8)","rgba(249, 168, 212, 0.8)","rgba(161, 161, 170, 0.8)"];function rfI(g,A,I,e={}){const t=e.padding??40,o=e.yFlip??!1;let B;if("center"in g){const E=g.width/2,n=g.height/2;B={minX:g.center.x-E,maxX:g.center.x+E,minY:g.center.y-n,maxY:g.center.y+n}}else B=g;const C=B.maxX-B.minX||1,Q=B.maxY-B.minY||1,i=Math.min((A-2*t)/C,(I-2*t)/Q);return bw(qc(A/2,I/2),GJ(i,o?-i:i),qc(-(B.minX+C/2),-(B.minY+Q/2)))}function RCo(g){const A=[...g.points||[],...(g.lines||[]).flatMap(I=>I.points),...(g.polygons||[]).flatMap(I=>I.points),...(g.rects||[]).flatMap(I=>GCo(I)),...(g.circles||[]).flatMap(I=>[{x:I.center.x-I.radius,y:I.center.y},{x:I.center.x+I.radius,y:I.center.y},{x:I.center.x,y:I.center.y-I.radius},{x:I.center.x,y:I.center.y+I.radius}]),...(g.arrows||[]).flatMap(I=>{const e=fCo(I);return[{x:e.minX,y:e.minY},{x:e.maxX,y:e.maxY}]}),...(g.texts||[]).flatMap(I=>{const e=I.fontSize??12,t=I.text.length*e*DCo,o=e*dCo,B=I.anchorSide??"center",C={top_left:{dx:0,dy:0},top_center:{dx:-t/2,dy:0},top_right:{dx:-t,dy:0},center_left:{dx:0,dy:-o/2},center:{dx:-t/2,dy:-o/2},center_right:{dx:-t,dy:-o/2},bottom_left:{dx:0,dy:-o},bottom_center:{dx:-t/2,dy:-o},bottom_right:{dx:-t,dy:-o}},{dx:Q,dy:i}=C[B],E=I.x+Q,n=I.y+i;return[{x:E,y:n},{x:E+t,y:n+o}]})];return A.length===0?{minX:-1,maxX:1,minY:-1,maxY:1}:A.reduce((I,e)=>({minX:Math.min(I.minX,e.x),maxX:Math.max(I.maxX,e.x),minY:Math.min(I.minY,e.y),maxY:Math.max(I.maxY,e.y)}),{minX:1/0,maxX:-1/0,minY:1/0,maxY:-1/0})}function NCo(g,A,I={}){const e=I.disableLabels!==!1,t=I.hideInlineLabels??e,o=A instanceof HTMLCanvasElement?A.getContext("2d"):A;if(!o)throw new Error("Could not get 2D context from canvas");const B=A instanceof HTMLCanvasElement?A.width:A.canvas.width,C=A instanceof HTMLCanvasElement?A.height:A.canvas.height;let Q;if(I.transform)Q=I.transform;else if(I.viewbox)Q=rfI(I.viewbox,B,C,{padding:I.padding,yFlip:I.yFlip});else{const i=RCo(g),E=g.coordinateSystem==="cartesian";Q=rfI(i,B,C,{padding:I.padding??40,yFlip:E})}if(o.clearRect(0,0,B,C),o.save(),g.rects&&g.rects.length>0&&g.rects.forEach(i=>{const E=pCo(i,Q);o.save(),o.translate(E.center.x,E.center.y),Math.abs(E.angleRadians)>1e-6&&o.rotate(E.angleRadians),o.beginPath(),o.rect(-E.width/2,-E.height/2,E.width,E.height),i.fill&&(o.fillStyle=i.fill,o.fill()),i.stroke&&(o.strokeStyle=i.stroke,o.stroke()),o.restore()}),g.circles&&g.circles.length>0&&g.circles.forEach(i=>{const E=Mt(Q,i.center),n=i.radius*Math.abs(Q.a);o.beginPath(),o.arc(E.x,E.y,n,0,2*Math.PI),i.fill&&(o.fillStyle=i.fill,o.fill()),i.stroke&&(o.strokeStyle=i.stroke??"transparent",o.stroke())}),g.polygons&&g.polygons.length>0&&g.polygons.forEach(i=>{if(i.points.length===0)return;const E=i.points.map(n=>Mt(Q,n));o.beginPath(),o.moveTo(E[0].x,E[0].y);for(let n=1;n<E.length;n++)o.lineTo(E[n].x,E[n].y);o.closePath(),i.fill&&(o.fillStyle=i.fill,o.fill()),i.stroke&&(o.strokeStyle=i.stroke,i.strokeWidth!==void 0&&(o.lineWidth=i.strokeWidth*Math.abs(Q.a)),o.stroke())}),g.arrows&&g.arrows.length>0&&g.arrows.forEach((i,E)=>{const n=sfI(i),s=Mt(Q,n.shaftStart),r=Mt(Q,n.shaftEnd),a=i.color||K3[E%K3.length],c=Math.hypot(Q.a,Q.b);o.strokeStyle=a,o.fillStyle=a,o.lineWidth=n.shaftWidth*(c||1),o.lineCap="round",o.setLineDash([]),o.beginPath(),o.moveTo(s.x,s.y),o.lineTo(r.x,r.y),o.stroke(),n.heads.forEach(w=>{const u=Mt(Q,w.tip),G=Mt(Q,w.leftWing),m=Mt(Q,w.rightWing);o.beginPath(),o.moveTo(u.x,u.y),o.lineTo(G.x,G.y),o.lineTo(m.x,m.y),o.closePath(),o.fill()});const h=12,l=n.shaftWidth*(c||1),D=h*.6,d=afI(s,r,{fontSize:h,strokeWidth:l,normalPadding:6,alongOffset:i.label?D:0}),y=afI(s,r,{fontSize:h,strokeWidth:l,normalPadding:12,alongOffset:i.inlineLabel?-D:0});if(o.fillStyle=a,o.font=`${h}px sans-serif`,!e&&i.label){const w=y.x,u=y.y;o.save(),o.textAlign="center",o.textBaseline="middle",o.fillText(i.label,w,u),o.restore()}!t&&i.inlineLabel&&(o.save(),o.translate(d.x,d.y),o.rotate(d.angleRadians),o.textAlign="center",o.textBaseline="middle",o.fillText(i.inlineLabel,0,0),o.restore())}),g.lines&&g.lines.length>0&&g.lines.map((i,E)=>({line:i,originalIndex:E})).sort((i,E)=>(i.line.zIndex??0)-(E.line.zIndex??0)||i.originalIndex-E.originalIndex).forEach(({line:i,originalIndex:E})=>{if(i.points.length===0)return;o.beginPath();const n=Mt(Q,i.points[0]);o.moveTo(n.x,n.y);for(let s=1;s<i.points.length;s++){const r=Mt(Q,i.points[s]);o.lineTo(r.x,r.y)}if(o.strokeStyle=i.strokeColor||K3[E%K3.length],i.strokeWidth?o.lineWidth=i.strokeWidth*Q.a:o.lineWidth=2,o.lineCap="round",i.strokeDash)if(typeof i.strokeDash=="string"){let s;if(i.strokeDash.includes(","))s=i.strokeDash.split(",").map(r=>parseFloat(r.trim())).filter(r=>!Number.isNaN(r));else{const r=parseFloat(i.strokeDash.trim());s=Number.isNaN(r)?[]:[r]}o.setLineDash(s)}else o.setLineDash(i.strokeDash.map(s=>s*Math.abs(Q.a)));else o.setLineDash([]);o.stroke()}),g.infiniteLines&&g.infiniteLines.length>0){const i=lCo(Q,B,C);g.infiniteLines.forEach((E,n)=>{const s=hCo(E,i);if(!s)return;const[r,a]=s,c=Mt(Q,r),h=Mt(Q,a);if(o.beginPath(),o.moveTo(c.x,c.y),o.lineTo(h.x,h.y),o.strokeStyle=E.strokeColor||K3[n%K3.length],o.lineWidth=E.strokeWidth?E.strokeWidth*Math.abs(Q.a):2,o.lineCap="round",E.strokeDash)if(typeof E.strokeDash=="string"){let l;if(E.strokeDash.includes(","))l=E.strokeDash.split(",").map(D=>parseFloat(D.trim())).filter(D=>!Number.isNaN(D));else{const D=parseFloat(E.strokeDash.trim());l=Number.isNaN(D)?[]:[D]}o.setLineDash(l)}else o.setLineDash(E.strokeDash.map(l=>l*Math.abs(Q.a)));else o.setLineDash([]);o.stroke()})}g.texts&&g.texts.length>0&&g.texts.forEach(i=>{const E=Mt(Q,{x:i.x,y:i.y});o.fillStyle=i.color||"black",o.font=`${(i.fontSize??12)*Math.abs(Q.a)}px sans-serif`;const n=i.anchorSide??"center",s={top_left:"left",center_left:"left",bottom_left:"left",top_center:"center",center:"center",bottom_center:"center",top_right:"right",center_right:"right",bottom_right:"right"},r={top_left:"top",top_center:"top",top_right:"top",center_left:"middle",center:"middle",center_right:"middle",bottom_left:"bottom",bottom_center:"bottom",bottom_right:"bottom"};o.textAlign=s[n],o.textBaseline=r[n],o.fillText(i.text,E.x,E.y)}),g.points&&g.points.length>0&&g.points.forEach((i,E)=>{const n=Mt(Q,i);o.beginPath(),o.arc(n.x,n.y,3,0,2*Math.PI),o.fillStyle=i.color||K3[E%K3.length],o.fill(),i.label&&!e&&(o.fillStyle=i.color||"black",o.font="12px sans-serif",o.fillText(i.label,n.x+5,n.y-5))}),o.restore()}lSI(Deo(),1);var xCo=({children:g,transform:A,debugGraphics:I})=>{const e=z.useRef(null),[t,{width:o,height:B}]=QeA(),C=ii(Q=>Q.is_showing_autorouting);return z.useEffect(()=>{C&&e.current&&I&&o&&B&&(e.current.width=o,e.current.height=B,NCo(I,e.current,{transform:A,disableLabels:!0}))},[I,A,o,B,C]),C?q.jsxs("div",{ref:t,style:{position:"relative",width:"100%",height:"100%"},children:[g,q.jsx("canvas",{ref:e,style:{position:"absolute",top:0,left:0,opacity:.5,zIndex:100,width:"100%",height:"100%",pointerEvents:"none"}})]}):g};function FCo(g){const{dimensionStart:A,dimensionEnd:I,screenDimensionStart:e,screenDimensionEnd:t,flipX:o,flipY:B}=g,C=I.x-A.x,Q=I.y-A.y,i=Math.sqrt(C*C+Q*Q),E=t.x-e.x,n=t.y-e.y,s=Math.sqrt(E*E+n*n),r=Math.atan2(n,E)*(180/Math.PI),a=Math.abs(r)%90,h=Math.min(a,90-a)>15,l=(e.x+t.x)/2,D=(e.y+t.y)/2,d=15,y=r+90;let w=Math.cos(y*Math.PI/180)*d,u=Math.sin(y*Math.PI/180)*d;const G=E>0&&n<0,m=E>0&&n>0,p=E<0&&n>0;o!==B&&!G&&(w=-w,u=-u),G&&(w+=Math.cos(y*Math.PI/180)*-45,u+=Math.sin(y*Math.PI/180)*-45),m&&(w+=Math.cos(y*Math.PI/180)+-20,u+=Math.sin(y*Math.PI/180)+-10),p&&(w+=Math.cos(y*Math.PI/180)*10,u+=Math.sin(y*Math.PI/180)*10);const k=l+w,S=D+u;return{distance:i,screenDistance:s,x:k,y:S,show:i>.01&&s>30&&h}}function UCo(g){const{dimensionStart:A,dimensionEnd:I,screenDimensionStart:e,screenDimensionEnd:t,flipX:o,flipY:B}=g;return z.useMemo(()=>FCo({dimensionStart:A,dimensionEnd:I,screenDimensionStart:e,screenDimensionEnd:t,flipX:o,flipY:B}),[A,I,e,t,o,B])}var JCo=(g,A,I)=>{const e=I*Math.PI/180,t=Math.cos(e),o=Math.sin(e),B=g.x-A.x,C=g.y-A.y,Q=B*t-C*o,i=B*o+C*t;return{x:Q+A.x,y:i+A.y}},cfI=(g,A,I,e)=>{const t={top_left:{x:g.x-A,y:g.y-I},top_center:{x:g.x,y:g.y-I},top_right:{x:g.x+A,y:g.y-I},center_left:{x:g.x-A,y:g.y},center:{x:g.x,y:g.y},center_right:{x:g.x+A,y:g.y},bottom_left:{x:g.x-A,y:g.y+I},bottom_center:{x:g.x,y:g.y+I},bottom_right:{x:g.x+A,y:g.y+I}};return e===0?Object.entries(t).map(([o,B])=>({anchor:o,point:B})):Object.entries(t).map(([o,B])=>({anchor:o,point:JCo(B,g,e)}))},PCo=g=>{switch(g.pcb_drawing_type){case"rect":{const A=g.ccw_rotation??0;return cfI({x:g.x,y:g.y},g.w/2,g.h/2,A)}case"pill":{const A=g.ccw_rotation??0;return cfI({x:g.x,y:g.y},g.w/2,g.h/2,A)}case"circle":return[{anchor:"circle_center",point:{x:g.x,y:g.y}},{anchor:"circle_right",point:{x:g.x+g.r,y:g.y}},{anchor:"circle_left",point:{x:g.x-g.r,y:g.y}},{anchor:"circle_top",point:{x:g.x,y:g.y-g.r}},{anchor:"circle_bottom",point:{x:g.x,y:g.y+g.r}}];case"oval":return[{anchor:"oval_center",point:{x:g.x,y:g.y}},{anchor:"oval_right",point:{x:g.x+g.rX,y:g.y}},{anchor:"oval_left",point:{x:g.x-g.rX,y:g.y}},{anchor:"oval_top",point:{x:g.x,y:g.y-g.rY}},{anchor:"oval_bottom",point:{x:g.x,y:g.y+g.rY}}];case"line":{const A={x:(g.x1+g.x2)/2,y:(g.y1+g.y2)/2};return[{anchor:"line_start",point:{x:g.x1,y:g.y1}},{anchor:"line_mid",point:A},{anchor:"line_end",point:{x:g.x2,y:g.y2}}]}case"polygon":return g.points.map((A,I)=>({anchor:`polygon_vertex_${I}`,point:A}));case"polygon_with_arcs":return g.brep_shape.outer_ring.vertices.map((A,I)=>({anchor:`polygon_with_arcs_vertex_${I}`,point:{x:A.x,y:A.y}}));default:return[]}},KCo=[];function hfI({snappingPoints:g,realToScreenTransform:A,isEnabled:I}){return I?g.map((e,t)=>({...e,id:`${t}-${e.anchor}`,screenPoint:Mt(A,e.point)})):KCo}var lfI=({screenPoint:{x:g,y:A}})=>`M${g-2.5},${A-2.5}l5,5m0,-5l-5,5`,LCo=z.memo(function({points:A,startId:I,endId:e}){const{path:t,pointsById:o}=z.useMemo(()=>({path:A.map(lfI).join(""),pointsById:new Map(A.map(C=>[C.id,C]))}),[A]),B=[...new Set([I,e])].flatMap(C=>{const Q=C===null?void 0:o.get(C);return Q?[lfI(Q)]:[]}).join("");return q.jsxs("svg",{"aria-hidden":"true",width:"100%",height:"100%",style:{position:"absolute",left:0,top:0,overflow:"visible",pointerEvents:"none",zIndex:da.dimensionOverlay},fill:"none",strokeWidth:1,children:[q.jsx("path",{d:t,stroke:"white"}),q.jsx("path",{d:B,stroke:"#66ccff"})]})}),YCo=16,_Co=[],bCo=uJ(),DfI=g=>{if(g.pcb_drawing_type==="text")return!0;const A=g._element;if(!A||typeof A!="object")return!1;const I=typeof A.type=="string"?A.type:void 0;return I?!!(I.startsWith("pcb_silkscreen_")||I.startsWith("pcb_note_")||I==="pcb_text"||I.startsWith("pcb_fabrication_note_")&&I!=="pcb_fabrication_note_rect"):!1},HCo=({children:g,transform:A,focusOnHover:I=!1,primitives:e=_Co,onBoundsSelected:t,cancelPanDrag:o})=>{A||(A=bCo);const[B,C]=z.useState(!1),[Q,i]=z.useState(!1),[E,n]=z.useState(!1),[s,r]=z.useState(!1),[a,c]=z.useState(!1),[h,l]=z.useState(!1),[D,d]=z.useState({start:null,end:null}),y=ii(FA=>FA.is_mouse_over_container),w=z.useCallback(()=>{E&&(n(!1),window.dispatchEvent(new Event("disarm-dimension-tool")))},[E]),u=z.useCallback(()=>{s&&(r(!1),window.dispatchEvent(new Event("disarm-bounds-tool")))},[s]),[G,m]=z.useState({x:0,y:0}),[p,k]=z.useState({x:0,y:0}),[S,R]=z.useState({x:0,y:0}),[x,N]=z.useState({x:0,y:0}),U=z.useRef({x:0,y:0}),K=z.useRef(!1),_=z.useRef(null),T=_.current?.getBoundingClientRect(),j=z.useMemo(()=>{const FA=new Map;for(const aA of e){if(!aA._element||DfI(aA)||aA.pcb_drawing_type==="pill"||aA.pcb_drawing_type==="rect"&&aA.ccw_rotation&&aA.ccw_rotation!==0)continue;const xA=seg(aA);if(!xA)continue;const RA=FA.get(aA._element);FA.set(aA._element,Ooo(RA??void 0,xA))}return FA},[e]),W=z.useMemo(()=>{const FA=[];for(const aA of e){if(!aA._element||DfI(aA))continue;const xA=PCo(aA);if(xA.length!==0)for(const RA of xA)FA.push({anchor:RA.anchor,point:RA.point,element:aA._element})}return FA},[e]),O=z.useMemo(()=>{const FA=[];j.forEach((aA,xA)=>{if(!aA)return;const RA=(aA.minX+aA.maxX)/2,NA=(aA.minY+aA.maxY)/2,YA={top_left:{x:aA.minX,y:aA.minY},top_center:{x:RA,y:aA.minY},top_right:{x:aA.maxX,y:aA.minY},center_left:{x:aA.minX,y:NA},center:{x:RA,y:NA},center_right:{x:aA.maxX,y:NA},bottom_left:{x:aA.minX,y:aA.maxY},bottom_center:{x:RA,y:aA.maxY},bottom_right:{x:aA.maxX,y:aA.maxY}};for(const[PA,mA]of Object.entries(YA))FA.push({anchor:PA,point:mA,element:xA})});for(const aA of W)FA.push(aA);return FA.push({anchor:"origin",point:{x:0,y:0},element:null}),FA},[j,W]),gA=z.useMemo(()=>hfI({snappingPoints:O,realToScreenTransform:A,isEnabled:E||Q}),[O,A,E,Q]),tA=z.useCallback(FA=>{let aA=gA;if(aA.length===0&&(aA=hfI({snappingPoints:O,realToScreenTransform:A,isEnabled:!0})),aA.length===0)return{point:FA,id:null};const xA=Mt(A,FA);let RA=null;for(const NA of aA){const YA=NA.screenPoint.x-xA.x,PA=NA.screenPoint.y-xA.y,mA=Math.hypot(YA,PA);mA>YCo||(!RA||mA<RA.distance)&&(RA={distance:mA,id:NA.id,point:NA.point})}return RA?{point:RA.point,id:RA.id}:{point:FA,id:null}},[O,gA,A]);z.useEffect(()=>{const FA=RA=>{const NA=RA.target;if(NA.tagName==="INPUT"||NA.tagName==="TEXTAREA"||NA.isContentEditable)return;const YA=_.current?.contains(document.activeElement)||document.activeElement===_.current;if(!(!y&&!YA)){if(RA.key==="d"){const PA=tA({x:U.current.x,y:U.current.y});m({x:PA.point.x,y:PA.point.y}),k({x:PA.point.x,y:PA.point.y}),d({start:PA.id,end:PA.id}),B?(C(!1),i(!1),d({start:null,end:null})):(C(!0),i(!0)),w()}RA.key==="Escape"&&(C(!1),i(!1),d({start:null,end:null}),c(!1),l(!1),w(),u())}},aA=()=>{n(!0),r(!1),window.dispatchEvent(new Event("disarm-bounds-tool"))},xA=()=>{r(!0),n(!1),C(!1),i(!1),window.dispatchEvent(new Event("disarm-dimension-tool"))};return window.addEventListener("keydown",FA),window.addEventListener("arm-dimension-tool",aA),window.addEventListener("arm-bounds-tool",xA),()=>{window.removeEventListener("keydown",FA),window.removeEventListener("arm-dimension-tool",aA),window.removeEventListener("arm-bounds-tool",xA),w(),u()}},[y,B,w,u,tA]);const IA=Mt(A,G),QA=Mt(A,p),nA=Mt(A,S),DA=Mt(A,x),CA={minX:Math.min(S.x,x.x),minY:Math.min(S.y,x.y),maxX:Math.max(S.x,x.x),maxY:Math.max(S.y,x.y)},hA={left:Math.min(nA.x,DA.x),top:Math.min(nA.y,DA.y),width:Math.abs(nA.x-DA.x),height:Math.abs(nA.y-DA.y)},sA=z.useCallback((FA,aA)=>{const xA={minX:Math.min(FA.x,aA.x),minY:Math.min(FA.y,aA.y),maxX:Math.max(FA.x,aA.x),maxY:Math.max(FA.y,aA.y)};t?.(xA),window.dispatchEvent(new CustomEvent("pcb-viewer:bounds-selected",{detail:xA}))},[t]),cA={left:Math.min(IA.x,QA.x),right:Math.max(IA.x,QA.x),top:Math.min(IA.y,QA.y),bottom:Math.max(IA.y,QA.y),flipX:IA.x>QA.x,flipY:IA.y>QA.y,width:0,height:0};cA.width=cA.right-cA.left,cA.height=cA.bottom-cA.top;const SA=UCo({dimensionStart:G,dimensionEnd:p,screenDimensionStart:IA,screenDimensionEnd:QA,flipX:cA.flipX,flipY:cA.flipY});return q.jsxs("div",{ref:_,"data-pcb-viewer":!0,tabIndex:0,style:{position:"relative",outline:"none"},onMouseDownCapture:()=>{K.current=!1},onClickCapture:FA=>{K.current&&(K.current=!1,FA.stopPropagation(),_.current?.focus())},onContextMenuCapture:FA=>{!E&&!B&&!K.current||(FA.preventDefault(),FA.stopPropagation())},onMouseEnter:()=>{I&&_.current&&_.current.focus()},onMouseLeave:()=>{_.current&&_.current.blur()},onClick:()=>{_.current&&_.current.focus()},onMouseMove:FA=>{const aA=FA.currentTarget.getBoundingClientRect(),xA=FA.clientX-aA.left,RA=FA.clientY-aA.top,NA=Mt(Nx(A),{x:xA,y:RA});if(U.current.x=NA.x,U.current.y=NA.y,Q){const YA=tA(NA);k({x:YA.point.x,y:YA.point.y}),d(PA=>({...PA,end:YA.id}))}h&&(o?.(),N({x:NA.x,y:NA.y}))},onMouseDown:FA=>{K.current=E||B;const aA=FA.currentTarget.getBoundingClientRect(),xA=FA.clientX-aA.left,RA=FA.clientY-aA.top,NA=Mt(Nx(A),{x:xA,y:RA});if(s)FA.preventDefault(),FA.stopPropagation(),o?.(),R({x:NA.x,y:NA.y}),N({x:NA.x,y:NA.y}),c(!0),l(!0),u();else if(E&&!B){const YA=tA(NA);m({x:YA.point.x,y:YA.point.y}),k({x:YA.point.x,y:YA.point.y}),d({start:YA.id,end:YA.id}),C(!0),i(!0),w()}else Q?(i(!1),d(YA=>({...YA,end:null}))):B&&(C(!1),d({start:null,end:null}))},onMouseUp:FA=>{if(!h)return;const aA=FA.currentTarget.getBoundingClientRect(),xA=FA.clientX-aA.left,RA=FA.clientY-aA.top,NA=Mt(Nx(A),{x:xA,y:RA}),YA={x:NA.x,y:NA.y};FA.preventDefault(),FA.stopPropagation(),o?.(),N(YA),l(!1),sA(S,YA)},children:[g,a&&q.jsxs(q.Fragment,{children:[q.jsx("svg",{style:{position:"absolute",left:0,top:0,pointerEvents:"none",mixBlendMode:"difference",zIndex:da.dimensionOverlay},width:T.width,height:T.height,children:q.jsx("rect",{x:hA.left,y:hA.top,width:hA.width,height:hA.height,stroke:"red",strokeWidth:1.5,strokeDasharray:"4,3",fill:"rgba(255, 0, 0, 0.12)"})}),q.jsxs("div",{style:{left:0,bottom:B?58:0,position:"absolute",color:"red",fontFamily:"sans-serif",fontSize:12,margin:4,pointerEvents:"none",mixBlendMode:"difference",zIndex:da.dimensionOverlay},children:["minX: ",CA.minX.toFixed(2),", minY:"," ",CA.minY.toFixed(2),q.jsx("br",{}),"maxX: ",CA.maxX.toFixed(2),", maxY:"," ",CA.maxY.toFixed(2)]})]}),B&&q.jsxs(q.Fragment,{children:[SA.show&&q.jsx("div",{style:{position:"absolute",left:SA.x,top:SA.y,color:"red",mixBlendMode:"difference",pointerEvents:"none",fontSize:12,fontFamily:"sans-serif",whiteSpace:"nowrap",zIndex:da.dimensionOverlay},children:SA.distance.toFixed(2)}),q.jsx("div",{style:{position:"absolute",left:cA.left,width:cA.width,textAlign:"center",top:IA.y+2,color:"red",mixBlendMode:"difference",pointerEvents:"none",marginTop:cA.flipY?0:-20,fontSize:12,fontFamily:"sans-serif",zIndex:da.dimensionOverlay},children:Math.abs(G.x-p.x).toFixed(2)}),q.jsx("div",{style:{position:"absolute",left:QA.x,height:cA.height,display:"flex",flexDirection:"column",justifyContent:"center",top:cA.top,color:"red",pointerEvents:"none",mixBlendMode:"difference",fontSize:12,fontFamily:"sans-serif",zIndex:da.dimensionOverlay},children:q.jsx("div",{style:{marginLeft:cA.flipX?"-100%":4,paddingRight:4},children:Math.abs(G.y-p.y).toFixed(2)})}),q.jsxs("svg",{style:{position:"absolute",left:0,top:0,pointerEvents:"none",mixBlendMode:"difference",zIndex:da.dimensionOverlay},width:T.width,height:T.height,children:[q.jsx("defs",{children:q.jsx("marker",{id:"head",orient:"auto",markerWidth:"3",markerHeight:"4",refX:"2",refY:"2",children:q.jsx("path",{d:"M0,0 V4 L2,2 Z",fill:"red"})})}),q.jsx("line",{x1:IA.x,y1:IA.y,x2:QA.x,y2:QA.y,markerEnd:"url(#head)",strokeWidth:1.5,fill:"none",stroke:"red"}),q.jsx("line",{x1:IA.x,y1:IA.y,x2:QA.x,y2:IA.y,strokeWidth:1.5,fill:"none",strokeDasharray:"2,2",stroke:"red"}),q.jsx("line",{x1:QA.x,y1:IA.y,x2:QA.x,y2:QA.y,strokeWidth:1.5,fill:"none",strokeDasharray:"2,2",stroke:"red"})]}),Q&&q.jsx(LCo,{points:gA,startId:D.start,endId:D.end}),q.jsxs("div",{style:{right:0,bottom:0,position:"absolute",color:"red",fontFamily:"sans-serif",fontSize:12,margin:4},children:["(",G.x.toFixed(2),",",G.y.toFixed(2),")",q.jsx("br",{}),"(",p.x.toFixed(2),",",p.y.toFixed(2),")",q.jsx("br",{}),"dist:"," ",Math.sqrt((p.x-G.x)**2+(p.y-G.y)**2).toFixed(2)]})]})]})},vCo=(g,A,I=0)=>{const e=g.width/2,t=g.height/2,o=g.center.x-e-I,B=g.center.x+e+I,C=g.center.y-t-I,Q=g.center.y+t+I;return A.x>o&&A.x<B&&A.y>C&&A.y<Q},qCo=({children:g,disabled:A,transform:I,soup:e,cancelPanDrag:t,onCreateEditEvent:o,onModifyEditEvent:B})=>{I||(I=uJ());const C=z.useRef(null),[Q,i]=z.useState(null),[E,n]=z.useState(null),s=Q!==null;ii(h=>h.in_edit_mode);const r=ii(h=>h.in_move_footprint_mode),a=ii(h=>h.setIsMovingComponent),c=A||!r;return q.jsxs("div",{ref:C,style:{position:"relative",overflow:"hidden"},onMouseDown:h=>{if(c)return;const l=h.currentTarget.getBoundingClientRect(),D=h.clientX-l.left,d=h.clientY-l.top;if(Number.isNaN(D)||Number.isNaN(d))return;const y=Mt(Nx(I),{x:D,y:d});let w=!1;for(const u of e)if(u.type==="pcb_component"&&vCo(u,y,10/I.a)){t(),i(u.pcb_component_id),w=!0;const G=Math.random().toString();n({dragStart:y,originalCenter:u.center,dragEnd:y,edit_event_id:G}),o({edit_event_id:G,edit_event_type:"edit_pcb_component_location",pcb_edit_event_type:"edit_component_location",pcb_component_id:u.pcb_component_id,original_center:u.center,new_center:u.center,in_progress:!0,created_at:Date.now()}),a(!0);break}if(w||i(null),w)return h.preventDefault(),!1},onMouseMove:h=>{if(!Q||!E)return;const l=h.currentTarget.getBoundingClientRect(),D=h.clientX-l.left,d=h.clientY-l.top;if(Number.isNaN(D)||Number.isNaN(d))return;const y=Mt(Nx(I),{x:D,y:d});n({...E,dragEnd:y}),B({edit_event_id:E.edit_event_id,new_center:{x:E.originalCenter.x+y.x-E.dragStart.x,y:E.originalCenter.y+y.y-E.dragStart.y}})},onMouseUp:h=>{Q&&(i(null),a(!1),E&&(B({edit_event_id:E.edit_event_id,in_progress:!1}),n(null)))},children:[g,!c&&e.filter(h=>h.type==="pcb_component").map(h=>{if(!h?.center)return null;const l=Mt(I,h.center);return q.jsx("div",{style:{position:"absolute",pointerEvents:"none",left:l.x,top:l.y,width:h.width*I.a+20,height:h.height*I.a+20,transform:"translate(-50%, -50%)",background:s&&Q===h.pcb_component_id?"rgba(255, 0, 0, 0.2)":""}},h.pcb_component_id)})]})},ceg=(g,A)=>{const I=A.current;if(!I)return{transform:"translate(-50%, -100%)",left:g.x,top:g.y};const e=I.getBoundingClientRect(),t=200,o=10,B=60;let C="-50%",Q="-100%",i=g.x,E=g.y;return g.x+B+t<e.width-o?(i=g.x+B,C="0%"):g.x-B-t>o?(i=g.x-B,C="-100%"):(i=g.x,C="-50%"),{transform:`translate(${C}, ${Q})`,left:i,top:E}},TCo=({center:g})=>q.jsxs("svg",{style:{position:"absolute",left:0,top:0,pointerEvents:"none",mixBlendMode:"difference",zIndex:da.errorOverlay+30},width:"100%",height:"100%",children:[q.jsx("circle",{cx:g.x,cy:g.y,r:11,fill:"none",stroke:"#ff6b6b",strokeWidth:2.5,opacity:.95}),q.jsx("circle",{cx:g.x,cy:g.y,r:4.5,fill:"#ff6b6b",opacity:.95}),q.jsx("line",{x1:g.x-18,y1:g.y,x2:g.x-8,y2:g.y,stroke:"#ff6b6b",strokeWidth:2}),q.jsx("line",{x1:g.x+8,y1:g.y,x2:g.x+18,y2:g.y,stroke:"#ff6b6b",strokeWidth:2}),q.jsx("line",{x1:g.x,y1:g.y-18,x2:g.x,y2:g.y-8,stroke:"#ff6b6b",strokeWidth:2}),q.jsx("line",{x1:g.x,y1:g.y+8,x2:g.x,y2:g.y+18,stroke:"#ff6b6b",strokeWidth:2})]}),dfI=({errorCenter:g,isHighlighted:A=!1})=>q.jsx("svg",{style:{position:"absolute",left:0,top:0,pointerEvents:"none",mixBlendMode:"difference",zIndex:da.errorOverlay},width:"100%",height:"100%",children:q.jsx("rect",{x:g.x-7,y:g.y-7,width:14,height:14,transform:`rotate(45 ${g.x} ${g.y})`,fill:A?"#ff4444":"transparent",stroke:A?"#ff4444":"red",strokeWidth:A?2.5:1.5})}),heg=j7`
5423
+ `)?.every(A=>A.includes("LINESTRING"))}function Vto(g){return g.startsWith("POINT")||n2I(g)||g.startsWith("LINESTRING")||s2I(g)||g.startsWith("MULTILINESTRING")||g.startsWith("POLYGON")||g.startsWith("MULTIPOINT")||g.startsWith("MULTIPOLYGON")||g.startsWith("GEOMETRYCOLLECTION")}jA.isWktString=Vto,jA.parseWKT=E2I,jA.BooleanOperations=Ato,jA.Relations=rto;function a2I(g,A,I){if(!A||!I)return;let e=g.get(A);e||(e=new Set,g.set(A,e)),e.add(I);let t=g.get(I);t||(t=new Set,g.set(I,t)),t.add(A)}function r2I(g,A){if(!A.subcircuit_id&&!A.source_group_id)return[...g];let I=A;if(A.subcircuit_id){const C=new Set([A.subcircuit_id]),Q=new Map,i=new Map;for(const n of g)if(n.type==="source_group"){const s=n.source_group_id,r=n.subcircuit_id;r&&i.set(s,r);const a=n.parent_source_group_id;a&&(Q.has(a)||Q.set(a,[]),Q.get(a).push(s))}let E;for(const[n,s]of i)if(s===A.subcircuit_id){E=n;break}if(E){const n=s=>{const r=Q.get(s)||[];for(const a of r){const c=i.get(a);c&&C.add(c),n(a)}};n(E),I={...A,subcircuit_ids:Array.from(C)}}}const e=new Map;for(const C of g){const Q=`${C.type}_id`,i=C[Q];typeof i=="string"&&e.set(i,C)}const t=new Map;for(const C of g){const Q=Object.entries(C);for(const[i,E]of Q)if(i!=="parent_source_group_id"){if(i.endsWith("_id")&&typeof E=="string"){const n=e.get(E);a2I(t,C,n)}else if(i.endsWith("_ids")&&Array.isArray(E)){for(const n of E)if(typeof n=="string"){const s=e.get(n);a2I(t,C,s)}}}}const o=[],B=new Set;for(const C of g){let Q=!1;(I.subcircuit_id&&"subcircuit_id"in C&&C.subcircuit_id===I.subcircuit_id||I.subcircuit_ids&&"subcircuit_id"in C&&C.subcircuit_id&&I.subcircuit_ids.includes(C.subcircuit_id)||I.source_group_id&&"source_group_id"in C&&C.source_group_id===I.source_group_id||I.source_group_id&&"member_source_group_ids"in C&&Array.isArray(C.member_source_group_ids)&&C.member_source_group_ids.includes(I.source_group_id))&&(Q=!0),Q&&(o.push(C),B.add(C))}for(;o.length>0;){const C=o.shift(),Q=t.get(C);if(Q)for(const i of Q)B.has(i)||(B.add(i),o.push(i))}return g.filter(C=>B.has(C))}var HwA=(g,A={})=>{const I=g;let e=I._internal_store;if(!e){e={counts:{},editCount:0},I._internal_store=e;for(const o of I){const B=o.type,C=o[`${B}_id`];if(!C)continue;const Q=Number.parseInt(C.split("_").pop());Number.isNaN(Q)||(e.counts[B]=Math.max(e.counts[B]??0,Q))}}const t=new Proxy({},{get:(o,B)=>{if(B==="toArray")return()=>(I.editCount=e.editCount,I);if(B==="editCount")return e.editCount;if(B==="subtree")return Q=>HwA(r2I(I,Q),A);if(B==="insert")return Q=>{const i=Q.type;if(!i)throw new Error("insert requires an element with a type");e.counts[i]??=-1,e.counts[i]++;const E=e.counts[i],n={...Q,type:i,[`${i}_id`]:`${i}_${E}`};return A.validateInserts&&(wN[i]??mf).parse(n),I.push(n),e.editCount++,n};if(B==="insertAll")return Q=>Q.map(i=>t.insert(i));const C=B;return{get:Q=>I.find(i=>i.type===C&&i[`${C}_id`]===Q),getUsing:Q=>{const i=Object.keys(Q);if(i.length!==1)throw new Error("getUsing requires exactly one key, e.g. { pcb_component_id }");const E=i[0],n=E.replace("_id",""),s=I.find(r=>r.type===n&&r[E]===Q[E]);return s?I.find(r=>r.type===C&&r[`${C}_id`]===s[`${C}_id`]):null},getWhere:Q=>{const i=Object.keys(Q);return I.find(E=>E.type===C&&i.every(n=>E[n]===Q[n]))},list:Q=>{const i=Q?Object.keys(Q):[];return I.filter(E=>E.type===C&&i.every(n=>E[n]===Q[n]))},insert:Q=>{e.counts[C]??=-1,e.counts[C]++;const i=e.counts[C],E={type:C,[`${C}_id`]:`${C}_${i}`,...Q};return A.validateInserts&&(wN[C]??mf).parse(E),I.push(E),e.editCount++,E},delete:Q=>{const i=I.find(E=>E[`${C}_id`]===Q);i&&(I.splice(I.indexOf(i),1),e.editCount++)},update:(Q,i)=>{const E=I.find(n=>n.type===C&&n[`${C}_id`]===Q);return E?(Object.assign(E,i),e.editCount++,E):null},select:Q=>{if(C==="source_component")return I.find(i=>i.type==="source_component"&&i.name===Q.replace(/\./g,""));if(C==="pcb_port"||C==="source_port"||C==="schematic_port"){const[i,E]=Q.replace(/\./g,"").split(/[\s\>]+/),n=I.find(r=>r.type==="source_component"&&r.name===i);if(!n)return null;const s=I.find(r=>r.type==="source_port"&&r.source_component_id===n.source_component_id&&(r.name===E||(r.port_hints??[]).includes(E)));if(!s)return null;if(C==="source_port")return s;if(C==="pcb_port")return I.find(r=>r.type==="pcb_port"&&r.source_port_id===s.source_port_id);if(C==="schematic_port")return I.find(r=>r.type==="schematic_port"&&r.source_port_id===s.source_port_id)}}}}});return t};HwA.unparsed=HwA;var Y5=HwA;function Beg(g){const A=g.type;return`${A}:${g[`${A}_id`]}`}var Ceg=(g,A={})=>{let I=g._internal_store_indexed;if(!I){I={counts:{},editCount:0,indexes:{}};for(const B of g){const C=B.type,Q=B[`${C}_id`];if(!Q)continue;const i=Number.parseInt(Q.split("_").pop()||"");Number.isNaN(i)||(I.counts[C]=Math.max(I.counts[C]??0,i))}const t=A.indexConfig||{},o=I.indexes;if(t.byId&&(o.byId=new Map),t.byType&&(o.byType=new Map),t.byRelation&&(o.byRelation=new Map),t.bySubcircuit&&(o.bySubcircuit=new Map),t.byCustomField&&t.byCustomField.length>0){o.byCustomField=new Map;for(const B of t.byCustomField)o.byCustomField.set(B,new Map)}for(const B of g){if(t.byId){const C=Beg(B);o.byId.set(C,B)}if(t.byType){const C=o.byType.get(B.type)||[];C.push(B),o.byType.set(B.type,C)}if(t.byRelation){const C=Object.entries(B);for(const[Q,i]of C)if(Q.endsWith("_id")&&Q!==`${B.type}_id`&&typeof i=="string"){const E=o.byRelation.get(Q)||new Map,n=E.get(i)||[];n.push(B),E.set(i,n),o.byRelation.set(Q,E)}}if(t.bySubcircuit&&"subcircuit_id"in B){const C=B.subcircuit_id;if(C&&typeof C=="string"){const Q=o.bySubcircuit.get(C)||[];Q.push(B),o.bySubcircuit.set(C,Q)}}if(t.byCustomField&&o.byCustomField){for(const C of t.byCustomField)if(C in B){const Q=B[C];if(Q!==void 0&&(typeof Q=="string"||typeof Q=="number")){const i=String(Q),E=o.byCustomField.get(C),n=E.get(i)||[];n.push(B),E.set(i,n)}}}}g._internal_store_indexed=I}const e=new Proxy({},{get:(t,o)=>{if(o==="toArray")return()=>(g.editCount=I.editCount,g);if(o==="editCount")return I.editCount;if(o==="insert")return C=>{const{type:Q,...i}=C;if(!Q)throw new Error("insert requires an element with a type");return delete i[`${Q}_id`],e[Q].insert(i)};if(o==="insertAll")return C=>C.map(Q=>e.insert(Q));if(o==="subtree")return C=>Ceg(r2I(g,C),A);const B=o;return{get:C=>{const Q=A.indexConfig||{};return Q.byId&&I.indexes.byId?I.indexes.byId.get(`${B}:${C}`)||null:Q.byType&&I.indexes.byType?(I.indexes.byType.get(B)||[]).find(E=>E[`${B}_id`]===C)||null:g.find(i=>i.type===B&&i[`${B}_id`]===C)||null},getUsing:C=>{const Q=A.indexConfig||{},i=Object.keys(C);if(i.length!==1)throw new Error("getUsing requires exactly one key, e.g. { pcb_component_id }");const E=i[0],n=E.replace("_id","");if(Q.byRelation&&I.indexes.byRelation){const r=I.indexes.byRelation.get(E);if(r){const c=(r.get(C[E])||[]).find(l=>l.type===n);if(!c)return null;const h=c[`${B}_id`];return Q.byId&&I.indexes.byId?I.indexes.byId.get(`${B}:${h}`)||null:Q.byType&&I.indexes.byType?(I.indexes.byType.get(B)||[]).find(D=>D[`${B}_id`]===h)||null:g.find(l=>l.type===B&&l[`${B}_id`]===h)||null}}const s=g.find(r=>r.type===n&&r[E]===C[E]);return s&&g.find(r=>r.type===B&&r[`${B}_id`]===s[`${B}_id`])||null},getWhere:C=>{const Q=A.indexConfig||{},i=Object.keys(C);if(i.length===1&&Q.byCustomField&&I.indexes.byCustomField){const E=i[0],n=I.indexes.byCustomField.get(E);if(n){const s=String(C[E]);return(n.get(s)||[]).find(a=>a.type===B)||null}}if("subcircuit_id"in C&&Q.bySubcircuit&&I.indexes.bySubcircuit){const E=C.subcircuit_id;return(I.indexes.bySubcircuit.get(E)||[]).find(s=>s.type===B&&i.every(r=>s[r]===C[r]))||null}return Q.byType&&I.indexes.byType?(I.indexes.byType.get(B)||[]).find(n=>i.every(s=>n[s]===C[s]))||null:g.find(E=>E.type===B&&i.every(n=>E[n]===C[n]))||null},list:C=>{const Q=A.indexConfig||{},i=C?Object.keys(C):[];if(i.length===0&&Q.byType&&I.indexes.byType)return(I.indexes.byType.get(B)||[]).slice();if(i.length===1&&i[0]==="subcircuit_id"&&Q.bySubcircuit&&I.indexes.bySubcircuit){const n=C.subcircuit_id;return(I.indexes.bySubcircuit.get(n)||[]).filter(r=>r.type===B)}let E;return Q.byType&&I.indexes.byType?E=I.indexes.byType.get(B)||[]:E=g.filter(n=>n.type===B),i.length>0?E.filter(n=>i.every(s=>n[s]===C[s])):E.slice()},insert:C=>{I.counts[B]??=-1,I.counts[B]++;const Q=I.counts[B],i={type:B,[`${B}_id`]:`${B}_${Q}`,...C};A.validateInserts&&(wN[B]??mf).parse(i),g.push(i),I.editCount++;const E=A.indexConfig||{};if(E.byId&&I.indexes.byId){const n=Beg(i);I.indexes.byId.set(n,i)}if(E.byType&&I.indexes.byType){const n=I.indexes.byType.get(B)||[];n.push(i),I.indexes.byType.set(B,n)}if(E.byRelation&&I.indexes.byRelation){const n=Object.entries(i);for(const[s,r]of n)if(s.endsWith("_id")&&s!==`${i.type}_id`&&typeof r=="string"){const a=I.indexes.byRelation.get(s)||new Map,c=a.get(r)||[];c.push(i),a.set(r,c),I.indexes.byRelation.set(s,a)}}if(E.bySubcircuit&&I.indexes.bySubcircuit&&"subcircuit_id"in i){const n=i.subcircuit_id;if(n&&typeof n=="string"){const s=I.indexes.bySubcircuit.get(n)||[];s.push(i),I.indexes.bySubcircuit.set(n,s)}}if(E.byCustomField&&I.indexes.byCustomField){for(const n of E.byCustomField)if(n in i){const s=i[n];if(s!==void 0&&(typeof s=="string"||typeof s=="number")){const r=String(s),a=I.indexes.byCustomField.get(n),c=a.get(r)||[];c.push(i),a.set(r,c)}}}return i},delete:C=>{const Q=A.indexConfig||{};let i;if(Q.byId&&I.indexes.byId?i=I.indexes.byId.get(`${B}:${C}`):Q.byType&&I.indexes.byType?i=(I.indexes.byType.get(B)||[]).find(s=>s[`${B}_id`]===C):i=g.find(n=>n[`${B}_id`]===C),!i)return;const E=g.indexOf(i);if(E>=0&&(g.splice(E,1),I.editCount++),Q.byId&&I.indexes.byId){const n=Beg(i);I.indexes.byId.delete(n)}if(Q.byType&&I.indexes.byType){const s=(I.indexes.byType.get(B)||[]).filter(r=>r[`${B}_id`]!==C);I.indexes.byType.set(B,s)}if(Q.byRelation&&I.indexes.byRelation)for(const[n,s]of I.indexes.byRelation.entries())for(const[r,a]of s.entries()){const c=a.filter(h=>h!==i);c.length===0?s.delete(r):s.set(r,c)}if(Q.bySubcircuit&&I.indexes.bySubcircuit&&"subcircuit_id"in i){const n=i.subcircuit_id;if(n){const r=(I.indexes.bySubcircuit.get(n)||[]).filter(a=>a!==i);r.length===0?I.indexes.bySubcircuit.delete(n):I.indexes.bySubcircuit.set(n,r)}}if(Q.byCustomField&&I.indexes.byCustomField)for(const n of I.indexes.byCustomField.values())for(const[s,r]of n.entries()){const a=r.filter(c=>c!==i);a.length===0?n.delete(s):n.set(s,a)}},update:(C,Q)=>{const i=A.indexConfig||{};let E;if(i.byId&&I.indexes.byId?E=I.indexes.byId.get(`${B}:${C}`):i.byType&&I.indexes.byType?E=(I.indexes.byType.get(B)||[]).find(s=>s[`${B}_id`]===C):E=g.find(n=>n.type===B&&n[`${B}_id`]===C),!E)return null;if(i.byRelation&&I.indexes.byRelation){const n=Object.entries(E);for(const[s,r]of n)if(s.endsWith("_id")&&s!==`${E.type}_id`&&typeof r=="string"&&s in Q&&Q[s]!==r){const a=I.indexes.byRelation.get(s);if(a){const h=(a.get(r)||[]).filter(l=>l!==E);h.length===0?a.delete(r):a.set(r,h)}}}if(i.bySubcircuit&&I.indexes.bySubcircuit&&"subcircuit_id"in E&&"subcircuit_id"in Q){const n=E.subcircuit_id,s=Q.subcircuit_id;if(n!==s){const a=(I.indexes.bySubcircuit.get(n)||[]).filter(c=>c!==E);a.length===0?I.indexes.bySubcircuit.delete(n):I.indexes.bySubcircuit.set(n,a)}}if(i.byCustomField&&I.indexes.byCustomField){for(const n of i.byCustomField)if(n in E&&n in Q&&E[n]!==Q[n]){const s=I.indexes.byCustomField.get(n);if(s){const r=String(E[n]),c=(s.get(r)||[]).filter(h=>h!==E);c.length===0?s.delete(r):s.set(r,c)}}}if(Object.assign(E,Q),I.editCount++,i.byRelation&&I.indexes.byRelation){const n=Object.entries(E);for(const[s,r]of n)if(s.endsWith("_id")&&s!==`${E.type}_id`&&typeof r=="string"&&s in Q){const a=I.indexes.byRelation.get(s)||new Map,c=a.get(r)||[];c.includes(E)||(c.push(E),a.set(r,c),I.indexes.byRelation.set(s,a))}}if(i.bySubcircuit&&I.indexes.bySubcircuit&&"subcircuit_id"in E&&"subcircuit_id"in Q){const n=E.subcircuit_id;if(n&&typeof n=="string"){const s=I.indexes.bySubcircuit.get(n)||[];s.includes(E)||(s.push(E),I.indexes.bySubcircuit.set(n,s))}}if(i.byCustomField&&I.indexes.byCustomField){for(const n of i.byCustomField)if(n in E&&n in Q){const s=E[n];if(s!==void 0&&(typeof s=="string"||typeof s=="number")){const r=String(s),a=I.indexes.byCustomField.get(n),c=a.get(r)||[];c.includes(E)||(c.push(E),a.set(r,c))}}}return E},select:C=>{if(B==="source_component")return g.find(Q=>Q.type==="source_component"&&Q.name===C.replace(/\./g,""))||null;if(B==="pcb_port"||B==="source_port"||B==="schematic_port"){const[Q,i]=C.replace(/\./g,"").split(/[\s\>]+/),E=g.find(s=>s.type==="source_component"&&s.name===Q);if(!E)return null;const n=g.find(s=>s.type==="source_port"&&s.source_component_id===E.source_component_id&&(s.name===i||(s.port_hints??[]).includes(i)));if(!n)return null;if(B==="source_port")return n;if(B==="pcb_port")return g.find(s=>s.type==="pcb_port"&&s.source_port_id===n.source_port_id)||null;if(B==="schematic_port")return g.find(s=>s.type==="schematic_port"&&s.source_port_id===n.source_port_id)||null}return null}}}});return e};Ceg.unparsed=Ceg;var jto=g=>Math.round(g/(Math.PI/2)),zto=g=>{switch(g){case"from_left":return{x:-1,y:0};case"from_right":return{x:1,y:0};case"from_top":return{x:0,y:1};case"from_bottom":return{x:0,y:-1}}},Xto=({x:g,y:A})=>g>0?"from_right":g<0?"from_left":A>0?"from_top":"from_bottom",$to=(g,A)=>{if(!g)return g;if(g==="from_above"||g==="from_below")return A.isFlipped?g==="from_above"?"from_below":"from_above":g;let{x:I,y:e}=zto(g),t=Math.round(A.rotationDegrees/90);for(;t>0;)[I,e]=[-e,I],t--;for(;t<0;)[I,e]=[e,-I],t++;return A.isFlipped&&(e=-e),Xto({x:I,y:e})},Aoo=(g,A)=>{if(g.shape==="polygon")return g.points=g.points.map(B=>Mt(A,B)),g;const I=Mt(A,{x:g.x,y:g.y});if(g.x=I.x,g.y=I.y,g.shape==="circle")return g;const e=g.shape==="rotated_rect"?g.ccw_rotation:0,t=A.a*A.d-A.b*A.c<0,o=PMI(bw(A,zgo(e)),!1,t).rotation.angle*180/Math.PI;return Math.abs(o)<1e-8?(Object.assign(g,{shape:"rect"}),Reflect.deleteProperty(g,"ccw_rotation")):Object.assign(g,{shape:"rotated_rect",ccw_rotation:o}),g},goo=(g,A)=>{if(g.type==="pcb_soldermask_opening")return Aoo(g,A);if((g.type==="pcb_smtpad"||g.type==="pcb_solder_paste")&&g.shape==="polygon")return g.points=g.points.map(B=>Mt(A,B)),g.type==="pcb_solder_paste"&&g.holes&&(g.holes=g.holes.map(B=>B.map(C=>Mt(A,C)))),g;const I=PMI(A),e=Math.abs(jto(I.rotation.angle))%2===1,t=I.rotation.angle/Math.PI*180,o=I.scale.sy<0;if(g.type==="pcb_plated_hole"||g.type==="pcb_hole"||g.type==="pcb_via"||g.type==="pcb_smtpad"||g.type==="pcb_solder_paste"||g.type==="pcb_port"){const{x:B,y:C}=Mt(A,{x:g.x,y:g.y});g.x=B,g.y=C}else if(g.type==="pcb_keepout"&&g.shape==="outline")g.outline=g.outline.map(B=>Mt(A,B));else if(g.type==="pcb_keepout"||g.type==="pcb_board")g.center=Mt(A,g.center);else if(g.type==="pcb_silkscreen_text"||g.type==="pcb_fabrication_note_text"||g.type==="pcb_note_text")g.anchor_position=Mt(A,g.anchor_position);else if(g.type==="pcb_copper_text")g.anchor_position&&(g.anchor_position=Mt(A,g.anchor_position));else if(g.type==="pcb_courtyard_rect")g.center=Mt(A,g.center),g.ccw_rotation=((g.ccw_rotation??0)+t)%360;else if(g.type==="pcb_silkscreen_circle"||g.type==="pcb_silkscreen_rect"||g.type==="pcb_silkscreen_pill"||g.type==="pcb_silkscreen_oval"||g.type==="pcb_note_rect"||g.type==="pcb_courtyard_circle")g.center=Mt(A,g.center);else if(g.type==="pcb_component")g.center=Mt(A,g.center),g.rotation=g.rotation+t,g.rotation=g.rotation%360,g.cable_insertion_center&&(g.cable_insertion_center=Mt(A,g.cable_insertion_center)),g.insertion_direction=$to(g.insertion_direction,{rotationDegrees:t,isFlipped:o}),e&&([g.width,g.height]=[g.height,g.width]);else if(g.type==="pcb_courtyard_outline")g.outline=g.outline.map(B=>{const C=Mt(A,B);return B.x=C.x,B.y=C.y,B});else if(g.type==="pcb_courtyard_polygon")g.points=g.points.map(B=>{const C=Mt(A,B);return B.x=C.x,B.y=C.y,B});else if(g.type==="pcb_trace")g.route=g.route.map(B=>{if(!("x"in B))return B.start=Mt(A,B.start),B.end=Mt(A,B.end),B;const C=Mt(A,B);return B.x=C.x,B.y=C.y,B});else if(g.type==="pcb_silkscreen_path"||g.type==="pcb_trace_hint"||g.type==="pcb_fabrication_note_path"||g.type==="pcb_note_path")g.route=g.route.map(B=>{const C=Mt(A,B);return B.x=C.x,B.y=C.y,B});else if(g.type==="pcb_silkscreen_line"||g.type==="pcb_note_line"){const B={x:g.x1,y:g.y1},C={x:g.x2,y:g.y2},Q=Mt(A,B),i=Mt(A,C);g.x1=Q.x,g.y1=Q.y,g.x2=i.x,g.y2=i.y}else if(g.type==="cad_component"){const B=Mt(A,{x:g.position.x,y:g.position.y});g.position.x=B.x,g.position.y=B.y}return g},Ioo=g=>{const A=g.type;return g[`${A}_id`]},Qeg=(g,A)=>({minX:Math.min(g.minX,A.minX),minY:Math.min(g.minY,A.minY),maxX:Math.max(g.maxX,A.maxX),maxY:Math.max(g.maxY,A.maxY)}),CeA=(g,A,I)=>{const e=I/2;return{minX:g-e,minY:A-e,maxX:g+e,maxY:A+e}},c2I=(g,A,I,e,t)=>{const o=I/2,B=e/2,C=t*Math.PI/180,Q=Math.cos(C),i=Math.sin(C),E=[{x:-o,y:-B},{x:o,y:-B},{x:o,y:B},{x:-o,y:B}].map(n=>({x:g+n.x*Q-n.y*i,y:A+n.x*i+n.y*Q}));return{minX:Math.min(...E.map(n=>n.x)),minY:Math.min(...E.map(n=>n.y)),maxX:Math.max(...E.map(n=>n.x)),maxY:Math.max(...E.map(n=>n.y))}},eoo=(g,A,I,e,t)=>{const o=I/2,B=e/2,C=t*Math.PI/180,Q=Math.cos(C),i=Math.sin(C),E=Math.hypot(o*Q,B*i),n=Math.hypot(o*i,B*Q);return{minX:g-E,minY:A-n,maxX:g+E,maxY:A+n}},too=(g,A,I,e,t)=>{const o=Math.min(I,e)/2,B=Math.max(I,e)/2-o,C=t*Math.PI/180,Q=I>=e?{x:B,y:0}:{x:0,y:B},i={x:Q.x*Math.cos(C)-Q.y*Math.sin(C),y:Q.x*Math.sin(C)+Q.y*Math.cos(C)},E=Math.abs(i.x)+o,n=Math.abs(i.y)+o;return{minX:g-E,minY:A-n,maxX:g+E,maxY:A+n}},vwA=g=>g.length===0?null:{minX:Math.min(...g.map(A=>A.x)),minY:Math.min(...g.map(A=>A.y)),maxX:Math.max(...g.map(A=>A.x)),maxY:Math.max(...g.map(A=>A.y))},ieg=g=>Array.isArray(g)?g.flatMap(A=>!A||typeof A!="object"?[]:"x"in A&&"y"in A&&typeof A.x=="number"&&typeof A.y=="number"?[{x:A.x,y:A.y}]:"start"in A&&"end"in A?[A.start,A.end].filter(e=>!!(e&&typeof e=="object"&&"x"in e&&"y"in e&&typeof e.x=="number"&&typeof e.y=="number")):[]):[],h2I=g=>{if(!g.type.startsWith("pcb_"))return null;if(g.type==="pcb_smtpad"&&g.shape==="polygon"&&Array.isArray(g.points))return vwA(g.points);if(g.type==="pcb_hole"&&g.hole_shape==="circle")return CeA(g.x,g.y,g.hole_diameter);if(g.type==="pcb_plated_hole"){let n;if("outer_diameter"in g&&typeof g.outer_diameter=="number"?n=CeA(g.x,g.y,g.outer_diameter):"hole_diameter"in g&&typeof g.hole_diameter=="number"&&(n=CeA(g.x,g.y,g.hole_diameter)),(g.shape==="oval"||g.shape==="pill")&&typeof g.outer_width=="number"&&typeof g.outer_height=="number"&&(n=(g.shape==="pill"?too:eoo)(g.x,g.y,g.outer_width,g.outer_height,g.ccw_rotation??0)),"rect_pad_width"in g&&typeof g.rect_pad_width=="number"&&"rect_pad_height"in g&&typeof g.rect_pad_height=="number"){const s=c2I(g.x,g.y,g.rect_pad_width,g.rect_pad_height,"rect_ccw_rotation"in g?g.rect_ccw_rotation??0:0);n=n?Qeg(n,s):s}if("hole_diameter"in g&&typeof g.hole_diameter=="number"){const s=CeA(g.x+("hole_offset_x"in g?g.hole_offset_x??0:0),g.y+("hole_offset_y"in g?g.hole_offset_y??0:0),g.hole_diameter);n=n?Qeg(n,s):s}if(n)return n}const A=g,I=vwA(ieg(A.route));if(I)return I;const e=vwA(ieg(A.outline));if(e)return e;const t=vwA(ieg(A.points));if(t)return t;let o,B,C,Q;"x"in g&&"y"in g&&(o=Number(g.x),B=Number(g.y)),"outer_diameter"in g&&(C=Number(g.outer_diameter),Q=Number(g.outer_diameter)),"width"in g&&(C=Number(g.width)),"height"in g&&(Q=Number(g.height)),"center"in g&&g.center&&typeof g.center=="object"&&"x"in g.center&&"y"in g.center&&(o=Number(g.center.x),B=Number(g.center.y));let i=0;if("rotation"in g&&typeof g.rotation=="number"&&(i=g.rotation),"ccw_rotation"in g&&typeof g.ccw_rotation=="number"&&(i=g.ccw_rotation),o!==void 0&&B!==void 0)return C!==void 0&&Q!==void 0?i?c2I(o,B,C,Q,i):{minX:o-C/2,minY:B-Q/2,maxX:o+C/2,maxY:B+Q/2}:"radius"in g&&typeof g.radius=="number"?CeA(o,B,g.radius*2):{minX:o,minY:B,maxX:o,maxY:B};const E=[A.anchor_position,A.position].filter(n=>!!(n&&typeof n=="object"&&"x"in n&&"y"in n&&typeof n.x=="number"&&typeof n.y=="number")).at(0);return E?{minX:E.x,minY:E.y,maxX:E.x,maxY:E.y}:null},Eeg=g=>{let A={minX:Number.POSITIVE_INFINITY,minY:Number.POSITIVE_INFINITY,maxX:Number.NEGATIVE_INFINITY,maxY:Number.NEGATIVE_INFINITY};for(const I of g){const e=h2I(I);e&&(A=Qeg(A,e))}return A};function ooo(g){let A=0;if(g.length==0)return A;for(var I=0;I<g.length;I++){var e=g.charCodeAt(I);A=(A<<5)-A+e,A=A&A}return Math.abs(A)}var l2I=[["#69d2e7","#a7dbd8","#e0e4cc","#f38630","#fa6900"],["#fe4365","#fc9d9a","#f9cdad","#c8c8a9","#83af9b"],["#ecd078","#d95b43","#c02942","#542437","#53777a"],["#556270","#4ecdc4","#c7f464","#ff6b6b","#c44d58"],["#774f38","#e08e79","#f1d4af","#ece5ce","#c5e0dc"],["#e8ddcb","#cdb380","#036564","#033649","#031634"],["#490a3d","#bd1550","#e97f02","#f8ca00","#8a9b0f"],["#594f4f","#547980","#45ada8","#9de0ad","#e5fcc2"],["#00a0b0","#6a4a3c","#cc333f","#eb6841","#edc951"],["#e94e77","#d68189","#c6a49a","#c6e5d9","#f4ead5"],["#3fb8af","#7fc7af","#dad8a7","#ff9e9d","#ff3d7f"],["#d9ceb2","#948c75","#d5ded9","#7a6a53","#99b2b7"],["#ffffff","#cbe86b","#f2e9e1","#1c140d","#cbe86b"],["#efffcd","#dce9be","#555152","#2e2633","#99173c"],["#343838","#005f6b","#008c9e","#00b4cc","#00dffc"],["#413e4a","#73626e","#b38184","#f0b49e","#f7e4be"],["#ff4e50","#fc913a","#f9d423","#ede574","#e1f5c4"],["#99b898","#fecea8","#ff847c","#e84a5f","#2a363b"],["#655643","#80bca3","#f6f7bd","#e6ac27","#bf4d28"],["#00a8c6","#40c0cb","#f9f2e7","#aee239","#8fbe00"],["#351330","#424254","#64908a","#e8caa4","#cc2a41"],["#554236","#f77825","#d3ce3d","#f1efa5","#60b99a"],["#5d4157","#838689","#a8caba","#cad7b2","#ebe3aa"],["#8c2318","#5e8c6a","#88a65e","#bfb35a","#f2c45a"],["#fad089","#ff9c5b","#f5634a","#ed303c","#3b8183"],["#ff4242","#f4fad2","#d4ee5e","#e1edb9","#f0f2eb"],["#f8b195","#f67280","#c06c84","#6c5b7b","#355c7d"],["#d1e751","#ffffff","#000000","#4dbce9","#26ade4"],["#1b676b","#519548","#88c425","#bef202","#eafde6"],["#5e412f","#fcebb6","#78c0a8","#f07818","#f0a830"],["#bcbdac","#cfbe27","#f27435","#f02475","#3b2d38"],["#452632","#91204d","#e4844a","#e8bf56","#e2f7ce"],["#eee6ab","#c5bc8e","#696758","#45484b","#36393b"],["#f0d8a8","#3d1c00","#86b8b1","#f2d694","#fa2a00"],["#2a044a","#0b2e59","#0d6759","#7ab317","#a0c55f"],["#f04155","#ff823a","#f2f26f","#fff7bd","#95cfb7"],["#b9d7d9","#668284","#2a2829","#493736","#7b3b3b"],["#bbbb88","#ccc68d","#eedd99","#eec290","#eeaa88"],["#b3cc57","#ecf081","#ffbe40","#ef746f","#ab3e5b"],["#a3a948","#edb92e","#f85931","#ce1836","#009989"],["#300030","#480048","#601848","#c04848","#f07241"],["#67917a","#170409","#b8af03","#ccbf82","#e33258"],["#aab3ab","#c4cbb7","#ebefc9","#eee0b7","#e8caaf"],["#e8d5b7","#0e2430","#fc3a51","#f5b349","#e8d5b9"],["#ab526b","#bca297","#c5ceae","#f0e2a4","#f4ebc3"],["#607848","#789048","#c0d860","#f0f0d8","#604848"],["#b6d8c0","#c8d9bf","#dadabd","#ecdbbc","#fedcba"],["#a8e6ce","#dcedc2","#ffd3b5","#ffaaa6","#ff8c94"],["#3e4147","#fffedf","#dfba69","#5a2e2e","#2a2c31"],["#fc354c","#29221f","#13747d","#0abfbc","#fcf7c5"],["#cc0c39","#e6781e","#c8cf02","#f8fcc1","#1693a7"],["#1c2130","#028f76","#b3e099","#ffeaad","#d14334"],["#a7c5bd","#e5ddcb","#eb7b59","#cf4647","#524656"],["#dad6ca","#1bb0ce","#4f8699","#6a5e72","#563444"],["#5c323e","#a82743","#e15e32","#c0d23e","#e5f04c"],["#edebe6","#d6e1c7","#94c7b6","#403b33","#d3643b"],["#fdf1cc","#c6d6b8","#987f69","#e3ad40","#fcd036"],["#230f2b","#f21d41","#ebebbc","#bce3c5","#82b3ae"],["#b9d3b0","#81bda4","#b28774","#f88f79","#f6aa93"],["#3a111c","#574951","#83988e","#bcdea5","#e6f9bc"],["#5e3929","#cd8c52","#b7d1a3","#dee8be","#fcf7d3"],["#1c0113","#6b0103","#a30006","#c21a01","#f03c02"],["#000000","#9f111b","#b11623","#292c37","#cccccc"],["#382f32","#ffeaf2","#fcd9e5","#fbc5d8","#f1396d"],["#e3dfba","#c8d6bf","#93ccc6","#6cbdb5","#1a1f1e"],["#f6f6f6","#e8e8e8","#333333","#990100","#b90504"],["#1b325f","#9cc4e4","#e9f2f9","#3a89c9","#f26c4f"],["#a1dbb2","#fee5ad","#faca66","#f7a541","#f45d4c"],["#c1b398","#605951","#fbeec2","#61a6ab","#accec0"],["#5e9fa3","#dcd1b4","#fab87f","#f87e7b","#b05574"],["#951f2b","#f5f4d7","#e0dfb1","#a5a36c","#535233"],["#8dccad","#988864","#fea6a2","#f9d6ac","#ffe9af"],["#2d2d29","#215a6d","#3ca2a2","#92c7a3","#dfece6"],["#413d3d","#040004","#c8ff00","#fa023c","#4b000f"],["#eff3cd","#b2d5ba","#61ada0","#248f8d","#605063"],["#ffefd3","#fffee4","#d0ecea","#9fd6d2","#8b7a5e"],["#cfffdd","#b4dec1","#5c5863","#a85163","#ff1f4c"],["#9dc9ac","#fffec7","#f56218","#ff9d2e","#919167"],["#4e395d","#827085","#8ebe94","#ccfc8e","#dc5b3e"],["#a8a7a7","#cc527a","#e8175d","#474747","#363636"],["#f8edd1","#d88a8a","#474843","#9d9d93","#c5cfc6"],["#046d8b","#309292","#2fb8ac","#93a42a","#ecbe13"],["#f38a8a","#55443d","#a0cab5","#cde9ca","#f1edd0"],["#a70267","#f10c49","#fb6b41","#f6d86b","#339194"],["#ff003c","#ff8a00","#fabe28","#88c100","#00c176"],["#ffedbf","#f7803c","#f54828","#2e0d23","#f8e4c1"],["#4e4d4a","#353432","#94ba65","#2790b0","#2b4e72"],["#0ca5b0","#4e3f30","#fefeeb","#f8f4e4","#a5b3aa"],["#4d3b3b","#de6262","#ffb88c","#ffd0b3","#f5e0d3"],["#fffbb7","#a6f6af","#66b6ab","#5b7c8d","#4f2958"],["#edf6ee","#d1c089","#b3204d","#412e28","#151101"],["#9d7e79","#ccac95","#9a947c","#748b83","#5b756c"],["#fcfef5","#e9ffe1","#cdcfb7","#d6e6c3","#fafbe3"],["#9cddc8","#bfd8ad","#ddd9ab","#f7af63","#633d2e"],["#30261c","#403831","#36544f","#1f5f61","#0b8185"],["#aaff00","#ffaa00","#ff00aa","#aa00ff","#00aaff"],["#d1313d","#e5625c","#f9bf76","#8eb2c5","#615375"],["#ffe181","#eee9e5","#fad3b2","#ffba7f","#ff9c97"],["#73c8a9","#dee1b6","#e1b866","#bd5532","#373b44"],["#805841","#dcf7f3","#fffcdd","#ffd8d8","#f5a2a2"]],Boo=g=>{let{x:A,y:I,width:e,height:t}={...g,...g.size,...g.center,...g.position};if(g.x1!==void 0&&g.x2!==void 0&&g.y1!==void 0&&g.y2!==void 0&&(A=(g.x1+g.x2)/2,I=(g.y1+g.y2)/2,e=Math.abs(g.x1-g.x2),t=Math.abs(g.y1-g.y2)),g.points&&Array.isArray(g.points)&&g.points.length>0){const C=g.points.map(r=>r.x),Q=g.points.map(r=>r.y),i=Math.min(...C),E=Math.max(...C),n=Math.min(...Q),s=Math.max(...Q);A=(i+E)/2,I=(n+s)/2,e=E-i,t=s-n}const o=g.text||g.name||g.source?.text||g.source?.name||"?",B=g;return A===void 0||I===void 0?null:(e===void 0&&("radius"in g?(e=g.radius*2,t=g.radius*2):"outer_diameter"in g?(e=g.outer_diameter,t=g.outer_diameter):"rect_pad_width"in g&&"rect_pad_height"in g?(e=g.rect_pad_width,t=g.rect_pad_height,"hole_diameter"in g&&(e=Math.max(e,g.hole_diameter),t=Math.max(t,g.hole_diameter))):"hole_diameter"in g&&(e=g.hole_diameter,t=g.hole_diameter)),(e===void 0||t===void 0)&&(e=.1,t=.1),{x:A,y:I,width:e,height:t,title:o,content:B,bg_color:l2I[ooo(g.type||o)%l2I.length]?.[4]??"#f00"})},Coo=g=>!!g,Qoo=g=>{const A=g.filter(i=>i.type.startsWith("pcb_")||i.type.startsWith("schematic_")).concat(g.filter(i=>i.type==="pcb_trace"||i.type==="schematic_trace").flatMap(i=>i.route)).map(i=>Boo(i)).filter(Coo);if(A.length===0)return{center:{x:0,y:0},width:0,height:0};let I=A[0].x-A[0].width/2,e=A[0].x+A[0].width/2,t=A[0].y-A[0].height/2,o=A[0].y+A[0].height/2;for(const i of A.slice(1))I=Math.min(I,i.x-i.width/2),e=Math.max(e,i.x+i.width/2),t=Math.min(t,i.y-i.height/2),o=Math.max(o,i.y+i.height/2);const B=e-I,C=o-t;return{center:{x:I+B/2,y:t+C/2},width:B,height:C}};function ioo({circuitJson:g,editEvents:A}){if(A.length===0)return g;let I=structuredClone(g);for(const e of A){if(e.edit_event_type==="edit_pcb_component_location"){const C=Y5(I).pcb_component.get(e.pcb_component_id);if(C?.center.x===e.new_center.x&&C.center.y===e.new_center.y)continue;const i=qc(e.new_center.x-e.original_center.x,e.new_center.y-e.original_center.y);I=I.map(E=>"pcb_component_id"in E&&E.pcb_component_id===e.pcb_component_id?goo(E,i):E);continue}if(e.edit_event_type==="edit_schematic_component_location"){I=I.map(C=>C.type==="schematic_component"&&C.schematic_component_id===e.schematic_component_id?{...C,center:e.new_center}:C);continue}if(e.edit_event_type!=="edit_pcb_trace_hint"||!e.pcb_trace_hint_id)continue;if(Y5(I).pcb_trace_hint.get(e.pcb_trace_hint_id)){I=I.map(C=>C.type==="pcb_trace_hint"&&C.pcb_trace_hint_id===e.pcb_trace_hint_id?{...C,route:e.route}:C);continue}const o=Y5(I).pcb_port.get(e.pcb_port_id);if(!o?.pcb_component_id)continue;const B={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:o.pcb_component_id};I=I.filter(C=>C.type!=="pcb_trace_hint"||C.pcb_port_id!==e.pcb_port_id).concat(B)}return I}var Eoo=g=>{if(!g)return"empty";const A=g.find(e=>e.type==="pcb_board");if(!A)return"no-board";const I=e=>Math.round(e*1e3)/1e3;return A.outline?A.outline.map(e=>`${I(e.x)}_${I(e.y)}`).join(","):`${I(A.width)}_${I(A.height)}`},qwA=g=>Number.isFinite(g)?g.toFixed(4):"NaN",noo=g=>{let A=5381;for(let I=0;I<g.length;I++)A=(A<<5)+A+g.charCodeAt(I);return Math.abs(A)},soo=g=>{if(!g?.length)return"0";const A=[];for(const t of g){if(!t?.type?.startsWith("pcb_"))continue;const o=Ioo(t),B=Eeg([t]),C=[qwA(B.minX),qwA(B.minY),qwA(B.maxX),qwA(B.maxY)].join(",");let Q=`${o}:${C}`;if(t.type==="pcb_trace"){const i=(t.route??[]).length;Q+=`:${i}`;for(const E of t.route??[])E.route_type==="via"&&(Q+=`:${E.tented_on_top}:${E.tented_on_bottom}`)}t.type==="pcb_board"&&(Q+=`:${t.default_via_tented_on_top}:${t.default_via_tented_on_bottom}`),t.type==="pcb_via"&&(Q+=`:${t.tented_on_top}:${t.tented_on_bottom}`),A.push(Q)}if(A.length===0)return"0";A.sort();const I=A.join(","),e=noo(I);return`${A.length}_${e.toString(36)}`},D2I=z.createContext(null),aoo=({children:g,initialState:A,disablePcbGroups:I})=>{const e=z.useMemo(()=>coo(A,I),[I]);return q.jsx(D2I.Provider,{value:e,children:g})},Mh={RENDERING_ENGINE:"pcb_viewer_rendering_engine",COPPER_POUR_OPACITY:"pcb_viewer_copper_pour_opacity",HIDDEN_LAYER_OPACITY:"pcb_viewer_hidden_layer_opacity",IS_SHOWING_PCB_GROUPS:"pcb_viewer_is_showing_pcb_groups",PCB_GROUP_VIEW_MODE:"pcb_viewer_group_view_mode",IS_SHOWING_COPPER_POURS:"pcb_viewer_is_showing_copper_pours",IS_SHOWING_COURTYARDS:"pcb_viewer_is_showing_courtyards",IS_SHOWING_GROUP_ANCHOR_OFFSETS:"pcb_viewer_is_showing_group_anchor_offsets",IS_SHOWING_SOLDER_MASK:"pcb_viewer_is_showing_solder_mask",IS_SHOWING_FABRICATION_NOTES:"pcb_viewer_is_showing_fabrication_notes",IS_SHOWING_PCB_NOTES:"pcb_viewer_is_showing_pcb_notes",IS_SHOWING_SILKSCREEN:"pcb_viewer_is_showing_silkscreen"},U3=(g,A)=>{if(typeof window>"u")return A;try{const I=localStorage.getItem(g);return I!==null?JSON.parse(I):A}catch{return A}},J3=(g,A)=>{if(!(typeof window>"u"))try{localStorage.setItem(g,JSON.stringify(A))}catch{}},d2I=(g,A)=>{if(typeof window>"u")return A;try{const I=localStorage.getItem(g);return I!==null?JSON.parse(I):A}catch{return A}},y2I=(g,A)=>{if(!(typeof window>"u"))try{localStorage.setItem(g,JSON.stringify(A))}catch{}},w2I=(g,A)=>{if(typeof window>"u")return A;try{const I=localStorage.getItem(g),e=I!==null?JSON.parse(I):null;return typeof e=="number"&&Number.isFinite(e)?e:A}catch{return A}},u2I=(g,A)=>{if(!(typeof window>"u"))try{localStorage.setItem(g,JSON.stringify(A))}catch{}},roo="named_only",coo=(g={},A=!1)=>_Vg(I=>({copper_pour_opacity:Math.max(0,Math.min(1,w2I(Mh.COPPER_POUR_OPACITY,1))),setCopperPourOpacity:e=>{if(!Number.isFinite(e))return;const t=Math.max(0,Math.min(1,e));u2I(Mh.COPPER_POUR_OPACITY,t),I({copper_pour_opacity:t})},hidden_layer_opacity:Math.max(0,Math.min(1,w2I(Mh.HIDDEN_LAYER_OPACITY,.2))),setHiddenLayerOpacity:e=>{if(!Number.isFinite(e))return;const t=Math.max(0,Math.min(1,e));u2I(Mh.HIDDEN_LAYER_OPACITY,t),I({hidden_layer_opacity:t})},selected_layer:"top",pcb_viewer_id:`pcb_viewer_${Math.random().toString().slice(2,10)}`,in_edit_mode:!1,in_move_footprint_mode:!1,is_moving_component:!1,is_mouse_over_container:!1,is_showing_multiple_traces_length:!1,is_showing_rats_nest:!1,is_showing_autorouting:!0,is_showing_drc_errors:!0,is_showing_drc_warnings:!0,is_showing_copper_pours:U3(Mh.IS_SHOWING_COPPER_POURS,!0),is_showing_courtyards:U3(Mh.IS_SHOWING_COURTYARDS,!0),is_showing_pcb_groups:A?!1:U3(Mh.IS_SHOWING_PCB_GROUPS,!0),is_showing_group_anchor_offsets:U3(Mh.IS_SHOWING_GROUP_ANCHOR_OFFSETS,!1),is_showing_solder_mask:U3(Mh.IS_SHOWING_SOLDER_MASK,!1),is_showing_silkscreen:U3(Mh.IS_SHOWING_SILKSCREEN,!0),is_showing_fabrication_notes:U3(Mh.IS_SHOWING_FABRICATION_NOTES,!1),is_showing_pcb_notes:U3(Mh.IS_SHOWING_PCB_NOTES,!0),pcb_group_view_mode:A?"all":d2I(Mh.PCB_GROUP_VIEW_MODE,roo),hovered_error_id:null,focused_error_id:null,...g,selectLayer:e=>I({selected_layer:e}),setEditMode:e=>I({in_edit_mode:e!=="off",in_move_footprint_mode:e==="move_footprint",is_moving_component:!1}),setIsShowingRatsNest:e=>I({is_showing_rats_nest:e}),setIsMovingComponent:e=>I({is_moving_component:e}),setIsMouseOverContainer:e=>I({is_mouse_over_container:e}),setIsShowingMultipleTracesLength:e=>I({is_showing_multiple_traces_length:e}),setIsShowingAutorouting:e=>I({is_showing_autorouting:e}),setIsShowingDrcErrors:e=>I({is_showing_drc_errors:e}),setIsShowingDrcWarnings:e=>I({is_showing_drc_warnings:e}),setIsShowingCopperPours:e=>{J3(Mh.IS_SHOWING_COPPER_POURS,e),I({is_showing_copper_pours:e})},setIsShowingCourtyards:e=>{J3(Mh.IS_SHOWING_COURTYARDS,e),I({is_showing_courtyards:e})},setIsShowingPcbGroups:e=>{A||(J3(Mh.IS_SHOWING_PCB_GROUPS,e),I({is_showing_pcb_groups:e}))},setIsShowingGroupAnchorOffsets:e=>{J3(Mh.IS_SHOWING_GROUP_ANCHOR_OFFSETS,e),I({is_showing_group_anchor_offsets:e})},setIsShowingSolderMask:e=>{J3(Mh.IS_SHOWING_SOLDER_MASK,e),I({is_showing_solder_mask:e})},setIsShowingSilkscreen:e=>{J3(Mh.IS_SHOWING_SILKSCREEN,e),I({is_showing_silkscreen:e})},setIsShowingFabricationNotes:e=>{J3(Mh.IS_SHOWING_FABRICATION_NOTES,e),I({is_showing_fabrication_notes:e})},setIsShowingPcbNotes:e=>{J3(Mh.IS_SHOWING_PCB_NOTES,e),I({is_showing_pcb_notes:e})},setPcbGroupViewMode:e=>{A||(y2I(Mh.PCB_GROUP_VIEW_MODE,e),I({pcb_group_view_mode:e}))},setHoveredErrorId:e=>I({hovered_error_id:e}),setFocusedErrorId:e=>I({focused_error_id:e})})),ii=g=>{const A=z.useContext(D2I);return jVg(A,g)},hoo=()=>{z.useEffect(()=>{nIo()},[]);const g=ii(A=>A.pcb_viewer_id);return q.jsx(EIo,{position:"top-center",containerId:g})},da={elementOverlay:40,dimensionOverlay:40,errorOverlay:40,pcbGroupOverlay:35,ratsNestOverlay:30,toolbarOverlay:70,warnings:30,topLayer:30,clickToInteractOverlay:100};function loo(){var g=z.useRef(!1),A=z.useCallback(function(){return g.current},[]);return z.useEffect(function(){return g.current=!0,function(){g.current=!1}},[]),A}var Doo=function(g){g===void 0&&(g={});var A=z.useState(g),I=A[0],e=A[1],t=z.useCallback(function(o){e(function(B){return Object.assign({},B,o instanceof Function?o(B):o)})},[]);return[I,t]},doo=Doo,yoo=function(){},G2I=typeof window<"u",woo=lSI(leo()),uoo=function(){var g=loo(),A=doo({value:void 0,error:void 0,noUserInteraction:!0}),I=A[0],e=A[1],t=z.useCallback(function(o){if(g()){var B,C;try{if(typeof o!="string"&&typeof o!="number"){var Q=new Error("Cannot copy typeof "+typeof o+" to clipboard, must be a string");console.error(Q),e({value:o,error:Q,noUserInteraction:!0});return}else if(o===""){var Q=new Error("Cannot copy empty string to clipboard.");console.error(Q),e({value:o,error:Q,noUserInteraction:!0});return}C=o.toString(),B=(0,woo.default)(C),e({value:C,error:void 0,noUserInteraction:B})}catch(i){e({value:C,error:i,noUserInteraction:B})}}},[]);return[I,t]},Goo=uoo,moo=G2I?z.useLayoutEffect:z.useEffect,poo=moo,m2I={x:0,y:0,width:0,height:0,top:0,left:0,bottom:0,right:0};function koo(){var g=z.useState(null),A=g[0],I=g[1],e=z.useState(m2I),t=e[0],o=e[1],B=z.useMemo(function(){return new window.ResizeObserver(function(C){if(C[0]){var Q=C[0].contentRect,i=Q.x,E=Q.y,n=Q.width,s=Q.height,r=Q.top,a=Q.left,c=Q.bottom,h=Q.right;o({x:i,y:E,width:n,height:s,top:r,left:a,bottom:c,right:h})}})},[]);return poo(function(){if(A)return B.observe(A),function(){B.disconnect()}},[A]),[I,t]}var QeA=G2I&&typeof window.ResizeObserver<"u"?koo:function(){return[yoo,m2I]},p2I=({initialTransform:g,initialTouch1:A,initialTouch2:I,finalTouch1:e,finalTouch2:t})=>{if(!e||!t)return g;const o={x:(A.x+I.x)/2,y:(A.y+I.y)/2},B={x:(e.x+t.x)/2,y:(e.y+t.y)/2},C=Math.hypot(I.x-A.x,I.y-A.y),Q=Math.hypot(t.x-e.x,t.y-e.y),i=C===0?1:Q/C,E=B.x-o.x,n=B.y-o.y;return bw(qc(E,n),qc(o.x,o.y),GJ(i,i),qc(-o.x,-o.y),g)},Moo=(g={})=>{const A=z.useRef(null),[I,e]=z.useState(0),t=g.canvasElm??A.current,[o,B]=z.useState(g.initialTransform??uJ()),[C,Q]=z.useState(0),[i,E]=z.useReducer(d=>d+1,0),n=z.useCallback(d=>{g.onSetTransform&&g.onSetTransform(d),g.transform||B(d)},[g.onSetTransform,B]),s=z.useCallback(d=>{n(d),E()},[n]),r=g.transform??o,a=z.useCallback(()=>{e(Date.now())},[]),c=z.useRef("none"),h=z.useRef(null),l=z.useRef(null);z.useEffect(()=>{const d=g.canvasElm??A.current;if(d&&!t){Q(C+1);return}if(!d){const _=setTimeout(()=>{Q(C+1)},100);return()=>clearTimeout(_)}let y=g.transform??o,w={x:0,y:0},u={x:0,y:0},G=!1;const m=_=>({x:_.pageX-d.getBoundingClientRect().left-window.scrollX,y:_.pageY-d.getBoundingClientRect().top-window.scrollY});function p(_){g.enabled!==!1&&(g.shouldDrag&&!g.shouldDrag(_)||(w=m(_),!(Date.now()-I<100)&&(G=!0,_.preventDefault())))}function k(_){if(!G||g.enabled===!1||g.shouldDrag&&!g.shouldDrag(_))return;u=m(_);const b=bw(qc(u.x-w.x,u.y-w.y),y);n(b),y=b,G=!1}function S(_){if(m(_),!G||g.enabled===!1||g.shouldDrag&&!g.shouldDrag(_))return;u=m(_);const b=bw(qc(u.x-w.x,u.y-w.y),y);n(b)}function R(_){if(g.enabled===!1||g.shouldDrag&&!g.shouldDrag(_))return;const b=m(_),T=bw(qc(b.x,b.y),GJ(1-_.deltaY/1e3,1-_.deltaY/1e3),qc(-b.x,-b.y),y);n(T),y=T,_.preventDefault()}function x(_){if(!G||g.shouldDrag&&!g.shouldDrag(_))return;if(d){const T=d.getBoundingClientRect();if(_.clientX>=T.left+10&&_.clientX<=T.right-10&&_.clientY>=T.top+10&&_.clientY<=T.bottom-10)return}G=!1,u=m(_);const b=bw(qc(u.x-w.x,u.y-w.y),y);n(b),y=b}function N(_){if(_.preventDefault(),g.enabled!==!1){if(_.touches.length===1){c.current="drag";const b=_.touches[0];h.current={initialTransform:y,initialTouch:{x:b.clientX,y:b.clientY}}}else if(_.touches.length===2){c.current="pinch";const b=_.touches[0],T=_.touches[1];l.current={initialTransform:y,initialTouch1:{x:b.clientX,y:b.clientY},initialTouch2:{x:T.clientX,y:T.clientY},finalTouch1:null,finalTouch2:null}}}}function U(_){if(_.preventDefault(),g.enabled!==!1){if(c.current==="drag"&&_.touches.length===1&&h.current){const b=_.touches[0],T={x:b.clientX,y:b.clientY},j=T.x-h.current.initialTouch.x,W=T.y-h.current.initialTouch.y,O=bw(qc(j,W),h.current.initialTransform);n(O)}else if(c.current==="pinch"&&_.touches.length===2&&l.current){const b=_.touches[0],T=_.touches[1];l.current.finalTouch1={x:b.clientX,y:b.clientY},l.current.finalTouch2={x:T.clientX,y:T.clientY};const j=p2I(l.current);n(j)}}}function K(_){_.preventDefault();const b=_.changedTouches[0];if(c.current==="drag"&&h.current&&b){const T={x:b.clientX,y:b.clientY},j=T.x-h.current.initialTouch.x,W=T.y-h.current.initialTouch.y,O=bw(qc(j,W),h.current.initialTransform);n(O),y=O}else if(c.current==="pinch"&&l.current){const T=p2I(l.current);n(T),y=T}c.current="none",h.current=null,l.current=null}return d.addEventListener("mousedown",p),d.addEventListener("mouseup",k),window.addEventListener("mousemove",S),d.addEventListener("mouseout",x),d.addEventListener("wheel",R),d.addEventListener("touchstart",N,{passive:!1}),d.addEventListener("touchmove",U,{passive:!1}),d.addEventListener("touchend",K,{passive:!1}),d.addEventListener("touchcancel",K,{passive:!1}),()=>{d.removeEventListener("mousedown",p),d.removeEventListener("mouseup",k),window.removeEventListener("mousemove",S),d.removeEventListener("mouseout",x),d.removeEventListener("wheel",R),d.removeEventListener("touchstart",N),d.removeEventListener("touchmove",U),d.removeEventListener("touchend",K),d.removeEventListener("touchcancel",K)}},[t,C,i,I,g.enabled,g.shouldDrag]);const D=z.useCallback(d=>Mt(r,d),[r]);return{ref:A,transform:r,applyTransformToPoint:D,setTransform:s,cancelDrag:a}},Soo=Moo;function k2I(g){let A=g;for(;A.parent!==null;)A=A.parent;let I=g;for(;I.parent!==null&&I.parent!==A;){const e=I.parent;I.parent=A,I=e}return A}function foo(g,A){const I={nodeId:g,nextMember:null},e={parent:null,networkId:`connectivity_net${A.nextNetworkNumber++}`,firstMember:I,lastMember:I};return A.rootByNodeId.set(g,e),e}function Roo(g,A){const I=A.rootByNodeId.get(g);return I===void 0?foo(g,A):k2I(I)}function Noo({targetRoot:g,sourceRoot:A}){g.lastMember.nextMember=A.firstMember,g.lastMember=A.lastMember,A.parent=g}function xoo(g){const A=[];let I=g.firstMember;for(;I!==null;)A.push(I.nodeId),I=I.nextMember;return A}function Foo(g){const A={rootByNodeId:new Map,nextNetworkNumber:0};for(const e of g){let t=null;for(const o of e){const B=Roo(o,A);if(t===null){t=B;continue}t=k2I(t),B!==t&&Noo({targetRoot:t,sourceRoot:B})}}const I={};for(const e of A.rootByNodeId.values())e.parent===null&&(I[e.networkId]=xoo(e));return I}var Uoo=class{netMap;idToNetMap;constructor(g){this.netMap=g,this.idToNetMap={};for(const[A,I]of Object.entries(g))for(const e of I)this.idToNetMap[e]=A}addConnections(g){for(const A of g){const I=new Set;for(const t of A){const o=this.idToNetMap[t];o&&I.add(o)}let e;if(I.size===0)e=`connectivity_net${Object.keys(this.netMap).length}`,this.netMap[e]=[];else if(I.size===1)e=I.values().next().value??`connectivity_net${Object.keys(this.netMap).length}`;else{e=I.values().next().value??`connectivity_net${Object.keys(this.netMap).length}`;for(const t of I)if(t!==e){this.netMap[e].push(...this.netMap[t]),this.netMap[t]=this.netMap[e];for(const o of this.netMap[e])this.idToNetMap[o]=e}}for(const t of A)this.netMap[e].includes(t)||this.netMap[e].push(t),this.idToNetMap[t]=e}}getIdsConnectedToNet(g){return this.netMap[g]||[]}getNetConnectedToId(g){return this.idToNetMap[g]}areIdsConnected(g,A){if(g===A)return!0;const I=this.getNetConnectedToId(g);if(!I)return!1;const e=this.getNetConnectedToId(A);return e?I===e||e===g||e===g:!1}areAllIdsConnected(g){const A=this.getNetConnectedToId(g[0]);for(const I of g){const e=this.getNetConnectedToId(I);if(e===void 0||e!==A)return!1}return!0}},Joo=g=>{const A=[];for(const e of g)if(e.type==="source_trace")A.push([e.source_trace_id,...e.connected_source_port_ids??[],...e.connected_source_net_ids??[]].filter(Boolean));else if(e.type==="pcb_port"){const{pcb_port_id:t,source_port_id:o}=e;o&&t&&A.push([o,t])}else if(e.type==="pcb_smtpad"){const{pcb_smtpad_id:t,pcb_port_id:o}=e;o&&t&&A.push([t,o])}else if(e.type==="pcb_plated_hole"){const{pcb_plated_hole_id:t,pcb_port_id:o}=e;o&&t&&A.push([t,o])}else if(e.type==="pcb_trace"){const{pcb_trace_id:t,source_trace_id:o}=e,B=Array.isArray(e.route)?e.route.filter(C=>C&&C.route_type==="wire"):[];if(o&&t&&A.push([t,o]),Array.isArray(B)){const C=B.find(i=>i?.start_pcb_port_id)?.start_pcb_port_id,Q=B.find(i=>i?.end_pcb_port_id)?.end_pcb_port_id;C&&t&&A.push([C,t]),t&&Q&&A.push([t,Q])}}else if(e.type==="pcb_via"){const{pcb_via_id:t,pcb_trace_id:o,source_trace_id:B,source_net_id:C}=e,Q=[...e.pcb_port_ids??[],o,B,C].filter(i=>!!i);t&&Q.length>0&&A.push([t,...Q])}else if(e.type==="source_component"&&e.internally_connected_source_port_ids)for(const t of e.internally_connected_source_port_ids)A.push(t);const I=Foo(A);return new Uoo(I)};function Poo(g,A){if(g.length<2)throw new Error("Stroke must have at least two points");const I=g.map(n=>Array.isArray(n)?{x:n[0],y:n[1]}:n),e=[],t=[];function o(n,s){const r=s.x-n.x,a=s.y-n.y,c=Math.sqrt(r*r+a*a);return{x:-a/c,y:r/c}}function B(n,s,r,a){const c=a/2,h={x:n.x+s.x*c*r,y:n.y+s.y*c*r};r>0?e.push(h):t.unshift(h)}const C=o(I[0],I[1]),Q=I[0].trace_width??A;B(I[0],C,1,Q),B(I[0],C,-1,Q);for(let n=1;n<I.length-1;n++){const s=I[n-1],r=I[n],a=I[n+1],c=o(s,r),h=o(r,a),l=c.x+h.x,D=c.y+h.y,d=Math.sqrt(l*l+D*D),y=r.trace_width??A;if(d/2>2*(y/2))B(r,c,1,y),B(r,h,1,y),B(r,c,-1,y),B(r,h,-1,y);else{const u=1/d;B(r,{x:l*u,y:D*u},1,y),B(r,{x:l*u,y:D*u},-1,y)}}const i=o(I[I.length-2],I[I.length-1]),E=I[I.length-1].trace_width??A;return B(I[I.length-1],i,1,E),B(I[I.length-1],i,-1,E),[...e,...t]}var Koo=(g,A)=>{const{x:I,y:e,width:t,height:o,layer:B,rect_border_radius:C}=g,Q=g.corner_radius??C??0,i=[{_pcb_drawing_object_id:LR("rect"),pcb_drawing_type:"rect",x:I,y:e,w:t,h:o,layer:B||"top",_element:g,_parent_pcb_component:A._parent_pcb_component,_parent_source_component:A._parent_source_component,_source_port:A._source_port,roundness:Q,...g.shape==="rotated_rect"&&g.ccw_rotation!==void 0?{ccw_rotation:g.ccw_rotation}:{}}];if(g.is_covered_with_solder_mask){const E=B==="bottom"?"soldermask_with_copper_bottom":"soldermask_with_copper_top",s={...{_pcb_drawing_object_id:LR("rect"),pcb_drawing_type:"rect",x:I,y:e,w:t,h:o,layer:E,_element:g,_parent_pcb_component:A._parent_pcb_component,_parent_source_component:A._parent_source_component,_source_port:A._source_port,roundness:Q,...g.shape==="rotated_rect"&&g.ccw_rotation!==void 0?{ccw_rotation:g.ccw_rotation}:{}},..."solder_mask_color"in g&&g.solder_mask_color?{color:g.solder_mask_color}:{}};i.push(s)}return i},Loo=(g,A)=>{const{x:I,y:e,radius:t,layer:o}=g,B=[{_pcb_drawing_object_id:LR("circle"),pcb_drawing_type:"circle",x:I,y:e,r:t,layer:o||"top",_element:g,_parent_pcb_component:A._parent_pcb_component,_parent_source_component:A._parent_source_component,_source_port:A._source_port}];if(g.is_covered_with_solder_mask){const C=o==="bottom"?"soldermask_with_copper_bottom":"soldermask_with_copper_top",Q={_pcb_drawing_object_id:LR("circle"),pcb_drawing_type:"circle",x:I,y:e,r:t,layer:C,_element:g,_parent_pcb_component:A._parent_pcb_component,_parent_source_component:A._parent_source_component,_source_port:A._source_port,..."solder_mask_color"in g&&g.solder_mask_color?{color:g.solder_mask_color}:{}};B.push(Q)}return B},Yoo=(g,A)=>{const{layer:I,points:e}=g,t=[{_pcb_drawing_object_id:LR("polygon"),pcb_drawing_type:"polygon",points:neg(e),layer:I||"top",_element:g,_parent_pcb_component:A._parent_pcb_component,_parent_source_component:A._parent_source_component,_source_port:A._source_port}];if(g.is_covered_with_solder_mask){const o=I==="bottom"?"soldermask_with_copper_bottom":"soldermask_with_copper_top",B={_pcb_drawing_object_id:LR("polygon"),pcb_drawing_type:"polygon",points:neg(e),layer:o,_element:g,_parent_pcb_component:A._parent_pcb_component,_parent_source_component:A._parent_source_component,_source_port:A._source_port,..."solder_mask_color"in g&&g.solder_mask_color?{color:g.solder_mask_color}:{}};t.push(B)}return t},_oo=(g,A)=>{const{x:I,y:e,width:t,height:o,layer:B}=g,C=[{_pcb_drawing_object_id:LR("pill"),pcb_drawing_type:"pill",x:I,y:e,w:t,h:o,layer:B||"top",_element:g,_parent_pcb_component:A._parent_pcb_component,_parent_source_component:A._parent_source_component,_source_port:A._source_port}];if(g.is_covered_with_solder_mask){const Q=B==="bottom"?"soldermask_with_copper_bottom":"soldermask_with_copper_top",i={_pcb_drawing_object_id:LR("pill"),pcb_drawing_type:"pill",x:I,y:e,w:t,h:o,layer:Q,_element:g,_parent_pcb_component:A._parent_pcb_component,_parent_source_component:A._parent_source_component,_source_port:A._source_port,..."solder_mask_color"in g&&g.solder_mask_color?{color:g.solder_mask_color}:{}};C.push(i)}return C},boo=(g,A)=>{const{x:I,y:e,width:t,height:o,layer:B,ccw_rotation:C}=g,Q=[{_pcb_drawing_object_id:LR("pill"),pcb_drawing_type:"pill",x:I,y:e,w:t,h:o,layer:B||"top",_element:g,_parent_pcb_component:A._parent_pcb_component,_parent_source_component:A._parent_source_component,_source_port:A._source_port,ccw_rotation:C}];if(g.is_covered_with_solder_mask){const i=B==="bottom"?"soldermask_with_copper_bottom":"soldermask_with_copper_top",E={_pcb_drawing_object_id:LR("pill"),pcb_drawing_type:"pill",x:I,y:e,w:t,h:o,layer:i,_element:g,_parent_pcb_component:A._parent_pcb_component,_parent_source_component:A._parent_source_component,_source_port:A._source_port,ccw_rotation:C,..."solder_mask_color"in g&&g.solder_mask_color?{color:g.solder_mask_color}:{}};Q.push(E)}return Q},Oc=0,LR=g=>`${g}_${Oc++}`,neg=g=>(g??[]).map(A=>({x:sg.parse(A.x),y:sg.parse(A.y)}));function Hoo(g){const A=new Map;for(const I of g){const e=I[`${I.type}_id`];e!==void 0&&!A.has(`${I.type}:${e}`)&&A.set(`${I.type}:${e}`,I)}return A}var voo=(g,A,I)=>{const e=(Q,i)=>{if(i!==void 0)return I?I.get(`${Q}:${i}`):A.find(E=>E.type===Q&&E[`${Q}_id`]===i)},t=e("pcb_component","pcb_component_id"in g?g.pcb_component_id:void 0),o=e("source_component",t?.source_component_id),B="source_port_id"in g?g.source_port_id:"pcb_port_id"in g?e("pcb_port",g.pcb_port_id)?.source_port_id:void 0,C=e("source_port",B);switch(g.type){case"pcb_smtpad":{const Q={_parent_pcb_component:t,_parent_source_component:o,_source_port:C};return g.shape==="rect"||g.shape==="rotated_rect"?Koo(g,Q):g.shape==="circle"?Loo(g,Q):g.shape==="polygon"?Yoo(g,Q):g.shape==="pill"?_oo(g,Q):g.shape==="rotated_pill"?boo(g,Q):[]}case"pcb_trace":{const Q=[];if(g.route_thickness_mode==="interpolated"){const n=g.route.flatMap(a=>a.route_type==="through_pad"?[{...a.start,trace_width:a.width},{...a.end,trace_width:a.width}]:[{x:a.x,y:a.y,trace_width:a.route_type==="wire"?a.width:.5}]),s=Poo(n,.5),r=g.route[0].layer;return Q.push({_pcb_drawing_object_id:`polygon_${Oc++}`,_element:g,pcb_drawing_type:"polygon",points:s,layer:r}),g.route.forEach(a=>{a.route_type==="via"&&Q.push({_pcb_drawing_object_id:`circle_${Oc++}`,_element:g,pcb_drawing_type:"circle",x:a.x,y:a.y,r:a.outer_diameter/2,layer:a.from_layer})}),Q}let i=null,E=null;for(const n of g.route)n.route_type==="wire"&&(i!==null&&E!==null&&Q.push({_pcb_drawing_object_id:`line_${Oc++}`,_element:g,pcb_drawing_type:"line",x1:i,y1:E,x2:n.x,y2:n.y,width:n.width,squareCap:!1,layer:n.layer}),i=n.x,E=n.y);return Q}case"pcb_via":{const{x:Q,y:i,outer_diameter:E,hole_diameter:n}=g,s=g.from_layer,r=g.to_layer,a=g.layers,c=[];s&&r?c.push(s,r):a&&Array.isArray(a)?c.push(...a):c.push("top","bottom");const h=[];for(const l of c)h.push({_pcb_drawing_object_id:`circle_${Oc++}`,pcb_drawing_type:"circle",x:Q,y:i,r:E/2,layer:l,_element:g,_parent_pcb_component:t,_parent_source_component:o});return h.push({_pcb_drawing_object_id:`circle_${Oc++}`,pcb_drawing_type:"circle",x:Q,y:i,r:n/2,layer:"drill",_element:g}),h}case"pcb_plated_hole":if(g.shape==="circle"){const{x:Q,y:i,hole_diameter:E,outer_diameter:n}=g;return[{_pcb_drawing_object_id:`circle_${Oc++}`,pcb_drawing_type:"circle",x:Q,y:i,r:n/2,layer:"top",_element:g,_parent_pcb_component:t,_parent_source_component:o,_source_port:C},{_pcb_drawing_object_id:`circle_${Oc++}`,pcb_drawing_type:"circle",x:Q,y:i,r:E/2,layer:"drill",_element:g}]}else if(g.shape==="oval"){const{x:Q,y:i,outer_height:E,outer_width:n,hole_height:s,hole_width:r}=g;return[{_pcb_drawing_object_id:`oval_${Oc++}`,pcb_drawing_type:"oval",x:Q,y:i,rX:n/2,rY:E/2,layer:"top",_element:g,_parent_pcb_component:t,_parent_source_component:o,_source_port:C},{_pcb_drawing_object_id:`oval_${Oc++}`,_element:g,pcb_drawing_type:"oval",x:Q,y:i,rX:r/2,rY:s/2,layer:"drill"}]}else if(g.shape==="pill"){const{x:Q,y:i,outer_height:E,outer_width:n,hole_height:s,hole_width:r}=g;return[{_pcb_drawing_object_id:`pill_${Oc++}`,pcb_drawing_type:"pill",x:Q,y:i,w:n,h:E,layer:"top",_element:g,_parent_pcb_component:t,_parent_source_component:o,_source_port:C,ccw_rotation:g.ccw_rotation},{_pcb_drawing_object_id:`pill_${Oc++}`,_element:g,pcb_drawing_type:"pill",x:Q,y:i,w:r,h:s,layer:"drill",ccw_rotation:g.ccw_rotation}]}else if(g.shape==="circular_hole_with_rect_pad"){const{x:Q,y:i,hole_diameter:E,rect_pad_width:n,rect_pad_height:s,rect_border_radius:r,hole_offset_x:a,hole_offset_y:c}=g,h=sg.parse(a??0),l=sg.parse(c??0);return[{_pcb_drawing_object_id:`rect_${Oc++}`,pcb_drawing_type:"rect",x:Q,y:i,w:n,h:s,layer:"top",_element:g,_parent_pcb_component:t,_parent_source_component:o,_source_port:C,roundness:r},{_pcb_drawing_object_id:`rect_${Oc++}`,pcb_drawing_type:"rect",x:Q,y:i,w:n,h:s,layer:"bottom",_element:g,_parent_pcb_component:t,_parent_source_component:o,_source_port:C,roundness:r,is_hoverable:!1},{_pcb_drawing_object_id:`circle_${Oc++}`,_element:g,pcb_drawing_type:"circle",x:Q+h,y:i+l,r:E/2,layer:"drill",is_hoverable:!1}]}else if(g.shape==="pill_hole_with_rect_pad"){const{x:Q,y:i,hole_width:E,hole_height:n,rect_pad_width:s,rect_pad_height:r,rect_border_radius:a}=g;return[{_pcb_drawing_object_id:`rect_${Oc++}`,pcb_drawing_type:"rect",x:Q,y:i,w:s,h:r,layer:"top",_element:g,_parent_pcb_component:t,_parent_source_component:o,_source_port:C,roundness:a},{_pcb_drawing_object_id:`rect_${Oc++}`,pcb_drawing_type:"rect",x:Q,y:i,w:s,h:r,layer:"bottom",_element:g,_parent_pcb_component:t,_parent_source_component:o,_source_port:C,roundness:a,is_hoverable:!1},{_pcb_drawing_object_id:`pill_${Oc++}`,_element:g,pcb_drawing_type:"pill",x:Q,y:i,w:E,h:n,layer:"drill",is_hoverable:!1}]}else if(g.shape==="rotated_pill_hole_with_rect_pad"){const{x:Q,y:i,hole_width:E,hole_height:n,hole_ccw_rotation:s,rect_pad_width:r,rect_pad_height:a,rect_ccw_rotation:c,rect_border_radius:h}=g;return[{_pcb_drawing_object_id:`rect_${Oc++}`,pcb_drawing_type:"rect",x:Q,y:i,w:r,h:a,layer:"top",_element:g,_parent_pcb_component:t,_parent_source_component:o,_source_port:C,ccw_rotation:c,roundness:h},{_pcb_drawing_object_id:`rect_${Oc++}`,pcb_drawing_type:"rect",x:Q,y:i,w:r,h:a,layer:"bottom",_element:g,_parent_pcb_component:t,_parent_source_component:o,_source_port:C,ccw_rotation:c,roundness:h,is_hoverable:!1},{_pcb_drawing_object_id:`pill_${Oc++}`,_element:g,pcb_drawing_type:"pill",x:Q,y:i,w:E,h:n,layer:"drill",ccw_rotation:s,is_hoverable:!1}]}else if(g.shape==="hole_with_polygon_pad"){const{x:Q,y:i,pad_outline:E,hole_shape:n,hole_diameter:s,hole_width:r,hole_height:a,layers:c,hole_offset_x:h,hole_offset_y:l}=g,D=sg.parse(h??0),d=sg.parse(l??0),y=E,w=[];if(y&&Array.isArray(y)){const m=neg(y).map(p=>({x:p.x+Q,y:p.y+i}));for(const p of c||["top","bottom"])w.push({_pcb_drawing_object_id:`polygon_${Oc++}`,pcb_drawing_type:"polygon",points:m,layer:p,_element:g,_parent_pcb_component:t,_parent_source_component:o,_source_port:C})}const u={x:Q+D,y:i+d},G=[];return n==="circle"?G.push({_pcb_drawing_object_id:`circle_${Oc++}`,pcb_drawing_type:"circle",x:u.x,y:u.y,r:(s??0)/2,layer:"drill",_element:g,_parent_pcb_component:t,_parent_source_component:o}):n==="oval"?G.push({_pcb_drawing_object_id:`oval_${Oc++}`,pcb_drawing_type:"oval",x:u.x,y:u.y,rX:(r??0)/2,rY:(a??0)/2,layer:"drill",_element:g,_parent_pcb_component:t,_parent_source_component:o}):(n==="pill"||n==="rotated_pill")&&G.push({_pcb_drawing_object_id:`pill_${Oc++}`,pcb_drawing_type:"pill",x:u.x,y:u.y,w:r??0,h:a??0,layer:"drill",_element:g,_parent_pcb_component:t,_parent_source_component:o,ccw_rotation:g.ccw_rotation}),[...w,...G]}else return[]}return[]};function qoo(g,A,I){const e=document.createElement("canvas");e.width=e.height=1;const t=e.getContext("2d");return g.filter(o=>o.type!=="pcb_copper_pour"||o.layer!==I?!1:(ndI({ctx:t,pour:o,realToCanvasMat:uJ(),colorMap:Lw}),t.isPointInPath(A.x,A.y,o.shape==="brep"?"evenodd":"nonzero")))}function Too(g){return g.type==="pcb_copper_pour"}function M2I({canvas:g,elements:A,layers:I,realToCanvasMat:e,opacity:t=1}){const o=A.filter(Too);if(o.length===0||t<=0)return;const B=new XE(g);B.configure({colorOverrides:{copper:Object.fromEntries(Object.entries(Lw.copper).map(([C,Q])=>[C,uQ(Q).alpha(t).rgb().string()]))}}),B.realToCanvasMat=e,B.drawElements(o,{layers:I})}var TwA=(g,A,I)=>I(g,A),S2I=(g,A,I,e,t)=>{const o=t*Math.PI/180,B=Math.cos(o),C=Math.sin(o),Q=g-I,i=A-e,E=Q*B-i*C,n=Q*C+i*B;return{x:E+I,y:n+e}},ieA=g=>{if(g.length===0)return null;let A=g[0].x,I=g[0].x,e=g[0].y,t=g[0].y;for(const o of g)A=TwA(A,o.x,Math.min),I=TwA(I,o.x,Math.max),e=TwA(e,o.y,Math.min),t=TwA(t,o.y,Math.max);return{minX:A,maxX:I,minY:e,maxY:t}},Zoo=(g,A)=>({minX:Math.min(g.minX,A.minX),maxX:Math.max(g.maxX,A.maxX),minY:Math.min(g.minY,A.minY),maxY:Math.max(g.maxY,A.maxY)}),Ooo=(g,A)=>g?Zoo(g,A):A,seg=g=>{switch(g.pcb_drawing_type){case"line":{const A=(g.width??0)/2,I=[{x:g.x1,y:g.y1},{x:g.x2,y:g.y2}],e=ieA(I);return e?{minX:e.minX-A,maxX:e.maxX+A,minY:e.minY-A,maxY:e.maxY+A}:null}case"rect":{const A=g.w/2,I=g.h/2,e=[{x:g.x-A,y:g.y-I},{x:g.x+A,y:g.y-I},{x:g.x+A,y:g.y+I},{x:g.x-A,y:g.y+I}],t=g.ccw_rotation??0,o=t===0?e:e.map(B=>S2I(B.x,B.y,g.x,g.y,t));return ieA(o)}case"circle":return{minX:g.x-g.r,maxX:g.x+g.r,minY:g.y-g.r,maxY:g.y+g.r};case"oval":return{minX:g.x-g.rX,maxX:g.x+g.rX,minY:g.y-g.rY,maxY:g.y+g.rY};case"pill":{const A=g.w/2,I=g.h/2,e=[{x:g.x-A,y:g.y-I},{x:g.x+A,y:g.y-I},{x:g.x+A,y:g.y+I},{x:g.x-A,y:g.y+I}],t=g.ccw_rotation??0,o=t===0?e:e.map(B=>S2I(B.x,B.y,g.x,g.y,t));return ieA(o)}case"polygon":return ieA(g.points);case"polygon_with_arcs":{const A=g.brep_shape.outer_ring.vertices.map(I=>({x:I.x,y:I.y}));return ieA(A)}case"text":{const A=g.size??0,I=g.text?g.text.length*A*.6:0,e=A;if(I===0&&e===0)return{minX:g.x,maxX:g.x,minY:g.y,maxY:g.y};const t=I/2,o=e/2;return{minX:g.x-t,maxX:g.x+t,minY:g.y-o,maxY:g.y+o}}default:return null}},Woo=64,Voo=256,joo=8;function f2I({cellX:g,cellY:A}){return`${g}:${A}`}function zoo(g){let A=1/0,I=1/0,e=-1/0,t=-1/0;for(const C of g){const Q=seg(C);Q&&(A=Math.min(A,Q.minX),I=Math.min(I,Q.minY),e=Math.max(e,Q.maxX),t=Math.max(t,Q.maxY))}if(!Number.isFinite(A))return 1;const o=Math.max(e-A,t-I),B=Math.sqrt(Math.max(1,g.length/joo));return Math.max(.5,Math.min(20,o/B))}function R2I(g){const A=zoo(g),I=new Map,e=new Map,t=[];let o=0;for(const[B,C]of g.entries()){e.set(C,B),C.pcb_drawing_type==="line"&&C._element?.type==="pcb_trace"&&(o=Math.max(o,C.width));const Q=seg(C);if(!Q){t.push(C);continue}const i=Math.floor(Q.minX/A),E=Math.floor(Q.maxX/A),n=Math.floor(Q.minY/A),s=Math.floor(Q.maxY/A);if((E-i+1)*(s-n+1)>Woo){t.push(C);continue}for(let a=i;a<=E;a++)for(let c=n;c<=s;c++){const h=f2I({cellX:a,cellY:c}),l=I.get(h)??[];l.push(C),I.set(h,l)}}return{cellSize:A,globalPrimitives:t,maxTraceWidth:o,primitiveIndexByPrimitive:e,primitives:g,primitivesByCell:I}}function N2I({point:g,realToScreenScale:A,spatialIndex:I}){const e=Math.max(Math.abs(A),Number.EPSILON),t=Math.max(I.maxTraceWidth*25,2)/e,o=Math.floor((g.x-t)/I.cellSize),B=Math.floor((g.x+t)/I.cellSize),C=Math.floor((g.y-t)/I.cellSize),Q=Math.floor((g.y+t)/I.cellSize);if((B-o+1)*(Q-C+1)>Voo)return I.primitives;const E=new Set(I.globalPrimitives);for(let n=o;n<=B;n++)for(let s=C;s<=Q;s++){const r=f2I({cellX:n,cellY:s}),a=I.primitivesByCell.get(r);if(a)for(const c of a)E.add(c)}return[...E].sort((n,s)=>(I.primitiveIndexByPrimitive.get(n)??Number.MAX_SAFE_INTEGER)-(I.primitiveIndexByPrimitive.get(s)??Number.MAX_SAFE_INTEGER))}function Xoo({primitivesWithoutInteractionMetadata:g,drawingObjectIdsWithMouseOver:A,primitiveIdsInMousedOverNet:I}){const e=[],t=new Set(I);for(const o of g){const B={...o},C=o._element,Q=o._parent_pcb_component;o?.layer==="drill"?(B.is_in_highlighted_net=!1,B.is_mouse_over=!1):A.has(o._pcb_drawing_object_id)?B.is_mouse_over=!0:C&&("pcb_trace_id"in C&&t.has(C.pcb_trace_id)||"pcb_port_id"in C&&t.has(C.pcb_port_id)||"pcb_via_id"in C&&t.has(C.pcb_via_id)||"pcb_component_id"in C&&t.has(C.pcb_component_id)||Q&&"pcb_component_id"in Q&&t.has(Q.pcb_component_id))?B.is_in_highlighted_net=!0:(B.is_in_highlighted_net=!1,B.is_mouse_over=!1),e.push(B)}return e}var x2I=g=>{const A=new Map,I=new Map,e=new Map,t=new Map,o=new Map;for(const B of g)B.type==="pcb_trace"&&B.pcb_trace_id?A.set(B.pcb_trace_id,B):B.type==="pcb_port"&&B.pcb_port_id?I.set(B.pcb_port_id,B):B.type==="pcb_via"&&B.pcb_via_id?e.set(B.pcb_via_id,B):B.type==="pcb_component"&&B.pcb_component_id?t.set(B.pcb_component_id,B):B.type==="pcb_board"&&B.pcb_board_id&&o.set(B.pcb_board_id,B);return{tracesById:A,portsById:I,viasById:e,componentsById:t,boardsById:o}},j2=(g,A)=>A?g?{minX:Math.min(g.minX,A.minX),maxX:Math.max(g.maxX,A.maxX),minY:Math.min(g.minY,A.minY),maxY:Math.max(g.maxY,A.maxY)}:A:g,_5=(g,A=.45)=>({minX:g.x-A,maxX:g.x+A,minY:g.y-A,maxY:g.y+A}),$oo=g=>{if(g.length===0)return null;let A=null;for(const I of g){const e=Math.max((I.width??.2)/2,.3);A=j2(A,_5(I,e))}return A},F2I=g=>{if(!g?.center)return null;const A=Math.max(g.width??0,1.2),I=Math.max(g.height??0,1.2);return{minX:g.center.x-A/2,maxX:g.center.x+A/2,minY:g.center.y-I/2,maxY:g.center.y+I/2}},ABo=g=>!g?.center||typeof g.width!="number"||typeof g.height!="number"?null:{minX:g.center.x-g.width/2,maxX:g.center.x+g.width/2,minY:g.center.y-g.height/2,maxY:g.center.y+g.height/2},gBo=(g,A)=>({minX:g.minX-A,maxX:g.maxX+A,minY:g.minY-A,maxY:g.maxY+A}),IBo=(g,A=.35)=>{const I=$h(g);return I?gBo(I,A):null},U2I=({error:g,tracesById:A,portsById:I,viasById:e,componentsById:t})=>{if(g.center)return g.center;if(g.pcb_center)return g.pcb_center;if(g.component_center)return g.component_center;if(g.pcb_via_ids?.length){const o=g.pcb_via_ids.map(B=>e.get(B)).filter(Boolean);if(o.length>0)return{x:o.reduce((B,C)=>B+C.x,0)/o.length,y:o.reduce((B,C)=>B+C.y,0)/o.length}}if(g.pcb_port_ids?.length){const o=g.pcb_port_ids.map(B=>I.get(B)).filter(Boolean);if(o.length>0)return{x:o.reduce((B,C)=>B+C.x,0)/o.length,y:o.reduce((B,C)=>B+C.y,0)/o.length}}if(g.pcb_trace_id){const o=A.get(g.pcb_trace_id);if(o?.route?.length){const B=Math.floor(o.route.length/2);return{x:o.route[B].x,y:o.route[B].y}}}return g.pcb_component_id?t.get(g.pcb_component_id)?.center??null:null},eBo=({error:g,indexes:A})=>U2I({error:g,...A}),tBo=({error:g,boardsById:A})=>{if(!g.component_bounds||!g.pcb_board_id)return null;const I=ABo(A.get(g.pcb_board_id));if(!I)return null;const e=g.component_bounds,t=[];return e.min_x<I.minX&&(t.push({x:I.minX,y:Math.max(e.min_y,I.minY)}),t.push({x:I.minX,y:Math.min(e.max_y,I.maxY)})),e.max_x>I.maxX&&(t.push({x:I.maxX,y:Math.max(e.min_y,I.minY)}),t.push({x:I.maxX,y:Math.min(e.max_y,I.maxY)})),e.min_y<I.minY&&(t.push({x:Math.max(e.min_x,I.minX),y:I.minY}),t.push({x:Math.min(e.max_x,I.maxX),y:I.minY})),e.max_y>I.maxY&&(t.push({x:Math.max(e.min_x,I.minX),y:I.maxY}),t.push({x:Math.min(e.max_x,I.maxX),y:I.maxY})),IBo(t,.3)},J2I=new Set(["source_failed_to_create_component_error"]),oBo=({error:g,indexes:A})=>{if(J2I.has(g.error_type)||J2I.has(g.type))return null;let I=null;const e=U2I({error:g,...A});if(e&&(I=j2(I,_5(e,.35))),g.error_type==="pcb_component_outside_board_error"?I=j2(I,tBo({error:g,boardsById:A.boardsById})):g.component_bounds&&!e&&(I=j2(I,{minX:g.component_bounds.min_x,maxX:g.component_bounds.max_x,minY:g.component_bounds.min_y,maxY:g.component_bounds.max_y})),g.center&&!e&&(I=j2(I,_5(g.center))),g.pcb_center&&!e&&(I=j2(I,_5(g.pcb_center))),g.component_center&&!e&&(I=j2(I,_5(g.component_center))),g.pcb_port_ids&&!e)for(const t of g.pcb_port_ids){const o=A.portsById.get(t);o&&(I=j2(I,_5({x:o.x,y:o.y},.4)))}if(g.pcb_trace_id&&!e){const t=A.tracesById.get(g.pcb_trace_id);t?.route&&(I=j2(I,$oo(t.route)))}if(g.pcb_via_ids)for(const t of g.pcb_via_ids){const o=A.viasById.get(t);o&&(I=j2(I,_5({x:o.x,y:o.y},Math.max((o.outer_diameter??.5)/2,.28))))}if(g.pcb_component_id&&!e&&(I=j2(I,F2I(A.componentsById.get(g.pcb_component_id)))),g.pcb_component_ids&&!e)for(const t of g.pcb_component_ids)I=j2(I,F2I(A.componentsById.get(t)));return I},P2I=({bounds:g,width:A,height:I})=>{const e={x:(g.minX+g.maxX)/2,y:(g.minY+g.maxY)/2},t=Math.max(g.maxX-g.minX,.8)+1.4,o=Math.max(g.maxY-g.minY,.8)+1.4,B=Math.min(A/t,I/o,240)*.92;return bw(qc(A/2,I/2),GJ(B,-B,0,0),qc(-e.x,-e.y))},BBo=g=>{const A=new Set;g.pcb_trace_id&&A.add(g.pcb_trace_id);for(const I of g.pcb_port_ids??[])A.add(I);for(const I of g.pcb_via_ids??[])A.add(I);g.pcb_component_id&&A.add(g.pcb_component_id);for(const I of g.pcb_component_ids??[])A.add(I);return[...A]},CZ=(g,A)=>{const I=["pcb_trace_error_id","pcb_via_clearance_error_id","pcb_component_outside_board_error_id","source_failed_to_create_component_error_id","pcb_error_id"];for(const e of I)if(typeof g?.[e]=="string"&&g[e].length>0)return g[e];for(const[e,t]of Object.entries(g??{}))if(e.endsWith("_error_id")&&typeof t=="string"&&t.length>0)return t;return`error_${A}_${g?.error_type}_${g?.message?.slice(0,20)}`},K2I=(g,A)=>A?g.find((I,e)=>I.type?.includes("error")?CZ(I,e)===A:!1)??null:null,CBo=g=>1-(1-g)**3,QBo=(g,A,I)=>({a:g.a+(A.a-g.a)*I,b:g.b+(A.b-g.b)*I,c:g.c+(A.c-g.c)*I,d:g.d+(A.d-g.d)*I,e:g.e+(A.e-g.e)*I,f:g.f+(A.f-g.f)*I}),L2I=g=>{g!==null&&window.cancelAnimationFrame(g)},iBo=({startTransform:g,endTransform:A,durationMs:I,onUpdate:e,setAnimationFrameId:t,onComplete:o})=>{const B=performance.now(),C=i=>{const E=i-B,n=Math.min(1,E/I),s=CBo(n);if(e(QBo(g,A,s)),n<1){t(window.requestAnimationFrame(C));return}t(null),o?.()},Q=window.requestAnimationFrame(C);return t(Q),Q},ZwA=g=>g?.trim()||null;function Y2I(g){const A=new Map,I=new Map;for(const e of g)e.type==="source_net"?A.set(e.source_net_id,e):e.type==="source_trace"&&I.set(e.source_trace_id,e);return{sourceNetById:A,sourceTraceById:I}}function aeg({primitiveElement:g,traceOverlayElementIndex:A}){const I=g.source_trace_id;if(!I)return null;const e=A.sourceTraceById.get(I),t=ZwA(e?.name);if(t)return t;const o=A.sourceNetById.get(I),B=ZwA(o?.name);if(B)return B;for(const C of e?.connected_source_net_ids??[]){const Q=ZwA(A.sourceNetById.get(C)?.name);if(Q)return Q}return null}function _2I({primitiveElement:g,traceOverlayElementIndex:A}){const I=g.source_trace_id,e=I?A.sourceTraceById.get(I):void 0,t=g.trace_length,o=typeof t=="number",B=e?.max_length,C=o?`${t.toFixed(3)}${typeof B=="number"?` / ${B}`:""} mm`:"",Q=aeg({primitiveElement:g,traceOverlayElementIndex:A})??ZwA(e?.display_name);if(!C&&!Q)return null;const i=!!(o&&typeof B=="number"&&t>B);return{text:C,name:Q,isOverLength:i}}function QZ(g,A){if(!g)return;const I=[];for(const e of[`${g.type}_id`,"pcb_port_id","pcb_trace_id","source_trace_id","source_net_id"]){const t=g[e];typeof t=="string"&&I.push(t)}for(const e of I){const t=A.getNetConnectedToId(e);if(t)return t}if("source_net_id"in g)return g.source_net_id}function b2I(g){return g&&["pcb_trace","pcb_smtpad","pcb_plated_hole","pcb_via","pcb_copper_pour"].includes(g.type)}function EBo(g,A,I){const e=Y2I(A),t=g.type==="pcb_trace"?aeg({primitiveElement:g,traceOverlayElementIndex:e}):null;if(t)return t;const o=QZ(g,I),B=o?A.filter(C=>QZ(C,I)===o):[];for(const C of["source_net","source_trace"])for(const Q of B)if(Q.type===C&&"name"in Q&&typeof Q.name=="string"&&Q.name.trim())return Q.name.trim();if(g.type==="pcb_trace"){const C=_2I({primitiveElement:g,traceOverlayElementIndex:e})?.name;if(C)return C}for(const C of B)if(C.type==="source_trace"&&C.display_name?.trim())return C.display_name.trim();return"Net"}function nBo(g,A,I){return A.flatMap(e=>{if(e.type!=="source_bus")return[];const t=[...new Set(e.source_trace_ids.flatMap(o=>{const B=I.getNetConnectedToId(o);return B?[B]:[]}))];return t.includes(g)?[{id:e.source_bus_id,name:e.name?.trim()||"Bus",netIds:t}]:[]})}var sBo=(g,A)=>{if(g?.type!=="pcb_smtpad"&&g?.type!=="pcb_plated_hole")return;const I=A.find(t=>t.type==="pcb_component"&&t.pcb_component_id===g.pcb_component_id);if(I?.type!=="pcb_component")return;const e=A.find(t=>t.type==="source_component"&&t.source_component_id===I.source_component_id);if(e?.type==="source_component")return{source_component_id:e.source_component_id,pcb_component_id:I.pcb_component_id,refdes:e.name,manufacturer_part_number:e.manufacturer_part_number}},ho={board:{anchor:"rgb(255, 38, 226)",aux_items:"rgb(255, 255, 255)",b_adhes:"rgb(0, 0, 132)",b_crtyd:"rgb(38, 233, 255)",b_fab:"rgb(88, 93, 132)",b_mask:"rgba(2, 255, 238, 0.400)",b_paste:"rgb(0, 194, 194)",b_silks:"rgb(242, 237, 161)",background:"rgb(0, 16, 35)",cmts_user:"rgb(89, 148, 220)",copper:{b:"rgb(77, 127, 196)",f:"rgb(200, 52, 52)",in1:"rgb(127, 200, 127)",in10:"rgb(237, 124, 51)",in11:"rgb(91, 195, 235)",in12:"rgb(247, 111, 142)",in13:"rgb(167, 165, 198)",in14:"rgb(40, 204, 217)",in15:"rgb(232, 178, 167)",in16:"rgb(242, 237, 161)",in17:"rgb(237, 124, 51)",in18:"rgb(91, 195, 235)",in19:"rgb(247, 111, 142)",in2:"rgb(206, 125, 44)",in20:"rgb(167, 165, 198)",in21:"rgb(40, 204, 217)",in22:"rgb(232, 178, 167)",in23:"rgb(242, 237, 161)",in24:"rgb(237, 124, 51)",in25:"rgb(91, 195, 235)",in26:"rgb(247, 111, 142)",in27:"rgb(167, 165, 198)",in28:"rgb(40, 204, 217)",in29:"rgb(232, 178, 167)",in3:"rgb(79, 203, 203)",in30:"rgb(242, 237, 161)",in4:"rgb(219, 98, 139)",in5:"rgb(167, 165, 198)",in6:"rgb(40, 204, 217)",in7:"rgb(232, 178, 167)",in8:"rgb(242, 237, 161)",in9:"rgb(141, 203, 129)"},cursor:"rgb(255, 255, 255)",drc:"rgb(194, 194, 194)",drc_error:"rgba(215, 91, 107, 0.800)",drc_exclusion:"rgb(255, 255, 255)",drc_warning:"rgba(255, 208, 66, 0.902)",dwgs_user:"rgb(194, 194, 194)",eco1_user:"rgb(180, 219, 210)",eco2_user:"rgb(216, 200, 82)",edge_cuts:"rgb(208, 210, 205)",f_adhes:"rgb(132, 0, 132)",f_crtyd:"rgb(255, 0, 245)",f_fab:"rgb(175, 175, 175)",f_mask:"rgba(216, 100, 255, 0.400)",f_paste:"rgba(180, 160, 154, 0.902)",f_silks:"rgb(242, 237, 161)",footprint_text_back:"rgb(0, 0, 132)",footprint_text_front:"rgb(194, 194, 194)",footprint_text_invisible:"rgb(132, 132, 132)",grid:"rgb(132, 132, 132)",grid_axes:"rgb(194, 194, 194)",margin:"rgb(255, 38, 226)",microvia:"rgb(0, 132, 132)",no_connect:"rgb(0, 0, 132)",pad_back:"rgb(77, 127, 196)",pad_front:"rgb(200, 52, 52)",pad_plated_hole:"rgb(194, 194, 0)",pad_through_hole:"rgb(227, 183, 46)",plated_hole:"rgb(26, 196, 210)",ratsnest:"rgba(245, 255, 213, 0.702)",select_overlay:"rgb(4, 255, 67)",soldermaskWithCopper:{top:"rgb(18, 82, 50)",bottom:"rgb(77, 127, 196)"},soldermask:{top:"rgb(12, 55, 33)",bottom:"rgb(12, 55, 33)"},through_via:"rgb(236, 236, 236)",user_1:"rgb(194, 194, 194)",user_2:"rgb(89, 148, 220)",user_3:"rgb(180, 219, 210)",user_4:"rgb(216, 200, 82)",user_5:"rgb(194, 194, 194)",user_6:"rgb(89, 148, 220)",user_7:"rgb(180, 219, 210)",user_8:"rgb(216, 200, 82)",user_9:"rgb(232, 178, 167)",via_blind_buried:"rgb(187, 151, 38)",via_hole:"rgb(227, 183, 46)",via_micro:"rgb(0, 132, 132)",via_through:"rgb(236, 236, 236)",worksheet:"rgb(200, 114, 171)"}},yk=(g,A=1)=>{if(Math.abs(g.a)!==Math.abs(g.d))throw new Error("Cannot scale non-uniformly");return A*Math.abs(g.a)},EeA={red:"red",black:"black",green:"green",board:"rgb(255, 255, 255)",other:"#eee",top:ho.board.copper.f,inner1:ho.board.copper.in1,inner2:ho.board.copper.in2,inner3:ho.board.copper.in3,inner4:ho.board.copper.in4,inner5:ho.board.copper.in5,inner6:ho.board.copper.in6,inner7:ho.board.copper.in7,inner8:ho.board.copper.in8,bottom:ho.board.copper.b,drill:ho.board.anchor,keepout:ho.board.background,tkeepout:ho.board.b_crtyd,tplace:ho.board.b_silks,top_courtyard:ho.board.f_crtyd,bottom_courtyard:ho.board.b_crtyd,top_silkscreen:ho.board.f_silks,bottom_silkscreen:ho.board.b_silks,top_fabrication:ho.board.f_fab,bottom_fabrication:ho.board.b_fab,soldermask_top:ho.board.soldermask.top,soldermask_bottom:ho.board.soldermask.bottom,soldermask_with_copper_top:ho.board.soldermaskWithCopper.top,soldermask_with_copper_bottom:ho.board.soldermaskWithCopper.bottom,bottom_notes:ho.board.user_2,top_notes:ho.board.user_2,...ho.board},aBo=["board","bottom","soldermask_bottom","bottom_silkscreen","top","soldermask_top","bottom_courtyard","bottom_fabrication","top_courtyard","top_fabrication","edge_cuts","top_silkscreen"],rBo=class{canvasLayerMap;ctxLayerMap;aperture;transform;foregroundLayer="top";hiddenLayerOpacity=.2;xRayNetActive=!1;lastPoint;constructor(g){this.canvasLayerMap=g,this.ctxLayerMap=Object.fromEntries(Object.entries(g).map(([A,I])=>[A,I.getContext("2d")])),this.transform=uJ(),this.transform.d*=-1,this.transform=bw(this.transform,qc(0,-500)),this.lastPoint={x:0,y:0},this.equip({})}clear(){for(const g of Object.values(this.ctxLayerMap))g.clearRect(0,0,g.canvas.width,g.canvas.height)}equip(g){this.aperture={fontSize:0,shape:"circle",mode:"add",size:0,color:"red",layer:"top",opacity:this.foregroundLayer===g.color?1:.5,...g}}drawMeshPattern(g,A,I,e,t,o=45){const B=this.getLayerCtx(),[C,Q]=Mt(this.transform,[g,A]),[i,E]=Mt(this.transform,[g+I,A+e]),n=yk(this.transform,t);B.lineWidth=1,B.strokeStyle=this.aperture.color;const s=r=>{const a=Math.sin(r),c=Math.cos(r),h=Math.sqrt((i-C)**2+(E-Q)**2);for(let l=-h;l<=h;l+=n)B.beginPath(),B.moveTo(C+l*c-h*a,Q+l*a+h*c),B.lineTo(C+l*c+h*a,Q+l*a-h*c),B.stroke()};s(o*Math.PI/180),s((o+90)*Math.PI/180)}rect({x:g,y:A,w:I,h:e,mesh_fill:t,is_filled:o=!0,has_stroke:B,is_stroke_dashed:C,stroke_width:Q,roundness:i}){const[E,n]=Mt(this.transform,[g-I/2,A-e/2]),[s,r]=Mt(this.transform,[g+I/2,A+e/2]);this.applyAperture();const a=this.getLayerCtx(),c=i?yk(this.transform,i):0,h=B===void 0?o===!1:B;if(t)a.save(),a.beginPath(),c>0&&a.roundRect?a.roundRect(E,n,s-E,r-n,c):a.rect(E,n,s-E,r-n),a.clip(),this.drawMeshPattern(g-I/2,A-e/2,I,e,.15),a.restore(),c>0&&a.roundRect?(a.beginPath(),a.roundRect(E,n,s-E,r-n,c),a.stroke()):a.strokeRect(E,n,s-E,r-n);else if(o!==!1&&(c>0&&a.roundRect?(a.beginPath(),a.roundRect(E,n,s-E,r-n,c),a.fill()):a.fillRect(E,n,s-E,r-n)),h){const l=a.lineWidth;if(Q!==void 0&&(a.lineWidth=yk(this.transform,Q)),C){let D=[];const d=Math.abs(this.transform.a);if(d>0){const w=.1*d,u=w*1.3;w>.5&&(D=[w,u])}a.setLineDash(D)}c>0&&a.roundRect?(a.beginPath(),a.roundRect(E,n,s-E,r-n,c),a.stroke()):a.strokeRect(E,n,s-E,r-n),C&&a.setLineDash([]),Q!==void 0&&(a.lineWidth=l)}}rotatedRect(g,A,I,e,t,o,B){const C=this.getLayerCtx();this.applyAperture();const[Q,i]=Mt(this.transform,[g-I/2,A-e/2]),[E,n]=Mt(this.transform,[g+I/2,A+e/2]),s=o?yk(this.transform,o):0;C.save();const[r,a]=Mt(this.transform,[g,A]);C.translate(r,a);const c=360-t;t&&C.rotate(c*Math.PI/180),C.translate(-r,-a),B?(C.beginPath(),s>0&&C.roundRect?C.roundRect(Q,i,E-Q,n-i,s):C.rect(Q,i,E-Q,n-i),C.clip(),this.drawMeshPattern(g-I/2,A-e/2,I,e,.15),s>0&&C.roundRect?(C.beginPath(),C.roundRect(Q,i,E-Q,n-i,s),C.stroke()):C.strokeRect(Q,i,E-Q,n-i)):s>0&&C.roundRect?(C.beginPath(),C.roundRect(Q,i,E-Q,n-i,s),C.fill()):C.fillRect(Q,i,E-Q,n-i),C.restore()}rotatedPill(g,A,I,e,t){const o=this.getLayerCtx();this.applyAperture(),o.save();const[B,C]=Mt(this.transform,[g,A]);o.translate(B,C);const Q=360-t;t&&o.rotate(Q*Math.PI/180),o.translate(-B,-C),this.pill(g,A,I,e),o.restore()}circle(g,A,I,e,t=!0){const o=yk(this.transform,I),[B,C]=Mt(this.transform,[g,A]);this.applyAperture();const Q=this.getLayerCtx();e?(Q.save(),Q.beginPath(),Q.arc(B,C,o,0,2*Math.PI),Q.clip(),this.drawMeshPattern(g-I,A-I,I*2,I*2,.15),Q.restore(),Q.beginPath(),Q.arc(B,C,o,0,2*Math.PI),Q.stroke()):(Q.beginPath(),Q.arc(B,C,o,0,2*Math.PI),Q.fill())}oval(g,A,I,e){const t=yk(this.transform,I),o=yk(this.transform,e),[B,C]=Mt(this.transform,[g,A]);this.applyAperture();const Q=this.getLayerCtx();Q.beginPath(),Q.ellipse(B,C,t,o,0,0,2*Math.PI),Q.fill(),Q.closePath()}pill(g,A,I,e){const[t,o]=Mt(this.transform,[g-I/2,A+e/2]),B=yk(this.transform,I),C=yk(this.transform,e),Q=Math.min(B,C)/2;this.applyAperture();const i=this.getLayerCtx();i.beginPath(),i.arc(t+Q,o+Q,Q,Math.PI,Math.PI*1.5),i.arc(t+B-Q,o+Q,Q,Math.PI*1.5,0),i.arc(t+B-Q,o+C-Q,Q,0,Math.PI*.5),i.arc(t+Q,o+C-Q,Q,Math.PI*.5,Math.PI),i.fill(),i.closePath()}polygon(g){if(g.length<3)return;this.applyAperture();const A=this.getLayerCtx(),I=g.map(t=>Mt(this.transform,[t.x,t.y]));A.beginPath(),A.moveTo(I[0][0],I[0][1]);for(let t=1;t<I.length;t++)A.lineTo(I[t][0],I[t][1]);A.closePath(),A.fill("evenodd");const e=yk(this.transform,this.aperture.size);e>0&&(A.lineWidth=e,A.stroke())}debugText(g,A,I){const[e,t]=Mt(this.transform,[A,I]);this.applyAperture();const o=this.getLayerCtx();o.font="10px sans-serif",o.fillText(g,e,t)}getLayerCtx(){const g=this.ctxLayerMap[this.aperture.layer];if(!g)throw new Error(`No context for layer "${this.aperture.layer}"`);return g}getLayerOpacity(g){if(this.xRayNetActive)return/^(top|bottom|inner\d+)$/.test(g)?this.hiddenLayerOpacity:0;const A=this.foregroundLayer,I=(A==="top"||A==="bottom")&&(g.startsWith(`${A}_`)||g.endsWith(`_${A}`)),e=["board","drill","edge_cuts","other"].includes(g);return g===A||I||e?1:this.hiddenLayerOpacity}orderAndFadeLayers(){const{canvasLayerMap:g,foregroundLayer:A}=this,e=["board",...Object.keys(g).filter(n=>/^inner\d+$/.test(n)).sort((n,s)=>Number(s.slice(5))-Number(n.slice(5))),...aBo.filter(n=>n!=="board")],t=A==="top"?"soldermask_top":A==="bottom"?"soldermask_bottom":void 0,o=A==="top"?"top_silkscreen":A==="bottom"?"bottom_silkscreen":void 0,B=A==="top"?"top_notes":A==="bottom"?"bottom_notes":void 0,C=A==="top"?"top_fabrication":A==="bottom"?"bottom_fabrication":void 0,Q=A==="top"?"top_courtyard":A==="bottom"?"bottom_courtyard":void 0,i=[A,"edge_cuts",...t?[t]:[],...o?[o]:[],...B?[B]:[],...C?[C]:[],...Q?[Q]:[]],E=[...e.filter(n=>!i.includes(n)),...A==="drill"?[]:[A],...t?[t]:[],"edge_cuts",...o?[o]:[],...B?[B]:[],...C?[C]:[],...Q?[Q]:[],"drill"];E.forEach((n,s)=>{const r=g[n];r&&(r.style.zIndex=`${da.topLayer-(E.length-s)}`)});for(const[n,s]of Object.entries(g)){const r=this.getLayerOpacity(n);s.style.opacity=String(r),s.style.display=r===0?"none":""}}applyAperture(){const{transform:g,aperture:A}=this;let{size:I,mode:e,color:t,fontSize:o,layer:B}=A;B in this.ctxLayerMap||(this.aperture.layer="other");const C=this.getLayerCtx();if(!C)throw new Error(`No context for layer "${this.foregroundLayer}"`);if(t||(t="undefined"),C.lineWidth=yk(g,I),C.lineCap="round",e==="add"){C.globalCompositeOperation="source-over";let Q=EeA[t.toLowerCase()];if(!Q)try{Q=uQ(t).rgb().toString()}catch{console.warn(`Invalid color format: '${t}'`),Q="white"}C.fillStyle=Q,C.strokeStyle=Q}else C.globalCompositeOperation="destination-out",C.fillStyle="rgba(0,0,0,1)",C.strokeStyle="rgba(0,0,0,1)";C.font=`${yk(Nx(g),o)}px sans-serif`}moveTo(g,A){this.lastPoint={x:g,y:A}}lineTo(g,A){const[I,e]=Mt(this.transform,[g,A]),{size:t,shape:o,mode:B}=this.aperture,C=yk(this.transform,t),{lastPoint:Q}=this,i=Mt(this.transform,Q);this.applyAperture();const E=this.getLayerCtx();o==="square"&&E.fillRect(i.x-C/2,i.y-C/2,C,C),E.beginPath(),E.moveTo(i.x,i.y),E.lineTo(I,e),E.stroke(),E.closePath(),o==="square"&&E.fillRect(I-C/2,e-C/2,C,C),this.lastPoint={x:g,y:A}}polygonWithArcs(g){const A=this.getLayerCtx(),I=e=>{if(e.vertices.length===0)return;const t=e.vertices[0],o=Mt(this.transform,[t.x,t.y]);A.moveTo(o[0],o[1]);for(let B=0;B<e.vertices.length;B++){const C=e.vertices[B],Q=e.vertices[(B+1)%e.vertices.length];if(C.bulge&&C.bulge!==0){const i=C.bulge,E=Q.x-C.x,n=Q.y-C.y,s=Math.sqrt(E*E+n*n);if(s<1e-9){const R=Mt(this.transform,[Q.x,Q.y]);A.lineTo(R[0],R[1]);continue}const r=4*Math.atan(i),a=Math.abs(s/(2*Math.sin(r/2))),c=(C.x+Q.x)/2,h=(C.y+Q.y)/2,l=E/s,d=-(n/s),y=l,w=Math.sqrt(Math.max(0,a*a-(s/2)**2)),u=c+w*d*Math.sign(i),G=h+w*y*Math.sign(i),m=Math.atan2(C.y-G,C.x-u);let p=Math.atan2(Q.y-G,Q.x-u);i>0&&p<m?p+=2*Math.PI:i<0&&p>m&&(p-=2*Math.PI);const k=Mt(this.transform,[u,G]),S=yk(this.transform,a);A.arc(k[0],k[1],S,-m,-p,i>0)}else{const i=Mt(this.transform,[Q.x,Q.y]);A.lineTo(i[0],i[1])}}A.closePath()};if(A.beginPath(),I(g.outer_ring),g.inner_rings)for(const e of g.inner_rings)I(e);A.fill("evenodd")}},cBo=(g=2)=>{const A=Math.max(2,Math.min(10,Math.floor(g)));return["top",...Array.from({length:A-2},(I,e)=>`inner${e+1}`),"bottom"]},OwA=g=>{const A=g.find(I=>I.type==="pcb_board");return cBo(A?.num_layers??2)},reg=g=>`${g}_copper`,H2I=g=>g.map(A=>A.endsWith("_copper")?A.slice(0,-7):A),hBo=g=>["board","bottom","soldermask_bottom","bottom_silkscreen","top","soldermask_top","soldermask_with_copper_bottom","soldermask_with_copper_top","top_fabrication","bottom_fabrication",...OwA(g).filter(I=>I.startsWith("inner")),"drill","edge_cuts","bottom_notes","top_notes","top_silkscreen","top_courtyard","bottom_courtyard","other"],lBo=(g,A)=>{const I=OwA(g).reverse();return[...I.filter(e=>e!==A),...I.filter(e=>e===A)]},DBo={...Lw,courtyard:{top:ho.board.f_crtyd,bottom:ho.board.b_crtyd}};function dBo(g){return g.type==="pcb_courtyard_circle"||g.type==="pcb_courtyard_rect"||g.type==="pcb_courtyard_outline"}function v2I({canvas:g,elements:A,layers:I,realToCanvasMat:e}){const t=new XE(g);t.configure({colorOverrides:DBo}),t.realToCanvasMat=e;const o=A.filter(dBo);t.drawElements(o,{layers:I})}var yBo={...Lw,silkscreen:{top:ho.board.f_fab,bottom:ho.board.b_fab}};function wBo(g){return g.type.startsWith("pcb_fabrication_note_")}function q2I({canvas:g,elements:A,layers:I,realToCanvasMat:e}){const t=new XE(g);t.configure({colorOverrides:yBo}),t.realToCanvasMat=e;const o=A.filter(B=>wBo(B)&&"layer"in B&&(I.length===0||B.layer==="top"&&I.includes("top_fabrication_note")||B.layer==="bottom"&&I.includes("bottom_fabrication_note")));t.drawElements(o,{layers:I})}function uBo(g){return g.type==="pcb_hole"}function GBo({canvas:g,elements:A,layers:I,realToCanvasMat:e,drawSoldermask:t}){const o=new XE(g);o.realToCanvasMat=e;const B=A.filter(uBo);o.drawElements(B,{layers:I,drawSoldermask:t})}function mBo(g){return g.type==="pcb_board"}function T2I({canvas:g,elements:A,layers:I,realToCanvasMat:e,drawSoldermask:t}){const o=new XE(g);o.realToCanvasMat=e;const B=A.filter(mBo);for(const C of B)o.drawElements([C],{layers:I,drawSoldermask:!1,drawBoardMaterial:t??!1,minBoardOutlineStrokePx:2})}function pBo(g){return g.type==="pcb_copper_text"}function kBo({canvas:g,elements:A,layers:I,realToCanvasMat:e}){const t=A.filter(pBo);if(t.length===0)return;const o=new XE(g);o.realToCanvasMat=e,o.drawElements(t,{layers:I})}function MBo(g){return g.type==="pcb_cutout"}function SBo({canvas:g,elements:A,layers:I,realToCanvasMat:e}){const t=new XE(g);t.realToCanvasMat=e;const o=A.filter(MBo);t.drawElements(o,{layers:I})}function fBo(g){return g.type==="pcb_keepout"}function RBo({elements:g,layer:A}){return g.filter(fBo).filter(I=>I.layers.includes(A))}function NBo(g){return uQ(EeA[g]).lighten(.4).hex()}function xBo({canvas:g,elements:A,layer:I,realToCanvasMat:e}){const t=RBo({elements:A,layer:I});if(t.length===0)return;const o=new XE(g),B=NBo(I);o.configure({colorOverrides:{keepout:{top:B,bottom:B}}}),o.realToCanvasMat=e,o.drawElements(t,{layers:[reg(I)]})}function FBo(g){return g.type.startsWith("pcb_note_")}function Z2I({canvas:g,elements:A,layers:I,realToCanvasMat:e}){const t=new XE(g);t.realToCanvasMat=e;const o=A.filter(FBo);t.drawElements(o,{layers:I})}function UBo(g){return g.type==="pcb_panel"}function JBo({canvas:g,elements:A,layers:I,realToCanvasMat:e,drawSoldermask:t}){const o=new XE(g);o.realToCanvasMat=e;const B=A.filter(UBo);for(const C of B)o.drawElements([C],{layers:I})}var PBo={...Lw,copper:{...Lw.copper,top:uQ(ho.board.pad_front).lighten(.5).toString(),bottom:uQ(ho.board.pad_back).lighten(.5).toString(),inner1:uQ(ho.board.copper.in1).lighten(.5).toString(),inner2:uQ(ho.board.copper.in2).lighten(.5).toString(),inner3:uQ(ho.board.copper.in3).lighten(.5).toString(),inner4:uQ(ho.board.copper.in4).lighten(.5).toString(),inner5:uQ(ho.board.copper.in5).lighten(.5).toString(),inner6:uQ(ho.board.copper.in6).lighten(.5).toString(),inner7:uQ(ho.board.copper.in7).lighten(.5).toString(),inner8:uQ(ho.board.copper.in8).lighten(.5).toString()}};function KBo(g){return g.type==="pcb_smtpad"}function O2I({canvas:g,elements:A,layers:I,realToCanvasMat:e,primitives:t,drawSoldermask:o}){const B=new Set(H2I(I)),C=A.filter(KBo).filter(n=>B.has(n.layer));if(C.length===0)return;const Q=new Set;if(t)for(const n of t)(n.is_mouse_over||n.is_in_highlighted_net)&&n._element?.type==="pcb_smtpad"&&Q.add(n._element.pcb_smtpad_id);const i=C.filter(n=>Q.has(n.pcb_smtpad_id)),E=C.filter(n=>!Q.has(n.pcb_smtpad_id));if(E.length>0){const n=new XE(g);n.realToCanvasMat=e,n.drawElements(E,{layers:I,drawSoldermask:o})}if(i.length>0){const n=new XE(g);n.configure({colorOverrides:PBo}),n.realToCanvasMat=e,n.drawElements(i,{layers:I,drawSoldermask:o})}}var LBo={...Lw,copper:Object.fromEntries(Object.entries(Lw.copper).map(([g,A])=>[g,uQ(A).lighten(.5).toString()]))};function YBo(g){return g.type==="pcb_trace"}var _Bo=(g,A)=>{const I=g.route.filter(o=>o.route_type==="wire"&&"layer"in o&&A.has(o.layer)?!0:o.route_type==="via"?A.has(o.from_layer)||A.has(o.to_layer):!1),e=I.filter(o=>o.route_type==="wire").length,t=I.some(o=>o.route_type==="via");return e<2&&!t?null:{...g,route:I}},bBo=g=>({...g,route:g.route.map(A=>!("is_inside_copper_pour"in A)||A.is_inside_copper_pour!==!0?A:{...A,is_inside_copper_pour:!1})}),HBo=(g,A)=>A?g:g.filter(I=>I.type!=="pcb_copper_pour"),vBo=({primitives:g})=>{const A=new Set;for(const I of g)(I.is_mouse_over||I.is_in_highlighted_net)&&I._element?.type==="pcb_trace"&&A.add(I._element.pcb_trace_id);return A};function W2I({canvas:g,elements:A,layers:I,realToCanvasMat:e,primitives:t,showCopperPours:o}){const B=new Set(H2I(I)),C=A.filter(YBo).map(s=>_Bo(s,B)).filter(s=>s!==null).map(s=>o?s:bBo(s));if(C.length===0)return;const Q=vBo({primitives:t??[]}),i=[],E=[];for(const s of C)Q.has(s.pcb_trace_id)?i.push(s):E.push(s);const n=HBo(A,o);if(E.length>0){const s=new XE(g);s.realToCanvasMat=e,s.drawElements(E,{layers:I,clipContextElements:n})}if(i.length>0){const s=new XE(g);s.configure({colorOverrides:LBo}),s.realToCanvasMat=e,s.drawElements(i,{layers:I,clipContextElements:n})}}var qBo={...Lw,copper:{...Lw.copper,top:uQ(ho.board.pad_front).lighten(.5).toString(),bottom:uQ(ho.board.pad_back).lighten(.5).toString(),inner1:uQ(ho.board.copper.in1).lighten(.5).toString(),inner2:uQ(ho.board.copper.in2).lighten(.5).toString(),inner3:uQ(ho.board.copper.in3).lighten(.5).toString(),inner4:uQ(ho.board.copper.in4).lighten(.5).toString(),inner5:uQ(ho.board.copper.in5).lighten(.5).toString(),inner6:uQ(ho.board.copper.in6).lighten(.5).toString(),inner7:uQ(ho.board.copper.in7).lighten(.5).toString(),inner8:uQ(ho.board.copper.in8).lighten(.5).toString()}};function TBo(g){return g.type==="pcb_plated_hole"}function V2I({canvas:g,elements:A,layers:I,realToCanvasMat:e,primitives:t,drawSoldermask:o}){const B=A.filter(TBo);if(B.length===0)return;const C=new Set;if(t)for(const E of t)(E.is_mouse_over||E.is_in_highlighted_net)&&E._element?.type==="pcb_plated_hole"&&C.add(E._element.pcb_plated_hole_id);const Q=B.filter(E=>C.has(E.pcb_plated_hole_id)),i=B.filter(E=>!C.has(E.pcb_plated_hole_id));if(i.length>0){const E=new XE(g);E.realToCanvasMat=e,E.drawElements(i,{layers:I,drawSoldermask:o})}if(Q.length>0){const E=new XE(g);E.configure({colorOverrides:qBo}),E.realToCanvasMat=e,E.drawElements(Q,{layers:I,drawSoldermask:o})}}function j2I(g){const{lines:A,anchorPoint:I,ccwRotation:e}=g;if(!e)return A;const t=e*Math.PI/180,o=JMI(t),B=bw(qc(I.x,I.y),o,qc(-I.x,-I.y));return Mt(B,I),A.map(C=>({...C,x1:Mt(B,{x:C.x1,y:C.y1}).x,y1:Mt(B,{x:C.x1,y:C.y1}).y,x2:Mt(B,{x:C.x2,y:C.y2}).x,y2:Mt(B,{x:C.x2,y:C.y2}).y}))}var ZBo=.6,z2I=.2,X2I=g=>{const A=g.size*.7,I=A*ZBo,e=A*z2I,t=A*z2I,o=g.text.split(/\r?\n/),B=g.text.length>0&&A>0,C=B?o.length:0,Q=B?o.map(n=>n.length===0?0:n.length*I+(n.length-1)*e):[],i=Q.length>0?Math.max(...Q):0,E=C>0?C*A+(C-1)*t:0;return{text_lines:o,line_count:C,line_widths:Q,target_height:A,target_width_char:I,space_between_chars:e,space_between_lines:t,width:i,height:E}},$2I=g=>{const A=X2I(g);return{width:A.width,height:A.height,lineHeight:A.target_height,lineSpacing:A.space_between_lines,lineCount:A.line_count}},AfI=g=>{const{text_lines:A,line_count:I,line_widths:e,target_height:t,target_width_char:o,space_between_chars:B,space_between_lines:C,width:Q}=X2I(g);if(t<=0||I===0)return[];const i=t/12,E=[];for(let n=0;n<I;n++){const s=-n*(t+C),r=e[n],a=(Q-r)/2;let c=g.x+a;for(let h=0;h<A[n].length;h++){const l=A[n][h],D=nU[l]??nU[l.toUpperCase()];if(!D){c+=o+B;continue}for(const{x1:d,y1:y,x2:w,y2:u}of D)E.push({_pcb_drawing_object_id:LR("line"),pcb_drawing_type:"line",x1:c+o*d,y1:g.y+s+t*y,x2:c+o*w,y2:g.y+s+t*u,width:i,layer:g.layer,unit:g.unit,color:g.color});c+=o+B}}return E};function Lx(g){const I=g.color??EeA[g.layer];let e=uQ(I);return g._element?.type==="pcb_copper_pour"&&(e=e.alpha(.7)),g.is_mouse_over||g.is_in_highlighted_net?e.lighten(.5).rgb().toString():e.rgb().toString()}var gfI=(g,A)=>{g.equip({size:A.zoomIndependent?A.width/g.transform.a:A.width,shape:A.squareCap?"square":"circle",color:Lx(A),layer:A.layer}),g.moveTo(A.x1,A.y1),g.lineTo(A.x2,A.y2)},OBo=(g,A,I)=>{switch(I){case"top_left":return{x:0,y:-A};case"top_center":return{x:-g/2,y:-A};case"top_right":return{x:-g,y:-A};case"center_left":return{x:0,y:-A/2};case"center":return{x:-g/2,y:-A/2};case"center_right":return{x:-g,y:-A/2};case"bottom_left":return{x:0,y:0};case"bottom_center":return{x:-g/2,y:0};case"bottom_right":return{x:-g,y:0};default:return{x:0,y:0}}},IfI=g=>g.layer==="bottom_silkscreen"||g.layer==="bottom"?g.is_mirrored!==!1:g.is_mirrored===!0,WBo=(g,A)=>{g.equip({fontSize:A.size,color:Lx(A),layer:A.layer});const{width:I,height:e}=$2I(A),t=OBo(I,e,A.align);A.x??=0,A.y??=0;const o={x:A.x,y:A.y};let B=AfI({...A,x:A.x+t.x,y:A.y+t.y});if(IfI(A)&&(B=B.map(C=>({...C,x1:2*A.x-C.x1,x2:2*A.x-C.x2}))),A.ccw_rotation){const C={lines:B,anchorPoint:o,ccwRotation:A.ccw_rotation};B=j2I(C)}for(const C of B)gfI(g,C)},VBo=(g,A)=>{const{width:I,height:e,lineHeight:t}=$2I(A);A.x??=0,A.y??=0;const o=A.knockout_padding??{left:A.size*.5,right:A.size*.5,top:A.size*.3,bottom:A.size*.3},B=I+o.left+o.right,C=e+o.top+o.bottom,Q=I/2,i=t-e/2,E=A.x-Q,n=A.y-i,s={x:A.x,y:A.y},r={_pcb_drawing_object_id:`knockout_rect_${A._pcb_drawing_object_id}`,x:A.x,y:A.y,w:B,h:C,layer:A.layer,ccw_rotation:A.ccw_rotation};A.ccw_rotation?tfI(g,r):efI(g,r);let a=AfI({...A,x:E,y:n});if(IfI(A)&&(a=a.map(c=>({...c,x1:2*A.x-c.x1,x2:2*A.x-c.x2}))),A.ccw_rotation){const c={lines:a,anchorPoint:s,ccwRotation:A.ccw_rotation};a=j2I(c)}for(const c of a)g.equip({size:c.width,shape:"circle",color:"black",layer:A.layer,mode:"subtract"}),g.moveTo(c.x1,c.y1),g.lineTo(c.x2,c.y2);g.equip({mode:"add"})},efI=(g,A)=>{g.equip({color:Lx(A),layer:A.layer,size:A.stroke_width}),g.rect({x:A.x,y:A.y,w:A.w,h:A.h,mesh_fill:A.mesh_fill,is_filled:A.is_filled,has_stroke:A.has_stroke,is_stroke_dashed:A.is_stroke_dashed,stroke_width:A.stroke_width,roundness:A.roundness})},tfI=(g,A)=>{g.equip({color:Lx(A),layer:A.layer}),g.rotatedRect(A.x,A.y,A.w,A.h,A.ccw_rotation,A.roundness,A.mesh_fill)},jBo=(g,A)=>{g.equip({color:Lx(A),layer:A.layer}),g.rotatedPill(A.x,A.y,A.w,A.h,A.ccw_rotation)},zBo=(g,A)=>{g.equip({color:Lx(A),layer:A.layer}),g.circle(A.x,A.y,A.r,A.mesh_fill)},XBo=(g,A)=>{g.equip({color:Lx(A),layer:A.layer}),g.oval(A.x,A.y,A.rX,A.rY)},$Bo=(g,A)=>{g.equip({color:Lx(A),layer:A.layer}),g.pill(A.x,A.y,A.w,A.h)},ACo=(g,A)=>{g.equip({color:Lx(A),layer:A.layer}),g.polygon(A.points)},gCo=(g,A)=>{g.equip({color:Lx(A),layer:A.layer}),g.polygonWithArcs(A.brep_shape)},ICo=(g,A)=>{switch(A.pcb_drawing_type){case"line":return gfI(g,A);case"text":return A.is_knockout?VBo(g,A):WBo(g,A);case"rect":return A.ccw_rotation?tfI(g,A):efI(g,A);case"circle":return zBo(g,A);case"oval":return XBo(g,A);case"pill":return A.ccw_rotation?jBo(g,A):$Bo(g,A);case"polygon":return ACo(g,A);case"polygon_with_arcs":return gCo(g,A)}},eCo=(g,A)=>{for(const I of A)ICo(g,I)},tCo={...Lw,silkscreen:{top:ho.board.f_silks,bottom:ho.board.b_silks}};function oCo(g){return g.type.includes("pcb_silkscreen")}function ofI({canvas:g,elements:A,layers:I,realToCanvasMat:e}){const t=new XE(g);t.configure({colorOverrides:tCo}),t.realToCanvasMat=e;const o=A.filter(oCo);t.drawElements(o,{layers:I})}var BCo={...Lw,copper:{...Lw.copper,top:uQ(ho.board.pad_front).lighten(.5).toString(),bottom:uQ(ho.board.pad_back).lighten(.5).toString(),inner1:uQ(ho.board.copper.in1).lighten(.5).toString(),inner2:uQ(ho.board.copper.in2).lighten(.5).toString(),inner3:uQ(ho.board.copper.in3).lighten(.5).toString(),inner4:uQ(ho.board.copper.in4).lighten(.5).toString(),inner5:uQ(ho.board.copper.in5).lighten(.5).toString(),inner6:uQ(ho.board.copper.in6).lighten(.5).toString(),inner7:uQ(ho.board.copper.in7).lighten(.5).toString(),inner8:uQ(ho.board.copper.in8).lighten(.5).toString()},soldermask:{...Lw.soldermask,top:uQ(ho.board.soldermask.top).lighten(.35).toString(),bottom:uQ(ho.board.soldermask.bottom).lighten(.35).toString()}};function BfI({canvas:g,elements:A,layers:I,realToCanvasMat:e,drawSoldermaskTop:t,drawSoldermaskBottom:o,primitives:B}){const C=new XE(g);C.realToCanvasMat=e;const Q=A.filter(s=>s.type==="pcb_board");if(C.drawElements(A,{layers:I,drawSoldermask:!0,drawSoldermaskTop:t,drawSoldermaskBottom:o,drawBoardMaterial:!1}),Q.length>1&&T2I({canvas:g,elements:Q,layers:[],realToCanvasMat:e,drawSoldermask:!1}),!B)return;const i=new Set;for(const s of B){if(!(s.is_mouse_over||s.is_in_highlighted_net))continue;const r=s._element;r?.type==="pcb_smtpad"?i.add(r.pcb_smtpad_id):r?.type==="pcb_plated_hole"?i.add(r.pcb_plated_hole_id):r?.type==="pcb_via"&&i.add(r.pcb_via_id)}if(i.size===0)return;const E=A.filter(s=>s.type==="pcb_smtpad"?i.has(s.pcb_smtpad_id):s.type==="pcb_plated_hole"?i.has(s.pcb_plated_hole_id):s.type==="pcb_via"?i.has(s.pcb_via_id):!1);if(E.length===0)return;const n=new XE(g);n.configure({colorOverrides:BCo}),n.realToCanvasMat=e,n.drawElements(E,{layers:I,clipContextElements:A,drawSoldermask:!0,drawSoldermaskTop:t,drawSoldermaskBottom:o,drawBoardMaterial:!1})}var CCo={...Lw,copper:{...Lw.copper,top:uQ(ho.board.pad_front).lighten(.5).toString(),bottom:uQ(ho.board.pad_back).lighten(.5).toString(),inner1:uQ(ho.board.copper.in1).lighten(.5).toString(),inner2:uQ(ho.board.copper.in2).lighten(.5).toString(),inner3:uQ(ho.board.copper.in3).lighten(.5).toString(),inner4:uQ(ho.board.copper.in4).lighten(.5).toString(),inner5:uQ(ho.board.copper.in5).lighten(.5).toString(),inner6:uQ(ho.board.copper.in6).lighten(.5).toString(),inner7:uQ(ho.board.copper.in7).lighten(.5).toString(),inner8:uQ(ho.board.copper.in8).lighten(.5).toString()}};function QCo(g){return g.type==="pcb_via"}function CfI({canvas:g,elements:A,layers:I,realToCanvasMat:e,primitives:t,drawSoldermask:o}){const B=A.filter(QCo).filter(E=>I.some(n=>n.includes("copper")));if(B.length===0)return;const C=new Set;if(t)for(const E of t)(E.is_mouse_over||E.is_in_highlighted_net)&&E._element?.type==="pcb_via"&&C.add(E._element.pcb_via_id);const Q=B.filter(E=>C.has(E.pcb_via_id)),i=B.filter(E=>!C.has(E.pcb_via_id));if(i.length>0){const E=new XE(g);E.realToCanvasMat=e,E.drawElements(i,{layers:I,drawSoldermask:o,drawSoldermaskTop:I.includes("top_copper"),drawSoldermaskBottom:I.includes("bottom_copper"),clipContextElements:A})}if(Q.length>0){const E=new XE(g);E.configure({colorOverrides:CCo}),E.realToCanvasMat=e,E.drawElements(Q,{layers:I,drawSoldermask:o,drawSoldermaskTop:I.includes("top_copper"),drawSoldermaskBottom:I.includes("bottom_copper"),clipContextElements:A})}}var iCo=({primitives:g,isShowingSolderMask:A,isShowingSilkscreen:I,isShowingFabricationNotes:e})=>g.filter(t=>A||!t.layer?.includes("soldermask")).filter(t=>I||!t.layer?.includes("silkscreen")).filter(t=>e||!t.layer?.includes("fabrication")).filter(t=>t.layer!=="board").filter(t=>t._element?.type!=="pcb_smtpad").filter(t=>t._element?.type!=="pcb_plated_hole"||t.layer==="drill").filter(t=>t._element?.type!=="pcb_via").filter(t=>t._element?.type!=="pcb_trace").filter(t=>t._element?.type!=="pcb_copper_text"),ECo=({primitives:g,elements:A,circuitJson:I,xRayElements:e,transform:t,grid:o,width:B=500,height:C=500,onRenderComplete:Q})=>{const i=z.useRef(null),E=z.useRef({}),n=z.useRef(Q),s=z.useRef(void 0),r=ii(u=>u.hidden_layer_opacity),a=ii(u=>u.selected_layer),c=ii(u=>u.copper_pour_opacity),h=ii(u=>u.is_showing_copper_pours),l=ii(u=>u.is_showing_solder_mask),D=ii(u=>u.is_showing_fabrication_notes),d=ii(u=>u.is_showing_pcb_notes),y=ii(u=>u.is_showing_courtyards),w=ii(u=>u.is_showing_silkscreen);return z.useEffect(()=>{n.current=Q},[Q]),z.useEffect(()=>{if(!E.current||Object.keys(E.current).length===0)return;const u=Object.fromEntries(Object.entries(E.current).filter(([S,R])=>!!R));if(Object.keys(u).length===0)return;const G=new rBo(u);t&&(G.transform=t),G.clear(),G.foregroundLayer=a,G.hiddenLayerOpacity=r,G.xRayNetActive=!!e;const m=Object.fromEntries(Object.entries(u).filter(([S])=>G.getLayerOpacity(S)>0)),p=iCo({primitives:g,isShowingSolderMask:l,isShowingSilkscreen:w,isShowingFabricationNotes:D});if(eCo(G,p.filter(S=>G.getLayerOpacity(S.layer??"other")>0)),t){const S=OwA(A).map(U=>({canvas:m[U],layer:U,copperLayer:reg(U)}));for(const{canvas:U,copperLayer:K}of S)U&&W2I({canvas:U,elements:A,layers:[K],realToCanvasMat:t,primitives:g,showCopperPours:h&&c>0});for(const{canvas:U,copperLayer:K}of S)U&&kBo({canvas:U,elements:A,layers:[K],realToCanvasMat:t});for(const{canvas:U,copperLayer:K,layer:_}of S)U&&V2I({canvas:U,elements:A,layers:[K],realToCanvasMat:t,primitives:g,drawSoldermask:l&&(_==="top"||_==="bottom")});for(const{canvas:U,copperLayer:K}of S)U&&M2I({canvas:U,elements:A,layers:[K],realToCanvasMat:t,opacity:h?c:0});for(const{canvas:U,copperLayer:K}of S)U&&O2I({canvas:U,elements:A,layers:[K],realToCanvasMat:t,primitives:g,drawSoldermask:l});for(const{canvas:U,copperLayer:K,layer:_}of S)U&&CfI({canvas:U,elements:A,layers:[K],realToCanvasMat:t,primitives:g,drawSoldermask:l&&(_==="top"||_==="bottom")});if(l){const U=a==="bottom"?"bottom":"top",K=U==="top",_=U==="bottom",b=m.soldermask_top;b&&U==="top"&&BfI({canvas:b,elements:A,layers:["top_soldermask"],realToCanvasMat:t,drawSoldermaskTop:K,drawSoldermaskBottom:_,primitives:g});const T=m.soldermask_bottom;T&&U==="bottom"&&BfI({canvas:T,elements:A,layers:["bottom_soldermask"],realToCanvasMat:t,drawSoldermaskTop:K,drawSoldermaskBottom:_,primitives:g})}const R=m.drill;if(R&&GBo({canvas:R,elements:A,layers:["drill"],realToCanvasMat:t}),w){const U=m.top_silkscreen;U&&ofI({canvas:U,elements:A,layers:["top_silkscreen"],realToCanvasMat:t});const K=m.bottom_silkscreen;K&&ofI({canvas:K,elements:A,layers:["bottom_silkscreen"],realToCanvasMat:t})}if(D){const U=m.top_fabrication;U&&q2I({canvas:U,elements:A,layers:["top_fabrication_note"],realToCanvasMat:t});const K=m.bottom_fabrication;K&&q2I({canvas:K,elements:A,layers:["bottom_fabrication_note"],realToCanvasMat:t})}if(d){const U=m.bottom_notes;U&&Z2I({canvas:U,elements:A,layers:["bottom_user_note"],realToCanvasMat:t});const K=m.top_notes;K&&Z2I({canvas:K,elements:A,layers:["top_user_note"],realToCanvasMat:t})}if(y){const U=m.top_courtyard;U&&v2I({canvas:U,elements:A,layers:["top_courtyard"],realToCanvasMat:t});const K=m.bottom_courtyard;K&&v2I({canvas:K,elements:A,layers:["bottom_courtyard"],realToCanvasMat:t})}const x=m.board;x&&(JBo({canvas:x,elements:A,layers:[],realToCanvasMat:t,drawSoldermask:l}),T2I({canvas:x,elements:A,layers:[],realToCanvasMat:t,drawSoldermask:l}));const N=m.edge_cuts;N&&SBo({canvas:N,elements:A,layers:["edge_cuts"],realToCanvasMat:t});for(const{canvas:U,layer:K}of S)U&&xBo({canvas:U,elements:A,layer:K,realToCanvasMat:t})}G.orderAndFadeLayers();const k=i.current;if(k&&t&&e){k.getContext("2d").clearRect(0,0,B,C);for(const R of lBo(A,a)){const x={canvas:k,elements:e,layers:[reg(R)],realToCanvasMat:t,drawSoldermask:!1};h&&M2I({...x,opacity:c}),W2I({...x,showCopperPours:!1}),O2I(x),V2I(x),CfI(x)}const S=new XE(k);S.realToCanvasMat=t,S.drawElements(e.filter(R=>R.type==="pcb_via"||R.type==="pcb_plated_hole"),{layers:["drill"],drawSoldermask:!1})}s.current!==I&&(s.current=I,n.current?.())},[g,A,I,e,B,C,t,a,r,c,h,l,D,d,y,w]),q.jsxs("div",{style:{backgroundColor:"black",width:B,height:C,position:"relative"},children:[q.jsx(F5.SuperGrid,{textColor:"rgba(0,255,0,0.8)",majorColor:"rgba(0,255,0,0.4)",minorColor:"rgba(0,255,0,0.2)",screenSpaceCellSize:200,width:B,height:C,transform:t,stringifyCoord:(u,G,m)=>`${F5.toMMSI(u,m)}, ${F5.toMMSI(G,m)}`}),e&&q.jsx("canvas",{ref:i,className:"pcb-x-ray-net",width:B,height:C,style:{position:"absolute",left:0,top:0,zIndex:da.topLayer,pointerEvents:"none"}}),hBo(A).filter(u=>!(!l&&u.includes("soldermask")||!w&&u.includes("silkscreen"))).map(u=>u.replace(/-/g,"")).map((u,G)=>q.jsx("canvas",{className:`pcb-layer-${u}`,ref:m=>{E.current??={},m?E.current[u]=m:delete E.current[u]},style:{position:"absolute",zIndex:G,left:0,top:0,pointerEvents:"none"},width:B,height:C},u))]})};new TextEncoder,(()=>{const g=new Uint8Array(4),A=new Uint32Array(g.buffer);return!((A[0]=1)&g[0])})();var nCo=new Uint16Array([255]),sCo=new Uint8Array(nCo.buffer);sCo[0];var aCo=new Uint16Array([255]),rCo=new Uint8Array(aCo.buffer);rCo[0],new TextDecoder("latin1");var P3=1e-9,WwA=(g,A,I)=>g>=A-P3&&g<=I+P3,cCo=g=>{const A=[];for(const I of g)A.some(e=>Math.abs(e.x-I.x)<P3&&Math.abs(e.y-I.y)<P3)||A.push(I);return A};function hCo(g,A){const{origin:I,directionVector:e}=g;if(Math.abs(e.x)<P3&&Math.abs(e.y)<P3)return null;const t=[];if(Math.abs(e.x)>=P3){const i=(A.minX-I.x)/e.x,E=I.y+i*e.y;WwA(E,A.minY,A.maxY)&&t.push({x:A.minX,y:E});const n=(A.maxX-I.x)/e.x,s=I.y+n*e.y;WwA(s,A.minY,A.maxY)&&t.push({x:A.maxX,y:s})}if(Math.abs(e.y)>=P3){const i=(A.minY-I.y)/e.y,E=I.x+i*e.x;WwA(E,A.minX,A.maxX)&&t.push({x:E,y:A.minY});const n=(A.maxY-I.y)/e.y,s=I.x+n*e.x;WwA(s,A.minX,A.maxX)&&t.push({x:s,y:A.maxY})}const o=cCo(t);if(o.length<2)return null;let B=o[0],C=o[1],Q=(B.x-C.x)**2+(B.y-C.y)**2;for(let i=0;i<o.length;i++)for(let E=i+1;E<o.length;E++){const n=o[i],s=o[E],r=(n.x-s.x)**2+(n.y-s.y)**2;r>Q&&(B=n,C=s,Q=r)}return[B,C]}function lCo(g,A,I){const e=Nx(g),t=[Mt(e,{x:0,y:0}),Mt(e,{x:A,y:0}),Mt(e,{x:0,y:I}),Mt(e,{x:A,y:I})];return{minX:Math.min(...t.map(o=>o.x)),maxX:Math.max(...t.map(o=>o.x)),minY:Math.min(...t.map(o=>o.y)),maxY:Math.max(...t.map(o=>o.y))}}var DCo=.6,dCo=1,QfI=(g,A)=>Math.hypot(g.x-A.x,g.y-A.y),ifI=g=>(g.ccwRotationDegrees??0)*Math.PI/180,yCo=g=>g.a*g.d-g.b*g.c<0?1:-1,wCo=(g,A)=>ifI(g)*yCo(A),uCo=(g,A)=>{const I=Math.cos(A),e=Math.sin(A);return{x:g.x*I-g.y*e,y:g.x*e+g.y*I}},GCo=g=>EfI(g,ifI(g)),mCo=(g,A)=>EfI(g,wCo(g,A)),EfI=(g,A)=>{const I=g.width/2,e=g.height/2;return[{x:-I,y:-e},{x:I,y:-e},{x:I,y:e},{x:-I,y:e}].map(t=>{const o=uCo(t,A);return{x:g.center.x+o.x,y:g.center.y+o.y}})},pCo=(g,A)=>{const I=mCo(g,A).map(i=>Mt(A,i)),e=Mt(A,g.center),t=QfI(I[0],I[1]),o=QfI(I[1],I[2]),B=I.length>=2?Math.atan2(I[1].y-I[0].y,I[1].x-I[0].x):0,C=B*180/Math.PI,Q=I.reduce((i,E)=>({minX:Math.min(i.minX,E.x),maxX:Math.max(i.maxX,E.x),minY:Math.min(i.minY,E.y),maxY:Math.max(i.maxY,E.y)}),{minX:1/0,maxX:-1/0,minY:1/0,maxY:-1/0});return{center:e,corners:I,width:t,height:o,angleRadians:B,angleDegrees:C,bounds:Q}},kCo=2,MCo=12,SCo=12,VwA=g=>({tip:{...g},base:{...g},leftWing:{...g},rightWing:{...g}}),nfI=(g,A,I)=>{const e=g.x-A.x,t=g.y-A.y,o=Math.hypot(e,t);if(o===0)return VwA(g);const B=e/o,Q=-(t/o)*(I/2),i=B*(I/2);return{tip:{...g},base:{...A},leftWing:{x:A.x+Q,y:A.y+i},rightWing:{x:A.x-Q,y:A.y-i}}};function sfI(g){const{start:A,end:I}=g,e=I.x-A.x,t=I.y-A.y,o=Math.hypot(e,t),B=kCo,C=MCo;if(o===0){const D=g.doubleSided?[VwA(A),VwA(A)]:[VwA(A)];return{shaftStart:{...A},shaftEnd:{...A},heads:D,shaftWidth:B,headLength:0,headWidth:C,length:o}}const Q=e/o,i=t/o,E=Math.min(SCo,o*.5),n=Math.max(E,B*2),s=g.doubleSided?o/2:o,r=Math.min(n,s),a={x:I.x-Q*r,y:I.y-i*r},c=[nfI(I,a,C)];let h={...A};const l={...a};if(g.doubleSided){const D={x:A.x+Q*r,y:A.y+i*r};c.unshift(nfI(A,D,C)),h=D}return{shaftStart:h,shaftEnd:l,heads:c,shaftWidth:B,headLength:r,headWidth:C,length:o}}function fCo(g){const A=sfI(g);return[A.shaftStart,A.shaftEnd,...A.heads.flatMap(e=>[e.tip,e.base,e.leftWing,e.rightWing])].reduce((e,t)=>({minX:Math.min(e.minX,t.x),maxX:Math.max(e.maxX,t.x),minY:Math.min(e.minY,t.y),maxY:Math.max(e.maxY,t.y)}),{minX:1/0,maxX:-1/0,minY:1/0,maxY:-1/0})}function afI(g,A,{fontSize:I=12,strokeWidth:e=2,normalPadding:t=6,alongOffset:o=0}={}){const B={x:(g.x+A.x)/2,y:(g.y+A.y)/2},C=A.x-g.x,Q=A.y-g.y,i=Math.hypot(C,Q);if(i===0)return{x:B.x+o,y:B.y-(e/2+I*.65+t),angleRadians:0,angleDegrees:0,direction:{x:1,y:0},normal:{x:0,y:-1}};let E=C/i,n=Q/i,s=-n,r=E;(E<0||E===0&&n<0)&&(E=-E,n=-n,s=-s,r=-r);const c=Math.atan2(n,E),h=e/2+I*.65+t;return{x:B.x+s*h+E*o,y:B.y+r*h+n*o,angleRadians:c,angleDegrees:c*180/Math.PI,direction:{x:E,y:n},normal:{x:s,y:r}}}var K3=["rgba(239, 68, 68, 0.8)","rgba(249, 115, 22, 0.8)","rgba(245, 158, 11, 0.8)","rgba(234, 179, 8, 0.8)","rgba(132, 204, 22, 0.8)","rgba(34, 197, 94, 0.8)","rgba(16, 185, 129, 0.8)","rgba(20, 184, 166, 0.8)","rgba(6, 182, 212, 0.8)","rgba(14, 165, 233, 0.8)","rgba(59, 130, 246, 0.8)","rgba(99, 102, 241, 0.8)","rgba(139, 92, 246, 0.8)","rgba(168, 85, 247, 0.8)","rgba(217, 70, 239, 0.8)","rgba(236, 72, 153, 0.8)","rgba(249, 168, 212, 0.8)","rgba(161, 161, 170, 0.8)"];function rfI(g,A,I,e={}){const t=e.padding??40,o=e.yFlip??!1;let B;if("center"in g){const E=g.width/2,n=g.height/2;B={minX:g.center.x-E,maxX:g.center.x+E,minY:g.center.y-n,maxY:g.center.y+n}}else B=g;const C=B.maxX-B.minX||1,Q=B.maxY-B.minY||1,i=Math.min((A-2*t)/C,(I-2*t)/Q);return bw(qc(A/2,I/2),GJ(i,o?-i:i),qc(-(B.minX+C/2),-(B.minY+Q/2)))}function RCo(g){const A=[...g.points||[],...(g.lines||[]).flatMap(I=>I.points),...(g.polygons||[]).flatMap(I=>I.points),...(g.rects||[]).flatMap(I=>GCo(I)),...(g.circles||[]).flatMap(I=>[{x:I.center.x-I.radius,y:I.center.y},{x:I.center.x+I.radius,y:I.center.y},{x:I.center.x,y:I.center.y-I.radius},{x:I.center.x,y:I.center.y+I.radius}]),...(g.arrows||[]).flatMap(I=>{const e=fCo(I);return[{x:e.minX,y:e.minY},{x:e.maxX,y:e.maxY}]}),...(g.texts||[]).flatMap(I=>{const e=I.fontSize??12,t=I.text.length*e*DCo,o=e*dCo,B=I.anchorSide??"center",C={top_left:{dx:0,dy:0},top_center:{dx:-t/2,dy:0},top_right:{dx:-t,dy:0},center_left:{dx:0,dy:-o/2},center:{dx:-t/2,dy:-o/2},center_right:{dx:-t,dy:-o/2},bottom_left:{dx:0,dy:-o},bottom_center:{dx:-t/2,dy:-o},bottom_right:{dx:-t,dy:-o}},{dx:Q,dy:i}=C[B],E=I.x+Q,n=I.y+i;return[{x:E,y:n},{x:E+t,y:n+o}]})];return A.length===0?{minX:-1,maxX:1,minY:-1,maxY:1}:A.reduce((I,e)=>({minX:Math.min(I.minX,e.x),maxX:Math.max(I.maxX,e.x),minY:Math.min(I.minY,e.y),maxY:Math.max(I.maxY,e.y)}),{minX:1/0,maxX:-1/0,minY:1/0,maxY:-1/0})}function NCo(g,A,I={}){const e=I.disableLabels!==!1,t=I.hideInlineLabels??e,o=A instanceof HTMLCanvasElement?A.getContext("2d"):A;if(!o)throw new Error("Could not get 2D context from canvas");const B=A instanceof HTMLCanvasElement?A.width:A.canvas.width,C=A instanceof HTMLCanvasElement?A.height:A.canvas.height;let Q;if(I.transform)Q=I.transform;else if(I.viewbox)Q=rfI(I.viewbox,B,C,{padding:I.padding,yFlip:I.yFlip});else{const i=RCo(g),E=g.coordinateSystem==="cartesian";Q=rfI(i,B,C,{padding:I.padding??40,yFlip:E})}if(o.clearRect(0,0,B,C),o.save(),g.rects&&g.rects.length>0&&g.rects.forEach(i=>{const E=pCo(i,Q);o.save(),o.translate(E.center.x,E.center.y),Math.abs(E.angleRadians)>1e-6&&o.rotate(E.angleRadians),o.beginPath(),o.rect(-E.width/2,-E.height/2,E.width,E.height),i.fill&&(o.fillStyle=i.fill,o.fill()),i.stroke&&(o.strokeStyle=i.stroke,o.stroke()),o.restore()}),g.circles&&g.circles.length>0&&g.circles.forEach(i=>{const E=Mt(Q,i.center),n=i.radius*Math.abs(Q.a);o.beginPath(),o.arc(E.x,E.y,n,0,2*Math.PI),i.fill&&(o.fillStyle=i.fill,o.fill()),i.stroke&&(o.strokeStyle=i.stroke??"transparent",o.stroke())}),g.polygons&&g.polygons.length>0&&g.polygons.forEach(i=>{if(i.points.length===0)return;const E=i.points.map(n=>Mt(Q,n));o.beginPath(),o.moveTo(E[0].x,E[0].y);for(let n=1;n<E.length;n++)o.lineTo(E[n].x,E[n].y);o.closePath(),i.fill&&(o.fillStyle=i.fill,o.fill()),i.stroke&&(o.strokeStyle=i.stroke,i.strokeWidth!==void 0&&(o.lineWidth=i.strokeWidth*Math.abs(Q.a)),o.stroke())}),g.arrows&&g.arrows.length>0&&g.arrows.forEach((i,E)=>{const n=sfI(i),s=Mt(Q,n.shaftStart),r=Mt(Q,n.shaftEnd),a=i.color||K3[E%K3.length],c=Math.hypot(Q.a,Q.b);o.strokeStyle=a,o.fillStyle=a,o.lineWidth=n.shaftWidth*(c||1),o.lineCap="round",o.setLineDash([]),o.beginPath(),o.moveTo(s.x,s.y),o.lineTo(r.x,r.y),o.stroke(),n.heads.forEach(w=>{const u=Mt(Q,w.tip),G=Mt(Q,w.leftWing),m=Mt(Q,w.rightWing);o.beginPath(),o.moveTo(u.x,u.y),o.lineTo(G.x,G.y),o.lineTo(m.x,m.y),o.closePath(),o.fill()});const h=12,l=n.shaftWidth*(c||1),D=h*.6,d=afI(s,r,{fontSize:h,strokeWidth:l,normalPadding:6,alongOffset:i.label?D:0}),y=afI(s,r,{fontSize:h,strokeWidth:l,normalPadding:12,alongOffset:i.inlineLabel?-D:0});if(o.fillStyle=a,o.font=`${h}px sans-serif`,!e&&i.label){const w=y.x,u=y.y;o.save(),o.textAlign="center",o.textBaseline="middle",o.fillText(i.label,w,u),o.restore()}!t&&i.inlineLabel&&(o.save(),o.translate(d.x,d.y),o.rotate(d.angleRadians),o.textAlign="center",o.textBaseline="middle",o.fillText(i.inlineLabel,0,0),o.restore())}),g.lines&&g.lines.length>0&&g.lines.map((i,E)=>({line:i,originalIndex:E})).sort((i,E)=>(i.line.zIndex??0)-(E.line.zIndex??0)||i.originalIndex-E.originalIndex).forEach(({line:i,originalIndex:E})=>{if(i.points.length===0)return;o.beginPath();const n=Mt(Q,i.points[0]);o.moveTo(n.x,n.y);for(let s=1;s<i.points.length;s++){const r=Mt(Q,i.points[s]);o.lineTo(r.x,r.y)}if(o.strokeStyle=i.strokeColor||K3[E%K3.length],i.strokeWidth?o.lineWidth=i.strokeWidth*Q.a:o.lineWidth=2,o.lineCap="round",i.strokeDash)if(typeof i.strokeDash=="string"){let s;if(i.strokeDash.includes(","))s=i.strokeDash.split(",").map(r=>parseFloat(r.trim())).filter(r=>!Number.isNaN(r));else{const r=parseFloat(i.strokeDash.trim());s=Number.isNaN(r)?[]:[r]}o.setLineDash(s)}else o.setLineDash(i.strokeDash.map(s=>s*Math.abs(Q.a)));else o.setLineDash([]);o.stroke()}),g.infiniteLines&&g.infiniteLines.length>0){const i=lCo(Q,B,C);g.infiniteLines.forEach((E,n)=>{const s=hCo(E,i);if(!s)return;const[r,a]=s,c=Mt(Q,r),h=Mt(Q,a);if(o.beginPath(),o.moveTo(c.x,c.y),o.lineTo(h.x,h.y),o.strokeStyle=E.strokeColor||K3[n%K3.length],o.lineWidth=E.strokeWidth?E.strokeWidth*Math.abs(Q.a):2,o.lineCap="round",E.strokeDash)if(typeof E.strokeDash=="string"){let l;if(E.strokeDash.includes(","))l=E.strokeDash.split(",").map(D=>parseFloat(D.trim())).filter(D=>!Number.isNaN(D));else{const D=parseFloat(E.strokeDash.trim());l=Number.isNaN(D)?[]:[D]}o.setLineDash(l)}else o.setLineDash(E.strokeDash.map(l=>l*Math.abs(Q.a)));else o.setLineDash([]);o.stroke()})}g.texts&&g.texts.length>0&&g.texts.forEach(i=>{const E=Mt(Q,{x:i.x,y:i.y});o.fillStyle=i.color||"black",o.font=`${(i.fontSize??12)*Math.abs(Q.a)}px sans-serif`;const n=i.anchorSide??"center",s={top_left:"left",center_left:"left",bottom_left:"left",top_center:"center",center:"center",bottom_center:"center",top_right:"right",center_right:"right",bottom_right:"right"},r={top_left:"top",top_center:"top",top_right:"top",center_left:"middle",center:"middle",center_right:"middle",bottom_left:"bottom",bottom_center:"bottom",bottom_right:"bottom"};o.textAlign=s[n],o.textBaseline=r[n],o.fillText(i.text,E.x,E.y)}),g.points&&g.points.length>0&&g.points.forEach((i,E)=>{const n=Mt(Q,i);o.beginPath(),o.arc(n.x,n.y,3,0,2*Math.PI),o.fillStyle=i.color||K3[E%K3.length],o.fill(),i.label&&!e&&(o.fillStyle=i.color||"black",o.font="12px sans-serif",o.fillText(i.label,n.x+5,n.y-5))}),o.restore()}lSI(Deo(),1);var xCo=({children:g,transform:A,debugGraphics:I})=>{const e=z.useRef(null),[t,{width:o,height:B}]=QeA(),C=ii(Q=>Q.is_showing_autorouting);return z.useEffect(()=>{C&&e.current&&I&&o&&B&&(e.current.width=o,e.current.height=B,NCo(I,e.current,{transform:A,disableLabels:!0}))},[I,A,o,B,C]),C?q.jsxs("div",{ref:t,style:{position:"relative",width:"100%",height:"100%"},children:[g,q.jsx("canvas",{ref:e,style:{position:"absolute",top:0,left:0,opacity:.5,zIndex:100,width:"100%",height:"100%",pointerEvents:"none"}})]}):g};function FCo(g){const{dimensionStart:A,dimensionEnd:I,screenDimensionStart:e,screenDimensionEnd:t,flipX:o,flipY:B}=g,C=I.x-A.x,Q=I.y-A.y,i=Math.sqrt(C*C+Q*Q),E=t.x-e.x,n=t.y-e.y,s=Math.sqrt(E*E+n*n),r=Math.atan2(n,E)*(180/Math.PI),a=Math.abs(r)%90,h=Math.min(a,90-a)>15,l=(e.x+t.x)/2,D=(e.y+t.y)/2,d=15,y=r+90;let w=Math.cos(y*Math.PI/180)*d,u=Math.sin(y*Math.PI/180)*d;const G=E>0&&n<0,m=E>0&&n>0,p=E<0&&n>0;o!==B&&!G&&(w=-w,u=-u),G&&(w+=Math.cos(y*Math.PI/180)*-45,u+=Math.sin(y*Math.PI/180)*-45),m&&(w+=Math.cos(y*Math.PI/180)+-20,u+=Math.sin(y*Math.PI/180)+-10),p&&(w+=Math.cos(y*Math.PI/180)*10,u+=Math.sin(y*Math.PI/180)*10);const k=l+w,S=D+u;return{distance:i,screenDistance:s,x:k,y:S,show:i>.01&&s>30&&h}}function UCo(g){const{dimensionStart:A,dimensionEnd:I,screenDimensionStart:e,screenDimensionEnd:t,flipX:o,flipY:B}=g;return z.useMemo(()=>FCo({dimensionStart:A,dimensionEnd:I,screenDimensionStart:e,screenDimensionEnd:t,flipX:o,flipY:B}),[A,I,e,t,o,B])}var JCo=(g,A,I)=>{const e=I*Math.PI/180,t=Math.cos(e),o=Math.sin(e),B=g.x-A.x,C=g.y-A.y,Q=B*t-C*o,i=B*o+C*t;return{x:Q+A.x,y:i+A.y}},cfI=(g,A,I,e)=>{const t={top_left:{x:g.x-A,y:g.y-I},top_center:{x:g.x,y:g.y-I},top_right:{x:g.x+A,y:g.y-I},center_left:{x:g.x-A,y:g.y},center:{x:g.x,y:g.y},center_right:{x:g.x+A,y:g.y},bottom_left:{x:g.x-A,y:g.y+I},bottom_center:{x:g.x,y:g.y+I},bottom_right:{x:g.x+A,y:g.y+I}};return e===0?Object.entries(t).map(([o,B])=>({anchor:o,point:B})):Object.entries(t).map(([o,B])=>({anchor:o,point:JCo(B,g,e)}))},PCo=g=>{switch(g.pcb_drawing_type){case"rect":{const A=g.ccw_rotation??0;return cfI({x:g.x,y:g.y},g.w/2,g.h/2,A)}case"pill":{const A=g.ccw_rotation??0;return cfI({x:g.x,y:g.y},g.w/2,g.h/2,A)}case"circle":return[{anchor:"circle_center",point:{x:g.x,y:g.y}},{anchor:"circle_right",point:{x:g.x+g.r,y:g.y}},{anchor:"circle_left",point:{x:g.x-g.r,y:g.y}},{anchor:"circle_top",point:{x:g.x,y:g.y-g.r}},{anchor:"circle_bottom",point:{x:g.x,y:g.y+g.r}}];case"oval":return[{anchor:"oval_center",point:{x:g.x,y:g.y}},{anchor:"oval_right",point:{x:g.x+g.rX,y:g.y}},{anchor:"oval_left",point:{x:g.x-g.rX,y:g.y}},{anchor:"oval_top",point:{x:g.x,y:g.y-g.rY}},{anchor:"oval_bottom",point:{x:g.x,y:g.y+g.rY}}];case"line":{const A={x:(g.x1+g.x2)/2,y:(g.y1+g.y2)/2};return[{anchor:"line_start",point:{x:g.x1,y:g.y1}},{anchor:"line_mid",point:A},{anchor:"line_end",point:{x:g.x2,y:g.y2}}]}case"polygon":return g.points.map((A,I)=>({anchor:`polygon_vertex_${I}`,point:A}));case"polygon_with_arcs":return g.brep_shape.outer_ring.vertices.map((A,I)=>({anchor:`polygon_with_arcs_vertex_${I}`,point:{x:A.x,y:A.y}}));default:return[]}},KCo=[];function hfI({snappingPoints:g,realToScreenTransform:A,isEnabled:I}){return I?g.map((e,t)=>({...e,id:`${t}-${e.anchor}`,screenPoint:Mt(A,e.point)})):KCo}var lfI=({screenPoint:{x:g,y:A}})=>`M${g-2.5},${A-2.5}l5,5m0,-5l-5,5`,LCo=z.memo(function({points:A,startId:I,endId:e}){const{path:t,pointsById:o}=z.useMemo(()=>({path:A.map(lfI).join(""),pointsById:new Map(A.map(C=>[C.id,C]))}),[A]),B=[...new Set([I,e])].flatMap(C=>{const Q=C===null?void 0:o.get(C);return Q?[lfI(Q)]:[]}).join("");return q.jsxs("svg",{"aria-hidden":"true",width:"100%",height:"100%",style:{position:"absolute",left:0,top:0,overflow:"visible",pointerEvents:"none",zIndex:da.dimensionOverlay},fill:"none",strokeWidth:1,children:[q.jsx("path",{d:t,stroke:"white"}),q.jsx("path",{d:B,stroke:"#66ccff"})]})}),YCo=16,_Co=[],bCo=uJ(),DfI=g=>{if(g.pcb_drawing_type==="text")return!0;const A=g._element;if(!A||typeof A!="object")return!1;const I=typeof A.type=="string"?A.type:void 0;return I?!!(I.startsWith("pcb_silkscreen_")||I.startsWith("pcb_note_")||I==="pcb_text"||I.startsWith("pcb_fabrication_note_")&&I!=="pcb_fabrication_note_rect"):!1},HCo=({children:g,transform:A,focusOnHover:I=!1,primitives:e=_Co,onBoundsSelected:t,cancelPanDrag:o})=>{A||(A=bCo);const[B,C]=z.useState(!1),[Q,i]=z.useState(!1),[E,n]=z.useState(!1),[s,r]=z.useState(!1),[a,c]=z.useState(!1),[h,l]=z.useState(!1),[D,d]=z.useState({start:null,end:null}),y=ii(FA=>FA.is_mouse_over_container),w=z.useCallback(()=>{E&&(n(!1),window.dispatchEvent(new Event("disarm-dimension-tool")))},[E]),u=z.useCallback(()=>{s&&(r(!1),window.dispatchEvent(new Event("disarm-bounds-tool")))},[s]),[G,m]=z.useState({x:0,y:0}),[p,k]=z.useState({x:0,y:0}),[S,R]=z.useState({x:0,y:0}),[x,N]=z.useState({x:0,y:0}),U=z.useRef({x:0,y:0}),K=z.useRef(!1),_=z.useRef(null),T=_.current?.getBoundingClientRect(),j=z.useMemo(()=>{const FA=new Map;for(const aA of e){if(!aA._element||DfI(aA)||aA.pcb_drawing_type==="pill"||aA.pcb_drawing_type==="rect"&&aA.ccw_rotation&&aA.ccw_rotation!==0)continue;const xA=seg(aA);if(!xA)continue;const RA=FA.get(aA._element);FA.set(aA._element,Ooo(RA??void 0,xA))}return FA},[e]),W=z.useMemo(()=>{const FA=[];for(const aA of e){if(!aA._element||DfI(aA))continue;const xA=PCo(aA);if(xA.length!==0)for(const RA of xA)FA.push({anchor:RA.anchor,point:RA.point,element:aA._element})}return FA},[e]),O=z.useMemo(()=>{const FA=[];j.forEach((aA,xA)=>{if(!aA)return;const RA=(aA.minX+aA.maxX)/2,NA=(aA.minY+aA.maxY)/2,YA={top_left:{x:aA.minX,y:aA.minY},top_center:{x:RA,y:aA.minY},top_right:{x:aA.maxX,y:aA.minY},center_left:{x:aA.minX,y:NA},center:{x:RA,y:NA},center_right:{x:aA.maxX,y:NA},bottom_left:{x:aA.minX,y:aA.maxY},bottom_center:{x:RA,y:aA.maxY},bottom_right:{x:aA.maxX,y:aA.maxY}};for(const[PA,mA]of Object.entries(YA))FA.push({anchor:PA,point:mA,element:xA})});for(const aA of W)FA.push(aA);return FA.push({anchor:"origin",point:{x:0,y:0},element:null}),FA},[j,W]),gA=z.useMemo(()=>hfI({snappingPoints:O,realToScreenTransform:A,isEnabled:E||Q}),[O,A,E,Q]),tA=z.useCallback(FA=>{let aA=gA;if(aA.length===0&&(aA=hfI({snappingPoints:O,realToScreenTransform:A,isEnabled:!0})),aA.length===0)return{point:FA,id:null};const xA=Mt(A,FA);let RA=null;for(const NA of aA){const YA=NA.screenPoint.x-xA.x,PA=NA.screenPoint.y-xA.y,mA=Math.hypot(YA,PA);mA>YCo||(!RA||mA<RA.distance)&&(RA={distance:mA,id:NA.id,point:NA.point})}return RA?{point:RA.point,id:RA.id}:{point:FA,id:null}},[O,gA,A]);z.useEffect(()=>{const FA=RA=>{const NA=RA.target;if(NA.tagName==="INPUT"||NA.tagName==="TEXTAREA"||NA.isContentEditable)return;const YA=_.current?.contains(document.activeElement)||document.activeElement===_.current;if(!(!y&&!YA)){if(RA.key==="d"){const PA=tA({x:U.current.x,y:U.current.y});m({x:PA.point.x,y:PA.point.y}),k({x:PA.point.x,y:PA.point.y}),d({start:PA.id,end:PA.id}),B?(C(!1),i(!1),d({start:null,end:null})):(C(!0),i(!0)),w()}RA.key==="Escape"&&(C(!1),i(!1),d({start:null,end:null}),c(!1),l(!1),w(),u())}},aA=()=>{n(!0),r(!1),window.dispatchEvent(new Event("disarm-bounds-tool"))},xA=()=>{r(!0),n(!1),C(!1),i(!1),window.dispatchEvent(new Event("disarm-dimension-tool"))};return window.addEventListener("keydown",FA),window.addEventListener("arm-dimension-tool",aA),window.addEventListener("arm-bounds-tool",xA),()=>{window.removeEventListener("keydown",FA),window.removeEventListener("arm-dimension-tool",aA),window.removeEventListener("arm-bounds-tool",xA),w(),u()}},[y,B,w,u,tA]);const IA=Mt(A,G),QA=Mt(A,p),nA=Mt(A,S),DA=Mt(A,x),CA={minX:Math.min(S.x,x.x),minY:Math.min(S.y,x.y),maxX:Math.max(S.x,x.x),maxY:Math.max(S.y,x.y)},hA={left:Math.min(nA.x,DA.x),top:Math.min(nA.y,DA.y),width:Math.abs(nA.x-DA.x),height:Math.abs(nA.y-DA.y)},sA=z.useCallback((FA,aA)=>{const xA={minX:Math.min(FA.x,aA.x),minY:Math.min(FA.y,aA.y),maxX:Math.max(FA.x,aA.x),maxY:Math.max(FA.y,aA.y)};t?.(xA),window.dispatchEvent(new CustomEvent("pcb-viewer:bounds-selected",{detail:xA}))},[t]),cA={left:Math.min(IA.x,QA.x),right:Math.max(IA.x,QA.x),top:Math.min(IA.y,QA.y),bottom:Math.max(IA.y,QA.y),flipX:IA.x>QA.x,flipY:IA.y>QA.y,width:0,height:0};cA.width=cA.right-cA.left,cA.height=cA.bottom-cA.top;const SA=UCo({dimensionStart:G,dimensionEnd:p,screenDimensionStart:IA,screenDimensionEnd:QA,flipX:cA.flipX,flipY:cA.flipY});return q.jsxs("div",{ref:_,"data-pcb-viewer":!0,tabIndex:0,style:{position:"relative",outline:"none"},onMouseDownCapture:()=>{K.current=!1},onClickCapture:FA=>{K.current&&(K.current=!1,FA.stopPropagation(),_.current?.focus())},onContextMenuCapture:FA=>{!E&&!B&&!K.current||(FA.preventDefault(),FA.stopPropagation())},onMouseEnter:()=>{I&&_.current&&_.current.focus()},onMouseLeave:()=>{_.current&&_.current.blur()},onClick:()=>{_.current&&_.current.focus()},onMouseMove:FA=>{const aA=FA.currentTarget.getBoundingClientRect(),xA=FA.clientX-aA.left,RA=FA.clientY-aA.top,NA=Mt(Nx(A),{x:xA,y:RA});if(U.current.x=NA.x,U.current.y=NA.y,Q){const YA=tA(NA);k({x:YA.point.x,y:YA.point.y}),d(PA=>({...PA,end:YA.id}))}h&&(o?.(),N({x:NA.x,y:NA.y}))},onMouseDown:FA=>{K.current=E||B;const aA=FA.currentTarget.getBoundingClientRect(),xA=FA.clientX-aA.left,RA=FA.clientY-aA.top,NA=Mt(Nx(A),{x:xA,y:RA});if(s)FA.preventDefault(),FA.stopPropagation(),o?.(),R({x:NA.x,y:NA.y}),N({x:NA.x,y:NA.y}),c(!0),l(!0),u();else if(E&&!B){const YA=tA(NA);m({x:YA.point.x,y:YA.point.y}),k({x:YA.point.x,y:YA.point.y}),d({start:YA.id,end:YA.id}),C(!0),i(!0),w()}else Q?(i(!1),d(YA=>({...YA,end:null}))):B&&(C(!1),d({start:null,end:null}))},onMouseUp:FA=>{if(!h)return;const aA=FA.currentTarget.getBoundingClientRect(),xA=FA.clientX-aA.left,RA=FA.clientY-aA.top,NA=Mt(Nx(A),{x:xA,y:RA}),YA={x:NA.x,y:NA.y};FA.preventDefault(),FA.stopPropagation(),o?.(),N(YA),l(!1),sA(S,YA)},children:[g,a&&q.jsxs(q.Fragment,{children:[q.jsx("svg",{style:{position:"absolute",left:0,top:0,pointerEvents:"none",mixBlendMode:"difference",zIndex:da.dimensionOverlay},width:T.width,height:T.height,children:q.jsx("rect",{x:hA.left,y:hA.top,width:hA.width,height:hA.height,stroke:"red",strokeWidth:1.5,strokeDasharray:"4,3",fill:"rgba(255, 0, 0, 0.12)"})}),q.jsxs("div",{style:{left:0,bottom:B?58:0,position:"absolute",color:"red",fontFamily:"sans-serif",fontSize:12,margin:4,pointerEvents:"none",mixBlendMode:"difference",zIndex:da.dimensionOverlay},children:["minX: ",CA.minX.toFixed(2),", minY:"," ",CA.minY.toFixed(2),q.jsx("br",{}),"maxX: ",CA.maxX.toFixed(2),", maxY:"," ",CA.maxY.toFixed(2)]})]}),B&&q.jsxs(q.Fragment,{children:[SA.show&&q.jsx("div",{style:{position:"absolute",left:SA.x,top:SA.y,color:"red",mixBlendMode:"difference",pointerEvents:"none",fontSize:12,fontFamily:"sans-serif",whiteSpace:"nowrap",zIndex:da.dimensionOverlay},children:SA.distance.toFixed(2)}),q.jsx("div",{style:{position:"absolute",left:cA.left,width:cA.width,textAlign:"center",top:IA.y+2,color:"red",mixBlendMode:"difference",pointerEvents:"none",marginTop:cA.flipY?0:-20,fontSize:12,fontFamily:"sans-serif",zIndex:da.dimensionOverlay},children:Math.abs(G.x-p.x).toFixed(2)}),q.jsx("div",{style:{position:"absolute",left:QA.x,height:cA.height,display:"flex",flexDirection:"column",justifyContent:"center",top:cA.top,color:"red",pointerEvents:"none",mixBlendMode:"difference",fontSize:12,fontFamily:"sans-serif",zIndex:da.dimensionOverlay},children:q.jsx("div",{style:{marginLeft:cA.flipX?"-100%":4,paddingRight:4},children:Math.abs(G.y-p.y).toFixed(2)})}),q.jsxs("svg",{style:{position:"absolute",left:0,top:0,pointerEvents:"none",mixBlendMode:"difference",zIndex:da.dimensionOverlay},width:T.width,height:T.height,children:[q.jsx("defs",{children:q.jsx("marker",{id:"head",orient:"auto",markerWidth:"3",markerHeight:"4",refX:"2",refY:"2",children:q.jsx("path",{d:"M0,0 V4 L2,2 Z",fill:"red"})})}),q.jsx("line",{x1:IA.x,y1:IA.y,x2:QA.x,y2:QA.y,markerEnd:"url(#head)",strokeWidth:1.5,fill:"none",stroke:"red"}),q.jsx("line",{x1:IA.x,y1:IA.y,x2:QA.x,y2:IA.y,strokeWidth:1.5,fill:"none",strokeDasharray:"2,2",stroke:"red"}),q.jsx("line",{x1:QA.x,y1:IA.y,x2:QA.x,y2:QA.y,strokeWidth:1.5,fill:"none",strokeDasharray:"2,2",stroke:"red"})]}),Q&&q.jsx(LCo,{points:gA,startId:D.start,endId:D.end}),q.jsxs("div",{style:{right:0,bottom:0,position:"absolute",color:"red",fontFamily:"sans-serif",fontSize:12,margin:4},children:["(",G.x.toFixed(2),",",G.y.toFixed(2),")",q.jsx("br",{}),"(",p.x.toFixed(2),",",p.y.toFixed(2),")",q.jsx("br",{}),"dist:"," ",Math.sqrt((p.x-G.x)**2+(p.y-G.y)**2).toFixed(2)]})]})]})},vCo=(g,A,I=0)=>{const e=g.width/2,t=g.height/2,o=g.center.x-e-I,B=g.center.x+e+I,C=g.center.y-t-I,Q=g.center.y+t+I;return A.x>o&&A.x<B&&A.y>C&&A.y<Q},qCo=({children:g,disabled:A,transform:I,soup:e,cancelPanDrag:t,onCreateEditEvent:o,onModifyEditEvent:B})=>{I||(I=uJ());const C=z.useRef(null),[Q,i]=z.useState(null),[E,n]=z.useState(null),s=Q!==null;ii(h=>h.in_edit_mode);const r=ii(h=>h.in_move_footprint_mode),a=ii(h=>h.setIsMovingComponent),c=A||!r;return q.jsxs("div",{ref:C,style:{position:"relative",overflow:"hidden"},onMouseDown:h=>{if(c)return;const l=h.currentTarget.getBoundingClientRect(),D=h.clientX-l.left,d=h.clientY-l.top;if(Number.isNaN(D)||Number.isNaN(d))return;const y=Mt(Nx(I),{x:D,y:d});let w=!1;for(const u of e)if(u.type==="pcb_component"&&vCo(u,y,10/I.a)){t(),i(u.pcb_component_id),w=!0;const G=Math.random().toString();n({dragStart:y,originalCenter:u.center,dragEnd:y,edit_event_id:G}),o({edit_event_id:G,edit_event_type:"edit_pcb_component_location",pcb_edit_event_type:"edit_component_location",pcb_component_id:u.pcb_component_id,original_center:u.center,new_center:u.center,in_progress:!0,created_at:Date.now()}),a(!0);break}if(w||i(null),w)return h.preventDefault(),!1},onMouseMove:h=>{if(!Q||!E)return;const l=h.currentTarget.getBoundingClientRect(),D=h.clientX-l.left,d=h.clientY-l.top;if(Number.isNaN(D)||Number.isNaN(d))return;const y=Mt(Nx(I),{x:D,y:d});n({...E,dragEnd:y}),B({edit_event_id:E.edit_event_id,new_center:{x:E.originalCenter.x+y.x-E.dragStart.x,y:E.originalCenter.y+y.y-E.dragStart.y}})},onMouseUp:h=>{Q&&(i(null),a(!1),E&&(B({edit_event_id:E.edit_event_id,in_progress:!1}),n(null)))},children:[g,!c&&e.filter(h=>h.type==="pcb_component").map(h=>{if(!h?.center)return null;const l=Mt(I,h.center);return q.jsx("div",{style:{position:"absolute",pointerEvents:"none",left:l.x,top:l.y,width:h.width*I.a+20,height:h.height*I.a+20,transform:"translate(-50%, -50%)",background:s&&Q===h.pcb_component_id?"rgba(255, 0, 0, 0.2)":""}},h.pcb_component_id)})]})},ceg=(g,A)=>{const I=A.current;if(!I)return{transform:"translate(-50%, -100%)",left:g.x,top:g.y};const e=I.getBoundingClientRect(),t=200,o=10,B=60;let C="-50%",Q="-100%",i=g.x,E=g.y;return g.x+B+t<e.width-o?(i=g.x+B,C="0%"):g.x-B-t>o?(i=g.x-B,C="-100%"):(i=g.x,C="-50%"),{transform:`translate(${C}, ${Q})`,left:i,top:E}},TCo=({center:g})=>q.jsxs("svg",{style:{position:"absolute",left:0,top:0,pointerEvents:"none",mixBlendMode:"difference",zIndex:da.errorOverlay+30},width:"100%",height:"100%",children:[q.jsx("circle",{cx:g.x,cy:g.y,r:11,fill:"none",stroke:"#ff6b6b",strokeWidth:2.5,opacity:.95}),q.jsx("circle",{cx:g.x,cy:g.y,r:4.5,fill:"#ff6b6b",opacity:.95}),q.jsx("line",{x1:g.x-18,y1:g.y,x2:g.x-8,y2:g.y,stroke:"#ff6b6b",strokeWidth:2}),q.jsx("line",{x1:g.x+8,y1:g.y,x2:g.x+18,y2:g.y,stroke:"#ff6b6b",strokeWidth:2}),q.jsx("line",{x1:g.x,y1:g.y-18,x2:g.x,y2:g.y-8,stroke:"#ff6b6b",strokeWidth:2}),q.jsx("line",{x1:g.x,y1:g.y+8,x2:g.x,y2:g.y+18,stroke:"#ff6b6b",strokeWidth:2})]}),dfI=({errorCenter:g,isHighlighted:A=!1})=>q.jsx("svg",{style:{position:"absolute",left:0,top:0,pointerEvents:"none",mixBlendMode:"difference",zIndex:da.errorOverlay},width:"100%",height:"100%",children:q.jsx("rect",{x:g.x-7,y:g.y-7,width:14,height:14,transform:`rotate(45 ${g.x} ${g.y})`,fill:A?"#ff4444":"transparent",stroke:A?"#ff4444":"red",strokeWidth:A?2.5:1.5})}),heg=j7`
5424
5424
  opacity: 0;
5425
5425
  pointer-events: none;
5426
5426
  background-color: rgba(0, 0, 0, 0.8);
@@ -5433,7 +5433,7 @@ ${e.svg()}`;return I+=`" >
5433
5433
  transition: opacity 0.2s;
5434
5434
  margin-bottom: 10px;
5435
5435
  color: red;
5436
- `,ZCo=[];function OCo(g){return g.type==="source_component"?g.source_component_id:g.type==="pcb_component"?g.pcb_component_id:"component"}var WCo=({children:g,transform:A=uJ(),elements:I})=>{const e=z.useRef(null),{isShowingDRCErrors:t,hoveredErrorId:o,focusedErrorId:B}=ii(l=>({isShowingDRCErrors:l.is_showing_drc_errors,hoveredErrorId:l.hovered_error_id,focusedErrorId:l.focused_error_id})),C=B??o,Q=I??ZCo,i=z.useMemo(()=>Q.filter(l=>l.type==="pcb_trace_error"&&!l.message?.includes("Multiple components found with name")),[Q]),E=z.useMemo(()=>Q.filter(l=>l.type==="pcb_via_clearance_error"),[Q]),n=z.useMemo(()=>Q.filter(l=>l.type==="pcb_trace_error"&&!!l.message?.includes("Multiple components found with name")),[Q]),s=z.useMemo(()=>x2I(Q),[Q]),r=z.useMemo(()=>K2I(Q,C),[C,Q]),a=z.useMemo(()=>n.map((l,D)=>{const d=("component_name"in l&&typeof l.component_name=="string"?l.component_name:void 0)??l.message?.match(/name "([^"]+)"/)?.[1];return d?{components:Q.filter(w=>w.type==="source_component"&&w.name===d||w.type==="pcb_component"&&Q.some(u=>u.type==="source_component"&&u.source_component_id===w.source_component_id&&u.name===d)),error:l,errorIndex:D}:{components:[],error:l,errorIndex:D}}),[n,Q]);if(!I)return q.jsx("div",{style:{position:"relative"},ref:e,children:g});const c=l=>{const D=eBo({error:l,indexes:s});if(!D||typeof D.x!="number"||typeof D.y!="number")return null;const d=Mt(A,D);return Number.isNaN(d.x)||Number.isNaN(d.y)?null:d};let h=null;return r&&(h=c(r)),q.jsxs("div",{style:{position:"relative"},ref:e,children:[g,i.map((l,D)=>{const d=CZ(l,D),y=C===d;if(!y&&!t)return null;const w=c(l);if(!w)return null;const u=ceg(w,e);return q.jsxs(z.Fragment,{children:[q.jsx(dfI,{errorCenter:w,isHighlighted:y}),q.jsx("div",{style:{position:"absolute",left:w.x-15,top:w.y-15,width:30,height:30,zIndex:da.errorOverlay+5,cursor:"pointer",borderRadius:"50%"},onMouseEnter:G=>{const m=G.currentTarget.nextElementSibling;if(m){const p=m.querySelector(".error-message");p&&(p.style.opacity="1")}},onMouseLeave:G=>{if(!y){const m=G.currentTarget.nextElementSibling;if(m){const p=m.querySelector(".error-message");p&&(p.style.opacity="0")}}}}),q.jsx("div",{style:{position:"absolute",zIndex:y?200:100,left:u.left,top:u.top,color:y?"#ff4444":"red",textAlign:"center",fontFamily:"sans-serif",fontSize:12,display:t||y?"flex":"none",flexDirection:"column",alignItems:"center",pointerEvents:"none",transform:u.transform},children:q.jsx("div",{className:`error-message ${heg}`,style:{opacity:y?1:0,border:`1px solid ${y?"#ff4444":"red"}`},children:l.message})})]},d)}),E.map((l,D)=>{const d=CZ(l,D),y=C===d;if(!y&&!t)return null;const w=c(l);if(!w)return null;const u=ceg({x:w.x,y:w.y},e);return q.jsxs(z.Fragment,{children:[q.jsx(dfI,{errorCenter:w,isHighlighted:y}),q.jsx("div",{style:{position:"absolute",left:w.x-15,top:w.y-15,width:30,height:30,zIndex:da.errorOverlay+5,cursor:"pointer",borderRadius:"50%"},onMouseEnter:G=>{const m=G.currentTarget.nextElementSibling;if(m){const p=m.querySelector(".error-message");p&&(p.style.opacity="1")}},onMouseLeave:G=>{if(!y){const m=G.currentTarget.nextElementSibling;if(m){const p=m.querySelector(".error-message");p&&(p.style.opacity="0")}}}}),q.jsx("div",{style:{position:"absolute",zIndex:y?da.errorOverlay+10:da.errorOverlay+1,left:u.left,top:u.top,color:y?"#ff4444":"red",textAlign:"center",fontFamily:"sans-serif",fontSize:12,display:"flex",flexDirection:"column",alignItems:"center",pointerEvents:"none",transform:u.transform},children:q.jsx("div",{className:`error-message ${heg}`,style:{opacity:y?1:0,border:`1px solid ${y?"#ff4444":"red"}`},children:l.message})})]},d)}),a.map(({components:l,error:D,errorIndex:d})=>{const y=CZ(D,d),w=C===y;return!w&&!t?null:l.map(u=>{let G={x:0,y:0};if(u.type==="pcb_component")G=u.center||{x:0,y:0};else if(u.type==="source_component"){const U=I?.find(K=>K.type==="pcb_component"&&K.source_component_id===u.source_component_id);U&&U.type==="pcb_component"&&(G=U.center||{x:0,y:0})}const m=Mt(A,G);if(Number.isNaN(m.x)||Number.isNaN(m.y))return null;const p=Math.abs(A.a),x=Math.max(8,Math.min(30,.5*p)),N=ceg(m,e);return q.jsxs(z.Fragment,{children:[q.jsx("svg",{style:{position:"absolute",left:0,top:0,pointerEvents:"none",mixBlendMode:"difference",zIndex:da.errorOverlay},width:"100%",height:"100%",children:w?q.jsx("polygon",{points:`${m.x},${m.y-x*1.25} ${m.x+x},${m.y} ${m.x},${m.y+x*1.25} ${m.x-x},${m.y}`,fill:"#ff4444"}):q.jsx("circle",{cx:m.x,cy:m.y,r:x,fill:"none",stroke:w?"#ff4444":"red",strokeWidth:w?Math.max(2,x*.15):Math.max(1,x*.1),opacity:1})}),q.jsx("div",{style:{position:"absolute",left:m.x-(x+10),top:m.y-(x+10),width:(x+10)*2,height:(x+10)*2,zIndex:da.errorOverlay+5,cursor:"pointer",borderRadius:"50%"},onMouseEnter:U=>{const K=U.currentTarget.nextElementSibling;if(K){const _=K.querySelector(".error-message");_&&(_.style.opacity="1")}},onMouseLeave:U=>{if(!w){const K=U.currentTarget.nextElementSibling;if(K){const _=K.querySelector(".error-message");_&&(_.style.opacity="0")}}}}),q.jsx("div",{style:{position:"absolute",zIndex:w?da.errorOverlay+20:da.errorOverlay+10,left:N.left,top:N.top,color:w?"#ff4444":"red",textAlign:"center",fontFamily:"sans-serif",fontSize:12,display:t||w?"flex":"none",flexDirection:"column",alignItems:"center",pointerEvents:"none",transform:N.transform},children:q.jsx("div",{className:`error-message ${heg}`,style:{opacity:w?1:0,border:`1px solid ${w?"#ff4444":"red"}`},children:D.message})})]},`${y}_${u.type}_${OCo(u)}`)})}),h&&q.jsx(TCo,{center:h})]})},yfI=(g,A,I,e)=>{if(I<=0||e<=0)return;const t=g.find(B=>B.type==="pcb_component"&&B.pcb_component_id===A);if(t?.type!=="pcb_component")return;const o=h2I(t);if(o)return{component:t,bounds:o,transform:P2I({bounds:o,width:I,height:e})}},VCo=({focusRequest:g,elements:A,transform:I})=>{const e=g?.pcbComponentId,t=ii(E=>E.selectLayer),o=e?yfI(A,e,1,1):void 0,B=o?.component.layer;if(z.useEffect(()=>{B&&t(B)},[g,B,t]),!o||!I)return null;const{bounds:C}=o,Q=Mt(I,{x:C.minX,y:C.minY}),i=Mt(I,{x:C.maxX,y:C.maxY});return q.jsx("div",{"data-focused-pcb-component-id":e,style:{position:"absolute",left:Math.min(Q.x,i.x)-4,top:Math.min(Q.y,i.y)-4,width:Math.abs(i.x-Q.x)+8,height:Math.abs(i.y-Q.y)+8,border:"2px solid #3399ff",borderRadius:4,boxSizing:"border-box",pointerEvents:"none",zIndex:da.elementOverlay}})};function jCo(g,A){return g.size!==A.size?!1:Array.from(g).every(I=>A.has(I))}var ec={MIN_LINE_LENGTH_FOR_LABEL:40,LABEL_OFFSET_ABOVE:2,LABEL_OFFSET_BELOW:-18,LABEL_OFFSET_RIGHT:8,LABEL_OFFSET_LEFT:-120,Y_LABEL_MIN_WIDTH:110,LINE_STROKE_WIDTH:1.5,LINE_DASH_PATTERN:"4,4",COMPONENT_MARKER_RADIUS:3,LABEL_FONT_SIZE:11,ANCHOR_MARKER_SIZE:6,ANCHOR_MARKER_STROKE_WIDTH:1.5},CS={OFFSET_LINE:"white",COMPONENT_MARKER_FILL:"#66ccff",COMPONENT_MARKER_STROKE:"white",LABEL_TEXT:"white"},leg=({targets:g,transform:A,containerWidth:I,containerHeight:e})=>{if(g.length===0)return null;const t={color:CS.LABEL_TEXT,mixBlendMode:"difference",pointerEvents:"none",fontSize:ec.LABEL_FONT_SIZE,fontFamily:"monospace",fontWeight:"bold"},o=new Map;return g.forEach(B=>{if(!o.has(B.anchor_id)){const C=Mt(A,B.anchor);o.set(B.anchor_id,C)}}),q.jsx("div",{style:{position:"absolute",left:0,top:0,width:I,height:e,overflow:"hidden",pointerEvents:"none",zIndex:da.dimensionOverlay},children:q.jsxs("svg",{style:{position:"absolute",left:0,top:0,pointerEvents:"none"},width:I,height:e,children:[g.map(B=>{const C=B.anchor,Q=B.anchor_id,i=B.target,E=o.get(Q),n=Mt(A,i),s=i.x-C.x,r=i.y-C.y,a=Math.abs(n.x-E.x),c=Math.abs(n.y-E.y),h=n.y<E.y,l=n.x>E.x,D=h?ec.LABEL_OFFSET_ABOVE:ec.LABEL_OFFSET_BELOW,d=l?ec.LABEL_OFFSET_RIGHT:ec.LABEL_OFFSET_LEFT,y=a>ec.MIN_LINE_LENGTH_FOR_LABEL,w=c>ec.MIN_LINE_LENGTH_FOR_LABEL,u=`${B.display_offset_x??s.toFixed(2)}mm`,G=`${B.display_offset_y??r.toFixed(2)}mm`;return q.jsxs("g",{children:[q.jsx("line",{x1:E.x,y1:E.y,x2:n.x,y2:E.y,stroke:CS.OFFSET_LINE,strokeWidth:ec.LINE_STROKE_WIDTH,strokeDasharray:ec.LINE_DASH_PATTERN}),q.jsx("line",{x1:n.x,y1:E.y,x2:n.x,y2:n.y,stroke:CS.OFFSET_LINE,strokeWidth:ec.LINE_STROKE_WIDTH,strokeDasharray:ec.LINE_DASH_PATTERN}),B.type==="component"||B.type==="board"?q.jsx("circle",{cx:n.x,cy:n.y,r:ec.COMPONENT_MARKER_RADIUS,fill:CS.COMPONENT_MARKER_FILL,stroke:CS.COMPONENT_MARKER_STROKE,strokeWidth:1}):q.jsxs(q.Fragment,{children:[q.jsx("line",{x1:n.x-ec.ANCHOR_MARKER_SIZE,y1:n.y,x2:n.x+ec.ANCHOR_MARKER_SIZE,y2:n.y,stroke:CS.OFFSET_LINE,strokeWidth:ec.ANCHOR_MARKER_STROKE_WIDTH}),q.jsx("line",{x1:n.x,y1:n.y-ec.ANCHOR_MARKER_SIZE,x2:n.x,y2:n.y+ec.ANCHOR_MARKER_SIZE,stroke:CS.OFFSET_LINE,strokeWidth:ec.ANCHOR_MARKER_STROKE_WIDTH})]}),y&&q.jsx("foreignObject",{x:Math.min(E.x,n.x),y:E.y+D,width:Math.abs(n.x-E.x),height:20,style:{overflow:"visible"},children:q.jsx("div",{style:{...t,textAlign:"center"},children:u})}),w&&q.jsx("foreignObject",{x:n.x+d,y:Math.min(E.y,n.y),width:ec.Y_LABEL_MIN_WIDTH,height:Math.abs(n.y-E.y),style:{overflow:"visible"},children:q.jsx("div",{style:{...t,display:"flex",alignItems:"center",justifyContent:l?"flex-start":"flex-end",whiteSpace:"nowrap",padding:"0 4px",height:"100%"},children:G})})]},B.id)}),Array.from(o.entries()).map(([B,C])=>q.jsxs("g",{children:[q.jsx("line",{x1:C.x-ec.ANCHOR_MARKER_SIZE,y1:C.y,x2:C.x+ec.ANCHOR_MARKER_SIZE,y2:C.y,stroke:CS.OFFSET_LINE,strokeWidth:ec.ANCHOR_MARKER_STROKE_WIDTH}),q.jsx("line",{x1:C.x,y1:C.y-ec.ANCHOR_MARKER_SIZE,x2:C.x,y2:C.y+ec.ANCHOR_MARKER_SIZE,stroke:CS.OFFSET_LINE,strokeWidth:ec.ANCHOR_MARKER_STROKE_WIDTH})]},`anchor-${B}`))]})})},L3=g=>g?.type==="pcb_component",wfI=g=>g?.type==="pcb_group",zCo=g=>g?.type==="pcb_panel",Deg=g=>g?.type==="pcb_board",XCo=({elements:g,highlightedPrimitives:A,transform:I,containerWidth:e,containerHeight:t})=>{const o=ii(l=>l.is_showing_group_anchor_offsets),B=A.map(l=>L3(l._parent_pcb_component)?l._parent_pcb_component.pcb_component_id:L3(l._element)?l._element.pcb_component_id:null).filter(l=>!!l);if(!o&&B.length===0)return null;const C=g.filter(l=>Deg(l)),Q=g.filter(l=>L3(l)),i=g.filter(l=>wfI(l)),E=new Set;B.forEach(l=>{const D=Q.find(d=>d.pcb_component_id===l);D?.pcb_group_id&&E.add(D.pcb_group_id)});const n=Q.map(l=>{const D=l.positioned_relative_to_pcb_board_id;if(!D)return null;const d=C.find(y=>y.pcb_board_id===D);return d?{component:l,board:d,type:"component"}:null}).filter(l=>!!l),s=i.map(l=>{const D=l.positioned_relative_to_pcb_board_id;if(!D||!l.center)return null;const d=C.find(y=>y.pcb_board_id===D);return d?{group:l,board:d,type:"group"}:null}).filter(l=>!!l),r=[...n,...s];if(r.length===0)return null;const a=B.length===0,c=r.filter(l=>l.type==="component"?a||B.includes(l.component.pcb_component_id):a||E.has(l.group.pcb_group_id));if(c.length===0)return null;const h=c.map(l=>l.type==="component"?{id:`${l.board.pcb_board_id}-${l.component.pcb_component_id}-${l.type}`,anchor:l.board.center,anchor_id:l.board.pcb_board_id,target:l.component.center,type:"component",display_offset_x:l.component.display_offset_x,display_offset_y:l.component.display_offset_y}:{id:`${l.board.pcb_board_id}-${l.group.pcb_group_id}-${l.type}`,anchor:l.board.center,anchor_id:l.board.pcb_board_id,target:{x:l.group.anchor_position?.x??l.group.center.x,y:l.group.anchor_position?.y??l.group.center.y},type:"group",display_offset_x:l.group.display_offset_x,display_offset_y:l.group.display_offset_y}).filter(l=>!!l);return q.jsx(leg,{targets:h,transform:I,containerWidth:e,containerHeight:t})},$Co=({elements:g,highlightedPrimitives:A,transform:I,containerWidth:e,containerHeight:t})=>{const o=ii(l=>l.is_showing_group_anchor_offsets),B=A.map(l=>L3(l._parent_pcb_component)?l._parent_pcb_component.pcb_component_id:L3(l._element)?l._element.pcb_component_id:null).filter(l=>!!l);if(!o&&B.length===0)return null;const C=g.filter(l=>wfI(l)),Q=g.filter(l=>L3(l)),i=(l,D)=>{if(D.has(l))return;D.add(l);const d=C.find(y=>y.pcb_group_id===l);d?.position_mode==="relative_to_group_anchor"&&d.positioned_relative_to_pcb_group_id&&i(d.positioned_relative_to_pcb_group_id,D)},E=new Set;B.forEach(l=>{const D=Q.find(d=>d.pcb_component_id===l);D&&(D.position_mode==="relative_to_group_anchor"&&D.positioned_relative_to_pcb_group_id&&i(D.positioned_relative_to_pcb_group_id,E),D.pcb_group_id&&i(D.pcb_group_id,E))});const n=Q.map(l=>{if(l.position_mode==="relative_to_group_anchor"&&l.positioned_relative_to_pcb_group_id){const D=C.find(d=>d.pcb_group_id===l.positioned_relative_to_pcb_group_id);return D?.anchor_position?{component:l,parentGroup:D,type:"component"}:null}if(l.pcb_group_id){const D=C.find(d=>d.pcb_group_id===l.pcb_group_id);return D?.anchor_position?{component:l,parentGroup:D,type:"component"}:null}return null}).filter(l=>!!l),s=C.map(l=>{if(l.position_mode==="relative_to_group_anchor"&&l.positioned_relative_to_pcb_group_id){const D=C.find(d=>d.pcb_group_id===l.positioned_relative_to_pcb_group_id);if(D?.anchor_position&&l.anchor_position)return{group:l,parentGroup:D,type:"group"}}return null}).filter(l=>!!l),r=[...n,...s];if(r.length===0)return null;const a=B.length===0,c=r.filter(l=>l.type==="component"?a||B.includes(l.component.pcb_component_id):a||E.has(l.group.pcb_group_id)||E.has(l.parentGroup.pcb_group_id));if(c.length===0)return null;const h=c.map(l=>{const D=l.parentGroup.anchor_position;return D?l.type==="component"?l.component.center?{id:`${l.parentGroup.pcb_group_id}-${l.component.pcb_component_id}-${l.type}`,anchor:D,anchor_id:l.parentGroup.pcb_group_id,target:l.component.center,type:"component",display_offset_x:l.component.display_offset_x,display_offset_y:l.component.display_offset_y}:null:l.group.anchor_position?{id:`${l.parentGroup.pcb_group_id}-${l.group.pcb_group_id}-${l.type}`,anchor:D,anchor_id:l.parentGroup.pcb_group_id,target:l.group.anchor_position,type:"group",display_offset_x:l.group.display_offset_x,display_offset_y:l.group.display_offset_y}:null:null}).filter(l=>!!l);return q.jsx(leg,{targets:h,transform:I,containerWidth:e,containerHeight:t})},AQo=(g,A)=>{const I=g.pcb_component_id,e=A.filter(t=>(t.type==="pcb_smtpad"||t.type==="pcb_plated_hole")&&t.pcb_component_id===I||t.type==="pcb_hole"&&t.pcb_component_id===I);return e.length===0?Eeg([g]):Eeg(e)},gQo=({elements:g,highlightedPrimitives:A,transform:I,containerWidth:e,containerHeight:t})=>{const o=new Map;for(const C of A)L3(C._parent_pcb_component)&&o.set(C._parent_pcb_component.pcb_component_id,C._parent_pcb_component),L3(C._element)&&o.set(C._element.pcb_component_id,C._element);if(o.size===0)return null;const B=[];for(const C of o.values()){const Q=AQo(C,g);if(!Q)continue;const i=C.positioned_relative_to_pcb_group_id??C.pcb_group_id,E=i?Y5(g).pcb_group.get(i):null;B.push({component:C,bbox:Q,group:E})}return B.length===0?null:q.jsx("div",{style:{position:"absolute",left:0,top:0,width:e,height:t,overflow:"hidden",pointerEvents:"none",zIndex:da.dimensionOverlay},children:q.jsx("svg",{style:{position:"absolute",left:0,top:0,pointerEvents:"none"},width:e,height:t,children:B.map(({component:C,bbox:Q,group:i})=>{const E=Mt(I,{x:Q.minX,y:Q.maxY}),n=Mt(I,{x:Q.maxX,y:Q.minY}),s={x:Math.min(E.x,n.x),y:Math.min(E.y,n.y),width:Math.abs(n.x-E.x),height:Math.abs(n.y-E.y)},r=C.center??{x:(Q.minX+Q.maxX)/2,y:(Q.minY+Q.maxY)/2},a=Mt(I,r);return q.jsxs("g",{children:[q.jsx("rect",{x:s.x,y:s.y,width:s.width,height:s.height,fill:"none",stroke:"white",strokeWidth:1.5,strokeDasharray:"4,4"}),q.jsx("line",{x1:a.x-6,y1:a.y,x2:a.x+6,y2:a.y,stroke:CS.COMPONENT_MARKER_STROKE,strokeWidth:1.5}),q.jsx("line",{x1:a.x,y1:a.y-6,x2:a.x,y2:a.y+6,stroke:CS.COMPONENT_MARKER_STROKE,strokeWidth:1.5}),q.jsx("circle",{cx:a.x,cy:a.y,r:ec.COMPONENT_MARKER_RADIUS,fill:CS.COMPONENT_MARKER_FILL,stroke:CS.COMPONENT_MARKER_STROKE,strokeWidth:1})]},C.pcb_component_id)})})})},IQo=({elements:g,highlightedPrimitives:A,transform:I,containerWidth:e,containerHeight:t})=>{const o=ii(r=>r.is_showing_group_anchor_offsets),B=A.map(r=>Deg(r._element)?r._element.pcb_board_id:null).filter(r=>!!r);if(!o&&B.length===0)return null;const C=g.filter(r=>zCo(r)),i=g.filter(r=>Deg(r)).map(r=>{const a=r.pcb_panel_id,c=r.position_mode;if(!a||c!=="relative_to_panel_anchor")return null;const h=C.find(l=>l.pcb_panel_id===a);return h?{board:r,panel:h,type:"board"}:null}).filter(r=>!!r);if(i.length===0)return null;const E=B.length===0,n=i.filter(r=>E||B.includes(r.board.pcb_board_id));if(n.length===0)return null;const s=n.map(r=>r.board.center?{id:`${r.panel.pcb_panel_id}-${r.board.pcb_board_id}-${r.type}`,anchor:r.panel.center,anchor_id:r.panel.pcb_panel_id,target:r.board.center,type:"board",display_offset_x:r.board.display_offset_x,display_offset_y:r.board.display_offset_y}:null).filter(r=>!!r);return q.jsx(leg,{targets:s,transform:I,containerWidth:e,containerHeight:t})};function eQo(g){const{primitives:A,is_showing_multiple_traces_length:I,traceOverlayElementIndex:e}=g,t=A.filter(C=>C._element.type==="pcb_trace"),o=A.filter(C=>C._element.type!=="pcb_trace"),B=t.filter(C=>(C._element.source_trace_id?e.sourceTraceById.get(C._element.source_trace_id):void 0)?.max_length!==void 0||aeg({primitiveElement:C._element,traceOverlayElementIndex:e})!==null);if(!I)return[...o,...B];if(t.length>1){const C=t.reduce((Q,i)=>{const E=Q._element.trace_length;return i._element.trace_length<E?i:Q},t[0]);return[...o,C]}return A}var tQo={position:"absolute",left:0,top:0,pointerEvents:"none",color:"red",fontFamily:"sans-serif",fontSize:12,textShadow:"0 0 2px black"},oQo=g=>{const{_element:A,_parent_pcb_component:I,_parent_source_component:e,_source_port:t}=g;switch(A.type){case"pcb_trace":return A.trace_length?`${A.trace_length.toFixed(3)}`:"";case"pcb_smtpad":case"pcb_plated_hole":{const o=[],B=Array.from(new Set((A.port_hints??[]).concat(t?.port_hints??[]))).filter(Q=>!/^[0-9]+$/.test(Q)).filter(Q=>!Q.includes("unnamed_")).sort((Q,i)=>i.localeCompare(Q)),C=e&&"name"in e&&e.name&&!e.name.includes("unnamed_")?e.name:null;return B.length>0?C?o.push(...B.map(Q=>`${C}.${Q}`)):o.push(...B):C&&o.push(C),o.join(", ")}default:return""}},BQo={top:"red",bottom:"aqua"},CQo=({primitive:g,mousePos:A,traceOverlayElementIndex:I})=>{const[e,t]=z.useState(!1),o=g._element;z.useEffect(()=>{setTimeout(()=>{t(!0)},100)},[]);const[B,C,Q,i]=[g.screen_x,g.screen_y,g.screen_w,g.screen_h],E=g.same_space_index??0,n=26,s=BQo[g?._element?.layer]??"red";let r=0;if(o.type==="pcb_smtpad"&&o?.shape==="rotated_rect"?r=o?.ccw_rotation??0:(o.type==="pcb_smtpad"&&(o?.shape==="pill"||o?.shape==="rotated_pill")&&"ccw_rotation"in g||o.type==="pcb_plated_hole"&&(o?.shape==="pill"||o?.shape==="oval")&&"ccw_rotation"in g)&&(r=o.ccw_rotation??0),o.type==="pcb_trace"){const h=_2I({primitiveElement:o,traceOverlayElementIndex:I});return h?q.jsx("div",{style:{zIndex:da.elementOverlay,position:"absolute",left:A.x+12,top:A.y+12,color:s,pointerEvents:"none"},children:q.jsxs("div",{style:{backgroundColor:"#f2efcc",color:h.isOverLength?"red":"black",textShadow:"none",WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale",padding:"4px 6px",borderRadius:"4px",fontSize:"11px",lineHeight:1.2,textAlign:"left",whiteSpace:"nowrap"},children:[h.text&&q.jsx("div",{children:h.text}),h.name&&q.jsx("div",{style:{marginTop:h.text?"2px":0},children:h.name})]})}):null}const a=oQo(g);return a.trim().length===0?null:q.jsx("div",{style:{zIndex:da.elementOverlay,position:"absolute",left:B-Q/2-8,top:C-i/2-8,width:Q+16,height:i+16,color:s,transform:`rotate(${-r}deg)`,transformOrigin:"center center"},children:q.jsx("div",{style:{width:e?`calc(100% + ${n*2*E}px)`:"100%",height:e?`calc(100% + ${n*2*E}px)`:"100%",marginLeft:e?`${-n*E}px`:0,marginTop:e?`${-n*E}px`:0,border:`1px solid ${s}`,opacity:e||E===0?1:0,transition:"width 0.2s, height 0.2s, margin-left 0.2s, margin-top 0.2s, opacity 0.2s"},children:q.jsx("div",{style:{position:"absolute",bottom:i+20+n*E,marginRight:e?`${-n*E}px`:0,marginBottom:e?0:-n*E,transition:"margin-right 0.2s, margin-bottom 0.2s",backgroundColor:"#f2efcc",color:"black",textShadow:"none",WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale",padding:"6px 6px",borderRadius:"6px",fontSize:"14px",transform:`rotate(${r}deg)`,minWidth:"45px",textAlign:"center"},children:a})})})},QQo=({highlightedPrimitives:g,mousePos:A,elements:I})=>{const[e,t]=ii(Q=>[Q.is_moving_component,Q.is_showing_multiple_traces_length]),o=z.useMemo(()=>Y2I(I),[I]),B=g.some(Q=>Q._element.type==="pcb_smtpad")&&g.some(Q=>Q._element.type==="pcb_trace");let C=g;return B&&(C=C.filter(Q=>Q._element.type==="pcb_smtpad")),C=eQo({primitives:C,is_showing_multiple_traces_length:t,traceOverlayElementIndex:o}),q.jsx("div",{style:tQo,children:!e&&C.map(Q=>q.jsx(CQo,{primitive:Q,mousePos:A,traceOverlayElementIndex:o},Q._pcb_drawing_object_id))})},jwA=g=>{if(g.length===0)return null;let A=g[0].x,I=g[0].y,e=g[0].x,t=g[0].y;for(const o of g)o.x<A&&(A=o.x),o.y<I&&(I=o.y),o.x>e&&(e=o.x),o.y>t&&(t=o.y);return{center:{x:(A+e)/2,y:(I+t)/2},width:e-A,height:t-I}},ufI=(g,A)=>{if(A.length<3)return!1;let I=!1;for(let e=0,t=A.length-1;e<A.length;t=e++){const o=A[e].x,B=A[e].y,C=A[t].x,Q=A[t].y;B>g.y!=Q>g.y&&g.x<(C-o)*(g.y-B)/(Q-B||Number.EPSILON)+o&&(I=!I)}return I},deg=({includeHiddenTraces:g=!1,primitives:A,rwPoint:I,selectedLayer:e,transform:t})=>{const o=[];for(const B of A){if(!B._element||!g&&B._element.type==="pcb_trace"&&B.layer!==e)continue;if("x1"in B&&B._element?.type==="pcb_trace"){const i=rh({x:I.x,y:I.y},{x:B.x1,y:B.y1},{x:B.x2,y:B.y2}),E=B.width||.5,n=Math.max(E*25,2)/t.a;i<n&&o.push(B);continue}if(B.pcb_drawing_type==="polygon"){const i=B.points.map(n=>({x:sg.parse(n.x),y:sg.parse(n.y)})),E=jwA(i);if(!E||I.x<E.center.x-E.width/2||I.x>E.center.x+E.width/2||I.y<E.center.y-E.height/2||I.y>E.center.y+E.height/2)continue;ufI(I,i)&&o.push(B);continue}if(B.pcb_drawing_type==="polygon_with_arcs"){const i=B.brep_shape.outer_ring.vertices.map(n=>({x:sg.parse(n.x),y:sg.parse(n.y)})),E=jwA(i);if(!E||I.x<E.center.x-E.width/2||I.x>E.center.x+E.width/2||I.y<E.center.y-E.height/2||I.y>E.center.y+E.height/2)continue;ufI(I,i)&&o.push(B);continue}if(!("x"in B&&"y"in B))continue;let C=0,Q=0;if("w"in B&&"h"in B)C=B.w,Q=B.h;else if("r"in B)C=B.r*2,Q=B.r*2;else if("rX"in B&&"rY"in B)C=B.rX*2,Q=B.rY*2;else continue;Math.abs(B.x-I.x)<C/2&&Math.abs(B.y-I.y)<Q/2&&o.push(B)}return o},iQo=({elements:g,children:A,transform:I,primitives:e,selectedLayer:t,onMouseHoverOverPrimitives:o})=>{const[B,C]=z.useState([]),[Q,i]=z.useState({x:0,y:0}),[E,{width:n,height:s}]=QeA(),r=z.useMemo(()=>R2I(e),[e]);z.useEffect(()=>{C([]),o([])},[t,e,o]);const a=z.useMemo(()=>{const h=[];for(const l of B){if(l._element?.type==="pcb_via"||l._element?.type==="pcb_component"||l?.layer==="drill"||l?.is_hoverable===!1)continue;let D=null,d=0,y=0;if(l.pcb_drawing_type==="polygon"){const m=jwA(l.points);if(!m)continue;D=m.center,d=m.width,y=m.height}else if(l.pcb_drawing_type==="polygon_with_arcs"){const m=l.brep_shape.outer_ring.vertices.map(k=>({x:k.x,y:k.y})),p=jwA(m);if(!p)continue;D=p.center,d=p.width,y=p.height}else l.pcb_drawing_type==="line"?(D={x:(l.x1+l.x2)/2,y:(l.y1+l.y2)/2},d=Math.abs(l.x2-l.x1),y=Math.abs(l.y2-l.y1)):"x"in l&&"y"in l&&(D={x:l.x,y:l.y},d="w"in l?l.w:"r"in l?l.r*2:"rX"in l&&"rY"in l?l.rX*2:0,y="h"in l?l.h:"r"in l?l.r*2:"rX"in l&&"rY"in l?l.rY*2:0);if(!D)continue;const w=Mt(I,D),u={w:d*I.a,h:y*I.a},G=h.filter(m=>w.x===m.screen_x&&w.y===m.screen_y&&u.w===m.screen_w&&u.h===m.screen_h).length;h.push({...l,x:D.x,y:D.y,w:d,h:y,screen_x:w.x,screen_y:w.y,screen_w:u.w,screen_h:u.h,same_space_index:G})}return h},[B,I]),c=({screenPoint:h,transform:l})=>{const{x:D,y:d}=h;i({x:D,y:d});const y=Mt(Nx(l),{x:D,y:d}),w=N2I({point:y,realToScreenScale:l.a,spatialIndex:r}),u=deg({primitives:w,rwPoint:y,selectedLayer:t,transform:l});jCo(new Set(u.map(G=>G._pcb_drawing_object_id)),new Set(B.map(G=>G._pcb_drawing_object_id)))||(C(u),o(u))};return q.jsxs("div",{ref:E,style:{position:"relative",width:"100%",height:"100%"},onMouseMove:h=>{if(h.buttons===0&&I){const l=h.currentTarget.getBoundingClientRect(),D=h.clientX-l.left,d=h.clientY-l.top;c({screenPoint:{x:D,y:d},transform:I})}},onTouchStart:h=>{if(I){const l=h.touches[0],D=h.currentTarget.getBoundingClientRect(),d=l.clientX-D.left,y=l.clientY-D.top;c({screenPoint:{x:d,y},transform:I})}},children:[A,q.jsx(QQo,{elements:g,mousePos:Q,highlightedPrimitives:a}),I&&q.jsxs(q.Fragment,{children:[q.jsx(XCo,{elements:g,highlightedPrimitives:a,transform:I,containerWidth:n,containerHeight:s}),q.jsx($Co,{elements:g,highlightedPrimitives:a,transform:I,containerWidth:n,containerHeight:s}),q.jsx(gQo,{elements:g,highlightedPrimitives:a,transform:I,containerWidth:n,containerHeight:s}),q.jsx(IQo,{elements:g,highlightedPrimitives:a,transform:I,containerWidth:n,containerHeight:s})]})]})},GfI=["rgb(255, 100, 100)","rgb(100, 255, 100)","rgb(100, 100, 255)","rgb(255, 255, 100)","rgb(255, 100, 255)","rgb(100, 255, 255)","rgb(255, 150, 100)","rgb(150, 100, 255)","rgb(100, 255, 150)","rgb(255, 100, 150)"];function mfI(g){if("parent_source_group_id"in g)return typeof g.parent_source_group_id=="string"?g.parent_source_group_id:void 0}function yeg(g,A){const I=[],e=A.get(g)??[];for(const t of e)I.push(t),I.push(...yeg(t,A));return I}function pfI(g,A){const I=A.get(g);if(!I)return 0;const e=mfI(I);return e?1+pfI(e,A):0}var EQo=({children:g,transform:A=uJ(),elements:I=[],hoveredComponentIds:e=[]})=>{const[t,{width:o,height:B}]=QeA(),C=z.useRef(null),{is_showing_pcb_groups:Q,pcb_group_view_mode:i,is_showing_group_anchor_offsets:E}=ii(a=>({is_showing_pcb_groups:a.is_showing_pcb_groups,pcb_group_view_mode:a.pcb_group_view_mode,is_showing_group_anchor_offsets:a.is_showing_group_anchor_offsets})),{pcbComponents:n,pcbGroups:s,sourceGroups:r}=z.useMemo(()=>{const a=[],c=[],h=[];for(const l of I)l.type==="pcb_component"?a.push(l):l.type==="pcb_group"?c.push(l):l.type==="source_group"&&h.push(l);return{pcbComponents:a,pcbGroups:c,sourceGroups:h}},[I]);return z.useEffect(()=>{const a=C.current;if(!a||!o||!B)return;a.width=o,a.height=B;const c=a.getContext("2d");if(!c||(c.clearRect(0,0,o,B),!Q))return;const h=new Map(r.map(y=>[y.source_group_id,y])),l=s.filter(y=>{if(y.name?.toLowerCase().includes("subpanel"))return!1;if(i==="all")return!0;if(!y.source_group_id)return!1;const w=h.get(y.source_group_id);return w?w.was_automatically_named!==!0:!1}),D=new Map;r.forEach(y=>{const w=mfI(y);if(w){const u=D.get(w)??[];u.push(y.source_group_id),D.set(w,u)}});const d=new Set;if(e.length>0)for(const y of n){if(!e.includes(y.pcb_component_id))continue;const w=y.positioned_relative_to_pcb_group_id??y.pcb_group_id;w&&d.add(w)}l.forEach((y,w)=>{let u=n.filter(xA=>xA.pcb_group_id===y.pcb_group_id);if(y.source_group_id){const xA=yeg(y.source_group_id,D),RA=s.filter(NA=>NA.source_group_id&&xA.includes(NA.source_group_id));for(const NA of RA){const YA=n.filter(PA=>PA.pcb_group_id===NA.pcb_group_id);u=[...u,...YA]}}let G,m,p,k,S=!1;if(y.center&&y.width&&y.height){S=!0;const xA=y.width/2,RA=y.height/2;G=y.center.x-xA,p=y.center.x+xA,m=y.center.y-RA,k=y.center.y+RA}else if(u.length===0||(G=1/0,m=1/0,p=-1/0,k=-1/0,u.forEach(xA=>{if(xA.center&&typeof xA.width=="number"&&typeof xA.height=="number"){const RA=xA.center.x-xA.width/2,NA=xA.center.x+xA.width/2,YA=xA.center.y+xA.height/2,PA=xA.center.y-xA.height/2;G=Math.min(G,RA),p=Math.max(p,NA),m=Math.min(m,PA),k=Math.max(k,YA)}}),G===1/0||p===-1/0))return;const R=y.source_group_id?pfI(y.source_group_id,h):0,x=y.source_group_id?yeg(y.source_group_id,D).length>0:!1;if(!S){const NA=1+(x?.5:0);G-=NA,p+=NA,m-=NA,k+=NA}const N=Mt(A,{x:G,y:k}),U=Mt(A,{x:p,y:k}),K=Mt(A,{x:G,y:m}),_=Mt(A,{x:p,y:m}),b=GfI[w%GfI.length];c.strokeStyle=b,c.lineWidth=2;const T=Math.max(4,Math.min(12,8*Math.abs(A.a))),j=Math.max(2,Math.min(6,4*Math.abs(A.a))),O=T*(x?1.3:1),gA=j;c.setLineDash([O,gA]),c.beginPath(),c.moveTo(N.x,N.y),c.lineTo(U.x,U.y),c.lineTo(_.x,_.y),c.lineTo(K.x,K.y),c.closePath(),c.stroke();const tA=Math.max(8,Math.min(12,10*Math.abs(A.a))),IA=R===0||R===1?0:R*.11,QA=tA*(1-IA),nA=4,DA=y.name||`Group ${w+1}`;c.font=`${QA}px sans-serif`,c.setLineDash([]);const hA=c.measureText(DA).width+nA*2,sA=QA+nA*2,cA=N.x-5,SA=N.y-5,FA=3;if(c.fillStyle="rgba(0, 0, 0, 0.8)",c.beginPath(),c.roundRect(cA,SA-sA,hA,sA,FA),c.fill(),c.fillStyle=b,c.textAlign="left",c.textBaseline="middle",c.fillText(DA,cA+nA,SA-sA/2),E&&d.has(y.pcb_group_id)&&!!y.anchor_position&&y.anchor_position){const xA=Array.isArray(y.anchor_position)?{x:y.anchor_position[0]??0,y:y.anchor_position[1]??0}:{x:y.anchor_position.x,y:y.anchor_position.y},RA=Mt(A,xA);c.strokeStyle="white",c.lineWidth=1.5,c.setLineDash([]);const NA=Math.max(4,Math.min(8,6*Math.abs(A.a)));c.beginPath(),c.moveTo(RA.x-NA,RA.y),c.lineTo(RA.x+NA,RA.y),c.stroke(),c.beginPath(),c.moveTo(RA.x,RA.y-NA),c.lineTo(RA.x,RA.y+NA),c.stroke()}})},[B,Q,E,e,n,s,i,r,A,o]),q.jsxs("div",{ref:t,style:{position:"relative",width:"100%",height:"100%"},children:[g,q.jsx("canvas",{ref:C,style:{position:"absolute",top:0,left:0,pointerEvents:"none",zIndex:da.pcbGroupOverlay,display:Q?"block":"none"}})]})},nQo=({transform:g,soup:A,connectivityMap:I,children:e})=>{const t=ii(Q=>Q.is_showing_rats_nest),{netMap:o,idToNetMap:B}=I,C=z.useMemo(()=>{if(!A||!t)return[];const Q=r=>{const a=Y5(A)[r.replace(/_\d+$/,"")].get(r);return a&&"x"in a&&"y"in a?{x:a.x,y:a.y}:null},i=(r,a)=>{const c=o[a]||[];let h=null,l=1/0;return c.forEach(D=>{const d=Q(D);if(d){const y=Math.sqrt((r.x-d.x)**2+(r.y-d.y)**2);y<l&&y>0&&(l=y,h=d)}}),h},E=Y5(A).pcb_port.list(),n=Y5(A).source_trace.list(),s=[];return E.forEach((r,a)=>{const c=B[r.pcb_port_id];let h=!1;for(const d of n)d.connected_source_port_ids.includes(r.source_port_id)&&d.connected_source_net_ids.length>0&&(h=!0);if(!c)return;const l={x:r.x,y:r.y},D=i(l,c);D&&s.push({key:`${r.pcb_port_id}-${a}`,startPoint:l,endPoint:D,isInNet:h})}),s},[A,o,B,t]);return!A||!t?e:(g||(g=uJ()),q.jsxs("div",{style:{position:"relative"},children:[e,q.jsx("svg",{style:{position:"absolute",left:0,top:0,width:"100%",height:"100%",pointerEvents:"none",opacity:.5,zIndex:da.ratsNestOverlay},children:C.map(({key:Q,startPoint:i,endPoint:E,isInNet:n})=>{const s=Mt(g,i),r=Mt(g,E);return q.jsx("line",{x1:s.x,y1:s.y,x2:r.x,y2:r.y,stroke:"white",strokeWidth:"1",strokeDasharray:n?"6,6":void 0},Q)})})]}))},Yx=(g,A,I)=>{const e=ii(B=>B.is_mouse_over_container),t=z.useRef(e),o=z.useRef(A);z.useEffect(()=>{t.current=e},[e]),z.useEffect(()=>{o.current=A},[A]),z.useEffect(()=>{if(!g)return;const B=C=>{const Q=C.target;if(Q.tagName==="INPUT"||Q.tagName==="TEXTAREA"||Q.isContentEditable)return;const i=g.split("+"),E=i.includes("ctrl"),n=i.includes("shift"),s=i.includes("alt"),r=i.includes("meta"),a=i[i.length-1],c=I?.current?I.current.contains(document.activeElement)||document.activeElement===I.current:!1;(t.current||c)&&(!E||C.ctrlKey)&&(!n||C.shiftKey)&&(!s||C.altKey)&&(!r||C.metaKey)&&C.key.toLowerCase()===a.toLowerCase()&&(C.preventDefault(),o.current())};return window.addEventListener("keydown",B),()=>{window.removeEventListener("keydown",B)}},[g])},sQo=()=>{const[g,A]=z.useState(!1);return z.useEffect(()=>{const I=()=>{A(window.innerWidth<=768)};return I(),window.addEventListener("resize",I),()=>window.removeEventListener("resize",I)},[]),g},neA=(g,A={stopPropagation:!0})=>{const I=z.useRef(0),e=z.useCallback(B=>{A.stopPropagation&&B.stopPropagation();const C=Date.now();C-I.current<300||(I.current=C,g?.(B))},[g,A.stopPropagation]),t=z.useCallback(B=>{B.preventDefault(),e(B)},[e]);return{onClick:e,onTouchEnd:t,style:{touchAction:"manipulation"}}},aQo={version:"1.11.430"},iZ=({children:g,isSmallScreen:A,onClick:I,...e})=>{const{style:t,...o}=neA(I);return q.jsx("div",{...e,...o,style:{backgroundColor:"#1F1F1F",border:"1px solid #666",margin:0,padding:4,paddingLeft:A?8:6,paddingRight:A?8:6,borderRadius:2,color:"#eee",cursor:"pointer",fontSize:12,height:"fit-content",userSelect:"none",whiteSpace:"nowrap",...t,...e.style},children:g})},rQo=g=>{const A=new Map;return g.forEach((I,e)=>{const t=I.error_type||"unknown_error",o=A.get(t)||[];o.push({error:I,index:e,errorId:CZ(I,e)}),A.set(t,o)}),Array.from(A.entries()).map(([I,e])=>({errorType:I,errors:e}))},cQo=({onClose:g,setHoveredErrorId:A,setFocusedErrorId:I,highlightDurationMs:e=3e3})=>{const t=z.useRef(null),o=z.useRef(null),B=z.useRef(null),C=z.useCallback(()=>{t.current!==null&&(window.clearTimeout(t.current),t.current=null),o.current!==null&&(window.cancelAnimationFrame(o.current),o.current=null)},[]);z.useEffect(()=>C,[C]);const Q=z.useCallback(E=>{C(),B.current=E,A(E),I(null),o.current=window.requestAnimationFrame(()=>{I(E),o.current=null}),g(),t.current=window.setTimeout(()=>{B.current=null,A(null),I(null),t.current=null},e)},[C,e,g,I,A]),i=z.useCallback(E=>B.current===E,[]);return{handleErrorSelect:Q,isSelectedError:i}},hQo=({errorId:g,errorMessage:A,copiedErrorId:I,onCopy:e})=>{const{style:t,...o}=neA(()=>e(A,g));return q.jsx("button",{type:"button","aria-label":I===g?"Error message copied":"Copy error message",style:{position:"absolute",top:12,right:16,cursor:"pointer",color:"#888",fontSize:16,background:"none",border:"none",padding:0,display:"flex",alignItems:"center",...t},...o,children:I===g?q.jsx("span",{style:{color:"#4caf50",fontSize:12},children:"Copied!"}):q.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",children:q.jsx("path",{d:"M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"})})})},lQo=({elements:g,isOpen:A,isSmallScreen:I,onToggle:e,onClose:t,setHoveredErrorId:o,setFocusedErrorId:B})=>{const[C,Q]=z.useState(null),[i,E]=z.useState(new Set),[n,s]=z.useState(new Set),[,r]=Goo(),{handleErrorSelect:a,isSelectedError:c}=cQo({onClose:t,setHoveredErrorId:o,setFocusedErrorId:B}),h=z.useMemo(()=>g?.filter(w=>w.type.includes("error"))??[],[g]),l=h.length,D=z.useMemo(()=>rQo(h),[h]),d=z.useCallback(w=>{E(u=>{const G=new Set(u);return G.has(w)?G.delete(w):G.add(w),G})},[]),y=z.useCallback(w=>{s(u=>{const G=new Set(u);return G.has(w)?G.delete(w):G.add(w),G})},[]);return q.jsxs("div",{style:{position:"relative"},children:[q.jsx(iZ,{isSmallScreen:I,style:l>0?{color:"red"}:void 0,onClick:e,children:q.jsxs("div",{children:[l," errors"]})}),A&&l>0&&q.jsx("div",{style:{position:"absolute",top:"100%",left:0,backgroundColor:"#2a2a2a",border:"1px solid #666",borderRadius:4,marginTop:4,zIndex:1e3,minWidth:I?"280px":"400px",maxWidth:I?"90vw":"600px",maxHeight:"400px",overflow:"auto",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.3)"},children:D.map(({errorType:w,errors:u},G)=>{const m=i.has(w);return q.jsxs("div",{style:{borderBottom:G<D.length-1?"1px solid #444":"none"},children:[q.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",cursor:"pointer",backgroundColor:"#232323",transition:"background-color 0.2s ease",touchAction:"manipulation",position:"sticky",top:0,zIndex:1},onMouseEnter:p=>{p.currentTarget.style.backgroundColor="#303030"},onMouseLeave:p=>{p.currentTarget.style.backgroundColor="#232323"},onTouchStart:p=>{p.stopPropagation(),p.currentTarget.style.backgroundColor="#303030"},onTouchEnd:p=>{p.stopPropagation(),p.preventDefault(),p.currentTarget.style.backgroundColor="#232323",d(w)},onClick:p=>{p.stopPropagation(),d(w)},children:[q.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,color:"#ff6b6b"},children:[q.jsx("div",{style:{color:"#888",fontSize:"16px",transform:m?"rotate(90deg)":"rotate(0deg)",transition:"transform 0.2s ease",flexShrink:0},children:"›"}),q.jsx("div",{style:{fontWeight:"bold",fontSize:I?"12px":"13px"},children:w})]}),q.jsx("div",{style:{fontSize:I?"12px":"13px",color:"#aaa",whiteSpace:"nowrap",marginLeft:12},children:u.length})]}),!m&&u.map(({error:p,index:k,errorId:S})=>{const R=n.has(S),x=p.message??"No error message";return q.jsxs("div",{style:{borderTop:"1px solid #3a3a3a"},children:[q.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"12px 16px 12px 24px",cursor:"pointer",backgroundColor:"#2a2a2a",transition:"background-color 0.2s ease",touchAction:"manipulation"},onMouseEnter:N=>{N.currentTarget.style.backgroundColor="#333",o(S)},onMouseLeave:N=>{N.currentTarget.style.backgroundColor="#2a2a2a",c(S)||o(null)},onTouchStart:N=>{N.stopPropagation(),N.currentTarget.style.backgroundColor="#333",o(S)},onTouchEnd:N=>{N.stopPropagation(),N.preventDefault(),N.currentTarget.style.backgroundColor="#2a2a2a",a(S)},onClick:N=>{N.stopPropagation(),a(S)},children:[q.jsx("div",{style:{flex:1,fontSize:I?"12px":"13px",color:"#ddd",lineHeight:1.4,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",userSelect:"text"},children:x}),q.jsx("button",{type:"button","aria-label":R?"Collapse error details":"Expand error details",style:{color:"#888",fontSize:"16px",transform:R?"rotate(0deg)":"rotate(90deg)",transition:"transform 0.2s ease",flexShrink:0,background:"none",border:"none",padding:0,cursor:"pointer"},onMouseDown:N=>N.stopPropagation(),onClick:N=>{N.stopPropagation(),y(S)},onTouchEnd:N=>{N.stopPropagation(),N.preventDefault(),y(S)},children:"›"})]}),R&&q.jsxs("div",{"data-error-id":k,style:{display:"block",padding:"12px 16px 12px 24px",backgroundColor:"#1a1a1a",borderTop:"1px solid #444",position:"relative"},children:[q.jsx("div",{style:{fontSize:I?"11px":"12px",color:"#ccc",lineHeight:1.5,wordWrap:"break-word",overflowWrap:"break-word",hyphens:"auto",userSelect:"text",paddingRight:30},onMouseDown:N=>N.stopPropagation(),onClick:N=>N.stopPropagation(),children:x}),q.jsx(hQo,{errorId:S,errorMessage:x,copiedErrorId:C,onCopy:(N,U)=>{r(N),Q(U),setTimeout(()=>Q(null),2e3)}})]})]},S)})]},w)})})]})},kfI=z.createContext(null),DQo=()=>z.useContext(kfI),seA=j7`
5436
+ `,ZCo=[];function OCo(g){return g.type==="source_component"?g.source_component_id:g.type==="pcb_component"?g.pcb_component_id:"component"}var WCo=({children:g,transform:A=uJ(),elements:I})=>{const e=z.useRef(null),{isShowingDRCErrors:t,hoveredErrorId:o,focusedErrorId:B}=ii(l=>({isShowingDRCErrors:l.is_showing_drc_errors,hoveredErrorId:l.hovered_error_id,focusedErrorId:l.focused_error_id})),C=B??o,Q=I??ZCo,i=z.useMemo(()=>Q.filter(l=>l.type==="pcb_trace_error"&&!l.message?.includes("Multiple components found with name")),[Q]),E=z.useMemo(()=>Q.filter(l=>l.type==="pcb_via_clearance_error"),[Q]),n=z.useMemo(()=>Q.filter(l=>l.type==="pcb_trace_error"&&!!l.message?.includes("Multiple components found with name")),[Q]),s=z.useMemo(()=>x2I(Q),[Q]),r=z.useMemo(()=>K2I(Q,C),[C,Q]),a=z.useMemo(()=>n.map((l,D)=>{const d=("component_name"in l&&typeof l.component_name=="string"?l.component_name:void 0)??l.message?.match(/name "([^"]+)"/)?.[1];return d?{components:Q.filter(w=>w.type==="source_component"&&w.name===d||w.type==="pcb_component"&&Q.some(u=>u.type==="source_component"&&u.source_component_id===w.source_component_id&&u.name===d)),error:l,errorIndex:D}:{components:[],error:l,errorIndex:D}}),[n,Q]);if(!I)return q.jsx("div",{style:{position:"relative"},ref:e,children:g});const c=l=>{const D=eBo({error:l,indexes:s});if(!D||typeof D.x!="number"||typeof D.y!="number")return null;const d=Mt(A,D);return Number.isNaN(d.x)||Number.isNaN(d.y)?null:d};let h=null;return r&&(h=c(r)),q.jsxs("div",{style:{position:"relative"},ref:e,children:[g,i.map((l,D)=>{const d=CZ(l,D),y=C===d;if(!y&&!t)return null;const w=c(l);if(!w)return null;const u=ceg(w,e);return q.jsxs(z.Fragment,{children:[q.jsx(dfI,{errorCenter:w,isHighlighted:y}),q.jsx("div",{style:{position:"absolute",left:w.x-15,top:w.y-15,width:30,height:30,zIndex:da.errorOverlay+5,cursor:"pointer",borderRadius:"50%"},onMouseEnter:G=>{const m=G.currentTarget.nextElementSibling;if(m){const p=m.querySelector(".error-message");p&&(p.style.opacity="1")}},onMouseLeave:G=>{if(!y){const m=G.currentTarget.nextElementSibling;if(m){const p=m.querySelector(".error-message");p&&(p.style.opacity="0")}}}}),q.jsx("div",{style:{position:"absolute",zIndex:y?200:100,left:u.left,top:u.top,color:y?"#ff4444":"red",textAlign:"center",fontFamily:"sans-serif",fontSize:12,display:t||y?"flex":"none",flexDirection:"column",alignItems:"center",pointerEvents:"none",transform:u.transform},children:q.jsx("div",{className:`error-message ${heg}`,style:{opacity:y?1:0,border:`1px solid ${y?"#ff4444":"red"}`},children:l.message})})]},d)}),E.map((l,D)=>{const d=CZ(l,D),y=C===d;if(!y&&!t)return null;const w=c(l);if(!w)return null;const u=ceg({x:w.x,y:w.y},e);return q.jsxs(z.Fragment,{children:[q.jsx(dfI,{errorCenter:w,isHighlighted:y}),q.jsx("div",{style:{position:"absolute",left:w.x-15,top:w.y-15,width:30,height:30,zIndex:da.errorOverlay+5,cursor:"pointer",borderRadius:"50%"},onMouseEnter:G=>{const m=G.currentTarget.nextElementSibling;if(m){const p=m.querySelector(".error-message");p&&(p.style.opacity="1")}},onMouseLeave:G=>{if(!y){const m=G.currentTarget.nextElementSibling;if(m){const p=m.querySelector(".error-message");p&&(p.style.opacity="0")}}}}),q.jsx("div",{style:{position:"absolute",zIndex:y?da.errorOverlay+10:da.errorOverlay+1,left:u.left,top:u.top,color:y?"#ff4444":"red",textAlign:"center",fontFamily:"sans-serif",fontSize:12,display:"flex",flexDirection:"column",alignItems:"center",pointerEvents:"none",transform:u.transform},children:q.jsx("div",{className:`error-message ${heg}`,style:{opacity:y?1:0,border:`1px solid ${y?"#ff4444":"red"}`},children:l.message})})]},d)}),a.map(({components:l,error:D,errorIndex:d})=>{const y=CZ(D,d),w=C===y;return!w&&!t?null:l.map(u=>{let G={x:0,y:0};if(u.type==="pcb_component")G=u.center||{x:0,y:0};else if(u.type==="source_component"){const U=I?.find(K=>K.type==="pcb_component"&&K.source_component_id===u.source_component_id);U&&U.type==="pcb_component"&&(G=U.center||{x:0,y:0})}const m=Mt(A,G);if(Number.isNaN(m.x)||Number.isNaN(m.y))return null;const p=Math.abs(A.a),x=Math.max(8,Math.min(30,.5*p)),N=ceg(m,e);return q.jsxs(z.Fragment,{children:[q.jsx("svg",{style:{position:"absolute",left:0,top:0,pointerEvents:"none",mixBlendMode:"difference",zIndex:da.errorOverlay},width:"100%",height:"100%",children:w?q.jsx("polygon",{points:`${m.x},${m.y-x*1.25} ${m.x+x},${m.y} ${m.x},${m.y+x*1.25} ${m.x-x},${m.y}`,fill:"#ff4444"}):q.jsx("circle",{cx:m.x,cy:m.y,r:x,fill:"none",stroke:w?"#ff4444":"red",strokeWidth:w?Math.max(2,x*.15):Math.max(1,x*.1),opacity:1})}),q.jsx("div",{style:{position:"absolute",left:m.x-(x+10),top:m.y-(x+10),width:(x+10)*2,height:(x+10)*2,zIndex:da.errorOverlay+5,cursor:"pointer",borderRadius:"50%"},onMouseEnter:U=>{const K=U.currentTarget.nextElementSibling;if(K){const _=K.querySelector(".error-message");_&&(_.style.opacity="1")}},onMouseLeave:U=>{if(!w){const K=U.currentTarget.nextElementSibling;if(K){const _=K.querySelector(".error-message");_&&(_.style.opacity="0")}}}}),q.jsx("div",{style:{position:"absolute",zIndex:w?da.errorOverlay+20:da.errorOverlay+10,left:N.left,top:N.top,color:w?"#ff4444":"red",textAlign:"center",fontFamily:"sans-serif",fontSize:12,display:t||w?"flex":"none",flexDirection:"column",alignItems:"center",pointerEvents:"none",transform:N.transform},children:q.jsx("div",{className:`error-message ${heg}`,style:{opacity:w?1:0,border:`1px solid ${w?"#ff4444":"red"}`},children:D.message})})]},`${y}_${u.type}_${OCo(u)}`)})}),h&&q.jsx(TCo,{center:h})]})},yfI=(g,A,I,e)=>{if(I<=0||e<=0)return;const t=g.find(B=>B.type==="pcb_component"&&B.pcb_component_id===A);if(t?.type!=="pcb_component")return;const o=h2I(t);if(o)return{component:t,bounds:o,transform:P2I({bounds:o,width:I,height:e})}},VCo=({focusRequest:g,elements:A,transform:I})=>{const e=g?.pcbComponentId,t=ii(E=>E.selectLayer),o=e?yfI(A,e,1,1):void 0,B=o?.component.layer;if(z.useEffect(()=>{B&&t(B)},[g,B,t]),!o||!I)return null;const{bounds:C}=o,Q=Mt(I,{x:C.minX,y:C.minY}),i=Mt(I,{x:C.maxX,y:C.maxY});return q.jsx("div",{"data-focused-pcb-component-id":e,style:{position:"absolute",left:Math.min(Q.x,i.x)-4,top:Math.min(Q.y,i.y)-4,width:Math.abs(i.x-Q.x)+8,height:Math.abs(i.y-Q.y)+8,border:"2px solid #3399ff",borderRadius:4,boxSizing:"border-box",pointerEvents:"none",zIndex:da.elementOverlay}})};function jCo(g,A){return g.size!==A.size?!1:Array.from(g).every(I=>A.has(I))}var ec={MIN_LINE_LENGTH_FOR_LABEL:40,LABEL_OFFSET_ABOVE:2,LABEL_OFFSET_BELOW:-18,LABEL_OFFSET_RIGHT:8,LABEL_OFFSET_LEFT:-120,Y_LABEL_MIN_WIDTH:110,LINE_STROKE_WIDTH:1.5,LINE_DASH_PATTERN:"4,4",COMPONENT_MARKER_RADIUS:3,LABEL_FONT_SIZE:11,ANCHOR_MARKER_SIZE:6,ANCHOR_MARKER_STROKE_WIDTH:1.5},CS={OFFSET_LINE:"white",COMPONENT_MARKER_FILL:"#66ccff",COMPONENT_MARKER_STROKE:"white",LABEL_TEXT:"white"},leg=({targets:g,transform:A,containerWidth:I,containerHeight:e})=>{if(g.length===0)return null;const t={color:CS.LABEL_TEXT,mixBlendMode:"difference",pointerEvents:"none",fontSize:ec.LABEL_FONT_SIZE,fontFamily:"monospace",fontWeight:"bold"},o=new Map;return g.forEach(B=>{if(!o.has(B.anchor_id)){const C=Mt(A,B.anchor);o.set(B.anchor_id,C)}}),q.jsx("div",{style:{position:"absolute",left:0,top:0,width:I,height:e,overflow:"hidden",pointerEvents:"none",zIndex:da.dimensionOverlay},children:q.jsxs("svg",{style:{position:"absolute",left:0,top:0,pointerEvents:"none"},width:I,height:e,children:[g.map(B=>{const C=B.anchor,Q=B.anchor_id,i=B.target,E=o.get(Q),n=Mt(A,i),s=i.x-C.x,r=i.y-C.y,a=Math.abs(n.x-E.x),c=Math.abs(n.y-E.y),h=n.y<E.y,l=n.x>E.x,D=h?ec.LABEL_OFFSET_ABOVE:ec.LABEL_OFFSET_BELOW,d=l?ec.LABEL_OFFSET_RIGHT:ec.LABEL_OFFSET_LEFT,y=a>ec.MIN_LINE_LENGTH_FOR_LABEL,w=c>ec.MIN_LINE_LENGTH_FOR_LABEL,u=`${B.display_offset_x??s.toFixed(2)}mm`,G=`${B.display_offset_y??r.toFixed(2)}mm`;return q.jsxs("g",{children:[q.jsx("line",{x1:E.x,y1:E.y,x2:n.x,y2:E.y,stroke:CS.OFFSET_LINE,strokeWidth:ec.LINE_STROKE_WIDTH,strokeDasharray:ec.LINE_DASH_PATTERN}),q.jsx("line",{x1:n.x,y1:E.y,x2:n.x,y2:n.y,stroke:CS.OFFSET_LINE,strokeWidth:ec.LINE_STROKE_WIDTH,strokeDasharray:ec.LINE_DASH_PATTERN}),B.type==="component"||B.type==="board"?q.jsx("circle",{cx:n.x,cy:n.y,r:ec.COMPONENT_MARKER_RADIUS,fill:CS.COMPONENT_MARKER_FILL,stroke:CS.COMPONENT_MARKER_STROKE,strokeWidth:1}):q.jsxs(q.Fragment,{children:[q.jsx("line",{x1:n.x-ec.ANCHOR_MARKER_SIZE,y1:n.y,x2:n.x+ec.ANCHOR_MARKER_SIZE,y2:n.y,stroke:CS.OFFSET_LINE,strokeWidth:ec.ANCHOR_MARKER_STROKE_WIDTH}),q.jsx("line",{x1:n.x,y1:n.y-ec.ANCHOR_MARKER_SIZE,x2:n.x,y2:n.y+ec.ANCHOR_MARKER_SIZE,stroke:CS.OFFSET_LINE,strokeWidth:ec.ANCHOR_MARKER_STROKE_WIDTH})]}),y&&q.jsx("foreignObject",{x:Math.min(E.x,n.x),y:E.y+D,width:Math.abs(n.x-E.x),height:20,style:{overflow:"visible"},children:q.jsx("div",{style:{...t,textAlign:"center"},children:u})}),w&&q.jsx("foreignObject",{x:n.x+d,y:Math.min(E.y,n.y),width:ec.Y_LABEL_MIN_WIDTH,height:Math.abs(n.y-E.y),style:{overflow:"visible"},children:q.jsx("div",{style:{...t,display:"flex",alignItems:"center",justifyContent:l?"flex-start":"flex-end",whiteSpace:"nowrap",padding:"0 4px",height:"100%"},children:G})})]},B.id)}),Array.from(o.entries()).map(([B,C])=>q.jsxs("g",{children:[q.jsx("line",{x1:C.x-ec.ANCHOR_MARKER_SIZE,y1:C.y,x2:C.x+ec.ANCHOR_MARKER_SIZE,y2:C.y,stroke:CS.OFFSET_LINE,strokeWidth:ec.ANCHOR_MARKER_STROKE_WIDTH}),q.jsx("line",{x1:C.x,y1:C.y-ec.ANCHOR_MARKER_SIZE,x2:C.x,y2:C.y+ec.ANCHOR_MARKER_SIZE,stroke:CS.OFFSET_LINE,strokeWidth:ec.ANCHOR_MARKER_STROKE_WIDTH})]},`anchor-${B}`))]})})},L3=g=>g?.type==="pcb_component",wfI=g=>g?.type==="pcb_group",zCo=g=>g?.type==="pcb_panel",Deg=g=>g?.type==="pcb_board",XCo=({elements:g,highlightedPrimitives:A,transform:I,containerWidth:e,containerHeight:t})=>{const o=ii(l=>l.is_showing_group_anchor_offsets),B=A.map(l=>L3(l._parent_pcb_component)?l._parent_pcb_component.pcb_component_id:L3(l._element)?l._element.pcb_component_id:null).filter(l=>!!l);if(!o&&B.length===0)return null;const C=g.filter(l=>Deg(l)),Q=g.filter(l=>L3(l)),i=g.filter(l=>wfI(l)),E=new Set;B.forEach(l=>{const D=Q.find(d=>d.pcb_component_id===l);D?.pcb_group_id&&E.add(D.pcb_group_id)});const n=Q.map(l=>{const D=l.positioned_relative_to_pcb_board_id;if(!D)return null;const d=C.find(y=>y.pcb_board_id===D);return d?{component:l,board:d,type:"component"}:null}).filter(l=>!!l),s=i.map(l=>{const D=l.positioned_relative_to_pcb_board_id;if(!D||!l.center)return null;const d=C.find(y=>y.pcb_board_id===D);return d?{group:l,board:d,type:"group"}:null}).filter(l=>!!l),r=[...n,...s];if(r.length===0)return null;const a=B.length===0,c=r.filter(l=>l.type==="component"?a||B.includes(l.component.pcb_component_id):a||E.has(l.group.pcb_group_id));if(c.length===0)return null;const h=c.map(l=>l.type==="component"?{id:`${l.board.pcb_board_id}-${l.component.pcb_component_id}-${l.type}`,anchor:l.board.center,anchor_id:l.board.pcb_board_id,target:l.component.center,type:"component",display_offset_x:l.component.display_offset_x,display_offset_y:l.component.display_offset_y}:{id:`${l.board.pcb_board_id}-${l.group.pcb_group_id}-${l.type}`,anchor:l.board.center,anchor_id:l.board.pcb_board_id,target:{x:l.group.anchor_position?.x??l.group.center.x,y:l.group.anchor_position?.y??l.group.center.y},type:"group",display_offset_x:l.group.display_offset_x,display_offset_y:l.group.display_offset_y}).filter(l=>!!l);return q.jsx(leg,{targets:h,transform:I,containerWidth:e,containerHeight:t})},$Co=({elements:g,highlightedPrimitives:A,transform:I,containerWidth:e,containerHeight:t})=>{const o=ii(l=>l.is_showing_group_anchor_offsets),B=A.map(l=>L3(l._parent_pcb_component)?l._parent_pcb_component.pcb_component_id:L3(l._element)?l._element.pcb_component_id:null).filter(l=>!!l);if(!o&&B.length===0)return null;const C=g.filter(l=>wfI(l)),Q=g.filter(l=>L3(l)),i=(l,D)=>{if(D.has(l))return;D.add(l);const d=C.find(y=>y.pcb_group_id===l);d?.position_mode==="relative_to_group_anchor"&&d.positioned_relative_to_pcb_group_id&&i(d.positioned_relative_to_pcb_group_id,D)},E=new Set;B.forEach(l=>{const D=Q.find(d=>d.pcb_component_id===l);D&&(D.position_mode==="relative_to_group_anchor"&&D.positioned_relative_to_pcb_group_id&&i(D.positioned_relative_to_pcb_group_id,E),D.pcb_group_id&&i(D.pcb_group_id,E))});const n=Q.map(l=>{if(l.position_mode==="relative_to_group_anchor"&&l.positioned_relative_to_pcb_group_id){const D=C.find(d=>d.pcb_group_id===l.positioned_relative_to_pcb_group_id);return D?.anchor_position?{component:l,parentGroup:D,type:"component"}:null}if(l.pcb_group_id){const D=C.find(d=>d.pcb_group_id===l.pcb_group_id);return D?.anchor_position?{component:l,parentGroup:D,type:"component"}:null}return null}).filter(l=>!!l),s=C.map(l=>{if(l.position_mode==="relative_to_group_anchor"&&l.positioned_relative_to_pcb_group_id){const D=C.find(d=>d.pcb_group_id===l.positioned_relative_to_pcb_group_id);if(D?.anchor_position&&l.anchor_position)return{group:l,parentGroup:D,type:"group"}}return null}).filter(l=>!!l),r=[...n,...s];if(r.length===0)return null;const a=B.length===0,c=r.filter(l=>l.type==="component"?a||B.includes(l.component.pcb_component_id):a||E.has(l.group.pcb_group_id)||E.has(l.parentGroup.pcb_group_id));if(c.length===0)return null;const h=c.map(l=>{const D=l.parentGroup.anchor_position;return D?l.type==="component"?l.component.center?{id:`${l.parentGroup.pcb_group_id}-${l.component.pcb_component_id}-${l.type}`,anchor:D,anchor_id:l.parentGroup.pcb_group_id,target:l.component.center,type:"component",display_offset_x:l.component.display_offset_x,display_offset_y:l.component.display_offset_y}:null:l.group.anchor_position?{id:`${l.parentGroup.pcb_group_id}-${l.group.pcb_group_id}-${l.type}`,anchor:D,anchor_id:l.parentGroup.pcb_group_id,target:l.group.anchor_position,type:"group",display_offset_x:l.group.display_offset_x,display_offset_y:l.group.display_offset_y}:null:null}).filter(l=>!!l);return q.jsx(leg,{targets:h,transform:I,containerWidth:e,containerHeight:t})},AQo=(g,A)=>{const I=g.pcb_component_id,e=A.filter(t=>(t.type==="pcb_smtpad"||t.type==="pcb_plated_hole")&&t.pcb_component_id===I||t.type==="pcb_hole"&&t.pcb_component_id===I);return e.length===0?Eeg([g]):Eeg(e)},gQo=({elements:g,highlightedPrimitives:A,transform:I,containerWidth:e,containerHeight:t})=>{const o=new Map;for(const C of A)L3(C._parent_pcb_component)&&o.set(C._parent_pcb_component.pcb_component_id,C._parent_pcb_component),L3(C._element)&&o.set(C._element.pcb_component_id,C._element);if(o.size===0)return null;const B=[];for(const C of o.values()){const Q=AQo(C,g);if(!Q)continue;const i=C.positioned_relative_to_pcb_group_id??C.pcb_group_id,E=i?Y5(g).pcb_group.get(i):null;B.push({component:C,bbox:Q,group:E})}return B.length===0?null:q.jsx("div",{style:{position:"absolute",left:0,top:0,width:e,height:t,overflow:"hidden",pointerEvents:"none",zIndex:da.dimensionOverlay},children:q.jsx("svg",{style:{position:"absolute",left:0,top:0,pointerEvents:"none"},width:e,height:t,children:B.map(({component:C,bbox:Q,group:i})=>{const E=Mt(I,{x:Q.minX,y:Q.maxY}),n=Mt(I,{x:Q.maxX,y:Q.minY}),s={x:Math.min(E.x,n.x),y:Math.min(E.y,n.y),width:Math.abs(n.x-E.x),height:Math.abs(n.y-E.y)},r=C.center??{x:(Q.minX+Q.maxX)/2,y:(Q.minY+Q.maxY)/2},a=Mt(I,r);return q.jsxs("g",{children:[q.jsx("rect",{x:s.x,y:s.y,width:s.width,height:s.height,fill:"none",stroke:"white",strokeWidth:1.5,strokeDasharray:"4,4"}),q.jsx("line",{x1:a.x-6,y1:a.y,x2:a.x+6,y2:a.y,stroke:CS.COMPONENT_MARKER_STROKE,strokeWidth:1.5}),q.jsx("line",{x1:a.x,y1:a.y-6,x2:a.x,y2:a.y+6,stroke:CS.COMPONENT_MARKER_STROKE,strokeWidth:1.5}),q.jsx("circle",{cx:a.x,cy:a.y,r:ec.COMPONENT_MARKER_RADIUS,fill:CS.COMPONENT_MARKER_FILL,stroke:CS.COMPONENT_MARKER_STROKE,strokeWidth:1})]},C.pcb_component_id)})})})},IQo=({elements:g,highlightedPrimitives:A,transform:I,containerWidth:e,containerHeight:t})=>{const o=ii(r=>r.is_showing_group_anchor_offsets),B=A.map(r=>Deg(r._element)?r._element.pcb_board_id:null).filter(r=>!!r);if(!o&&B.length===0)return null;const C=g.filter(r=>zCo(r)),i=g.filter(r=>Deg(r)).map(r=>{const a=r.pcb_panel_id,c=r.position_mode;if(!a||c!=="relative_to_panel_anchor")return null;const h=C.find(l=>l.pcb_panel_id===a);return h?{board:r,panel:h,type:"board"}:null}).filter(r=>!!r);if(i.length===0)return null;const E=B.length===0,n=i.filter(r=>E||B.includes(r.board.pcb_board_id));if(n.length===0)return null;const s=n.map(r=>r.board.center?{id:`${r.panel.pcb_panel_id}-${r.board.pcb_board_id}-${r.type}`,anchor:r.panel.center,anchor_id:r.panel.pcb_panel_id,target:r.board.center,type:"board",display_offset_x:r.board.display_offset_x,display_offset_y:r.board.display_offset_y}:null).filter(r=>!!r);return q.jsx(leg,{targets:s,transform:I,containerWidth:e,containerHeight:t})};function eQo(g){const{primitives:A,is_showing_multiple_traces_length:I,traceOverlayElementIndex:e}=g,t=A.filter(C=>C._element.type==="pcb_trace"),o=A.filter(C=>C._element.type!=="pcb_trace"),B=t.filter(C=>(C._element.source_trace_id?e.sourceTraceById.get(C._element.source_trace_id):void 0)?.max_length!==void 0||aeg({primitiveElement:C._element,traceOverlayElementIndex:e})!==null);if(!I)return[...o,...B];if(t.length>1){const C=t.reduce((Q,i)=>{const E=Q._element.trace_length;return i._element.trace_length<E?i:Q},t[0]);return[...o,C]}return A}var tQo={position:"absolute",left:0,top:0,pointerEvents:"none",color:"red",fontFamily:"sans-serif",fontSize:12,textShadow:"0 0 2px black"},oQo=g=>{const{_element:A,_parent_pcb_component:I,_parent_source_component:e,_source_port:t}=g;switch(A.type){case"pcb_trace":return A.trace_length?`${A.trace_length.toFixed(3)}`:"";case"pcb_smtpad":case"pcb_plated_hole":{const o=[],B=Array.from(new Set((A.port_hints??[]).concat(t?.port_hints??[]))).filter(Q=>!/^[0-9]+$/.test(Q)).filter(Q=>!Q.includes("unnamed_")).sort((Q,i)=>i.localeCompare(Q)),C=e&&"name"in e&&e.name&&!e.name.includes("unnamed_")?e.name:null;return B.length>0?C?o.push(...B.map(Q=>`${C}.${Q}`)):o.push(...B):C&&o.push(C),o.join(", ")}default:return""}},BQo={top:"red",bottom:"aqua"},CQo=({primitive:g,mousePos:A,traceOverlayElementIndex:I})=>{const[e,t]=z.useState(!1),o=g._element;z.useEffect(()=>{setTimeout(()=>{t(!0)},100)},[]);const[B,C,Q,i]=[g.screen_x,g.screen_y,g.screen_w,g.screen_h],E=g.same_space_index??0,n=26,s=BQo[g?._element?.layer]??"red";let r=0;if(o.type==="pcb_smtpad"&&o?.shape==="rotated_rect"?r=o?.ccw_rotation??0:(o.type==="pcb_smtpad"&&(o?.shape==="pill"||o?.shape==="rotated_pill")&&"ccw_rotation"in g||o.type==="pcb_plated_hole"&&(o?.shape==="pill"||o?.shape==="oval")&&"ccw_rotation"in g)&&(r=o.ccw_rotation??0),o.type==="pcb_trace"){const h=_2I({primitiveElement:o,traceOverlayElementIndex:I});return h?q.jsx("div",{style:{zIndex:da.elementOverlay,position:"absolute",left:A.x+12,top:A.y+12,color:s,pointerEvents:"none"},children:q.jsxs("div",{style:{backgroundColor:"#f2efcc",color:h.isOverLength?"red":"black",textShadow:"none",WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale",padding:"4px 6px",borderRadius:"4px",fontSize:"11px",lineHeight:1.2,textAlign:"left",whiteSpace:"nowrap"},children:[h.text&&q.jsx("div",{children:h.text}),h.name&&q.jsx("div",{style:{marginTop:h.text?"2px":0},children:h.name})]})}):null}const a=oQo(g);return a.trim().length===0?null:q.jsx("div",{style:{zIndex:da.elementOverlay,position:"absolute",left:B-Q/2-8,top:C-i/2-8,width:Q+16,height:i+16,color:s,transform:`rotate(${-r}deg)`,transformOrigin:"center center"},children:q.jsx("div",{style:{width:e?`calc(100% + ${n*2*E}px)`:"100%",height:e?`calc(100% + ${n*2*E}px)`:"100%",marginLeft:e?`${-n*E}px`:0,marginTop:e?`${-n*E}px`:0,border:`1px solid ${s}`,opacity:e||E===0?1:0,transition:"width 0.2s, height 0.2s, margin-left 0.2s, margin-top 0.2s, opacity 0.2s"},children:q.jsx("div",{style:{position:"absolute",bottom:i+20+n*E,marginRight:e?`${-n*E}px`:0,marginBottom:e?0:-n*E,transition:"margin-right 0.2s, margin-bottom 0.2s",backgroundColor:"#f2efcc",color:"black",textShadow:"none",WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale",padding:"6px 6px",borderRadius:"6px",fontSize:"14px",transform:`rotate(${r}deg)`,minWidth:"45px",textAlign:"center"},children:a})})})},QQo=({highlightedPrimitives:g,mousePos:A,elements:I})=>{const[e,t]=ii(Q=>[Q.is_moving_component,Q.is_showing_multiple_traces_length]),o=z.useMemo(()=>Y2I(I),[I]),B=g.some(Q=>Q._element.type==="pcb_smtpad")&&g.some(Q=>Q._element.type==="pcb_trace");let C=g;return B&&(C=C.filter(Q=>Q._element.type==="pcb_smtpad")),C=eQo({primitives:C,is_showing_multiple_traces_length:t,traceOverlayElementIndex:o}),q.jsx("div",{style:tQo,children:!e&&C.map(Q=>q.jsx(CQo,{primitive:Q,mousePos:A,traceOverlayElementIndex:o},Q._pcb_drawing_object_id))})},jwA=g=>{if(g.length===0)return null;let A=g[0].x,I=g[0].y,e=g[0].x,t=g[0].y;for(const o of g)o.x<A&&(A=o.x),o.y<I&&(I=o.y),o.x>e&&(e=o.x),o.y>t&&(t=o.y);return{center:{x:(A+e)/2,y:(I+t)/2},width:e-A,height:t-I}},ufI=(g,A)=>{if(A.length<3)return!1;let I=!1;for(let e=0,t=A.length-1;e<A.length;t=e++){const o=A[e].x,B=A[e].y,C=A[t].x,Q=A[t].y;B>g.y!=Q>g.y&&g.x<(C-o)*(g.y-B)/(Q-B||Number.EPSILON)+o&&(I=!I)}return I},deg=({includeHiddenTraces:g=!1,primitives:A,rwPoint:I,selectedLayer:e,transform:t})=>{const o=[];for(const B of A){if(!B._element||!g&&B._element.type==="pcb_trace"&&B.layer!==e)continue;if("x1"in B&&B._element?.type==="pcb_trace"){const i=rh({x:I.x,y:I.y},{x:B.x1,y:B.y1},{x:B.x2,y:B.y2}),E=B.width||.5,n=Math.max(E*25,2)/t.a;i<n&&o.push(B);continue}if(B.pcb_drawing_type==="polygon"){const i=B.points.map(n=>({x:sg.parse(n.x),y:sg.parse(n.y)})),E=jwA(i);if(!E||I.x<E.center.x-E.width/2||I.x>E.center.x+E.width/2||I.y<E.center.y-E.height/2||I.y>E.center.y+E.height/2)continue;ufI(I,i)&&o.push(B);continue}if(B.pcb_drawing_type==="polygon_with_arcs"){const i=B.brep_shape.outer_ring.vertices.map(n=>({x:sg.parse(n.x),y:sg.parse(n.y)})),E=jwA(i);if(!E||I.x<E.center.x-E.width/2||I.x>E.center.x+E.width/2||I.y<E.center.y-E.height/2||I.y>E.center.y+E.height/2)continue;ufI(I,i)&&o.push(B);continue}if(!("x"in B&&"y"in B))continue;let C=0,Q=0;if("w"in B&&"h"in B)C=B.w,Q=B.h;else if("r"in B)C=B.r*2,Q=B.r*2;else if("rX"in B&&"rY"in B)C=B.rX*2,Q=B.rY*2;else continue;Math.abs(B.x-I.x)<C/2&&Math.abs(B.y-I.y)<Q/2&&o.push(B)}return o},iQo=({elements:g,children:A,transform:I,primitives:e,selectedLayer:t,onMouseHoverOverPrimitives:o})=>{const[B,C]=z.useState([]),[Q,i]=z.useState({x:0,y:0}),[E,{width:n,height:s}]=QeA(),r=z.useMemo(()=>R2I(e),[e]);z.useEffect(()=>{C([]),o([])},[t,e,o]);const a=z.useMemo(()=>{const h=[];for(const l of B){if(l._element?.type==="pcb_via"||l._element?.type==="pcb_component"||l?.layer==="drill"||l?.is_hoverable===!1)continue;let D=null,d=0,y=0;if(l.pcb_drawing_type==="polygon"){const m=jwA(l.points);if(!m)continue;D=m.center,d=m.width,y=m.height}else if(l.pcb_drawing_type==="polygon_with_arcs"){const m=l.brep_shape.outer_ring.vertices.map(k=>({x:k.x,y:k.y})),p=jwA(m);if(!p)continue;D=p.center,d=p.width,y=p.height}else l.pcb_drawing_type==="line"?(D={x:(l.x1+l.x2)/2,y:(l.y1+l.y2)/2},d=Math.abs(l.x2-l.x1),y=Math.abs(l.y2-l.y1)):"x"in l&&"y"in l&&(D={x:l.x,y:l.y},d="w"in l?l.w:"r"in l?l.r*2:"rX"in l&&"rY"in l?l.rX*2:0,y="h"in l?l.h:"r"in l?l.r*2:"rX"in l&&"rY"in l?l.rY*2:0);if(!D)continue;const w=Mt(I,D),u={w:d*I.a,h:y*I.a},G=h.filter(m=>w.x===m.screen_x&&w.y===m.screen_y&&u.w===m.screen_w&&u.h===m.screen_h).length;h.push({...l,x:D.x,y:D.y,w:d,h:y,screen_x:w.x,screen_y:w.y,screen_w:u.w,screen_h:u.h,same_space_index:G})}return h},[B,I]),c=({screenPoint:h,transform:l})=>{const{x:D,y:d}=h;i({x:D,y:d});const y=Mt(Nx(l),{x:D,y:d}),w=N2I({point:y,realToScreenScale:l.a,spatialIndex:r}),u=deg({primitives:w,rwPoint:y,selectedLayer:t,transform:l});jCo(new Set(u.map(G=>G._pcb_drawing_object_id)),new Set(B.map(G=>G._pcb_drawing_object_id)))||(C(u),o(u))};return q.jsxs("div",{ref:E,style:{position:"relative",width:"100%",height:"100%"},onMouseMove:h=>{if(h.buttons===0&&I){const l=h.currentTarget.getBoundingClientRect(),D=h.clientX-l.left,d=h.clientY-l.top;c({screenPoint:{x:D,y:d},transform:I})}},onTouchStart:h=>{if(I){const l=h.touches[0],D=h.currentTarget.getBoundingClientRect(),d=l.clientX-D.left,y=l.clientY-D.top;c({screenPoint:{x:d,y},transform:I})}},children:[A,q.jsx(QQo,{elements:g,mousePos:Q,highlightedPrimitives:a}),I&&q.jsxs(q.Fragment,{children:[q.jsx(XCo,{elements:g,highlightedPrimitives:a,transform:I,containerWidth:n,containerHeight:s}),q.jsx($Co,{elements:g,highlightedPrimitives:a,transform:I,containerWidth:n,containerHeight:s}),q.jsx(gQo,{elements:g,highlightedPrimitives:a,transform:I,containerWidth:n,containerHeight:s}),q.jsx(IQo,{elements:g,highlightedPrimitives:a,transform:I,containerWidth:n,containerHeight:s})]})]})},GfI=["rgb(255, 100, 100)","rgb(100, 255, 100)","rgb(100, 100, 255)","rgb(255, 255, 100)","rgb(255, 100, 255)","rgb(100, 255, 255)","rgb(255, 150, 100)","rgb(150, 100, 255)","rgb(100, 255, 150)","rgb(255, 100, 150)"];function mfI(g){if("parent_source_group_id"in g)return typeof g.parent_source_group_id=="string"?g.parent_source_group_id:void 0}function yeg(g,A){const I=[],e=A.get(g)??[];for(const t of e)I.push(t),I.push(...yeg(t,A));return I}function pfI(g,A){const I=A.get(g);if(!I)return 0;const e=mfI(I);return e?1+pfI(e,A):0}var EQo=({children:g,transform:A=uJ(),elements:I=[],hoveredComponentIds:e=[]})=>{const[t,{width:o,height:B}]=QeA(),C=z.useRef(null),{is_showing_pcb_groups:Q,pcb_group_view_mode:i,is_showing_group_anchor_offsets:E}=ii(a=>({is_showing_pcb_groups:a.is_showing_pcb_groups,pcb_group_view_mode:a.pcb_group_view_mode,is_showing_group_anchor_offsets:a.is_showing_group_anchor_offsets})),{pcbComponents:n,pcbGroups:s,sourceGroups:r}=z.useMemo(()=>{const a=[],c=[],h=[];for(const l of I)l.type==="pcb_component"?a.push(l):l.type==="pcb_group"?c.push(l):l.type==="source_group"&&h.push(l);return{pcbComponents:a,pcbGroups:c,sourceGroups:h}},[I]);return z.useEffect(()=>{const a=C.current;if(!a||!o||!B)return;a.width=o,a.height=B;const c=a.getContext("2d");if(!c||(c.clearRect(0,0,o,B),!Q))return;const h=new Map(r.map(y=>[y.source_group_id,y])),l=s.filter(y=>{if(y.name?.toLowerCase().includes("subpanel"))return!1;if(i==="all")return!0;if(!y.source_group_id)return!1;const w=h.get(y.source_group_id);return w?w.was_automatically_named!==!0:!1}),D=new Map;r.forEach(y=>{const w=mfI(y);if(w){const u=D.get(w)??[];u.push(y.source_group_id),D.set(w,u)}});const d=new Set;if(e.length>0)for(const y of n){if(!e.includes(y.pcb_component_id))continue;const w=y.positioned_relative_to_pcb_group_id??y.pcb_group_id;w&&d.add(w)}l.forEach((y,w)=>{let u=n.filter(xA=>xA.pcb_group_id===y.pcb_group_id);if(y.source_group_id){const xA=yeg(y.source_group_id,D),RA=s.filter(NA=>NA.source_group_id&&xA.includes(NA.source_group_id));for(const NA of RA){const YA=n.filter(PA=>PA.pcb_group_id===NA.pcb_group_id);u=[...u,...YA]}}let G,m,p,k,S=!1;if(y.center&&y.width&&y.height){S=!0;const xA=y.width/2,RA=y.height/2;G=y.center.x-xA,p=y.center.x+xA,m=y.center.y-RA,k=y.center.y+RA}else if(u.length===0||(G=1/0,m=1/0,p=-1/0,k=-1/0,u.forEach(xA=>{if(xA.center&&typeof xA.width=="number"&&typeof xA.height=="number"){const RA=xA.center.x-xA.width/2,NA=xA.center.x+xA.width/2,YA=xA.center.y+xA.height/2,PA=xA.center.y-xA.height/2;G=Math.min(G,RA),p=Math.max(p,NA),m=Math.min(m,PA),k=Math.max(k,YA)}}),G===1/0||p===-1/0))return;const R=y.source_group_id?pfI(y.source_group_id,h):0,x=y.source_group_id?yeg(y.source_group_id,D).length>0:!1;if(!S){const NA=1+(x?.5:0);G-=NA,p+=NA,m-=NA,k+=NA}const N=Mt(A,{x:G,y:k}),U=Mt(A,{x:p,y:k}),K=Mt(A,{x:G,y:m}),_=Mt(A,{x:p,y:m}),b=GfI[w%GfI.length];c.strokeStyle=b,c.lineWidth=2;const T=Math.max(4,Math.min(12,8*Math.abs(A.a))),j=Math.max(2,Math.min(6,4*Math.abs(A.a))),O=T*(x?1.3:1),gA=j;c.setLineDash([O,gA]),c.beginPath(),c.moveTo(N.x,N.y),c.lineTo(U.x,U.y),c.lineTo(_.x,_.y),c.lineTo(K.x,K.y),c.closePath(),c.stroke();const tA=Math.max(8,Math.min(12,10*Math.abs(A.a))),IA=R===0||R===1?0:R*.11,QA=tA*(1-IA),nA=4,DA=y.name||`Group ${w+1}`;c.font=`${QA}px sans-serif`,c.setLineDash([]);const hA=c.measureText(DA).width+nA*2,sA=QA+nA*2,cA=N.x-5,SA=N.y-5,FA=3;if(c.fillStyle="rgba(0, 0, 0, 0.8)",c.beginPath(),c.roundRect(cA,SA-sA,hA,sA,FA),c.fill(),c.fillStyle=b,c.textAlign="left",c.textBaseline="middle",c.fillText(DA,cA+nA,SA-sA/2),E&&d.has(y.pcb_group_id)&&!!y.anchor_position&&y.anchor_position){const xA=Array.isArray(y.anchor_position)?{x:y.anchor_position[0]??0,y:y.anchor_position[1]??0}:{x:y.anchor_position.x,y:y.anchor_position.y},RA=Mt(A,xA);c.strokeStyle="white",c.lineWidth=1.5,c.setLineDash([]);const NA=Math.max(4,Math.min(8,6*Math.abs(A.a)));c.beginPath(),c.moveTo(RA.x-NA,RA.y),c.lineTo(RA.x+NA,RA.y),c.stroke(),c.beginPath(),c.moveTo(RA.x,RA.y-NA),c.lineTo(RA.x,RA.y+NA),c.stroke()}})},[B,Q,E,e,n,s,i,r,A,o]),q.jsxs("div",{ref:t,style:{position:"relative",width:"100%",height:"100%"},children:[g,q.jsx("canvas",{ref:C,style:{position:"absolute",top:0,left:0,pointerEvents:"none",zIndex:da.pcbGroupOverlay,display:Q?"block":"none"}})]})},nQo=({transform:g,soup:A,connectivityMap:I,children:e})=>{const t=ii(Q=>Q.is_showing_rats_nest),{netMap:o,idToNetMap:B}=I,C=z.useMemo(()=>{if(!A||!t)return[];const Q=r=>{const a=Y5(A)[r.replace(/_\d+$/,"")].get(r);return a&&"x"in a&&"y"in a?{x:a.x,y:a.y}:null},i=(r,a)=>{const c=o[a]||[];let h=null,l=1/0;return c.forEach(D=>{const d=Q(D);if(d){const y=Math.sqrt((r.x-d.x)**2+(r.y-d.y)**2);y<l&&y>0&&(l=y,h=d)}}),h},E=Y5(A).pcb_port.list(),n=Y5(A).source_trace.list(),s=[];return E.forEach((r,a)=>{const c=B[r.pcb_port_id];let h=!1;for(const d of n)d.connected_source_port_ids.includes(r.source_port_id)&&d.connected_source_net_ids.length>0&&(h=!0);if(!c)return;const l={x:r.x,y:r.y},D=i(l,c);D&&s.push({key:`${r.pcb_port_id}-${a}`,startPoint:l,endPoint:D,isInNet:h})}),s},[A,o,B,t]);return!A||!t?e:(g||(g=uJ()),q.jsxs("div",{style:{position:"relative"},children:[e,q.jsx("svg",{style:{position:"absolute",left:0,top:0,width:"100%",height:"100%",pointerEvents:"none",opacity:.5,zIndex:da.ratsNestOverlay},children:C.map(({key:Q,startPoint:i,endPoint:E,isInNet:n})=>{const s=Mt(g,i),r=Mt(g,E);return q.jsx("line",{x1:s.x,y1:s.y,x2:r.x,y2:r.y,stroke:"white",strokeWidth:"1",strokeDasharray:n?"6,6":void 0},Q)})})]}))},Yx=(g,A,I)=>{const e=ii(B=>B.is_mouse_over_container),t=z.useRef(e),o=z.useRef(A);z.useEffect(()=>{t.current=e},[e]),z.useEffect(()=>{o.current=A},[A]),z.useEffect(()=>{if(!g)return;const B=C=>{const Q=C.target;if(Q.tagName==="INPUT"||Q.tagName==="TEXTAREA"||Q.isContentEditable)return;const i=g.split("+"),E=i.includes("ctrl"),n=i.includes("shift"),s=i.includes("alt"),r=i.includes("meta"),a=i[i.length-1],c=I?.current?I.current.contains(document.activeElement)||document.activeElement===I.current:!1;(t.current||c)&&(!E||C.ctrlKey)&&(!n||C.shiftKey)&&(!s||C.altKey)&&(!r||C.metaKey)&&C.key.toLowerCase()===a.toLowerCase()&&(C.preventDefault(),o.current())};return window.addEventListener("keydown",B),()=>{window.removeEventListener("keydown",B)}},[g])},sQo=()=>{const[g,A]=z.useState(!1);return z.useEffect(()=>{const I=()=>{A(window.innerWidth<=768)};return I(),window.addEventListener("resize",I),()=>window.removeEventListener("resize",I)},[]),g},neA=(g,A={stopPropagation:!0})=>{const I=z.useRef(0),e=z.useCallback(B=>{A.stopPropagation&&B.stopPropagation();const C=Date.now();C-I.current<300||(I.current=C,g?.(B))},[g,A.stopPropagation]),t=z.useCallback(B=>{B.preventDefault(),e(B)},[e]);return{onClick:e,onTouchEnd:t,style:{touchAction:"manipulation"}}},aQo={version:"1.11.431"},iZ=({children:g,isSmallScreen:A,onClick:I,...e})=>{const{style:t,...o}=neA(I);return q.jsx("div",{...e,...o,style:{backgroundColor:"#1F1F1F",border:"1px solid #666",margin:0,padding:4,paddingLeft:A?8:6,paddingRight:A?8:6,borderRadius:2,color:"#eee",cursor:"pointer",fontSize:12,height:"fit-content",userSelect:"none",whiteSpace:"nowrap",...t,...e.style},children:g})},rQo=g=>{const A=new Map;return g.forEach((I,e)=>{const t=I.error_type||"unknown_error",o=A.get(t)||[];o.push({error:I,index:e,errorId:CZ(I,e)}),A.set(t,o)}),Array.from(A.entries()).map(([I,e])=>({errorType:I,errors:e}))},cQo=({onClose:g,setHoveredErrorId:A,setFocusedErrorId:I,highlightDurationMs:e=3e3})=>{const t=z.useRef(null),o=z.useRef(null),B=z.useRef(null),C=z.useCallback(()=>{t.current!==null&&(window.clearTimeout(t.current),t.current=null),o.current!==null&&(window.cancelAnimationFrame(o.current),o.current=null)},[]);z.useEffect(()=>C,[C]);const Q=z.useCallback(E=>{C(),B.current=E,A(E),I(null),o.current=window.requestAnimationFrame(()=>{I(E),o.current=null}),g(),t.current=window.setTimeout(()=>{B.current=null,A(null),I(null),t.current=null},e)},[C,e,g,I,A]),i=z.useCallback(E=>B.current===E,[]);return{handleErrorSelect:Q,isSelectedError:i}},hQo=({errorId:g,errorMessage:A,copiedErrorId:I,onCopy:e})=>{const{style:t,...o}=neA(()=>e(A,g));return q.jsx("button",{type:"button","aria-label":I===g?"Error message copied":"Copy error message",style:{position:"absolute",top:12,right:16,cursor:"pointer",color:"#888",fontSize:16,background:"none",border:"none",padding:0,display:"flex",alignItems:"center",...t},...o,children:I===g?q.jsx("span",{style:{color:"#4caf50",fontSize:12},children:"Copied!"}):q.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",children:q.jsx("path",{d:"M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"})})})},lQo=({elements:g,isOpen:A,isSmallScreen:I,onToggle:e,onClose:t,setHoveredErrorId:o,setFocusedErrorId:B})=>{const[C,Q]=z.useState(null),[i,E]=z.useState(new Set),[n,s]=z.useState(new Set),[,r]=Goo(),{handleErrorSelect:a,isSelectedError:c}=cQo({onClose:t,setHoveredErrorId:o,setFocusedErrorId:B}),h=z.useMemo(()=>g?.filter(w=>w.type.includes("error"))??[],[g]),l=h.length,D=z.useMemo(()=>rQo(h),[h]),d=z.useCallback(w=>{E(u=>{const G=new Set(u);return G.has(w)?G.delete(w):G.add(w),G})},[]),y=z.useCallback(w=>{s(u=>{const G=new Set(u);return G.has(w)?G.delete(w):G.add(w),G})},[]);return q.jsxs("div",{style:{position:"relative"},children:[q.jsx(iZ,{isSmallScreen:I,style:l>0?{color:"red"}:void 0,onClick:e,children:q.jsxs("div",{children:[l," errors"]})}),A&&l>0&&q.jsx("div",{style:{position:"absolute",top:"100%",left:0,backgroundColor:"#2a2a2a",border:"1px solid #666",borderRadius:4,marginTop:4,zIndex:1e3,minWidth:I?"280px":"400px",maxWidth:I?"90vw":"600px",maxHeight:"400px",overflow:"auto",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.3)"},children:D.map(({errorType:w,errors:u},G)=>{const m=i.has(w);return q.jsxs("div",{style:{borderBottom:G<D.length-1?"1px solid #444":"none"},children:[q.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",cursor:"pointer",backgroundColor:"#232323",transition:"background-color 0.2s ease",touchAction:"manipulation",position:"sticky",top:0,zIndex:1},onMouseEnter:p=>{p.currentTarget.style.backgroundColor="#303030"},onMouseLeave:p=>{p.currentTarget.style.backgroundColor="#232323"},onTouchStart:p=>{p.stopPropagation(),p.currentTarget.style.backgroundColor="#303030"},onTouchEnd:p=>{p.stopPropagation(),p.preventDefault(),p.currentTarget.style.backgroundColor="#232323",d(w)},onClick:p=>{p.stopPropagation(),d(w)},children:[q.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,color:"#ff6b6b"},children:[q.jsx("div",{style:{color:"#888",fontSize:"16px",transform:m?"rotate(90deg)":"rotate(0deg)",transition:"transform 0.2s ease",flexShrink:0},children:"›"}),q.jsx("div",{style:{fontWeight:"bold",fontSize:I?"12px":"13px"},children:w})]}),q.jsx("div",{style:{fontSize:I?"12px":"13px",color:"#aaa",whiteSpace:"nowrap",marginLeft:12},children:u.length})]}),!m&&u.map(({error:p,index:k,errorId:S})=>{const R=n.has(S),x=p.message??"No error message";return q.jsxs("div",{style:{borderTop:"1px solid #3a3a3a"},children:[q.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"12px 16px 12px 24px",cursor:"pointer",backgroundColor:"#2a2a2a",transition:"background-color 0.2s ease",touchAction:"manipulation"},onMouseEnter:N=>{N.currentTarget.style.backgroundColor="#333",o(S)},onMouseLeave:N=>{N.currentTarget.style.backgroundColor="#2a2a2a",c(S)||o(null)},onTouchStart:N=>{N.stopPropagation(),N.currentTarget.style.backgroundColor="#333",o(S)},onTouchEnd:N=>{N.stopPropagation(),N.preventDefault(),N.currentTarget.style.backgroundColor="#2a2a2a",a(S)},onClick:N=>{N.stopPropagation(),a(S)},children:[q.jsx("div",{style:{flex:1,fontSize:I?"12px":"13px",color:"#ddd",lineHeight:1.4,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",userSelect:"text"},children:x}),q.jsx("button",{type:"button","aria-label":R?"Collapse error details":"Expand error details",style:{color:"#888",fontSize:"16px",transform:R?"rotate(0deg)":"rotate(90deg)",transition:"transform 0.2s ease",flexShrink:0,background:"none",border:"none",padding:0,cursor:"pointer"},onMouseDown:N=>N.stopPropagation(),onClick:N=>{N.stopPropagation(),y(S)},onTouchEnd:N=>{N.stopPropagation(),N.preventDefault(),y(S)},children:"›"})]}),R&&q.jsxs("div",{"data-error-id":k,style:{display:"block",padding:"12px 16px 12px 24px",backgroundColor:"#1a1a1a",borderTop:"1px solid #444",position:"relative"},children:[q.jsx("div",{style:{fontSize:I?"11px":"12px",color:"#ccc",lineHeight:1.5,wordWrap:"break-word",overflowWrap:"break-word",hyphens:"auto",userSelect:"text",paddingRight:30},onMouseDown:N=>N.stopPropagation(),onClick:N=>N.stopPropagation(),children:x}),q.jsx(hQo,{errorId:S,errorMessage:x,copiedErrorId:C,onCopy:(N,U)=>{r(N),Q(U),setTimeout(()=>Q(null),2e3)}})]})]},S)})]},w)})})]})},kfI=z.createContext(null),DQo=()=>z.useContext(kfI),seA=j7`
5437
5437
  background: #222;
5438
5438
  color: #eee;
5439
5439
  border: 1px solid #555;
@@ -5665,7 +5665,7 @@ test("${i} should solve problem correctly", () => {
5665
5665
  // Add more specific assertions based on expected output
5666
5666
  // expect(solver.netLabelPlacementSolver!.netLabelPlacements).toMatchInlineSnapshot()
5667
5667
  })
5668
- `,n=new Blob([E],{type:"text/plain"}),s=URL.createObjectURL(n),r=document.createElement("a");r.href=s,r.download=`${i}.test.ts`,r.click(),URL.revokeObjectURL(s)}catch(Q){alert(`Error generating test.ts for ${g.getSolverName()}: ${Q instanceof Error?Q.message:String(Q)}`)}e(!1)};return q.jsxs("div",{className:`relative ${A}`,ref:t,children:[q.jsx("button",{className:"px-2 py-1 rounded text-xs cursor-pointer",onClick:()=>e(!I),title:`Download options for ${g.getSolverName()}`,children:g.getSolverName()}),I&&q.jsxs("div",{className:"absolute top-full left-0 mt-1 bg-white border border-gray-300 rounded shadow-lg z-10 min-w-[150px]",children:[q.jsx("button",{className:"w-full text-left px-3 py-2 hover:bg-gray-100 text-xs",onClick:o,children:"Download JSON"}),q.jsx("button",{className:"w-full text-left px-3 py-2 hover:bg-gray-100 text-xs",onClick:B,children:"Download page.tsx"}),q.jsx("button",{className:"w-full text-left px-3 py-2 hover:bg-gray-100 text-xs",onClick:C,children:"Download test.ts"})]})]})},HxI=g=>g.activeSubSolver?[g,...HxI(g.activeSubSolver)]:[g],kdo=({solver:g})=>{const A=HxI(g);return q.jsx("div",{className:"flex gap-1 items-center text-sm pt-1",children:A.map((I,e)=>q.jsxs("div",{className:"flex items-center",children:[e>0&&q.jsx("span",{className:"text-gray-400 mx-1",children:"→"}),q.jsx(pdo,{solver:I})]},I.getSolverName()))})},Mdo=({solver:g,triggerRender:A,animationSpeed:I=25,renderer:e,onRendererChange:t,onAnimationSpeedChange:o,onDownloadVisualization:B,onSolverStarted:C,onSolverCompleted:Q})=>{const[i,E]=z.useReducer(m=>!m,!1),n=z.useRef(void 0),s=z.useRef(null),r="solver-debugger-last-iteration",[a,c]=z.useState(null),h=z.useRef(null),l=z.useMemo(()=>[{label:"Slow",value:250,description:"250ms"},{label:"Normal",value:100,description:"100ms"},{label:"Fast",value:10,description:"10ms"},{label:"Fast (2x)",value:5,description:"5ms"},{label:"Fast (10x)",value:1,description:"1ms"},{label:"Fast 20x",value:.5,description:"2 steps / 1ms"},{label:"Fast 100x",value:.1,description:"10 steps / 1ms"}],[]),D=()=>{const m=Math.max(1,I),p=I<1?Math.round(1/I):1;n.current=setInterval(()=>{if(g.solved||g.failed){n.current&&(clearInterval(n.current),n.current=void 0),E(),A(),Q&&g.solved&&Q(g);return}for(let k=0;k<p&&!(g.solved||g.failed);k++)g.step();A()},m)},d=()=>{n.current&&(clearInterval(n.current),n.current=void 0)},y=()=>{!g.solved&&!g.failed&&(g.step(),A())},w=()=>{!g.solved&&!g.failed&&(C&&C(g),g.solve(),A(),Q&&Q(g))},u=()=>{i?(d(),E()):(E(),D())},G=()=>{if(g.solved||g.failed||i)return;s.current===null&&typeof window<"u"&&(s.current=window.localStorage.getItem(r));const m=window.prompt("Step until which iteration?",s.current??`${g.iterations}`);if(m===null)return;s.current=m,typeof window<"u"&&window.localStorage.setItem(r,m);const p=Number(m);if(!Number.isFinite(p)){window.alert("Please enter a valid number for the iteration");return}for(;g.iterations<p&&!g.solved&&!g.failed;)g.step();A(),g.solved&&Q&&Q(g)};return z.useEffect(()=>()=>{d()},[]),z.useEffect(()=>{(g.solved||g.failed)&&i&&(d(),E())},[g.solved,g.failed,i]),z.useEffect(()=>{i&&(d(),D())},[I,i]),z.useEffect(()=>{if(typeof document>"u")return;const m=p=>{h.current&&!h.current.contains(p.target)&&c(null)};return document.addEventListener("mousedown",m),()=>{document.removeEventListener("mousedown",m)}},[]),q.jsxs("div",{className:"space-y-2 p-2 border-b",children:[q.jsx("div",{className:"flex items-center",children:q.jsxs("div",{className:"flex items-center gap-2",ref:h,children:[q.jsxs("div",{className:"flex h-9 items-center space-x-1 rounded-md border border-slate-200 bg-white p-1 shadow-sm",children:[q.jsxs("div",{className:"relative",children:[q.jsx("button",{type:"button",onClick:()=>c(a==="renderer"?null:"renderer"),className:"flex select-none items-center rounded-sm px-3 py-1 text-sm font-medium outline-none focus:bg-slate-100 data-[state=open]:bg-slate-100","data-state":a==="renderer"?"open":"closed",children:"Renderer"}),a==="renderer"&&q.jsx("div",{className:"absolute left-0 z-50 mt-1 min-w-[10rem] rounded-md border border-slate-200 bg-white p-1 text-slate-950 shadow-md",children:["vector","canvas"].map(m=>q.jsxs("button",{type:"button",onClick:()=>{t(m),c(null)},className:"flex w-full items-center rounded-sm px-2 py-1.5 text-sm hover:bg-slate-100",children:[m==="vector"?"Vector":"Canvas",e===m&&q.jsx("span",{className:"ml-auto text-xs text-slate-500",children:"✓"})]},m))})]}),q.jsxs("div",{className:"relative",children:[q.jsx("button",{type:"button",onClick:()=>c(a==="debug"?null:"debug"),className:"flex select-none items-center rounded-sm px-3 py-1 text-sm font-medium outline-none focus:bg-slate-100 data-[state=open]:bg-slate-100","data-state":a==="debug"?"open":"closed",children:"Debug"}),a==="debug"&&q.jsx("div",{className:"absolute left-0 z-50 mt-1 min-w-[12rem] rounded-md border border-slate-200 bg-white p-1 text-slate-950 shadow-md",children:q.jsx("button",{type:"button",onClick:()=>{B(),c(null)},className:"flex w-full items-center rounded-sm px-2 py-1.5 text-sm hover:bg-slate-100",children:"Download Visualization"})})]}),q.jsxs("div",{className:"relative",children:[q.jsx("button",{type:"button",onClick:()=>c(a==="animation"?null:"animation"),className:"flex select-none items-center rounded-sm px-3 py-1 text-sm font-medium outline-none focus:bg-slate-100 data-[state=open]:bg-slate-100","data-state":a==="animation"?"open":"closed",children:"Animation"}),a==="animation"&&q.jsx("div",{className:"absolute left-0 z-50 mt-1 min-w-[12rem] rounded-md border border-slate-200 bg-white p-1 text-slate-950 shadow-md",children:l.map(m=>q.jsxs("button",{type:"button",onClick:()=>{o(m.value),c(null)},className:"flex w-full items-center rounded-sm px-2 py-1.5 text-sm hover:bg-slate-100",children:[m.label,q.jsx("span",{className:"ml-auto text-xs text-slate-500",children:m.description}),I===m.value&&q.jsx("span",{className:"ml-2 text-xs text-slate-500",children:"✓"})]},m.value))})]})]}),q.jsx(kdo,{solver:g})]})}),q.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[q.jsx("button",{onClick:y,disabled:g.solved||g.failed||i,className:"bg-blue-500 hover:bg-blue-600 disabled:bg-gray-300 text-white px-3 py-1 rounded text-sm",children:"Step"}),q.jsx("button",{onClick:w,disabled:g.solved||g.failed||i,className:"bg-green-500 hover:bg-green-600 disabled:bg-gray-300 text-white px-3 py-1 rounded text-sm",children:"Solve"}),q.jsx("button",{onClick:u,disabled:g.solved||g.failed,className:`px-3 py-1 rounded text-white text-sm ${i?"bg-red-500 hover:bg-red-600":"bg-yellow-500 hover:bg-yellow-600"} disabled:bg-gray-300`,children:i?"Stop":"Animate"}),q.jsx("button",{onClick:G,disabled:g.solved||g.failed||i,className:"bg-orange-500 hover:bg-orange-600 disabled:bg-gray-300 text-white px-3 py-1 rounded text-sm",children:"Step Until Iteration"}),q.jsxs("div",{className:"text-sm text-gray-600",children:["Iterations: ",g.iterations]}),g.timeToSolve!==void 0&&q.jsxs("div",{className:"text-sm text-gray-600",children:["Time: ",(g.timeToSolve/1e3).toFixed(3),"s"]}),g.solved&&q.jsx("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded text-sm",children:"Solved"}),g.failed&&q.jsx("div",{className:"px-2 py-1 bg-red-100 text-red-800 rounded text-sm",children:"Failed"})]}),g.error&&q.jsxs("div",{className:"text-red-600 text-sm",children:["Error: ",g.error]})]})},Sdo=g=>g!==null&&"pipelineDef"in g&&Array.isArray(g.pipelineDef),fdo=(g,A,I)=>{const e=g.currentPipelineStageIndex;return A<e?"Completed":A===e&&g.activeSubSolver?g.activeSubSolver.failed?"Failed":"In Progress":"Not Started"},Rdo=(g,A)=>{const e=g.pipelineDef[A].solverName,t=fdo(g,A),o=g[e],B=g.firstIterationOfStage?.[e]??(A===g.currentPipelineStageIndex?g.iterations:null),C=g.iterations;let Q=0;if(t==="Completed"){const s=g.pipelineDef[A+1],r=s?g.firstIterationOfStage?.[s.solverName]:void 0;r!==void 0&&B!==null?Q=r-B:B!==null&&(Q=C-B)}else t==="In Progress"&&B!==null&&(Q=C-B);const i=g.timeSpentOnStage?.[e]??0;let E=0;t==="Completed"?E=1:t==="In Progress"&&o&&(E=o.progress??0);const n=o?.stats??null;return{index:A,name:e,status:t,firstIteration:B,iterations:Q,progress:E,timeSpent:i,stats:n&&Object.keys(n).length>0?n:null,solverInstance:o??null}},Ndo=({status:g})=>{const A={"Not Started":"text-blue-600","In Progress":"text-yellow-600",Completed:"text-green-600",Failed:"text-red-600"};return q.jsx("span",{className:`font-medium ${A[g]}`,children:g})},xdo=({progress:g})=>{if(g===0)return null;const A=Math.round(g*100);return q.jsxs("div",{className:"flex items-center gap-2",children:[q.jsx("div",{className:"w-20 h-2 bg-gray-200 rounded overflow-hidden",children:q.jsx("div",{className:"h-full bg-blue-500 transition-all duration-200",style:{width:`${A}%`}})}),q.jsxs("span",{className:"text-xs text-gray-500",children:[A,"%"]})]})},vxI=g=>{if(typeof g=="string")return g;if(typeof g=="number"||typeof g=="boolean"||typeof g=="bigint"||g==null)return String(g);if(typeof g=="object")try{return JSON.stringify(g)}catch{return String(g)}return String(g)},Fdo=g=>Object.entries(g).map(([A,I])=>`${A}: ${vxI(I)}`).join(", "),Udo=({stats:g})=>{if(!g||Object.keys(g).length===0)return q.jsx("span",{children:"-"});const A=Object.entries(g),I=Fdo(g);return q.jsxs("details",{className:"cursor-pointer",children:[q.jsx("summary",{className:"whitespace-nowrap overflow-hidden text-ellipsis max-w-[200px]",children:I}),q.jsx("div",{className:"mt-1 text-xs",children:A.map(([e,t])=>q.jsxs("div",{children:[e,": ",vxI(t)]},e))})]})},tog=g=>{if(g===null||typeof g!="object")return g;if(Array.isArray(g))return g.map(tog);const A={};for(const[I,e]of Object.entries(g))I.startsWith("_")||(A[I]=tog(e));return A},Jdo=(g,A)=>{try{if(typeof g.getConstructorParams!="function"){alert(`getConstructorParams() is not implemented for ${A}`);return}const I=tog(g.getConstructorParams()),e=new Blob([JSON.stringify(I,null,2)],{type:"application/json"}),t=URL.createObjectURL(e),o=document.createElement("a");o.href=t,o.download=`${A}_input.json`,o.click(),URL.revokeObjectURL(t)}catch(I){alert(`Error downloading input for ${A}: ${I instanceof Error?I.message:String(I)}`)}},Pdo=({expanded:g})=>q.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",className:`w-4 h-4 transition-transform duration-200 ${g?"rotate-90":""}`,children:q.jsx("path",{fillRule:"evenodd",d:"M4.5 5.653c0-1.426 1.529-2.33 2.779-1.643l11.54 6.348c1.295.712 1.295 2.573 0 3.285L7.28 19.991c-1.25.687-2.779-.217-2.779-1.643V5.653z",clipRule:"evenodd"})}),qxI=g=>{let A=g;for(;A.activeSubSolver;)A=A.activeSubSolver;return A},TxI=({solver:g,onStepUntilPhase:A,onDownloadInput:I,isNested:e=!1,indentLevel:t=0,triggerRender:o})=>{const[B,C]=z.useState(new Set),Q=g.pipelineDef.map((h,l)=>Rdo(g,l)),i=h=>{C(l=>{const D=new Set(l);return D.has(h)?D.delete(h):D.add(h),D})},E=h=>{A?.(h)},n=h=>{h.solverInstance&&(I?I(h.solverInstance,h.name):Jdo(h.solverInstance,h.name))},s=h=>`${(h/1e3).toFixed(2)}s`,r=()=>{if(!g.solved&&!g.failed){const h=g.activeSubSolver;for(;!g.solved&&!g.failed&&(g.step(),!(g.activeSubSolver&&g.activeSubSolver!==h)););o?.()}},a=()=>{if(!g.solved&&!g.failed){const h=qxI(g);for(;!g.solved&&!g.failed&&(g.step(),qxI(g)===h););o?.()}},c=t*24;return q.jsxs("div",{className:e?"":"border-t border-gray-200",children:[!e&&q.jsxs("div",{className:"px-4 py-2 bg-gray-50 border-b border-gray-200 flex items-center justify-between",children:[q.jsx("h3",{className:"text-sm font-semibold text-gray-700",children:"Pipeline Stages"}),q.jsxs("div",{className:"flex gap-2",children:[q.jsx("button",{onClick:a,disabled:g.solved||g.failed,className:"bg-indigo-500 hover:bg-indigo-600 disabled:bg-gray-300 disabled:cursor-not-allowed cursor-pointer text-white px-3 py-1 rounded text-sm",children:"Next Solver"}),q.jsx("button",{onClick:r,disabled:g.solved||g.failed,className:"bg-purple-500 hover:bg-purple-600 disabled:bg-gray-300 disabled:cursor-not-allowed cursor-pointer text-white px-3 py-1 rounded text-sm",children:"Next Stage"})]})]}),q.jsx("div",{className:"overflow-x-auto",children:q.jsxs("table",{className:"w-full text-sm",children:[!e&&q.jsx("thead",{children:q.jsxs("tr",{className:"bg-gray-50 border-b border-gray-200",children:[q.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Stage"}),q.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Status"}),q.jsxs("th",{className:"px-4 py-2 text-center font-semibold text-gray-700",children:["i",q.jsx("sub",{children:"0"})]}),q.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Iterations"}),q.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Progress"}),q.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Time"}),q.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Stats"}),q.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Input"})]})}),q.jsx("tbody",{children:Q.map(h=>{const l=Sdo(h.solverInstance),D=B.has(h.name);return q.jsxs(sC.Fragment,{children:[q.jsxs("tr",{className:`border-b border-gray-100 ${h.status==="In Progress"?"bg-yellow-50":""}`,children:[q.jsx("td",{className:"px-4 py-2",children:q.jsxs("div",{className:"flex items-center gap-2",style:{paddingLeft:c},children:[l?q.jsx("button",{onClick:()=>i(h.name),className:"text-gray-500 hover:text-gray-700",title:D?"Collapse":"Expand",children:q.jsx(Pdo,{expanded:D})}):q.jsx("span",{className:"w-4"}),q.jsx("span",{className:"text-gray-400 w-6",children:String(h.index+1).padStart(2,"0")}),q.jsx("button",{onClick:()=>E(h.name),disabled:h.status==="Completed"||g.solved||g.failed,className:"text-blue-500 hover:text-blue-700 disabled:text-gray-300 disabled:cursor-not-allowed",title:`Step until ${h.name} completes`,children:q.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",className:"w-4 h-4",children:q.jsx("path",{fillRule:"evenodd",d:"M4.5 5.653c0-1.426 1.529-2.33 2.779-1.643l11.54 6.348c1.295.712 1.295 2.573 0 3.285L7.28 19.991c-1.25.687-2.779-.217-2.779-1.643V5.653z",clipRule:"evenodd"})})}),q.jsx("span",{className:"font-medium text-gray-900",children:h.name})]})}),q.jsx("td",{className:"px-4 py-2",children:q.jsx(Ndo,{status:h.status})}),q.jsx("td",{className:"px-4 py-2 text-center text-gray-600",children:h.firstIteration!==null?h.firstIteration:""}),q.jsx("td",{className:"px-4 py-2 text-gray-600",children:h.iterations}),q.jsx("td",{className:"px-4 py-2",children:q.jsx(xdo,{progress:h.progress})}),q.jsx("td",{className:"px-4 py-2 text-gray-600",children:s(h.timeSpent)}),q.jsx("td",{className:"px-4 py-2 text-gray-500",children:q.jsx(Udo,{stats:h.stats})}),q.jsx("td",{className:"px-4 py-2",children:h.solverInstance?q.jsxs("button",{onClick:()=>n(h),className:"flex items-center gap-1 text-blue-500 hover:text-blue-700",title:`Download input for ${h.name}`,children:[q.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",className:"w-4 h-4",children:q.jsx("path",{fillRule:"evenodd",d:"M12 2.25a.75.75 0 01.75.75v11.69l3.22-3.22a.75.75 0 111.06 1.06l-4.5 4.5a.75.75 0 01-1.06 0l-4.5-4.5a.75.75 0 111.06-1.06l3.22 3.22V3a.75.75 0 01.75-.75zm-9 13.5a.75.75 0 01.75.75v2.25a1.5 1.5 0 001.5 1.5h13.5a1.5 1.5 0 001.5-1.5V16.5a.75.75 0 011.5 0v2.25a3 3 0 01-3 3H5.25a3 3 0 01-3-3V16.5a.75.75 0 01.75-.75z",clipRule:"evenodd"})}),q.jsx("span",{children:"Input"})]}):null})]}),l&&D&&q.jsx("tr",{children:q.jsx("td",{colSpan:8,className:"p-0",children:q.jsx(TxI,{solver:h.solverInstance,onStepUntilPhase:A,onDownloadInput:I,isNested:!0,indentLevel:t+1,triggerRender:o})})})]},h.name)})})]})})]})};function Kdo({graphics:g}){const A=g.points??[],I=g.lines??[],e=g.rects??[],t=g.circles??[],o=g.texts??[];let B=Number.POSITIVE_INFINITY,C=Number.POSITIVE_INFINITY,Q=Number.NEGATIVE_INFINITY,i=Number.NEGATIVE_INFINITY;const E=(h,l)=>{typeof h=="number"&&(h<B&&(B=h),h>Q&&(Q=h)),typeof l=="number"&&(l<C&&(C=l),l>i&&(i=l))};for(const h of A)E(h.x,h.y);for(const h of I){const l=h.points??[];for(const D of l)E(D.x,D.y)}for(const h of e){const l=h.x??0,D=h.y??0,d=h.width??0,y=h.height??0;E(l,D),E(l+d,D+y)}for(const h of t){const l=h.x??0,D=h.y??0,d=h.radius??1;E(l-d,D-d),E(l+d,D+d)}for(const h of o)E(h.x,h.y);(!isFinite(B)||!isFinite(C)||!isFinite(Q)||!isFinite(i))&&(B=-20,C=-20,Q=20,i=20);const n=10,s=B-n,r=C-n,a=Math.max(1,Q-B+2*n),c=Math.max(1,i-C+2*n);return q.jsxs("svg",{className:"w-full h-[400px] bg-white",viewBox:`${s} ${r} ${a} ${c}`,role:"img","aria-label":"Graphics fallback",children:[e.map((h,l)=>q.jsx("rect",{x:h.x??0,y:h.y??0,width:h.width??0,height:h.height??0,fill:"none",stroke:h.strokeColor??"black",strokeWidth:h.strokeWidth??1},`rect-${l}`)),I.map((h,l)=>q.jsx("polyline",{fill:"none",stroke:h.strokeColor??"black",strokeWidth:h.strokeWidth??1,points:(h.points??[]).map(D=>`${D.x??0},${D.y??0}`).join(" ")},`line-${l}`)),t.map((h,l)=>q.jsx("circle",{cx:h.x??0,cy:h.y??0,r:h.radius??1.5,fill:h.fillColor??"none",stroke:h.strokeColor??"black",strokeWidth:h.strokeWidth??1},`circle-${l}`)),A.map((h,l)=>q.jsx("circle",{cx:h.x??0,cy:h.y??0,r:h.radius??1.5,fill:h.color??"black"},`point-${l}`)),o.map((h,l)=>q.jsx("text",{x:h.x??0,y:h.y??0,fontSize:h.fontSize??10,fill:h.color??"black",children:h.text??""},`text-${l}`))]})}var Ldo=class extends sC.Component{constructor(g){super(g),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(g){console.error("InteractiveGraphics render error:",g)}render(){return this.state.hasError?this.props.fallback:this.props.children}},Ydo=({solver:g,createSolver:A,animationSpeed:I=25,onSolverStarted:e,onSolverCompleted:t})=>{const[o,B]=z.useReducer(D=>D+1,0),[C]=z.useState(()=>{if(A)return A();if(!g)throw new Error("GenericSolverDebugger requires solver or createSolver");return g}),[Q,i]=z.useState(()=>typeof window>"u"?"vector":window.localStorage.getItem("solver-utils-renderer")==="canvas"?"canvas":"vector"),[E,n]=z.useState(I),s=z.useMemo(()=>{try{return C.visualize()||{points:[],lines:[],rects:[],circles:[]}}catch(D){return console.error("Visualization error:",D),{points:[],lines:[],rects:[],circles:[]}}},[C,o]),r=z.useMemo(()=>(s.rects?.length||0)===0&&(s.lines?.length||0)===0&&(s.points?.length||0)===0&&(s.circles?.length||0)===0,[s]);z.useEffect(()=>{if(!(typeof document>"u")&&!document.querySelector('script[src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"]')){const D=document.createElement("script");D.src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4",document.head.appendChild(D)}},[]),z.useEffect(()=>{n(I)},[I]);const a=C.pipelineDef!==void 0,c=D=>{const d=C;if(!C.solved&&!C.failed){for(;!C.solved&&!C.failed&&d.currentPipelineStageIndex<=d.pipelineDef.findIndex(y=>y.solverName===D);)C.step();B()}},h=()=>{const D=JSON.stringify(s,null,2),d=new Blob([D],{type:"application/json"}),y=URL.createObjectURL(d),w=document.createElement("a");w.download="visualization.json",w.href=y,document.body.appendChild(w),w.click(),document.body.removeChild(w),URL.revokeObjectURL(y)},l=D=>{i(D),typeof window<"u"&&window.localStorage.setItem("solver-utils-renderer",D)};return q.jsxs("div",{children:[q.jsx(Mdo,{solver:C,triggerRender:B,animationSpeed:E,renderer:Q,onRendererChange:l,onAnimationSpeedChange:n,onDownloadVisualization:h,onSolverStarted:e,onSolverCompleted:t}),r?q.jsx("div",{className:"p-4 text-gray-500",children:"No Graphics Yet"}):q.jsx(Ldo,{fallback:q.jsx(Kdo,{graphics:s}),children:Q==="canvas"?q.jsx(mdo,{graphics:s}):q.jsx(wdo,{graphics:s})}),a&&q.jsx(TxI,{solver:C,onStepUntilPhase:c,triggerRender:B})]})};const _do=()=>{z.useEffect(()=>{const g="tailwind-cdn-script";if(document.getElementById(g)||window.tailwind)return;const A=document.createElement("div");A.className="hidden",document.body.appendChild(A);const I=window.getComputedStyle(A).display==="none";if(document.body.removeChild(A),I)return;const e=document.createElement("script");e.id=g,e.src="https://cdn.tailwindcss.com",document.head.appendChild(e)},[])},bdo=1e3,kk=(g,A)=>{const{fileName:I,mimeType:e="text/plain"}=A,t=g instanceof Blob?g:new Blob([g],{type:e}),o=URL.createObjectURL(t),B=document.createElement("a");B.href=o,B.download=I,B.target="_blank",B.rel="noopener noreferrer",B.style.display="none",document.body.appendChild(B),B.click(),document.body.removeChild(B),setTimeout(()=>{URL.revokeObjectURL(o)},bdo)},oog=g=>{let A=g.trim().replace(/[\\/:*?"<>|]/g,"_").replace(/[\x00-\x1f]/g,"").replace(/^\.+/,"").replace(/\.+$/,"").replace(/\s+/g," ").replace(/_+/g,"_");return/^(con|prn|aux|nul|com[0-9]|lpt[0-9])$/i.test(A)&&(A=`_${A}`),A=A.slice(0,200),A||"untitled"},Hdo=g=>{const A=g.solverConstructorArgs??[g.solverParams];if(g.solverName!=="AutoroutingPipelineSolver7_MultiGraph"||A.length!==1)return A;const[{input:I,options:e}]=A;return[I,e]},Ox="https://github.com/tscircuit/tscircuit-autorouter/issues/new",ZxI="https://github.com/tscircuit/copper-pour-solver/issues/new",OxI="https://github.com/tscircuit/calculate-packing/issues/new",vdo="https://github.com/tscircuit/matchpack/issues/new",WxI="https://github.com/tscircuit/schematic-trace-solver/issues/new?template=json-bug-report.yml",qdo={PackSolver2:OxI,LayoutPipelineSolver:vdo,AutoroutingPipelineSolver:Ox,AssignableAutoroutingPipeline2:Ox,AssignableAutoroutingPipeline3:Ox,AutoroutingPipeline1_OriginalUnravel:Ox,AutoroutingPipelineSolver3_HgPortPointPathing:Ox,AutoroutingPipelineSolver4:Ox,AutoroutingPipelineSolver5:Ox,AutoroutingPipelineSolver7_MultiGraph:Ox,AutoroutingPipelineSolver8:Ox,CopperPourPipelineSolver:ZxI,SchematicTracePipelineSolver:WxI},Tdo=g=>g.toLowerCase().includes("pack")?UfI:g.toLowerCase().includes("rout")?PfI:vQo,VxI=g=>{const A=qdo[g];if(A)return A;const I=g.toLowerCase();return I.includes("autorout")?Ox:I.includes("schematic")&&I.includes("trace")?WxI:I.includes("copperpour")?ZxI:I.includes("pack")?OxI:null},Zdo=g=>`${oog(`${g.componentName}-${g.solverName}`)}-solver-input.json`,jxI=g=>{kk(JSON.stringify(g.solverParams,null,2),{fileName:Zdo(g),mimeType:"application/json"})},Odo=({solverEvent:g})=>{const A=VxI(g.solverName);return q.jsxs("div",{className:"rf-flex rf-items-center rf-justify-end rf-gap-2 rf-border-b rf-border-gray-200 rf-bg-gray-50 rf-px-4 rf-py-2",children:[q.jsxs(Ei,{type:"button",variant:"outline",size:"sm",onClick:()=>jxI(g),children:[q.jsx(reA,{className:"rf-w-4 rf-h-4"}),"Download"]}),A?q.jsx(Ei,{asChild:!0,variant:"outline",size:"sm",children:q.jsxs("a",{href:A,target:"_blank",rel:"noopener noreferrer",children:[q.jsx(zwA,{className:"rf-w-4 rf-h-4"}),"Report"]})}):q.jsxs(Ei,{type:"button",variant:"outline",size:"sm",disabled:!0,title:"No report link configured for this solver",children:[q.jsx(zwA,{className:"rf-w-4 rf-h-4"}),"Report"]})]})},Wdo=({solverEvent:g})=>{const A=VxI(g.solverName);return A?q.jsx(Ei,{asChild:!0,variant:"ghost",size:"icon",className:"rf-h-8 rf-w-8",children:q.jsx("a",{href:A,target:"_blank",rel:"noopener noreferrer",title:"Report solver bug","aria-label":"Report solver bug",children:q.jsx(zwA,{className:"rf-w-4 rf-h-4"})})}):q.jsx(Ei,{type:"button",variant:"ghost",size:"icon",className:"rf-h-8 rf-w-8",disabled:!0,title:"No report link configured for this solver","aria-label":"Report solver bug",children:q.jsx(zwA,{className:"rf-w-4 rf-h-4"})})},Vdo=({solverEvents:g=[]})=>{const[A,I]=z.useState(null);_do();const e=z.useMemo(()=>{const C=new Map;for(const Q of g){const i=`${Q.componentName}-${Q.solverName}`;C.set(i,Q)}return C},[g]),t=z.useMemo(()=>Array.from(e.keys()),[e]),o=A?e.get(A):null,B=z.useMemo(()=>{if(!o)return{instance:null,error:null,classFound:!1};const C=V5A[o.solverName];if(!C)return{instance:null,error:`Solver class "${o.solverName}" not found in SOLVERS registry. Available: ${Object.keys(V5A).join(", ")}`,classFound:!1};try{return{instance:new C(...Hdo(o)),error:null,classFound:!0}}catch(Q){const i=Q instanceof Error?Q.message:String(Q);return console.error("Failed to reconstruct solver:",Q),{instance:null,error:`Failed to instantiate solver: ${i}`,classFound:!0}}},[o]);return g.length===0?q.jsx("div",{className:"rf-p-4",children:q.jsx("div",{className:"rf-bg-gray-50 rf-rounded-md rf-border rf-border-gray-200",children:q.jsxs("div",{className:"rf-p-4",children:[q.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-gray-800 rf-mb-3",children:"No Solvers Detected"}),q.jsx("p",{className:"rf-text-sm rf-text-gray-600",children:"Solvers will appear here when the circuit runs. Solvers are used for tasks like component packing and autorouting."})]})})}):q.jsxs("div",{className:"rf-flex rf-h-full rf-overflow-hidden",children:[q.jsxs("div",{className:"rf-w-64 rf-border-r rf-border-gray-200 rf-overflow-y-auto rf-flex-shrink-0",children:[q.jsxs("div",{className:"rf-text-xs rf-font-semibold rf-text-gray-500 rf-px-3 rf-py-2 rf-bg-gray-50 rf-border-b rf-border-gray-200",children:[t.length," ",t.length===1?"Solver":"Solvers"]}),t.map(C=>{const Q=e.get(C),i=A===C;return q.jsx("div",{className:`rf-px-3 rf-py-2 rf-cursor-pointer rf-border-b rf-border-gray-100 ${i?"rf-bg-blue-50 rf-border-l-2 rf-border-l-blue-500":"hover:rf-bg-gray-50"}`,onClick:()=>I(C),children:(()=>{const E=Tdo(Q.solverName);return q.jsxs("div",{className:"rf-flex rf-items-center rf-gap-2",children:[q.jsx(E,{className:"rf-w-4 rf-h-4 rf-text-blue-500 rf-flex-shrink-0"}),q.jsxs("div",{className:"rf-flex-1 rf-min-w-0",children:[q.jsx("div",{className:"rf-text-sm rf-font-medium rf-text-gray-800 rf-truncate",children:Q.componentName}),q.jsx("div",{className:"rf-text-xs rf-text-gray-500 rf-truncate",children:Q.solverName})]})]})})()},C)})]}),q.jsx("div",{className:"rf-flex-1 rf-overflow-hidden",children:o?B.instance?q.jsxs("div",{className:"rf-flex rf-h-full rf-flex-col rf-overflow-y-auto",children:[q.jsx(Odo,{solverEvent:o}),q.jsx("div",{className:"rf-min-h-0 rf-flex-1",children:q.jsx(QS,{fallback:q.jsx("div",{className:"rf-p-4",children:q.jsxs("div",{className:"rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200 rf-p-4",children:[q.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-2",children:"Error Loading Solver Debugger"}),q.jsxs("p",{className:"rf-text-sm rf-text-red-600",children:["Failed to render the solver debugger for"," ",o.solverName]})]})}),children:q.jsx(Ydo,{solver:B.instance})})})]}):q.jsxs("div",{className:"rf-p-4",children:[q.jsxs("div",{className:"rf-mb-4",children:[q.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-gray-800",children:o.solverName}),q.jsxs("p",{className:"rf-text-sm rf-text-gray-500",children:["Component: ",o.componentName]})]}),B.error&&q.jsx("div",{className:`rf-rounded-md rf-border rf-p-4 rf-mb-4 ${B.classFound?"rf-bg-red-50 rf-border-red-200":"rf-bg-yellow-50 rf-border-yellow-200"}`,children:q.jsx("p",{className:`rf-text-sm ${B.classFound?"rf-text-red-700":"rf-text-yellow-700"}`,children:B.error})}),q.jsxs("div",{className:"rf-border rf-border-gray-200 rf-rounded-md rf-overflow-hidden",children:[q.jsxs("div",{className:"rf-px-3 rf-py-2 rf-bg-gray-50 rf-flex rf-items-center rf-justify-between rf-gap-2",children:[q.jsx("span",{className:"rf-text-sm rf-font-medium rf-text-gray-700",children:"Solver Parameters"}),q.jsxs("div",{className:"rf-flex rf-items-center rf-gap-1",children:[q.jsx(Wdo,{solverEvent:o}),q.jsx(Ei,{type:"button",variant:"ghost",size:"icon",className:"rf-h-8 rf-w-8","aria-label":"Download solver input JSON",title:"Download solver input JSON",onClick:()=>jxI(o),children:q.jsx(reA,{className:"rf-w-4 rf-h-4"})})]})]}),q.jsx("div",{className:"rf-p-3 rf-bg-white rf-border-t rf-border-gray-200",children:q.jsx("pre",{className:"rf-text-xs rf-font-mono rf-text-gray-600 rf-whitespace-pre-wrap rf-overflow-x-auto",children:JSON.stringify(o.solverParams,null,2)})})]})]}):q.jsx("div",{className:"rf-flex rf-items-center rf-justify-center rf-h-full",children:q.jsx("p",{className:"rf-text-sm rf-text-gray-500",children:"Select a solver from the list to view details"})})})]})},jdo=["subcircuit_id","componentDisplayName","phaseName","routingPhaseIndex","phaseOrdinal","phaseCount","phaseStageIndex","phaseStageCount","connectionCount","obstacleCount","previousTraceCount","isReroutePhase","autorouterName","autorouterVersion","solverName","effort","cacheStatus"],zdo=["phaseOrdinal","routingPhaseIndex","phaseName","phaseStageIndex"];function Xdo(g,A){let I=-1,e=-1;for(let t=g.length-1;t>=0;t--){const o=g[t];if(o.status!=="running"||o.subcircuit_id!==A.subcircuit_id||o.componentDisplayName!==A.componentDisplayName)continue;let B=0,C=!1;for(const Q of zdo)if(!(o[Q]===void 0||A[Q]===void 0)){if(o[Q]!==A[Q]){C=!0;break}B++}!C&&B>e&&(I=t,e=B)}return I}function $do(g,A){const I=Object.fromEntries(jdo.filter(B=>A[B]!==void 0).map(B=>[B,A[B]])),e=A.simpleRouteJson?structuredClone(A.simpleRouteJson):void 0,t=A.type==="autorouting:start"?-1:Xdo(g,A),o={...t===-1?{id:`autorouting_phase_${g.length+1}`}:g[t],...I,status:A.type==="autorouting:start"?"running":A.type==="autorouting:end"?"complete":"error",...A.type==="autorouting:start"?{startSimpleRouteJson:e}:A.type==="autorouting:end"?{endSimpleRouteJson:e}:{errorSimpleRouteJson:e,error:A.error?{...A.error}:void 0}};return t===-1?[...g,o]:g.map((B,C)=>C===t?o:B)}const Ayo=new Map([["custom","Custom"],["fanout","Fanout"],["single_layer_fanout","Single layer fanout"],["tscircuit_simplify","Simplify"]]),gyo=new Set(["tscircuit","default","auto","auto_local"]);function Iyo(g){if(g==="FanoutSolver")return"Fanout";if(g==="AutoroutingPipelineSolver11_Simplification")return"Simplify";const A=g.match(/^AutoroutingPipeline(?:Solver)?(\d+)(?:_|$)/);if(A)return`Pipeline${A[1]}`;const I=g.match(/^AssignableAutoroutingPipeline(\d+)$/);return I?`Assignable${I[1]}`:g}function eyo(g){const A=g.autorouterName?.trim(),I=A?.replace(/-/g,"_"),e=I&&Ayo.get(I);if(e)return e;if(I&&!gyo.has(I))return A;const t=g.solverName?.trim();if(t)return Iyo(t);const o=g.autorouterVersion?.trim();if(o){const B=o.match(/^beta[_-]pipeline(\d+)$/);return B?`Pipeline${B[1]}`:o==="latest"?"default":o}return A?"default":"Unknown"}const Bog="#fbbf24";function tyo(g){const A=g.endSimpleRouteJson?.traces??[],I=new Set(A.flatMap(t=>[t.pcb_trace_id,t.__replaces_pcb_trace_id].filter(o=>o!==void 0)));return[...(g.startSimpleRouteJson?.traces??[]).filter(t=>!I.has(t.pcb_trace_id)),...A]}function zxI(g){const A=new Map((g.startSimpleRouteJson?.traces??[]).map(I=>[I.pcb_trace_id,I]));return(g.endSimpleRouteJson?.traces??[]).filter(I=>{const e=A.get(I.pcb_trace_id);return!e||!!I.__replaces_pcb_trace_id&&I.__replaces_pcb_trace_id!==e.__replaces_pcb_trace_id||JSON.stringify(e.route)!==JSON.stringify(I.route)}).map(I=>I.pcb_trace_id)}function oyo(g,A){return{outer_diameter:g.via_diameter??A.minViaPadDiameter??A.min_via_pad_diameter??A.minViaDiameter??.6,hole_diameter:g.via_hole_diameter??A.minViaHoleDiameter??A.min_via_hole_diameter??.3}}function XxI(g,A){const I=[];for(const C of g.route)C.route_type==="wire"?I.push({...C,layer:C.layer}):C.route_type==="via"?I.push({route_type:"via",x:C.x,y:C.y,from_layer:C.from_layer,to_layer:C.to_layer,...oyo(C,A)}):C.route_type==="through_obstacle"&&I.push({route_type:"through_pad",start:{...C.start},end:{...C.end},width:C.width,start_layer:C.from_layer,end_layer:C.to_layer,pcb_smtpad_id:C.circuitJsonMetadata?.pcb_smtpad_id,pcb_plated_hole_id:C.circuitJsonMetadata?.pcb_plated_hole_id});const e=C=>{let Q=-1,i=Number.POSITIVE_INFINITY;return I.forEach((E,n)=>{if(E.route_type!=="wire")return;const s=Math.hypot(E.x-C.x,E.y-C.y);s<i&&(i=s,Q=n)}),Q},t=g.route.filter(C=>C.route_type==="jumper").map(C=>[e(C.start),e(C.end)].sort((Q,i)=>Q-i)).filter(([C,Q])=>C>=0&&Q>C).sort(([C],[Q])=>C-Q),o=[];let B=0;for(const[C,Q]of t)C>=B&&o.push(I.slice(B,C+1)),B=Math.max(B,Q);return B<I.length&&o.push(I.slice(B)),o}function Byo(g){const A=[],I=[],e=g.endSimpleRouteJson;if(!e)return{lines:A,circles:I};const t=new Set(zxI(g));for(const o of e.traces??[])if(t.has(o.pcb_trace_id))for(const B of XxI(o,e)){let C;for(const Q of B){if(Q.route_type==="through_pad"){C={...Q.end,layer:Q.end_layer,width:Q.width};continue}const i=Q.route_type==="wire"?Q.layer:Q.from_layer;C&&C.layer===i&&(C.x!==Q.x||C.y!==Q.y)&&A.push({points:[{x:C.x,y:C.y},{x:Q.x,y:Q.y}],strokeWidth:Q.route_type==="wire"?Q.width:C.width,strokeColor:Bog,layer:i}),Q.route_type==="via"&&I.push({center:{x:Q.x,y:Q.y},radius:Q.outer_diameter/2,stroke:Bog,fill:"transparent"}),C={x:Q.x,y:Q.y,layer:Q.route_type==="wire"?Q.layer:Q.to_layer,width:Q.route_type==="wire"?Q.width:C?.width??e.minTraceWidth}}}return{coordinateSystem:"cartesian",lines:A,circles:I}}function Cyo(g){const A=JSON.stringify(g);let I=2166136261;for(let e=0;e<A.length;e++)I=Math.imul(I^A.charCodeAt(e),16777619);return(I>>>0).toString(36)}const Qyo=new Set(["pcb_trace","pcb_via","pcb_copper_pour","pcb_ground_plane","pcb_ground_plane_region","pcb_thermal_spoke","pcb_breakout_point"]);function iyo(g,A,I){const e=I==="input"?A.startSimpleRouteJson??A.errorSimpleRouteJson:A.endSimpleRouteJson,t=g.filter(i=>!Qyo.has(i.type)&&!i.type.endsWith("_error")&&!i.type.endsWith("_warning"));if(!e)return t;const o=I==="input"?e.traces??[]:tyo(A),B=new Set(g.filter(i=>i.type==="source_trace").map(i=>i.source_trace_id)),C=["top",...Array.from({length:Math.max(0,e.layerCount-2)},(i,E)=>`inner${E+1}`),...e.layerCount>1?["bottom"]:[]],Q=[];for(const i of o){const n=e.connections.find(r=>r.name===i.connection_name||r.source_trace_id===i.connection_name)?.source_trace_id??i.connection_name??"",s=XxI(i,e);for(const[r,a]of s.entries()){const c={type:"pcb_trace",pcb_trace_id:`${A.id}_${I}_${i.pcb_trace_id}_${r}_${Cyo(a)}`,subcircuit_id:A.subcircuit_id??void 0,source_trace_id:B.has(n)?n:void 0,route:a};Q.push(c);for(const[h,l]of a.entries()){if(l.route_type!=="via")continue;const D=C.indexOf(l.from_layer),d=C.indexOf(l.to_layer),y={type:"pcb_via",pcb_via_id:`${c.pcb_trace_id}_via_${h}`,pcb_trace_id:c.pcb_trace_id,subcircuit_id:A.subcircuit_id??void 0,x:l.x,y:l.y,outer_diameter:l.outer_diameter,hole_diameter:l.hole_diameter,layers:D>=0&&d>=0?C.slice(Math.min(D,d),Math.max(D,d)+1):[l.from_layer,l.to_layer]};Q.push(y)}}}return[...t,...Q]}const Cog=(g,A)=>g.phaseName||`Phase ${g.phaseOrdinal??A+1}`,$xI=g=>g.componentDisplayName?.match(/name="([^"]+)"/)?.[1]?.replace(/^\./,"")||g.componentDisplayName||g.subcircuit_id||"Board",AFI=g=>g.startSimpleRouteJson??g.endSimpleRouteJson??g.errorSimpleRouteJson,Eyo={is_showing_autorouting:!0,is_showing_rats_nest:!1,is_showing_drc_errors:!1,is_showing_drc_warnings:!1,is_showing_pcb_groups:!1},nyo=({circuitJson:g,phases:A=[],isRunning:I=!1})=>{const[e,t]=z.useState(null),[o,B]=z.useState("output"),[C,Q]=z.useState(!0),[i,E]=z.useState(!1),n=z.useRef(null),[s,r]=z.useState(480),a=e?A.findIndex(N=>N.id===e.id&&AFI(N)===AFI(e)):-1,c=a<0?A.length-1:a,h=A[c],l=a<0,D=!!h?.endSimpleRouteJson,d=h?.startSimpleRouteJson??h?.errorSimpleRouteJson,y=!!d,w=o==="output"&&!D?"input":o==="input"&&!y?"output":o,u=w==="input"?d:h?.endSimpleRouteJson,G=z.useMemo(()=>!h||!u?null:iyo(g??[],h,w),[g,h,u,w]),m=z.useMemo(()=>h&&w==="output"&&C?Byo(h):{lines:[],circles:[]},[h,w,C]);if(z.useLayoutEffect(()=>{const N=n.current;if(!N)return;const U=()=>r(Math.max(360,N.clientHeight));U();const K=new ResizeObserver(U);return K.observe(N),()=>K.disconnect()},[!!h]),!h)return q.jsxs("div",{className:"rf-flex rf-min-h-[400px] rf-flex-col rf-items-center rf-justify-center rf-gap-3 rf-p-8 rf-text-center",children:[q.jsx(PfI,{className:"rf-h-7 rf-w-7 rf-text-blue-500"}),q.jsx("h3",{className:"rf-text-base rf-font-medium",children:I?"Waiting for autorouting":"No autorouting captures"}),q.jsx("p",{className:"rf-max-w-md rf-text-sm rf-text-gray-500",children:I?"Phases appear as the circuit routes. Each capture includes its input and output on the PCB.":"Run a circuit with autorouting enabled to inspect its phases. A circuit JSON file alone does not include routing history."})]});const p=Cog(h,c),k=h.status==="running"&&I,S=!D,R=d?.connections.length,x=G?.filter(N=>N.type==="pcb_trace").length??0;return q.jsxs("div",{className:"rf-flex rf-h-full rf-min-h-[620px] rf-flex-col rf-bg-white md:rf-flex-row","data-testid":"autorouting-explorer",children:[q.jsxs("aside",{className:"rf-flex rf-shrink-0 rf-flex-col rf-border-b rf-border-gray-200 md:rf-w-52 md:rf-border-b-0 md:rf-border-r","aria-label":"Routing phases",children:[q.jsxs("div",{className:"rf-flex rf-items-center rf-justify-between rf-px-3 rf-py-2 rf-text-xs rf-text-gray-500",children:[q.jsx("span",{children:"Routing phases"}),q.jsx("span",{children:A.length})]}),q.jsx("div",{className:"rf-flex rf-gap-1 rf-overflow-x-auto rf-px-1.5 rf-pb-1.5 md:rf-flex-col md:rf-overflow-x-hidden md:rf-overflow-y-auto",children:A.map((N,U)=>{const K=zxI(N).length,_=N.endSimpleRouteJson?`${K} ${K===1?"trace":"traces"} routed`:N.status==="error"?"Failed":N.status==="running"&&I?"Routing…":"No output";return q.jsxs("button",{type:"button","aria-pressed":U===c,title:`${$xI(N)} · ${_}`,onClick:()=>t(N),className:to("rf-flex rf-min-w-[192px] rf-items-start rf-gap-2 rf-rounded-md rf-border rf-px-2 rf-py-2 rf-text-left md:rf-min-w-0",U===c?"rf-border-blue-200 rf-bg-blue-50":"rf-border-transparent hover:rf-bg-gray-50"),children:[q.jsx("span",{className:to("rf-flex rf-h-5 rf-w-5 rf-shrink-0 rf-items-center rf-justify-center rf-rounded-full rf-text-[11px]",U===c?"rf-bg-blue-600 rf-text-white":"rf-bg-gray-100 rf-text-gray-500"),children:U+1}),q.jsxs("span",{className:"rf-min-w-0 rf-flex-1",children:[q.jsxs("span",{className:"rf-flex rf-items-center rf-gap-1",children:[q.jsx("span",{className:"rf-min-w-0 rf-flex-1 rf-truncate rf-text-xs rf-font-medium rf-leading-5 rf-text-gray-800",title:Cog(N,U),children:Cog(N,U)}),N.status==="complete"?q.jsx(_x,{"aria-label":"Captured",className:"rf-h-3 rf-w-3 rf-shrink-0 rf-text-green-600"}):N.status==="error"?q.jsx(meg,{"aria-label":"Failed",className:"rf-h-3 rf-w-3 rf-shrink-0 rf-text-red-500"}):I?q.jsx(iS,{"aria-label":"Routing",className:"rf-h-3 rf-w-3 rf-shrink-0 rf-animate-spin rf-text-blue-500"}):null]}),q.jsxs("span",{className:"rf-block rf-text-[11px] rf-leading-4 rf-text-gray-500",children:[eyo(N)," · ",_]})]})]},N.id)})})]}),q.jsxs("div",{className:"rf-flex rf-min-w-0 rf-flex-1 rf-flex-col",children:[q.jsxs("div",{className:"rf-flex rf-flex-wrap rf-items-center rf-gap-3 rf-border-b rf-border-gray-200 rf-px-4 rf-py-3",children:[q.jsxs("h3",{className:"rf-mr-auto rf-flex rf-items-center rf-gap-2 rf-text-sm rf-font-medium",children:[p,q.jsxs("span",{className:"rf-text-xs rf-font-normal rf-text-gray-500",children:[c+1," of ",A.length]})]}),I&&q.jsx("button",{type:"button",onClick:()=>t(null),disabled:l,className:"rf-text-xs rf-text-blue-600 disabled:rf-text-gray-500",children:l?"Following latest":"Follow latest"}),q.jsx("div",{className:"rf-flex rf-rounded-md rf-bg-gray-100 rf-p-1","aria-label":"Phase snapshot",children:["input","output"].map(N=>q.jsx("button",{type:"button","aria-pressed":w===N,disabled:N==="input"?!y:!D,onClick:()=>B(N),className:to("rf-rounded rf-px-3 rf-py-1 rf-text-xs disabled:rf-opacity-40",w===N?"rf-bg-white rf-text-gray-900 rf-shadow-sm":"rf-text-gray-500"),children:N==="input"?"Input":"Output"},N))})]}),q.jsxs("div",{className:"rf-flex rf-flex-wrap rf-items-center rf-justify-between rf-gap-2 rf-px-4 rf-py-2 rf-text-xs rf-text-gray-600",children:[q.jsxs("label",{className:"rf-flex rf-items-center rf-gap-2",children:[q.jsx("input",{type:"checkbox",checked:C,disabled:w!=="output",onChange:N=>Q(N.target.checked),className:"rf-accent-blue-600"}),q.jsx("span",{"aria-hidden":"true",className:"rf-inline-block rf-h-0.5 rf-w-3",style:{backgroundColor:Bog}}),"Highlight changes (all layers)"]}),q.jsxs("span",{children:[w==="input"?"Before this phase":"After this phase"," ","· ",x," traces"]})]}),S&&q.jsx("div",{className:to("rf-border-y rf-px-4 rf-py-2 rf-text-xs",h.status==="error"?"rf-border-red-100 rf-bg-red-50 rf-text-red-700":"rf-border-blue-100 rf-bg-blue-50 rf-text-blue-700"),role:"status",children:h.status==="error"?`Routing failed: ${h.error?.message||"No output was captured."}`:k?"Routing in progress. Showing captured input until output is available.":"No output was captured for this phase. Showing the available input."}),q.jsx("div",{ref:n,className:"rf-relative rf-min-h-[360px] rf-flex-1","data-testid":"autorouting-pcb",children:G?q.jsx(weg,{circuitJson:G,height:s,allowEditing:!1,clickToInteractEnabled:!1,initialState:Eyo,debugGraphics:m}):q.jsx("div",{className:"rf-p-6 rf-text-sm rf-text-gray-500",children:"No PCB snapshot available for this capture."})}),q.jsxs("div",{className:"rf-flex rf-flex-wrap rf-items-center rf-justify-between rf-gap-2 rf-border-t rf-border-gray-200 rf-px-4 rf-py-3 rf-text-xs rf-text-gray-500",children:[q.jsxs("span",{children:[R===void 0?"Input unavailable":`${R} input connections`,` · ${$xI(h)}`]}),q.jsxs("div",{className:"rf-flex rf-items-center rf-gap-4",children:[q.jsxs("button",{type:"button",disabled:!u,onClick:()=>kk(JSON.stringify(u,null,2),{fileName:`${h.id}-${w}.srj.json`,mimeType:"application/json"}),className:"rf-flex rf-items-center rf-gap-1 disabled:rf-opacity-40",children:[q.jsx(reA,{className:"rf-h-3 rf-w-3"}),"Download SRJ"]}),q.jsxs("button",{type:"button","aria-expanded":i,onClick:()=>E(!i),className:"rf-flex rf-items-center rf-gap-1",children:[q.jsx(b5,{className:to("rf-h-3 rf-w-3",i&&"rf-rotate-90")}),"Inspect SRJ"]})]})]}),i&&q.jsx("pre",{className:"rf-m-0 rf-max-h-64 rf-overflow-auto rf-border-t rf-border-gray-200 rf-bg-gray-50 rf-p-4 rf-text-xs","aria-label":`${p} ${w} SRJ`,children:u?JSON.stringify(u,null,2):"No snapshot captured."})]})]})},gFI=({errorMessage:g,errorStack:A,circuitJsonErrors:I})=>{z.useEffect(()=>{if(VU("TSCIRCUIT_TELEMETRY_DISABLED")!==!0&&g){const e=new Error(g);A&&(e.stack=A);try{bq.captureException(e)}catch{}}},[g,A]),z.useEffect(()=>{if(VU("TSCIRCUIT_TELEMETRY_DISABLED")!==!0&&I&&I.length>0)for(const e of I){const t=new Error(e.message||"Circuit JSON Error");e.stack&&(t.stack=e.stack);try{bq.captureException(t,{error_type:e.type})}catch{}}},[I])},IFI=g=>{z.useEffect(()=>{try{vht(g)}catch{}},[g.source,g.component,g.isWebEmbedded,g.activeTab])},eFI="0.0.3046",syo={version:eFI},dGA=zVg()(XVg(g=>({lastRunEvalVersion:void 0,setLastRunEvalVersion:A=>{g({lastRunEvalVersion:A})}}),{name:"runframe-runner-store"})),ayo=g=>{const[A,I]=z.useState([]),[e,t]=z.useState(null),[o,B]=z.useState(""),[C,Q]=iq("eval-version-selection",null),i=dGA(r=>r.setLastRunEvalVersion),E=dGA(r=>r.lastRunEvalVersion);return z.useEffect(()=>{g&&fetch("https://data.jsdelivr.com/v1/package/npm/@tscircuit/eval").then(r=>r.json()).then(r=>{if(Array.isArray(r?.versions)){let a=[...r.versions];r.tags?.latest&&(t(r.tags.latest),a=a.filter(c=>c!==r.tags.latest)),I(a)}}).catch(()=>{})},[g]),z.useEffect(()=>{g&&(C?(window.TSCIRCUIT_LATEST_EVAL_VERSION=C,i(C)):e&&(window.TSCIRCUIT_LATEST_EVAL_VERSION=e,i(e)))},[g,C,e]),{versions:z.useMemo(()=>A.filter(r=>r.includes(o)).slice(0,50),[A,o]),latestVersion:e,lastRunEvalVersion:E,search:o,setSearch:B,selectVersion:r=>{Q(r),B("")}}},ryo=({snippetNames:g,onSelect:A,onCancel:I,isOpen:e})=>{const[t,o]=z.useState(""),[B,C]=z.useState("");if(!e)return null;const Q=g.filter(n=>n.toLowerCase().includes(B.toLowerCase())),i=B&&!g.includes(B),E=n=>{n.key==="Enter"&&(Q.length===1?o(Q[0]):i&&o(B))};return q.jsx("div",{className:"rf-fixed rf-inset-0 rf-bg-black rf-bg-opacity-50 rf-flex rf-items-center rf-justify-center rf-z-[100]",children:q.jsxs("div",{className:"rf-bg-white rf-rounded-lg rf-p-6 rf-w-96",children:[q.jsx("h2",{className:"rf-text-lg rf-font-semibold rf-mb-4",children:"Select Snippet"}),q.jsx("input",{type:"text",className:"rf-w-full rf-px-4 rf-py-2 rf-border rf-rounded rf-mb-4",placeholder:"Search snippets or new snippet name...",value:B,onChange:n=>C(n.target.value),onKeyDown:E}),q.jsxs("div",{className:"rf-h-60 rf-overflow-y-auto",children:[Q.map(n=>q.jsx("button",{type:"button",className:`w-full text-left px-4 py-2 rounded hover:bg-gray-100 ${t===n?"bg-blue-50":""}`,onClick:()=>o(n),children:n},n)),i&&q.jsxs("button",{type:"button",className:`w-full text-left px-4 py-2 rounded hover:bg-gray-100 text-blue-500 ${t===B?"bg-blue-50":""}`,onClick:()=>o(B),children:['Create new "',B,'"']})]}),q.jsxs("div",{className:"rf-mt-4 rf-flex rf-justify-end rf-gap-2",children:[q.jsx("button",{type:"button",className:"rf-px-4 rf-py-2 rf-text-gray-600 rf-hover:text-gray-800",onClick:I,children:"Cancel"}),q.jsx("button",{type:"button",className:"rf-px-4 rf-py-2 rf-bg-blue-500 rf-text-white rf-rounded rf-hover:bg-blue-600 rf-disabled:opacity-50",onClick:()=>t&&A(t),disabled:!t,children:t===B?`Create "${t}"`:`Save to ${t}`})]})]})})},cyo=g=>{const A=z.useRef(null),I=Uc(e=>e.recentEvents);z.useEffect(()=>{if(I.length===0)return;const e=I[0];e.event_id!==A.current&&(g(e),A.current=e.event_id)},[I,g])};var hyo=Object.defineProperty,xJ=(g,A)=>hyo(g,"name",{value:A,configurable:!0}),lyo="AlertDialog",[Dyo,ugB]=gk(lyo,[iNI]),FJ=iNI(),dyo=xJ(g=>{const{__scopeAlertDialog:A,...I}=g,e=FJ(A);return q.jsx(JuA,{...e,...I,modal:!0})},"AlertDialog");z.forwardRef(xJ(function(A,I){const{__scopeAlertDialog:e,...t}=A,o=FJ(e);return q.jsx(rso,{...o,...t,ref:I})},"AlertDialogTrigger"));var yyo=xJ(g=>{const{__scopeAlertDialog:A,...I}=g,e=FJ(A);return q.jsx(PuA,{...e,...I})},"AlertDialogPortal"),tFI=z.forwardRef(xJ(function(A,I){const{__scopeAlertDialog:e,...t}=A,o=FJ(e);return q.jsx(MeA,{...o,...t,ref:I})},"AlertDialogOverlay")),wyo="AlertDialogContent",[uyo,Gyo]=Dyo(wyo),oFI=z.forwardRef(xJ(function(A,I){const{__scopeAlertDialog:e,children:t,...o}=A,B=FJ(e),C=z.useRef(null),Q=wi(I,C),i=z.useRef(null);return q.jsx(uyo,{scope:e,cancelRef:i,children:q.jsx(feA,{role:"alertdialog",...B,...o,ref:Q,onOpenAutoFocus:Mo(o.onOpenAutoFocus,E=>{E.preventDefault(),i.current?.focus({preventScroll:!0})}),onPointerDownOutside:E=>E.preventDefault(),onInteractOutside:E=>E.preventDefault(),children:t})})},"AlertDialogContent")),BFI=z.forwardRef(xJ(function(A,I){const{__scopeAlertDialog:e,...t}=A,o=FJ(e);return q.jsx(KuA,{...o,...t,ref:I})},"AlertDialogTitle")),CFI=z.forwardRef(xJ(function(A,I){const{__scopeAlertDialog:e,...t}=A,o=FJ(e);return q.jsx(LuA,{...o,...t,ref:I})},"AlertDialogDescription")),QFI=z.forwardRef(xJ(function(A,I){const{__scopeAlertDialog:e,...t}=A,o=FJ(e);return q.jsx(atg,{...o,...t,ref:I})},"AlertDialogAction")),myo="AlertDialogCancel",iFI=z.forwardRef(xJ(function(A,I){const{__scopeAlertDialog:e,...t}=A,{cancelRef:o}=Gyo(myo,e),B=FJ(e),C=wi(I,o);return q.jsx(atg,{...B,...t,ref:C})},"AlertDialogCancel"));const EFI=dyo,pyo=yyo,nFI=z.forwardRef(({className:g,...A},I)=>q.jsx(tFI,{className:to("rf-fixed rf-inset-0 rf-z-50 rf-bg-black/80 data-[state=open]:rf-animate-in data-[state=closed]:rf-animate-out data-[state=closed]:rf-fade-out-0 data-[state=open]:rf-fade-in-0",g),...A,ref:I}));nFI.displayName=tFI.displayName;const Qog=z.forwardRef(({className:g,...A},I)=>q.jsxs(pyo,{children:[q.jsx(nFI,{}),q.jsx(oFI,{ref:I,className:to("rf-fixed rf-left-[50%] rf-top-[50%] rf-z-50 rf-grid rf-w-full rf-max-w-lg rf-translate-x-[-50%] rf-translate-y-[-50%] rf-gap-4 rf-border rf-border-zinc-200 rf-bg-white rf-p-6 rf-shadow-lg rf-duration-200 data-[state=open]:rf-animate-in data-[state=closed]:rf-animate-out data-[state=closed]:rf-fade-out-0 data-[state=open]:rf-fade-in-0 data-[state=closed]:rf-zoom-out-95 data-[state=open]:rf-zoom-in-95 data-[state=closed]:rf-slide-out-to-left-1/2 data-[state=closed]:rf-slide-out-to-top-[48%] data-[state=open]:rf-slide-in-from-left-1/2 data-[state=open]:rf-slide-in-from-top-[48%] sm:rf-rounded-lg dark:rf-border-zinc-800 dark:rf-bg-zinc-950",g),...A})]}));Qog.displayName=oFI.displayName;const iog=({className:g,...A})=>q.jsx("div",{className:to("rf-flex rf-flex-col rf-space-y-2 rf-text-center sm:rf-text-left",g),...A});iog.displayName="AlertDialogHeader";const Eog=({className:g,...A})=>q.jsx("div",{className:to("rf-flex rf-flex-col-reverse sm:rf-flex-row sm:rf-justify-end sm:rf-space-x-2",g),...A});Eog.displayName="AlertDialogFooter";const nog=z.forwardRef(({className:g,...A},I)=>q.jsx(BFI,{ref:I,className:to("rf-text-lg rf-font-semibold",g),...A}));nog.displayName=BFI.displayName;const sog=z.forwardRef(({className:g,...A},I)=>q.jsx(CFI,{ref:I,className:to("rf-text-sm rf-text-zinc-500 dark:rf-text-zinc-400",g),...A}));sog.displayName=CFI.displayName;const kyo=z.forwardRef(({className:g,...A},I)=>q.jsx(QFI,{ref:I,className:to(EZ(),g),...A}));kyo.displayName=QFI.displayName;const aog=z.forwardRef(({className:g,...A},I)=>q.jsx(iFI,{ref:I,className:to(EZ({variant:"outline"}),"rf-mt-2 sm:rf-mt-0",g),...A}));aog.displayName=iFI.displayName;var Myo=Object.defineProperty,UJ=(g,A)=>Myo(g,"name",{value:A,configurable:!0}),rog="Checkbox",[Syo,GgB]=gk(rog),[fyo,cog]=Syo(rog);function sFI(g){const{__scopeCheckbox:A,checked:I,children:e,defaultChecked:t,disabled:o,form:B,name:C,onCheckedChange:Q,required:i,value:E="on",internal_do_not_use_render:n}=g,[s,r]=sR({prop:I,defaultProp:t??!1,onChange:Q,caller:rog}),[a,c]=z.useState(null),[h,l]=z.useState(null),[D,d]=z.useState(null),y=a?!!B||!!a.closest("form"):!0,w={checked:s,disabled:o,setChecked:r,control:a,setControl:c,name:C,form:B,value:E,userClick:D,onUserClick:d,required:i,defaultChecked:gf(t)?!1:t,isFormControl:y,bubbleInput:h,setBubbleInput:l};return q.jsx(fyo,{scope:A,...w,children:rFI(n)?n(w):e})}UJ(sFI,"CheckboxProvider");var Ryo="CheckboxTrigger",Nyo=z.forwardRef(UJ(function({__scopeCheckbox:A,onKeyDown:I,onClick:e,...t},o){const{control:B,value:C,disabled:Q,checked:i,required:E,setControl:n,setChecked:s,onUserClick:r,isFormControl:a,bubbleInput:c}=cog(Ryo,A),h=wi(o,n),l=z.useRef(i);return z.useEffect(()=>{const D=B?.form;if(D){const d=UJ(()=>s(l.current),"reset");return D.addEventListener("reset",d),()=>D.removeEventListener("reset",d)}},[B,s]),q.jsx(dQ.button,{type:"button",role:"checkbox","aria-checked":gf(i)?"mixed":i,"aria-required":E,"data-state":hog(i),"data-disabled":Q?"":void 0,disabled:Q,value:C,...t,ref:h,onKeyDown:Mo(I,D=>{D.key==="Enter"&&D.preventDefault()}),onClick:Mo(e,D=>{const d=D.isPropagationStopped();r({requestedChecked:gf(i)?!0:!i,hasConsumerStoppedPropagation:d}),s(y=>gf(y)?!0:!y),c&&a&&(d||D.stopPropagation())})})},"CheckboxTrigger")),aFI=z.forwardRef(UJ(function(A,I){const{__scopeCheckbox:e,name:t,checked:o,defaultChecked:B,required:C,disabled:Q,value:i,onCheckedChange:E,form:n,...s}=A;return q.jsx(sFI,{__scopeCheckbox:e,checked:o,defaultChecked:B,disabled:Q,required:C,onCheckedChange:E,name:t,form:n,value:i,internal_do_not_use_render:({isFormControl:r})=>q.jsxs(q.Fragment,{children:[q.jsx(Nyo,{...s,ref:I,__scopeCheckbox:e}),r&&q.jsx(Jyo,{__scopeCheckbox:e})]})})},"Checkbox")),xyo="CheckboxIndicator",Fyo=z.forwardRef(UJ(function(A,I){const{__scopeCheckbox:e,forceMount:t,...o}=A,B=cog(xyo,e);return q.jsx(YM,{present:t||gf(B.checked)||B.checked===!0,children:q.jsx(dQ.span,{"data-state":hog(B.checked),"data-disabled":B.disabled?"":void 0,...o,ref:I,style:{pointerEvents:"none",...A.style}})})},"CheckboxIndicator")),Uyo="CheckboxBubbleInput",Jyo=z.forwardRef(UJ(function({__scopeCheckbox:A,onClick:I,...e},t){const{control:o,userClick:B,checked:C,defaultChecked:Q,required:i,disabled:E,name:n,value:s,form:r,bubbleInput:a,setBubbleInput:c}=cog(Uyo,A),h=wi(t,c),l=Weg(o),D=z.useRef(!1),d=z.useRef(C),y=z.useRef(B),w=z.useRef(null);z.useEffect(()=>{const G=a;if(!G)return;const m=window.HTMLInputElement.prototype,k=Object.getOwnPropertyDescriptor(m,"checked").set;if(!k)return;const S=d.current!==C;d.current=C;const R=B!==null&&B!==y.current;if(y.current=B,R)w.current=S?null:B,S&&(G.indeterminate=gf(C),k.call(G,gf(C)?!1:C)),G.dispatchEvent(new Event("click",{bubbles:!B.hasConsumerStoppedPropagation}));else if(S){const x=w.current;w.current=null;const N=x?.requestedChecked===C;D.current=!0,G.indeterminate=gf(C),k.call(G,gf(C)?!1:C),G.dispatchEvent(new Event("click",{bubbles:!(N&&x.hasConsumerStoppedPropagation)})),D.current=!1}},[a,C,B]);const u=z.useRef(gf(C)?!1:C);return q.jsx(dQ.input,{type:"checkbox","aria-hidden":!0,defaultChecked:Q??u.current,required:i,disabled:E,name:n,value:s,form:r,...e,tabIndex:-1,ref:h,onClick:Mo(I,G=>{D.current&&G.stopPropagation()}),style:{...e.style,...l,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})},"CheckboxBubbleInput"));function rFI(g){return typeof g=="function"}UJ(rFI,"isFunction");function gf(g){return g==="indeterminate"}UJ(gf,"isIndeterminate");function hog(g){return gf(g)?"indeterminate":g?"checked":"unchecked"}UJ(hog,"getState");const zeA=z.forwardRef(({className:g,...A},I)=>q.jsx(aFI,{ref:I,className:to("rf-peer rf-h-4 rf-w-4 rf-shrink-0 rf-rounded-sm rf-border rf-border-zinc-200 rf-border-zinc-900 rf-shadow focus-visible:rf-outline-none focus-visible:rf-ring-1 focus-visible:rf-ring-zinc-950 disabled:rf-cursor-not-allowed disabled:rf-opacity-50 data-[state=checked]:rf-bg-zinc-900 data-[state=checked]:rf-text-zinc-50 dark:rf-border-zinc-800 dark:rf-border-zinc-50 dark:focus-visible:rf-ring-zinc-300 dark:data-[state=checked]:rf-bg-zinc-50 dark:data-[state=checked]:rf-text-zinc-900",g),...A,children:q.jsx(Fyo,{className:to("rf-flex rf-items-center rf-justify-center rf-text-current"),children:q.jsx(_x,{className:"rf-h-4 rf-w-4"})})}));zeA.displayName=aFI.displayName;const j5=JuA,Pyo=PuA,cFI=z.forwardRef(({className:g,...A},I)=>q.jsx(MeA,{className:to("rf-fixed rf-inset-0 rf-z-50 rf-bg-black/80 data-[state=open]:rf-animate-in data-[state=closed]:rf-animate-out data-[state=closed]:rf-fade-out-0 data-[state=open]:rf-fade-in-0",g),...A,ref:I}));cFI.displayName=MeA.displayName;const W3=z.forwardRef(({className:g,children:A,showOverlay:I=!0,...e},t)=>q.jsxs(Pyo,{children:[q.jsx(cFI,{className:to(I?"":"rf-hidden")}),q.jsx(feA,{ref:t,className:to("rf-fixed rf-left-[50%] rf-top-[50%] rf-z-50 rf-grid rf-w-full rf-max-w-lg rf-translate-x-[-50%] rf-translate-y-[-50%] rf-gap-4 rf-border rf-border-zinc-200 rf-bg-white rf-p-6 rf-shadow-lg rf-duration-200 data-[state=open]:rf-animate-in data-[state=closed]:rf-animate-out data-[state=closed]:rf-fade-out-0 data-[state=open]:rf-fade-in-0 data-[state=closed]:rf-zoom-out-95 data-[state=open]:rf-zoom-in-95 data-[state=closed]:rf-slide-out-to-left-1/2 data-[state=closed]:rf-slide-out-to-top-[48%] data-[state=open]:rf-slide-in-from-left-1/2 data-[state=open]:rf-slide-in-from-top-[48%] sm:rf-rounded-lg dark:rf-border-zinc-800 dark:rf-bg-zinc-950",g),...e,children:A})]}));W3.displayName=feA.displayName;const V3=({className:g,...A})=>q.jsx("div",{className:to("rf-flex rf-flex-col rf-space-y-2 rf-text-center sm:rf-text-left",g),...A});V3.displayName="DialogHeader";const LZ=({className:g,...A})=>q.jsx("div",{className:to("rf-flex rf-flex-col-reverse sm:rf-flex-row sm:rf-justify-end sm:rf-space-x-2",g),...A});LZ.displayName="DialogFooter";const j3=z.forwardRef(({className:g,...A},I)=>q.jsx(KuA,{ref:I,className:to("rf-text-lg rf-font-semibold",g),...A}));j3.displayName=KuA.displayName;const z5=z.forwardRef(({className:g,...A},I)=>q.jsx(LuA,{ref:I,className:to("rf-text-sm rf-text-zinc-500 dark:rf-text-zinc-400",g),...A}));z5.displayName=LuA.displayName;const yGA={"tscircuit.com":{label:"tscircuit.com",placeholder:"Search tscircuit packages...",emptyMessage:"No packages found"},jlcpcb:{label:"JLCPCB Parts",placeholder:"Search JLCPCB parts (e.g. C14663)...",emptyMessage:"No parts found"},kicad:{label:"KiCad Footprints",placeholder:"Search KiCad footprints...",emptyMessage:"No footprints found"}},Kyo="https://cdn.jsdelivr.net/npm/easyeda@latest/dist/browser/index.js";let log=null;const Dog=async()=>(log||(log=import(Kyo)),log),Lyo=g=>(A,I)=>{const e=new Headers(I?.headers),t={};return e.forEach((o,B)=>{t[B]=o}),fetch(`${g?.apiBase??dm}/proxy`,{...I,headers:{...t,"X-Target-Url":A.toString(),"X-Sender-Origin":t.origin??"","X-Sender-Host":t.host??"https://easyeda.com","X-Sender-Referer":t.referer??"","X-Sender-User-Agent":t["user-agent"]??"","X-Sender-Cookie":t.cookie??"",authority:t.authority??"","content-type":t["content-type"]??"",...g?.headers}})},Yyo=async(g,A=10)=>{const I=encodeURIComponent(g),e=await fetch(`https://jlcsearch.tscircuit.com/api/search?limit=${A}&q=${I}`);if(!e.ok)throw new Error(`JLCPCB API error: ${e.status}`);return(await e.json()).components??[]},_yo=g=>({lcscId:g.lcsc,manufacturer:g.mfr,description:g.description,partNumber:`C${g.lcsc}`,package:g.package,price:g.price,stock:g.stock,isBasic:g.is_basic}),hFI=async(g,A)=>{const{fetchEasyEDAComponent:I}=await Dog();return I(g,{fetch:Lyo(A),includeModelMetadata:A?.includeModelMetadata})},byo=async(g,A)=>{const{convertRawEasyToTsx:I}=await Dog(),e=await hFI(g,A);return I({rawEasy:e})},Hyo=async(g,A)=>{const{EasyEdaJsonSchema:I,convertEasyEdaJsonToCircuitJson:e}=await Dog(),t=await hFI(g,{...A,includeModelMetadata:!1}),o=I.parse(t);return e(o,{shouldRecenter:!0,showDesignator:!0,useModelCdn:!1})};function z3(g){return Array.isArray?Array.isArray(g):DFI(g)==="[object Array]"}function vyo(g){if(typeof g=="string")return g;if(typeof g=="bigint")return g.toString();const A=g+"";return A=="0"&&1/g==-1/0?"-0":A}function dog(g){return g==null?"":vyo(g)}function CG(g){return typeof g=="string"}function wGA(g){return typeof g=="number"}function qyo(g){return g===!0||g===!1||Tyo(g)&&DFI(g)=="[object Boolean]"}function lFI(g){return typeof g=="object"}function Tyo(g){return lFI(g)&&g!==null}function hS(g){return g!=null}function uGA(g){return!g.trim().length}function DFI(g){return g==null?g===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(g)}const Zyo="Incorrect 'index' type",yog="Invalid doc index: must be a non-negative integer within the bounds of the docs array",Oyo=g=>`Invalid value for key ${g}`,Wyo=g=>`Pattern length exceeds max of ${g}.`,Vyo=g=>`Missing ${g} property in key`,jyo=g=>`Property 'weight' in key '${g}' must be a positive integer`,zyo="Fuse.match does not support useTokenSearch: token search requires corpus-level statistics (df, fieldCount) that a one-off string comparison does not have. Use new Fuse(...).search(...) instead.",dFI=Object.prototype.hasOwnProperty;var Xyo=class{constructor(g){this._keys=[],this._keyMap={};let A=0;g.forEach(I=>{const e=yFI(I);this._keys.push(e),this._keyMap[e.id]=e,A+=e.weight}),this._keys.forEach(I=>{I.weight/=A})}get(g){return this._keyMap[g]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}};function yFI(g){let A=null,I=null,e=null,t=1,o=null;if(CG(g)||z3(g))e=g,A=wFI(g),I=GGA(g);else{if(!dFI.call(g,"name"))throw new Error(Vyo("name"));const B=g.name;if(e=B,dFI.call(g,"weight")&&g.weight!==void 0&&(t=g.weight,t<=0))throw new Error(jyo(GGA(B)));A=wFI(B),I=GGA(B),o=g.getFn??null}return{path:A,id:I,weight:t,src:e,getFn:o}}function wFI(g){return z3(g)?g:g.split(".")}function GGA(g){return z3(g)?g.join("."):g}function $yo(g,A){const I=[];let e=!1;const t=(o,B,C,Q)=>{if(hS(o))if(!B[C])I.push(Q!==void 0?{v:o,i:Q}:o);else{const i=o[B[C]];if(!hS(i))return;if(C===B.length-1&&(CG(i)||wGA(i)||qyo(i)||typeof i=="bigint"))I.push(Q!==void 0?{v:dog(i),i:Q}:dog(i));else if(z3(i)){e=!0;for(let E=0,n=i.length;E<n;E+=1)t(i[E],B,C+1,E)}else B.length&&t(i,B,C+1,Q)}};return t(g,CG(A)?A.split("."):A,0),e?I:I[0]}const rQ=Object.freeze({...{isCaseSensitive:!1,ignoreDiacritics:!1,includeScore:!1,keys:[],shouldSort:!0,sortFn:(g,A)=>g.score===A.score?g.idx<A.idx?-1:1:g.score<A.score?-1:1},...{includeMatches:!1,findAllMatches:!1,minMatchCharLength:1},...{location:0,threshold:.6,distance:100},...{useExtendedSearch:!1,useTokenSearch:!1,tokenize:void 0,tokenMatch:"any",getFn:$yo,ignoreLocation:!1,ignoreFieldNorm:!1,fieldNormWeight:1}});function Awo(g){return g>=9&&g<=13||g===32||g===160}function gwo(g=1,A=3){const I=new Map,e=Math.pow(10,A);return{get(t){let o=0,B=!1;for(let Q=0;Q<t.length;Q++)Awo(t.charCodeAt(Q))?B=!1:B||(o++,B=!0);if(o===0&&(o=1),I.has(o))return I.get(o);const C=Math.round(e/Math.pow(o,.5*g))/e;return I.set(o,C),C},clear(){I.clear()}}}var wog=class{constructor({getFn:g=rQ.getFn,fieldNormWeight:A=rQ.fieldNormWeight}={}){this.norm=gwo(A,3),this.getFn=g,this.isCreated=!1,this.docs=[],this.keys=[],this._keysMap={},this.setIndexRecords()}setSources(g=[]){this.docs=g}setIndexRecords(g=[]){this.records=g}setKeys(g=[]){this.keys=g,this._keysMap={},g.forEach((A,I)=>{this._keysMap[A.id]=I})}create(){if(this.isCreated||!this.docs.length)return;this.isCreated=!0;const g=this.docs.length;this.records=new Array(g);let A=0;if(CG(this.docs[0]))for(let I=0;I<g;I++){const e=this._createStringRecord(this.docs[I],I);e&&(this.records[A++]=e)}else for(let I=0;I<g;I++)this.records[A++]=this._createObjectRecord(this.docs[I],I);this.records.length=A,this.norm.clear()}add(g,A){if(!Number.isInteger(A)||A<0)throw new Error(yog);if(CG(g)){const e=this._createStringRecord(g,A);return e&&this.records.push(e),e}const I=this._createObjectRecord(g,A);return this.records.push(I),I}removeAt(g){if(!Number.isInteger(g)||g<0)throw new Error(yog);for(let A=0,I=this.records.length;A<I;A+=1)if(this.records[A].i===g){this.records.splice(A,1);break}for(let A=0,I=this.records.length;A<I;A+=1)this.records[A].i>g&&(this.records[A].i-=1)}removeAll(g){const A=new Set;for(const e of g)Number.isInteger(e)&&e>=0&&A.add(e);if(A.size===0)return;this.records=this.records.filter(e=>!A.has(e.i));const I=Array.from(A).sort((e,t)=>e-t);for(const e of this.records){let t=0,o=I.length;for(;t<o;){const B=t+o>>>1;I[B]<e.i?t=B+1:o=B}e.i-=t}}getValueForItemAtKeyId(g,A){return g[this._keysMap[A]]}size(){return this.records.length}_createStringRecord(g,A){return!hS(g)||uGA(g)?null:{v:g,i:A,n:this.norm.get(g)}}_createObjectRecord(g,A){const I={i:A,$:{}};for(let e=0,t=this.keys.length;e<t;e++){const o=this.keys[e],B=o.getFn?o.getFn(g):this.getFn(g,o.path);if(hS(B)){if(z3(B)){const C=[];for(let Q=0,i=B.length;Q<i;Q+=1){const E=B[Q];if(hS(E)){if(CG(E)){if(!uGA(E)){const n={v:E,i:Q,n:this.norm.get(E)};C.push(n)}}else if(hS(E.v)){const n=CG(E.v)?E.v:dog(E.v);if(!uGA(n)){const s={v:n,i:E.i,n:this.norm.get(n)};C.push(s)}}}}I.$[e]=C}else if(CG(B)&&!uGA(B)){const C={v:B,n:this.norm.get(B)};I.$[e]=C}}}return I}toJSON(){return{keys:this.keys.map(({getFn:g,...A})=>A),records:this.records}}};function uFI(g,A,{getFn:I=rQ.getFn,fieldNormWeight:e=rQ.fieldNormWeight}={}){const t=new wog({getFn:I,fieldNormWeight:e});return t.setKeys(g.map(yFI)),t.setSources(A),t.create(),t}function Iwo(g,{getFn:A=rQ.getFn,fieldNormWeight:I=rQ.fieldNormWeight}={}){const{keys:e,records:t}=g,o=new wog({getFn:A,fieldNormWeight:I});return o.setKeys(e),o.setIndexRecords(t),o}function ewo(g=[],A=rQ.minMatchCharLength){const I=[];let e=-1,t=-1,o=0;for(let B=g.length;o<B;o+=1){const C=g[o];C&&e===-1?e=o:!C&&e!==-1&&(t=o-1,t-e+1>=A&&I.push([e,t]),e=-1)}return g[o-1]&&o-e>=A&&I.push([e,o-1]),I}function two(g,A,I,{location:e=rQ.location,distance:t=rQ.distance,threshold:o=rQ.threshold,findAllMatches:B=rQ.findAllMatches,minMatchCharLength:C=rQ.minMatchCharLength,includeMatches:Q=rQ.includeMatches,ignoreLocation:i=rQ.ignoreLocation}={}){if(A.length>32)throw new Error(Wyo(32));const E=A.length,n=g.length,s=Math.max(0,Math.min(e,n));let r=o,a=s;const c=(p,k)=>{const S=p/E;if(i)return S;const R=Math.abs(s-k);return t?S+R/t:R?1:S},h=C>1||Q,l=h?Array(n):[];let D;for(;(D=g.indexOf(A,a))>-1;){const p=c(0,D);if(r=Math.min(p,r),a=D+E,h){let k=0;for(;k<E;)l[D+k]=1,k+=1}}a=-1;let d=[],y=1,w=0,u=E+n;const G=1<<E-1;for(let p=0;p<E;p+=1){let k=0,S=u;for(;k<S;)c(p,s+S)<=r?k=S:u=S,S=Math.floor((u-k)/2+k);u=S;let R=Math.max(1,s-S+1);const x=B?n:Math.min(s+S,n)+E,N=Array(x+2);N[x+1]=(1<<p)-1;for(let U=x;U>=R;U-=1){const K=U-1,_=I[g[K]];if(N[U]=(N[U+1]<<1|1)&_,p&&(N[U]|=(d[U+1]|d[U])<<1|1|d[U+1]),N[U]&G&&(y=c(p,K),y<=r)){if(r=y,a=K,w=p,a<=s)break;R=Math.max(1,2*s-a)}}if(c(p+1,s)>r)break;d=N}if(h&&a>=0){const p=Math.min(n-1,a+E-1+w);for(let k=a;k<=p;k+=1)I[g[k]]&&(l[k]=1)}const m={isMatch:a>=0,score:Math.max(.001,y)};if(h){const p=ewo(l,C);p.length?Q&&(m.indices=p):m.isMatch=!1}return m}function owo(g){const A={};for(let I=0,e=g.length;I<e;I+=1){const t=g.charAt(I);A[t]=(A[t]||0)|1<<e-I-1}return A}function uog(g){if(g.length<=1)return g;g.sort((I,e)=>I[0]-e[0]||I[1]-e[1]);const A=[g[0]];for(let I=1,e=g.length;I<e;I+=1){const t=A[A.length-1],o=g[I];o[0]<=t[1]+1?t[1]=Math.max(t[1],o[1]):A.push(o)}return A}const GFI={ł:"l",Ł:"L",đ:"d",Đ:"D",ø:"o",Ø:"O",ħ:"h",Ħ:"H",ŧ:"t",Ŧ:"T",ı:"i",ß:"ss"},Bwo=new RegExp("["+Object.keys(GFI).join("")+"]","g"),XeA=typeof String.prototype.normalize=="function"?g=>g.normalize("NFD").replace(/[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C04\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u192B\u1930-\u193B\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F]/g,"").replace(Bwo,A=>GFI[A]):g=>g;var Gog=class{constructor(g,{location:A=rQ.location,threshold:I=rQ.threshold,distance:e=rQ.distance,includeMatches:t=rQ.includeMatches,findAllMatches:o=rQ.findAllMatches,minMatchCharLength:B=rQ.minMatchCharLength,isCaseSensitive:C=rQ.isCaseSensitive,ignoreDiacritics:Q=rQ.ignoreDiacritics,ignoreLocation:i=rQ.ignoreLocation}={}){if(this.options={location:A,threshold:I,distance:e,includeMatches:t,findAllMatches:o,minMatchCharLength:B,isCaseSensitive:C,ignoreDiacritics:Q,ignoreLocation:i},g=C?g:g.toLowerCase(),g=Q?XeA(g):g,this.pattern=g,this.chunks=[],!this.pattern.length)return;const E=(s,r)=>{this.chunks.push({pattern:s,alphabet:owo(s),startIndex:r})},n=this.pattern.length;if(n>32){let s=0;const r=n%32,a=n-r;for(;s<a;)E(this.pattern.substr(s,32),s),s+=32;if(r){const c=n-32;E(this.pattern.substr(c),c)}}else E(this.pattern,0)}searchIn(g){const{isCaseSensitive:A,ignoreDiacritics:I,includeMatches:e}=this.options;if(g=A?g:g.toLowerCase(),g=I?XeA(g):g,this.pattern===g){if(g.length<this.options.minMatchCharLength)return{isMatch:!1,score:1};const a={isMatch:!0,score:0};return e&&(a.indices=[[0,g.length-1]]),a}const{location:t,distance:o,threshold:B,findAllMatches:C,minMatchCharLength:Q,ignoreLocation:i}=this.options,E=[];let n=0,s=!1;this.chunks.forEach(({pattern:a,alphabet:c,startIndex:h})=>{const{isMatch:l,score:D,indices:d}=two(g,a,c,{location:t+h,distance:o,threshold:B,findAllMatches:C,minMatchCharLength:Q,includeMatches:e,ignoreLocation:i});l&&(s=!0),n+=D,l&&d&&E.push(...d)});const r={isMatch:s,score:s?n/this.chunks.length:1};return s&&e&&(r.indices=uog(E)),r}};const Cwo=new Set(["fuzzy","include"]);function Qwo(g){return g.startsWith("inverse")}const mog=[{type:"exact",multiRegex:/^="(.*)"$/,singleRegex:/^=(.*)$/,create:g=>({type:"exact",search(A){const I=A===g;return{isMatch:I,score:I?0:1,indices:[0,g.length-1]}}})},{type:"include",multiRegex:/^'"(.*)"$/,singleRegex:/^'(.*)$/,create:g=>({type:"include",search(A){let I=0,e;const t=[],o=g.length;for(;(e=A.indexOf(g,I))>-1;)I=e+o,t.push([e,I-1]);const B=!!t.length;return{isMatch:B,score:B?0:1,indices:t}}})},{type:"prefix-exact",multiRegex:/^\^"(.*)"$/,singleRegex:/^\^(.*)$/,create:g=>({type:"prefix-exact",search(A){const I=A.startsWith(g);return{isMatch:I,score:I?0:1,indices:[0,g.length-1]}}})},{type:"inverse-prefix-exact",multiRegex:/^!\^"(.*)"$/,singleRegex:/^!\^(.*)$/,create:g=>({type:"inverse-prefix-exact",search(A){const I=!A.startsWith(g);return{isMatch:I,score:I?0:1,indices:[0,A.length-1]}}})},{type:"inverse-suffix-exact",multiRegex:/^!"(.*)"\$$/,singleRegex:/^!(.*)\$$/,create:g=>({type:"inverse-suffix-exact",search(A){const I=!A.endsWith(g);return{isMatch:I,score:I?0:1,indices:[0,A.length-1]}}})},{type:"suffix-exact",multiRegex:/^"(.*)"\$$/,singleRegex:/^(.*)\$$/,create:g=>({type:"suffix-exact",search(A){const I=A.endsWith(g);return{isMatch:I,score:I?0:1,indices:[A.length-g.length,A.length-1]}}})},{type:"inverse-exact",multiRegex:/^!"(.*)"$/,singleRegex:/^!(.*)$/,create:g=>({type:"inverse-exact",search(A){const I=A.indexOf(g)===-1;return{isMatch:I,score:I?0:1,indices:[0,A.length-1]}}})},{type:"fuzzy",multiRegex:/^"(.*)"$/,singleRegex:/^(.*)$/,create:(g,A={})=>{const I=new Gog(g,{location:A.location??rQ.location,threshold:A.threshold??rQ.threshold,distance:A.distance??rQ.distance,includeMatches:A.includeMatches??rQ.includeMatches,findAllMatches:A.findAllMatches??rQ.findAllMatches,minMatchCharLength:A.minMatchCharLength??rQ.minMatchCharLength,isCaseSensitive:A.isCaseSensitive??rQ.isCaseSensitive,ignoreDiacritics:A.ignoreDiacritics??rQ.ignoreDiacritics,ignoreLocation:A.ignoreLocation??rQ.ignoreLocation});return{type:"fuzzy",search(e){return I.searchIn(e)}}}}],mFI=mog.length,iwo="\0",Ewo="|";function nwo(g){const A=[],I=g.length;let e=0;for(;e<I;){for(;e<I&&g[e]===" ";)e++;if(e>=I)break;let t=e;for(;t<I&&g[t]!==" "&&g[t]!=='"';)t++;if(t<I&&g[t]==='"'){for(t++;t<I;){if(g[t]==='"'){const o=t+1;if(o>=I||g[o]===" "){t++;break}if(g[o]==="$"&&(o+1>=I||g[o+1]===" ")){t+=2;break}}t++}A.push(g.substring(e,t)),e=t}else{for(;t<I&&g[t]!==" ";)t++;A.push(g.substring(e,t)),e=t}}return A}function pFI(g,A){const I=g.match(A);return I?I[1]:null}function swo(g,A={}){return g.replace(/\\\|/g,iwo).split(Ewo).map(I=>{const e=nwo(I.replace(/\u0000/g,"|").trim()).filter(o=>o&&!!o.trim()),t=[];for(let o=0,B=e.length;o<B;o+=1){const C=e[o];let Q=!1,i=-1;for(;!Q&&++i<mFI;){const E=mog[i],n=pFI(C,E.multiRegex);n&&(t.push(E.create(n,A)),Q=!0)}if(!Q)for(i=-1;++i<mFI;){const E=mog[i],n=pFI(C,E.singleRegex);if(n){t.push(E.create(n,A));break}}}return t})}var awo=class{constructor(g,{isCaseSensitive:A=rQ.isCaseSensitive,ignoreDiacritics:I=rQ.ignoreDiacritics,includeMatches:e=rQ.includeMatches,minMatchCharLength:t=rQ.minMatchCharLength,ignoreLocation:o=rQ.ignoreLocation,findAllMatches:B=rQ.findAllMatches,location:C=rQ.location,threshold:Q=rQ.threshold,distance:i=rQ.distance}={}){this.query=null,this.options={isCaseSensitive:A,ignoreDiacritics:I,includeMatches:e,minMatchCharLength:t,findAllMatches:B,ignoreLocation:o,location:C,threshold:Q,distance:i},g=A?g:g.toLowerCase(),g=I?XeA(g):g,this.pattern=g,this.query=swo(this.pattern,this.options)}static condition(g,A){return A.useExtendedSearch}searchIn(g){const A=this.query;if(!A)return{isMatch:!1,score:1};const{includeMatches:I,isCaseSensitive:e,ignoreDiacritics:t}=this.options;g=e?g:g.toLowerCase(),g=t?XeA(g):g;let o=0;const B=[];let C=0,Q=!1;for(let i=0,E=A.length;i<E;i+=1){const n=A[i];B.length=0,o=0,Q=!1;for(let s=0,r=n.length;s<r;s+=1){const a=n[s],{isMatch:c,indices:h,score:l}=a.search(g);if(c)o+=1,C+=l,Qwo(a.type)&&(Q=!0),I&&(Cwo.has(a.type)?B.push(...h):B.push(h));else{C=0,o=0,B.length=0,Q=!1;break}}if(o){const s={isMatch:!0,score:C/o};return Q&&(s.hasInverse=!0),I&&(s.indices=uog(B)),s}}return{isMatch:!1,score:1}}};const pog=[];function kog(...g){pog.push(...g)}function mGA(g,A){for(let I=0,e=pog.length;I<e;I+=1){const t=pog[I];if(t.condition(g,A))return new t(g,A)}return new Gog(g,A)}const pGA={AND:"$and",OR:"$or"},Mog={PATH:"$path",PATTERN:"$val"},Sog=g=>!!(g[pGA.AND]||g[pGA.OR]),rwo=g=>!!g[Mog.PATH],cwo=g=>!z3(g)&&lFI(g)&&!Sog(g),kFI=g=>({[pGA.AND]:Object.keys(g).map(A=>({[A]:g[A]}))});function MFI(g,A,{auto:I=!0}={}){const e=t=>{if(CG(t)){const Q={keyId:null,pattern:t};return I&&(Q.searcher=mGA(t,A)),Q}const o=Object.keys(t),B=rwo(t);if(!B&&o.length>1&&!Sog(t))return e(kFI(t));if(cwo(t)){const Q=B?t[Mog.PATH]:o[0],i=B?t[Mog.PATTERN]:t[Q];if(!CG(i))throw new Error(Oyo(Q));const E={keyId:GGA(Q),pattern:i};return I&&(E.searcher=mGA(i,A)),E}const C={children:[],operator:o[0]};return o.forEach(Q=>{const i=t[Q];z3(i)&&i.forEach(E=>{C.children.push(e(E))})}),C};return Sog(g)||(g=kFI(g)),e(g)}function fog(g,{ignoreFieldNorm:A=rQ.ignoreFieldNorm}){let I=1;return g.forEach(({key:e,norm:t,score:o})=>{const B=e?e.weight:null;I*=Math.pow(o===0&&B?Number.EPSILON:o,(B||1)*(A?1:t))}),I}function hwo(g,{ignoreFieldNorm:A=rQ.ignoreFieldNorm}){g.forEach(I=>{I.score=fog(I.matches,{ignoreFieldNorm:A})})}var lwo=class{constructor(g,A){this.limit=g,this.heap=[],this.comparator=A}get size(){return this.heap.length}insert(g){this.size<this.limit?(this.heap.push(g),this._bubbleUp(this.size-1)):this.comparator(g,this.heap[0])<0&&(this.heap[0]=g,this._sinkDown(0))}extractSorted(){return this.heap.sort(this.comparator)}_bubbleUp(g){const A=this.heap;for(;g>0;){const I=g-1>>1;if(this.comparator(A[g],A[I])<=0)break;const e=A[g];A[g]=A[I],A[I]=e,g=I}}_sinkDown(g){const A=this.heap,I=A.length;let e=g;do{g=e;const t=2*g+1,o=2*g+2;if(t<I&&this.comparator(A[t],A[e])>0&&(e=t),o<I&&this.comparator(A[o],A[e])>0&&(e=o),e!==g){const B=A[g];A[g]=A[e],A[e]=B}}while(e!==g)}};function Dwo(g){const A=[];return g.matches.forEach(I=>{if(!hS(I.indices)||!I.indices.length)return;const e={indices:I.indices,value:I.value};I.key&&(e.key=I.key.id),I.idx>-1&&(e.refIndex=I.idx),A.push(e)}),A}function dwo(g,A,{includeMatches:I=rQ.includeMatches,includeScore:e=rQ.includeScore}={}){return g.map(t=>{const{idx:o}=t,B={item:A[o],refIndex:o};return I&&(B.matches=Dwo(t)),e&&(B.score=t.score),B})}const ywo=/[\p{L}\p{M}\p{N}_]+/gu,SFI=new WeakSet;function wwo(g){SFI.has(g)||(SFI.add(g),console.warn(`[Fuse] tokenize regex ${g} lacks the global flag; only the first match per text will be returned. Add the 'g' flag.`))}function uwo(g){if(typeof g=="function"){let A=!1;return I=>{const e=g(I);if(!A&&(A=!0,!Array.isArray(e)||e.some(t=>typeof t!="string")))throw new Error(`[Fuse] tokenize function must return string[]; received ${Array.isArray(e)?"array containing non-strings":typeof e}.`);return e}}return g instanceof RegExp?(g.global||wwo(g),A=>A.match(g)||[]):A=>A.match(ywo)||[]}function Rog({isCaseSensitive:g=!1,ignoreDiacritics:A=!1,tokenize:I}={}){const e=uwo(I);return{tokenize(t){return g||(t=t.toLowerCase()),A&&(t=XeA(t)),e(t)}}}var Gwo=class{static condition(g,A){return A.useTokenSearch}constructor(g,A){this.options=A,this.analyzer=Rog({isCaseSensitive:A.isCaseSensitive,ignoreDiacritics:A.ignoreDiacritics,tokenize:A.tokenize});const I=this.analyzer.tokenize(g),{df:e,fieldCount:t}=A._invertedIndex;this.termSearchers=[],this.idfWeights=[];for(const o of I){this.termSearchers.push(new Gog(o,{location:A.location,threshold:A.threshold,distance:A.distance,includeMatches:A.includeMatches,findAllMatches:A.findAllMatches,minMatchCharLength:A.minMatchCharLength,isCaseSensitive:A.isCaseSensitive,ignoreDiacritics:A.ignoreDiacritics,ignoreLocation:!0}));const B=e.get(o)||0,C=Math.log(1+(t-B+.5)/(B+.5));this.idfWeights.push(C)}this.combineAll=A.tokenMatch==="all",this.numTerms=this.termSearchers.length,this.useMask=this.numTerms<=31}searchIn(g){if(!this.termSearchers.length)return{isMatch:!1,score:1};const A=[];let I=0,e=0,t=0,o=0;const B=this.combineAll&&!this.useMask?new Set:null;for(let i=0;i<this.termSearchers.length;i++){const E=this.termSearchers[i].searchIn(g),n=this.idfWeights[i];e+=n,E.isMatch&&(t++,I+=n*(1-E.score),E.indices&&A.push(...E.indices),this.combineAll&&(this.useMask?o|=1<<i:B.add(i)))}if(t===0)return{isMatch:!1,score:1};const C=e>0?1-I/e:0,Q={isMatch:!0,score:Math.max(.001,C)};return this.options.includeMatches&&A.length&&(Q.indices=uog(A)),this.combineAll&&(this.useMask?Q.matchedMask=o:Q.matchedTerms=B,Q.termCount=this.numTerms),Q}};function Nog(g,A,I,e){const t=e.tokenize(A);if(!t.length)return;g.fieldCount++,g.docFieldCount.set(I,(g.docFieldCount.get(I)||0)+1);const o=new Set(t);let B=g.docTermFieldHits.get(I);B||(B=new Map,g.docTermFieldHits.set(I,B));for(const C of o)B.set(C,(B.get(C)||0)+1),g.df.set(C,(g.df.get(C)||0)+1)}function fFI(g,A,I,e){const{i:t,v:o,$:B}=A;if(o!==void 0){Nog(g,o,t,e);return}if(B)for(let C=0;C<I;C++){const Q=B[C];if(Q)if(Array.isArray(Q))for(const i of Q)Nog(g,i.v,t,e);else Nog(g,Q.v,t,e)}}function mwo(g,A,I){const e={fieldCount:0,df:new Map,docFieldCount:new Map,docTermFieldHits:new Map};for(const t of g)fFI(e,t,A,I);return e}function pwo(g,A,I,e){fFI(g,A,I,e)}function kwo(g,A){const I=g.docFieldCount.get(A);if(I===void 0)return;g.fieldCount-=I,g.docFieldCount.delete(A);const e=g.docTermFieldHits.get(A);if(e){for(const[t,o]of e){const B=(g.df.get(t)||0)-o;B<=0?g.df.delete(t):g.df.set(t,B)}g.docTermFieldHits.delete(A)}}function RFI(g,A){if(A.length===0)return;const I=Array.from(new Set(A)).sort((C,Q)=>C-Q);for(const C of I)kwo(g,C);const e=C=>{let Q=0,i=I.length;for(;Q<i;){const E=Q+i>>>1;I[E]<C?Q=E+1:i=E}return C-Q},t=I[0],o=new Map;for(const[C,Q]of g.docFieldCount)o.set(C>t?e(C):C,Q);g.docFieldCount=o;const B=new Map;for(const[C,Q]of g.docTermFieldHits)B.set(C>t?e(C):C,Q);g.docTermFieldHits=B}var X3=class{constructor(g,A,I){this.options={...rQ,...A},this.options.useExtendedSearch,this.options.useTokenSearch,this._keyStore=new Xyo(this.options.keys),this._docs=g,this._myIndex=null,this._invertedIndex=null,this.setCollection(g,I),this._lastQuery=null,this._lastSearcher=null}_getSearcher(g){if(this._lastQuery===g)return this._lastSearcher;const A=mGA(g,this._invertedIndex?{...this.options,_invertedIndex:this._invertedIndex}:this.options);return this._lastQuery=g,this._lastSearcher=A,A}setCollection(g,A){if(this._docs=g,A&&!(A instanceof wog))throw new Error(Zyo);if(this._myIndex=A||uFI(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight}),this.options.useTokenSearch){const I=Rog({isCaseSensitive:this.options.isCaseSensitive,ignoreDiacritics:this.options.ignoreDiacritics,tokenize:this.options.tokenize});this._invertedIndex=mwo(this._myIndex.records,this._myIndex.keys.length,I)}this._invalidateSearcherCache()}add(g){if(!hS(g))return;this._docs.push(g);const A=this._myIndex.add(g,this._docs.length-1);if(this._invertedIndex&&A){const I=Rog({isCaseSensitive:this.options.isCaseSensitive,ignoreDiacritics:this.options.ignoreDiacritics,tokenize:this.options.tokenize});pwo(this._invertedIndex,A,this._myIndex.keys.length,I)}this._invalidateSearcherCache()}remove(g=()=>!1){const A=[],I=[];for(let e=0,t=this._docs.length;e<t;e+=1)g(this._docs[e],e)&&(A.push(this._docs[e]),I.push(e));if(I.length){this._invertedIndex&&RFI(this._invertedIndex,I);const e=new Set(I);this._docs=this._docs.filter((t,o)=>!e.has(o)),this._myIndex.removeAll(I),this._invalidateSearcherCache()}return A}removeAt(g){if(!Number.isInteger(g)||g<0||g>=this._docs.length)throw new Error(yog);this._invertedIndex&&RFI(this._invertedIndex,[g]);const A=this._docs.splice(g,1)[0];return this._myIndex.removeAt(g),this._invalidateSearcherCache(),A}_invalidateSearcherCache(){this._lastQuery=null,this._lastSearcher=null}getIndex(){return this._myIndex}_normalizedKeys(){return this._myIndex.keys.map(g=>this._keyStore.get(g.id)||g)}search(g,A){const{limit:I=-1}=A||{},{includeMatches:e,includeScore:t,shouldSort:o,sortFn:B,ignoreFieldNorm:C}=this.options;if(CG(g)&&!g.trim()){let s=this._docs.map((r,a)=>({item:r,refIndex:a}));return wGA(I)&&I>-1&&(s=s.slice(0,I)),s}const Q=o&&wGA(I)&&I>0&&CG(g),i=B,E=(s,r)=>i(s,r)||s.idx-r.idx;let n;if(Q){const s=new lwo(I,E);CG(this._docs[0])?this._searchStringList(g,{heap:s,ignoreFieldNorm:C}):this._searchObjectList(g,{heap:s,ignoreFieldNorm:C}),n=s.extractSorted()}else n=CG(g)?CG(this._docs[0])?this._searchStringList(g):this._searchObjectList(g):this._searchLogical(g),hwo(n,{ignoreFieldNorm:C}),o&&n.sort(CG(g)?E:i),wGA(I)&&I>-1&&(n=n.slice(0,I));return dwo(n,this._docs,{includeMatches:e,includeScore:t})}_searchStringList(g,{heap:A,ignoreFieldNorm:I}={}){const e=this._getSearcher(g),t=this.options.useTokenSearch&&this.options.tokenMatch==="all",{records:o}=this._myIndex,B=A?null:[];return o.forEach(({v:C,i:Q,n:i})=>{if(!hS(C))return;const E=e.searchIn(C);if(E.isMatch){const n={score:E.score,value:C,norm:i,indices:E.indices};t&&(n.matchedMask=E.matchedMask,n.matchedTerms=E.matchedTerms,n.termCount=E.termCount);const s=[n];if(!t||this._coversAllTokens(s)){const r={item:C,idx:Q,matches:s};A?(r.score=fog(r.matches,{ignoreFieldNorm:I}),A.insert(r)):B.push(r)}}}),B}_searchLogical(g){const A=MFI(g,this.options),I=this._normalizedKeys(),e=(C,Q,i)=>{if(!("children"in C)){const{keyId:r,searcher:a}=C;let c;return r===null?(c=[],I.forEach((h,l)=>{c.push(...this._findMatches({key:h,value:Q[l],searcher:a}))})):c=this._findMatches({key:this._keyStore.get(r),value:this._myIndex.getValueForItemAtKeyId(Q,r),searcher:a}),c&&c.length?[{idx:i,item:Q,matches:c}]:[]}const{children:E,operator:n}=C,s=[];for(let r=0,a=E.length;r<a;r+=1){const c=E[r],h=e(c,Q,i);if(h.length)s.push(...h);else if(n===pGA.AND)return[]}return s},t=this._myIndex.records,o=new Map,B=[];return t.forEach(({$:C,i:Q})=>{if(hS(C)){const i=e(A,C,Q);i.length&&(o.has(Q)||(o.set(Q,{idx:Q,item:C,matches:[]}),B.push(o.get(Q))),i.forEach(({matches:E})=>{o.get(Q).matches.push(...E)}))}}),B}_searchObjectList(g,{heap:A,ignoreFieldNorm:I}={}){const e=this._getSearcher(g),t=this.options.useTokenSearch&&this.options.tokenMatch==="all",{records:o}=this._myIndex,B=this._normalizedKeys(),C=A?null:[];return o.forEach(({$:Q,i})=>{if(!hS(Q))return;const E=[];let n=!1,s=!1;if(B.forEach((r,a)=>{const c=this._findMatches({key:r,value:Q[a],searcher:e});c.length?(E.push(...c),c[0].hasInverse&&(s=!0)):n=!0}),!(s&&n)&&E.length&&(!t||this._coversAllTokens(E))){const r={idx:i,item:Q,matches:E};A?(r.score=fog(r.matches,{ignoreFieldNorm:I}),A.insert(r)):C.push(r)}}),C}_findMatches({key:g,value:A,searcher:I}){if(!hS(A))return[];const e=[];if(z3(A))A.forEach(({v:t,i:o,n:B})=>{if(!hS(t))return;const C=I.searchIn(t);if(C.isMatch){const Q={score:C.score,key:g,value:t,idx:o,norm:B,indices:C.indices,hasInverse:C.hasInverse};C.termCount!==void 0&&(Q.matchedMask=C.matchedMask,Q.matchedTerms=C.matchedTerms,Q.termCount=C.termCount),e.push(Q)}});else{const{v:t,n:o}=A,B=I.searchIn(t);if(B.isMatch){const C={score:B.score,key:g,value:t,norm:o,indices:B.indices,hasInverse:B.hasInverse};B.termCount!==void 0&&(C.matchedMask=B.matchedMask,C.matchedTerms=B.matchedTerms,C.termCount=B.termCount),e.push(C)}}return e}_coversAllTokens(g){const A=g.length?g[0].termCount:void 0;if(A===void 0)return!0;if(A<=31){let e=0;for(let t=0;t<g.length;t++)e|=g[t].matchedMask||0;return e===2**A-1}const I=new Set;for(let e=0;e<g.length;e++){const t=g[e].matchedTerms;if(t)for(const o of t)I.add(o)}return I.size===A}};X3.version="7.5.0",X3.createIndex=uFI,X3.parseIndex=Iwo,X3.config=rQ,X3.match=function(g,A,I){if(I&&I.useTokenSearch)throw new Error(zyo);return mGA(g,{...rQ,...I}).searchIn(A)},X3.parseQuery=MFI,kog(awo),kog(Gwo),X3.use=function(...g){g.forEach(A=>kog(A))};var Mwo=X3;const Swo="https://kicad-mod-cache.tscircuit.com";let xog=null,$eA=null,Fog=null;const fwo=async()=>xog||$eA||($eA=fetch("https://kicad-mod-cache.tscircuit.com/kicad_files.json").then(g=>g.json()).then(g=>(xog=g,$eA=null,g)),$eA),Rwo=async(g,A=20)=>{const I=await fwo();return Fog||(Fog=new Mwo(I)),Fog.search(g).slice(0,A).map(e=>e.item)},Nwo=g=>{const A=g.replace(".pretty/","/").replace(".kicad_mod",""),I=`kicad:${A}`;return{path:g,qualifiedName:I,description:A}},xwo=g=>g.replace(/^\/+/,"").split("/").map(A=>encodeURIComponent(A)).join("/"),Fwo=async g=>{const A=await fetch(`${Swo}/${xwo(g)}`);if(!A.ok)throw new Error(`KiCad footprint fetch failed: ${A.status}`);const I=await A.text(),{KicadFootprintToCircuitJsonConverter:e}=await cS("kicad-to-circuit-json"),t=new e;return t.addFile(g.split("/").pop()??"selected-footprint.kicad_mod",I),t.runUntilFinished(),t.getOutput()},NFI=g=>g?.source==="jlcpcb"||g?.source==="kicad",Uwo=async(g,A)=>{if(g.source==="jlcpcb")return Hyo(g.component.partNumber,A?.jlcpcb);if(g.source==="kicad")return Fwo(g.footprint.path);throw new Error("Footprint preview is not available for this source")},Jwo=({query:g,placeholder:A,isSearching:I,onQueryChange:e,onSubmit:t})=>{const o=z.useCallback(B=>{B.key==="Enter"&&(B.preventDefault(),t())},[t]);return q.jsxs("div",{className:"rf-flex rf-items-center rf-gap-2 rf-mt-4",children:[q.jsxs("div",{className:"rf-relative rf-flex-grow",children:[q.jsx(keg,{className:"rf-absolute rf-left-2 rf-top-2.5 rf-h-4 rf-w-4 rf-text-muted-foreground"}),q.jsx(Xtg,{placeholder:A,className:"rf-pl-8",spellCheck:!1,autoComplete:"off",value:g,onChange:B=>e(B.target.value),onKeyDown:o})]}),q.jsx(Ei,{onClick:t,disabled:I||g.trim().length<1,className:"sm:rf-px-4 rf-px-3",children:I?q.jsx(iS,{className:"rf-h-4 rf-w-4 rf-animate-spin"}):q.jsxs(q.Fragment,{children:[q.jsx(keg,{className:"rf-h-4 rf-w-4 sm:rf-hidden"}),q.jsx("span",{className:"rf-hidden sm:rf-inline",children:"Search"})]})})]})},Pwo=new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}),Kwo=g=>Pwo.format(g),xFI=g=>{switch(g.source){case"tscircuit.com":{const A=g.package;return`tscircuit-${A.package_id??`${A.org_owner_tscircuit_handle??"unknown"}-${A.unscoped_name??A.name??"package"}`}`}case"jlcpcb":return`jlc-${g.component.lcscId}`;case"kicad":return`kicad-${g.footprint.path}`;default:return"unknown"}},Lwo=g=>{switch(g.source){case"tscircuit.com":return g.package.unscoped_name;case"jlcpcb":return g.component.isDirectLookup?g.component.partNumber:g.component.manufacturer;case"kicad":return g.footprint.qualifiedName}},Ywo=g=>{switch(g.source){case"tscircuit.com":return g.package.description||(g.package.org_owner_tscircuit_handle?`Component by ${g.package.org_owner_tscircuit_handle}`:void 0);case"jlcpcb":return g.component.description;case"kicad":return g.footprint.description}},_wo=g=>{switch(g.source){case"tscircuit.com":return g.package.name;case"jlcpcb":return g.component.isDirectLookup?void 0:g.component.partNumber;case"kicad":return}},bwo=({results:g,selected:A,onSelect:I,onShowDetails:e})=>{const t=A?xFI(A):null;return q.jsx("div",{className:"rf-divide-y rf-w-full rf-overflow-hidden",children:g.map(o=>{const B=xFI(o),C=t===B,Q=Lwo(o),i=Ywo(o),E=_wo(o),n=o.source==="jlcpcb"?o.component.stock:null,s=o.source==="jlcpcb"?o.component.price:null,r=o.source==="jlcpcb"?o.component.isBasic:null,a=o.source==="jlcpcb"?o.component.isDirectLookup:!1;return q.jsxs("div",{className:`rf-p-3 rf-flex rf-flex-col sm:rf-grid sm:rf-grid-cols-[minmax(0,1fr)_auto] rf-items-start sm:rf-items-center rf-cursor-pointer hover:rf-bg-zinc-100 rf-gap-2 rf-overflow-hidden ${C?"rf-bg-zinc-100":""}`,onClick:()=>I(o),children:[q.jsxs("div",{className:"rf-min-w-0 rf-overflow-hidden rf-w-full",children:[q.jsxs("div",{className:"rf-flex rf-items-start rf-gap-2 rf-min-w-0",children:[q.jsxs("div",{className:"rf-font-medium rf-text-sm rf-truncate rf-flex-1 rf-min-w-0 rf-flex rf-items-center rf-gap-1.5",children:[Q,o.source==="jlcpcb"&&r!=null&&q.jsx("span",{className:`rf-text-xs rf-px-1.5 rf-py-0.5 rf-rounded rf-font-medium rf-flex-shrink-0 ${r?"rf-bg-green-100 rf-text-green-700":"rf-bg-orange-100 rf-text-orange-700"}`,children:r?"Basic":"Extended"}),a&&q.jsx("span",{className:"rf-text-xs rf-px-1.5 rf-py-0.5 rf-rounded rf-font-medium rf-flex-shrink-0 rf-bg-blue-100 rf-text-blue-700",children:"Direct lookup"}),o.source==="tscircuit.com"&&o.package.is_private&&q.jsx(oio,{className:"rf-ml-1 rf-h-3 rf-w-3 rf-text-zinc-400 rf-flex-shrink-0"})]}),o.source==="jlcpcb"&&n!=null?q.jsxs("div",{className:"rf-text-xs rf-text-zinc-500 rf-font-medium rf-whitespace-nowrap rf-flex-shrink-0 sm:rf-hidden",children:[n.toLocaleString()," in stock"]}):null]}),q.jsxs("div",{className:"rf-text-xs rf-text-zinc-500 rf-truncate rf-w-full",children:[E?q.jsx("span",{className:"rf-mr-2",children:E}):null,i]})]}),q.jsxs("div",{children:[o.source==="tscircuit.com"&&e?q.jsx("div",{className:"rf-flex-shrink-0 rf-w-full sm:rf-w-auto",children:q.jsx(Ei,{variant:"outline",size:"sm",className:"rf-text-xs rf-w-full sm:rf-w-auto",onClick:c=>{c.stopPropagation(),e(o)},children:"See Details"})}):o.source==="jlcpcb"&&n!=null?q.jsxs("div",{className:"rf-hidden sm:rf-block rf-text-xs rf-text-zinc-500 rf-font-medium rf-whitespace-nowrap rf-flex-shrink-0",children:[n.toLocaleString()," in stock"]}):null,s!=null&&q.jsx("div",{className:"rf-hidden sm:rf-block rf-text-xs rf-text-zinc-500 rf-font-medium rf-whitespace-nowrap rf-flex-shrink-0 rf-text-right",children:Kwo(s)})]})]},B)})})},Hwo=({circuitJson:g,error:A,isLoading:I,height:e})=>q.jsx("section",{className:"rf-flex rf-min-w-0 rf-items-center rf-justify-center",style:{height:e},children:I?q.jsxs("div",{className:"rf-flex rf-w-full rf-items-center rf-justify-center rf-gap-2 rf-bg-zinc-950 rf-text-sm rf-text-zinc-300",style:{height:e},children:[q.jsx(iS,{className:"rf-h-4 rf-w-4 rf-animate-spin"}),"Loading preview..."]}):A?q.jsx("div",{className:"rf-flex rf-w-full rf-items-center rf-justify-center rf-bg-zinc-950 rf-p-4",style:{height:e},children:q.jsxs("div",{className:"rf-flex rf-max-w-[320px] rf-items-start rf-gap-2 rf-text-sm rf-text-zinc-300",children:[q.jsx(meg,{className:"rf-mt-0.5 rf-h-4 rf-w-4 rf-flex-shrink-0"}),q.jsx("span",{children:A})]})}):g?q.jsx("div",{className:"rf-w-full rf-min-w-0 rf-overflow-hidden",children:q.jsx(weg,{circuitJson:g,height:e,allowEditing:!1,clickToInteractEnabled:!1,focusOnHover:!1,disablePcbGroups:!0})}):q.jsx("div",{className:"rf-flex rf-w-full rf-items-center rf-justify-center rf-bg-zinc-950 rf-text-sm rf-text-zinc-300",style:{height:e},children:"No preview"})}),FFI={importComponentDialog:101,importComponentDetailsDialog:102},vwo=({packageResult:g,isOpen:A,onOpenChange:I,isLoading:e,details:t,previewTab:o,onPreviewTabChange:B,isSubmitting:C,onImport:Q})=>{const i=g?.package??null,E=i?.latest_pcb_preview_image_url,n=i?.latest_sch_preview_image_url,s=i?.latest_cad_preview_image_url,r=i?.unscoped_name?.split("/").pop()??i?.unscoped_name,a=i?.org_owner_tscircuit_handle??void 0,c=a?`https://tscircuit.com/${a}`:void 0,h=a&&r?`https://tscircuit.com/${a}/${r}`:void 0;return q.jsx(j5,{open:A,onOpenChange:I,children:q.jsxs(W3,{showOverlay:!1,style:{width:"calc(100vw - 2rem)",zIndex:FFI.importComponentDetailsDialog},className:"rf-max-w-5xl no-scrollbar !rf-overflow-y-auto rf-max-h-[90vh] rf-overflow-hidden rf-flex rf-flex-col rf-rounded-sm",children:[q.jsx(V3,{className:"rf-pb-4 rf-border-b",children:q.jsx("div",{className:"rf-flex rf-items-start rf-justify-between rf-gap-4",children:q.jsxs("div",{className:"rf-flex-1 rf-min-w-0",children:[q.jsx(j3,{className:"rf-text-xl rf-font-semibold rf-truncate",children:r}),q.jsx(z5,{children:i?.description})]})})}),q.jsxs("div",{className:"rf-flex-1 rf-overflow-y-auto rf-py-4 rf-space-y-6",children:[a?q.jsxs("div",{children:[q.jsx("span",{className:"rf-text-xs rf-font-medium rf-text-gray-500 rf-uppercase rf-tracking-wide",children:"Created by"}),q.jsx("div",{className:"rf-mt-1 rf-text-sm rf-font-medium",children:c?q.jsx("a",{href:c,target:"_blank",rel:"noopener noreferrer",className:"rf-text-black hover:rf-underline",children:a}):a})]}):null,(s||E||n)&&q.jsx(q.Fragment,{children:q.jsxs("div",{children:[q.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-mb-4",children:"Preview"}),q.jsxs(A6A,{value:o,onValueChange:l=>B(l),children:[q.jsxs(ylA,{className:"rf-inline-flex rf-h-9 rf-items-center rf-justify-center rf-rounded-lg rf-bg-zinc-100 rf-p-1 rf-text-zinc-500 dark:rf-bg-zinc-800 dark:rf-text-zinc-400",children:[E&&q.jsx(gx,{value:"pcb",children:"PCB"}),n&&q.jsx(gx,{value:"schematic",children:"Schematic"}),s&&q.jsx(gx,{value:"3d",children:"3D"})]}),q.jsxs("div",{className:"rf-mt-4",children:[q.jsx(py,{value:"pcb",className:"rf-border rf-rounded-lg rf-overflow-hidden rf-bg-gray-50",children:E?q.jsx("img",{src:E,alt:`${r??"package"} PCB preview`,className:"rf-w-full rf-h-full rf-object-contain rf-bg-white rf-p-4"}):null}),q.jsx(py,{value:"schematic",className:"rf-border rf-rounded-lg rf-overflow-hidden rf-bg-gray-50",children:n?q.jsx("img",{src:n,alt:`${r??"package"} schematic preview`,className:"rf-w-full rf-h-full rf-object-contain rf-bg-white rf-p-4"}):null}),q.jsx(py,{value:"3d",className:"rf-border rf-rounded-lg rf-overflow-hidden rf-bg-gray-50",children:s?q.jsx("img",{src:s,alt:`${r??"package"} 3D preview`,className:"rf-w-full rf-h-full rf-object-contain rf-bg-white rf-p-4"}):null})]})]})]})}),t?.ai_description?q.jsxs("section",{children:[q.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-mb-3",children:"AI Description"}),q.jsx("div",{className:"rf-bg-gray-50 rf-border rf-border-gray-200 rf-rounded-lg rf-p-4",children:q.jsx("p",{className:"rf-text-sm rf-text-gray-700 rf-leading-relaxed",children:t.ai_description})})]}):null,t?.ai_usage_instructions?q.jsxs("section",{children:[q.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-mb-3",children:"Usage Instructions"}),q.jsx("div",{className:"rf-bg-gray-50 rf-border rf-border-gray-200 rf-rounded-lg rf-p-4",children:q.jsx("p",{className:"rf-text-sm rf-text-gray-700 rf-leading-relaxed rf-whitespace-pre-wrap",children:t.ai_usage_instructions})})]}):null,e?q.jsxs("div",{className:"rf-flex rf-justify-center rf-items-center rf-gap-2 rf-text-gray-500",children:[q.jsx(iS,{className:"rf-h-4 rf-w-4 rf-animate-spin"}),q.jsx("span",{className:"rf-text-sm",children:"Loading package details..."})]}):null]}),q.jsxs(LZ,{className:"rf-pt-4 rf-border-t rf-flex rf-flex-col sm:rf-flex-row rf-justify-between rf-gap-2",children:[q.jsx("div",{className:"rf-flex-1",children:h?q.jsxs(Ei,{variant:"outline",size:"sm",className:"rf-gap-2 rf-w-full sm:rf-w-auto",onClick:()=>window.open(h,"_blank"),children:[q.jsx(XQo,{className:"rf-h-4 rf-w-4"}),"View on tscircuit.com"]}):null}),q.jsxs("div",{className:"rf-flex rf-flex-col sm:rf-flex-row rf-gap-2",children:[q.jsx(Ei,{variant:"outline",onClick:()=>I(!1),className:"rf-order-2 sm:rf-order-1",children:"Close"}),q.jsx(Ei,{onClick:Q,disabled:C,className:"rf-bg-blue-600 hover:rf-bg-blue-700",children:C?q.jsx(iS,{className:"rf-h-4 rf-w-4 rf-animate-spin"}):"Import Component"})]})]})]})})},qwo=()=>{const[g,A]=z.useState(null),[I,e]=z.useState(!1),t=z.useCallback(async(B,C)=>{e(!0);try{const Q=await fetch(`https://api.tscircuit.com/packages/get?name=${encodeURIComponent(`${B}/${C}`)}`);if(!Q.ok)throw new Error(`Failed to load package details: ${Q.status}`);const i=await Q.json();A(i.package??null)}catch(Q){console.error("Failed to fetch package details",Q),A(null)}finally{e(!1)}},[]),o=z.useCallback(()=>{A(null),e(!1)},[]);return{details:g,isLoading:I,fetchDetails:t,reset:o}},Two=(g,A)=>{const[I,e]=z.useState({circuitJson:null,error:null,isLoading:!1});return z.useEffect(()=>{if(!g||!NFI(g)){e({circuitJson:null,error:null,isLoading:!1});return}let t=!1;return e({circuitJson:null,error:null,isLoading:!0}),Uwo(g,A).then(o=>{t||e({circuitJson:o,error:null,isLoading:!1})}).catch(o=>{t||e({circuitJson:null,error:o instanceof Error?o.message:"Failed to load footprint preview",isLoading:!1})}),()=>{t=!0}},[g,A]),I},Zwo=async(g,A)=>{const I={"Content-Type":"application/json"};A&&(I.Authorization=`Bearer ${A}`);const e=await fetch("https://registry-api.tscircuit.com/packages/search",{method:"POST",headers:I,body:JSON.stringify({query:g})});if(!e.ok)throw new Error(`tscircuit registry error: ${e.status}`);return(await e.json()).packages??[]},Owo=({sessionToken:g})=>{const[A,I]=z.useState([]),[e,t]=z.useState(!1),[o,B]=z.useState(null),[C,Q]=z.useState(!1),i=z.useCallback(async n=>{const s=n.trim();if(!s)return[];t(!0),B(null);try{const a=(await Zwo(s,g)).map(c=>({source:"tscircuit.com",package:c}));return I(a),a}catch(r){return console.error("Error searching tscircuit packages",r),I([]),B(r instanceof Error?r.message:"Failed to search tscircuit packages"),[]}finally{t(!1),Q(!0)}},[g]),E=z.useCallback(()=>{I([]),t(!1),B(null),Q(!1)},[]);return{results:A,isSearching:e,error:o,hasSearched:C,search:i,reset:E}},Wwo=g=>{const A=/^C(\d+)$/i.exec(g.trim());if(!A)return null;const I=Number(A[1]);if(!Number.isSafeInteger(I))return null;const e=`C${A[1]}`;return{source:"jlcpcb",component:{lcscId:I,manufacturer:e,partNumber:e,description:"Import directly from EasyEDA; stock and availability are unknown",package:"",isDirectLookup:!0}}},UFI=(g,A)=>{const I=Wwo(g);return I?A.some(t=>t.component.partNumber.toUpperCase()===I.component.partNumber)?A:[I,...A]:A},Vwo=g=>{const A=g.trim();return/^C\d+/i.test(A)?A.replace(/^C/i,""):A},jwo=()=>{const[g,A]=z.useState([]),[I,e]=z.useState(!1),[t,o]=z.useState(null),[B,C]=z.useState(!1),Q=z.useCallback(async E=>{const n=Vwo(E);if(!n)return[];e(!0),o(null);try{const s=await Yyo(n,10),r=UFI(E,s.map(a=>({source:"jlcpcb",component:_yo(a)})));return A(r),r}catch(s){console.error("Error searching JLCPCB components",s);const r=UFI(E,[]);return A(r),o(r.length>0?null:s instanceof Error?s.message:"Failed to search JLCPCB components"),r}finally{e(!1),C(!0)}},[]),i=z.useCallback(()=>{A([]),e(!1),o(null),C(!1)},[]);return{results:g,isSearching:I,error:t,hasSearched:B,search:Q,reset:i}},zwo=()=>{const[g,A]=z.useState([]),[I,e]=z.useState(!1),[t,o]=z.useState(null),[B,C]=z.useState(!1),Q=z.useCallback(async E=>{const n=E.trim();if(!n)return[];e(!0),o(null);try{const r=(await Rwo(n,20)).map(a=>({source:"kicad",footprint:Nwo(a)}));return A(r),r}catch(s){return console.error("Error searching KiCad footprints",s),A([]),o(s instanceof Error?s.message:"Failed to search KiCad footprints"),[]}finally{e(!1),C(!0)}},[]),i=z.useCallback(()=>{A([]),e(!1),o(null),C(!1)},[]);return{results:g,isSearching:I,error:t,hasSearched:B,search:Q,reset:i}},Xwo=({onTscircuitPackageSelected:g,onJlcpcbComponentTsxLoaded:A,onKicadStringSelected:I})=>{const e=[];return g&&e.push("tscircuit.com"),A&&e.push("jlcpcb"),I&&e.push("kicad"),e},$wo=({isOpen:g,onClose:A,jlcpcbProxyRequestHeaders:I,onKicadStringSelected:e,onTscircuitPackageSelected:t,onJlcpcbComponentTsxLoaded:o,jlcpcbProxyApiBase:B,tscircuitSessionToken:C})=>{WeA();const Q=z.useMemo(()=>Xwo({onKicadStringSelected:e,onTscircuitPackageSelected:t,onJlcpcbComponentTsxLoaded:o}),[e,t,o]),i=Q.length>0,E=Q.length===1,[n,s]=z.useState(Q[0]??"tscircuit.com"),[r,a]=z.useState(""),[c,h]=z.useState(null),{results:l,isSearching:D,error:d,hasSearched:y,search:w,reset:u}=Owo({sessionToken:C}),{results:G,isSearching:m,error:p,hasSearched:k,search:S,reset:R}=jwo(),{results:x,isSearching:N,error:U,hasSearched:K,search:_,reset:b}=zwo(),{details:T,isLoading:j,fetchDetails:W,reset:O}=qwo(),[gA,tA]=z.useState(null),[IA,QA]=z.useState(!1),[nA,DA]=z.useState("pcb"),[CA,hA]=z.useState(null),[sA,cA]=z.useState(!1),SA=z.useMemo(()=>({jlcpcb:{headers:I,apiBase:B}}),[B,I]),{circuitJson:FA,error:aA,isLoading:xA}=Two(c,SA),RA=NFI(c);z.useEffect(()=>{hA(null)},[c]);const NA=z.useCallback(()=>{u(),R(),b(),h(null)},[R,b,u]);z.useEffect(()=>{g||(NA(),a(""),QA(!1),tA(null),hA(null))},[g,NA]),z.useEffect(()=>{a(""),h(null),n==="tscircuit.com"?u():n==="jlcpcb"?R():n==="kicad"&&b()},[n,R,b,u]);const YA=kA=>{h(kA),tA(kA),DA("pcb"),QA(!0),O();const OA=kA.package.org_owner_tscircuit_handle,$A=kA.package.unscoped_name;if(OA&&$A){const og=$A.split("/").pop()??$A;W(OA,og)}},PA=async()=>{r.trim()&&(h(null),n==="tscircuit.com"?await w(r):n==="jlcpcb"?await S(r):n==="kicad"&&await _(r))},mA=async kA=>{try{if(hA(null),cA(!0),kA.source==="kicad"){if(!e)throw new Error("KiCad handler not provided");await e({result:kA,footprint:kA.footprint.qualifiedName})}else if(kA.source==="jlcpcb"){if(!o)throw new Error("JLCPCB handler not provided");const OA=await byo(kA.component.partNumber,{headers:I,apiBase:B});await o({result:kA,tsx:OA})}else if(kA.source==="tscircuit.com"){if(!t)throw new Error("tscircuit package handler not provided");const OA=kA.package.org_owner_tscircuit_handle,$A=kA.package.unscoped_name;if(!OA||!$A)throw new Error("Missing package metadata");const og=$A.split("/").pop()??$A,dg=`@tsci/${OA}.${og}`;await t({result:kA,fullPackageName:dg})}return!0}catch(OA){return console.error("Failed to import component",OA),hA(OA instanceof Error?OA.message:"Failed to import component"),!1}finally{cA(!1)}};let LA=[],dA=!1,HA=null,WA=!1;n==="tscircuit.com"?(LA=l,dA=D,HA=d,WA=y):n==="jlcpcb"?(LA=G,dA=m,HA=p,WA=k):n==="kicad"&&(LA=x,dA=N,HA=U,WA=K);const Qg=async()=>{if(!c)return;await mA(c)&&(A(),NA(),a(""))},_A=kA=>{kA||A()},uA=kA=>{QA(kA),kA||tA(null)};return q.jsxs(j5,{open:g,onOpenChange:_A,children:[q.jsxs(W3,{style:{width:"calc(100vw - 2rem)",maxWidth:RA?"min(1120px, calc(100vw - 2rem))":"min(672px, calc(100vw - 2rem))",zIndex:FFI.importComponentDialog},className:"rf-rounded-sm rf-max-h-[90vh] rf-overflow-y-auto rf-overflow-x-hidden rf-flex rf-flex-col",children:[q.jsxs(V3,{children:[q.jsxs(j3,{className:"rf-text-lg sm:rf-text-xl",children:["Import ",E?yGA[n].label:""," ","Component"]}),q.jsx(z5,{className:"rf-text-sm",children:i?"Search for components from available sources.":"Import options are disabled because no handlers were provided."})]}),i?q.jsxs(A6A,{value:n,onValueChange:kA=>s(kA),className:"rf-min-w-0 rf-w-full",children:[!E&&q.jsx(ylA,{className:"rf-flex rf-w-full rf-gap-2",children:Q.map(kA=>q.jsx(gx,{value:kA,className:"rf-flex-1 rf-text-xs sm:rf-text-sm",children:yGA[kA].label},kA))}),q.jsxs("div",{className:"rf-min-w-0",style:RA?{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(360px, 0.95fr)",gap:"1.5rem",alignItems:"start"}:void 0,children:[q.jsxs("div",{className:"rf-min-w-0",children:[q.jsx(Jwo,{query:r,placeholder:yGA[n].placeholder,isSearching:dA,onQueryChange:a,onSubmit:PA}),q.jsx("div",{className:"no-scrollbar rf-mt-4 rf-flex-1 rf-min-h-[200px] !rf-max-h-[40vh] !rf-overflow-y-auto rf-overflow-x-hidden rf-border rf-rounded-md rf-min-w-0",children:dA?q.jsxs("div",{className:"rf-p-8 rf-text-center rf-text-zinc-500",children:[q.jsx(iS,{className:"rf-h-8 rf-w-8 rf-animate-spin rf-mx-auto rf-mb-2"}),q.jsx("p",{children:"Searching..."})]}):LA.length>0?q.jsx(bwo,{results:LA,selected:c,onSelect:h,onShowDetails:n==="tscircuit.com"?YA:void 0}):q.jsx("div",{className:"rf-p-8 rf-text-center rf-text-zinc-500",children:HA?`Error: ${HA}`:WA?yGA[n].emptyMessage:"Enter a search term to find components"})})]}),RA?q.jsx("div",{className:"rf-mt-4",children:q.jsx(Hwo,{circuitJson:FA,error:aA,isLoading:xA,height:325})}):null]})]}):null,CA?q.jsx("div",{className:"rf-text-sm rf-text-red-600 rf-mt-2",children:CA}):null,q.jsxs(LZ,{className:"rf-flex rf-flex-col sm:rf-flex-row rf-gap-2",children:[q.jsx(Ei,{variant:"outline",onClick:A,className:"rf-order-2 sm:rf-order-1",children:"Cancel"}),q.jsx(Ei,{onClick:Qg,disabled:!c||sA,className:"rf-order-1 sm:rf-order-2",children:sA?q.jsx(iS,{className:"rf-h-4 rf-w-4 rf-animate-spin"}):"Import"})]})]}),q.jsx(vwo,{packageResult:gA,isOpen:IA,onOpenChange:uA,isLoading:j,details:T,previewTab:nA,onPreviewTabChange:kA=>DA(kA),isSubmitting:sA,onImport:()=>{gA&&mA(gA).then(kA=>{kA&&(QA(!1),A(),NA(),a(""))})}})]})},Auo=g=>{const A=g.match(/export const (\w+) =/);if(!A)throw new Error("Could not determine component name from TSX contents");return A[1]},JFI=g=>{const A=Uc(B=>B.pushEvent),I=Uc(B=>B.upsertFile),e=async({result:B,fullPackageName:C})=>{const i=B.package.unscoped_name??B.package.name;await JC.promise(A({event_type:"INSTALL_PACKAGE",full_package_name:C}),{loading:`Requesting install for "${i}"`,success:`Install requested for "${i}"`,error:E=>`Failed to request install: ${E instanceof Error?E.message:String(E)}`})},t=async({footprint:B})=>{await JC.promise(navigator.clipboard.writeText(B),{loading:`Copying "${B}"`,success:`Copied "${B}" to clipboard`,error:C=>`Failed to copy footprint: ${C instanceof Error?C.message:String(C)}`})},o=async({result:B,tsx:C})=>{const i=`imports/${Auo(C)}.tsx`;await JC.promise(I(i,C),{loading:`Importing ${B.component.partNumber}`,success:`Imported to "${i}"`,error:E=>`Failed to import component: ${E instanceof Error?E.message:String(E)}`})};return q.jsx($wo,{...g,onTscircuitPackageSelected:e,onKicadStringSelected:t,onJlcpcbComponentTsxLoaded:o})};JFI.displayName="ImportComponentDialogForCli";const guo=async({circuitJson:g,projectName:A})=>{const{convertCircuitJsonToAltiumZip:I}=await Promise.resolve().then(()=>w5o),e=await I(g,A);return new Blob([new Uint8Array(e)],{type:"application/zip"})},Iuo=async({circuitJson:g,projectName:A})=>{await JC.promise((async()=>{const I=await guo({circuitJson:g,projectName:A});kk(I,{fileName:`${A}_altium_project.zip`})})(),{loading:"Generating Altium project...",success:"Altium project ZIP ready",error:I=>`Failed to generate Altium project: ${I instanceof Error?I.message:String(I)}`})};var Uog={exports:{}},PFI;function euo(){return PFI||(PFI=1,(function(g,A){var I={env:{},version:""};(function(e){g.exports=e()})(function(){return(function e(t,o,B){function C(E,n){if(!o[E]){if(!t[E]){var s=typeof bF=="function"&&bF;if(!n&&s)return s(E,!0);if(Q)return Q(E,!0);var r=new Error("Cannot find module '"+E+"'");throw r.code="MODULE_NOT_FOUND",r}var a=o[E]={exports:{}};t[E][0].call(a.exports,function(c){var h=t[E][1][c];return C(h||c)},a,a.exports,e,t,o,B)}return o[E].exports}for(var Q=typeof bF=="function"&&bF,i=0;i<B.length;i++)C(B[i]);return C})({1:[function(e,t,o){var B=e("./utils"),C=e("./support"),Q="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";o.encode=function(i){for(var E,n,s,r,a,c,h,l=[],D=0,d=i.length,y=d,w=B.getTypeOf(i)!=="string";D<i.length;)y=d-D,s=w?(E=i[D++],n=D<d?i[D++]:0,D<d?i[D++]:0):(E=i.charCodeAt(D++),n=D<d?i.charCodeAt(D++):0,D<d?i.charCodeAt(D++):0),r=E>>2,a=(3&E)<<4|n>>4,c=1<y?(15&n)<<2|s>>6:64,h=2<y?63&s:64,l.push(Q.charAt(r)+Q.charAt(a)+Q.charAt(c)+Q.charAt(h));return l.join("")},o.decode=function(i){var E,n,s,r,a,c,h=0,l=0,D="data:";if(i.substr(0,D.length)===D)throw new Error("Invalid base64 input, it looks like a data url.");var d,y=3*(i=i.replace(/[^A-Za-z0-9+/=]/g,"")).length/4;if(i.charAt(i.length-1)===Q.charAt(64)&&y--,i.charAt(i.length-2)===Q.charAt(64)&&y--,y%1!=0)throw new Error("Invalid base64 input, bad content length.");for(d=C.uint8array?new Uint8Array(0|y):new Array(0|y);h<i.length;)E=Q.indexOf(i.charAt(h++))<<2|(r=Q.indexOf(i.charAt(h++)))>>4,n=(15&r)<<4|(a=Q.indexOf(i.charAt(h++)))>>2,s=(3&a)<<6|(c=Q.indexOf(i.charAt(h++))),d[l++]=E,a!==64&&(d[l++]=n),c!==64&&(d[l++]=s);return d}},{"./support":30,"./utils":32}],2:[function(e,t,o){var B=e("./external"),C=e("./stream/DataWorker"),Q=e("./stream/Crc32Probe"),i=e("./stream/DataLengthProbe");function E(n,s,r,a,c){this.compressedSize=n,this.uncompressedSize=s,this.crc32=r,this.compression=a,this.compressedContent=c}E.prototype={getContentWorker:function(){var n=new C(B.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new i("data_length")),s=this;return n.on("end",function(){if(this.streamInfo.data_length!==s.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),n},getCompressedWorker:function(){return new C(B.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},E.createWorkerFrom=function(n,s,r){return n.pipe(new Q).pipe(new i("uncompressedSize")).pipe(s.compressWorker(r)).pipe(new i("compressedSize")).withStreamInfo("compression",s)},t.exports=E},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(e,t,o){var B=e("./stream/GenericWorker");o.STORE={magic:"\0\0",compressWorker:function(){return new B("STORE compression")},uncompressWorker:function(){return new B("STORE decompression")}},o.DEFLATE=e("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(e,t,o){var B=e("./utils"),C=(function(){for(var Q,i=[],E=0;E<256;E++){Q=E;for(var n=0;n<8;n++)Q=1&Q?3988292384^Q>>>1:Q>>>1;i[E]=Q}return i})();t.exports=function(Q,i){return Q!==void 0&&Q.length?B.getTypeOf(Q)!=="string"?(function(E,n,s,r){var a=C,c=r+s;E^=-1;for(var h=r;h<c;h++)E=E>>>8^a[255&(E^n[h])];return-1^E})(0|i,Q,Q.length,0):(function(E,n,s,r){var a=C,c=r+s;E^=-1;for(var h=r;h<c;h++)E=E>>>8^a[255&(E^n.charCodeAt(h))];return-1^E})(0|i,Q,Q.length,0):0}},{"./utils":32}],5:[function(e,t,o){o.base64=!1,o.binary=!1,o.dir=!1,o.createFolders=!0,o.date=null,o.compression=null,o.compressionOptions=null,o.comment=null,o.unixPermissions=null,o.dosPermissions=null},{}],6:[function(e,t,o){var B=null;B=typeof Promise<"u"?Promise:e("lie"),t.exports={Promise:B}},{lie:37}],7:[function(e,t,o){var B=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",C=e("pako"),Q=e("./utils"),i=e("./stream/GenericWorker"),E=B?"uint8array":"array";function n(s,r){i.call(this,"FlateWorker/"+s),this._pako=null,this._pakoAction=s,this._pakoOptions=r,this.meta={}}o.magic="\b\0",Q.inherits(n,i),n.prototype.processChunk=function(s){this.meta=s.meta,this._pako===null&&this._createPako(),this._pako.push(Q.transformTo(E,s.data),!1)},n.prototype.flush=function(){i.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},n.prototype.cleanUp=function(){i.prototype.cleanUp.call(this),this._pako=null},n.prototype._createPako=function(){this._pako=new C[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var s=this;this._pako.onData=function(r){s.push({data:r,meta:s.meta})}},o.compressWorker=function(s){return new n("Deflate",s)},o.uncompressWorker=function(){return new n("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(e,t,o){function B(a,c){var h,l="";for(h=0;h<c;h++)l+=String.fromCharCode(255&a),a>>>=8;return l}function C(a,c,h,l,D,d){var y,w,u=a.file,G=a.compression,m=d!==E.utf8encode,p=Q.transformTo("string",d(u.name)),k=Q.transformTo("string",E.utf8encode(u.name)),S=u.comment,R=Q.transformTo("string",d(S)),x=Q.transformTo("string",E.utf8encode(S)),N=k.length!==u.name.length,U=x.length!==S.length,K="",_="",b="",T=u.dir,j=u.date,W={crc32:0,compressedSize:0,uncompressedSize:0};c&&!h||(W.crc32=a.crc32,W.compressedSize=a.compressedSize,W.uncompressedSize=a.uncompressedSize);var O=0;c&&(O|=8),m||!N&&!U||(O|=2048);var gA=0,tA=0;T&&(gA|=16),D==="UNIX"?(tA=798,gA|=(function(QA,nA){var DA=QA;return QA||(DA=nA?16893:33204),(65535&DA)<<16})(u.unixPermissions,T)):(tA=20,gA|=(function(QA){return 63&(QA||0)})(u.dosPermissions)),y=j.getUTCHours(),y<<=6,y|=j.getUTCMinutes(),y<<=5,y|=j.getUTCSeconds()/2,w=j.getUTCFullYear()-1980,w<<=4,w|=j.getUTCMonth()+1,w<<=5,w|=j.getUTCDate(),N&&(_=B(1,1)+B(n(p),4)+k,K+="up"+B(_.length,2)+_),U&&(b=B(1,1)+B(n(R),4)+x,K+="uc"+B(b.length,2)+b);var IA="";return IA+=`
5668
+ `,n=new Blob([E],{type:"text/plain"}),s=URL.createObjectURL(n),r=document.createElement("a");r.href=s,r.download=`${i}.test.ts`,r.click(),URL.revokeObjectURL(s)}catch(Q){alert(`Error generating test.ts for ${g.getSolverName()}: ${Q instanceof Error?Q.message:String(Q)}`)}e(!1)};return q.jsxs("div",{className:`relative ${A}`,ref:t,children:[q.jsx("button",{className:"px-2 py-1 rounded text-xs cursor-pointer",onClick:()=>e(!I),title:`Download options for ${g.getSolverName()}`,children:g.getSolverName()}),I&&q.jsxs("div",{className:"absolute top-full left-0 mt-1 bg-white border border-gray-300 rounded shadow-lg z-10 min-w-[150px]",children:[q.jsx("button",{className:"w-full text-left px-3 py-2 hover:bg-gray-100 text-xs",onClick:o,children:"Download JSON"}),q.jsx("button",{className:"w-full text-left px-3 py-2 hover:bg-gray-100 text-xs",onClick:B,children:"Download page.tsx"}),q.jsx("button",{className:"w-full text-left px-3 py-2 hover:bg-gray-100 text-xs",onClick:C,children:"Download test.ts"})]})]})},HxI=g=>g.activeSubSolver?[g,...HxI(g.activeSubSolver)]:[g],kdo=({solver:g})=>{const A=HxI(g);return q.jsx("div",{className:"flex gap-1 items-center text-sm pt-1",children:A.map((I,e)=>q.jsxs("div",{className:"flex items-center",children:[e>0&&q.jsx("span",{className:"text-gray-400 mx-1",children:"→"}),q.jsx(pdo,{solver:I})]},I.getSolverName()))})},Mdo=({solver:g,triggerRender:A,animationSpeed:I=25,renderer:e,onRendererChange:t,onAnimationSpeedChange:o,onDownloadVisualization:B,onSolverStarted:C,onSolverCompleted:Q})=>{const[i,E]=z.useReducer(m=>!m,!1),n=z.useRef(void 0),s=z.useRef(null),r="solver-debugger-last-iteration",[a,c]=z.useState(null),h=z.useRef(null),l=z.useMemo(()=>[{label:"Slow",value:250,description:"250ms"},{label:"Normal",value:100,description:"100ms"},{label:"Fast",value:10,description:"10ms"},{label:"Fast (2x)",value:5,description:"5ms"},{label:"Fast (10x)",value:1,description:"1ms"},{label:"Fast 20x",value:.5,description:"2 steps / 1ms"},{label:"Fast 100x",value:.1,description:"10 steps / 1ms"}],[]),D=()=>{const m=Math.max(1,I),p=I<1?Math.round(1/I):1;n.current=setInterval(()=>{if(g.solved||g.failed){n.current&&(clearInterval(n.current),n.current=void 0),E(),A(),Q&&g.solved&&Q(g);return}for(let k=0;k<p&&!(g.solved||g.failed);k++)g.step();A()},m)},d=()=>{n.current&&(clearInterval(n.current),n.current=void 0)},y=()=>{!g.solved&&!g.failed&&(g.step(),A())},w=()=>{!g.solved&&!g.failed&&(C&&C(g),g.solve(),A(),Q&&Q(g))},u=()=>{i?(d(),E()):(E(),D())},G=()=>{if(g.solved||g.failed||i)return;s.current===null&&typeof window<"u"&&(s.current=window.localStorage.getItem(r));const m=window.prompt("Step until which iteration?",s.current??`${g.iterations}`);if(m===null)return;s.current=m,typeof window<"u"&&window.localStorage.setItem(r,m);const p=Number(m);if(!Number.isFinite(p)){window.alert("Please enter a valid number for the iteration");return}for(;g.iterations<p&&!g.solved&&!g.failed;)g.step();A(),g.solved&&Q&&Q(g)};return z.useEffect(()=>()=>{d()},[]),z.useEffect(()=>{(g.solved||g.failed)&&i&&(d(),E())},[g.solved,g.failed,i]),z.useEffect(()=>{i&&(d(),D())},[I,i]),z.useEffect(()=>{if(typeof document>"u")return;const m=p=>{h.current&&!h.current.contains(p.target)&&c(null)};return document.addEventListener("mousedown",m),()=>{document.removeEventListener("mousedown",m)}},[]),q.jsxs("div",{className:"space-y-2 p-2 border-b",children:[q.jsx("div",{className:"flex items-center",children:q.jsxs("div",{className:"flex items-center gap-2",ref:h,children:[q.jsxs("div",{className:"flex h-9 items-center space-x-1 rounded-md border border-slate-200 bg-white p-1 shadow-sm",children:[q.jsxs("div",{className:"relative",children:[q.jsx("button",{type:"button",onClick:()=>c(a==="renderer"?null:"renderer"),className:"flex select-none items-center rounded-sm px-3 py-1 text-sm font-medium outline-none focus:bg-slate-100 data-[state=open]:bg-slate-100","data-state":a==="renderer"?"open":"closed",children:"Renderer"}),a==="renderer"&&q.jsx("div",{className:"absolute left-0 z-50 mt-1 min-w-[10rem] rounded-md border border-slate-200 bg-white p-1 text-slate-950 shadow-md",children:["vector","canvas"].map(m=>q.jsxs("button",{type:"button",onClick:()=>{t(m),c(null)},className:"flex w-full items-center rounded-sm px-2 py-1.5 text-sm hover:bg-slate-100",children:[m==="vector"?"Vector":"Canvas",e===m&&q.jsx("span",{className:"ml-auto text-xs text-slate-500",children:"✓"})]},m))})]}),q.jsxs("div",{className:"relative",children:[q.jsx("button",{type:"button",onClick:()=>c(a==="debug"?null:"debug"),className:"flex select-none items-center rounded-sm px-3 py-1 text-sm font-medium outline-none focus:bg-slate-100 data-[state=open]:bg-slate-100","data-state":a==="debug"?"open":"closed",children:"Debug"}),a==="debug"&&q.jsx("div",{className:"absolute left-0 z-50 mt-1 min-w-[12rem] rounded-md border border-slate-200 bg-white p-1 text-slate-950 shadow-md",children:q.jsx("button",{type:"button",onClick:()=>{B(),c(null)},className:"flex w-full items-center rounded-sm px-2 py-1.5 text-sm hover:bg-slate-100",children:"Download Visualization"})})]}),q.jsxs("div",{className:"relative",children:[q.jsx("button",{type:"button",onClick:()=>c(a==="animation"?null:"animation"),className:"flex select-none items-center rounded-sm px-3 py-1 text-sm font-medium outline-none focus:bg-slate-100 data-[state=open]:bg-slate-100","data-state":a==="animation"?"open":"closed",children:"Animation"}),a==="animation"&&q.jsx("div",{className:"absolute left-0 z-50 mt-1 min-w-[12rem] rounded-md border border-slate-200 bg-white p-1 text-slate-950 shadow-md",children:l.map(m=>q.jsxs("button",{type:"button",onClick:()=>{o(m.value),c(null)},className:"flex w-full items-center rounded-sm px-2 py-1.5 text-sm hover:bg-slate-100",children:[m.label,q.jsx("span",{className:"ml-auto text-xs text-slate-500",children:m.description}),I===m.value&&q.jsx("span",{className:"ml-2 text-xs text-slate-500",children:"✓"})]},m.value))})]})]}),q.jsx(kdo,{solver:g})]})}),q.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[q.jsx("button",{onClick:y,disabled:g.solved||g.failed||i,className:"bg-blue-500 hover:bg-blue-600 disabled:bg-gray-300 text-white px-3 py-1 rounded text-sm",children:"Step"}),q.jsx("button",{onClick:w,disabled:g.solved||g.failed||i,className:"bg-green-500 hover:bg-green-600 disabled:bg-gray-300 text-white px-3 py-1 rounded text-sm",children:"Solve"}),q.jsx("button",{onClick:u,disabled:g.solved||g.failed,className:`px-3 py-1 rounded text-white text-sm ${i?"bg-red-500 hover:bg-red-600":"bg-yellow-500 hover:bg-yellow-600"} disabled:bg-gray-300`,children:i?"Stop":"Animate"}),q.jsx("button",{onClick:G,disabled:g.solved||g.failed||i,className:"bg-orange-500 hover:bg-orange-600 disabled:bg-gray-300 text-white px-3 py-1 rounded text-sm",children:"Step Until Iteration"}),q.jsxs("div",{className:"text-sm text-gray-600",children:["Iterations: ",g.iterations]}),g.timeToSolve!==void 0&&q.jsxs("div",{className:"text-sm text-gray-600",children:["Time: ",(g.timeToSolve/1e3).toFixed(3),"s"]}),g.solved&&q.jsx("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded text-sm",children:"Solved"}),g.failed&&q.jsx("div",{className:"px-2 py-1 bg-red-100 text-red-800 rounded text-sm",children:"Failed"})]}),g.error&&q.jsxs("div",{className:"text-red-600 text-sm",children:["Error: ",g.error]})]})},Sdo=g=>g!==null&&"pipelineDef"in g&&Array.isArray(g.pipelineDef),fdo=(g,A,I)=>{const e=g.currentPipelineStageIndex;return A<e?"Completed":A===e&&g.activeSubSolver?g.activeSubSolver.failed?"Failed":"In Progress":"Not Started"},Rdo=(g,A)=>{const e=g.pipelineDef[A].solverName,t=fdo(g,A),o=g[e],B=g.firstIterationOfStage?.[e]??(A===g.currentPipelineStageIndex?g.iterations:null),C=g.iterations;let Q=0;if(t==="Completed"){const s=g.pipelineDef[A+1],r=s?g.firstIterationOfStage?.[s.solverName]:void 0;r!==void 0&&B!==null?Q=r-B:B!==null&&(Q=C-B)}else t==="In Progress"&&B!==null&&(Q=C-B);const i=g.timeSpentOnStage?.[e]??0;let E=0;t==="Completed"?E=1:t==="In Progress"&&o&&(E=o.progress??0);const n=o?.stats??null;return{index:A,name:e,status:t,firstIteration:B,iterations:Q,progress:E,timeSpent:i,stats:n&&Object.keys(n).length>0?n:null,solverInstance:o??null}},Ndo=({status:g})=>{const A={"Not Started":"text-blue-600","In Progress":"text-yellow-600",Completed:"text-green-600",Failed:"text-red-600"};return q.jsx("span",{className:`font-medium ${A[g]}`,children:g})},xdo=({progress:g})=>{if(g===0)return null;const A=Math.round(g*100);return q.jsxs("div",{className:"flex items-center gap-2",children:[q.jsx("div",{className:"w-20 h-2 bg-gray-200 rounded overflow-hidden",children:q.jsx("div",{className:"h-full bg-blue-500 transition-all duration-200",style:{width:`${A}%`}})}),q.jsxs("span",{className:"text-xs text-gray-500",children:[A,"%"]})]})},vxI=g=>{if(typeof g=="string")return g;if(typeof g=="number"||typeof g=="boolean"||typeof g=="bigint"||g==null)return String(g);if(typeof g=="object")try{return JSON.stringify(g)}catch{return String(g)}return String(g)},Fdo=g=>Object.entries(g).map(([A,I])=>`${A}: ${vxI(I)}`).join(", "),Udo=({stats:g})=>{if(!g||Object.keys(g).length===0)return q.jsx("span",{children:"-"});const A=Object.entries(g),I=Fdo(g);return q.jsxs("details",{className:"cursor-pointer",children:[q.jsx("summary",{className:"whitespace-nowrap overflow-hidden text-ellipsis max-w-[200px]",children:I}),q.jsx("div",{className:"mt-1 text-xs",children:A.map(([e,t])=>q.jsxs("div",{children:[e,": ",vxI(t)]},e))})]})},tog=g=>{if(g===null||typeof g!="object")return g;if(Array.isArray(g))return g.map(tog);const A={};for(const[I,e]of Object.entries(g))I.startsWith("_")||(A[I]=tog(e));return A},Jdo=(g,A)=>{try{if(typeof g.getConstructorParams!="function"){alert(`getConstructorParams() is not implemented for ${A}`);return}const I=tog(g.getConstructorParams()),e=new Blob([JSON.stringify(I,null,2)],{type:"application/json"}),t=URL.createObjectURL(e),o=document.createElement("a");o.href=t,o.download=`${A}_input.json`,o.click(),URL.revokeObjectURL(t)}catch(I){alert(`Error downloading input for ${A}: ${I instanceof Error?I.message:String(I)}`)}},Pdo=({expanded:g})=>q.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",className:`w-4 h-4 transition-transform duration-200 ${g?"rotate-90":""}`,children:q.jsx("path",{fillRule:"evenodd",d:"M4.5 5.653c0-1.426 1.529-2.33 2.779-1.643l11.54 6.348c1.295.712 1.295 2.573 0 3.285L7.28 19.991c-1.25.687-2.779-.217-2.779-1.643V5.653z",clipRule:"evenodd"})}),qxI=g=>{let A=g;for(;A.activeSubSolver;)A=A.activeSubSolver;return A},TxI=({solver:g,onStepUntilPhase:A,onDownloadInput:I,isNested:e=!1,indentLevel:t=0,triggerRender:o})=>{const[B,C]=z.useState(new Set),Q=g.pipelineDef.map((h,l)=>Rdo(g,l)),i=h=>{C(l=>{const D=new Set(l);return D.has(h)?D.delete(h):D.add(h),D})},E=h=>{A?.(h)},n=h=>{h.solverInstance&&(I?I(h.solverInstance,h.name):Jdo(h.solverInstance,h.name))},s=h=>`${(h/1e3).toFixed(2)}s`,r=()=>{if(!g.solved&&!g.failed){const h=g.activeSubSolver;for(;!g.solved&&!g.failed&&(g.step(),!(g.activeSubSolver&&g.activeSubSolver!==h)););o?.()}},a=()=>{if(!g.solved&&!g.failed){const h=qxI(g);for(;!g.solved&&!g.failed&&(g.step(),qxI(g)===h););o?.()}},c=t*24;return q.jsxs("div",{className:e?"":"border-t border-gray-200",children:[!e&&q.jsxs("div",{className:"px-4 py-2 bg-gray-50 border-b border-gray-200 flex items-center justify-between",children:[q.jsx("h3",{className:"text-sm font-semibold text-gray-700",children:"Pipeline Stages"}),q.jsxs("div",{className:"flex gap-2",children:[q.jsx("button",{onClick:a,disabled:g.solved||g.failed,className:"bg-indigo-500 hover:bg-indigo-600 disabled:bg-gray-300 disabled:cursor-not-allowed cursor-pointer text-white px-3 py-1 rounded text-sm",children:"Next Solver"}),q.jsx("button",{onClick:r,disabled:g.solved||g.failed,className:"bg-purple-500 hover:bg-purple-600 disabled:bg-gray-300 disabled:cursor-not-allowed cursor-pointer text-white px-3 py-1 rounded text-sm",children:"Next Stage"})]})]}),q.jsx("div",{className:"overflow-x-auto",children:q.jsxs("table",{className:"w-full text-sm",children:[!e&&q.jsx("thead",{children:q.jsxs("tr",{className:"bg-gray-50 border-b border-gray-200",children:[q.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Stage"}),q.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Status"}),q.jsxs("th",{className:"px-4 py-2 text-center font-semibold text-gray-700",children:["i",q.jsx("sub",{children:"0"})]}),q.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Iterations"}),q.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Progress"}),q.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Time"}),q.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Stats"}),q.jsx("th",{className:"px-4 py-2 text-left font-semibold text-gray-700",children:"Input"})]})}),q.jsx("tbody",{children:Q.map(h=>{const l=Sdo(h.solverInstance),D=B.has(h.name);return q.jsxs(sC.Fragment,{children:[q.jsxs("tr",{className:`border-b border-gray-100 ${h.status==="In Progress"?"bg-yellow-50":""}`,children:[q.jsx("td",{className:"px-4 py-2",children:q.jsxs("div",{className:"flex items-center gap-2",style:{paddingLeft:c},children:[l?q.jsx("button",{onClick:()=>i(h.name),className:"text-gray-500 hover:text-gray-700",title:D?"Collapse":"Expand",children:q.jsx(Pdo,{expanded:D})}):q.jsx("span",{className:"w-4"}),q.jsx("span",{className:"text-gray-400 w-6",children:String(h.index+1).padStart(2,"0")}),q.jsx("button",{onClick:()=>E(h.name),disabled:h.status==="Completed"||g.solved||g.failed,className:"text-blue-500 hover:text-blue-700 disabled:text-gray-300 disabled:cursor-not-allowed",title:`Step until ${h.name} completes`,children:q.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",className:"w-4 h-4",children:q.jsx("path",{fillRule:"evenodd",d:"M4.5 5.653c0-1.426 1.529-2.33 2.779-1.643l11.54 6.348c1.295.712 1.295 2.573 0 3.285L7.28 19.991c-1.25.687-2.779-.217-2.779-1.643V5.653z",clipRule:"evenodd"})})}),q.jsx("span",{className:"font-medium text-gray-900",children:h.name})]})}),q.jsx("td",{className:"px-4 py-2",children:q.jsx(Ndo,{status:h.status})}),q.jsx("td",{className:"px-4 py-2 text-center text-gray-600",children:h.firstIteration!==null?h.firstIteration:""}),q.jsx("td",{className:"px-4 py-2 text-gray-600",children:h.iterations}),q.jsx("td",{className:"px-4 py-2",children:q.jsx(xdo,{progress:h.progress})}),q.jsx("td",{className:"px-4 py-2 text-gray-600",children:s(h.timeSpent)}),q.jsx("td",{className:"px-4 py-2 text-gray-500",children:q.jsx(Udo,{stats:h.stats})}),q.jsx("td",{className:"px-4 py-2",children:h.solverInstance?q.jsxs("button",{onClick:()=>n(h),className:"flex items-center gap-1 text-blue-500 hover:text-blue-700",title:`Download input for ${h.name}`,children:[q.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",className:"w-4 h-4",children:q.jsx("path",{fillRule:"evenodd",d:"M12 2.25a.75.75 0 01.75.75v11.69l3.22-3.22a.75.75 0 111.06 1.06l-4.5 4.5a.75.75 0 01-1.06 0l-4.5-4.5a.75.75 0 111.06-1.06l3.22 3.22V3a.75.75 0 01.75-.75zm-9 13.5a.75.75 0 01.75.75v2.25a1.5 1.5 0 001.5 1.5h13.5a1.5 1.5 0 001.5-1.5V16.5a.75.75 0 011.5 0v2.25a3 3 0 01-3 3H5.25a3 3 0 01-3-3V16.5a.75.75 0 01.75-.75z",clipRule:"evenodd"})}),q.jsx("span",{children:"Input"})]}):null})]}),l&&D&&q.jsx("tr",{children:q.jsx("td",{colSpan:8,className:"p-0",children:q.jsx(TxI,{solver:h.solverInstance,onStepUntilPhase:A,onDownloadInput:I,isNested:!0,indentLevel:t+1,triggerRender:o})})})]},h.name)})})]})})]})};function Kdo({graphics:g}){const A=g.points??[],I=g.lines??[],e=g.rects??[],t=g.circles??[],o=g.texts??[];let B=Number.POSITIVE_INFINITY,C=Number.POSITIVE_INFINITY,Q=Number.NEGATIVE_INFINITY,i=Number.NEGATIVE_INFINITY;const E=(h,l)=>{typeof h=="number"&&(h<B&&(B=h),h>Q&&(Q=h)),typeof l=="number"&&(l<C&&(C=l),l>i&&(i=l))};for(const h of A)E(h.x,h.y);for(const h of I){const l=h.points??[];for(const D of l)E(D.x,D.y)}for(const h of e){const l=h.x??0,D=h.y??0,d=h.width??0,y=h.height??0;E(l,D),E(l+d,D+y)}for(const h of t){const l=h.x??0,D=h.y??0,d=h.radius??1;E(l-d,D-d),E(l+d,D+d)}for(const h of o)E(h.x,h.y);(!isFinite(B)||!isFinite(C)||!isFinite(Q)||!isFinite(i))&&(B=-20,C=-20,Q=20,i=20);const n=10,s=B-n,r=C-n,a=Math.max(1,Q-B+2*n),c=Math.max(1,i-C+2*n);return q.jsxs("svg",{className:"w-full h-[400px] bg-white",viewBox:`${s} ${r} ${a} ${c}`,role:"img","aria-label":"Graphics fallback",children:[e.map((h,l)=>q.jsx("rect",{x:h.x??0,y:h.y??0,width:h.width??0,height:h.height??0,fill:"none",stroke:h.strokeColor??"black",strokeWidth:h.strokeWidth??1},`rect-${l}`)),I.map((h,l)=>q.jsx("polyline",{fill:"none",stroke:h.strokeColor??"black",strokeWidth:h.strokeWidth??1,points:(h.points??[]).map(D=>`${D.x??0},${D.y??0}`).join(" ")},`line-${l}`)),t.map((h,l)=>q.jsx("circle",{cx:h.x??0,cy:h.y??0,r:h.radius??1.5,fill:h.fillColor??"none",stroke:h.strokeColor??"black",strokeWidth:h.strokeWidth??1},`circle-${l}`)),A.map((h,l)=>q.jsx("circle",{cx:h.x??0,cy:h.y??0,r:h.radius??1.5,fill:h.color??"black"},`point-${l}`)),o.map((h,l)=>q.jsx("text",{x:h.x??0,y:h.y??0,fontSize:h.fontSize??10,fill:h.color??"black",children:h.text??""},`text-${l}`))]})}var Ldo=class extends sC.Component{constructor(g){super(g),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(g){console.error("InteractiveGraphics render error:",g)}render(){return this.state.hasError?this.props.fallback:this.props.children}},Ydo=({solver:g,createSolver:A,animationSpeed:I=25,onSolverStarted:e,onSolverCompleted:t})=>{const[o,B]=z.useReducer(D=>D+1,0),[C]=z.useState(()=>{if(A)return A();if(!g)throw new Error("GenericSolverDebugger requires solver or createSolver");return g}),[Q,i]=z.useState(()=>typeof window>"u"?"vector":window.localStorage.getItem("solver-utils-renderer")==="canvas"?"canvas":"vector"),[E,n]=z.useState(I),s=z.useMemo(()=>{try{return C.visualize()||{points:[],lines:[],rects:[],circles:[]}}catch(D){return console.error("Visualization error:",D),{points:[],lines:[],rects:[],circles:[]}}},[C,o]),r=z.useMemo(()=>(s.rects?.length||0)===0&&(s.lines?.length||0)===0&&(s.points?.length||0)===0&&(s.circles?.length||0)===0,[s]);z.useEffect(()=>{if(!(typeof document>"u")&&!document.querySelector('script[src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"]')){const D=document.createElement("script");D.src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4",document.head.appendChild(D)}},[]),z.useEffect(()=>{n(I)},[I]);const a=C.pipelineDef!==void 0,c=D=>{const d=C;if(!C.solved&&!C.failed){for(;!C.solved&&!C.failed&&d.currentPipelineStageIndex<=d.pipelineDef.findIndex(y=>y.solverName===D);)C.step();B()}},h=()=>{const D=JSON.stringify(s,null,2),d=new Blob([D],{type:"application/json"}),y=URL.createObjectURL(d),w=document.createElement("a");w.download="visualization.json",w.href=y,document.body.appendChild(w),w.click(),document.body.removeChild(w),URL.revokeObjectURL(y)},l=D=>{i(D),typeof window<"u"&&window.localStorage.setItem("solver-utils-renderer",D)};return q.jsxs("div",{children:[q.jsx(Mdo,{solver:C,triggerRender:B,animationSpeed:E,renderer:Q,onRendererChange:l,onAnimationSpeedChange:n,onDownloadVisualization:h,onSolverStarted:e,onSolverCompleted:t}),r?q.jsx("div",{className:"p-4 text-gray-500",children:"No Graphics Yet"}):q.jsx(Ldo,{fallback:q.jsx(Kdo,{graphics:s}),children:Q==="canvas"?q.jsx(mdo,{graphics:s}):q.jsx(wdo,{graphics:s})}),a&&q.jsx(TxI,{solver:C,onStepUntilPhase:c,triggerRender:B})]})};const _do=()=>{z.useEffect(()=>{const g="tailwind-cdn-script";if(document.getElementById(g)||window.tailwind)return;const A=document.createElement("div");A.className="hidden",document.body.appendChild(A);const I=window.getComputedStyle(A).display==="none";if(document.body.removeChild(A),I)return;const e=document.createElement("script");e.id=g,e.src="https://cdn.tailwindcss.com",document.head.appendChild(e)},[])},bdo=1e3,kk=(g,A)=>{const{fileName:I,mimeType:e="text/plain"}=A,t=g instanceof Blob?g:new Blob([g],{type:e}),o=URL.createObjectURL(t),B=document.createElement("a");B.href=o,B.download=I,B.target="_blank",B.rel="noopener noreferrer",B.style.display="none",document.body.appendChild(B),B.click(),document.body.removeChild(B),setTimeout(()=>{URL.revokeObjectURL(o)},bdo)},oog=g=>{let A=g.trim().replace(/[\\/:*?"<>|]/g,"_").replace(/[\x00-\x1f]/g,"").replace(/^\.+/,"").replace(/\.+$/,"").replace(/\s+/g," ").replace(/_+/g,"_");return/^(con|prn|aux|nul|com[0-9]|lpt[0-9])$/i.test(A)&&(A=`_${A}`),A=A.slice(0,200),A||"untitled"},Hdo=g=>{const A=g.solverConstructorArgs??[g.solverParams];if(g.solverName!=="AutoroutingPipelineSolver7_MultiGraph"||A.length!==1)return A;const[{input:I,options:e}]=A;return[I,e]},Ox="https://github.com/tscircuit/tscircuit-autorouter/issues/new",ZxI="https://github.com/tscircuit/copper-pour-solver/issues/new",OxI="https://github.com/tscircuit/calculate-packing/issues/new",vdo="https://github.com/tscircuit/matchpack/issues/new",WxI="https://github.com/tscircuit/schematic-trace-solver/issues/new?template=json-bug-report.yml",qdo={PackSolver2:OxI,LayoutPipelineSolver:vdo,AutoroutingPipelineSolver:Ox,AssignableAutoroutingPipeline2:Ox,AssignableAutoroutingPipeline3:Ox,AutoroutingPipeline1_OriginalUnravel:Ox,AutoroutingPipelineSolver3_HgPortPointPathing:Ox,AutoroutingPipelineSolver4:Ox,AutoroutingPipelineSolver5:Ox,AutoroutingPipelineSolver7_MultiGraph:Ox,AutoroutingPipelineSolver8:Ox,CopperPourPipelineSolver:ZxI,SchematicTracePipelineSolver:WxI},Tdo=g=>g.toLowerCase().includes("pack")?UfI:g.toLowerCase().includes("rout")?PfI:vQo,VxI=g=>{const A=qdo[g];if(A)return A;const I=g.toLowerCase();return I.includes("autorout")?Ox:I.includes("schematic")&&I.includes("trace")?WxI:I.includes("copperpour")?ZxI:I.includes("pack")?OxI:null},Zdo=g=>`${oog(`${g.componentName}-${g.solverName}`)}-solver-input.json`,jxI=g=>{kk(JSON.stringify(g.solverParams,null,2),{fileName:Zdo(g),mimeType:"application/json"})},Odo=({solverEvent:g})=>{const A=VxI(g.solverName);return q.jsxs("div",{className:"rf-flex rf-items-center rf-justify-end rf-gap-2 rf-border-b rf-border-gray-200 rf-bg-gray-50 rf-px-4 rf-py-2",children:[q.jsxs(Ei,{type:"button",variant:"outline",size:"sm",onClick:()=>jxI(g),children:[q.jsx(reA,{className:"rf-w-4 rf-h-4"}),"Download"]}),A?q.jsx(Ei,{asChild:!0,variant:"outline",size:"sm",children:q.jsxs("a",{href:A,target:"_blank",rel:"noopener noreferrer",children:[q.jsx(zwA,{className:"rf-w-4 rf-h-4"}),"Report"]})}):q.jsxs(Ei,{type:"button",variant:"outline",size:"sm",disabled:!0,title:"No report link configured for this solver",children:[q.jsx(zwA,{className:"rf-w-4 rf-h-4"}),"Report"]})]})},Wdo=({solverEvent:g})=>{const A=VxI(g.solverName);return A?q.jsx(Ei,{asChild:!0,variant:"ghost",size:"icon",className:"rf-h-8 rf-w-8",children:q.jsx("a",{href:A,target:"_blank",rel:"noopener noreferrer",title:"Report solver bug","aria-label":"Report solver bug",children:q.jsx(zwA,{className:"rf-w-4 rf-h-4"})})}):q.jsx(Ei,{type:"button",variant:"ghost",size:"icon",className:"rf-h-8 rf-w-8",disabled:!0,title:"No report link configured for this solver","aria-label":"Report solver bug",children:q.jsx(zwA,{className:"rf-w-4 rf-h-4"})})},Vdo=({solverEvents:g=[]})=>{const[A,I]=z.useState(null);_do();const e=z.useMemo(()=>{const C=new Map;for(const Q of g){const i=`${Q.componentName}-${Q.solverName}`;C.set(i,Q)}return C},[g]),t=z.useMemo(()=>Array.from(e.keys()),[e]),o=A?e.get(A):null,B=z.useMemo(()=>{if(!o)return{instance:null,error:null,classFound:!1};const C=V5A[o.solverName];if(!C)return{instance:null,error:`Solver class "${o.solverName}" not found in SOLVERS registry. Available: ${Object.keys(V5A).join(", ")}`,classFound:!1};try{return{instance:new C(...Hdo(o)),error:null,classFound:!0}}catch(Q){const i=Q instanceof Error?Q.message:String(Q);return console.error("Failed to reconstruct solver:",Q),{instance:null,error:`Failed to instantiate solver: ${i}`,classFound:!0}}},[o]);return g.length===0?q.jsx("div",{className:"rf-p-4",children:q.jsx("div",{className:"rf-bg-gray-50 rf-rounded-md rf-border rf-border-gray-200",children:q.jsxs("div",{className:"rf-p-4",children:[q.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-gray-800 rf-mb-3",children:"No Solvers Detected"}),q.jsx("p",{className:"rf-text-sm rf-text-gray-600",children:"Solvers will appear here when the circuit runs. Solvers are used for tasks like component packing and autorouting."})]})})}):q.jsxs("div",{className:"rf-flex rf-h-full rf-overflow-hidden",children:[q.jsxs("div",{className:"rf-w-64 rf-border-r rf-border-gray-200 rf-overflow-y-auto rf-flex-shrink-0",children:[q.jsxs("div",{className:"rf-text-xs rf-font-semibold rf-text-gray-500 rf-px-3 rf-py-2 rf-bg-gray-50 rf-border-b rf-border-gray-200",children:[t.length," ",t.length===1?"Solver":"Solvers"]}),t.map(C=>{const Q=e.get(C),i=A===C;return q.jsx("div",{className:`rf-px-3 rf-py-2 rf-cursor-pointer rf-border-b rf-border-gray-100 ${i?"rf-bg-blue-50 rf-border-l-2 rf-border-l-blue-500":"hover:rf-bg-gray-50"}`,onClick:()=>I(C),children:(()=>{const E=Tdo(Q.solverName);return q.jsxs("div",{className:"rf-flex rf-items-center rf-gap-2",children:[q.jsx(E,{className:"rf-w-4 rf-h-4 rf-text-blue-500 rf-flex-shrink-0"}),q.jsxs("div",{className:"rf-flex-1 rf-min-w-0",children:[q.jsx("div",{className:"rf-text-sm rf-font-medium rf-text-gray-800 rf-truncate",children:Q.componentName}),q.jsx("div",{className:"rf-text-xs rf-text-gray-500 rf-truncate",children:Q.solverName})]})]})})()},C)})]}),q.jsx("div",{className:"rf-flex-1 rf-overflow-hidden",children:o?B.instance?q.jsxs("div",{className:"rf-flex rf-h-full rf-flex-col rf-overflow-y-auto",children:[q.jsx(Odo,{solverEvent:o}),q.jsx("div",{className:"rf-min-h-0 rf-flex-1",children:q.jsx(QS,{fallback:q.jsx("div",{className:"rf-p-4",children:q.jsxs("div",{className:"rf-bg-red-50 rf-rounded-md rf-border rf-border-red-200 rf-p-4",children:[q.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-red-800 rf-mb-2",children:"Error Loading Solver Debugger"}),q.jsxs("p",{className:"rf-text-sm rf-text-red-600",children:["Failed to render the solver debugger for"," ",o.solverName]})]})}),children:q.jsx(Ydo,{solver:B.instance})})})]}):q.jsxs("div",{className:"rf-p-4",children:[q.jsxs("div",{className:"rf-mb-4",children:[q.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-text-gray-800",children:o.solverName}),q.jsxs("p",{className:"rf-text-sm rf-text-gray-500",children:["Component: ",o.componentName]})]}),B.error&&q.jsx("div",{className:`rf-rounded-md rf-border rf-p-4 rf-mb-4 ${B.classFound?"rf-bg-red-50 rf-border-red-200":"rf-bg-yellow-50 rf-border-yellow-200"}`,children:q.jsx("p",{className:`rf-text-sm ${B.classFound?"rf-text-red-700":"rf-text-yellow-700"}`,children:B.error})}),q.jsxs("div",{className:"rf-border rf-border-gray-200 rf-rounded-md rf-overflow-hidden",children:[q.jsxs("div",{className:"rf-px-3 rf-py-2 rf-bg-gray-50 rf-flex rf-items-center rf-justify-between rf-gap-2",children:[q.jsx("span",{className:"rf-text-sm rf-font-medium rf-text-gray-700",children:"Solver Parameters"}),q.jsxs("div",{className:"rf-flex rf-items-center rf-gap-1",children:[q.jsx(Wdo,{solverEvent:o}),q.jsx(Ei,{type:"button",variant:"ghost",size:"icon",className:"rf-h-8 rf-w-8","aria-label":"Download solver input JSON",title:"Download solver input JSON",onClick:()=>jxI(o),children:q.jsx(reA,{className:"rf-w-4 rf-h-4"})})]})]}),q.jsx("div",{className:"rf-p-3 rf-bg-white rf-border-t rf-border-gray-200",children:q.jsx("pre",{className:"rf-text-xs rf-font-mono rf-text-gray-600 rf-whitespace-pre-wrap rf-overflow-x-auto",children:JSON.stringify(o.solverParams,null,2)})})]})]}):q.jsx("div",{className:"rf-flex rf-items-center rf-justify-center rf-h-full",children:q.jsx("p",{className:"rf-text-sm rf-text-gray-500",children:"Select a solver from the list to view details"})})})]})},jdo=["subcircuit_id","componentDisplayName","phaseName","routingPhaseIndex","phaseOrdinal","phaseCount","phaseStageIndex","phaseStageCount","connectionCount","obstacleCount","previousTraceCount","isReroutePhase","autorouterName","autorouterVersion","solverName","effort","cacheStatus"],zdo=["phaseOrdinal","routingPhaseIndex","phaseName","phaseStageIndex"];function Xdo(g,A){let I=-1,e=-1;for(let t=g.length-1;t>=0;t--){const o=g[t];if(o.status!=="running"||o.subcircuit_id!==A.subcircuit_id||o.componentDisplayName!==A.componentDisplayName)continue;let B=0,C=!1;for(const Q of zdo)if(!(o[Q]===void 0||A[Q]===void 0)){if(o[Q]!==A[Q]){C=!0;break}B++}!C&&B>e&&(I=t,e=B)}return I}function $do(g,A){const I=Object.fromEntries(jdo.filter(B=>A[B]!==void 0).map(B=>[B,A[B]])),e=A.simpleRouteJson?structuredClone(A.simpleRouteJson):void 0,t=A.type==="autorouting:start"?-1:Xdo(g,A),o={...t===-1?{id:`autorouting_phase_${g.length+1}`}:g[t],...I,status:A.type==="autorouting:start"?"running":A.type==="autorouting:end"?"complete":"error",...A.type==="autorouting:start"?{startSimpleRouteJson:e}:A.type==="autorouting:end"?{endSimpleRouteJson:e}:{errorSimpleRouteJson:e,error:A.error?{...A.error}:void 0}};return t===-1?[...g,o]:g.map((B,C)=>C===t?o:B)}const Ayo=new Map([["custom","Custom"],["fanout","Fanout"],["single_layer_fanout","Single layer fanout"],["tscircuit_simplify","Simplify"]]),gyo=new Set(["tscircuit","default","auto","auto_local"]);function Iyo(g){if(g==="FanoutSolver")return"Fanout";if(g==="AutoroutingPipelineSolver11_Simplification")return"Simplify";const A=g.match(/^AutoroutingPipeline(?:Solver)?(\d+)(?:_|$)/);if(A)return`Pipeline${A[1]}`;const I=g.match(/^AssignableAutoroutingPipeline(\d+)$/);return I?`Assignable${I[1]}`:g}function eyo(g){const A=g.autorouterName?.trim(),I=A?.replace(/-/g,"_"),e=I&&Ayo.get(I);if(e)return e;if(I&&!gyo.has(I))return A;const t=g.solverName?.trim();if(t)return Iyo(t);const o=g.autorouterVersion?.trim();if(o){const B=o.match(/^beta[_-]pipeline(\d+)$/);return B?`Pipeline${B[1]}`:o==="latest"?"default":o}return A?"default":"Unknown"}const Bog="#fbbf24";function tyo(g){const A=g.endSimpleRouteJson?.traces??[],I=new Set(A.flatMap(t=>[t.pcb_trace_id,t.__replaces_pcb_trace_id].filter(o=>o!==void 0)));return[...(g.startSimpleRouteJson?.traces??[]).filter(t=>!I.has(t.pcb_trace_id)),...A]}function zxI(g){const A=new Map((g.startSimpleRouteJson?.traces??[]).map(I=>[I.pcb_trace_id,I]));return(g.endSimpleRouteJson?.traces??[]).filter(I=>{const e=A.get(I.pcb_trace_id);return!e||!!I.__replaces_pcb_trace_id&&I.__replaces_pcb_trace_id!==e.__replaces_pcb_trace_id||JSON.stringify(e.route)!==JSON.stringify(I.route)}).map(I=>I.pcb_trace_id)}function oyo(g,A){return{outer_diameter:g.via_diameter??A.minViaPadDiameter??A.min_via_pad_diameter??A.minViaDiameter??.6,hole_diameter:g.via_hole_diameter??A.minViaHoleDiameter??A.min_via_hole_diameter??.3}}function XxI(g,A){const I=[];for(const C of g.route)C.route_type==="wire"?I.push({...C,layer:C.layer}):C.route_type==="via"?I.push({route_type:"via",x:C.x,y:C.y,from_layer:C.from_layer,to_layer:C.to_layer,...oyo(C,A)}):C.route_type==="through_obstacle"&&I.push({route_type:"through_pad",start:{...C.start},end:{...C.end},width:C.width,start_layer:C.from_layer,end_layer:C.to_layer,pcb_smtpad_id:C.circuitJsonMetadata?.pcb_smtpad_id,pcb_plated_hole_id:C.circuitJsonMetadata?.pcb_plated_hole_id});const e=C=>{let Q=-1,i=Number.POSITIVE_INFINITY;return I.forEach((E,n)=>{if(E.route_type!=="wire")return;const s=Math.hypot(E.x-C.x,E.y-C.y);s<i&&(i=s,Q=n)}),Q},t=g.route.filter(C=>C.route_type==="jumper").map(C=>[e(C.start),e(C.end)].sort((Q,i)=>Q-i)).filter(([C,Q])=>C>=0&&Q>C).sort(([C],[Q])=>C-Q),o=[];let B=0;for(const[C,Q]of t)C>=B&&o.push(I.slice(B,C+1)),B=Math.max(B,Q);return B<I.length&&o.push(I.slice(B)),o}function Byo(g){const A=[],I=[],e=g.endSimpleRouteJson;if(!e)return{lines:A,circles:I};const t=new Set(zxI(g));for(const o of e.traces??[])if(t.has(o.pcb_trace_id))for(const B of XxI(o,e)){let C;for(const Q of B){if(Q.route_type==="through_pad"){C={...Q.end,layer:Q.end_layer,width:Q.width};continue}const i=Q.route_type==="wire"?Q.layer:Q.from_layer;C&&C.layer===i&&(C.x!==Q.x||C.y!==Q.y)&&A.push({points:[{x:C.x,y:C.y},{x:Q.x,y:Q.y}],strokeWidth:Q.route_type==="wire"?Q.width:C.width,strokeColor:Bog,layer:i}),Q.route_type==="via"&&I.push({center:{x:Q.x,y:Q.y},radius:Q.outer_diameter/2,stroke:Bog,fill:"transparent"}),C={x:Q.x,y:Q.y,layer:Q.route_type==="wire"?Q.layer:Q.to_layer,width:Q.route_type==="wire"?Q.width:C?.width??e.minTraceWidth}}}return{coordinateSystem:"cartesian",lines:A,circles:I}}function Cyo(g){const A=JSON.stringify(g);let I=2166136261;for(let e=0;e<A.length;e++)I=Math.imul(I^A.charCodeAt(e),16777619);return(I>>>0).toString(36)}const Qyo=new Set(["pcb_trace","pcb_via","pcb_copper_pour","pcb_ground_plane","pcb_ground_plane_region","pcb_thermal_spoke","pcb_breakout_point"]);function iyo(g,A,I){const e=I==="input"?A.startSimpleRouteJson??A.errorSimpleRouteJson:A.endSimpleRouteJson,t=g.filter(i=>!Qyo.has(i.type)&&!i.type.endsWith("_error")&&!i.type.endsWith("_warning"));if(!e)return t;const o=I==="input"?e.traces??[]:tyo(A),B=new Set(g.filter(i=>i.type==="source_trace").map(i=>i.source_trace_id)),C=["top",...Array.from({length:Math.max(0,e.layerCount-2)},(i,E)=>`inner${E+1}`),...e.layerCount>1?["bottom"]:[]],Q=[];for(const i of o){const n=e.connections.find(r=>r.name===i.connection_name||r.source_trace_id===i.connection_name)?.source_trace_id??i.connection_name??"",s=XxI(i,e);for(const[r,a]of s.entries()){const c={type:"pcb_trace",pcb_trace_id:`${A.id}_${I}_${i.pcb_trace_id}_${r}_${Cyo(a)}`,subcircuit_id:A.subcircuit_id??void 0,source_trace_id:B.has(n)?n:void 0,route:a};Q.push(c);for(const[h,l]of a.entries()){if(l.route_type!=="via")continue;const D=C.indexOf(l.from_layer),d=C.indexOf(l.to_layer),y={type:"pcb_via",pcb_via_id:`${c.pcb_trace_id}_via_${h}`,pcb_trace_id:c.pcb_trace_id,subcircuit_id:A.subcircuit_id??void 0,x:l.x,y:l.y,outer_diameter:l.outer_diameter,hole_diameter:l.hole_diameter,layers:D>=0&&d>=0?C.slice(Math.min(D,d),Math.max(D,d)+1):[l.from_layer,l.to_layer]};Q.push(y)}}}return[...t,...Q]}const Cog=(g,A)=>g.phaseName||`Phase ${g.phaseOrdinal??A+1}`,$xI=g=>g.componentDisplayName?.match(/name="([^"]+)"/)?.[1]?.replace(/^\./,"")||g.componentDisplayName||g.subcircuit_id||"Board",AFI=g=>g.startSimpleRouteJson??g.endSimpleRouteJson??g.errorSimpleRouteJson,Eyo={is_showing_autorouting:!0,is_showing_rats_nest:!1,is_showing_drc_errors:!1,is_showing_drc_warnings:!1,is_showing_pcb_groups:!1},nyo=({circuitJson:g,phases:A=[],isRunning:I=!1})=>{const[e,t]=z.useState(null),[o,B]=z.useState("output"),[C,Q]=z.useState(!0),[i,E]=z.useState(!1),n=z.useRef(null),[s,r]=z.useState(480),a=e?A.findIndex(N=>N.id===e.id&&AFI(N)===AFI(e)):-1,c=a<0?A.length-1:a,h=A[c],l=a<0,D=!!h?.endSimpleRouteJson,d=h?.startSimpleRouteJson??h?.errorSimpleRouteJson,y=!!d,w=o==="output"&&!D?"input":o==="input"&&!y?"output":o,u=w==="input"?d:h?.endSimpleRouteJson,G=z.useMemo(()=>!h||!u?null:iyo(g??[],h,w),[g,h,u,w]),m=z.useMemo(()=>h&&w==="output"&&C?Byo(h):{lines:[],circles:[]},[h,w,C]);if(z.useLayoutEffect(()=>{const N=n.current;if(!N)return;const U=()=>r(Math.max(360,N.clientHeight));U();const K=new ResizeObserver(U);return K.observe(N),()=>K.disconnect()},[!!h]),!h)return q.jsxs("div",{className:"rf-flex rf-min-h-[400px] rf-flex-col rf-items-center rf-justify-center rf-gap-3 rf-p-8 rf-text-center",children:[q.jsx(PfI,{className:"rf-h-7 rf-w-7 rf-text-blue-500"}),q.jsx("h3",{className:"rf-text-base rf-font-medium",children:I?"Waiting for autorouting":"No autorouting captures"}),q.jsx("p",{className:"rf-max-w-md rf-text-sm rf-text-gray-500",children:I?"Phases appear as the circuit routes. Each capture includes its input and output on the PCB.":"Run a circuit with autorouting enabled to inspect its phases. A circuit JSON file alone does not include routing history."})]});const p=Cog(h,c),k=h.status==="running"&&I,S=!D,R=d?.connections.length,x=G?.filter(N=>N.type==="pcb_trace").length??0;return q.jsxs("div",{className:"rf-flex rf-h-full rf-min-h-[620px] rf-flex-col rf-bg-white md:rf-flex-row","data-testid":"autorouting-explorer",children:[q.jsxs("aside",{className:"rf-flex rf-shrink-0 rf-flex-col rf-border-b rf-border-gray-200 md:rf-w-52 md:rf-border-b-0 md:rf-border-r","aria-label":"Routing phases",children:[q.jsxs("div",{className:"rf-flex rf-items-center rf-justify-between rf-px-3 rf-py-2 rf-text-xs rf-text-gray-500",children:[q.jsx("span",{children:"Routing phases"}),q.jsx("span",{children:A.length})]}),q.jsx("div",{className:"rf-flex rf-gap-1 rf-overflow-x-auto rf-px-1.5 rf-pb-1.5 md:rf-flex-col md:rf-overflow-x-hidden md:rf-overflow-y-auto",children:A.map((N,U)=>{const K=zxI(N).length,_=N.endSimpleRouteJson?`${K} ${K===1?"trace":"traces"} routed`:N.status==="error"?"Failed":N.status==="running"&&I?"Routing…":"No output";return q.jsxs("button",{type:"button","aria-pressed":U===c,title:`${$xI(N)} · ${_}`,onClick:()=>t(N),className:to("rf-flex rf-min-w-[192px] rf-items-start rf-gap-2 rf-rounded-md rf-border rf-px-2 rf-py-2 rf-text-left md:rf-min-w-0",U===c?"rf-border-blue-200 rf-bg-blue-50":"rf-border-transparent hover:rf-bg-gray-50"),children:[q.jsx("span",{className:to("rf-flex rf-h-5 rf-w-5 rf-shrink-0 rf-items-center rf-justify-center rf-rounded-full rf-text-[11px]",U===c?"rf-bg-blue-600 rf-text-white":"rf-bg-gray-100 rf-text-gray-500"),children:U+1}),q.jsxs("span",{className:"rf-min-w-0 rf-flex-1",children:[q.jsxs("span",{className:"rf-flex rf-items-center rf-gap-1",children:[q.jsx("span",{className:"rf-min-w-0 rf-flex-1 rf-truncate rf-text-xs rf-font-medium rf-leading-5 rf-text-gray-800",title:Cog(N,U),children:Cog(N,U)}),N.status==="complete"?q.jsx(_x,{"aria-label":"Captured",className:"rf-h-3 rf-w-3 rf-shrink-0 rf-text-green-600"}):N.status==="error"?q.jsx(meg,{"aria-label":"Failed",className:"rf-h-3 rf-w-3 rf-shrink-0 rf-text-red-500"}):I?q.jsx(iS,{"aria-label":"Routing",className:"rf-h-3 rf-w-3 rf-shrink-0 rf-animate-spin rf-text-blue-500"}):null]}),q.jsxs("span",{className:"rf-block rf-text-[11px] rf-leading-4 rf-text-gray-500",children:[eyo(N)," · ",_]})]})]},N.id)})})]}),q.jsxs("div",{className:"rf-flex rf-min-w-0 rf-flex-1 rf-flex-col",children:[q.jsxs("div",{className:"rf-flex rf-flex-wrap rf-items-center rf-gap-3 rf-border-b rf-border-gray-200 rf-px-4 rf-py-3",children:[q.jsxs("h3",{className:"rf-mr-auto rf-flex rf-items-center rf-gap-2 rf-text-sm rf-font-medium",children:[p,q.jsxs("span",{className:"rf-text-xs rf-font-normal rf-text-gray-500",children:[c+1," of ",A.length]})]}),I&&q.jsx("button",{type:"button",onClick:()=>t(null),disabled:l,className:"rf-text-xs rf-text-blue-600 disabled:rf-text-gray-500",children:l?"Following latest":"Follow latest"}),q.jsx("div",{className:"rf-flex rf-rounded-md rf-bg-gray-100 rf-p-1","aria-label":"Phase snapshot",children:["input","output"].map(N=>q.jsx("button",{type:"button","aria-pressed":w===N,disabled:N==="input"?!y:!D,onClick:()=>B(N),className:to("rf-rounded rf-px-3 rf-py-1 rf-text-xs disabled:rf-opacity-40",w===N?"rf-bg-white rf-text-gray-900 rf-shadow-sm":"rf-text-gray-500"),children:N==="input"?"Input":"Output"},N))})]}),q.jsxs("div",{className:"rf-flex rf-flex-wrap rf-items-center rf-justify-between rf-gap-2 rf-px-4 rf-py-2 rf-text-xs rf-text-gray-600",children:[q.jsxs("label",{className:"rf-flex rf-items-center rf-gap-2",children:[q.jsx("input",{type:"checkbox",checked:C,disabled:w!=="output",onChange:N=>Q(N.target.checked),className:"rf-accent-blue-600"}),q.jsx("span",{"aria-hidden":"true",className:"rf-inline-block rf-h-0.5 rf-w-3",style:{backgroundColor:Bog}}),"Highlight changes (all layers)"]}),q.jsxs("span",{children:[w==="input"?"Before this phase":"After this phase"," ","· ",x," traces"]})]}),S&&q.jsx("div",{className:to("rf-border-y rf-px-4 rf-py-2 rf-text-xs",h.status==="error"?"rf-border-red-100 rf-bg-red-50 rf-text-red-700":"rf-border-blue-100 rf-bg-blue-50 rf-text-blue-700"),role:"status",children:h.status==="error"?`Routing failed: ${h.error?.message||"No output was captured."}`:k?"Routing in progress. Showing captured input until output is available.":"No output was captured for this phase. Showing the available input."}),q.jsx("div",{ref:n,className:"rf-relative rf-min-h-[360px] rf-flex-1","data-testid":"autorouting-pcb",children:G?q.jsx(weg,{circuitJson:G,height:s,allowEditing:!1,clickToInteractEnabled:!1,initialState:Eyo,debugGraphics:m}):q.jsx("div",{className:"rf-p-6 rf-text-sm rf-text-gray-500",children:"No PCB snapshot available for this capture."})}),q.jsxs("div",{className:"rf-flex rf-flex-wrap rf-items-center rf-justify-between rf-gap-2 rf-border-t rf-border-gray-200 rf-px-4 rf-py-3 rf-text-xs rf-text-gray-500",children:[q.jsxs("span",{children:[R===void 0?"Input unavailable":`${R} input connections`,` · ${$xI(h)}`]}),q.jsxs("div",{className:"rf-flex rf-items-center rf-gap-4",children:[q.jsxs("button",{type:"button",disabled:!u,onClick:()=>kk(JSON.stringify(u,null,2),{fileName:`${h.id}-${w}.srj.json`,mimeType:"application/json"}),className:"rf-flex rf-items-center rf-gap-1 disabled:rf-opacity-40",children:[q.jsx(reA,{className:"rf-h-3 rf-w-3"}),"Download SRJ"]}),q.jsxs("button",{type:"button","aria-expanded":i,onClick:()=>E(!i),className:"rf-flex rf-items-center rf-gap-1",children:[q.jsx(b5,{className:to("rf-h-3 rf-w-3",i&&"rf-rotate-90")}),"Inspect SRJ"]})]})]}),i&&q.jsx("pre",{className:"rf-m-0 rf-max-h-64 rf-overflow-auto rf-border-t rf-border-gray-200 rf-bg-gray-50 rf-p-4 rf-text-xs","aria-label":`${p} ${w} SRJ`,children:u?JSON.stringify(u,null,2):"No snapshot captured."})]})]})},gFI=({errorMessage:g,errorStack:A,circuitJsonErrors:I})=>{z.useEffect(()=>{if(VU("TSCIRCUIT_TELEMETRY_DISABLED")!==!0&&g){const e=new Error(g);A&&(e.stack=A);try{bq.captureException(e)}catch{}}},[g,A]),z.useEffect(()=>{if(VU("TSCIRCUIT_TELEMETRY_DISABLED")!==!0&&I&&I.length>0)for(const e of I){const t=new Error(e.message||"Circuit JSON Error");e.stack&&(t.stack=e.stack);try{bq.captureException(t,{error_type:e.type})}catch{}}},[I])},IFI=g=>{z.useEffect(()=>{try{vht(g)}catch{}},[g.source,g.component,g.isWebEmbedded,g.activeTab])},eFI="0.0.3047",syo={version:eFI},dGA=zVg()(XVg(g=>({lastRunEvalVersion:void 0,setLastRunEvalVersion:A=>{g({lastRunEvalVersion:A})}}),{name:"runframe-runner-store"})),ayo=g=>{const[A,I]=z.useState([]),[e,t]=z.useState(null),[o,B]=z.useState(""),[C,Q]=iq("eval-version-selection",null),i=dGA(r=>r.setLastRunEvalVersion),E=dGA(r=>r.lastRunEvalVersion);return z.useEffect(()=>{g&&fetch("https://data.jsdelivr.com/v1/package/npm/@tscircuit/eval").then(r=>r.json()).then(r=>{if(Array.isArray(r?.versions)){let a=[...r.versions];r.tags?.latest&&(t(r.tags.latest),a=a.filter(c=>c!==r.tags.latest)),I(a)}}).catch(()=>{})},[g]),z.useEffect(()=>{g&&(C?(window.TSCIRCUIT_LATEST_EVAL_VERSION=C,i(C)):e&&(window.TSCIRCUIT_LATEST_EVAL_VERSION=e,i(e)))},[g,C,e]),{versions:z.useMemo(()=>A.filter(r=>r.includes(o)).slice(0,50),[A,o]),latestVersion:e,lastRunEvalVersion:E,search:o,setSearch:B,selectVersion:r=>{Q(r),B("")}}},ryo=({snippetNames:g,onSelect:A,onCancel:I,isOpen:e})=>{const[t,o]=z.useState(""),[B,C]=z.useState("");if(!e)return null;const Q=g.filter(n=>n.toLowerCase().includes(B.toLowerCase())),i=B&&!g.includes(B),E=n=>{n.key==="Enter"&&(Q.length===1?o(Q[0]):i&&o(B))};return q.jsx("div",{className:"rf-fixed rf-inset-0 rf-bg-black rf-bg-opacity-50 rf-flex rf-items-center rf-justify-center rf-z-[100]",children:q.jsxs("div",{className:"rf-bg-white rf-rounded-lg rf-p-6 rf-w-96",children:[q.jsx("h2",{className:"rf-text-lg rf-font-semibold rf-mb-4",children:"Select Snippet"}),q.jsx("input",{type:"text",className:"rf-w-full rf-px-4 rf-py-2 rf-border rf-rounded rf-mb-4",placeholder:"Search snippets or new snippet name...",value:B,onChange:n=>C(n.target.value),onKeyDown:E}),q.jsxs("div",{className:"rf-h-60 rf-overflow-y-auto",children:[Q.map(n=>q.jsx("button",{type:"button",className:`w-full text-left px-4 py-2 rounded hover:bg-gray-100 ${t===n?"bg-blue-50":""}`,onClick:()=>o(n),children:n},n)),i&&q.jsxs("button",{type:"button",className:`w-full text-left px-4 py-2 rounded hover:bg-gray-100 text-blue-500 ${t===B?"bg-blue-50":""}`,onClick:()=>o(B),children:['Create new "',B,'"']})]}),q.jsxs("div",{className:"rf-mt-4 rf-flex rf-justify-end rf-gap-2",children:[q.jsx("button",{type:"button",className:"rf-px-4 rf-py-2 rf-text-gray-600 rf-hover:text-gray-800",onClick:I,children:"Cancel"}),q.jsx("button",{type:"button",className:"rf-px-4 rf-py-2 rf-bg-blue-500 rf-text-white rf-rounded rf-hover:bg-blue-600 rf-disabled:opacity-50",onClick:()=>t&&A(t),disabled:!t,children:t===B?`Create "${t}"`:`Save to ${t}`})]})]})})},cyo=g=>{const A=z.useRef(null),I=Uc(e=>e.recentEvents);z.useEffect(()=>{if(I.length===0)return;const e=I[0];e.event_id!==A.current&&(g(e),A.current=e.event_id)},[I,g])};var hyo=Object.defineProperty,xJ=(g,A)=>hyo(g,"name",{value:A,configurable:!0}),lyo="AlertDialog",[Dyo,ugB]=gk(lyo,[iNI]),FJ=iNI(),dyo=xJ(g=>{const{__scopeAlertDialog:A,...I}=g,e=FJ(A);return q.jsx(JuA,{...e,...I,modal:!0})},"AlertDialog");z.forwardRef(xJ(function(A,I){const{__scopeAlertDialog:e,...t}=A,o=FJ(e);return q.jsx(rso,{...o,...t,ref:I})},"AlertDialogTrigger"));var yyo=xJ(g=>{const{__scopeAlertDialog:A,...I}=g,e=FJ(A);return q.jsx(PuA,{...e,...I})},"AlertDialogPortal"),tFI=z.forwardRef(xJ(function(A,I){const{__scopeAlertDialog:e,...t}=A,o=FJ(e);return q.jsx(MeA,{...o,...t,ref:I})},"AlertDialogOverlay")),wyo="AlertDialogContent",[uyo,Gyo]=Dyo(wyo),oFI=z.forwardRef(xJ(function(A,I){const{__scopeAlertDialog:e,children:t,...o}=A,B=FJ(e),C=z.useRef(null),Q=wi(I,C),i=z.useRef(null);return q.jsx(uyo,{scope:e,cancelRef:i,children:q.jsx(feA,{role:"alertdialog",...B,...o,ref:Q,onOpenAutoFocus:Mo(o.onOpenAutoFocus,E=>{E.preventDefault(),i.current?.focus({preventScroll:!0})}),onPointerDownOutside:E=>E.preventDefault(),onInteractOutside:E=>E.preventDefault(),children:t})})},"AlertDialogContent")),BFI=z.forwardRef(xJ(function(A,I){const{__scopeAlertDialog:e,...t}=A,o=FJ(e);return q.jsx(KuA,{...o,...t,ref:I})},"AlertDialogTitle")),CFI=z.forwardRef(xJ(function(A,I){const{__scopeAlertDialog:e,...t}=A,o=FJ(e);return q.jsx(LuA,{...o,...t,ref:I})},"AlertDialogDescription")),QFI=z.forwardRef(xJ(function(A,I){const{__scopeAlertDialog:e,...t}=A,o=FJ(e);return q.jsx(atg,{...o,...t,ref:I})},"AlertDialogAction")),myo="AlertDialogCancel",iFI=z.forwardRef(xJ(function(A,I){const{__scopeAlertDialog:e,...t}=A,{cancelRef:o}=Gyo(myo,e),B=FJ(e),C=wi(I,o);return q.jsx(atg,{...B,...t,ref:C})},"AlertDialogCancel"));const EFI=dyo,pyo=yyo,nFI=z.forwardRef(({className:g,...A},I)=>q.jsx(tFI,{className:to("rf-fixed rf-inset-0 rf-z-50 rf-bg-black/80 data-[state=open]:rf-animate-in data-[state=closed]:rf-animate-out data-[state=closed]:rf-fade-out-0 data-[state=open]:rf-fade-in-0",g),...A,ref:I}));nFI.displayName=tFI.displayName;const Qog=z.forwardRef(({className:g,...A},I)=>q.jsxs(pyo,{children:[q.jsx(nFI,{}),q.jsx(oFI,{ref:I,className:to("rf-fixed rf-left-[50%] rf-top-[50%] rf-z-50 rf-grid rf-w-full rf-max-w-lg rf-translate-x-[-50%] rf-translate-y-[-50%] rf-gap-4 rf-border rf-border-zinc-200 rf-bg-white rf-p-6 rf-shadow-lg rf-duration-200 data-[state=open]:rf-animate-in data-[state=closed]:rf-animate-out data-[state=closed]:rf-fade-out-0 data-[state=open]:rf-fade-in-0 data-[state=closed]:rf-zoom-out-95 data-[state=open]:rf-zoom-in-95 data-[state=closed]:rf-slide-out-to-left-1/2 data-[state=closed]:rf-slide-out-to-top-[48%] data-[state=open]:rf-slide-in-from-left-1/2 data-[state=open]:rf-slide-in-from-top-[48%] sm:rf-rounded-lg dark:rf-border-zinc-800 dark:rf-bg-zinc-950",g),...A})]}));Qog.displayName=oFI.displayName;const iog=({className:g,...A})=>q.jsx("div",{className:to("rf-flex rf-flex-col rf-space-y-2 rf-text-center sm:rf-text-left",g),...A});iog.displayName="AlertDialogHeader";const Eog=({className:g,...A})=>q.jsx("div",{className:to("rf-flex rf-flex-col-reverse sm:rf-flex-row sm:rf-justify-end sm:rf-space-x-2",g),...A});Eog.displayName="AlertDialogFooter";const nog=z.forwardRef(({className:g,...A},I)=>q.jsx(BFI,{ref:I,className:to("rf-text-lg rf-font-semibold",g),...A}));nog.displayName=BFI.displayName;const sog=z.forwardRef(({className:g,...A},I)=>q.jsx(CFI,{ref:I,className:to("rf-text-sm rf-text-zinc-500 dark:rf-text-zinc-400",g),...A}));sog.displayName=CFI.displayName;const kyo=z.forwardRef(({className:g,...A},I)=>q.jsx(QFI,{ref:I,className:to(EZ(),g),...A}));kyo.displayName=QFI.displayName;const aog=z.forwardRef(({className:g,...A},I)=>q.jsx(iFI,{ref:I,className:to(EZ({variant:"outline"}),"rf-mt-2 sm:rf-mt-0",g),...A}));aog.displayName=iFI.displayName;var Myo=Object.defineProperty,UJ=(g,A)=>Myo(g,"name",{value:A,configurable:!0}),rog="Checkbox",[Syo,GgB]=gk(rog),[fyo,cog]=Syo(rog);function sFI(g){const{__scopeCheckbox:A,checked:I,children:e,defaultChecked:t,disabled:o,form:B,name:C,onCheckedChange:Q,required:i,value:E="on",internal_do_not_use_render:n}=g,[s,r]=sR({prop:I,defaultProp:t??!1,onChange:Q,caller:rog}),[a,c]=z.useState(null),[h,l]=z.useState(null),[D,d]=z.useState(null),y=a?!!B||!!a.closest("form"):!0,w={checked:s,disabled:o,setChecked:r,control:a,setControl:c,name:C,form:B,value:E,userClick:D,onUserClick:d,required:i,defaultChecked:gf(t)?!1:t,isFormControl:y,bubbleInput:h,setBubbleInput:l};return q.jsx(fyo,{scope:A,...w,children:rFI(n)?n(w):e})}UJ(sFI,"CheckboxProvider");var Ryo="CheckboxTrigger",Nyo=z.forwardRef(UJ(function({__scopeCheckbox:A,onKeyDown:I,onClick:e,...t},o){const{control:B,value:C,disabled:Q,checked:i,required:E,setControl:n,setChecked:s,onUserClick:r,isFormControl:a,bubbleInput:c}=cog(Ryo,A),h=wi(o,n),l=z.useRef(i);return z.useEffect(()=>{const D=B?.form;if(D){const d=UJ(()=>s(l.current),"reset");return D.addEventListener("reset",d),()=>D.removeEventListener("reset",d)}},[B,s]),q.jsx(dQ.button,{type:"button",role:"checkbox","aria-checked":gf(i)?"mixed":i,"aria-required":E,"data-state":hog(i),"data-disabled":Q?"":void 0,disabled:Q,value:C,...t,ref:h,onKeyDown:Mo(I,D=>{D.key==="Enter"&&D.preventDefault()}),onClick:Mo(e,D=>{const d=D.isPropagationStopped();r({requestedChecked:gf(i)?!0:!i,hasConsumerStoppedPropagation:d}),s(y=>gf(y)?!0:!y),c&&a&&(d||D.stopPropagation())})})},"CheckboxTrigger")),aFI=z.forwardRef(UJ(function(A,I){const{__scopeCheckbox:e,name:t,checked:o,defaultChecked:B,required:C,disabled:Q,value:i,onCheckedChange:E,form:n,...s}=A;return q.jsx(sFI,{__scopeCheckbox:e,checked:o,defaultChecked:B,disabled:Q,required:C,onCheckedChange:E,name:t,form:n,value:i,internal_do_not_use_render:({isFormControl:r})=>q.jsxs(q.Fragment,{children:[q.jsx(Nyo,{...s,ref:I,__scopeCheckbox:e}),r&&q.jsx(Jyo,{__scopeCheckbox:e})]})})},"Checkbox")),xyo="CheckboxIndicator",Fyo=z.forwardRef(UJ(function(A,I){const{__scopeCheckbox:e,forceMount:t,...o}=A,B=cog(xyo,e);return q.jsx(YM,{present:t||gf(B.checked)||B.checked===!0,children:q.jsx(dQ.span,{"data-state":hog(B.checked),"data-disabled":B.disabled?"":void 0,...o,ref:I,style:{pointerEvents:"none",...A.style}})})},"CheckboxIndicator")),Uyo="CheckboxBubbleInput",Jyo=z.forwardRef(UJ(function({__scopeCheckbox:A,onClick:I,...e},t){const{control:o,userClick:B,checked:C,defaultChecked:Q,required:i,disabled:E,name:n,value:s,form:r,bubbleInput:a,setBubbleInput:c}=cog(Uyo,A),h=wi(t,c),l=Weg(o),D=z.useRef(!1),d=z.useRef(C),y=z.useRef(B),w=z.useRef(null);z.useEffect(()=>{const G=a;if(!G)return;const m=window.HTMLInputElement.prototype,k=Object.getOwnPropertyDescriptor(m,"checked").set;if(!k)return;const S=d.current!==C;d.current=C;const R=B!==null&&B!==y.current;if(y.current=B,R)w.current=S?null:B,S&&(G.indeterminate=gf(C),k.call(G,gf(C)?!1:C)),G.dispatchEvent(new Event("click",{bubbles:!B.hasConsumerStoppedPropagation}));else if(S){const x=w.current;w.current=null;const N=x?.requestedChecked===C;D.current=!0,G.indeterminate=gf(C),k.call(G,gf(C)?!1:C),G.dispatchEvent(new Event("click",{bubbles:!(N&&x.hasConsumerStoppedPropagation)})),D.current=!1}},[a,C,B]);const u=z.useRef(gf(C)?!1:C);return q.jsx(dQ.input,{type:"checkbox","aria-hidden":!0,defaultChecked:Q??u.current,required:i,disabled:E,name:n,value:s,form:r,...e,tabIndex:-1,ref:h,onClick:Mo(I,G=>{D.current&&G.stopPropagation()}),style:{...e.style,...l,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})},"CheckboxBubbleInput"));function rFI(g){return typeof g=="function"}UJ(rFI,"isFunction");function gf(g){return g==="indeterminate"}UJ(gf,"isIndeterminate");function hog(g){return gf(g)?"indeterminate":g?"checked":"unchecked"}UJ(hog,"getState");const zeA=z.forwardRef(({className:g,...A},I)=>q.jsx(aFI,{ref:I,className:to("rf-peer rf-h-4 rf-w-4 rf-shrink-0 rf-rounded-sm rf-border rf-border-zinc-200 rf-border-zinc-900 rf-shadow focus-visible:rf-outline-none focus-visible:rf-ring-1 focus-visible:rf-ring-zinc-950 disabled:rf-cursor-not-allowed disabled:rf-opacity-50 data-[state=checked]:rf-bg-zinc-900 data-[state=checked]:rf-text-zinc-50 dark:rf-border-zinc-800 dark:rf-border-zinc-50 dark:focus-visible:rf-ring-zinc-300 dark:data-[state=checked]:rf-bg-zinc-50 dark:data-[state=checked]:rf-text-zinc-900",g),...A,children:q.jsx(Fyo,{className:to("rf-flex rf-items-center rf-justify-center rf-text-current"),children:q.jsx(_x,{className:"rf-h-4 rf-w-4"})})}));zeA.displayName=aFI.displayName;const j5=JuA,Pyo=PuA,cFI=z.forwardRef(({className:g,...A},I)=>q.jsx(MeA,{className:to("rf-fixed rf-inset-0 rf-z-50 rf-bg-black/80 data-[state=open]:rf-animate-in data-[state=closed]:rf-animate-out data-[state=closed]:rf-fade-out-0 data-[state=open]:rf-fade-in-0",g),...A,ref:I}));cFI.displayName=MeA.displayName;const W3=z.forwardRef(({className:g,children:A,showOverlay:I=!0,...e},t)=>q.jsxs(Pyo,{children:[q.jsx(cFI,{className:to(I?"":"rf-hidden")}),q.jsx(feA,{ref:t,className:to("rf-fixed rf-left-[50%] rf-top-[50%] rf-z-50 rf-grid rf-w-full rf-max-w-lg rf-translate-x-[-50%] rf-translate-y-[-50%] rf-gap-4 rf-border rf-border-zinc-200 rf-bg-white rf-p-6 rf-shadow-lg rf-duration-200 data-[state=open]:rf-animate-in data-[state=closed]:rf-animate-out data-[state=closed]:rf-fade-out-0 data-[state=open]:rf-fade-in-0 data-[state=closed]:rf-zoom-out-95 data-[state=open]:rf-zoom-in-95 data-[state=closed]:rf-slide-out-to-left-1/2 data-[state=closed]:rf-slide-out-to-top-[48%] data-[state=open]:rf-slide-in-from-left-1/2 data-[state=open]:rf-slide-in-from-top-[48%] sm:rf-rounded-lg dark:rf-border-zinc-800 dark:rf-bg-zinc-950",g),...e,children:A})]}));W3.displayName=feA.displayName;const V3=({className:g,...A})=>q.jsx("div",{className:to("rf-flex rf-flex-col rf-space-y-2 rf-text-center sm:rf-text-left",g),...A});V3.displayName="DialogHeader";const LZ=({className:g,...A})=>q.jsx("div",{className:to("rf-flex rf-flex-col-reverse sm:rf-flex-row sm:rf-justify-end sm:rf-space-x-2",g),...A});LZ.displayName="DialogFooter";const j3=z.forwardRef(({className:g,...A},I)=>q.jsx(KuA,{ref:I,className:to("rf-text-lg rf-font-semibold",g),...A}));j3.displayName=KuA.displayName;const z5=z.forwardRef(({className:g,...A},I)=>q.jsx(LuA,{ref:I,className:to("rf-text-sm rf-text-zinc-500 dark:rf-text-zinc-400",g),...A}));z5.displayName=LuA.displayName;const yGA={"tscircuit.com":{label:"tscircuit.com",placeholder:"Search tscircuit packages...",emptyMessage:"No packages found"},jlcpcb:{label:"JLCPCB Parts",placeholder:"Search JLCPCB parts (e.g. C14663)...",emptyMessage:"No parts found"},kicad:{label:"KiCad Footprints",placeholder:"Search KiCad footprints...",emptyMessage:"No footprints found"}},Kyo="https://cdn.jsdelivr.net/npm/easyeda@latest/dist/browser/index.js";let log=null;const Dog=async()=>(log||(log=import(Kyo)),log),Lyo=g=>(A,I)=>{const e=new Headers(I?.headers),t={};return e.forEach((o,B)=>{t[B]=o}),fetch(`${g?.apiBase??dm}/proxy`,{...I,headers:{...t,"X-Target-Url":A.toString(),"X-Sender-Origin":t.origin??"","X-Sender-Host":t.host??"https://easyeda.com","X-Sender-Referer":t.referer??"","X-Sender-User-Agent":t["user-agent"]??"","X-Sender-Cookie":t.cookie??"",authority:t.authority??"","content-type":t["content-type"]??"",...g?.headers}})},Yyo=async(g,A=10)=>{const I=encodeURIComponent(g),e=await fetch(`https://jlcsearch.tscircuit.com/api/search?limit=${A}&q=${I}`);if(!e.ok)throw new Error(`JLCPCB API error: ${e.status}`);return(await e.json()).components??[]},_yo=g=>({lcscId:g.lcsc,manufacturer:g.mfr,description:g.description,partNumber:`C${g.lcsc}`,package:g.package,price:g.price,stock:g.stock,isBasic:g.is_basic}),hFI=async(g,A)=>{const{fetchEasyEDAComponent:I}=await Dog();return I(g,{fetch:Lyo(A),includeModelMetadata:A?.includeModelMetadata})},byo=async(g,A)=>{const{convertRawEasyToTsx:I}=await Dog(),e=await hFI(g,A);return I({rawEasy:e})},Hyo=async(g,A)=>{const{EasyEdaJsonSchema:I,convertEasyEdaJsonToCircuitJson:e}=await Dog(),t=await hFI(g,{...A,includeModelMetadata:!1}),o=I.parse(t);return e(o,{shouldRecenter:!0,showDesignator:!0,useModelCdn:!1})};function z3(g){return Array.isArray?Array.isArray(g):DFI(g)==="[object Array]"}function vyo(g){if(typeof g=="string")return g;if(typeof g=="bigint")return g.toString();const A=g+"";return A=="0"&&1/g==-1/0?"-0":A}function dog(g){return g==null?"":vyo(g)}function CG(g){return typeof g=="string"}function wGA(g){return typeof g=="number"}function qyo(g){return g===!0||g===!1||Tyo(g)&&DFI(g)=="[object Boolean]"}function lFI(g){return typeof g=="object"}function Tyo(g){return lFI(g)&&g!==null}function hS(g){return g!=null}function uGA(g){return!g.trim().length}function DFI(g){return g==null?g===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(g)}const Zyo="Incorrect 'index' type",yog="Invalid doc index: must be a non-negative integer within the bounds of the docs array",Oyo=g=>`Invalid value for key ${g}`,Wyo=g=>`Pattern length exceeds max of ${g}.`,Vyo=g=>`Missing ${g} property in key`,jyo=g=>`Property 'weight' in key '${g}' must be a positive integer`,zyo="Fuse.match does not support useTokenSearch: token search requires corpus-level statistics (df, fieldCount) that a one-off string comparison does not have. Use new Fuse(...).search(...) instead.",dFI=Object.prototype.hasOwnProperty;var Xyo=class{constructor(g){this._keys=[],this._keyMap={};let A=0;g.forEach(I=>{const e=yFI(I);this._keys.push(e),this._keyMap[e.id]=e,A+=e.weight}),this._keys.forEach(I=>{I.weight/=A})}get(g){return this._keyMap[g]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}};function yFI(g){let A=null,I=null,e=null,t=1,o=null;if(CG(g)||z3(g))e=g,A=wFI(g),I=GGA(g);else{if(!dFI.call(g,"name"))throw new Error(Vyo("name"));const B=g.name;if(e=B,dFI.call(g,"weight")&&g.weight!==void 0&&(t=g.weight,t<=0))throw new Error(jyo(GGA(B)));A=wFI(B),I=GGA(B),o=g.getFn??null}return{path:A,id:I,weight:t,src:e,getFn:o}}function wFI(g){return z3(g)?g:g.split(".")}function GGA(g){return z3(g)?g.join("."):g}function $yo(g,A){const I=[];let e=!1;const t=(o,B,C,Q)=>{if(hS(o))if(!B[C])I.push(Q!==void 0?{v:o,i:Q}:o);else{const i=o[B[C]];if(!hS(i))return;if(C===B.length-1&&(CG(i)||wGA(i)||qyo(i)||typeof i=="bigint"))I.push(Q!==void 0?{v:dog(i),i:Q}:dog(i));else if(z3(i)){e=!0;for(let E=0,n=i.length;E<n;E+=1)t(i[E],B,C+1,E)}else B.length&&t(i,B,C+1,Q)}};return t(g,CG(A)?A.split("."):A,0),e?I:I[0]}const rQ=Object.freeze({...{isCaseSensitive:!1,ignoreDiacritics:!1,includeScore:!1,keys:[],shouldSort:!0,sortFn:(g,A)=>g.score===A.score?g.idx<A.idx?-1:1:g.score<A.score?-1:1},...{includeMatches:!1,findAllMatches:!1,minMatchCharLength:1},...{location:0,threshold:.6,distance:100},...{useExtendedSearch:!1,useTokenSearch:!1,tokenize:void 0,tokenMatch:"any",getFn:$yo,ignoreLocation:!1,ignoreFieldNorm:!1,fieldNormWeight:1}});function Awo(g){return g>=9&&g<=13||g===32||g===160}function gwo(g=1,A=3){const I=new Map,e=Math.pow(10,A);return{get(t){let o=0,B=!1;for(let Q=0;Q<t.length;Q++)Awo(t.charCodeAt(Q))?B=!1:B||(o++,B=!0);if(o===0&&(o=1),I.has(o))return I.get(o);const C=Math.round(e/Math.pow(o,.5*g))/e;return I.set(o,C),C},clear(){I.clear()}}}var wog=class{constructor({getFn:g=rQ.getFn,fieldNormWeight:A=rQ.fieldNormWeight}={}){this.norm=gwo(A,3),this.getFn=g,this.isCreated=!1,this.docs=[],this.keys=[],this._keysMap={},this.setIndexRecords()}setSources(g=[]){this.docs=g}setIndexRecords(g=[]){this.records=g}setKeys(g=[]){this.keys=g,this._keysMap={},g.forEach((A,I)=>{this._keysMap[A.id]=I})}create(){if(this.isCreated||!this.docs.length)return;this.isCreated=!0;const g=this.docs.length;this.records=new Array(g);let A=0;if(CG(this.docs[0]))for(let I=0;I<g;I++){const e=this._createStringRecord(this.docs[I],I);e&&(this.records[A++]=e)}else for(let I=0;I<g;I++)this.records[A++]=this._createObjectRecord(this.docs[I],I);this.records.length=A,this.norm.clear()}add(g,A){if(!Number.isInteger(A)||A<0)throw new Error(yog);if(CG(g)){const e=this._createStringRecord(g,A);return e&&this.records.push(e),e}const I=this._createObjectRecord(g,A);return this.records.push(I),I}removeAt(g){if(!Number.isInteger(g)||g<0)throw new Error(yog);for(let A=0,I=this.records.length;A<I;A+=1)if(this.records[A].i===g){this.records.splice(A,1);break}for(let A=0,I=this.records.length;A<I;A+=1)this.records[A].i>g&&(this.records[A].i-=1)}removeAll(g){const A=new Set;for(const e of g)Number.isInteger(e)&&e>=0&&A.add(e);if(A.size===0)return;this.records=this.records.filter(e=>!A.has(e.i));const I=Array.from(A).sort((e,t)=>e-t);for(const e of this.records){let t=0,o=I.length;for(;t<o;){const B=t+o>>>1;I[B]<e.i?t=B+1:o=B}e.i-=t}}getValueForItemAtKeyId(g,A){return g[this._keysMap[A]]}size(){return this.records.length}_createStringRecord(g,A){return!hS(g)||uGA(g)?null:{v:g,i:A,n:this.norm.get(g)}}_createObjectRecord(g,A){const I={i:A,$:{}};for(let e=0,t=this.keys.length;e<t;e++){const o=this.keys[e],B=o.getFn?o.getFn(g):this.getFn(g,o.path);if(hS(B)){if(z3(B)){const C=[];for(let Q=0,i=B.length;Q<i;Q+=1){const E=B[Q];if(hS(E)){if(CG(E)){if(!uGA(E)){const n={v:E,i:Q,n:this.norm.get(E)};C.push(n)}}else if(hS(E.v)){const n=CG(E.v)?E.v:dog(E.v);if(!uGA(n)){const s={v:n,i:E.i,n:this.norm.get(n)};C.push(s)}}}}I.$[e]=C}else if(CG(B)&&!uGA(B)){const C={v:B,n:this.norm.get(B)};I.$[e]=C}}}return I}toJSON(){return{keys:this.keys.map(({getFn:g,...A})=>A),records:this.records}}};function uFI(g,A,{getFn:I=rQ.getFn,fieldNormWeight:e=rQ.fieldNormWeight}={}){const t=new wog({getFn:I,fieldNormWeight:e});return t.setKeys(g.map(yFI)),t.setSources(A),t.create(),t}function Iwo(g,{getFn:A=rQ.getFn,fieldNormWeight:I=rQ.fieldNormWeight}={}){const{keys:e,records:t}=g,o=new wog({getFn:A,fieldNormWeight:I});return o.setKeys(e),o.setIndexRecords(t),o}function ewo(g=[],A=rQ.minMatchCharLength){const I=[];let e=-1,t=-1,o=0;for(let B=g.length;o<B;o+=1){const C=g[o];C&&e===-1?e=o:!C&&e!==-1&&(t=o-1,t-e+1>=A&&I.push([e,t]),e=-1)}return g[o-1]&&o-e>=A&&I.push([e,o-1]),I}function two(g,A,I,{location:e=rQ.location,distance:t=rQ.distance,threshold:o=rQ.threshold,findAllMatches:B=rQ.findAllMatches,minMatchCharLength:C=rQ.minMatchCharLength,includeMatches:Q=rQ.includeMatches,ignoreLocation:i=rQ.ignoreLocation}={}){if(A.length>32)throw new Error(Wyo(32));const E=A.length,n=g.length,s=Math.max(0,Math.min(e,n));let r=o,a=s;const c=(p,k)=>{const S=p/E;if(i)return S;const R=Math.abs(s-k);return t?S+R/t:R?1:S},h=C>1||Q,l=h?Array(n):[];let D;for(;(D=g.indexOf(A,a))>-1;){const p=c(0,D);if(r=Math.min(p,r),a=D+E,h){let k=0;for(;k<E;)l[D+k]=1,k+=1}}a=-1;let d=[],y=1,w=0,u=E+n;const G=1<<E-1;for(let p=0;p<E;p+=1){let k=0,S=u;for(;k<S;)c(p,s+S)<=r?k=S:u=S,S=Math.floor((u-k)/2+k);u=S;let R=Math.max(1,s-S+1);const x=B?n:Math.min(s+S,n)+E,N=Array(x+2);N[x+1]=(1<<p)-1;for(let U=x;U>=R;U-=1){const K=U-1,_=I[g[K]];if(N[U]=(N[U+1]<<1|1)&_,p&&(N[U]|=(d[U+1]|d[U])<<1|1|d[U+1]),N[U]&G&&(y=c(p,K),y<=r)){if(r=y,a=K,w=p,a<=s)break;R=Math.max(1,2*s-a)}}if(c(p+1,s)>r)break;d=N}if(h&&a>=0){const p=Math.min(n-1,a+E-1+w);for(let k=a;k<=p;k+=1)I[g[k]]&&(l[k]=1)}const m={isMatch:a>=0,score:Math.max(.001,y)};if(h){const p=ewo(l,C);p.length?Q&&(m.indices=p):m.isMatch=!1}return m}function owo(g){const A={};for(let I=0,e=g.length;I<e;I+=1){const t=g.charAt(I);A[t]=(A[t]||0)|1<<e-I-1}return A}function uog(g){if(g.length<=1)return g;g.sort((I,e)=>I[0]-e[0]||I[1]-e[1]);const A=[g[0]];for(let I=1,e=g.length;I<e;I+=1){const t=A[A.length-1],o=g[I];o[0]<=t[1]+1?t[1]=Math.max(t[1],o[1]):A.push(o)}return A}const GFI={ł:"l",Ł:"L",đ:"d",Đ:"D",ø:"o",Ø:"O",ħ:"h",Ħ:"H",ŧ:"t",Ŧ:"T",ı:"i",ß:"ss"},Bwo=new RegExp("["+Object.keys(GFI).join("")+"]","g"),XeA=typeof String.prototype.normalize=="function"?g=>g.normalize("NFD").replace(/[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C04\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u192B\u1930-\u193B\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F]/g,"").replace(Bwo,A=>GFI[A]):g=>g;var Gog=class{constructor(g,{location:A=rQ.location,threshold:I=rQ.threshold,distance:e=rQ.distance,includeMatches:t=rQ.includeMatches,findAllMatches:o=rQ.findAllMatches,minMatchCharLength:B=rQ.minMatchCharLength,isCaseSensitive:C=rQ.isCaseSensitive,ignoreDiacritics:Q=rQ.ignoreDiacritics,ignoreLocation:i=rQ.ignoreLocation}={}){if(this.options={location:A,threshold:I,distance:e,includeMatches:t,findAllMatches:o,minMatchCharLength:B,isCaseSensitive:C,ignoreDiacritics:Q,ignoreLocation:i},g=C?g:g.toLowerCase(),g=Q?XeA(g):g,this.pattern=g,this.chunks=[],!this.pattern.length)return;const E=(s,r)=>{this.chunks.push({pattern:s,alphabet:owo(s),startIndex:r})},n=this.pattern.length;if(n>32){let s=0;const r=n%32,a=n-r;for(;s<a;)E(this.pattern.substr(s,32),s),s+=32;if(r){const c=n-32;E(this.pattern.substr(c),c)}}else E(this.pattern,0)}searchIn(g){const{isCaseSensitive:A,ignoreDiacritics:I,includeMatches:e}=this.options;if(g=A?g:g.toLowerCase(),g=I?XeA(g):g,this.pattern===g){if(g.length<this.options.minMatchCharLength)return{isMatch:!1,score:1};const a={isMatch:!0,score:0};return e&&(a.indices=[[0,g.length-1]]),a}const{location:t,distance:o,threshold:B,findAllMatches:C,minMatchCharLength:Q,ignoreLocation:i}=this.options,E=[];let n=0,s=!1;this.chunks.forEach(({pattern:a,alphabet:c,startIndex:h})=>{const{isMatch:l,score:D,indices:d}=two(g,a,c,{location:t+h,distance:o,threshold:B,findAllMatches:C,minMatchCharLength:Q,includeMatches:e,ignoreLocation:i});l&&(s=!0),n+=D,l&&d&&E.push(...d)});const r={isMatch:s,score:s?n/this.chunks.length:1};return s&&e&&(r.indices=uog(E)),r}};const Cwo=new Set(["fuzzy","include"]);function Qwo(g){return g.startsWith("inverse")}const mog=[{type:"exact",multiRegex:/^="(.*)"$/,singleRegex:/^=(.*)$/,create:g=>({type:"exact",search(A){const I=A===g;return{isMatch:I,score:I?0:1,indices:[0,g.length-1]}}})},{type:"include",multiRegex:/^'"(.*)"$/,singleRegex:/^'(.*)$/,create:g=>({type:"include",search(A){let I=0,e;const t=[],o=g.length;for(;(e=A.indexOf(g,I))>-1;)I=e+o,t.push([e,I-1]);const B=!!t.length;return{isMatch:B,score:B?0:1,indices:t}}})},{type:"prefix-exact",multiRegex:/^\^"(.*)"$/,singleRegex:/^\^(.*)$/,create:g=>({type:"prefix-exact",search(A){const I=A.startsWith(g);return{isMatch:I,score:I?0:1,indices:[0,g.length-1]}}})},{type:"inverse-prefix-exact",multiRegex:/^!\^"(.*)"$/,singleRegex:/^!\^(.*)$/,create:g=>({type:"inverse-prefix-exact",search(A){const I=!A.startsWith(g);return{isMatch:I,score:I?0:1,indices:[0,A.length-1]}}})},{type:"inverse-suffix-exact",multiRegex:/^!"(.*)"\$$/,singleRegex:/^!(.*)\$$/,create:g=>({type:"inverse-suffix-exact",search(A){const I=!A.endsWith(g);return{isMatch:I,score:I?0:1,indices:[0,A.length-1]}}})},{type:"suffix-exact",multiRegex:/^"(.*)"\$$/,singleRegex:/^(.*)\$$/,create:g=>({type:"suffix-exact",search(A){const I=A.endsWith(g);return{isMatch:I,score:I?0:1,indices:[A.length-g.length,A.length-1]}}})},{type:"inverse-exact",multiRegex:/^!"(.*)"$/,singleRegex:/^!(.*)$/,create:g=>({type:"inverse-exact",search(A){const I=A.indexOf(g)===-1;return{isMatch:I,score:I?0:1,indices:[0,A.length-1]}}})},{type:"fuzzy",multiRegex:/^"(.*)"$/,singleRegex:/^(.*)$/,create:(g,A={})=>{const I=new Gog(g,{location:A.location??rQ.location,threshold:A.threshold??rQ.threshold,distance:A.distance??rQ.distance,includeMatches:A.includeMatches??rQ.includeMatches,findAllMatches:A.findAllMatches??rQ.findAllMatches,minMatchCharLength:A.minMatchCharLength??rQ.minMatchCharLength,isCaseSensitive:A.isCaseSensitive??rQ.isCaseSensitive,ignoreDiacritics:A.ignoreDiacritics??rQ.ignoreDiacritics,ignoreLocation:A.ignoreLocation??rQ.ignoreLocation});return{type:"fuzzy",search(e){return I.searchIn(e)}}}}],mFI=mog.length,iwo="\0",Ewo="|";function nwo(g){const A=[],I=g.length;let e=0;for(;e<I;){for(;e<I&&g[e]===" ";)e++;if(e>=I)break;let t=e;for(;t<I&&g[t]!==" "&&g[t]!=='"';)t++;if(t<I&&g[t]==='"'){for(t++;t<I;){if(g[t]==='"'){const o=t+1;if(o>=I||g[o]===" "){t++;break}if(g[o]==="$"&&(o+1>=I||g[o+1]===" ")){t+=2;break}}t++}A.push(g.substring(e,t)),e=t}else{for(;t<I&&g[t]!==" ";)t++;A.push(g.substring(e,t)),e=t}}return A}function pFI(g,A){const I=g.match(A);return I?I[1]:null}function swo(g,A={}){return g.replace(/\\\|/g,iwo).split(Ewo).map(I=>{const e=nwo(I.replace(/\u0000/g,"|").trim()).filter(o=>o&&!!o.trim()),t=[];for(let o=0,B=e.length;o<B;o+=1){const C=e[o];let Q=!1,i=-1;for(;!Q&&++i<mFI;){const E=mog[i],n=pFI(C,E.multiRegex);n&&(t.push(E.create(n,A)),Q=!0)}if(!Q)for(i=-1;++i<mFI;){const E=mog[i],n=pFI(C,E.singleRegex);if(n){t.push(E.create(n,A));break}}}return t})}var awo=class{constructor(g,{isCaseSensitive:A=rQ.isCaseSensitive,ignoreDiacritics:I=rQ.ignoreDiacritics,includeMatches:e=rQ.includeMatches,minMatchCharLength:t=rQ.minMatchCharLength,ignoreLocation:o=rQ.ignoreLocation,findAllMatches:B=rQ.findAllMatches,location:C=rQ.location,threshold:Q=rQ.threshold,distance:i=rQ.distance}={}){this.query=null,this.options={isCaseSensitive:A,ignoreDiacritics:I,includeMatches:e,minMatchCharLength:t,findAllMatches:B,ignoreLocation:o,location:C,threshold:Q,distance:i},g=A?g:g.toLowerCase(),g=I?XeA(g):g,this.pattern=g,this.query=swo(this.pattern,this.options)}static condition(g,A){return A.useExtendedSearch}searchIn(g){const A=this.query;if(!A)return{isMatch:!1,score:1};const{includeMatches:I,isCaseSensitive:e,ignoreDiacritics:t}=this.options;g=e?g:g.toLowerCase(),g=t?XeA(g):g;let o=0;const B=[];let C=0,Q=!1;for(let i=0,E=A.length;i<E;i+=1){const n=A[i];B.length=0,o=0,Q=!1;for(let s=0,r=n.length;s<r;s+=1){const a=n[s],{isMatch:c,indices:h,score:l}=a.search(g);if(c)o+=1,C+=l,Qwo(a.type)&&(Q=!0),I&&(Cwo.has(a.type)?B.push(...h):B.push(h));else{C=0,o=0,B.length=0,Q=!1;break}}if(o){const s={isMatch:!0,score:C/o};return Q&&(s.hasInverse=!0),I&&(s.indices=uog(B)),s}}return{isMatch:!1,score:1}}};const pog=[];function kog(...g){pog.push(...g)}function mGA(g,A){for(let I=0,e=pog.length;I<e;I+=1){const t=pog[I];if(t.condition(g,A))return new t(g,A)}return new Gog(g,A)}const pGA={AND:"$and",OR:"$or"},Mog={PATH:"$path",PATTERN:"$val"},Sog=g=>!!(g[pGA.AND]||g[pGA.OR]),rwo=g=>!!g[Mog.PATH],cwo=g=>!z3(g)&&lFI(g)&&!Sog(g),kFI=g=>({[pGA.AND]:Object.keys(g).map(A=>({[A]:g[A]}))});function MFI(g,A,{auto:I=!0}={}){const e=t=>{if(CG(t)){const Q={keyId:null,pattern:t};return I&&(Q.searcher=mGA(t,A)),Q}const o=Object.keys(t),B=rwo(t);if(!B&&o.length>1&&!Sog(t))return e(kFI(t));if(cwo(t)){const Q=B?t[Mog.PATH]:o[0],i=B?t[Mog.PATTERN]:t[Q];if(!CG(i))throw new Error(Oyo(Q));const E={keyId:GGA(Q),pattern:i};return I&&(E.searcher=mGA(i,A)),E}const C={children:[],operator:o[0]};return o.forEach(Q=>{const i=t[Q];z3(i)&&i.forEach(E=>{C.children.push(e(E))})}),C};return Sog(g)||(g=kFI(g)),e(g)}function fog(g,{ignoreFieldNorm:A=rQ.ignoreFieldNorm}){let I=1;return g.forEach(({key:e,norm:t,score:o})=>{const B=e?e.weight:null;I*=Math.pow(o===0&&B?Number.EPSILON:o,(B||1)*(A?1:t))}),I}function hwo(g,{ignoreFieldNorm:A=rQ.ignoreFieldNorm}){g.forEach(I=>{I.score=fog(I.matches,{ignoreFieldNorm:A})})}var lwo=class{constructor(g,A){this.limit=g,this.heap=[],this.comparator=A}get size(){return this.heap.length}insert(g){this.size<this.limit?(this.heap.push(g),this._bubbleUp(this.size-1)):this.comparator(g,this.heap[0])<0&&(this.heap[0]=g,this._sinkDown(0))}extractSorted(){return this.heap.sort(this.comparator)}_bubbleUp(g){const A=this.heap;for(;g>0;){const I=g-1>>1;if(this.comparator(A[g],A[I])<=0)break;const e=A[g];A[g]=A[I],A[I]=e,g=I}}_sinkDown(g){const A=this.heap,I=A.length;let e=g;do{g=e;const t=2*g+1,o=2*g+2;if(t<I&&this.comparator(A[t],A[e])>0&&(e=t),o<I&&this.comparator(A[o],A[e])>0&&(e=o),e!==g){const B=A[g];A[g]=A[e],A[e]=B}}while(e!==g)}};function Dwo(g){const A=[];return g.matches.forEach(I=>{if(!hS(I.indices)||!I.indices.length)return;const e={indices:I.indices,value:I.value};I.key&&(e.key=I.key.id),I.idx>-1&&(e.refIndex=I.idx),A.push(e)}),A}function dwo(g,A,{includeMatches:I=rQ.includeMatches,includeScore:e=rQ.includeScore}={}){return g.map(t=>{const{idx:o}=t,B={item:A[o],refIndex:o};return I&&(B.matches=Dwo(t)),e&&(B.score=t.score),B})}const ywo=/[\p{L}\p{M}\p{N}_]+/gu,SFI=new WeakSet;function wwo(g){SFI.has(g)||(SFI.add(g),console.warn(`[Fuse] tokenize regex ${g} lacks the global flag; only the first match per text will be returned. Add the 'g' flag.`))}function uwo(g){if(typeof g=="function"){let A=!1;return I=>{const e=g(I);if(!A&&(A=!0,!Array.isArray(e)||e.some(t=>typeof t!="string")))throw new Error(`[Fuse] tokenize function must return string[]; received ${Array.isArray(e)?"array containing non-strings":typeof e}.`);return e}}return g instanceof RegExp?(g.global||wwo(g),A=>A.match(g)||[]):A=>A.match(ywo)||[]}function Rog({isCaseSensitive:g=!1,ignoreDiacritics:A=!1,tokenize:I}={}){const e=uwo(I);return{tokenize(t){return g||(t=t.toLowerCase()),A&&(t=XeA(t)),e(t)}}}var Gwo=class{static condition(g,A){return A.useTokenSearch}constructor(g,A){this.options=A,this.analyzer=Rog({isCaseSensitive:A.isCaseSensitive,ignoreDiacritics:A.ignoreDiacritics,tokenize:A.tokenize});const I=this.analyzer.tokenize(g),{df:e,fieldCount:t}=A._invertedIndex;this.termSearchers=[],this.idfWeights=[];for(const o of I){this.termSearchers.push(new Gog(o,{location:A.location,threshold:A.threshold,distance:A.distance,includeMatches:A.includeMatches,findAllMatches:A.findAllMatches,minMatchCharLength:A.minMatchCharLength,isCaseSensitive:A.isCaseSensitive,ignoreDiacritics:A.ignoreDiacritics,ignoreLocation:!0}));const B=e.get(o)||0,C=Math.log(1+(t-B+.5)/(B+.5));this.idfWeights.push(C)}this.combineAll=A.tokenMatch==="all",this.numTerms=this.termSearchers.length,this.useMask=this.numTerms<=31}searchIn(g){if(!this.termSearchers.length)return{isMatch:!1,score:1};const A=[];let I=0,e=0,t=0,o=0;const B=this.combineAll&&!this.useMask?new Set:null;for(let i=0;i<this.termSearchers.length;i++){const E=this.termSearchers[i].searchIn(g),n=this.idfWeights[i];e+=n,E.isMatch&&(t++,I+=n*(1-E.score),E.indices&&A.push(...E.indices),this.combineAll&&(this.useMask?o|=1<<i:B.add(i)))}if(t===0)return{isMatch:!1,score:1};const C=e>0?1-I/e:0,Q={isMatch:!0,score:Math.max(.001,C)};return this.options.includeMatches&&A.length&&(Q.indices=uog(A)),this.combineAll&&(this.useMask?Q.matchedMask=o:Q.matchedTerms=B,Q.termCount=this.numTerms),Q}};function Nog(g,A,I,e){const t=e.tokenize(A);if(!t.length)return;g.fieldCount++,g.docFieldCount.set(I,(g.docFieldCount.get(I)||0)+1);const o=new Set(t);let B=g.docTermFieldHits.get(I);B||(B=new Map,g.docTermFieldHits.set(I,B));for(const C of o)B.set(C,(B.get(C)||0)+1),g.df.set(C,(g.df.get(C)||0)+1)}function fFI(g,A,I,e){const{i:t,v:o,$:B}=A;if(o!==void 0){Nog(g,o,t,e);return}if(B)for(let C=0;C<I;C++){const Q=B[C];if(Q)if(Array.isArray(Q))for(const i of Q)Nog(g,i.v,t,e);else Nog(g,Q.v,t,e)}}function mwo(g,A,I){const e={fieldCount:0,df:new Map,docFieldCount:new Map,docTermFieldHits:new Map};for(const t of g)fFI(e,t,A,I);return e}function pwo(g,A,I,e){fFI(g,A,I,e)}function kwo(g,A){const I=g.docFieldCount.get(A);if(I===void 0)return;g.fieldCount-=I,g.docFieldCount.delete(A);const e=g.docTermFieldHits.get(A);if(e){for(const[t,o]of e){const B=(g.df.get(t)||0)-o;B<=0?g.df.delete(t):g.df.set(t,B)}g.docTermFieldHits.delete(A)}}function RFI(g,A){if(A.length===0)return;const I=Array.from(new Set(A)).sort((C,Q)=>C-Q);for(const C of I)kwo(g,C);const e=C=>{let Q=0,i=I.length;for(;Q<i;){const E=Q+i>>>1;I[E]<C?Q=E+1:i=E}return C-Q},t=I[0],o=new Map;for(const[C,Q]of g.docFieldCount)o.set(C>t?e(C):C,Q);g.docFieldCount=o;const B=new Map;for(const[C,Q]of g.docTermFieldHits)B.set(C>t?e(C):C,Q);g.docTermFieldHits=B}var X3=class{constructor(g,A,I){this.options={...rQ,...A},this.options.useExtendedSearch,this.options.useTokenSearch,this._keyStore=new Xyo(this.options.keys),this._docs=g,this._myIndex=null,this._invertedIndex=null,this.setCollection(g,I),this._lastQuery=null,this._lastSearcher=null}_getSearcher(g){if(this._lastQuery===g)return this._lastSearcher;const A=mGA(g,this._invertedIndex?{...this.options,_invertedIndex:this._invertedIndex}:this.options);return this._lastQuery=g,this._lastSearcher=A,A}setCollection(g,A){if(this._docs=g,A&&!(A instanceof wog))throw new Error(Zyo);if(this._myIndex=A||uFI(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight}),this.options.useTokenSearch){const I=Rog({isCaseSensitive:this.options.isCaseSensitive,ignoreDiacritics:this.options.ignoreDiacritics,tokenize:this.options.tokenize});this._invertedIndex=mwo(this._myIndex.records,this._myIndex.keys.length,I)}this._invalidateSearcherCache()}add(g){if(!hS(g))return;this._docs.push(g);const A=this._myIndex.add(g,this._docs.length-1);if(this._invertedIndex&&A){const I=Rog({isCaseSensitive:this.options.isCaseSensitive,ignoreDiacritics:this.options.ignoreDiacritics,tokenize:this.options.tokenize});pwo(this._invertedIndex,A,this._myIndex.keys.length,I)}this._invalidateSearcherCache()}remove(g=()=>!1){const A=[],I=[];for(let e=0,t=this._docs.length;e<t;e+=1)g(this._docs[e],e)&&(A.push(this._docs[e]),I.push(e));if(I.length){this._invertedIndex&&RFI(this._invertedIndex,I);const e=new Set(I);this._docs=this._docs.filter((t,o)=>!e.has(o)),this._myIndex.removeAll(I),this._invalidateSearcherCache()}return A}removeAt(g){if(!Number.isInteger(g)||g<0||g>=this._docs.length)throw new Error(yog);this._invertedIndex&&RFI(this._invertedIndex,[g]);const A=this._docs.splice(g,1)[0];return this._myIndex.removeAt(g),this._invalidateSearcherCache(),A}_invalidateSearcherCache(){this._lastQuery=null,this._lastSearcher=null}getIndex(){return this._myIndex}_normalizedKeys(){return this._myIndex.keys.map(g=>this._keyStore.get(g.id)||g)}search(g,A){const{limit:I=-1}=A||{},{includeMatches:e,includeScore:t,shouldSort:o,sortFn:B,ignoreFieldNorm:C}=this.options;if(CG(g)&&!g.trim()){let s=this._docs.map((r,a)=>({item:r,refIndex:a}));return wGA(I)&&I>-1&&(s=s.slice(0,I)),s}const Q=o&&wGA(I)&&I>0&&CG(g),i=B,E=(s,r)=>i(s,r)||s.idx-r.idx;let n;if(Q){const s=new lwo(I,E);CG(this._docs[0])?this._searchStringList(g,{heap:s,ignoreFieldNorm:C}):this._searchObjectList(g,{heap:s,ignoreFieldNorm:C}),n=s.extractSorted()}else n=CG(g)?CG(this._docs[0])?this._searchStringList(g):this._searchObjectList(g):this._searchLogical(g),hwo(n,{ignoreFieldNorm:C}),o&&n.sort(CG(g)?E:i),wGA(I)&&I>-1&&(n=n.slice(0,I));return dwo(n,this._docs,{includeMatches:e,includeScore:t})}_searchStringList(g,{heap:A,ignoreFieldNorm:I}={}){const e=this._getSearcher(g),t=this.options.useTokenSearch&&this.options.tokenMatch==="all",{records:o}=this._myIndex,B=A?null:[];return o.forEach(({v:C,i:Q,n:i})=>{if(!hS(C))return;const E=e.searchIn(C);if(E.isMatch){const n={score:E.score,value:C,norm:i,indices:E.indices};t&&(n.matchedMask=E.matchedMask,n.matchedTerms=E.matchedTerms,n.termCount=E.termCount);const s=[n];if(!t||this._coversAllTokens(s)){const r={item:C,idx:Q,matches:s};A?(r.score=fog(r.matches,{ignoreFieldNorm:I}),A.insert(r)):B.push(r)}}}),B}_searchLogical(g){const A=MFI(g,this.options),I=this._normalizedKeys(),e=(C,Q,i)=>{if(!("children"in C)){const{keyId:r,searcher:a}=C;let c;return r===null?(c=[],I.forEach((h,l)=>{c.push(...this._findMatches({key:h,value:Q[l],searcher:a}))})):c=this._findMatches({key:this._keyStore.get(r),value:this._myIndex.getValueForItemAtKeyId(Q,r),searcher:a}),c&&c.length?[{idx:i,item:Q,matches:c}]:[]}const{children:E,operator:n}=C,s=[];for(let r=0,a=E.length;r<a;r+=1){const c=E[r],h=e(c,Q,i);if(h.length)s.push(...h);else if(n===pGA.AND)return[]}return s},t=this._myIndex.records,o=new Map,B=[];return t.forEach(({$:C,i:Q})=>{if(hS(C)){const i=e(A,C,Q);i.length&&(o.has(Q)||(o.set(Q,{idx:Q,item:C,matches:[]}),B.push(o.get(Q))),i.forEach(({matches:E})=>{o.get(Q).matches.push(...E)}))}}),B}_searchObjectList(g,{heap:A,ignoreFieldNorm:I}={}){const e=this._getSearcher(g),t=this.options.useTokenSearch&&this.options.tokenMatch==="all",{records:o}=this._myIndex,B=this._normalizedKeys(),C=A?null:[];return o.forEach(({$:Q,i})=>{if(!hS(Q))return;const E=[];let n=!1,s=!1;if(B.forEach((r,a)=>{const c=this._findMatches({key:r,value:Q[a],searcher:e});c.length?(E.push(...c),c[0].hasInverse&&(s=!0)):n=!0}),!(s&&n)&&E.length&&(!t||this._coversAllTokens(E))){const r={idx:i,item:Q,matches:E};A?(r.score=fog(r.matches,{ignoreFieldNorm:I}),A.insert(r)):C.push(r)}}),C}_findMatches({key:g,value:A,searcher:I}){if(!hS(A))return[];const e=[];if(z3(A))A.forEach(({v:t,i:o,n:B})=>{if(!hS(t))return;const C=I.searchIn(t);if(C.isMatch){const Q={score:C.score,key:g,value:t,idx:o,norm:B,indices:C.indices,hasInverse:C.hasInverse};C.termCount!==void 0&&(Q.matchedMask=C.matchedMask,Q.matchedTerms=C.matchedTerms,Q.termCount=C.termCount),e.push(Q)}});else{const{v:t,n:o}=A,B=I.searchIn(t);if(B.isMatch){const C={score:B.score,key:g,value:t,norm:o,indices:B.indices,hasInverse:B.hasInverse};B.termCount!==void 0&&(C.matchedMask=B.matchedMask,C.matchedTerms=B.matchedTerms,C.termCount=B.termCount),e.push(C)}}return e}_coversAllTokens(g){const A=g.length?g[0].termCount:void 0;if(A===void 0)return!0;if(A<=31){let e=0;for(let t=0;t<g.length;t++)e|=g[t].matchedMask||0;return e===2**A-1}const I=new Set;for(let e=0;e<g.length;e++){const t=g[e].matchedTerms;if(t)for(const o of t)I.add(o)}return I.size===A}};X3.version="7.5.0",X3.createIndex=uFI,X3.parseIndex=Iwo,X3.config=rQ,X3.match=function(g,A,I){if(I&&I.useTokenSearch)throw new Error(zyo);return mGA(g,{...rQ,...I}).searchIn(A)},X3.parseQuery=MFI,kog(awo),kog(Gwo),X3.use=function(...g){g.forEach(A=>kog(A))};var Mwo=X3;const Swo="https://kicad-mod-cache.tscircuit.com";let xog=null,$eA=null,Fog=null;const fwo=async()=>xog||$eA||($eA=fetch("https://kicad-mod-cache.tscircuit.com/kicad_files.json").then(g=>g.json()).then(g=>(xog=g,$eA=null,g)),$eA),Rwo=async(g,A=20)=>{const I=await fwo();return Fog||(Fog=new Mwo(I)),Fog.search(g).slice(0,A).map(e=>e.item)},Nwo=g=>{const A=g.replace(".pretty/","/").replace(".kicad_mod",""),I=`kicad:${A}`;return{path:g,qualifiedName:I,description:A}},xwo=g=>g.replace(/^\/+/,"").split("/").map(A=>encodeURIComponent(A)).join("/"),Fwo=async g=>{const A=await fetch(`${Swo}/${xwo(g)}`);if(!A.ok)throw new Error(`KiCad footprint fetch failed: ${A.status}`);const I=await A.text(),{KicadFootprintToCircuitJsonConverter:e}=await cS("kicad-to-circuit-json"),t=new e;return t.addFile(g.split("/").pop()??"selected-footprint.kicad_mod",I),t.runUntilFinished(),t.getOutput()},NFI=g=>g?.source==="jlcpcb"||g?.source==="kicad",Uwo=async(g,A)=>{if(g.source==="jlcpcb")return Hyo(g.component.partNumber,A?.jlcpcb);if(g.source==="kicad")return Fwo(g.footprint.path);throw new Error("Footprint preview is not available for this source")},Jwo=({query:g,placeholder:A,isSearching:I,onQueryChange:e,onSubmit:t})=>{const o=z.useCallback(B=>{B.key==="Enter"&&(B.preventDefault(),t())},[t]);return q.jsxs("div",{className:"rf-flex rf-items-center rf-gap-2 rf-mt-4",children:[q.jsxs("div",{className:"rf-relative rf-flex-grow",children:[q.jsx(keg,{className:"rf-absolute rf-left-2 rf-top-2.5 rf-h-4 rf-w-4 rf-text-muted-foreground"}),q.jsx(Xtg,{placeholder:A,className:"rf-pl-8",spellCheck:!1,autoComplete:"off",value:g,onChange:B=>e(B.target.value),onKeyDown:o})]}),q.jsx(Ei,{onClick:t,disabled:I||g.trim().length<1,className:"sm:rf-px-4 rf-px-3",children:I?q.jsx(iS,{className:"rf-h-4 rf-w-4 rf-animate-spin"}):q.jsxs(q.Fragment,{children:[q.jsx(keg,{className:"rf-h-4 rf-w-4 sm:rf-hidden"}),q.jsx("span",{className:"rf-hidden sm:rf-inline",children:"Search"})]})})]})},Pwo=new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}),Kwo=g=>Pwo.format(g),xFI=g=>{switch(g.source){case"tscircuit.com":{const A=g.package;return`tscircuit-${A.package_id??`${A.org_owner_tscircuit_handle??"unknown"}-${A.unscoped_name??A.name??"package"}`}`}case"jlcpcb":return`jlc-${g.component.lcscId}`;case"kicad":return`kicad-${g.footprint.path}`;default:return"unknown"}},Lwo=g=>{switch(g.source){case"tscircuit.com":return g.package.unscoped_name;case"jlcpcb":return g.component.isDirectLookup?g.component.partNumber:g.component.manufacturer;case"kicad":return g.footprint.qualifiedName}},Ywo=g=>{switch(g.source){case"tscircuit.com":return g.package.description||(g.package.org_owner_tscircuit_handle?`Component by ${g.package.org_owner_tscircuit_handle}`:void 0);case"jlcpcb":return g.component.description;case"kicad":return g.footprint.description}},_wo=g=>{switch(g.source){case"tscircuit.com":return g.package.name;case"jlcpcb":return g.component.isDirectLookup?void 0:g.component.partNumber;case"kicad":return}},bwo=({results:g,selected:A,onSelect:I,onShowDetails:e})=>{const t=A?xFI(A):null;return q.jsx("div",{className:"rf-divide-y rf-w-full rf-overflow-hidden",children:g.map(o=>{const B=xFI(o),C=t===B,Q=Lwo(o),i=Ywo(o),E=_wo(o),n=o.source==="jlcpcb"?o.component.stock:null,s=o.source==="jlcpcb"?o.component.price:null,r=o.source==="jlcpcb"?o.component.isBasic:null,a=o.source==="jlcpcb"?o.component.isDirectLookup:!1;return q.jsxs("div",{className:`rf-p-3 rf-flex rf-flex-col sm:rf-grid sm:rf-grid-cols-[minmax(0,1fr)_auto] rf-items-start sm:rf-items-center rf-cursor-pointer hover:rf-bg-zinc-100 rf-gap-2 rf-overflow-hidden ${C?"rf-bg-zinc-100":""}`,onClick:()=>I(o),children:[q.jsxs("div",{className:"rf-min-w-0 rf-overflow-hidden rf-w-full",children:[q.jsxs("div",{className:"rf-flex rf-items-start rf-gap-2 rf-min-w-0",children:[q.jsxs("div",{className:"rf-font-medium rf-text-sm rf-truncate rf-flex-1 rf-min-w-0 rf-flex rf-items-center rf-gap-1.5",children:[Q,o.source==="jlcpcb"&&r!=null&&q.jsx("span",{className:`rf-text-xs rf-px-1.5 rf-py-0.5 rf-rounded rf-font-medium rf-flex-shrink-0 ${r?"rf-bg-green-100 rf-text-green-700":"rf-bg-orange-100 rf-text-orange-700"}`,children:r?"Basic":"Extended"}),a&&q.jsx("span",{className:"rf-text-xs rf-px-1.5 rf-py-0.5 rf-rounded rf-font-medium rf-flex-shrink-0 rf-bg-blue-100 rf-text-blue-700",children:"Direct lookup"}),o.source==="tscircuit.com"&&o.package.is_private&&q.jsx(oio,{className:"rf-ml-1 rf-h-3 rf-w-3 rf-text-zinc-400 rf-flex-shrink-0"})]}),o.source==="jlcpcb"&&n!=null?q.jsxs("div",{className:"rf-text-xs rf-text-zinc-500 rf-font-medium rf-whitespace-nowrap rf-flex-shrink-0 sm:rf-hidden",children:[n.toLocaleString()," in stock"]}):null]}),q.jsxs("div",{className:"rf-text-xs rf-text-zinc-500 rf-truncate rf-w-full",children:[E?q.jsx("span",{className:"rf-mr-2",children:E}):null,i]})]}),q.jsxs("div",{children:[o.source==="tscircuit.com"&&e?q.jsx("div",{className:"rf-flex-shrink-0 rf-w-full sm:rf-w-auto",children:q.jsx(Ei,{variant:"outline",size:"sm",className:"rf-text-xs rf-w-full sm:rf-w-auto",onClick:c=>{c.stopPropagation(),e(o)},children:"See Details"})}):o.source==="jlcpcb"&&n!=null?q.jsxs("div",{className:"rf-hidden sm:rf-block rf-text-xs rf-text-zinc-500 rf-font-medium rf-whitespace-nowrap rf-flex-shrink-0",children:[n.toLocaleString()," in stock"]}):null,s!=null&&q.jsx("div",{className:"rf-hidden sm:rf-block rf-text-xs rf-text-zinc-500 rf-font-medium rf-whitespace-nowrap rf-flex-shrink-0 rf-text-right",children:Kwo(s)})]})]},B)})})},Hwo=({circuitJson:g,error:A,isLoading:I,height:e})=>q.jsx("section",{className:"rf-flex rf-min-w-0 rf-items-center rf-justify-center",style:{height:e},children:I?q.jsxs("div",{className:"rf-flex rf-w-full rf-items-center rf-justify-center rf-gap-2 rf-bg-zinc-950 rf-text-sm rf-text-zinc-300",style:{height:e},children:[q.jsx(iS,{className:"rf-h-4 rf-w-4 rf-animate-spin"}),"Loading preview..."]}):A?q.jsx("div",{className:"rf-flex rf-w-full rf-items-center rf-justify-center rf-bg-zinc-950 rf-p-4",style:{height:e},children:q.jsxs("div",{className:"rf-flex rf-max-w-[320px] rf-items-start rf-gap-2 rf-text-sm rf-text-zinc-300",children:[q.jsx(meg,{className:"rf-mt-0.5 rf-h-4 rf-w-4 rf-flex-shrink-0"}),q.jsx("span",{children:A})]})}):g?q.jsx("div",{className:"rf-w-full rf-min-w-0 rf-overflow-hidden",children:q.jsx(weg,{circuitJson:g,height:e,allowEditing:!1,clickToInteractEnabled:!1,focusOnHover:!1,disablePcbGroups:!0})}):q.jsx("div",{className:"rf-flex rf-w-full rf-items-center rf-justify-center rf-bg-zinc-950 rf-text-sm rf-text-zinc-300",style:{height:e},children:"No preview"})}),FFI={importComponentDialog:101,importComponentDetailsDialog:102},vwo=({packageResult:g,isOpen:A,onOpenChange:I,isLoading:e,details:t,previewTab:o,onPreviewTabChange:B,isSubmitting:C,onImport:Q})=>{const i=g?.package??null,E=i?.latest_pcb_preview_image_url,n=i?.latest_sch_preview_image_url,s=i?.latest_cad_preview_image_url,r=i?.unscoped_name?.split("/").pop()??i?.unscoped_name,a=i?.org_owner_tscircuit_handle??void 0,c=a?`https://tscircuit.com/${a}`:void 0,h=a&&r?`https://tscircuit.com/${a}/${r}`:void 0;return q.jsx(j5,{open:A,onOpenChange:I,children:q.jsxs(W3,{showOverlay:!1,style:{width:"calc(100vw - 2rem)",zIndex:FFI.importComponentDetailsDialog},className:"rf-max-w-5xl no-scrollbar !rf-overflow-y-auto rf-max-h-[90vh] rf-overflow-hidden rf-flex rf-flex-col rf-rounded-sm",children:[q.jsx(V3,{className:"rf-pb-4 rf-border-b",children:q.jsx("div",{className:"rf-flex rf-items-start rf-justify-between rf-gap-4",children:q.jsxs("div",{className:"rf-flex-1 rf-min-w-0",children:[q.jsx(j3,{className:"rf-text-xl rf-font-semibold rf-truncate",children:r}),q.jsx(z5,{children:i?.description})]})})}),q.jsxs("div",{className:"rf-flex-1 rf-overflow-y-auto rf-py-4 rf-space-y-6",children:[a?q.jsxs("div",{children:[q.jsx("span",{className:"rf-text-xs rf-font-medium rf-text-gray-500 rf-uppercase rf-tracking-wide",children:"Created by"}),q.jsx("div",{className:"rf-mt-1 rf-text-sm rf-font-medium",children:c?q.jsx("a",{href:c,target:"_blank",rel:"noopener noreferrer",className:"rf-text-black hover:rf-underline",children:a}):a})]}):null,(s||E||n)&&q.jsx(q.Fragment,{children:q.jsxs("div",{children:[q.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-mb-4",children:"Preview"}),q.jsxs(A6A,{value:o,onValueChange:l=>B(l),children:[q.jsxs(ylA,{className:"rf-inline-flex rf-h-9 rf-items-center rf-justify-center rf-rounded-lg rf-bg-zinc-100 rf-p-1 rf-text-zinc-500 dark:rf-bg-zinc-800 dark:rf-text-zinc-400",children:[E&&q.jsx(gx,{value:"pcb",children:"PCB"}),n&&q.jsx(gx,{value:"schematic",children:"Schematic"}),s&&q.jsx(gx,{value:"3d",children:"3D"})]}),q.jsxs("div",{className:"rf-mt-4",children:[q.jsx(py,{value:"pcb",className:"rf-border rf-rounded-lg rf-overflow-hidden rf-bg-gray-50",children:E?q.jsx("img",{src:E,alt:`${r??"package"} PCB preview`,className:"rf-w-full rf-h-full rf-object-contain rf-bg-white rf-p-4"}):null}),q.jsx(py,{value:"schematic",className:"rf-border rf-rounded-lg rf-overflow-hidden rf-bg-gray-50",children:n?q.jsx("img",{src:n,alt:`${r??"package"} schematic preview`,className:"rf-w-full rf-h-full rf-object-contain rf-bg-white rf-p-4"}):null}),q.jsx(py,{value:"3d",className:"rf-border rf-rounded-lg rf-overflow-hidden rf-bg-gray-50",children:s?q.jsx("img",{src:s,alt:`${r??"package"} 3D preview`,className:"rf-w-full rf-h-full rf-object-contain rf-bg-white rf-p-4"}):null})]})]})]})}),t?.ai_description?q.jsxs("section",{children:[q.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-mb-3",children:"AI Description"}),q.jsx("div",{className:"rf-bg-gray-50 rf-border rf-border-gray-200 rf-rounded-lg rf-p-4",children:q.jsx("p",{className:"rf-text-sm rf-text-gray-700 rf-leading-relaxed",children:t.ai_description})})]}):null,t?.ai_usage_instructions?q.jsxs("section",{children:[q.jsx("h3",{className:"rf-text-lg rf-font-semibold rf-mb-3",children:"Usage Instructions"}),q.jsx("div",{className:"rf-bg-gray-50 rf-border rf-border-gray-200 rf-rounded-lg rf-p-4",children:q.jsx("p",{className:"rf-text-sm rf-text-gray-700 rf-leading-relaxed rf-whitespace-pre-wrap",children:t.ai_usage_instructions})})]}):null,e?q.jsxs("div",{className:"rf-flex rf-justify-center rf-items-center rf-gap-2 rf-text-gray-500",children:[q.jsx(iS,{className:"rf-h-4 rf-w-4 rf-animate-spin"}),q.jsx("span",{className:"rf-text-sm",children:"Loading package details..."})]}):null]}),q.jsxs(LZ,{className:"rf-pt-4 rf-border-t rf-flex rf-flex-col sm:rf-flex-row rf-justify-between rf-gap-2",children:[q.jsx("div",{className:"rf-flex-1",children:h?q.jsxs(Ei,{variant:"outline",size:"sm",className:"rf-gap-2 rf-w-full sm:rf-w-auto",onClick:()=>window.open(h,"_blank"),children:[q.jsx(XQo,{className:"rf-h-4 rf-w-4"}),"View on tscircuit.com"]}):null}),q.jsxs("div",{className:"rf-flex rf-flex-col sm:rf-flex-row rf-gap-2",children:[q.jsx(Ei,{variant:"outline",onClick:()=>I(!1),className:"rf-order-2 sm:rf-order-1",children:"Close"}),q.jsx(Ei,{onClick:Q,disabled:C,className:"rf-bg-blue-600 hover:rf-bg-blue-700",children:C?q.jsx(iS,{className:"rf-h-4 rf-w-4 rf-animate-spin"}):"Import Component"})]})]})]})})},qwo=()=>{const[g,A]=z.useState(null),[I,e]=z.useState(!1),t=z.useCallback(async(B,C)=>{e(!0);try{const Q=await fetch(`https://api.tscircuit.com/packages/get?name=${encodeURIComponent(`${B}/${C}`)}`);if(!Q.ok)throw new Error(`Failed to load package details: ${Q.status}`);const i=await Q.json();A(i.package??null)}catch(Q){console.error("Failed to fetch package details",Q),A(null)}finally{e(!1)}},[]),o=z.useCallback(()=>{A(null),e(!1)},[]);return{details:g,isLoading:I,fetchDetails:t,reset:o}},Two=(g,A)=>{const[I,e]=z.useState({circuitJson:null,error:null,isLoading:!1});return z.useEffect(()=>{if(!g||!NFI(g)){e({circuitJson:null,error:null,isLoading:!1});return}let t=!1;return e({circuitJson:null,error:null,isLoading:!0}),Uwo(g,A).then(o=>{t||e({circuitJson:o,error:null,isLoading:!1})}).catch(o=>{t||e({circuitJson:null,error:o instanceof Error?o.message:"Failed to load footprint preview",isLoading:!1})}),()=>{t=!0}},[g,A]),I},Zwo=async(g,A)=>{const I={"Content-Type":"application/json"};A&&(I.Authorization=`Bearer ${A}`);const e=await fetch("https://registry-api.tscircuit.com/packages/search",{method:"POST",headers:I,body:JSON.stringify({query:g})});if(!e.ok)throw new Error(`tscircuit registry error: ${e.status}`);return(await e.json()).packages??[]},Owo=({sessionToken:g})=>{const[A,I]=z.useState([]),[e,t]=z.useState(!1),[o,B]=z.useState(null),[C,Q]=z.useState(!1),i=z.useCallback(async n=>{const s=n.trim();if(!s)return[];t(!0),B(null);try{const a=(await Zwo(s,g)).map(c=>({source:"tscircuit.com",package:c}));return I(a),a}catch(r){return console.error("Error searching tscircuit packages",r),I([]),B(r instanceof Error?r.message:"Failed to search tscircuit packages"),[]}finally{t(!1),Q(!0)}},[g]),E=z.useCallback(()=>{I([]),t(!1),B(null),Q(!1)},[]);return{results:A,isSearching:e,error:o,hasSearched:C,search:i,reset:E}},Wwo=g=>{const A=/^C(\d+)$/i.exec(g.trim());if(!A)return null;const I=Number(A[1]);if(!Number.isSafeInteger(I))return null;const e=`C${A[1]}`;return{source:"jlcpcb",component:{lcscId:I,manufacturer:e,partNumber:e,description:"Import directly from EasyEDA; stock and availability are unknown",package:"",isDirectLookup:!0}}},UFI=(g,A)=>{const I=Wwo(g);return I?A.some(t=>t.component.partNumber.toUpperCase()===I.component.partNumber)?A:[I,...A]:A},Vwo=g=>{const A=g.trim();return/^C\d+/i.test(A)?A.replace(/^C/i,""):A},jwo=()=>{const[g,A]=z.useState([]),[I,e]=z.useState(!1),[t,o]=z.useState(null),[B,C]=z.useState(!1),Q=z.useCallback(async E=>{const n=Vwo(E);if(!n)return[];e(!0),o(null);try{const s=await Yyo(n,10),r=UFI(E,s.map(a=>({source:"jlcpcb",component:_yo(a)})));return A(r),r}catch(s){console.error("Error searching JLCPCB components",s);const r=UFI(E,[]);return A(r),o(r.length>0?null:s instanceof Error?s.message:"Failed to search JLCPCB components"),r}finally{e(!1),C(!0)}},[]),i=z.useCallback(()=>{A([]),e(!1),o(null),C(!1)},[]);return{results:g,isSearching:I,error:t,hasSearched:B,search:Q,reset:i}},zwo=()=>{const[g,A]=z.useState([]),[I,e]=z.useState(!1),[t,o]=z.useState(null),[B,C]=z.useState(!1),Q=z.useCallback(async E=>{const n=E.trim();if(!n)return[];e(!0),o(null);try{const r=(await Rwo(n,20)).map(a=>({source:"kicad",footprint:Nwo(a)}));return A(r),r}catch(s){return console.error("Error searching KiCad footprints",s),A([]),o(s instanceof Error?s.message:"Failed to search KiCad footprints"),[]}finally{e(!1),C(!0)}},[]),i=z.useCallback(()=>{A([]),e(!1),o(null),C(!1)},[]);return{results:g,isSearching:I,error:t,hasSearched:B,search:Q,reset:i}},Xwo=({onTscircuitPackageSelected:g,onJlcpcbComponentTsxLoaded:A,onKicadStringSelected:I})=>{const e=[];return g&&e.push("tscircuit.com"),A&&e.push("jlcpcb"),I&&e.push("kicad"),e},$wo=({isOpen:g,onClose:A,jlcpcbProxyRequestHeaders:I,onKicadStringSelected:e,onTscircuitPackageSelected:t,onJlcpcbComponentTsxLoaded:o,jlcpcbProxyApiBase:B,tscircuitSessionToken:C})=>{WeA();const Q=z.useMemo(()=>Xwo({onKicadStringSelected:e,onTscircuitPackageSelected:t,onJlcpcbComponentTsxLoaded:o}),[e,t,o]),i=Q.length>0,E=Q.length===1,[n,s]=z.useState(Q[0]??"tscircuit.com"),[r,a]=z.useState(""),[c,h]=z.useState(null),{results:l,isSearching:D,error:d,hasSearched:y,search:w,reset:u}=Owo({sessionToken:C}),{results:G,isSearching:m,error:p,hasSearched:k,search:S,reset:R}=jwo(),{results:x,isSearching:N,error:U,hasSearched:K,search:_,reset:b}=zwo(),{details:T,isLoading:j,fetchDetails:W,reset:O}=qwo(),[gA,tA]=z.useState(null),[IA,QA]=z.useState(!1),[nA,DA]=z.useState("pcb"),[CA,hA]=z.useState(null),[sA,cA]=z.useState(!1),SA=z.useMemo(()=>({jlcpcb:{headers:I,apiBase:B}}),[B,I]),{circuitJson:FA,error:aA,isLoading:xA}=Two(c,SA),RA=NFI(c);z.useEffect(()=>{hA(null)},[c]);const NA=z.useCallback(()=>{u(),R(),b(),h(null)},[R,b,u]);z.useEffect(()=>{g||(NA(),a(""),QA(!1),tA(null),hA(null))},[g,NA]),z.useEffect(()=>{a(""),h(null),n==="tscircuit.com"?u():n==="jlcpcb"?R():n==="kicad"&&b()},[n,R,b,u]);const YA=kA=>{h(kA),tA(kA),DA("pcb"),QA(!0),O();const OA=kA.package.org_owner_tscircuit_handle,$A=kA.package.unscoped_name;if(OA&&$A){const og=$A.split("/").pop()??$A;W(OA,og)}},PA=async()=>{r.trim()&&(h(null),n==="tscircuit.com"?await w(r):n==="jlcpcb"?await S(r):n==="kicad"&&await _(r))},mA=async kA=>{try{if(hA(null),cA(!0),kA.source==="kicad"){if(!e)throw new Error("KiCad handler not provided");await e({result:kA,footprint:kA.footprint.qualifiedName})}else if(kA.source==="jlcpcb"){if(!o)throw new Error("JLCPCB handler not provided");const OA=await byo(kA.component.partNumber,{headers:I,apiBase:B});await o({result:kA,tsx:OA})}else if(kA.source==="tscircuit.com"){if(!t)throw new Error("tscircuit package handler not provided");const OA=kA.package.org_owner_tscircuit_handle,$A=kA.package.unscoped_name;if(!OA||!$A)throw new Error("Missing package metadata");const og=$A.split("/").pop()??$A,dg=`@tsci/${OA}.${og}`;await t({result:kA,fullPackageName:dg})}return!0}catch(OA){return console.error("Failed to import component",OA),hA(OA instanceof Error?OA.message:"Failed to import component"),!1}finally{cA(!1)}};let LA=[],dA=!1,HA=null,WA=!1;n==="tscircuit.com"?(LA=l,dA=D,HA=d,WA=y):n==="jlcpcb"?(LA=G,dA=m,HA=p,WA=k):n==="kicad"&&(LA=x,dA=N,HA=U,WA=K);const Qg=async()=>{if(!c)return;await mA(c)&&(A(),NA(),a(""))},_A=kA=>{kA||A()},uA=kA=>{QA(kA),kA||tA(null)};return q.jsxs(j5,{open:g,onOpenChange:_A,children:[q.jsxs(W3,{style:{width:"calc(100vw - 2rem)",maxWidth:RA?"min(1120px, calc(100vw - 2rem))":"min(672px, calc(100vw - 2rem))",zIndex:FFI.importComponentDialog},className:"rf-rounded-sm rf-max-h-[90vh] rf-overflow-y-auto rf-overflow-x-hidden rf-flex rf-flex-col",children:[q.jsxs(V3,{children:[q.jsxs(j3,{className:"rf-text-lg sm:rf-text-xl",children:["Import ",E?yGA[n].label:""," ","Component"]}),q.jsx(z5,{className:"rf-text-sm",children:i?"Search for components from available sources.":"Import options are disabled because no handlers were provided."})]}),i?q.jsxs(A6A,{value:n,onValueChange:kA=>s(kA),className:"rf-min-w-0 rf-w-full",children:[!E&&q.jsx(ylA,{className:"rf-flex rf-w-full rf-gap-2",children:Q.map(kA=>q.jsx(gx,{value:kA,className:"rf-flex-1 rf-text-xs sm:rf-text-sm",children:yGA[kA].label},kA))}),q.jsxs("div",{className:"rf-min-w-0",style:RA?{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(360px, 0.95fr)",gap:"1.5rem",alignItems:"start"}:void 0,children:[q.jsxs("div",{className:"rf-min-w-0",children:[q.jsx(Jwo,{query:r,placeholder:yGA[n].placeholder,isSearching:dA,onQueryChange:a,onSubmit:PA}),q.jsx("div",{className:"no-scrollbar rf-mt-4 rf-flex-1 rf-min-h-[200px] !rf-max-h-[40vh] !rf-overflow-y-auto rf-overflow-x-hidden rf-border rf-rounded-md rf-min-w-0",children:dA?q.jsxs("div",{className:"rf-p-8 rf-text-center rf-text-zinc-500",children:[q.jsx(iS,{className:"rf-h-8 rf-w-8 rf-animate-spin rf-mx-auto rf-mb-2"}),q.jsx("p",{children:"Searching..."})]}):LA.length>0?q.jsx(bwo,{results:LA,selected:c,onSelect:h,onShowDetails:n==="tscircuit.com"?YA:void 0}):q.jsx("div",{className:"rf-p-8 rf-text-center rf-text-zinc-500",children:HA?`Error: ${HA}`:WA?yGA[n].emptyMessage:"Enter a search term to find components"})})]}),RA?q.jsx("div",{className:"rf-mt-4",children:q.jsx(Hwo,{circuitJson:FA,error:aA,isLoading:xA,height:325})}):null]})]}):null,CA?q.jsx("div",{className:"rf-text-sm rf-text-red-600 rf-mt-2",children:CA}):null,q.jsxs(LZ,{className:"rf-flex rf-flex-col sm:rf-flex-row rf-gap-2",children:[q.jsx(Ei,{variant:"outline",onClick:A,className:"rf-order-2 sm:rf-order-1",children:"Cancel"}),q.jsx(Ei,{onClick:Qg,disabled:!c||sA,className:"rf-order-1 sm:rf-order-2",children:sA?q.jsx(iS,{className:"rf-h-4 rf-w-4 rf-animate-spin"}):"Import"})]})]}),q.jsx(vwo,{packageResult:gA,isOpen:IA,onOpenChange:uA,isLoading:j,details:T,previewTab:nA,onPreviewTabChange:kA=>DA(kA),isSubmitting:sA,onImport:()=>{gA&&mA(gA).then(kA=>{kA&&(QA(!1),A(),NA(),a(""))})}})]})},Auo=g=>{const A=g.match(/export const (\w+) =/);if(!A)throw new Error("Could not determine component name from TSX contents");return A[1]},JFI=g=>{const A=Uc(B=>B.pushEvent),I=Uc(B=>B.upsertFile),e=async({result:B,fullPackageName:C})=>{const i=B.package.unscoped_name??B.package.name;await JC.promise(A({event_type:"INSTALL_PACKAGE",full_package_name:C}),{loading:`Requesting install for "${i}"`,success:`Install requested for "${i}"`,error:E=>`Failed to request install: ${E instanceof Error?E.message:String(E)}`})},t=async({footprint:B})=>{await JC.promise(navigator.clipboard.writeText(B),{loading:`Copying "${B}"`,success:`Copied "${B}" to clipboard`,error:C=>`Failed to copy footprint: ${C instanceof Error?C.message:String(C)}`})},o=async({result:B,tsx:C})=>{const i=`imports/${Auo(C)}.tsx`;await JC.promise(I(i,C),{loading:`Importing ${B.component.partNumber}`,success:`Imported to "${i}"`,error:E=>`Failed to import component: ${E instanceof Error?E.message:String(E)}`})};return q.jsx($wo,{...g,onTscircuitPackageSelected:e,onKicadStringSelected:t,onJlcpcbComponentTsxLoaded:o})};JFI.displayName="ImportComponentDialogForCli";const guo=async({circuitJson:g,projectName:A})=>{const{convertCircuitJsonToAltiumZip:I}=await Promise.resolve().then(()=>w5o),e=await I(g,A);return new Blob([new Uint8Array(e)],{type:"application/zip"})},Iuo=async({circuitJson:g,projectName:A})=>{await JC.promise((async()=>{const I=await guo({circuitJson:g,projectName:A});kk(I,{fileName:`${A}_altium_project.zip`})})(),{loading:"Generating Altium project...",success:"Altium project ZIP ready",error:I=>`Failed to generate Altium project: ${I instanceof Error?I.message:String(I)}`})};var Uog={exports:{}},PFI;function euo(){return PFI||(PFI=1,(function(g,A){var I={env:{},version:""};(function(e){g.exports=e()})(function(){return(function e(t,o,B){function C(E,n){if(!o[E]){if(!t[E]){var s=typeof bF=="function"&&bF;if(!n&&s)return s(E,!0);if(Q)return Q(E,!0);var r=new Error("Cannot find module '"+E+"'");throw r.code="MODULE_NOT_FOUND",r}var a=o[E]={exports:{}};t[E][0].call(a.exports,function(c){var h=t[E][1][c];return C(h||c)},a,a.exports,e,t,o,B)}return o[E].exports}for(var Q=typeof bF=="function"&&bF,i=0;i<B.length;i++)C(B[i]);return C})({1:[function(e,t,o){var B=e("./utils"),C=e("./support"),Q="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";o.encode=function(i){for(var E,n,s,r,a,c,h,l=[],D=0,d=i.length,y=d,w=B.getTypeOf(i)!=="string";D<i.length;)y=d-D,s=w?(E=i[D++],n=D<d?i[D++]:0,D<d?i[D++]:0):(E=i.charCodeAt(D++),n=D<d?i.charCodeAt(D++):0,D<d?i.charCodeAt(D++):0),r=E>>2,a=(3&E)<<4|n>>4,c=1<y?(15&n)<<2|s>>6:64,h=2<y?63&s:64,l.push(Q.charAt(r)+Q.charAt(a)+Q.charAt(c)+Q.charAt(h));return l.join("")},o.decode=function(i){var E,n,s,r,a,c,h=0,l=0,D="data:";if(i.substr(0,D.length)===D)throw new Error("Invalid base64 input, it looks like a data url.");var d,y=3*(i=i.replace(/[^A-Za-z0-9+/=]/g,"")).length/4;if(i.charAt(i.length-1)===Q.charAt(64)&&y--,i.charAt(i.length-2)===Q.charAt(64)&&y--,y%1!=0)throw new Error("Invalid base64 input, bad content length.");for(d=C.uint8array?new Uint8Array(0|y):new Array(0|y);h<i.length;)E=Q.indexOf(i.charAt(h++))<<2|(r=Q.indexOf(i.charAt(h++)))>>4,n=(15&r)<<4|(a=Q.indexOf(i.charAt(h++)))>>2,s=(3&a)<<6|(c=Q.indexOf(i.charAt(h++))),d[l++]=E,a!==64&&(d[l++]=n),c!==64&&(d[l++]=s);return d}},{"./support":30,"./utils":32}],2:[function(e,t,o){var B=e("./external"),C=e("./stream/DataWorker"),Q=e("./stream/Crc32Probe"),i=e("./stream/DataLengthProbe");function E(n,s,r,a,c){this.compressedSize=n,this.uncompressedSize=s,this.crc32=r,this.compression=a,this.compressedContent=c}E.prototype={getContentWorker:function(){var n=new C(B.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new i("data_length")),s=this;return n.on("end",function(){if(this.streamInfo.data_length!==s.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),n},getCompressedWorker:function(){return new C(B.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},E.createWorkerFrom=function(n,s,r){return n.pipe(new Q).pipe(new i("uncompressedSize")).pipe(s.compressWorker(r)).pipe(new i("compressedSize")).withStreamInfo("compression",s)},t.exports=E},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(e,t,o){var B=e("./stream/GenericWorker");o.STORE={magic:"\0\0",compressWorker:function(){return new B("STORE compression")},uncompressWorker:function(){return new B("STORE decompression")}},o.DEFLATE=e("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(e,t,o){var B=e("./utils"),C=(function(){for(var Q,i=[],E=0;E<256;E++){Q=E;for(var n=0;n<8;n++)Q=1&Q?3988292384^Q>>>1:Q>>>1;i[E]=Q}return i})();t.exports=function(Q,i){return Q!==void 0&&Q.length?B.getTypeOf(Q)!=="string"?(function(E,n,s,r){var a=C,c=r+s;E^=-1;for(var h=r;h<c;h++)E=E>>>8^a[255&(E^n[h])];return-1^E})(0|i,Q,Q.length,0):(function(E,n,s,r){var a=C,c=r+s;E^=-1;for(var h=r;h<c;h++)E=E>>>8^a[255&(E^n.charCodeAt(h))];return-1^E})(0|i,Q,Q.length,0):0}},{"./utils":32}],5:[function(e,t,o){o.base64=!1,o.binary=!1,o.dir=!1,o.createFolders=!0,o.date=null,o.compression=null,o.compressionOptions=null,o.comment=null,o.unixPermissions=null,o.dosPermissions=null},{}],6:[function(e,t,o){var B=null;B=typeof Promise<"u"?Promise:e("lie"),t.exports={Promise:B}},{lie:37}],7:[function(e,t,o){var B=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",C=e("pako"),Q=e("./utils"),i=e("./stream/GenericWorker"),E=B?"uint8array":"array";function n(s,r){i.call(this,"FlateWorker/"+s),this._pako=null,this._pakoAction=s,this._pakoOptions=r,this.meta={}}o.magic="\b\0",Q.inherits(n,i),n.prototype.processChunk=function(s){this.meta=s.meta,this._pako===null&&this._createPako(),this._pako.push(Q.transformTo(E,s.data),!1)},n.prototype.flush=function(){i.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},n.prototype.cleanUp=function(){i.prototype.cleanUp.call(this),this._pako=null},n.prototype._createPako=function(){this._pako=new C[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var s=this;this._pako.onData=function(r){s.push({data:r,meta:s.meta})}},o.compressWorker=function(s){return new n("Deflate",s)},o.uncompressWorker=function(){return new n("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(e,t,o){function B(a,c){var h,l="";for(h=0;h<c;h++)l+=String.fromCharCode(255&a),a>>>=8;return l}function C(a,c,h,l,D,d){var y,w,u=a.file,G=a.compression,m=d!==E.utf8encode,p=Q.transformTo("string",d(u.name)),k=Q.transformTo("string",E.utf8encode(u.name)),S=u.comment,R=Q.transformTo("string",d(S)),x=Q.transformTo("string",E.utf8encode(S)),N=k.length!==u.name.length,U=x.length!==S.length,K="",_="",b="",T=u.dir,j=u.date,W={crc32:0,compressedSize:0,uncompressedSize:0};c&&!h||(W.crc32=a.crc32,W.compressedSize=a.compressedSize,W.uncompressedSize=a.uncompressedSize);var O=0;c&&(O|=8),m||!N&&!U||(O|=2048);var gA=0,tA=0;T&&(gA|=16),D==="UNIX"?(tA=798,gA|=(function(QA,nA){var DA=QA;return QA||(DA=nA?16893:33204),(65535&DA)<<16})(u.unixPermissions,T)):(tA=20,gA|=(function(QA){return 63&(QA||0)})(u.dosPermissions)),y=j.getUTCHours(),y<<=6,y|=j.getUTCMinutes(),y<<=5,y|=j.getUTCSeconds()/2,w=j.getUTCFullYear()-1980,w<<=4,w|=j.getUTCMonth()+1,w<<=5,w|=j.getUTCDate(),N&&(_=B(1,1)+B(n(p),4)+k,K+="up"+B(_.length,2)+_),U&&(b=B(1,1)+B(n(R),4)+x,K+="uc"+B(b.length,2)+b);var IA="";return IA+=`
5669
5669
  \0`,IA+=B(O,2),IA+=G.magic,IA+=B(y,2),IA+=B(w,2),IA+=B(W.crc32,4),IA+=B(W.compressedSize,4),IA+=B(W.uncompressedSize,4),IA+=B(p.length,2),IA+=B(K.length,2),{fileRecord:s.LOCAL_FILE_HEADER+IA+p+K,dirRecord:s.CENTRAL_FILE_HEADER+B(tA,2)+IA+B(R.length,2)+"\0\0\0\0"+B(gA,4)+B(l,4)+p+K+R}}var Q=e("../utils"),i=e("../stream/GenericWorker"),E=e("../utf8"),n=e("../crc32"),s=e("../signature");function r(a,c,h,l){i.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=c,this.zipPlatform=h,this.encodeFileName=l,this.streamFiles=a,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}Q.inherits(r,i),r.prototype.push=function(a){var c=a.meta.percent||0,h=this.entriesCount,l=this._sources.length;this.accumulate?this.contentBuffer.push(a):(this.bytesWritten+=a.data.length,i.prototype.push.call(this,{data:a.data,meta:{currentFile:this.currentFile,percent:h?(c+100*(h-l-1))/h:100}}))},r.prototype.openedSource=function(a){this.currentSourceOffset=this.bytesWritten,this.currentFile=a.file.name;var c=this.streamFiles&&!a.file.dir;if(c){var h=C(a,c,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:h.fileRecord,meta:{percent:0}})}else this.accumulate=!0},r.prototype.closedSource=function(a){this.accumulate=!1;var c=this.streamFiles&&!a.file.dir,h=C(a,c,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(h.dirRecord),c)this.push({data:(function(l){return s.DATA_DESCRIPTOR+B(l.crc32,4)+B(l.compressedSize,4)+B(l.uncompressedSize,4)})(a),meta:{percent:100}});else for(this.push({data:h.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},r.prototype.flush=function(){for(var a=this.bytesWritten,c=0;c<this.dirRecords.length;c++)this.push({data:this.dirRecords[c],meta:{percent:100}});var h=this.bytesWritten-a,l=(function(D,d,y,w,u){var G=Q.transformTo("string",u(w));return s.CENTRAL_DIRECTORY_END+"\0\0\0\0"+B(D,2)+B(D,2)+B(d,4)+B(y,4)+B(G.length,2)+G})(this.dirRecords.length,h,a,this.zipComment,this.encodeFileName);this.push({data:l,meta:{percent:100}})},r.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume()},r.prototype.registerPrevious=function(a){this._sources.push(a);var c=this;return a.on("data",function(h){c.processChunk(h)}),a.on("end",function(){c.closedSource(c.previous.streamInfo),c._sources.length?c.prepareNextSource():c.end()}),a.on("error",function(h){c.error(h)}),this},r.prototype.resume=function(){return!!i.prototype.resume.call(this)&&(!this.previous&&this._sources.length?(this.prepareNextSource(),!0):this.previous||this._sources.length||this.generatedError?void 0:(this.end(),!0))},r.prototype.error=function(a){var c=this._sources;if(!i.prototype.error.call(this,a))return!1;for(var h=0;h<c.length;h++)try{c[h].error(a)}catch{}return!0},r.prototype.lock=function(){i.prototype.lock.call(this);for(var a=this._sources,c=0;c<a.length;c++)a[c].lock()},t.exports=r},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(e,t,o){var B=e("../compressions"),C=e("./ZipFileWorker");o.generateWorker=function(Q,i,E){var n=new C(i.streamFiles,E,i.platform,i.encodeFileName),s=0;try{Q.forEach(function(r,a){s++;var c=(function(d,y){var w=d||y,u=B[w];if(!u)throw new Error(w+" is not a valid compression method !");return u})(a.options.compression,i.compression),h=a.options.compressionOptions||i.compressionOptions||{},l=a.dir,D=a.date;a._compressWorker(c,h).withStreamInfo("file",{name:r,dir:l,date:D,comment:a.comment||"",unixPermissions:a.unixPermissions,dosPermissions:a.dosPermissions}).pipe(n)}),n.entriesCount=s}catch(r){n.error(r)}return n}},{"../compressions":3,"./ZipFileWorker":8}],10:[function(e,t,o){function B(){if(!(this instanceof B))return new B;if(arguments.length)throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");this.files=Object.create(null),this.comment=null,this.root="",this.clone=function(){var C=new B;for(var Q in this)typeof this[Q]!="function"&&(C[Q]=this[Q]);return C}}(B.prototype=e("./object")).loadAsync=e("./load"),B.support=e("./support"),B.defaults=e("./defaults"),B.version="3.10.2",B.loadAsync=function(C,Q){return new B().loadAsync(C,Q)},B.external=e("./external"),t.exports=B},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(e,t,o){var B=e("./utils"),C=e("./external"),Q=e("./utf8"),i=e("./zipEntries"),E=e("./stream/Crc32Probe"),n=e("./nodejsUtils");function s(r){return new C.Promise(function(a,c){var h=r.decompressed.getContentWorker().pipe(new E);h.on("error",function(l){c(l)}).on("end",function(){h.streamInfo.crc32!==r.decompressed.crc32?c(new Error("Corrupted zip : CRC32 mismatch")):a()}).resume()})}t.exports=function(r,a){var c=this;return a=B.extend(a||{},{base64:!1,checkCRC32:!1,optimizedBinaryString:!1,createFolders:!1,decodeFileName:Q.utf8decode}),n.isNode&&n.isStream(r)?C.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")):B.prepareContent("the loaded zip file",r,!0,a.optimizedBinaryString,a.base64).then(function(h){var l=new i(a);return l.load(h),l}).then(function(h){var l=[C.Promise.resolve(h)],D=h.files;if(a.checkCRC32)for(var d=0;d<D.length;d++)l.push(s(D[d]));return C.Promise.all(l)}).then(function(h){for(var l=h.shift(),D=l.files,d=0;d<D.length;d++){var y=D[d],w=y.fileNameStr,u=B.resolve(y.fileNameStr);c.file(u,y.decompressed,{binary:!0,optimizedBinaryString:!0,date:y.date,dir:y.dir,comment:y.fileCommentStr.length?y.fileCommentStr:null,unixPermissions:y.unixPermissions,dosPermissions:y.dosPermissions,createFolders:a.createFolders}),y.dir||(c.file(u).unsafeOriginalName=w)}return l.zipComment.length&&(c.comment=l.zipComment),c})}},{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(e,t,o){var B=e("../utils"),C=e("../stream/GenericWorker");function Q(i,E){C.call(this,"Nodejs stream input adapter for "+i),this._upstreamEnded=!1,this._bindStream(E)}B.inherits(Q,C),Q.prototype._bindStream=function(i){var E=this;(this._stream=i).pause(),i.on("data",function(n){E.push({data:n,meta:{percent:0}})}).on("error",function(n){E.isPaused?this.generatedError=n:E.error(n)}).on("end",function(){E.isPaused?E._upstreamEnded=!0:E.end()})},Q.prototype.pause=function(){return!!C.prototype.pause.call(this)&&(this._stream.pause(),!0)},Q.prototype.resume=function(){return!!C.prototype.resume.call(this)&&(this._upstreamEnded?this.end():this._stream.resume(),!0)},t.exports=Q},{"../stream/GenericWorker":28,"../utils":32}],13:[function(e,t,o){var B=e("readable-stream").Readable;function C(Q,i,E){B.call(this,i),this._helper=Q;var n=this;Q.on("data",function(s,r){n.push(s)||n._helper.pause(),E&&E(r)}).on("error",function(s){n.emit("error",s)}).on("end",function(){n.push(null)})}e("../utils").inherits(C,B),C.prototype._read=function(){this._helper.resume()},t.exports=C},{"../utils":32,"readable-stream":16}],14:[function(e,t,o){t.exports={isNode:typeof Buffer<"u",newBufferFrom:function(B,C){if(Buffer.from&&Buffer.from!==Uint8Array.from)return Buffer.from(B,C);if(typeof B=="number")throw new Error('The "data" argument must not be a number');return new Buffer(B,C)},allocBuffer:function(B){if(Buffer.alloc)return Buffer.alloc(B);var C=new Buffer(B);return C.fill(0),C},isBuffer:function(B){return Buffer.isBuffer(B)},isStream:function(B){return B&&typeof B.on=="function"&&typeof B.pause=="function"&&typeof B.resume=="function"}}},{}],15:[function(e,t,o){function B(u,G,m){var p,k=Q.getTypeOf(G),S=Q.extend(m||{},n);S.date=S.date||new Date,S.compression!==null&&(S.compression=S.compression.toUpperCase()),typeof S.unixPermissions=="string"&&(S.unixPermissions=parseInt(S.unixPermissions,8)),S.unixPermissions&&16384&S.unixPermissions&&(S.dir=!0),S.dosPermissions&&16&S.dosPermissions&&(S.dir=!0),S.dir&&(u=D(u)),S.createFolders&&(p=l(u))&&d.call(this,p,!0);var R=k==="string"&&S.binary===!1&&S.base64===!1;m&&m.binary!==void 0||(S.binary=!R),(G instanceof s&&G.uncompressedSize===0||S.dir||!G||G.length===0)&&(S.base64=!1,S.binary=!0,G="",S.compression="STORE",k="string");var x=null;x=G instanceof s||G instanceof i?G:c.isNode&&c.isStream(G)?new h(u,G):Q.prepareContent(u,G,S.binary,S.optimizedBinaryString,S.base64);var N=new r(u,x,S);this.files[u]=N}var C=e("./utf8"),Q=e("./utils"),i=e("./stream/GenericWorker"),E=e("./stream/StreamHelper"),n=e("./defaults"),s=e("./compressedObject"),r=e("./zipObject"),a=e("./generate"),c=e("./nodejsUtils"),h=e("./nodejs/NodejsStreamInputAdapter"),l=function(u){u.slice(-1)==="/"&&(u=u.substring(0,u.length-1));var G=u.lastIndexOf("/");return 0<G?u.substring(0,G):""},D=function(u){return u.slice(-1)!=="/"&&(u+="/"),u},d=function(u,G){return G=G!==void 0?G:n.createFolders,u=D(u),this.files[u]||B.call(this,u,null,{dir:!0,createFolders:G}),this.files[u]};function y(u){return Object.prototype.toString.call(u)==="[object RegExp]"}var w={load:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},forEach:function(u){var G,m,p;for(G in this.files)p=this.files[G],(m=G.slice(this.root.length,G.length))&&G.slice(0,this.root.length)===this.root&&u(m,p)},filter:function(u){var G=[];return this.forEach(function(m,p){u(m,p)&&G.push(p)}),G},file:function(u,G,m){if(arguments.length!==1)return u=this.root+u,B.call(this,u,G,m),this;if(y(u)){var p=u;return this.filter(function(S,R){return!R.dir&&p.test(S)})}var k=this.files[this.root+u];return k&&!k.dir?k:null},folder:function(u){if(!u)return this;if(y(u))return this.filter(function(k,S){return S.dir&&u.test(k)});var G=this.root+u,m=d.call(this,G),p=this.clone();return p.root=m.name,p},remove:function(u){u=this.root+u;var G=this.files[u];if(G||(u.slice(-1)!=="/"&&(u+="/"),G=this.files[u]),G&&!G.dir)delete this.files[u];else for(var m=this.filter(function(k,S){return S.name.slice(0,u.length)===u}),p=0;p<m.length;p++)delete this.files[m[p].name];return this},generate:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},generateInternalStream:function(u){var G,m={};try{if((m=Q.extend(u||{},{streamFiles:!1,compression:"STORE",compressionOptions:null,type:"",platform:"DOS",comment:null,mimeType:"application/zip",encodeFileName:C.utf8encode})).type=m.type.toLowerCase(),m.compression=m.compression.toUpperCase(),m.type==="binarystring"&&(m.type="string"),!m.type)throw new Error("No output type specified.");Q.checkSupport(m.type),m.platform!=="darwin"&&m.platform!=="freebsd"&&m.platform!=="linux"&&m.platform!=="sunos"||(m.platform="UNIX"),m.platform==="win32"&&(m.platform="DOS");var p=m.comment||this.comment||"";G=a.generateWorker(this,m,p)}catch(k){(G=new i("error")).error(k)}return new E(G,m.type||"string",m.mimeType)},generateAsync:function(u,G){return this.generateInternalStream(u).accumulate(G)},generateNodeStream:function(u,G){return(u=u||{}).type||(u.type="nodebuffer"),this.generateInternalStream(u).toNodejsStream(G)}};t.exports=w},{"./compressedObject":2,"./defaults":5,"./generate":9,"./nodejs/NodejsStreamInputAdapter":12,"./nodejsUtils":14,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31,"./utils":32,"./zipObject":35}],16:[function(e,t,o){t.exports=e("stream")},{stream:void 0}],17:[function(e,t,o){var B=e("./DataReader");function C(Q){B.call(this,Q);for(var i=0;i<this.data.length;i++)Q[i]=255&Q[i]}e("../utils").inherits(C,B),C.prototype.byteAt=function(Q){return this.data[this.zero+Q]},C.prototype.lastIndexOfSignature=function(Q){for(var i=Q.charCodeAt(0),E=Q.charCodeAt(1),n=Q.charCodeAt(2),s=Q.charCodeAt(3),r=this.length-4;0<=r;--r)if(this.data[r]===i&&this.data[r+1]===E&&this.data[r+2]===n&&this.data[r+3]===s)return r-this.zero;return-1},C.prototype.readAndCheckSignature=function(Q){var i=Q.charCodeAt(0),E=Q.charCodeAt(1),n=Q.charCodeAt(2),s=Q.charCodeAt(3),r=this.readData(4);return i===r[0]&&E===r[1]&&n===r[2]&&s===r[3]},C.prototype.readData=function(Q){if(this.checkOffset(Q),Q===0)return[];var i=this.data.slice(this.zero+this.index,this.zero+this.index+Q);return this.index+=Q,i},t.exports=C},{"../utils":32,"./DataReader":18}],18:[function(e,t,o){var B=e("../utils");function C(Q){this.data=Q,this.length=Q.length,this.index=0,this.zero=0}C.prototype={checkOffset:function(Q){this.checkIndex(this.index+Q)},checkIndex:function(Q){if(this.length<this.zero+Q||Q<0)throw new Error("End of data reached (data length = "+this.length+", asked index = "+Q+"). Corrupted zip ?")},setIndex:function(Q){this.checkIndex(Q),this.index=Q},skip:function(Q){this.setIndex(this.index+Q)},byteAt:function(){},readInt:function(Q){var i,E=0;for(this.checkOffset(Q),i=this.index+Q-1;i>=this.index;i--)E=(E<<8)+this.byteAt(i);return this.index+=Q,E},readString:function(Q){return B.transformTo("string",this.readData(Q))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var Q=this.readInt(4);return new Date(Date.UTC(1980+(Q>>25&127),(Q>>21&15)-1,Q>>16&31,Q>>11&31,Q>>5&63,(31&Q)<<1))}},t.exports=C},{"../utils":32}],19:[function(e,t,o){var B=e("./Uint8ArrayReader");function C(Q){B.call(this,Q)}e("../utils").inherits(C,B),C.prototype.readData=function(Q){this.checkOffset(Q);var i=this.data.slice(this.zero+this.index,this.zero+this.index+Q);return this.index+=Q,i},t.exports=C},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(e,t,o){var B=e("./DataReader");function C(Q){B.call(this,Q)}e("../utils").inherits(C,B),C.prototype.byteAt=function(Q){return this.data.charCodeAt(this.zero+Q)},C.prototype.lastIndexOfSignature=function(Q){return this.data.lastIndexOf(Q)-this.zero},C.prototype.readAndCheckSignature=function(Q){return Q===this.readData(4)},C.prototype.readData=function(Q){this.checkOffset(Q);var i=this.data.slice(this.zero+this.index,this.zero+this.index+Q);return this.index+=Q,i},t.exports=C},{"../utils":32,"./DataReader":18}],21:[function(e,t,o){var B=e("./ArrayReader");function C(Q){B.call(this,Q)}e("../utils").inherits(C,B),C.prototype.readData=function(Q){if(this.checkOffset(Q),Q===0)return new Uint8Array(0);var i=this.data.subarray(this.zero+this.index,this.zero+this.index+Q);return this.index+=Q,i},t.exports=C},{"../utils":32,"./ArrayReader":17}],22:[function(e,t,o){var B=e("../utils"),C=e("../support"),Q=e("./ArrayReader"),i=e("./StringReader"),E=e("./NodeBufferReader"),n=e("./Uint8ArrayReader");t.exports=function(s){var r=B.getTypeOf(s);return B.checkSupport(r),r!=="string"||C.uint8array?r==="nodebuffer"?new E(s):C.uint8array?new n(B.transformTo("uint8array",s)):new Q(B.transformTo("array",s)):new i(s)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(e,t,o){o.LOCAL_FILE_HEADER="PK",o.CENTRAL_FILE_HEADER="PK",o.CENTRAL_DIRECTORY_END="PK",o.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",o.ZIP64_CENTRAL_DIRECTORY_END="PK",o.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(e,t,o){var B=e("./GenericWorker"),C=e("../utils");function Q(i){B.call(this,"ConvertWorker to "+i),this.destType=i}C.inherits(Q,B),Q.prototype.processChunk=function(i){this.push({data:C.transformTo(this.destType,i.data),meta:i.meta})},t.exports=Q},{"../utils":32,"./GenericWorker":28}],25:[function(e,t,o){var B=e("./GenericWorker"),C=e("../crc32");function Q(){B.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}e("../utils").inherits(Q,B),Q.prototype.processChunk=function(i){this.streamInfo.crc32=C(i.data,this.streamInfo.crc32||0),this.push(i)},t.exports=Q},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(e,t,o){var B=e("../utils"),C=e("./GenericWorker");function Q(i){C.call(this,"DataLengthProbe for "+i),this.propName=i,this.withStreamInfo(i,0)}B.inherits(Q,C),Q.prototype.processChunk=function(i){if(i){var E=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=E+i.data.length}C.prototype.processChunk.call(this,i)},t.exports=Q},{"../utils":32,"./GenericWorker":28}],27:[function(e,t,o){var B=e("../utils"),C=e("./GenericWorker");function Q(i){C.call(this,"DataWorker");var E=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,i.then(function(n){E.dataIsReady=!0,E.data=n,E.max=n&&n.length||0,E.type=B.getTypeOf(n),E.isPaused||E._tickAndRepeat()},function(n){E.error(n)})}B.inherits(Q,C),Q.prototype.cleanUp=function(){C.prototype.cleanUp.call(this),this.data=null},Q.prototype.resume=function(){return!!C.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,B.delay(this._tickAndRepeat,[],this)),!0)},Q.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(B.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},Q.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var i=null,E=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":i=this.data.substring(this.index,E);break;case"uint8array":i=this.data.subarray(this.index,E);break;case"array":case"nodebuffer":i=this.data.slice(this.index,E)}return this.index=E,this.push({data:i,meta:{percent:this.max?this.index/this.max*100:0}})},t.exports=Q},{"../utils":32,"./GenericWorker":28}],28:[function(e,t,o){function B(C){this.name=C||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}B.prototype={push:function(C){this.emit("data",C)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(C){this.emit("error",C)}return!0},error:function(C){return!this.isFinished&&(this.isPaused?this.generatedError=C:(this.isFinished=!0,this.emit("error",C),this.previous&&this.previous.error(C),this.cleanUp()),!0)},on:function(C,Q){return this._listeners[C].push(Q),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(C,Q){if(this._listeners[C])for(var i=0;i<this._listeners[C].length;i++)this._listeners[C][i].call(this,Q)},pipe:function(C){return C.registerPrevious(this)},registerPrevious:function(C){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.streamInfo=C.streamInfo,this.mergeStreamInfo(),this.previous=C;var Q=this;return C.on("data",function(i){Q.processChunk(i)}),C.on("end",function(){Q.end()}),C.on("error",function(i){Q.error(i)}),this},pause:function(){return!this.isPaused&&!this.isFinished&&(this.isPaused=!0,this.previous&&this.previous.pause(),!0)},resume:function(){if(!this.isPaused||this.isFinished)return!1;var C=this.isPaused=!1;return this.generatedError&&(this.error(this.generatedError),C=!0),this.previous&&this.previous.resume(),!C},flush:function(){},processChunk:function(C){this.push(C)},withStreamInfo:function(C,Q){return this.extraStreamInfo[C]=Q,this.mergeStreamInfo(),this},mergeStreamInfo:function(){for(var C in this.extraStreamInfo)Object.prototype.hasOwnProperty.call(this.extraStreamInfo,C)&&(this.streamInfo[C]=this.extraStreamInfo[C])},lock:function(){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.isLocked=!0,this.previous&&this.previous.lock()},toString:function(){var C="Worker "+this.name;return this.previous?this.previous+" -> "+C:C}},t.exports=B},{}],29:[function(e,t,o){var B=e("../utils"),C=e("./ConvertWorker"),Q=e("./GenericWorker"),i=e("../base64"),E=e("../support"),n=e("../external"),s=null;if(E.nodestream)try{s=e("../nodejs/NodejsStreamOutputAdapter")}catch{}function r(c,h){return new n.Promise(function(l,D){var d=[],y=c._internalType,w=c._outputType,u=c._mimeType;c.on("data",function(G,m){d.push(G),h&&h(m)}).on("error",function(G){d=[],D(G)}).on("end",function(){try{var G=(function(m,p,k){switch(m){case"blob":return B.newBlob(B.transformTo("arraybuffer",p),k);case"base64":return i.encode(p);default:return B.transformTo(m,p)}})(w,(function(m,p){var k,S=0,R=null,x=0;for(k=0;k<p.length;k++)x+=p[k].length;switch(m){case"string":return p.join("");case"array":return Array.prototype.concat.apply([],p);case"uint8array":for(R=new Uint8Array(x),k=0;k<p.length;k++)R.set(p[k],S),S+=p[k].length;return R;case"nodebuffer":return Buffer.concat(p);default:throw new Error("concat : unsupported type '"+m+"'")}})(y,d),u);l(G)}catch(m){D(m)}d=[]}).resume()})}function a(c,h,l){var D=h;switch(h){case"blob":case"arraybuffer":D="uint8array";break;case"base64":D="string"}try{this._internalType=D,this._outputType=h,this._mimeType=l,B.checkSupport(D),this._worker=c.pipe(new C(D)),c.lock()}catch(d){this._worker=new Q("error"),this._worker.error(d)}}a.prototype={accumulate:function(c){return r(this,c)},on:function(c,h){var l=this;return c==="data"?this._worker.on(c,function(D){h.call(l,D.data,D.meta)}):this._worker.on(c,function(){B.delay(h,arguments,l)}),this},resume:function(){return B.delay(this._worker.resume,[],this._worker),this},pause:function(){return this._worker.pause(),this},toNodejsStream:function(c){if(B.checkSupport("nodestream"),this._outputType!=="nodebuffer")throw new Error(this._outputType+" is not supported by this method");return new s(this,{objectMode:this._outputType!=="nodebuffer"},c)}},t.exports=a},{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(e,t,o){if(o.base64=!0,o.array=!0,o.string=!0,o.arraybuffer=typeof ArrayBuffer<"u"&&typeof Uint8Array<"u",o.nodebuffer=typeof Buffer<"u",o.uint8array=typeof Uint8Array<"u",typeof ArrayBuffer>"u")o.blob=!1;else{var B=new ArrayBuffer(0);try{o.blob=new Blob([B],{type:"application/zip"}).size===0}catch{try{var C=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);C.append(B),o.blob=C.getBlob("application/zip").size===0}catch{o.blob=!1}}}try{o.nodestream=!!e("readable-stream").Readable}catch{o.nodestream=!1}},{"readable-stream":16}],31:[function(e,t,o){for(var B=e("./utils"),C=e("./support"),Q=e("./nodejsUtils"),i=e("./stream/GenericWorker"),E=new Array(256),n=0;n<256;n++)E[n]=252<=n?6:248<=n?5:240<=n?4:224<=n?3:192<=n?2:1;E[254]=E[254]=1;function s(){i.call(this,"utf-8 decode"),this.leftOver=null}function r(){i.call(this,"utf-8 encode")}o.utf8encode=function(a){return C.nodebuffer?Q.newBufferFrom(a,"utf-8"):(function(c){var h,l,D,d,y,w=c.length,u=0;for(d=0;d<w;d++)(64512&(l=c.charCodeAt(d)))==55296&&d+1<w&&(64512&(D=c.charCodeAt(d+1)))==56320&&(l=65536+(l-55296<<10)+(D-56320),d++),u+=l<128?1:l<2048?2:l<65536?3:4;for(h=C.uint8array?new Uint8Array(u):new Array(u),d=y=0;y<u;d++)(64512&(l=c.charCodeAt(d)))==55296&&d+1<w&&(64512&(D=c.charCodeAt(d+1)))==56320&&(l=65536+(l-55296<<10)+(D-56320),d++),l<128?h[y++]=l:(l<2048?h[y++]=192|l>>>6:(l<65536?h[y++]=224|l>>>12:(h[y++]=240|l>>>18,h[y++]=128|l>>>12&63),h[y++]=128|l>>>6&63),h[y++]=128|63&l);return h})(a)},o.utf8decode=function(a){return C.nodebuffer?B.transformTo("nodebuffer",a).toString("utf-8"):(function(c){var h,l,D,d,y=c.length,w=new Array(2*y);for(h=l=0;h<y;)if((D=c[h++])<128)w[l++]=D;else if(4<(d=E[D]))w[l++]=65533,h+=d-1;else{for(D&=d===2?31:d===3?15:7;1<d&&h<y;)D=D<<6|63&c[h++],d--;1<d?w[l++]=65533:D<65536?w[l++]=D:(D-=65536,w[l++]=55296|D>>10&1023,w[l++]=56320|1023&D)}return w.length!==l&&(w.subarray?w=w.subarray(0,l):w.length=l),B.applyFromCharCode(w)})(a=B.transformTo(C.uint8array?"uint8array":"array",a))},B.inherits(s,i),s.prototype.processChunk=function(a){var c=B.transformTo(C.uint8array?"uint8array":"array",a.data);if(this.leftOver&&this.leftOver.length){if(C.uint8array){var h=c;(c=new Uint8Array(h.length+this.leftOver.length)).set(this.leftOver,0),c.set(h,this.leftOver.length)}else c=this.leftOver.concat(c);this.leftOver=null}var l=(function(d,y){var w;for((y=y||d.length)>d.length&&(y=d.length),w=y-1;0<=w&&(192&d[w])==128;)w--;return w<0||w===0?y:w+E[d[w]]>y?w:y})(c),D=c;l!==c.length&&(C.uint8array?(D=c.subarray(0,l),this.leftOver=c.subarray(l,c.length)):(D=c.slice(0,l),this.leftOver=c.slice(l,c.length))),this.push({data:o.utf8decode(D),meta:a.meta})},s.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:o.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},o.Utf8DecodeWorker=s,B.inherits(r,i),r.prototype.processChunk=function(a){this.push({data:o.utf8encode(a.data),meta:a.meta})},o.Utf8EncodeWorker=r},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(e,t,o){var B=e("./support"),C=e("./base64"),Q=e("./nodejsUtils"),i=e("./external");function E(h){return h}function n(h,l){for(var D=0;D<h.length;++D)l[D]=255&h.charCodeAt(D);return l}e("setimmediate"),o.newBlob=function(h,l){o.checkSupport("blob");try{return new Blob([h],{type:l})}catch{try{var D=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return D.append(h),D.getBlob(l)}catch{throw new Error("Bug : can't construct the Blob.")}}};var s={stringifyByChunk:function(h,l,D){var d=[],y=0,w=h.length;if(w<=D)return String.fromCharCode.apply(null,h);for(;y<w;)l==="array"||l==="nodebuffer"?d.push(String.fromCharCode.apply(null,h.slice(y,Math.min(y+D,w)))):d.push(String.fromCharCode.apply(null,h.subarray(y,Math.min(y+D,w)))),y+=D;return d.join("")},stringifyByChar:function(h){for(var l="",D=0;D<h.length;D++)l+=String.fromCharCode(h[D]);return l},applyCanBeUsed:{uint8array:(function(){try{return B.uint8array&&String.fromCharCode.apply(null,new Uint8Array(1)).length===1}catch{return!1}})(),nodebuffer:(function(){try{return B.nodebuffer&&String.fromCharCode.apply(null,Q.allocBuffer(1)).length===1}catch{return!1}})()}};function r(h){var l=65536,D=o.getTypeOf(h),d=!0;if(D==="uint8array"?d=s.applyCanBeUsed.uint8array:D==="nodebuffer"&&(d=s.applyCanBeUsed.nodebuffer),d)for(;1<l;)try{return s.stringifyByChunk(h,D,l)}catch{l=Math.floor(l/2)}return s.stringifyByChar(h)}function a(h,l){for(var D=0;D<h.length;D++)l[D]=h[D];return l}o.applyFromCharCode=r;var c={};c.string={string:E,array:function(h){return n(h,new Array(h.length))},arraybuffer:function(h){return c.string.uint8array(h).buffer},uint8array:function(h){return n(h,new Uint8Array(h.length))},nodebuffer:function(h){return n(h,Q.allocBuffer(h.length))}},c.array={string:r,array:E,arraybuffer:function(h){return new Uint8Array(h).buffer},uint8array:function(h){return new Uint8Array(h)},nodebuffer:function(h){return Q.newBufferFrom(h)}},c.arraybuffer={string:function(h){return r(new Uint8Array(h))},array:function(h){return a(new Uint8Array(h),new Array(h.byteLength))},arraybuffer:E,uint8array:function(h){return new Uint8Array(h)},nodebuffer:function(h){return Q.newBufferFrom(new Uint8Array(h))}},c.uint8array={string:r,array:function(h){return a(h,new Array(h.length))},arraybuffer:function(h){return h.buffer},uint8array:E,nodebuffer:function(h){return Q.newBufferFrom(h)}},c.nodebuffer={string:r,array:function(h){return a(h,new Array(h.length))},arraybuffer:function(h){return c.nodebuffer.uint8array(h).buffer},uint8array:function(h){return a(h,new Uint8Array(h.length))},nodebuffer:E},o.transformTo=function(h,l){if(l=l||"",!h)return l;o.checkSupport(h);var D=o.getTypeOf(l);return c[D][h](l)},o.resolve=function(h){for(var l=h.split("/"),D=[],d=0;d<l.length;d++){var y=l[d];y==="."||y===""&&d!==0&&d!==l.length-1||(y===".."?D.pop():D.push(y))}return D.join("/")},o.getTypeOf=function(h){if(typeof h=="string")return"string";var l=Object.prototype.toString.call(h);return l==="[object Array]"?"array":B.nodebuffer&&Q.isBuffer(h)?"nodebuffer":B.uint8array&&l==="[object Uint8Array]"?"uint8array":B.arraybuffer&&l==="[object ArrayBuffer]"?"arraybuffer":void 0},o.checkSupport=function(h){if(!B[h.toLowerCase()])throw new Error(h+" is not supported by this platform")},o.MAX_VALUE_16BITS=65535,o.MAX_VALUE_32BITS=-1,o.pretty=function(h){var l,D,d="";for(D=0;D<(h||"").length;D++)d+="\\x"+((l=h.charCodeAt(D))<16?"0":"")+l.toString(16).toUpperCase();return d},o.delay=function(h,l,D){setImmediate(function(){h.apply(D||null,l||[])})},o.inherits=function(h,l){function D(){}D.prototype=l.prototype,h.prototype=new D},o.extend=function(){var h,l,D={};for(h=0;h<arguments.length;h++)for(l in arguments[h])Object.prototype.hasOwnProperty.call(arguments[h],l)&&D[l]===void 0&&(D[l]=arguments[h][l]);return D},o.prepareContent=function(h,l,D,d,y){return i.Promise.resolve(l).then(function(w){return B.blob&&(w instanceof Blob||["[object File]","[object Blob]"].indexOf(Object.prototype.toString.call(w))!==-1)?Blob.prototype.arrayBuffer!==void 0?w.arrayBuffer():typeof FileReader<"u"?new i.Promise(function(u,G){var m=new FileReader;m.onload=function(p){u(p.target.result)},m.onerror=function(p){G(p.target.error)},m.readAsArrayBuffer(w)}):i.Promise.reject(new Error(h+" is a Blob, but we have no way of reading it.")):w}).then(function(w){var u=o.getTypeOf(w);return u?(u==="arraybuffer"?w=o.transformTo("uint8array",w):u==="string"&&(y?w=C.decode(w):D&&d!==!0&&(w=(function(G){return n(G,B.uint8array?new Uint8Array(G.length):new Array(G.length))})(w))),w):i.Promise.reject(new Error("Can't read the data of '"+h+"'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"))})}},{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,setimmediate:54}],33:[function(e,t,o){var B=e("./reader/readerFor"),C=e("./utils"),Q=e("./signature"),i=e("./zipEntry"),E=e("./support");function n(s){this.files=[],this.loadOptions=s}n.prototype={checkSignature:function(s){if(!this.reader.readAndCheckSignature(s)){this.reader.index-=4;var r=this.reader.readString(4);throw new Error("Corrupted zip or bug: unexpected signature ("+C.pretty(r)+", expected "+C.pretty(s)+")")}},isSignature:function(s,r){var a=this.reader.index;this.reader.setIndex(s);var c=this.reader.readString(4)===r;return this.reader.setIndex(a),c},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2);var s=this.reader.readData(this.zipCommentLength),r=E.uint8array?"uint8array":"array",a=C.transformTo(r,s);this.zipComment=this.loadOptions.decodeFileName(a)},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.reader.skip(4),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};for(var s,r,a,c=this.zip64EndOfCentralSize-44;0<c;)s=this.reader.readInt(2),r=this.reader.readInt(4),a=this.reader.readData(r),this.zip64ExtensibleData[s]={id:s,length:r,value:a}},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),1<this.disksCount)throw new Error("Multi-volumes zip are not supported")},readLocalFiles:function(){var s,r;for(s=0;s<this.files.length;s++)r=this.files[s],this.reader.setIndex(r.localHeaderOffset),this.checkSignature(Q.LOCAL_FILE_HEADER),r.readLocalPart(this.reader),r.handleUTF8(),r.processAttributes()},readCentralDir:function(){var s;for(this.reader.setIndex(this.centralDirOffset);this.reader.readAndCheckSignature(Q.CENTRAL_FILE_HEADER);)(s=new i({zip64:this.zip64},this.loadOptions)).readCentralPart(this.reader),this.files.push(s);if(this.centralDirRecords!==this.files.length&&this.centralDirRecords!==0&&this.files.length===0)throw new Error("Corrupted zip or bug: expected "+this.centralDirRecords+" records in central dir, got "+this.files.length)},readEndOfCentral:function(){var s=this.reader.lastIndexOfSignature(Q.CENTRAL_DIRECTORY_END);if(s<0)throw this.isSignature(0,Q.LOCAL_FILE_HEADER)?new Error("Corrupted zip: can't find end of central directory"):new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html");this.reader.setIndex(s);var r=s;if(this.checkSignature(Q.CENTRAL_DIRECTORY_END),this.readBlockEndOfCentral(),this.diskNumber===C.MAX_VALUE_16BITS||this.diskWithCentralDirStart===C.MAX_VALUE_16BITS||this.centralDirRecordsOnThisDisk===C.MAX_VALUE_16BITS||this.centralDirRecords===C.MAX_VALUE_16BITS||this.centralDirSize===C.MAX_VALUE_32BITS||this.centralDirOffset===C.MAX_VALUE_32BITS){if(this.zip64=!0,(s=this.reader.lastIndexOfSignature(Q.ZIP64_CENTRAL_DIRECTORY_LOCATOR))<0)throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");if(this.reader.setIndex(s),this.checkSignature(Q.ZIP64_CENTRAL_DIRECTORY_LOCATOR),this.readBlockZip64EndOfCentralLocator(),!this.isSignature(this.relativeOffsetEndOfZip64CentralDir,Q.ZIP64_CENTRAL_DIRECTORY_END)&&(this.relativeOffsetEndOfZip64CentralDir=this.reader.lastIndexOfSignature(Q.ZIP64_CENTRAL_DIRECTORY_END),this.relativeOffsetEndOfZip64CentralDir<0))throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir),this.checkSignature(Q.ZIP64_CENTRAL_DIRECTORY_END),this.readBlockZip64EndOfCentral()}var a=this.centralDirOffset+this.centralDirSize;this.zip64&&(a+=20,a+=12+this.zip64EndOfCentralSize);var c=r-a;if(0<c)this.isSignature(r,Q.CENTRAL_FILE_HEADER)||(this.reader.zero=c);else if(c<0)throw new Error("Corrupted zip: missing "+Math.abs(c)+" bytes.")},prepareReader:function(s){this.reader=B(s)},load:function(s){this.prepareReader(s),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles()}},t.exports=n},{"./reader/readerFor":22,"./signature":23,"./support":30,"./utils":32,"./zipEntry":34}],34:[function(e,t,o){var B=e("./reader/readerFor"),C=e("./utils"),Q=e("./compressedObject"),i=e("./crc32"),E=e("./utf8"),n=e("./compressions"),s=e("./support");function r(a,c){this.options=a,this.loadOptions=c}r.prototype={isEncrypted:function(){return(1&this.bitFlag)==1},useUTF8:function(){return(2048&this.bitFlag)==2048},readLocalPart:function(a){var c,h;if(a.skip(22),this.fileNameLength=a.readInt(2),h=a.readInt(2),this.fileName=a.readData(this.fileNameLength),a.skip(h),this.compressedSize===-1||this.uncompressedSize===-1)throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)");if((c=(function(l){for(var D in n)if(Object.prototype.hasOwnProperty.call(n,D)&&n[D].magic===l)return n[D];return null})(this.compressionMethod))===null)throw new Error("Corrupted zip : compression "+C.pretty(this.compressionMethod)+" unknown (inner file : "+C.transformTo("string",this.fileName)+")");this.decompressed=new Q(this.compressedSize,this.uncompressedSize,this.crc32,c,a.readData(this.compressedSize))},readCentralPart:function(a){this.versionMadeBy=a.readInt(2),a.skip(2),this.bitFlag=a.readInt(2),this.compressionMethod=a.readString(2),this.date=a.readDate(),this.crc32=a.readInt(4),this.compressedSize=a.readInt(4),this.uncompressedSize=a.readInt(4);var c=a.readInt(2);if(this.extraFieldsLength=a.readInt(2),this.fileCommentLength=a.readInt(2),this.diskNumberStart=a.readInt(2),this.internalFileAttributes=a.readInt(2),this.externalFileAttributes=a.readInt(4),this.localHeaderOffset=a.readInt(4),this.isEncrypted())throw new Error("Encrypted zip are not supported");a.skip(c),this.readExtraFields(a),this.parseZIP64ExtraField(a),this.fileComment=a.readData(this.fileCommentLength)},processAttributes:function(){this.unixPermissions=null,this.dosPermissions=null;var a=this.versionMadeBy>>8;this.dir=!!(16&this.externalFileAttributes),a==0&&(this.dosPermissions=63&this.externalFileAttributes),a==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var a=B(this.extraFields[1].value);this.uncompressedSize===C.MAX_VALUE_32BITS&&(this.uncompressedSize=a.readInt(8)),this.compressedSize===C.MAX_VALUE_32BITS&&(this.compressedSize=a.readInt(8)),this.localHeaderOffset===C.MAX_VALUE_32BITS&&(this.localHeaderOffset=a.readInt(8)),this.diskNumberStart===C.MAX_VALUE_32BITS&&(this.diskNumberStart=a.readInt(4))}},readExtraFields:function(a){var c,h,l,D=a.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});a.index+4<D;)c=a.readInt(2),h=a.readInt(2),l=a.readData(h),this.extraFields[c]={id:c,length:h,value:l};a.setIndex(D)},handleUTF8:function(){var a=s.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=E.utf8decode(this.fileName),this.fileCommentStr=E.utf8decode(this.fileComment);else{var c=this.findExtraFieldUnicodePath();if(c!==null)this.fileNameStr=c;else{var h=C.transformTo(a,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(h)}var l=this.findExtraFieldUnicodeComment();if(l!==null)this.fileCommentStr=l;else{var D=C.transformTo(a,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(D)}}},findExtraFieldUnicodePath:function(){var a=this.extraFields[28789];if(a){var c=B(a.value);return c.readInt(1)!==1||i(this.fileName)!==c.readInt(4)?null:E.utf8decode(c.readData(a.length-5))}return null},findExtraFieldUnicodeComment:function(){var a=this.extraFields[25461];if(a){var c=B(a.value);return c.readInt(1)!==1||i(this.fileComment)!==c.readInt(4)?null:E.utf8decode(c.readData(a.length-5))}return null}},t.exports=r},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(e,t,o){function B(c,h,l){this.name=c,this.dir=l.dir,this.date=l.date,this.comment=l.comment,this.unixPermissions=l.unixPermissions,this.dosPermissions=l.dosPermissions,this._data=h,this._dataBinary=l.binary,this.options={compression:l.compression,compressionOptions:l.compressionOptions}}var C=e("./stream/StreamHelper"),Q=e("./stream/DataWorker"),i=e("./utf8"),E=e("./compressedObject"),n=e("./stream/GenericWorker");B.prototype={internalStream:function(c){var h=null,l="string";try{if(!c)throw new Error("No output type specified.");var D=(l=c.toLowerCase())==="string"||l==="text";l!=="binarystring"&&l!=="text"||(l="string"),h=this._decompressWorker();var d=!this._dataBinary;d&&!D&&(h=h.pipe(new i.Utf8EncodeWorker)),!d&&D&&(h=h.pipe(new i.Utf8DecodeWorker))}catch(y){(h=new n("error")).error(y)}return new C(h,l,"")},async:function(c,h){return this.internalStream(c).accumulate(h)},nodeStream:function(c,h){return this.internalStream(c||"nodebuffer").toNodejsStream(h)},_compressWorker:function(c,h){if(this._data instanceof E&&this._data.compression.magic===c.magic)return this._data.getCompressedWorker();var l=this._decompressWorker();return this._dataBinary||(l=l.pipe(new i.Utf8EncodeWorker)),E.createWorkerFrom(l,c,h)},_decompressWorker:function(){return this._data instanceof E?this._data.getContentWorker():this._data instanceof n?this._data:new Q(this._data)}};for(var s=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],r=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},a=0;a<s.length;a++)B.prototype[s[a]]=r;t.exports=B},{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(e,t,o){(function(B){var C,Q,i=B.MutationObserver||B.WebKitMutationObserver;if(i){var E=0,n=new i(c),s=B.document.createTextNode("");n.observe(s,{characterData:!0}),C=function(){s.data=E=++E%2}}else if(B.setImmediate||B.MessageChannel===void 0)C="document"in B&&"onreadystatechange"in B.document.createElement("script")?function(){var h=B.document.createElement("script");h.onreadystatechange=function(){c(),h.onreadystatechange=null,h.parentNode.removeChild(h),h=null},B.document.documentElement.appendChild(h)}:function(){setTimeout(c,0)};else{var r=new B.MessageChannel;r.port1.onmessage=c,C=function(){r.port2.postMessage(0)}}var a=[];function c(){var h,l;Q=!0;for(var D=a.length;D;){for(l=a,a=[],h=-1;++h<D;)l[h]();D=a.length}Q=!1}t.exports=function(h){a.push(h)!==1||Q||C()}}).call(this,typeof zL<"u"?zL:typeof self<"u"?self:typeof window<"u"?window:{})},{}],37:[function(e,t,o){var B=e("immediate");function C(){}var Q={},i=["REJECTED"],E=["FULFILLED"],n=["PENDING"];function s(D){if(typeof D!="function")throw new TypeError("resolver must be a function");this.state=n,this.queue=[],this.outcome=void 0,D!==C&&h(this,D)}function r(D,d,y){this.promise=D,typeof d=="function"&&(this.onFulfilled=d,this.callFulfilled=this.otherCallFulfilled),typeof y=="function"&&(this.onRejected=y,this.callRejected=this.otherCallRejected)}function a(D,d,y){B(function(){var w;try{w=d(y)}catch(u){return Q.reject(D,u)}w===D?Q.reject(D,new TypeError("Cannot resolve promise with itself")):Q.resolve(D,w)})}function c(D){var d=D&&D.then;if(D&&(typeof D=="object"||typeof D=="function")&&typeof d=="function")return function(){d.apply(D,arguments)}}function h(D,d){var y=!1;function w(m){y||(y=!0,Q.reject(D,m))}function u(m){y||(y=!0,Q.resolve(D,m))}var G=l(function(){d(u,w)});G.status==="error"&&w(G.value)}function l(D,d){var y={};try{y.value=D(d),y.status="success"}catch(w){y.status="error",y.value=w}return y}(t.exports=s).prototype.finally=function(D){if(typeof D!="function")return this;var d=this.constructor;return this.then(function(y){return d.resolve(D()).then(function(){return y})},function(y){return d.resolve(D()).then(function(){throw y})})},s.prototype.catch=function(D){return this.then(null,D)},s.prototype.then=function(D,d){if(typeof D!="function"&&this.state===E||typeof d!="function"&&this.state===i)return this;var y=new this.constructor(C);return this.state!==n?a(y,this.state===E?D:d,this.outcome):this.queue.push(new r(y,D,d)),y},r.prototype.callFulfilled=function(D){Q.resolve(this.promise,D)},r.prototype.otherCallFulfilled=function(D){a(this.promise,this.onFulfilled,D)},r.prototype.callRejected=function(D){Q.reject(this.promise,D)},r.prototype.otherCallRejected=function(D){a(this.promise,this.onRejected,D)},Q.resolve=function(D,d){var y=l(c,d);if(y.status==="error")return Q.reject(D,y.value);var w=y.value;if(w)h(D,w);else{D.state=E,D.outcome=d;for(var u=-1,G=D.queue.length;++u<G;)D.queue[u].callFulfilled(d)}return D},Q.reject=function(D,d){D.state=i,D.outcome=d;for(var y=-1,w=D.queue.length;++y<w;)D.queue[y].callRejected(d);return D},s.resolve=function(D){return D instanceof this?D:Q.resolve(new this(C),D)},s.reject=function(D){var d=new this(C);return Q.reject(d,D)},s.all=function(D){var d=this;if(Object.prototype.toString.call(D)!=="[object Array]")return this.reject(new TypeError("must be an array"));var y=D.length,w=!1;if(!y)return this.resolve([]);for(var u=new Array(y),G=0,m=-1,p=new this(C);++m<y;)k(D[m],m);return p;function k(S,R){d.resolve(S).then(function(x){u[R]=x,++G!==y||w||(w=!0,Q.resolve(p,u))},function(x){w||(w=!0,Q.reject(p,x))})}},s.race=function(D){var d=this;if(Object.prototype.toString.call(D)!=="[object Array]")return this.reject(new TypeError("must be an array"));var y=D.length,w=!1;if(!y)return this.resolve([]);for(var u=-1,G=new this(C);++u<y;)m=D[u],d.resolve(m).then(function(p){w||(w=!0,Q.resolve(G,p))},function(p){w||(w=!0,Q.reject(G,p))});var m;return G}},{immediate:36}],38:[function(e,t,o){var B={};(0,e("./lib/utils/common").assign)(B,e("./lib/deflate"),e("./lib/inflate"),e("./lib/zlib/constants")),t.exports=B},{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(e,t,o){var B=e("./zlib/deflate"),C=e("./utils/common"),Q=e("./utils/strings"),i=e("./zlib/messages"),E=e("./zlib/zstream"),n=Object.prototype.toString,s=0,r=-1,a=0,c=8;function h(D){if(!(this instanceof h))return new h(D);this.options=C.assign({level:r,method:c,chunkSize:16384,windowBits:15,memLevel:8,strategy:a,to:""},D||{});var d=this.options;d.raw&&0<d.windowBits?d.windowBits=-d.windowBits:d.gzip&&0<d.windowBits&&d.windowBits<16&&(d.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new E,this.strm.avail_out=0;var y=B.deflateInit2(this.strm,d.level,d.method,d.windowBits,d.memLevel,d.strategy);if(y!==s)throw new Error(i[y]);if(d.header&&B.deflateSetHeader(this.strm,d.header),d.dictionary){var w;if(w=typeof d.dictionary=="string"?Q.string2buf(d.dictionary):n.call(d.dictionary)==="[object ArrayBuffer]"?new Uint8Array(d.dictionary):d.dictionary,(y=B.deflateSetDictionary(this.strm,w))!==s)throw new Error(i[y]);this._dict_set=!0}}function l(D,d){var y=new h(d);if(y.push(D,!0),y.err)throw y.msg||i[y.err];return y.result}h.prototype.push=function(D,d){var y,w,u=this.strm,G=this.options.chunkSize;if(this.ended)return!1;w=d===~~d?d:d===!0?4:0,typeof D=="string"?u.input=Q.string2buf(D):n.call(D)==="[object ArrayBuffer]"?u.input=new Uint8Array(D):u.input=D,u.next_in=0,u.avail_in=u.input.length;do{if(u.avail_out===0&&(u.output=new C.Buf8(G),u.next_out=0,u.avail_out=G),(y=B.deflate(u,w))!==1&&y!==s)return this.onEnd(y),!(this.ended=!0);u.avail_out!==0&&(u.avail_in!==0||w!==4&&w!==2)||(this.options.to==="string"?this.onData(Q.buf2binstring(C.shrinkBuf(u.output,u.next_out))):this.onData(C.shrinkBuf(u.output,u.next_out)))}while((0<u.avail_in||u.avail_out===0)&&y!==1);return w===4?(y=B.deflateEnd(this.strm),this.onEnd(y),this.ended=!0,y===s):w!==2||(this.onEnd(s),!(u.avail_out=0))},h.prototype.onData=function(D){this.chunks.push(D)},h.prototype.onEnd=function(D){D===s&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=C.flattenChunks(this.chunks)),this.chunks=[],this.err=D,this.msg=this.strm.msg},o.Deflate=h,o.deflate=l,o.deflateRaw=function(D,d){return(d=d||{}).raw=!0,l(D,d)},o.gzip=function(D,d){return(d=d||{}).gzip=!0,l(D,d)}},{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(e,t,o){var B=e("./zlib/inflate"),C=e("./utils/common"),Q=e("./utils/strings"),i=e("./zlib/constants"),E=e("./zlib/messages"),n=e("./zlib/zstream"),s=e("./zlib/gzheader"),r=Object.prototype.toString;function a(h){if(!(this instanceof a))return new a(h);this.options=C.assign({chunkSize:16384,windowBits:0,to:""},h||{});var l=this.options;l.raw&&0<=l.windowBits&&l.windowBits<16&&(l.windowBits=-l.windowBits,l.windowBits===0&&(l.windowBits=-15)),!(0<=l.windowBits&&l.windowBits<16)||h&&h.windowBits||(l.windowBits+=32),15<l.windowBits&&l.windowBits<48&&(15&l.windowBits)==0&&(l.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new n,this.strm.avail_out=0;var D=B.inflateInit2(this.strm,l.windowBits);if(D!==i.Z_OK)throw new Error(E[D]);this.header=new s,B.inflateGetHeader(this.strm,this.header)}function c(h,l){var D=new a(l);if(D.push(h,!0),D.err)throw D.msg||E[D.err];return D.result}a.prototype.push=function(h,l){var D,d,y,w,u,G,m=this.strm,p=this.options.chunkSize,k=this.options.dictionary,S=!1;if(this.ended)return!1;d=l===~~l?l:l===!0?i.Z_FINISH:i.Z_NO_FLUSH,typeof h=="string"?m.input=Q.binstring2buf(h):r.call(h)==="[object ArrayBuffer]"?m.input=new Uint8Array(h):m.input=h,m.next_in=0,m.avail_in=m.input.length;do{if(m.avail_out===0&&(m.output=new C.Buf8(p),m.next_out=0,m.avail_out=p),(D=B.inflate(m,i.Z_NO_FLUSH))===i.Z_NEED_DICT&&k&&(G=typeof k=="string"?Q.string2buf(k):r.call(k)==="[object ArrayBuffer]"?new Uint8Array(k):k,D=B.inflateSetDictionary(this.strm,G)),D===i.Z_BUF_ERROR&&S===!0&&(D=i.Z_OK,S=!1),D!==i.Z_STREAM_END&&D!==i.Z_OK)return this.onEnd(D),!(this.ended=!0);m.next_out&&(m.avail_out!==0&&D!==i.Z_STREAM_END&&(m.avail_in!==0||d!==i.Z_FINISH&&d!==i.Z_SYNC_FLUSH)||(this.options.to==="string"?(y=Q.utf8border(m.output,m.next_out),w=m.next_out-y,u=Q.buf2string(m.output,y),m.next_out=w,m.avail_out=p-w,w&&C.arraySet(m.output,m.output,y,w,0),this.onData(u)):this.onData(C.shrinkBuf(m.output,m.next_out)))),m.avail_in===0&&m.avail_out===0&&(S=!0)}while((0<m.avail_in||m.avail_out===0)&&D!==i.Z_STREAM_END);return D===i.Z_STREAM_END&&(d=i.Z_FINISH),d===i.Z_FINISH?(D=B.inflateEnd(this.strm),this.onEnd(D),this.ended=!0,D===i.Z_OK):d!==i.Z_SYNC_FLUSH||(this.onEnd(i.Z_OK),!(m.avail_out=0))},a.prototype.onData=function(h){this.chunks.push(h)},a.prototype.onEnd=function(h){h===i.Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=C.flattenChunks(this.chunks)),this.chunks=[],this.err=h,this.msg=this.strm.msg},o.Inflate=a,o.inflate=c,o.inflateRaw=function(h,l){return(l=l||{}).raw=!0,c(h,l)},o.ungzip=c},{"./utils/common":41,"./utils/strings":42,"./zlib/constants":44,"./zlib/gzheader":47,"./zlib/inflate":49,"./zlib/messages":51,"./zlib/zstream":53}],41:[function(e,t,o){var B=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Int32Array<"u";o.assign=function(i){for(var E=Array.prototype.slice.call(arguments,1);E.length;){var n=E.shift();if(n){if(typeof n!="object")throw new TypeError(n+"must be non-object");for(var s in n)n.hasOwnProperty(s)&&(i[s]=n[s])}}return i},o.shrinkBuf=function(i,E){return i.length===E?i:i.subarray?i.subarray(0,E):(i.length=E,i)};var C={arraySet:function(i,E,n,s,r){if(E.subarray&&i.subarray)i.set(E.subarray(n,n+s),r);else for(var a=0;a<s;a++)i[r+a]=E[n+a]},flattenChunks:function(i){var E,n,s,r,a,c;for(E=s=0,n=i.length;E<n;E++)s+=i[E].length;for(c=new Uint8Array(s),E=r=0,n=i.length;E<n;E++)a=i[E],c.set(a,r),r+=a.length;return c}},Q={arraySet:function(i,E,n,s,r){for(var a=0;a<s;a++)i[r+a]=E[n+a]},flattenChunks:function(i){return[].concat.apply([],i)}};o.setTyped=function(i){i?(o.Buf8=Uint8Array,o.Buf16=Uint16Array,o.Buf32=Int32Array,o.assign(o,C)):(o.Buf8=Array,o.Buf16=Array,o.Buf32=Array,o.assign(o,Q))},o.setTyped(B)},{}],42:[function(e,t,o){var B=e("./common"),C=!0,Q=!0;try{String.fromCharCode.apply(null,[0])}catch{C=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{Q=!1}for(var i=new B.Buf8(256),E=0;E<256;E++)i[E]=252<=E?6:248<=E?5:240<=E?4:224<=E?3:192<=E?2:1;function n(s,r){if(r<65537&&(s.subarray&&Q||!s.subarray&&C))return String.fromCharCode.apply(null,B.shrinkBuf(s,r));for(var a="",c=0;c<r;c++)a+=String.fromCharCode(s[c]);return a}i[254]=i[254]=1,o.string2buf=function(s){var r,a,c,h,l,D=s.length,d=0;for(h=0;h<D;h++)(64512&(a=s.charCodeAt(h)))==55296&&h+1<D&&(64512&(c=s.charCodeAt(h+1)))==56320&&(a=65536+(a-55296<<10)+(c-56320),h++),d+=a<128?1:a<2048?2:a<65536?3:4;for(r=new B.Buf8(d),h=l=0;l<d;h++)(64512&(a=s.charCodeAt(h)))==55296&&h+1<D&&(64512&(c=s.charCodeAt(h+1)))==56320&&(a=65536+(a-55296<<10)+(c-56320),h++),a<128?r[l++]=a:(a<2048?r[l++]=192|a>>>6:(a<65536?r[l++]=224|a>>>12:(r[l++]=240|a>>>18,r[l++]=128|a>>>12&63),r[l++]=128|a>>>6&63),r[l++]=128|63&a);return r},o.buf2binstring=function(s){return n(s,s.length)},o.binstring2buf=function(s){for(var r=new B.Buf8(s.length),a=0,c=r.length;a<c;a++)r[a]=s.charCodeAt(a);return r},o.buf2string=function(s,r){var a,c,h,l,D=r||s.length,d=new Array(2*D);for(a=c=0;a<D;)if((h=s[a++])<128)d[c++]=h;else if(4<(l=i[h]))d[c++]=65533,a+=l-1;else{for(h&=l===2?31:l===3?15:7;1<l&&a<D;)h=h<<6|63&s[a++],l--;1<l?d[c++]=65533:h<65536?d[c++]=h:(h-=65536,d[c++]=55296|h>>10&1023,d[c++]=56320|1023&h)}return n(d,c)},o.utf8border=function(s,r){var a;for((r=r||s.length)>s.length&&(r=s.length),a=r-1;0<=a&&(192&s[a])==128;)a--;return a<0||a===0?r:a+i[s[a]]>r?a:r}},{"./common":41}],43:[function(e,t,o){t.exports=function(B,C,Q,i){for(var E=65535&B|0,n=B>>>16&65535|0,s=0;Q!==0;){for(Q-=s=2e3<Q?2e3:Q;n=n+(E=E+C[i++]|0)|0,--s;);E%=65521,n%=65521}return E|n<<16|0}},{}],44:[function(e,t,o){t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],45:[function(e,t,o){var B=(function(){for(var C,Q=[],i=0;i<256;i++){C=i;for(var E=0;E<8;E++)C=1&C?3988292384^C>>>1:C>>>1;Q[i]=C}return Q})();t.exports=function(C,Q,i,E){var n=B,s=E+i;C^=-1;for(var r=E;r<s;r++)C=C>>>8^n[255&(C^Q[r])];return-1^C}},{}],46:[function(e,t,o){var B,C=e("../utils/common"),Q=e("./trees"),i=e("./adler32"),E=e("./crc32"),n=e("./messages"),s=0,r=4,a=0,c=-2,h=-1,l=4,D=2,d=8,y=9,w=286,u=30,G=19,m=2*w+1,p=15,k=3,S=258,R=S+k+1,x=42,N=113,U=1,K=2,_=3,b=4;function T(aA,xA){return aA.msg=n[xA],xA}function j(aA){return(aA<<1)-(4<aA?9:0)}function W(aA){for(var xA=aA.length;0<=--xA;)aA[xA]=0}function O(aA){var xA=aA.state,RA=xA.pending;RA>aA.avail_out&&(RA=aA.avail_out),RA!==0&&(C.arraySet(aA.output,xA.pending_buf,xA.pending_out,RA,aA.next_out),aA.next_out+=RA,xA.pending_out+=RA,aA.total_out+=RA,aA.avail_out-=RA,xA.pending-=RA,xA.pending===0&&(xA.pending_out=0))}function gA(aA,xA){Q._tr_flush_block(aA,0<=aA.block_start?aA.block_start:-1,aA.strstart-aA.block_start,xA),aA.block_start=aA.strstart,O(aA.strm)}function tA(aA,xA){aA.pending_buf[aA.pending++]=xA}function IA(aA,xA){aA.pending_buf[aA.pending++]=xA>>>8&255,aA.pending_buf[aA.pending++]=255&xA}function QA(aA,xA){var RA,NA,YA=aA.max_chain_length,PA=aA.strstart,mA=aA.prev_length,LA=aA.nice_match,dA=aA.strstart>aA.w_size-R?aA.strstart-(aA.w_size-R):0,HA=aA.window,WA=aA.w_mask,Qg=aA.prev,_A=aA.strstart+S,uA=HA[PA+mA-1],kA=HA[PA+mA];aA.prev_length>=aA.good_match&&(YA>>=2),LA>aA.lookahead&&(LA=aA.lookahead);do if(HA[(RA=xA)+mA]===kA&&HA[RA+mA-1]===uA&&HA[RA]===HA[PA]&&HA[++RA]===HA[PA+1]){PA+=2,RA++;do;while(HA[++PA]===HA[++RA]&&HA[++PA]===HA[++RA]&&HA[++PA]===HA[++RA]&&HA[++PA]===HA[++RA]&&HA[++PA]===HA[++RA]&&HA[++PA]===HA[++RA]&&HA[++PA]===HA[++RA]&&HA[++PA]===HA[++RA]&&PA<_A);if(NA=S-(_A-PA),PA=_A-S,mA<NA){if(aA.match_start=xA,LA<=(mA=NA))break;uA=HA[PA+mA-1],kA=HA[PA+mA]}}while((xA=Qg[xA&WA])>dA&&--YA!=0);return mA<=aA.lookahead?mA:aA.lookahead}function nA(aA){var xA,RA,NA,YA,PA,mA,LA,dA,HA,WA,Qg=aA.w_size;do{if(YA=aA.window_size-aA.lookahead-aA.strstart,aA.strstart>=Qg+(Qg-R)){for(C.arraySet(aA.window,aA.window,Qg,Qg,0),aA.match_start-=Qg,aA.strstart-=Qg,aA.block_start-=Qg,xA=RA=aA.hash_size;NA=aA.head[--xA],aA.head[xA]=Qg<=NA?NA-Qg:0,--RA;);for(xA=RA=Qg;NA=aA.prev[--xA],aA.prev[xA]=Qg<=NA?NA-Qg:0,--RA;);YA+=Qg}if(aA.strm.avail_in===0)break;if(mA=aA.strm,LA=aA.window,dA=aA.strstart+aA.lookahead,HA=YA,WA=void 0,WA=mA.avail_in,HA<WA&&(WA=HA),RA=WA===0?0:(mA.avail_in-=WA,C.arraySet(LA,mA.input,mA.next_in,WA,dA),mA.state.wrap===1?mA.adler=i(mA.adler,LA,WA,dA):mA.state.wrap===2&&(mA.adler=E(mA.adler,LA,WA,dA)),mA.next_in+=WA,mA.total_in+=WA,WA),aA.lookahead+=RA,aA.lookahead+aA.insert>=k)for(PA=aA.strstart-aA.insert,aA.ins_h=aA.window[PA],aA.ins_h=(aA.ins_h<<aA.hash_shift^aA.window[PA+1])&aA.hash_mask;aA.insert&&(aA.ins_h=(aA.ins_h<<aA.hash_shift^aA.window[PA+k-1])&aA.hash_mask,aA.prev[PA&aA.w_mask]=aA.head[aA.ins_h],aA.head[aA.ins_h]=PA,PA++,aA.insert--,!(aA.lookahead+aA.insert<k)););}while(aA.lookahead<R&&aA.strm.avail_in!==0)}function DA(aA,xA){for(var RA,NA;;){if(aA.lookahead<R){if(nA(aA),aA.lookahead<R&&xA===s)return U;if(aA.lookahead===0)break}if(RA=0,aA.lookahead>=k&&(aA.ins_h=(aA.ins_h<<aA.hash_shift^aA.window[aA.strstart+k-1])&aA.hash_mask,RA=aA.prev[aA.strstart&aA.w_mask]=aA.head[aA.ins_h],aA.head[aA.ins_h]=aA.strstart),RA!==0&&aA.strstart-RA<=aA.w_size-R&&(aA.match_length=QA(aA,RA)),aA.match_length>=k)if(NA=Q._tr_tally(aA,aA.strstart-aA.match_start,aA.match_length-k),aA.lookahead-=aA.match_length,aA.match_length<=aA.max_lazy_match&&aA.lookahead>=k){for(aA.match_length--;aA.strstart++,aA.ins_h=(aA.ins_h<<aA.hash_shift^aA.window[aA.strstart+k-1])&aA.hash_mask,RA=aA.prev[aA.strstart&aA.w_mask]=aA.head[aA.ins_h],aA.head[aA.ins_h]=aA.strstart,--aA.match_length!=0;);aA.strstart++}else aA.strstart+=aA.match_length,aA.match_length=0,aA.ins_h=aA.window[aA.strstart],aA.ins_h=(aA.ins_h<<aA.hash_shift^aA.window[aA.strstart+1])&aA.hash_mask;else NA=Q._tr_tally(aA,0,aA.window[aA.strstart]),aA.lookahead--,aA.strstart++;if(NA&&(gA(aA,!1),aA.strm.avail_out===0))return U}return aA.insert=aA.strstart<k-1?aA.strstart:k-1,xA===r?(gA(aA,!0),aA.strm.avail_out===0?_:b):aA.last_lit&&(gA(aA,!1),aA.strm.avail_out===0)?U:K}function CA(aA,xA){for(var RA,NA,YA;;){if(aA.lookahead<R){if(nA(aA),aA.lookahead<R&&xA===s)return U;if(aA.lookahead===0)break}if(RA=0,aA.lookahead>=k&&(aA.ins_h=(aA.ins_h<<aA.hash_shift^aA.window[aA.strstart+k-1])&aA.hash_mask,RA=aA.prev[aA.strstart&aA.w_mask]=aA.head[aA.ins_h],aA.head[aA.ins_h]=aA.strstart),aA.prev_length=aA.match_length,aA.prev_match=aA.match_start,aA.match_length=k-1,RA!==0&&aA.prev_length<aA.max_lazy_match&&aA.strstart-RA<=aA.w_size-R&&(aA.match_length=QA(aA,RA),aA.match_length<=5&&(aA.strategy===1||aA.match_length===k&&4096<aA.strstart-aA.match_start)&&(aA.match_length=k-1)),aA.prev_length>=k&&aA.match_length<=aA.prev_length){for(YA=aA.strstart+aA.lookahead-k,NA=Q._tr_tally(aA,aA.strstart-1-aA.prev_match,aA.prev_length-k),aA.lookahead-=aA.prev_length-1,aA.prev_length-=2;++aA.strstart<=YA&&(aA.ins_h=(aA.ins_h<<aA.hash_shift^aA.window[aA.strstart+k-1])&aA.hash_mask,RA=aA.prev[aA.strstart&aA.w_mask]=aA.head[aA.ins_h],aA.head[aA.ins_h]=aA.strstart),--aA.prev_length!=0;);if(aA.match_available=0,aA.match_length=k-1,aA.strstart++,NA&&(gA(aA,!1),aA.strm.avail_out===0))return U}else if(aA.match_available){if((NA=Q._tr_tally(aA,0,aA.window[aA.strstart-1]))&&gA(aA,!1),aA.strstart++,aA.lookahead--,aA.strm.avail_out===0)return U}else aA.match_available=1,aA.strstart++,aA.lookahead--}return aA.match_available&&(NA=Q._tr_tally(aA,0,aA.window[aA.strstart-1]),aA.match_available=0),aA.insert=aA.strstart<k-1?aA.strstart:k-1,xA===r?(gA(aA,!0),aA.strm.avail_out===0?_:b):aA.last_lit&&(gA(aA,!1),aA.strm.avail_out===0)?U:K}function hA(aA,xA,RA,NA,YA){this.good_length=aA,this.max_lazy=xA,this.nice_length=RA,this.max_chain=NA,this.func=YA}function sA(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=d,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new C.Buf16(2*m),this.dyn_dtree=new C.Buf16(2*(2*u+1)),this.bl_tree=new C.Buf16(2*(2*G+1)),W(this.dyn_ltree),W(this.dyn_dtree),W(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new C.Buf16(p+1),this.heap=new C.Buf16(2*w+1),W(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new C.Buf16(2*w+1),W(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function cA(aA){var xA;return aA&&aA.state?(aA.total_in=aA.total_out=0,aA.data_type=D,(xA=aA.state).pending=0,xA.pending_out=0,xA.wrap<0&&(xA.wrap=-xA.wrap),xA.status=xA.wrap?x:N,aA.adler=xA.wrap===2?0:1,xA.last_flush=s,Q._tr_init(xA),a):T(aA,c)}function SA(aA){var xA=cA(aA);return xA===a&&(function(RA){RA.window_size=2*RA.w_size,W(RA.head),RA.max_lazy_match=B[RA.level].max_lazy,RA.good_match=B[RA.level].good_length,RA.nice_match=B[RA.level].nice_length,RA.max_chain_length=B[RA.level].max_chain,RA.strstart=0,RA.block_start=0,RA.lookahead=0,RA.insert=0,RA.match_length=RA.prev_length=k-1,RA.match_available=0,RA.ins_h=0})(aA.state),xA}function FA(aA,xA,RA,NA,YA,PA){if(!aA)return c;var mA=1;if(xA===h&&(xA=6),NA<0?(mA=0,NA=-NA):15<NA&&(mA=2,NA-=16),YA<1||y<YA||RA!==d||NA<8||15<NA||xA<0||9<xA||PA<0||l<PA)return T(aA,c);NA===8&&(NA=9);var LA=new sA;return(aA.state=LA).strm=aA,LA.wrap=mA,LA.gzhead=null,LA.w_bits=NA,LA.w_size=1<<LA.w_bits,LA.w_mask=LA.w_size-1,LA.hash_bits=YA+7,LA.hash_size=1<<LA.hash_bits,LA.hash_mask=LA.hash_size-1,LA.hash_shift=~~((LA.hash_bits+k-1)/k),LA.window=new C.Buf8(2*LA.w_size),LA.head=new C.Buf16(LA.hash_size),LA.prev=new C.Buf16(LA.w_size),LA.lit_bufsize=1<<YA+6,LA.pending_buf_size=4*LA.lit_bufsize,LA.pending_buf=new C.Buf8(LA.pending_buf_size),LA.d_buf=1*LA.lit_bufsize,LA.l_buf=3*LA.lit_bufsize,LA.level=xA,LA.strategy=PA,LA.method=RA,SA(aA)}B=[new hA(0,0,0,0,function(aA,xA){var RA=65535;for(RA>aA.pending_buf_size-5&&(RA=aA.pending_buf_size-5);;){if(aA.lookahead<=1){if(nA(aA),aA.lookahead===0&&xA===s)return U;if(aA.lookahead===0)break}aA.strstart+=aA.lookahead,aA.lookahead=0;var NA=aA.block_start+RA;if((aA.strstart===0||aA.strstart>=NA)&&(aA.lookahead=aA.strstart-NA,aA.strstart=NA,gA(aA,!1),aA.strm.avail_out===0)||aA.strstart-aA.block_start>=aA.w_size-R&&(gA(aA,!1),aA.strm.avail_out===0))return U}return aA.insert=0,xA===r?(gA(aA,!0),aA.strm.avail_out===0?_:b):(aA.strstart>aA.block_start&&(gA(aA,!1),aA.strm.avail_out),U)}),new hA(4,4,8,4,DA),new hA(4,5,16,8,DA),new hA(4,6,32,32,DA),new hA(4,4,16,16,CA),new hA(8,16,32,32,CA),new hA(8,16,128,128,CA),new hA(8,32,128,256,CA),new hA(32,128,258,1024,CA),new hA(32,258,258,4096,CA)],o.deflateInit=function(aA,xA){return FA(aA,xA,d,15,8,0)},o.deflateInit2=FA,o.deflateReset=SA,o.deflateResetKeep=cA,o.deflateSetHeader=function(aA,xA){return aA&&aA.state?aA.state.wrap!==2?c:(aA.state.gzhead=xA,a):c},o.deflate=function(aA,xA){var RA,NA,YA,PA;if(!aA||!aA.state||5<xA||xA<0)return aA?T(aA,c):c;if(NA=aA.state,!aA.output||!aA.input&&aA.avail_in!==0||NA.status===666&&xA!==r)return T(aA,aA.avail_out===0?-5:c);if(NA.strm=aA,RA=NA.last_flush,NA.last_flush=xA,NA.status===x)if(NA.wrap===2)aA.adler=0,tA(NA,31),tA(NA,139),tA(NA,8),NA.gzhead?(tA(NA,(NA.gzhead.text?1:0)+(NA.gzhead.hcrc?2:0)+(NA.gzhead.extra?4:0)+(NA.gzhead.name?8:0)+(NA.gzhead.comment?16:0)),tA(NA,255&NA.gzhead.time),tA(NA,NA.gzhead.time>>8&255),tA(NA,NA.gzhead.time>>16&255),tA(NA,NA.gzhead.time>>24&255),tA(NA,NA.level===9?2:2<=NA.strategy||NA.level<2?4:0),tA(NA,255&NA.gzhead.os),NA.gzhead.extra&&NA.gzhead.extra.length&&(tA(NA,255&NA.gzhead.extra.length),tA(NA,NA.gzhead.extra.length>>8&255)),NA.gzhead.hcrc&&(aA.adler=E(aA.adler,NA.pending_buf,NA.pending,0)),NA.gzindex=0,NA.status=69):(tA(NA,0),tA(NA,0),tA(NA,0),tA(NA,0),tA(NA,0),tA(NA,NA.level===9?2:2<=NA.strategy||NA.level<2?4:0),tA(NA,3),NA.status=N);else{var mA=d+(NA.w_bits-8<<4)<<8;mA|=(2<=NA.strategy||NA.level<2?0:NA.level<6?1:NA.level===6?2:3)<<6,NA.strstart!==0&&(mA|=32),mA+=31-mA%31,NA.status=N,IA(NA,mA),NA.strstart!==0&&(IA(NA,aA.adler>>>16),IA(NA,65535&aA.adler)),aA.adler=1}if(NA.status===69)if(NA.gzhead.extra){for(YA=NA.pending;NA.gzindex<(65535&NA.gzhead.extra.length)&&(NA.pending!==NA.pending_buf_size||(NA.gzhead.hcrc&&NA.pending>YA&&(aA.adler=E(aA.adler,NA.pending_buf,NA.pending-YA,YA)),O(aA),YA=NA.pending,NA.pending!==NA.pending_buf_size));)tA(NA,255&NA.gzhead.extra[NA.gzindex]),NA.gzindex++;NA.gzhead.hcrc&&NA.pending>YA&&(aA.adler=E(aA.adler,NA.pending_buf,NA.pending-YA,YA)),NA.gzindex===NA.gzhead.extra.length&&(NA.gzindex=0,NA.status=73)}else NA.status=73;if(NA.status===73)if(NA.gzhead.name){YA=NA.pending;do{if(NA.pending===NA.pending_buf_size&&(NA.gzhead.hcrc&&NA.pending>YA&&(aA.adler=E(aA.adler,NA.pending_buf,NA.pending-YA,YA)),O(aA),YA=NA.pending,NA.pending===NA.pending_buf_size)){PA=1;break}PA=NA.gzindex<NA.gzhead.name.length?255&NA.gzhead.name.charCodeAt(NA.gzindex++):0,tA(NA,PA)}while(PA!==0);NA.gzhead.hcrc&&NA.pending>YA&&(aA.adler=E(aA.adler,NA.pending_buf,NA.pending-YA,YA)),PA===0&&(NA.gzindex=0,NA.status=91)}else NA.status=91;if(NA.status===91)if(NA.gzhead.comment){YA=NA.pending;do{if(NA.pending===NA.pending_buf_size&&(NA.gzhead.hcrc&&NA.pending>YA&&(aA.adler=E(aA.adler,NA.pending_buf,NA.pending-YA,YA)),O(aA),YA=NA.pending,NA.pending===NA.pending_buf_size)){PA=1;break}PA=NA.gzindex<NA.gzhead.comment.length?255&NA.gzhead.comment.charCodeAt(NA.gzindex++):0,tA(NA,PA)}while(PA!==0);NA.gzhead.hcrc&&NA.pending>YA&&(aA.adler=E(aA.adler,NA.pending_buf,NA.pending-YA,YA)),PA===0&&(NA.status=103)}else NA.status=103;if(NA.status===103&&(NA.gzhead.hcrc?(NA.pending+2>NA.pending_buf_size&&O(aA),NA.pending+2<=NA.pending_buf_size&&(tA(NA,255&aA.adler),tA(NA,aA.adler>>8&255),aA.adler=0,NA.status=N)):NA.status=N),NA.pending!==0){if(O(aA),aA.avail_out===0)return NA.last_flush=-1,a}else if(aA.avail_in===0&&j(xA)<=j(RA)&&xA!==r)return T(aA,-5);if(NA.status===666&&aA.avail_in!==0)return T(aA,-5);if(aA.avail_in!==0||NA.lookahead!==0||xA!==s&&NA.status!==666){var LA=NA.strategy===2?(function(dA,HA){for(var WA;;){if(dA.lookahead===0&&(nA(dA),dA.lookahead===0)){if(HA===s)return U;break}if(dA.match_length=0,WA=Q._tr_tally(dA,0,dA.window[dA.strstart]),dA.lookahead--,dA.strstart++,WA&&(gA(dA,!1),dA.strm.avail_out===0))return U}return dA.insert=0,HA===r?(gA(dA,!0),dA.strm.avail_out===0?_:b):dA.last_lit&&(gA(dA,!1),dA.strm.avail_out===0)?U:K})(NA,xA):NA.strategy===3?(function(dA,HA){for(var WA,Qg,_A,uA,kA=dA.window;;){if(dA.lookahead<=S){if(nA(dA),dA.lookahead<=S&&HA===s)return U;if(dA.lookahead===0)break}if(dA.match_length=0,dA.lookahead>=k&&0<dA.strstart&&(Qg=kA[_A=dA.strstart-1])===kA[++_A]&&Qg===kA[++_A]&&Qg===kA[++_A]){uA=dA.strstart+S;do;while(Qg===kA[++_A]&&Qg===kA[++_A]&&Qg===kA[++_A]&&Qg===kA[++_A]&&Qg===kA[++_A]&&Qg===kA[++_A]&&Qg===kA[++_A]&&Qg===kA[++_A]&&_A<uA);dA.match_length=S-(uA-_A),dA.match_length>dA.lookahead&&(dA.match_length=dA.lookahead)}if(dA.match_length>=k?(WA=Q._tr_tally(dA,1,dA.match_length-k),dA.lookahead-=dA.match_length,dA.strstart+=dA.match_length,dA.match_length=0):(WA=Q._tr_tally(dA,0,dA.window[dA.strstart]),dA.lookahead--,dA.strstart++),WA&&(gA(dA,!1),dA.strm.avail_out===0))return U}return dA.insert=0,HA===r?(gA(dA,!0),dA.strm.avail_out===0?_:b):dA.last_lit&&(gA(dA,!1),dA.strm.avail_out===0)?U:K})(NA,xA):B[NA.level].func(NA,xA);if(LA!==_&&LA!==b||(NA.status=666),LA===U||LA===_)return aA.avail_out===0&&(NA.last_flush=-1),a;if(LA===K&&(xA===1?Q._tr_align(NA):xA!==5&&(Q._tr_stored_block(NA,0,0,!1),xA===3&&(W(NA.head),NA.lookahead===0&&(NA.strstart=0,NA.block_start=0,NA.insert=0))),O(aA),aA.avail_out===0))return NA.last_flush=-1,a}return xA!==r?a:NA.wrap<=0?1:(NA.wrap===2?(tA(NA,255&aA.adler),tA(NA,aA.adler>>8&255),tA(NA,aA.adler>>16&255),tA(NA,aA.adler>>24&255),tA(NA,255&aA.total_in),tA(NA,aA.total_in>>8&255),tA(NA,aA.total_in>>16&255),tA(NA,aA.total_in>>24&255)):(IA(NA,aA.adler>>>16),IA(NA,65535&aA.adler)),O(aA),0<NA.wrap&&(NA.wrap=-NA.wrap),NA.pending!==0?a:1)},o.deflateEnd=function(aA){var xA;return aA&&aA.state?(xA=aA.state.status)!==x&&xA!==69&&xA!==73&&xA!==91&&xA!==103&&xA!==N&&xA!==666?T(aA,c):(aA.state=null,xA===N?T(aA,-3):a):c},o.deflateSetDictionary=function(aA,xA){var RA,NA,YA,PA,mA,LA,dA,HA,WA=xA.length;if(!aA||!aA.state||(PA=(RA=aA.state).wrap)===2||PA===1&&RA.status!==x||RA.lookahead)return c;for(PA===1&&(aA.adler=i(aA.adler,xA,WA,0)),RA.wrap=0,WA>=RA.w_size&&(PA===0&&(W(RA.head),RA.strstart=0,RA.block_start=0,RA.insert=0),HA=new C.Buf8(RA.w_size),C.arraySet(HA,xA,WA-RA.w_size,RA.w_size,0),xA=HA,WA=RA.w_size),mA=aA.avail_in,LA=aA.next_in,dA=aA.input,aA.avail_in=WA,aA.next_in=0,aA.input=xA,nA(RA);RA.lookahead>=k;){for(NA=RA.strstart,YA=RA.lookahead-(k-1);RA.ins_h=(RA.ins_h<<RA.hash_shift^RA.window[NA+k-1])&RA.hash_mask,RA.prev[NA&RA.w_mask]=RA.head[RA.ins_h],RA.head[RA.ins_h]=NA,NA++,--YA;);RA.strstart=NA,RA.lookahead=k-1,nA(RA)}return RA.strstart+=RA.lookahead,RA.block_start=RA.strstart,RA.insert=RA.lookahead,RA.lookahead=0,RA.match_length=RA.prev_length=k-1,RA.match_available=0,aA.next_in=LA,aA.input=dA,aA.avail_in=mA,RA.wrap=PA,a},o.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./messages":51,"./trees":52}],47:[function(e,t,o){t.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],48:[function(e,t,o){t.exports=function(B,C){var Q,i,E,n,s,r,a,c,h,l,D,d,y,w,u,G,m,p,k,S,R,x,N,U,K;Q=B.state,i=B.next_in,U=B.input,E=i+(B.avail_in-5),n=B.next_out,K=B.output,s=n-(C-B.avail_out),r=n+(B.avail_out-257),a=Q.dmax,c=Q.wsize,h=Q.whave,l=Q.wnext,D=Q.window,d=Q.hold,y=Q.bits,w=Q.lencode,u=Q.distcode,G=(1<<Q.lenbits)-1,m=(1<<Q.distbits)-1;A:do{y<15&&(d+=U[i++]<<y,y+=8,d+=U[i++]<<y,y+=8),p=w[d&G];g:for(;;){if(d>>>=k=p>>>24,y-=k,(k=p>>>16&255)===0)K[n++]=65535&p;else{if(!(16&k)){if((64&k)==0){p=w[(65535&p)+(d&(1<<k)-1)];continue g}if(32&k){Q.mode=12;break A}B.msg="invalid literal/length code",Q.mode=30;break A}S=65535&p,(k&=15)&&(y<k&&(d+=U[i++]<<y,y+=8),S+=d&(1<<k)-1,d>>>=k,y-=k),y<15&&(d+=U[i++]<<y,y+=8,d+=U[i++]<<y,y+=8),p=u[d&m];I:for(;;){if(d>>>=k=p>>>24,y-=k,!(16&(k=p>>>16&255))){if((64&k)==0){p=u[(65535&p)+(d&(1<<k)-1)];continue I}B.msg="invalid distance code",Q.mode=30;break A}if(R=65535&p,y<(k&=15)&&(d+=U[i++]<<y,(y+=8)<k&&(d+=U[i++]<<y,y+=8)),a<(R+=d&(1<<k)-1)){B.msg="invalid distance too far back",Q.mode=30;break A}if(d>>>=k,y-=k,(k=n-s)<R){if(h<(k=R-k)&&Q.sane){B.msg="invalid distance too far back",Q.mode=30;break A}if(N=D,(x=0)===l){if(x+=c-k,k<S){for(S-=k;K[n++]=D[x++],--k;);x=n-R,N=K}}else if(l<k){if(x+=c+l-k,(k-=l)<S){for(S-=k;K[n++]=D[x++],--k;);if(x=0,l<S){for(S-=k=l;K[n++]=D[x++],--k;);x=n-R,N=K}}}else if(x+=l-k,k<S){for(S-=k;K[n++]=D[x++],--k;);x=n-R,N=K}for(;2<S;)K[n++]=N[x++],K[n++]=N[x++],K[n++]=N[x++],S-=3;S&&(K[n++]=N[x++],1<S&&(K[n++]=N[x++]))}else{for(x=n-R;K[n++]=K[x++],K[n++]=K[x++],K[n++]=K[x++],2<(S-=3););S&&(K[n++]=K[x++],1<S&&(K[n++]=K[x++]))}break}}break}}while(i<E&&n<r);i-=S=y>>3,d&=(1<<(y-=S<<3))-1,B.next_in=i,B.next_out=n,B.avail_in=i<E?E-i+5:5-(i-E),B.avail_out=n<r?r-n+257:257-(n-r),Q.hold=d,Q.bits=y}},{}],49:[function(e,t,o){var B=e("../utils/common"),C=e("./adler32"),Q=e("./crc32"),i=e("./inffast"),E=e("./inftrees"),n=1,s=2,r=0,a=-2,c=1,h=852,l=592;function D(x){return(x>>>24&255)+(x>>>8&65280)+((65280&x)<<8)+((255&x)<<24)}function d(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new B.Buf16(320),this.work=new B.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function y(x){var N;return x&&x.state?(N=x.state,x.total_in=x.total_out=N.total=0,x.msg="",N.wrap&&(x.adler=1&N.wrap),N.mode=c,N.last=0,N.havedict=0,N.dmax=32768,N.head=null,N.hold=0,N.bits=0,N.lencode=N.lendyn=new B.Buf32(h),N.distcode=N.distdyn=new B.Buf32(l),N.sane=1,N.back=-1,r):a}function w(x){var N;return x&&x.state?((N=x.state).wsize=0,N.whave=0,N.wnext=0,y(x)):a}function u(x,N){var U,K;return x&&x.state?(K=x.state,N<0?(U=0,N=-N):(U=1+(N>>4),N<48&&(N&=15)),N&&(N<8||15<N)?a:(K.window!==null&&K.wbits!==N&&(K.window=null),K.wrap=U,K.wbits=N,w(x))):a}function G(x,N){var U,K;return x?(K=new d,(x.state=K).window=null,(U=u(x,N))!==r&&(x.state=null),U):a}var m,p,k=!0;function S(x){if(k){var N;for(m=new B.Buf32(512),p=new B.Buf32(32),N=0;N<144;)x.lens[N++]=8;for(;N<256;)x.lens[N++]=9;for(;N<280;)x.lens[N++]=7;for(;N<288;)x.lens[N++]=8;for(E(n,x.lens,0,288,m,0,x.work,{bits:9}),N=0;N<32;)x.lens[N++]=5;E(s,x.lens,0,32,p,0,x.work,{bits:5}),k=!1}x.lencode=m,x.lenbits=9,x.distcode=p,x.distbits=5}function R(x,N,U,K){var _,b=x.state;return b.window===null&&(b.wsize=1<<b.wbits,b.wnext=0,b.whave=0,b.window=new B.Buf8(b.wsize)),K>=b.wsize?(B.arraySet(b.window,N,U-b.wsize,b.wsize,0),b.wnext=0,b.whave=b.wsize):(K<(_=b.wsize-b.wnext)&&(_=K),B.arraySet(b.window,N,U-K,_,b.wnext),(K-=_)?(B.arraySet(b.window,N,U-K,K,0),b.wnext=K,b.whave=b.wsize):(b.wnext+=_,b.wnext===b.wsize&&(b.wnext=0),b.whave<b.wsize&&(b.whave+=_))),0}o.inflateReset=w,o.inflateReset2=u,o.inflateResetKeep=y,o.inflateInit=function(x){return G(x,15)},o.inflateInit2=G,o.inflate=function(x,N){var U,K,_,b,T,j,W,O,gA,tA,IA,QA,nA,DA,CA,hA,sA,cA,SA,FA,aA,xA,RA,NA,YA=0,PA=new B.Buf8(4),mA=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!x||!x.state||!x.output||!x.input&&x.avail_in!==0)return a;(U=x.state).mode===12&&(U.mode=13),T=x.next_out,_=x.output,W=x.avail_out,b=x.next_in,K=x.input,j=x.avail_in,O=U.hold,gA=U.bits,tA=j,IA=W,xA=r;A:for(;;)switch(U.mode){case c:if(U.wrap===0){U.mode=13;break}for(;gA<16;){if(j===0)break A;j--,O+=K[b++]<<gA,gA+=8}if(2&U.wrap&&O===35615){PA[U.check=0]=255&O,PA[1]=O>>>8&255,U.check=Q(U.check,PA,2,0),gA=O=0,U.mode=2;break}if(U.flags=0,U.head&&(U.head.done=!1),!(1&U.wrap)||(((255&O)<<8)+(O>>8))%31){x.msg="incorrect header check",U.mode=30;break}if((15&O)!=8){x.msg="unknown compression method",U.mode=30;break}if(gA-=4,aA=8+(15&(O>>>=4)),U.wbits===0)U.wbits=aA;else if(aA>U.wbits){x.msg="invalid window size",U.mode=30;break}U.dmax=1<<aA,x.adler=U.check=1,U.mode=512&O?10:12,gA=O=0;break;case 2:for(;gA<16;){if(j===0)break A;j--,O+=K[b++]<<gA,gA+=8}if(U.flags=O,(255&U.flags)!=8){x.msg="unknown compression method",U.mode=30;break}if(57344&U.flags){x.msg="unknown header flags set",U.mode=30;break}U.head&&(U.head.text=O>>8&1),512&U.flags&&(PA[0]=255&O,PA[1]=O>>>8&255,U.check=Q(U.check,PA,2,0)),gA=O=0,U.mode=3;case 3:for(;gA<32;){if(j===0)break A;j--,O+=K[b++]<<gA,gA+=8}U.head&&(U.head.time=O),512&U.flags&&(PA[0]=255&O,PA[1]=O>>>8&255,PA[2]=O>>>16&255,PA[3]=O>>>24&255,U.check=Q(U.check,PA,4,0)),gA=O=0,U.mode=4;case 4:for(;gA<16;){if(j===0)break A;j--,O+=K[b++]<<gA,gA+=8}U.head&&(U.head.xflags=255&O,U.head.os=O>>8),512&U.flags&&(PA[0]=255&O,PA[1]=O>>>8&255,U.check=Q(U.check,PA,2,0)),gA=O=0,U.mode=5;case 5:if(1024&U.flags){for(;gA<16;){if(j===0)break A;j--,O+=K[b++]<<gA,gA+=8}U.length=O,U.head&&(U.head.extra_len=O),512&U.flags&&(PA[0]=255&O,PA[1]=O>>>8&255,U.check=Q(U.check,PA,2,0)),gA=O=0}else U.head&&(U.head.extra=null);U.mode=6;case 6:if(1024&U.flags&&(j<(QA=U.length)&&(QA=j),QA&&(U.head&&(aA=U.head.extra_len-U.length,U.head.extra||(U.head.extra=new Array(U.head.extra_len)),B.arraySet(U.head.extra,K,b,QA,aA)),512&U.flags&&(U.check=Q(U.check,K,QA,b)),j-=QA,b+=QA,U.length-=QA),U.length))break A;U.length=0,U.mode=7;case 7:if(2048&U.flags){if(j===0)break A;for(QA=0;aA=K[b+QA++],U.head&&aA&&U.length<65536&&(U.head.name+=String.fromCharCode(aA)),aA&&QA<j;);if(512&U.flags&&(U.check=Q(U.check,K,QA,b)),j-=QA,b+=QA,aA)break A}else U.head&&(U.head.name=null);U.length=0,U.mode=8;case 8:if(4096&U.flags){if(j===0)break A;for(QA=0;aA=K[b+QA++],U.head&&aA&&U.length<65536&&(U.head.comment+=String.fromCharCode(aA)),aA&&QA<j;);if(512&U.flags&&(U.check=Q(U.check,K,QA,b)),j-=QA,b+=QA,aA)break A}else U.head&&(U.head.comment=null);U.mode=9;case 9:if(512&U.flags){for(;gA<16;){if(j===0)break A;j--,O+=K[b++]<<gA,gA+=8}if(O!==(65535&U.check)){x.msg="header crc mismatch",U.mode=30;break}gA=O=0}U.head&&(U.head.hcrc=U.flags>>9&1,U.head.done=!0),x.adler=U.check=0,U.mode=12;break;case 10:for(;gA<32;){if(j===0)break A;j--,O+=K[b++]<<gA,gA+=8}x.adler=U.check=D(O),gA=O=0,U.mode=11;case 11:if(U.havedict===0)return x.next_out=T,x.avail_out=W,x.next_in=b,x.avail_in=j,U.hold=O,U.bits=gA,2;x.adler=U.check=1,U.mode=12;case 12:if(N===5||N===6)break A;case 13:if(U.last){O>>>=7&gA,gA-=7&gA,U.mode=27;break}for(;gA<3;){if(j===0)break A;j--,O+=K[b++]<<gA,gA+=8}switch(U.last=1&O,gA-=1,3&(O>>>=1)){case 0:U.mode=14;break;case 1:if(S(U),U.mode=20,N!==6)break;O>>>=2,gA-=2;break A;case 2:U.mode=17;break;case 3:x.msg="invalid block type",U.mode=30}O>>>=2,gA-=2;break;case 14:for(O>>>=7&gA,gA-=7&gA;gA<32;){if(j===0)break A;j--,O+=K[b++]<<gA,gA+=8}if((65535&O)!=(O>>>16^65535)){x.msg="invalid stored block lengths",U.mode=30;break}if(U.length=65535&O,gA=O=0,U.mode=15,N===6)break A;case 15:U.mode=16;case 16:if(QA=U.length){if(j<QA&&(QA=j),W<QA&&(QA=W),QA===0)break A;B.arraySet(_,K,b,QA,T),j-=QA,b+=QA,W-=QA,T+=QA,U.length-=QA;break}U.mode=12;break;case 17:for(;gA<14;){if(j===0)break A;j--,O+=K[b++]<<gA,gA+=8}if(U.nlen=257+(31&O),O>>>=5,gA-=5,U.ndist=1+(31&O),O>>>=5,gA-=5,U.ncode=4+(15&O),O>>>=4,gA-=4,286<U.nlen||30<U.ndist){x.msg="too many length or distance symbols",U.mode=30;break}U.have=0,U.mode=18;case 18:for(;U.have<U.ncode;){for(;gA<3;){if(j===0)break A;j--,O+=K[b++]<<gA,gA+=8}U.lens[mA[U.have++]]=7&O,O>>>=3,gA-=3}for(;U.have<19;)U.lens[mA[U.have++]]=0;if(U.lencode=U.lendyn,U.lenbits=7,RA={bits:U.lenbits},xA=E(0,U.lens,0,19,U.lencode,0,U.work,RA),U.lenbits=RA.bits,xA){x.msg="invalid code lengths set",U.mode=30;break}U.have=0,U.mode=19;case 19:for(;U.have<U.nlen+U.ndist;){for(;hA=(YA=U.lencode[O&(1<<U.lenbits)-1])>>>16&255,sA=65535&YA,!((CA=YA>>>24)<=gA);){if(j===0)break A;j--,O+=K[b++]<<gA,gA+=8}if(sA<16)O>>>=CA,gA-=CA,U.lens[U.have++]=sA;else{if(sA===16){for(NA=CA+2;gA<NA;){if(j===0)break A;j--,O+=K[b++]<<gA,gA+=8}if(O>>>=CA,gA-=CA,U.have===0){x.msg="invalid bit length repeat",U.mode=30;break}aA=U.lens[U.have-1],QA=3+(3&O),O>>>=2,gA-=2}else if(sA===17){for(NA=CA+3;gA<NA;){if(j===0)break A;j--,O+=K[b++]<<gA,gA+=8}gA-=CA,aA=0,QA=3+(7&(O>>>=CA)),O>>>=3,gA-=3}else{for(NA=CA+7;gA<NA;){if(j===0)break A;j--,O+=K[b++]<<gA,gA+=8}gA-=CA,aA=0,QA=11+(127&(O>>>=CA)),O>>>=7,gA-=7}if(U.have+QA>U.nlen+U.ndist){x.msg="invalid bit length repeat",U.mode=30;break}for(;QA--;)U.lens[U.have++]=aA}}if(U.mode===30)break;if(U.lens[256]===0){x.msg="invalid code -- missing end-of-block",U.mode=30;break}if(U.lenbits=9,RA={bits:U.lenbits},xA=E(n,U.lens,0,U.nlen,U.lencode,0,U.work,RA),U.lenbits=RA.bits,xA){x.msg="invalid literal/lengths set",U.mode=30;break}if(U.distbits=6,U.distcode=U.distdyn,RA={bits:U.distbits},xA=E(s,U.lens,U.nlen,U.ndist,U.distcode,0,U.work,RA),U.distbits=RA.bits,xA){x.msg="invalid distances set",U.mode=30;break}if(U.mode=20,N===6)break A;case 20:U.mode=21;case 21:if(6<=j&&258<=W){x.next_out=T,x.avail_out=W,x.next_in=b,x.avail_in=j,U.hold=O,U.bits=gA,i(x,IA),T=x.next_out,_=x.output,W=x.avail_out,b=x.next_in,K=x.input,j=x.avail_in,O=U.hold,gA=U.bits,U.mode===12&&(U.back=-1);break}for(U.back=0;hA=(YA=U.lencode[O&(1<<U.lenbits)-1])>>>16&255,sA=65535&YA,!((CA=YA>>>24)<=gA);){if(j===0)break A;j--,O+=K[b++]<<gA,gA+=8}if(hA&&(240&hA)==0){for(cA=CA,SA=hA,FA=sA;hA=(YA=U.lencode[FA+((O&(1<<cA+SA)-1)>>cA)])>>>16&255,sA=65535&YA,!(cA+(CA=YA>>>24)<=gA);){if(j===0)break A;j--,O+=K[b++]<<gA,gA+=8}O>>>=cA,gA-=cA,U.back+=cA}if(O>>>=CA,gA-=CA,U.back+=CA,U.length=sA,hA===0){U.mode=26;break}if(32&hA){U.back=-1,U.mode=12;break}if(64&hA){x.msg="invalid literal/length code",U.mode=30;break}U.extra=15&hA,U.mode=22;case 22:if(U.extra){for(NA=U.extra;gA<NA;){if(j===0)break A;j--,O+=K[b++]<<gA,gA+=8}U.length+=O&(1<<U.extra)-1,O>>>=U.extra,gA-=U.extra,U.back+=U.extra}U.was=U.length,U.mode=23;case 23:for(;hA=(YA=U.distcode[O&(1<<U.distbits)-1])>>>16&255,sA=65535&YA,!((CA=YA>>>24)<=gA);){if(j===0)break A;j--,O+=K[b++]<<gA,gA+=8}if((240&hA)==0){for(cA=CA,SA=hA,FA=sA;hA=(YA=U.distcode[FA+((O&(1<<cA+SA)-1)>>cA)])>>>16&255,sA=65535&YA,!(cA+(CA=YA>>>24)<=gA);){if(j===0)break A;j--,O+=K[b++]<<gA,gA+=8}O>>>=cA,gA-=cA,U.back+=cA}if(O>>>=CA,gA-=CA,U.back+=CA,64&hA){x.msg="invalid distance code",U.mode=30;break}U.offset=sA,U.extra=15&hA,U.mode=24;case 24:if(U.extra){for(NA=U.extra;gA<NA;){if(j===0)break A;j--,O+=K[b++]<<gA,gA+=8}U.offset+=O&(1<<U.extra)-1,O>>>=U.extra,gA-=U.extra,U.back+=U.extra}if(U.offset>U.dmax){x.msg="invalid distance too far back",U.mode=30;break}U.mode=25;case 25:if(W===0)break A;if(QA=IA-W,U.offset>QA){if((QA=U.offset-QA)>U.whave&&U.sane){x.msg="invalid distance too far back",U.mode=30;break}nA=QA>U.wnext?(QA-=U.wnext,U.wsize-QA):U.wnext-QA,QA>U.length&&(QA=U.length),DA=U.window}else DA=_,nA=T-U.offset,QA=U.length;for(W<QA&&(QA=W),W-=QA,U.length-=QA;_[T++]=DA[nA++],--QA;);U.length===0&&(U.mode=21);break;case 26:if(W===0)break A;_[T++]=U.length,W--,U.mode=21;break;case 27:if(U.wrap){for(;gA<32;){if(j===0)break A;j--,O|=K[b++]<<gA,gA+=8}if(IA-=W,x.total_out+=IA,U.total+=IA,IA&&(x.adler=U.check=U.flags?Q(U.check,_,IA,T-IA):C(U.check,_,IA,T-IA)),IA=W,(U.flags?O:D(O))!==U.check){x.msg="incorrect data check",U.mode=30;break}gA=O=0}U.mode=28;case 28:if(U.wrap&&U.flags){for(;gA<32;){if(j===0)break A;j--,O+=K[b++]<<gA,gA+=8}if(O!==(4294967295&U.total)){x.msg="incorrect length check",U.mode=30;break}gA=O=0}U.mode=29;case 29:xA=1;break A;case 30:xA=-3;break A;case 31:return-4;default:return a}return x.next_out=T,x.avail_out=W,x.next_in=b,x.avail_in=j,U.hold=O,U.bits=gA,(U.wsize||IA!==x.avail_out&&U.mode<30&&(U.mode<27||N!==4))&&R(x,x.output,x.next_out,IA-x.avail_out)?(U.mode=31,-4):(tA-=x.avail_in,IA-=x.avail_out,x.total_in+=tA,x.total_out+=IA,U.total+=IA,U.wrap&&IA&&(x.adler=U.check=U.flags?Q(U.check,_,IA,x.next_out-IA):C(U.check,_,IA,x.next_out-IA)),x.data_type=U.bits+(U.last?64:0)+(U.mode===12?128:0)+(U.mode===20||U.mode===15?256:0),(tA==0&&IA===0||N===4)&&xA===r&&(xA=-5),xA)},o.inflateEnd=function(x){if(!x||!x.state)return a;var N=x.state;return N.window&&(N.window=null),x.state=null,r},o.inflateGetHeader=function(x,N){var U;return x&&x.state?(2&(U=x.state).wrap)==0?a:((U.head=N).done=!1,r):a},o.inflateSetDictionary=function(x,N){var U,K=N.length;return x&&x.state?(U=x.state).wrap!==0&&U.mode!==11?a:U.mode===11&&C(1,N,K,0)!==U.check?-3:R(x,N,K,K)?(U.mode=31,-4):(U.havedict=1,r):a},o.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./inffast":48,"./inftrees":50}],50:[function(e,t,o){var B=e("../utils/common"),C=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],Q=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],i=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],E=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];t.exports=function(n,s,r,a,c,h,l,D){var d,y,w,u,G,m,p,k,S,R=D.bits,x=0,N=0,U=0,K=0,_=0,b=0,T=0,j=0,W=0,O=0,gA=null,tA=0,IA=new B.Buf16(16),QA=new B.Buf16(16),nA=null,DA=0;for(x=0;x<=15;x++)IA[x]=0;for(N=0;N<a;N++)IA[s[r+N]]++;for(_=R,K=15;1<=K&&IA[K]===0;K--);if(K<_&&(_=K),K===0)return c[h++]=20971520,c[h++]=20971520,D.bits=1,0;for(U=1;U<K&&IA[U]===0;U++);for(_<U&&(_=U),x=j=1;x<=15;x++)if(j<<=1,(j-=IA[x])<0)return-1;if(0<j&&(n===0||K!==1))return-1;for(QA[1]=0,x=1;x<15;x++)QA[x+1]=QA[x]+IA[x];for(N=0;N<a;N++)s[r+N]!==0&&(l[QA[s[r+N]]++]=N);if(m=n===0?(gA=nA=l,19):n===1?(gA=C,tA-=257,nA=Q,DA-=257,256):(gA=i,nA=E,-1),x=U,G=h,T=N=O=0,w=-1,u=(W=1<<(b=_))-1,n===1&&852<W||n===2&&592<W)return 1;for(;;){for(p=x-T,S=l[N]<m?(k=0,l[N]):l[N]>m?(k=nA[DA+l[N]],gA[tA+l[N]]):(k=96,0),d=1<<x-T,U=y=1<<b;c[G+(O>>T)+(y-=d)]=p<<24|k<<16|S|0,y!==0;);for(d=1<<x-1;O&d;)d>>=1;if(d!==0?(O&=d-1,O+=d):O=0,N++,--IA[x]==0){if(x===K)break;x=s[r+l[N]]}if(_<x&&(O&u)!==w){for(T===0&&(T=_),G+=U,j=1<<(b=x-T);b+T<K&&!((j-=IA[b+T])<=0);)b++,j<<=1;if(W+=1<<b,n===1&&852<W||n===2&&592<W)return 1;c[w=O&u]=_<<24|b<<16|G-h|0}}return O!==0&&(c[G+O]=x-T<<24|64<<16|0),D.bits=_,0}},{"../utils/common":41}],51:[function(e,t,o){t.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],52:[function(e,t,o){var B=e("../utils/common"),C=0,Q=1;function i(YA){for(var PA=YA.length;0<=--PA;)YA[PA]=0}var E=0,n=29,s=256,r=s+1+n,a=30,c=19,h=2*r+1,l=15,D=16,d=7,y=256,w=16,u=17,G=18,m=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],p=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],k=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],S=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],R=new Array(2*(r+2));i(R);var x=new Array(2*a);i(x);var N=new Array(512);i(N);var U=new Array(256);i(U);var K=new Array(n);i(K);var _,b,T,j=new Array(a);function W(YA,PA,mA,LA,dA){this.static_tree=YA,this.extra_bits=PA,this.extra_base=mA,this.elems=LA,this.max_length=dA,this.has_stree=YA&&YA.length}function O(YA,PA){this.dyn_tree=YA,this.max_code=0,this.stat_desc=PA}function gA(YA){return YA<256?N[YA]:N[256+(YA>>>7)]}function tA(YA,PA){YA.pending_buf[YA.pending++]=255&PA,YA.pending_buf[YA.pending++]=PA>>>8&255}function IA(YA,PA,mA){YA.bi_valid>D-mA?(YA.bi_buf|=PA<<YA.bi_valid&65535,tA(YA,YA.bi_buf),YA.bi_buf=PA>>D-YA.bi_valid,YA.bi_valid+=mA-D):(YA.bi_buf|=PA<<YA.bi_valid&65535,YA.bi_valid+=mA)}function QA(YA,PA,mA){IA(YA,mA[2*PA],mA[2*PA+1])}function nA(YA,PA){for(var mA=0;mA|=1&YA,YA>>>=1,mA<<=1,0<--PA;);return mA>>>1}function DA(YA,PA,mA){var LA,dA,HA=new Array(l+1),WA=0;for(LA=1;LA<=l;LA++)HA[LA]=WA=WA+mA[LA-1]<<1;for(dA=0;dA<=PA;dA++){var Qg=YA[2*dA+1];Qg!==0&&(YA[2*dA]=nA(HA[Qg]++,Qg))}}function CA(YA){var PA;for(PA=0;PA<r;PA++)YA.dyn_ltree[2*PA]=0;for(PA=0;PA<a;PA++)YA.dyn_dtree[2*PA]=0;for(PA=0;PA<c;PA++)YA.bl_tree[2*PA]=0;YA.dyn_ltree[2*y]=1,YA.opt_len=YA.static_len=0,YA.last_lit=YA.matches=0}function hA(YA){8<YA.bi_valid?tA(YA,YA.bi_buf):0<YA.bi_valid&&(YA.pending_buf[YA.pending++]=YA.bi_buf),YA.bi_buf=0,YA.bi_valid=0}function sA(YA,PA,mA,LA){var dA=2*PA,HA=2*mA;return YA[dA]<YA[HA]||YA[dA]===YA[HA]&&LA[PA]<=LA[mA]}function cA(YA,PA,mA){for(var LA=YA.heap[mA],dA=mA<<1;dA<=YA.heap_len&&(dA<YA.heap_len&&sA(PA,YA.heap[dA+1],YA.heap[dA],YA.depth)&&dA++,!sA(PA,LA,YA.heap[dA],YA.depth));)YA.heap[mA]=YA.heap[dA],mA=dA,dA<<=1;YA.heap[mA]=LA}function SA(YA,PA,mA){var LA,dA,HA,WA,Qg=0;if(YA.last_lit!==0)for(;LA=YA.pending_buf[YA.d_buf+2*Qg]<<8|YA.pending_buf[YA.d_buf+2*Qg+1],dA=YA.pending_buf[YA.l_buf+Qg],Qg++,LA===0?QA(YA,dA,PA):(QA(YA,(HA=U[dA])+s+1,PA),(WA=m[HA])!==0&&IA(YA,dA-=K[HA],WA),QA(YA,HA=gA(--LA),mA),(WA=p[HA])!==0&&IA(YA,LA-=j[HA],WA)),Qg<YA.last_lit;);QA(YA,y,PA)}function FA(YA,PA){var mA,LA,dA,HA=PA.dyn_tree,WA=PA.stat_desc.static_tree,Qg=PA.stat_desc.has_stree,_A=PA.stat_desc.elems,uA=-1;for(YA.heap_len=0,YA.heap_max=h,mA=0;mA<_A;mA++)HA[2*mA]!==0?(YA.heap[++YA.heap_len]=uA=mA,YA.depth[mA]=0):HA[2*mA+1]=0;for(;YA.heap_len<2;)HA[2*(dA=YA.heap[++YA.heap_len]=uA<2?++uA:0)]=1,YA.depth[dA]=0,YA.opt_len--,Qg&&(YA.static_len-=WA[2*dA+1]);for(PA.max_code=uA,mA=YA.heap_len>>1;1<=mA;mA--)cA(YA,HA,mA);for(dA=_A;mA=YA.heap[1],YA.heap[1]=YA.heap[YA.heap_len--],cA(YA,HA,1),LA=YA.heap[1],YA.heap[--YA.heap_max]=mA,YA.heap[--YA.heap_max]=LA,HA[2*dA]=HA[2*mA]+HA[2*LA],YA.depth[dA]=(YA.depth[mA]>=YA.depth[LA]?YA.depth[mA]:YA.depth[LA])+1,HA[2*mA+1]=HA[2*LA+1]=dA,YA.heap[1]=dA++,cA(YA,HA,1),2<=YA.heap_len;);YA.heap[--YA.heap_max]=YA.heap[1],(function(kA,OA){var $A,og,dg,Sg,Bg,Yg,QI=OA.dyn_tree,GA=OA.max_code,ng=OA.stat_desc.static_tree,pg=OA.stat_desc.has_stree,Ug=OA.stat_desc.extra_bits,mg=OA.stat_desc.extra_base,Rg=OA.stat_desc.max_length,Jg=0;for(Sg=0;Sg<=l;Sg++)kA.bl_count[Sg]=0;for(QI[2*kA.heap[kA.heap_max]+1]=0,$A=kA.heap_max+1;$A<h;$A++)Rg<(Sg=QI[2*QI[2*(og=kA.heap[$A])+1]+1]+1)&&(Sg=Rg,Jg++),QI[2*og+1]=Sg,GA<og||(kA.bl_count[Sg]++,Bg=0,mg<=og&&(Bg=Ug[og-mg]),Yg=QI[2*og],kA.opt_len+=Yg*(Sg+Bg),pg&&(kA.static_len+=Yg*(ng[2*og+1]+Bg)));if(Jg!==0){do{for(Sg=Rg-1;kA.bl_count[Sg]===0;)Sg--;kA.bl_count[Sg]--,kA.bl_count[Sg+1]+=2,kA.bl_count[Rg]--,Jg-=2}while(0<Jg);for(Sg=Rg;Sg!==0;Sg--)for(og=kA.bl_count[Sg];og!==0;)GA<(dg=kA.heap[--$A])||(QI[2*dg+1]!==Sg&&(kA.opt_len+=(Sg-QI[2*dg+1])*QI[2*dg],QI[2*dg+1]=Sg),og--)}})(YA,PA),DA(HA,uA,YA.bl_count)}function aA(YA,PA,mA){var LA,dA,HA=-1,WA=PA[1],Qg=0,_A=7,uA=4;for(WA===0&&(_A=138,uA=3),PA[2*(mA+1)+1]=65535,LA=0;LA<=mA;LA++)dA=WA,WA=PA[2*(LA+1)+1],++Qg<_A&&dA===WA||(Qg<uA?YA.bl_tree[2*dA]+=Qg:dA!==0?(dA!==HA&&YA.bl_tree[2*dA]++,YA.bl_tree[2*w]++):Qg<=10?YA.bl_tree[2*u]++:YA.bl_tree[2*G]++,HA=dA,uA=(Qg=0)===WA?(_A=138,3):dA===WA?(_A=6,3):(_A=7,4))}function xA(YA,PA,mA){var LA,dA,HA=-1,WA=PA[1],Qg=0,_A=7,uA=4;for(WA===0&&(_A=138,uA=3),LA=0;LA<=mA;LA++)if(dA=WA,WA=PA[2*(LA+1)+1],!(++Qg<_A&&dA===WA)){if(Qg<uA)for(;QA(YA,dA,YA.bl_tree),--Qg!=0;);else dA!==0?(dA!==HA&&(QA(YA,dA,YA.bl_tree),Qg--),QA(YA,w,YA.bl_tree),IA(YA,Qg-3,2)):Qg<=10?(QA(YA,u,YA.bl_tree),IA(YA,Qg-3,3)):(QA(YA,G,YA.bl_tree),IA(YA,Qg-11,7));HA=dA,uA=(Qg=0)===WA?(_A=138,3):dA===WA?(_A=6,3):(_A=7,4)}}i(j);var RA=!1;function NA(YA,PA,mA,LA){IA(YA,(E<<1)+(LA?1:0),3),(function(dA,HA,WA,Qg){hA(dA),tA(dA,WA),tA(dA,~WA),B.arraySet(dA.pending_buf,dA.window,HA,WA,dA.pending),dA.pending+=WA})(YA,PA,mA)}o._tr_init=function(YA){RA||((function(){var PA,mA,LA,dA,HA,WA=new Array(l+1);for(dA=LA=0;dA<n-1;dA++)for(K[dA]=LA,PA=0;PA<1<<m[dA];PA++)U[LA++]=dA;for(U[LA-1]=dA,dA=HA=0;dA<16;dA++)for(j[dA]=HA,PA=0;PA<1<<p[dA];PA++)N[HA++]=dA;for(HA>>=7;dA<a;dA++)for(j[dA]=HA<<7,PA=0;PA<1<<p[dA]-7;PA++)N[256+HA++]=dA;for(mA=0;mA<=l;mA++)WA[mA]=0;for(PA=0;PA<=143;)R[2*PA+1]=8,PA++,WA[8]++;for(;PA<=255;)R[2*PA+1]=9,PA++,WA[9]++;for(;PA<=279;)R[2*PA+1]=7,PA++,WA[7]++;for(;PA<=287;)R[2*PA+1]=8,PA++,WA[8]++;for(DA(R,r+1,WA),PA=0;PA<a;PA++)x[2*PA+1]=5,x[2*PA]=nA(PA,5);_=new W(R,m,s+1,r,l),b=new W(x,p,0,a,l),T=new W(new Array(0),k,0,c,d)})(),RA=!0),YA.l_desc=new O(YA.dyn_ltree,_),YA.d_desc=new O(YA.dyn_dtree,b),YA.bl_desc=new O(YA.bl_tree,T),YA.bi_buf=0,YA.bi_valid=0,CA(YA)},o._tr_stored_block=NA,o._tr_flush_block=function(YA,PA,mA,LA){var dA,HA,WA=0;0<YA.level?(YA.strm.data_type===2&&(YA.strm.data_type=(function(Qg){var _A,uA=4093624447;for(_A=0;_A<=31;_A++,uA>>>=1)if(1&uA&&Qg.dyn_ltree[2*_A]!==0)return C;if(Qg.dyn_ltree[18]!==0||Qg.dyn_ltree[20]!==0||Qg.dyn_ltree[26]!==0)return Q;for(_A=32;_A<s;_A++)if(Qg.dyn_ltree[2*_A]!==0)return Q;return C})(YA)),FA(YA,YA.l_desc),FA(YA,YA.d_desc),WA=(function(Qg){var _A;for(aA(Qg,Qg.dyn_ltree,Qg.l_desc.max_code),aA(Qg,Qg.dyn_dtree,Qg.d_desc.max_code),FA(Qg,Qg.bl_desc),_A=c-1;3<=_A&&Qg.bl_tree[2*S[_A]+1]===0;_A--);return Qg.opt_len+=3*(_A+1)+5+5+4,_A})(YA),dA=YA.opt_len+3+7>>>3,(HA=YA.static_len+3+7>>>3)<=dA&&(dA=HA)):dA=HA=mA+5,mA+4<=dA&&PA!==-1?NA(YA,PA,mA,LA):YA.strategy===4||HA===dA?(IA(YA,2+(LA?1:0),3),SA(YA,R,x)):(IA(YA,4+(LA?1:0),3),(function(Qg,_A,uA,kA){var OA;for(IA(Qg,_A-257,5),IA(Qg,uA-1,5),IA(Qg,kA-4,4),OA=0;OA<kA;OA++)IA(Qg,Qg.bl_tree[2*S[OA]+1],3);xA(Qg,Qg.dyn_ltree,_A-1),xA(Qg,Qg.dyn_dtree,uA-1)})(YA,YA.l_desc.max_code+1,YA.d_desc.max_code+1,WA+1),SA(YA,YA.dyn_ltree,YA.dyn_dtree)),CA(YA),LA&&hA(YA)},o._tr_tally=function(YA,PA,mA){return YA.pending_buf[YA.d_buf+2*YA.last_lit]=PA>>>8&255,YA.pending_buf[YA.d_buf+2*YA.last_lit+1]=255&PA,YA.pending_buf[YA.l_buf+YA.last_lit]=255&mA,YA.last_lit++,PA===0?YA.dyn_ltree[2*mA]++:(YA.matches++,PA--,YA.dyn_ltree[2*(U[mA]+s+1)]++,YA.dyn_dtree[2*gA(PA)]++),YA.last_lit===YA.lit_bufsize-1},o._tr_align=function(YA){IA(YA,2,3),QA(YA,y,R),(function(PA){PA.bi_valid===16?(tA(PA,PA.bi_buf),PA.bi_buf=0,PA.bi_valid=0):8<=PA.bi_valid&&(PA.pending_buf[PA.pending++]=255&PA.bi_buf,PA.bi_buf>>=8,PA.bi_valid-=8)})(YA)}},{"../utils/common":41}],53:[function(e,t,o){t.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(e,t,o){(function(B){(function(C,Q){if(!C.setImmediate){var i,E,n,s,r=1,a={},c=!1,h=C.document,l=Object.getPrototypeOf&&Object.getPrototypeOf(C);l=l&&l.setTimeout?l:C,i={}.toString.call(C.process)==="[object process]"?function(w){I.nextTick(function(){d(w)})}:(function(){if(C.postMessage&&!C.importScripts){var w=!0,u=C.onmessage;return C.onmessage=function(){w=!1},C.postMessage("","*"),C.onmessage=u,w}})()?(s="setImmediate$"+Math.random()+"$",C.addEventListener?C.addEventListener("message",y,!1):C.attachEvent("onmessage",y),function(w){C.postMessage(s+w,"*")}):C.MessageChannel?((n=new MessageChannel).port1.onmessage=function(w){d(w.data)},function(w){n.port2.postMessage(w)}):h&&"onreadystatechange"in h.createElement("script")?(E=h.documentElement,function(w){var u=h.createElement("script");u.onreadystatechange=function(){d(w),u.onreadystatechange=null,E.removeChild(u),u=null},E.appendChild(u)}):function(w){setTimeout(d,0,w)},l.setImmediate=function(w){typeof w!="function"&&(w=new Function(""+w));for(var u=new Array(arguments.length-1),G=0;G<u.length;G++)u[G]=arguments[G+1];var m={callback:w,args:u};return a[r]=m,i(r),r++},l.clearImmediate=D}function D(w){delete a[w]}function d(w){if(c)setTimeout(d,0,w);else{var u=a[w];if(u){c=!0;try{(function(G){var m=G.callback,p=G.args;switch(p.length){case 0:m();break;case 1:m(p[0]);break;case 2:m(p[0],p[1]);break;case 3:m(p[0],p[1],p[2]);break;default:m.apply(Q,p)}})(u)}finally{D(w),c=!1}}}}function y(w){w.source===C&&typeof w.data=="string"&&w.data.indexOf(s)===0&&d(+w.data.slice(s.length))}})(typeof self>"u"?B===void 0?this:B:self)}).call(this,typeof zL<"u"?zL:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(Uog)),Uog.exports}var tuo=euo();const AtA=Sp(tuo),ouo=async()=>await Promise.resolve().then(()=>uqo),Buo=async({circuitJson:g,projectName:A})=>{try{const{circuitJsonToStep:I}=await ouo(),e=await I(g,{exportMode:"assembly"}),t=new AtA;for(const[o,B]of Object.entries(e))t.file(o,B);kk(await t.generateAsync({type:"blob"}),{fileName:`${A}-assembly.zip`})}catch(I){JC.error(`Failed to export assembly STEP: ${I instanceof Error?I.message:String(I)}`)}},Cuo=async({circuitJson:g,projectName:A})=>{await JC.promise((async()=>{const I=new AtA,[e,{convertCircuitJsonToBomRows:t,convertBomRowsToCsv:o},{convertCircuitJsonToPickAndPlaceCsv:B}]=await Promise.all([cS("circuit-json-to-gerber"),cS("circuit-json-to-bom-csv"),cS("circuit-json-to-pnp-csv")]),C=g.filter(r=>!("error_type"in r)&&!("warning_type"in r)),Q=e.convertCircuitJsonToGerberFiles(C,{flip_y_axis:!1});for(const[r,a]of Object.entries(Q))I.file(`gerber/${r}`,a);const i=await t({circuitJson:g}),E=await o(i);I.file("bom.csv",E);const n=await B(g,{supplier:"jlcpcb"});I.file("pick_and_place.csv",n);const s=await I.generateAsync({type:"blob"});kk(s,{fileName:`${A}_fabrication_files.zip`})})(),{loading:"Generating fabrication files...",success:"Fabrication ZIP ready",error:I=>`Failed to generate fabrication files: ${I instanceof Error?I.message:String(I)}`})},Quo=async g=>{const{createFdmComponentBox:A,renderFdmComponentBoxPng:I}=await cS("circuit-json-to-fdm-component-box"),[e,t]=await Promise.all([A(g),I(g,{},{width:960,height:640})]);return{...e,previewPng:t}},iuo=async g=>{const{createFdmComponentBox:A}=await cS("circuit-json-to-fdm-component-box");return A(g)},KFI=({generatedBox:g,projectName:A})=>{const I=Uint8Array.from(g.threeMf);kk(new Blob([I.buffer],{type:"model/3mf"}),{fileName:`${oog(A)}-component-box.3mf`})},Euo=async({circuitJson:g,projectName:A})=>{await JC.promise((async()=>{const I=await iuo(g);KFI({generatedBox:I,projectName:A})})(),{loading:"Generating component box...",success:"Component box 3MF ready",error:I=>`Failed to generate component box: ${I instanceof Error?I.message:String(I)}`})},nuo=async({circuitJson:g,projectName:A})=>{let I;try{const{convertCircuitJsonToGltf:e}=await cS("circuit-json-to-gltf");console.log("convertCircuitJsonToGltf",e);const t=await e(g,{format:"glb",boardTextureResolution:1024});if(!t||!(t instanceof ArrayBuffer))throw new Error("Invalid GLB data returned from converter");I=new Blob([t],{type:"model/gltf-binary"})}catch(e){console.error("GLB Export Error:",e);return}kk(I,{fileName:`${A}.glb`})},suo=async({circuitJson:g,libraryName:A})=>{const{CircuitJsonToKicadLibraryConverter:I}=await cS("circuit-json-to-kicad"),e=new I(g,{libraryName:A,footprintLibraryName:A});e.runUntilFinished();const t=e.getOutput(),o=new AtA;o.file(`${A}.kicad_sym`,t.kicadSymString);for(const B of t.footprints){const C=o.folder(`${A}.pretty`);C&&C.file(`${B.footprintName}.kicad_mod`,`${B.kicadModString}
5670
5670
  `)}if(t.model3dSourcePaths.length>0){const B=o.folder(`${A}.3dshapes`);if(B)for(const C of t.model3dSourcePaths)try{const Q=C.split("/").pop()||C,i=await fetch(C);if(i.ok){const E=await i.arrayBuffer();B.file(Q,E)}}catch{}}return o.file("fp-lib-table",t.fpLibTableString),o.file("sym-lib-table",t.symLibTableString),o},auo=async({circuitJson:g,projectName:A})=>{await JC.promise((async()=>{const e=await(await suo({circuitJson:g,libraryName:A})).generateAsync({type:"blob"});kk(e,{fileName:`${A}_kicad_library.zip`})})(),{loading:"Generating KiCad library...",success:"KiCad library ZIP ready",error:I=>`Failed to generate KiCad library: ${I instanceof Error?I.message:String(I)}`})},ruo=async({circuitJson:g,projectName:A})=>{const{CircuitJsonToKicadPcbConverter:I,CircuitJsonToKicadSchConverter:e,CircuitJsonToKicadProConverter:t,resolveAndLoadKicad3dModelFiles:o}=await cS("circuit-json-to-kicad"),B=new e(g);B.runUntilFinished();const C=B.getOutputString(),Q=new I(g,{includeBuiltin3dModels:!0,projectName:A});Q.runUntilFinished();const i=Q.getOutputString(),E=new t(g,{projectName:A,schematicFilename:`${A}.kicad_sch`,pcbFilename:`${A}.kicad_pcb`});E.runUntilFinished();const n=E.getOutputString(),s=new AtA;return s.file(`${A}.kicad_sch`,C),s.file(`${A}.kicad_pcb`,i),s.file(`${A}.kicad_pro`,n),await o({projectName:A,model3dSourcePaths:Q.getModel3dSourcePaths(),fetch,onModelFile:({outputPath:r,content:a})=>{s.file(r,a)},onError:({sourcePath:r})=>{console.warn(`Failed to load 3D model from ${r}`)}}),s},cuo=async({circuitJson:g,projectName:A})=>{await JC.promise((async()=>{const e=await(await ruo({circuitJson:g,projectName:A})).generateAsync({type:"blob"});kk(e,{fileName:`${A}_kicad_project.zip`})})(),{loading:"Generating KiCad project...",success:"KiCad project ZIP ready",error:I=>`Failed to generate KiCad project: ${I instanceof Error?I.message:String(I)}`})},LFI=async({circuitJson:g,projectName:A,options:I={}})=>{try{const{convertCircuitJsonToLbrn:e}=await cS("circuit-json-to-lbrn"),o=(await e(g,{includeSilkscreen:I.includeSilkscreen??!1,includeOxidationCleaningLayer:I.includeOxidationCleaningLayer??!0})).toXml(),B=new Blob([o],{type:"application/lbrn"});kk(B,{fileName:`${A}.lbrn2`})}catch(e){const t=e instanceof Error?e.message:"Unknown error";JC.error(`Failed to export to LBRN format: ${t}`)}},huo=async({circuitJson:g,projectName:A})=>{const{convertCircuitJsonToPinoutSvg:I}=await cS("circuit-to-svg"),e=I(g);kk(e,{fileName:`${A}-pinout.svg`,mimeType:"image/svg+xml"})},luo=async({circuitJson:g,projectName:A})=>{const{circuitJsonToStep:I}=await cS("circuit-json-to-step"),e=g.find(i=>i.type==="pcb_board"),t=e&&"width"in e?e.width:void 0,o=e&&"height"in e?e.height:void 0,B=e&&"thickness"in e?e.thickness:void 0;if(t===void 0||o===void 0||B===void 0){JC.error("Board dimensions not found. Please add a pcb_board with width, height, and thickness to your circuit.");return}let C;try{C=await I(g,{boardWidth:t,boardHeight:o,boardThickness:B,productName:A,includeComponents:!0,includeExternalMeshes:!0})}catch(i){const E=i instanceof Error?i.message:"Unknown error";JC.error(`Failed to convert circuit to STEP format: ${E}`);return}const Q=new Blob([C],{type:"application/step"});try{kk(Q,{fileName:`${A}.step`})}catch(i){const E=i instanceof Error?i.message:"Unknown error";JC.error(`Failed to download STEP file: ${E}`)}},Duo=[{extension:"json",name:"Circuit JSON"},{extension:"json",name:"Simple Route JSON"},{extension:"zip",name:"Fabrication Files"},{extension:"zip",name:"KiCad Project"},{extension:"zip",name:"Altium Project"},{extension:"zip",name:"KiCad Library"},{extension:"glb",name:"GLB (Binary GLTF)"},{extension:"svg",name:"Pinout SVG"},{extension:"step",name:"STEP"},{extension:"zip",name:"Assembly STEP"},{extension:"lbrn2",name:"LightBurn"}],duo=async({exportName:g,circuitJson:A,simpleRouteJson:I,projectName:e})=>{const t=oog(e);if(g==="Fabrication Files"){await Cuo({circuitJson:A,projectName:t});return}if(g==="KiCad Project"){await cuo({circuitJson:A,projectName:t});return}if(g==="Altium Project"){await Iuo({circuitJson:A,projectName:t});return}if(g==="KiCad Library"){await auo({circuitJson:A,projectName:t});return}if(g==="Circuit JSON"){kk(JSON.stringify(A,null,2),{fileName:`${t}.circuit.json`,mimeType:"application/json"});return}if(g==="Simple Route JSON"){if(!I)throw new Error("No Simple Route JSON available to export");kk(JSON.stringify(I,null,2),{fileName:`${t}.simple-route.json`,mimeType:"application/json"});return}if(g==="GLB (Binary GLTF)"){await nuo({circuitJson:A,projectName:t});return}if(g==="Pinout SVG"){huo({circuitJson:A,projectName:t});return}if(g==="STEP"){await luo({circuitJson:A,projectName:t});return}if(g==="Assembly STEP"){await Buo({circuitJson:A,projectName:t});return}if(g==="Component Box (3MF)"){await Euo({circuitJson:A,projectName:t});return}if(g==="LightBurn"){await LFI({circuitJson:A,projectName:t});return}throw new Error(`Unsupported export type: "${g}"`)},yuo=({packageName:g,onSelectReview:A})=>{const I=Uc(n=>n.fsMap),e=Uc(n=>n.circuitJson),[t,o]=z.useState([]),[B,C]=z.useState(!1),[Q,i]=z.useState(!1);z.useEffect(()=>{!g||!dlA()||(C(!0),pAA.get("ai_reviews/list",{searchParams:{package_name:g}}).json().then(n=>o(n.ai_reviews)).catch(n=>{console.error("Failed to load AI reviews",n),JC.error("Failed to load AI reviews")}).finally(()=>C(!1)))},[g]);const E=async()=>{if(!e){JC.error("Need Circuit JSON to Request AI Review");return}if(!dlA()){JC.error("Missing registry token");return}i(!0);try{const{ai_review:n}=await pAA.post("ai_reviews/create",{json:{package_name:g??"unknown",fs_map:Object.fromEntries(I),circuit_json:e}}).json();o(s=>[n,...s]),A(n),JC.success("AI review requested")}catch(n){console.error("Failed to create AI review",n),JC.error("Failed to request AI review")}finally{i(!1)}};return q.jsxs(q.Fragment,{children:[q.jsxs(V3,{children:[q.jsx(j3,{children:"AI Review"}),q.jsx(z5,{children:"Select an AI review or request a new one."})]}),q.jsx("div",{className:"rf-flex rf-gap-4 rf-mt-4",children:q.jsx("div",{className:"rf-w-48 rf-h-64 rf-overflow-y-auto rf-border rf-rounded rf-p-2 rf-flex-shrink-0",children:B?q.jsx("div",{className:"rf-text-sm",children:"Loading..."}):t.length>0?t.map(n=>q.jsx("div",{className:"rf-text-sm rf-p-2 rf-cursor-pointer rf-rounded hover:rf-bg-zinc-100",onClick:()=>A(n),children:new Date(n.created_at||"").toLocaleString()},n.ai_review_id)):q.jsx("div",{className:"rf-text-sm rf-text-muted-foreground",children:"No AI reviews found."})})}),q.jsx(LZ,{className:"rf-mt-4",children:q.jsx(Ei,{onClick:E,disabled:Q,children:Q?"Requesting...":"Review my Board"})})]})};function Jog(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var X5=Jog();function YFI(g){X5=g}var gtA={exec:()=>null};function Zs(g,A=""){let I=typeof g=="string"?g:g.source;const e={replace:(t,o)=>{let B=typeof o=="string"?o:o.source;return B=B.replace(Jm.caret,"$1"),I=I.replace(t,B),e},getRegex:()=>new RegExp(I,A)};return e}var Jm={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] /,listReplaceTask:/^\[[ xX]\] +/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:g=>new RegExp(`^( {0,3}${g})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:g=>new RegExp(`^ {0,${Math.min(3,g-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:g=>new RegExp(`^ {0,${Math.min(3,g-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:g=>new RegExp(`^ {0,${Math.min(3,g-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:g=>new RegExp(`^ {0,${Math.min(3,g-1)}}#`),htmlBeginRegex:g=>new RegExp(`^ {0,${Math.min(3,g-1)}}<(?:[a-z].*>|!--)`,"i")},wuo=/^(?:[ \t]*(?:\n|$))+/,uuo=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Guo=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,ItA=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,muo=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Pog=/(?:[*+-]|\d{1,9}[.)])/,_FI=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,bFI=Zs(_FI).replace(/bull/g,Pog).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),puo=Zs(_FI).replace(/bull/g,Pog).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Kog=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,kuo=/^[^\n]+/,Log=/(?!\s*\])(?:\\.|[^\[\]\\])+/,Muo=Zs(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Log).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Suo=Zs(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Pog).getRegex(),kGA="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",Yog=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,fuo=Zs("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",Yog).replace("tag",kGA).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),HFI=Zs(Kog).replace("hr",ItA).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",kGA).getRegex(),Ruo=Zs(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",HFI).getRegex(),_og={blockquote:Ruo,code:uuo,def:Muo,fences:Guo,heading:muo,hr:ItA,html:fuo,lheading:bFI,list:Suo,newline:wuo,paragraph:HFI,table:gtA,text:kuo},vFI=Zs("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",ItA).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",kGA).getRegex(),Nuo={..._og,lheading:puo,table:vFI,paragraph:Zs(Kog).replace("hr",ItA).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",vFI).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",kGA).getRegex()},xuo={..._og,html:Zs(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Yog).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:gtA,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:Zs(Kog).replace("hr",ItA).replace("heading",` *#{1,6} *[^
5671
5671
  ]`).replace("lheading",bFI).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Fuo=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Uuo=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,qFI=/^( {2,}|\\)\n(?!\s*$)/,Juo=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,MGA=/[\p{P}\p{S}]/u,bog=/[\s\p{P}\p{S}]/u,TFI=/[^\s\p{P}\p{S}]/u,Puo=Zs(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,bog).getRegex(),ZFI=/(?!~)[\p{P}\p{S}]/u,Kuo=/(?!~)[\s\p{P}\p{S}]/u,Luo=/(?:[^\s\p{P}\p{S}]|~)/u,Yuo=/\[[^[\]]*?\]\((?:\\.|[^\\\(\)]|\((?:\\.|[^\\\(\)])*\))*\)|`[^`]*?`|<[^<>]*?>/g,OFI=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,_uo=Zs(OFI,"u").replace(/punct/g,MGA).getRegex(),buo=Zs(OFI,"u").replace(/punct/g,ZFI).getRegex(),WFI="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Huo=Zs(WFI,"gu").replace(/notPunctSpace/g,TFI).replace(/punctSpace/g,bog).replace(/punct/g,MGA).getRegex(),vuo=Zs(WFI,"gu").replace(/notPunctSpace/g,Luo).replace(/punctSpace/g,Kuo).replace(/punct/g,ZFI).getRegex(),quo=Zs("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,TFI).replace(/punctSpace/g,bog).replace(/punct/g,MGA).getRegex(),Tuo=Zs(/\\(punct)/,"gu").replace(/punct/g,MGA).getRegex(),Zuo=Zs(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Ouo=Zs(Yog).replace("(?:-->|$)","-->").getRegex(),Wuo=Zs("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",Ouo).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),SGA=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,Vuo=Zs(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",SGA).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),VFI=Zs(/^!?\[(label)\]\[(ref)\]/).replace("label",SGA).replace("ref",Log).getRegex(),jFI=Zs(/^!?\[(ref)\](?:\[\])?/).replace("ref",Log).getRegex(),juo=Zs("reflink|nolink(?!\\()","g").replace("reflink",VFI).replace("nolink",jFI).getRegex(),Hog={_backpedal:gtA,anyPunctuation:Tuo,autolink:Zuo,blockSkip:Yuo,br:qFI,code:Uuo,del:gtA,emStrongLDelim:_uo,emStrongRDelimAst:Huo,emStrongRDelimUnd:quo,escape:Fuo,link:Vuo,nolink:jFI,punctuation:Puo,reflink:VFI,reflinkSearch:juo,tag:Wuo,text:Juo,url:gtA},zuo={...Hog,link:Zs(/^!?\[(label)\]\((.*?)\)/).replace("label",SGA).getRegex(),reflink:Zs(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",SGA).getRegex()},vog={...Hog,emStrongRDelimAst:vuo,emStrongLDelim:buo,url:Zs(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,"i").replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},Xuo={...vog,br:Zs(qFI).replace("{2,}","*").getRegex(),text:Zs(vog.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},fGA={normal:_og,gfm:Nuo,pedantic:xuo},etA={normal:Hog,gfm:vog,breaks:Xuo,pedantic:zuo},$uo={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},zFI=g=>$uo[g];function Wx(g,A){if(A){if(Jm.escapeTest.test(g))return g.replace(Jm.escapeReplace,zFI)}else if(Jm.escapeTestNoEncode.test(g))return g.replace(Jm.escapeReplaceNoEncode,zFI);return g}function XFI(g){try{g=encodeURI(g).replace(Jm.percentDecode,"%")}catch{return null}return g}function $FI(g,A){const I=g.replace(Jm.findPipe,(o,B,C)=>{let Q=!1,i=B;for(;--i>=0&&C[i]==="\\";)Q=!Q;return Q?"|":" |"}),e=I.split(Jm.splitPipe);let t=0;if(e[0].trim()||e.shift(),e.length>0&&!e.at(-1)?.trim()&&e.pop(),A)if(e.length>A)e.splice(A);else for(;e.length<A;)e.push("");for(;t<e.length;t++)e[t]=e[t].trim().replace(Jm.slashPipe,"|");return e}function ttA(g,A,I){const e=g.length;if(e===0)return"";let t=0;for(;t<e&&g.charAt(e-t-1)===A;)t++;return g.slice(0,e-t)}function AGo(g,A){if(g.indexOf(A[1])===-1)return-1;let I=0;for(let e=0;e<g.length;e++)if(g[e]==="\\")e++;else if(g[e]===A[0])I++;else if(g[e]===A[1]&&(I--,I<0))return e;return I>0?-2:-1}function AUI(g,A,I,e,t){const o=A.href,B=A.title||null,C=g[1].replace(t.other.outputLinkReplace,"$1");e.state.inLink=!0;const Q={type:g[0].charAt(0)==="!"?"image":"link",raw:I,href:o,title:B,text:C,tokens:e.inlineTokens(C)};return e.state.inLink=!1,Q}function gGo(g,A,I){const e=g.match(I.other.indentCodeCompensation);if(e===null)return A;const t=e[1];return A.split(`