UNPKG

@wayrisignals/kicad-webview

Version:

Interactive KiCad schematic, PCB and 3D viewer for the web, with Gerber, Excellon, linked views and offline HTML exports

11 lines • 50.3 kB
/*! KiCad WebView 1.2.1 | Copyright (c) 2026 wayri | SPDX-License-Identifier: MPL-2.0 | Source: https://github.com/wayri/kicad-webview/tree/v1.2.1 | Keep LICENSE and THIRD-PARTY-NOTICES.md; bundled dependencies retain their licenses. */
var Pe=Object.create;var Ce=Object.defineProperty;var Ue=Object.getOwnPropertyDescriptor;var je=Object.getOwnPropertyNames;var Ke=Object.getPrototypeOf,Xe=Object.prototype.hasOwnProperty;var Ae=(c=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(c,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):c)(function(c){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+c+'" is not supported')});var be=(c,t)=>()=>(t||c((t={exports:{}}).exports,t),t.exports);var $e=(c,t,r,g)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of je(t))!Xe.call(c,o)&&o!==r&&Ce(c,o,{get:()=>t[o],enumerable:!(g=Ue(t,o))||g.enumerable});return c};var Ne=(c,t,r)=>(r=c!=null?Pe(Ke(c)):{},$e(t||!c||!c.__esModule?Ce(r,"default",{value:c,enumerable:!0}):r,c));var Te=be((Ze,ue)=>{(c=>{"use strict";let o=d=>({quoted:String(d??"")}),i=d=>{let h=Number(d);if(!Number.isFinite(h)||Math.abs(h)>1e8)throw Error("Invalid legacy schematic coordinate.");return Math.round(h*.0254*1e8)/1e8},m=d=>[...d.matchAll(/"((?:\\.|[^"\\])*)"|([^\s]+)/g)].map(h=>h[1]!==void 0?h[1].replace(/\\(["\\])/g,"$1"):h[2]),X=(d,h,_=0)=>["at",i(d),i(h),_],Z=(d=50,h=!1)=>["effects",["font",["size",i(d),i(d)]],...h?["hide"]:[]];function J(d){if(typeof d!="string"||new TextEncoder().encode(d).length>8388608)throw Error("Legacy schematic/library exceeds its size limit.");let h=d.replace(/^\uFEFF/,"").split(/\r?\n/);if(h.length>15e4)throw Error("Legacy schematic/library exceeds its line limit.");return h}function S(d,h,_){let N,w=1,b=!1,M=!1,F=0,L=[];for(let W=h;W<_;W++){let Q=d[W].trim();if(!Q)continue;if(Q==="EndData"&&b&&!M){M=!0;continue}if(b&&!M){if(!/^[0-9a-f]{2}(?:\s+[0-9a-f]{2})*$/i.test(Q))throw Error("Invalid saved bitmap bytes.");let v=Q.match(/[0-9a-f]{2}/gi);if(F+=v.length,F>4*1024*1024)throw Error("Saved bitmap exceeds its 4 MiB limit.");for(let j=0;j<v.length;j+=8192)L.push(String.fromCharCode(...v.slice(j,j+8192).map(O=>parseInt(O,16))));continue}let[a,B,K]=m(Q);a==="Pos"&&B!==void 0&&K!==void 0&&(N=X(B,K)),a==="Scale"&&B!==void 0&&(w=Number(B)),a==="Data"&&!b&&(b=!0)}if(!N||!L.length||!M||!Number.isFinite(w)||w<=0)throw Error("Invalid saved bitmap placement or data.");return["image",N,["scale",w],["uuid",o("legacy-bitmap-"+h)],["data",o(btoa(L.join("")))]]}function z(d,h){let _=new Map,N=0;if(!Array.isArray(d))return _;if(d.length>16)throw Error("Too many legacy symbol libraries.");for(let w of d){let b=typeof w=="string"?w:w?.content;if(typeof b!="string")continue;if(N+=b.length,N>16*1024*1024)throw Error("Legacy symbol libraries exceed their combined limit.");let M=null,F=[],L=!1,W=new Map;for(let Q of J(b)){let a=m(Q),B=a[0];if(!B||B[0]==="#")continue;if(B==="DEF"){M=a,F=[],W=new Map;continue}if(!M)continue;if(B==="ALIAS"){F.push(...a.slice(1));continue}if(B==="DRAW"){L=!0;continue}if(B==="ENDDRAW"){L=!1;continue}if(B==="ENDDEF"){let O=M[1],H=["symbol",o(O),...M[9]==="P"?[["power"]]:[],...M[5]==="N"?[["pin_numbers","hide"]]:[],...M[6]==="N"?[["pin_names","hide"]]:[],...W.values()];for(let q of[O,...F])_.has(q)||_.set(q,H);M=null;continue}if(!L)continue;let K=(O,H,q)=>{let T=O+"_"+H;W.has(T)||W.set(T,["symbol",o(M[1]+"_"+T)]),W.get(T).push(q)},v=O=>["stroke",["width",Math.max(i(O||6),.01)]],j=O=>["fill",["type",O==="F"?"outline":O==="f"?"background":"none"]];if(B==="S")K(a[5],a[6],["rectangle",["start",i(a[1]),i(a[2])],["end",i(a[3]),i(a[4])],v(a[7]),j(a[8])]);else if(B==="C")K(a[4],a[5],["circle",["center",i(a[1]),i(a[2])],["radius",i(a[3])],v(a[6]),j(a[7])]);else if(B==="P"){let O=Number(a[1]);if(!Number.isInteger(O)||O<2||O>1e4||a.length<5+2*O)throw Error("Invalid legacy library polyline.");K(a[2],a[3],["polyline",["pts",...Array.from({length:O},(H,q)=>["xy",i(a[5+q*2]),i(a[6+q*2])])],v(a[4]),j(a[5+O*2])])}else if(B==="A"){let O=i(a[1]),H=i(a[2]),q=i(a[3]),T=Number(a[4])*Math.PI/1800,ee=Number(a[5])*Math.PI/1800-T;for(;ee<0;)ee+=Math.PI*2;let I=C=>[O+q*Math.cos(C),H+q*Math.sin(C)];K(a[6],a[7],["arc",["start",...I(T)],["mid",...I(T+ee/2)],["end",...I(T+ee)],v(a[8]),j(a[9])])}else if(B==="X"){let O={I:"input",O:"output",B:"bidirectional",T:"tri_state",P:"passive",U:"unspecified",W:"power_in",w:"power_out",C:"open_collector",E:"open_emitter",N:"no_connect"},H={R:0,U:90,L:180,D:270}[a[6]],q={"":"line",I:"inverted",C:"clock",CI:"inverted_clock",L:"input_low",CL:"clock_low",V:"output_low",F:"edge_clock_high",X:"non_logic"},T=a[12]||"",G=T.includes("N"),ee=q[T.replace(/N/g,"")];if(H===void 0||!ee){h("Unsupported legacy pin orientation/style omitted: "+a[1]);continue}K(a[9],a[10],["pin",O[a[11]]||"unspecified",ee,X(a[3],a[4],H),["length",i(a[5])],["name",o(a[1]),Z(a[8])],["number",o(a[2]),Z(a[7])],...G?["hide"]:[]])}else h(B==="T"?"Legacy library text is omitted; convert a copy in KiCad for complete typography.":"Unsupported legacy library graphic "+B+" omitted.")}}return _}function V(d,h={}){let _=J(d);if(!/^EESchema Schematic File Version [24]\b/.test(_[0]))throw Error("Only legacy Eeschema v2/v4 schematics are supported.");let N=new Set(["Restricted legacy schematic preview: only recognized saved records and supplied cache-library graphics are rendered. Convert a separate copy in KiCad for a complete modern preview."]),w=a=>{N.size<200&&N.add(a)},b=z(h.libraries,w),M=["kicad_sch",["version",Number(_[0].match(/\d+$/)[0])],["legacy_source",o(_[0])]],F=["lib_symbols"],L=[],W=(a,B,K,v,j=50,O=!1,H=0)=>["property",o(a),o(B),X(K,v,H),Z(j,O)];function Q(a,B){let K=[],v=a;for(;v<_.length&&_[v]!==B;v++)K.push(m(_[v]));if(v===_.length)throw Error("Incomplete legacy schematic "+B+" block.");return{records:K,end:v}}for(let a=1;a<_.length;a++){let B=m(_[a]),K=B[0];if(!(!K||K[0]==="#")){if(K==="$Descr"){M.push(["paper",o(B[1])]);continue}if(/^Comment[1-9]$/.test(K)){let v=M.find(j=>Array.isArray(j)&&j[0]==="title_block");v||(v=["title_block"],M.push(v)),v.push(["comment",Number(K.slice(7)),o(B[1])]);continue}if(["Title","Date","Rev","Comp"].includes(K)){let v=M.find(j=>Array.isArray(j)&&j[0]==="title_block");v||(v=["title_block"],M.push(v)),v.push([{Title:"title",Date:"date",Rev:"rev",Comp:"company"}[K],o(B[1])]);continue}if(K==="Wire"||K==="Entry"){let v=m(_[++a]||"");if(v.length!==4)throw Error("Invalid legacy wire record.");if(K==="Entry"){w("Legacy bus-entry geometry omitted.");continue}M.push([B[1]==="Bus"?"bus":"wire",["pts",["xy",i(v[0]),i(v[1])],["xy",i(v[2]),i(v[3])]]]);continue}if(K==="Connection"||K==="NoConn"){M.push([K==="Connection"?"junction":"no_connect",X(B[2],B[3])]);continue}if(K==="Text"){let v=_[++a]??"",j={Label:"label",GLabel:"global_label",HLabel:"hierarchical_label",Notes:"text"}[B[1]];if(!j){w("Unsupported legacy text record "+B[1]+" omitted.");continue}let O=[0,90,180,270],H=O[Number(B[4])];if(H===void 0){w("Unsupported legacy text orientation omitted.");continue}let q={Input:"input",Output:"output",BiDi:"bidirectional",TriState:"tri_state",UnSpc:"passive"}[B[6]];!["text","label"].includes(j)&&!q&&w("Unknown legacy label shape "+B[6]+"; passive outline used."),M.push([j,o(v.replace(/\\n/g,`
`)),X(B[2],B[3],H),Z(B[5]),...j==="text"||j==="label"?[]:[["shape",q||"passive"]]]);continue}if(K==="$Sheet"){let v=Q(a+1,"$EndSheet");a=v.end;let j=v.records,O=j.find(T=>T[0]==="S"),H=j.find(T=>T[0]==="U");if(!O)throw Error("Legacy sheet has no bounds.");let q=["sheet",X(O[1],O[2]),["size",i(O[3]),i(O[4])],["uuid",o(H?.[1]||"legacy-sheet-"+a)]];for(let T of j.filter(G=>/^F\d+$/.test(G[0])))if(T[0]==="F0"||T[0]==="F1")q.push(W(T[0]==="F0"?"Sheetname":"Sheetfile",T[1],O[1],O[2],T[2]));else{let G=T[3],ee={L:180,R:0,U:90,D:270}[G];q.push(["pin",o(T[1]),{I:"input",O:"output",B:"bidirectional",T:"tri_state",U:"passive"}[T[2]]||"passive",X(T[4],T[5],ee??0),Z(T[6])])}M.push(q);continue}if(K==="$Comp"){let v=Q(a+1,"$EndComp");a=v.end;let j=v.records,O=j.find(A=>A[0]==="L"),H=j.find(A=>A[0]==="U"),q=j.find(A=>A[0]==="P");if(!O||!q)throw Error("Incomplete legacy component.");let T=O[1],G=j.find(A=>A.length===4&&A.every(te=>/^-?\d+$/.test(te)))?.map(Number)||[1,0,0,-1],ee=null;for(let A of[0,90,180,270])for(let te of["","x","y"]){let e=A*Math.PI/180,s=Math.round(Math.cos(e)),n=Math.round(Math.sin(e)),l=te==="y"?-1:1,u=te==="x"?-1:1,p=[l*s,-l*n,-u*n,-u*s];G.every((f,x)=>f===p[x])&&(ee={angle:A,mirror:te})}if(!ee){w("Legacy component "+T+" has an unsupported orientation and is omitted.");continue}let I=["symbol",["lib_id",o(T)],X(q[1],q[2],ee.angle),["unit",Number(H?.[1]||1)],["convert",Number(H?.[2]||1)],["uuid",o(H?.[3]||"legacy-component-"+a)],...ee.mirror?[["mirror",ee.mirror]]:[]];for(let A of j.filter(te=>te[0]==="F")){let te=["Reference","Value","Footprint","Datasheet"][Number(A[1])]||A[11]||"Field"+A[1];I.push(W(te,A[2],A[4],A[5],A[6],A[7]!=="0000",(((A[3]==="V"?90:0)-ee.angle)%180+180)%180))}let C=b.get(T)||b.get(T.split(":").pop());C?L.includes(T)||(F.push(["symbol",o(T),...C.slice(2)]),L.push(T)):w("Missing saved legacy library definition for "+T+": symbol body and pins omitted; fields remain visible."),M.push(I);continue}if(K==="$Bitmap"){let v=_.indexOf("$EndBitmap",a+1);if(v<0){w("Legacy bitmap omitted: missing block terminator.");break}try{M.push(S(_,a+1,v))}catch(j){w("Legacy bitmap omitted: "+j.message)}a=v}}}if(!_.some(a=>a==="$EndSCHEMATC"))throw Error("Incomplete legacy schematic terminator.");return M.push(F,...[...N].map(a=>["legacy_diagnostic",o(a)])),M}function R(d){let h=J(d),_=[],N=!1;for(let w of h)if(w==="$Sheet")N=!0;else if(w==="$EndSheet")N=!1;else if(N){let b=m(w);b[0]==="F1"&&_.push(b[1])}return _}c.KiCadLegacy={parse:V,sheetFiles:R},typeof ue=="object"&&ue.exports&&(ue.exports=c.KiCadLegacy)})(globalThis)});var ye=be((Ie,ae)=>{(c=>{"use strict";let r=()=>268435456,Z=new Set(["symbol","sheet","wire","bus","bus_entry","label","global_label","hierarchical_label","junction","no_connect","text","text_box","polyline","rectangle","circle","arc","image","rule_area","netclass_flag","directive_label"]),J=new Set(["footprint","segment","arc","via","zone","gr_line","gr_rect","gr_circle","gr_arc","gr_poly","gr_curve","gr_text","gr_text_box","gr_bitmap","dimension","target"]),S=new Set(["uuid","tstamp","filled_polygon","fill_segments"]),z=/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?$/;function V(e){if(typeof e!="string")throw new TypeError("KiCad source must be a string.");if(!/[^\x00-\x7f]/.test(e))return e.length;let s=e.length;for(let n=0;n<e.length;n++){let l=e.charCodeAt(n);if(!(l<128)){if(l<2048){s++;continue}if(l>=55296&&l<=56319&&n+1<e.length){let u=e.charCodeAt(n+1);if(u>=56320&&u<=57343){s+=2,n++;continue}}s+=2}}return s}let R=e=>e===32||e>=9&&e<=13||e>127&&/\s/.test(String.fromCharCode(e));function d(e){if(!Array.isArray(e)||e.length!==4||e.some(f=>!f||!Number.isFinite(f.x)||!Number.isFinite(f.y)))throw Error("Bezier requires four finite control points.");let s=[{...e[0]}],n=[e],l=.005**2,u=(f,x,E)=>{let k=E.x-x.x,D=E.y-x.y,P=k*k+D*D,$=P?Math.max(0,Math.min(1,((f.x-x.x)*k+(f.y-x.y)*D)/P)):0;return(f.x-x.x-$*k)**2+(f.y-x.y-$*D)**2},p=(f,x)=>({x:f.x/2+x.x/2,y:f.y/2+x.y/2});for(;n.length;){let[f,x,E,k]=n.pop();if(Math.max(u(x,f,k),u(E,f,k))<=l){if(s.length>=2049)throw Error("Bezier exceeds the bounded tessellation budget.");s.push({...k})}else{let D=p(f,x),P=p(x,E),$=p(E,k),U=p(D,P),y=p(P,$),Y=p(U,y);if(n.length>32||[D,P,$,U,y,Y].some(ie=>!Number.isFinite(ie.x)||!Number.isFinite(ie.y)))throw Error("Bezier exceeds the bounded tessellation budget.");n.push([Y,y,$,k],[f,D,U,Y])}}return s}let h=new Set(["version","generator","generator_version","uuid","paper","title_block","property","sheet","symbol","footprint","module","sheet_instances","legacy_source","legacy_diagnostic"]),_=new Set([...h,"embedded_files"]),N=new Set(["property","uuid","path","instances"]);function w(e,s={}){if(typeof e!="string")throw new TypeError("KiCad source must be a string.");if(/^\s*PCBNEW-BOARD/.test(e))throw Error("Legacy .brd boards are detected but this drawing format is not yet rendered. Open and save a separate .kicad_pcb copy in KiCad.");if(/^\s*EESchema Schematic File Version [24]\b/.test(e)){let P=c.KiCadLegacy||(typeof ae=="object"&&ae.exports?Te():null);if(!P)throw Error("Legacy schematic adapter is unavailable; reload the extension.");return P.parse(e,s)}if(e.length>268435456||e.length>268435456/3&&V(e)>268435456)throw new Error("KiCad file exceeds browser parser size limits.");let n=[],l=[],u=/\(xy[ \t]+([-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?)[ \t]+([-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?)[ \t]*\)/y,p=0,f=0,x=0,E=()=>n.length===3&&n[0][0]==="kicad_pcb"&&n[1][0]==="zone"&&n[2][0]==="filled_polygon";function k(P){let $=P+4,U=0,y=new Float64Array(128);for(;$<e.length;){for(;R(e.charCodeAt($));)$++;if(e.charCodeAt($)===41)return U<6?null:(f+=1+U*2,D(["pts",U===y.length?y:y.slice(0,U)]),$+1);u.lastIndex=$;let Y=u.exec(e);if(!Y)return null;let ie=Number(Y[1]),ne=Number(Y[2]);if(!Number.isFinite(ie)||!Number.isFinite(ne))throw new Error("Invalid numeric KiCad value.");if(f+6+U*2>12e6)throw new Error("KiCad file has too many S-expression nodes.");if(U===y.length){let le=new Float64Array(y.length*2);le.set(y),y=le}y[U++]=ie,y[U++]=ne,$=u.lastIndex}return null}let D=P=>{if(++f>12e6)throw new Error("KiCad file has too many S-expression nodes.");x||(n.at(-1)||l).push(P)};for(;p<e.length;){let P=e[p];if(R(e.charCodeAt(p))){p++;continue}if((P==="<"||P===">")&&/^(?:<{7,}|>{7,})(?:\s|$)/.test(e.slice(p,p+120)))throw new Error("Unresolved Git merge conflict at line "+e.slice(0,p).split(`
`).length+". Resolve the conflict in a separate copy before viewing.");if(P===";"){for(;p<e.length&&e[p]!==`
`;)p++;continue}if(P==="("){if(n.length>=96)throw new Error("KiCad S-expression is too deep.");if(s.compactCopper&&!s.metadataOnly&&e.startsWith("(pts",p)&&R(e.charCodeAt(p+4))&&E()){let Y=k(p);if(Y!==null){p=Y;continue}}if(!s.metadataOnly&&n.length&&e.startsWith("(xy",p)){u.lastIndex=p;let Y=u.exec(e);if(Y){let ie=Number(Y[1]),ne=Number(Y[2]);if(!Number.isFinite(ie)||!Number.isFinite(ne))throw new Error("Invalid numeric KiCad value.");f+=3,D(["xy",ie,ne]),p=u.lastIndex;continue}}if(s.metadataOnly&&!x){let Y=null;if(n.length===1?Y=s.includeEmbeddedFonts?_:h:n.length===2&&["symbol","footprint","module"].includes(n.at(-1)?.[0])?Y=N:n.at(-1)?.[0]==="property"&&(Y=new Set),Y){let ie=p+1;for(;ie<e.length&&R(e.charCodeAt(ie));)ie++;let ne=ie;for(;ne<e.length&&!R(e.charCodeAt(ne))&&!["(",")",";"].includes(e[ne]);)ne++;Y.has(e.slice(ie,ne))||(x=n.length+1)}}let y=[];D(y),n.push(y),p++;continue}if(P===")"){if(!n.length)throw new Error("Unexpected closing parenthesis in KiCad file.");let y=n.pop();if(!x&&y.length>0&&y.length<=4){let Y=y.slice(),ie=n.at(-1)||l;ie[ie.length-1]=Y}x&&n.length<x&&(x=0),p++;continue}if(!n.length)throw new Error("Expected a KiCad S-expression.");if(P==='"'){let y=null,Y=++p,ie=!1,ne="";for(;p<e.length;){let le=e[p++];if(le==='"'){if(ie=!0,!x){let ce=e.slice(Y,p-1);y?(y.push(ce),ne=y.join("")):ne=ce}break}if(le==="\\"){if(p>=e.length)throw new Error("Unterminated KiCad escape sequence.");let ce=e[p++];if(!x){y??=[],y.push(e.slice(Y,p-2));let Se={n:`
`,r:"\r",t:"	",'"':'"',"\\":"\\"}[ce];y.push(Se===void 0?"\\"+ce:Se)}Y=p}}if(!ie)throw new Error("Unterminated quoted KiCad string.");D(x?null:{quoted:ne});continue}let $=p;for(;p<e.length;){let y=e.charCodeAt(p);if(y===40||y===41||y===59||y===34||R(y))break;p++}if($===p)throw new Error("Unexpected KiCad source character.");if(x){D(null);continue}let U=e.slice($,p);if(z.test(U)){let y=Number(U);if(!Number.isFinite(y))throw new Error("Invalid numeric KiCad value.");D(y)}else D(U==="xy"?"xy":U)}if(n.length||l.length!==1||!Array.isArray(l[0]))throw new Error("Incomplete KiCad S-expression.");return l[0]}let b=e=>e&&typeof e=="object"&&!Array.isArray(e)?e.quoted:e,M=e=>Array.isArray(e)?String(b(e[0])):"",F=(e,s)=>e.filter(n=>Array.isArray(n)&&M(n)===s),L=(e,s)=>e.find(n=>Array.isArray(n)&&M(n)===s),W=(e,s)=>b(L(e,s)?.[1]);function Q(e){let s=L(e,"polyline"),n=s&&L(s,"pts");if(!n||n.length<4||n.length>4097)return null;let l=[];for(let f of n.slice(1)){let x=b(f?.[1]),E=b(f?.[2]);if(!Array.isArray(f)||M(f)!=="xy"||!Number.isFinite(x)||!Number.isFinite(E))return null;let k=l.at(-1);(k?.x!==x||k.y!==E)&&l.push({x,y:E})}if(l[0].x===l.at(-1).x&&l[0].y===l.at(-1).y&&l.pop(),l.length<3)return null;let u=l[0],p=0;for(let f=1;f<l.length-1;f++){let x=l[f],E=l[f+1];p+=(x.x-u.x)*(E.y-u.y)-(x.y-u.y)*(E.x-u.x)}return Number.isFinite(p)&&p!==0?l:null}function a(e){for(let s of["at","start","center","end","xy"]){let n=L(e,s);if(n&&Number.isFinite(b(n[1]))&&Number.isFinite(b(n[2])))return{x:b(n[1]),y:b(n[2])}}for(let s of["pts","polygon"]){let n=L(e,s),l=n&&L(s==="polygon"&&L(n,"pts")||n,"xy");if(l&&Number.isFinite(b(l[1]))&&Number.isFinite(b(l[2])))return{x:b(l[1]),y:b(l[2])}}return null}function B(e,s){let n=[];for(let f of F(e,"property"))f.length>=3&&n.push([String(b(f[1])),String(b(f[2]))]);if(s==="footprint")for(let[f,x]of[["reference","Reference"],["value","Value"]]){let E=F(e,"fp_text").find(k=>b(k[1])===f);E&&E.length>=3&&!n.some(([k])=>k===x)&&n.push([x,String(b(E[2]))])}for(let f of["lib_id","layer","width","drill","size","unit"]){let x=L(e,f);x&&n.push([f,x.slice(1).map(b).join(", ")])}let l=L(e,"layers");l&&n.push(["Layers",l.slice(1).map(b).join(", ")]);let u=L(e,"net");u&&n.push(["Net",String(b(u[2]??u[1]))]);let p=L(e,"at");return p&&Number.isFinite(b(p[3]))&&n.push(["Angle",String(b(p[3]))]),["label","global_label","hierarchical_label","text","gr_text","gr_text_box"].includes(s)&&n.push(["Text",String(b(e[1]??""))]),s==="pad"&&(n.push(["Number",String(b(e[1]??""))]),n.push(["Type",String(b(e[2]??""))]),n.push(["Shape",String(b(e[3]??""))])),Object.fromEntries(n)}function K(e){return Array.isArray(e)?e.filter(s=>!Array.isArray(s)||!S.has(M(s))).map(K):e&&typeof e=="object"?["quoted",e.quoted]:e}function v(e){let s=2166136261;for(let n=0;n<e.length;n++)s=Math.imul(s^e.charCodeAt(n),16777619);return(s>>>0).toString(16).padStart(8,"0")}function j(e,s,n,l){let u=W(e,"uuid")??W(e,"tstamp")??(s==="rule_area"&&L(e,"polyline")?W(L(e,"polyline"),"uuid"):void 0);if(u!=null&&String(u))return{key:`uuid:${u}`,uuid:String(u)};let p=s==="pad"?n.Number:s==="sheet"?n.Sheetfile:s==="symbol"||s==="footprint"?n.Reference:void 0;return{key:p?`fallback:${String(p)}`:`fallback:${v(typeof l=="function"?l():l)}`,uuid:null}}function O(e,s,n,l){return s==="pad"?`${l||"Footprint"} pad ${n.Number||""}`.trim():n.Reference||n.Sheetname||n["Sheet name"]||n.Text||(s==="footprint"?String(b(e[1]??"Footprint")):s==="symbol"?n.lib_id||"symbol":s==="netclass_flag"||s==="directive_label"?"Directive label":s==="rule_area"?"Rule area":s.replace(/_/g," "))}function H(e,s){if(!e||!s?.position)return null;let n=Number(b(L(s.form,"at")?.[3]??0)),l=(Number.isFinite(n)?n:0)*Math.PI/180,u=Math.cos(l),p=Math.sin(l),f=s.position.x+e.x*u+e.y*p,x=s.position.y-e.x*p+e.y*u,E=k=>Math.round(k*1e6)/1e6;return{x:E(f),y:E(x)}}function q(e,s,n=null,l=null,u=!1){let p=M(s),f=B(s,p),x=a(p==="rule_area"&&L(s,"polyline")||s),E=p==="pad"?H(x,n):x,k,D=()=>k??=JSON.stringify([K(s),E,typeof l=="function"?l():l]);u||(f["Source fingerprint"]=v(D()));let P=j(s,p,f,D),U=`${n?`${n.scope}/`:`${e}/`}${p}:${P.key}`,y=O(s,p,f,n?.label);return{key:U,scope:U,signature:u?null:D(),metadata:{uuid:P.uuid,position:E,properties:f},path:e,kind:p,label:y,form:s}}function T(e,s,n=null,{forConnectivity:l=!1,parseOnly:u=!1,compactCopper:p=!1}={},f){let x=f||w(s,{compactCopper:p});n?.(x);let E=M(x);if(E!=="kicad_sch"&&E!=="kicad_pcb")throw new Error("Expected a KiCad schematic or board.");if(u)return[];let k=E==="kicad_sch"?Z:J,D=new Map;if(E==="kicad_sch"){let $=L(x,"lib_symbols");if($)for(let U of F($,"symbol")){let y=b(U[1]);typeof y=="string"&&D.set(y,l?U:JSON.stringify(K(U)))}}let P=[];for(let $ of x){if(!Array.isArray($)||!k.has(M($)))continue;let U=M($)==="symbol"?D.get(String(W($,"lib_name")??W($,"lib_id"))):null,y=q(e,$,null,l&&U?()=>JSON.stringify(K(U)):U,l);if(P.push(y),E==="kicad_pcb"&&y.kind==="footprint")for(let Y of F($,"pad"))P.push(q(e,Y,{form:$,position:y.metadata.position,scope:y.scope,label:y.label},null,l))}return P}function G(e,s={}){return w(e,{...s,metadataOnly:!0}).filter((l,u)=>u===0||Array.isArray(l)&&(s.includeEmbeddedFonts?_:h).has(l[0])).map(l=>Array.isArray(l)&&["symbol","footprint","module"].includes(l[0])?l.filter((u,p)=>p===0||Array.isArray(u)&&N.has(u[0])):l)}let ee=new WeakMap;function I(e,{forConnectivity:s=!1,compactCopper:n=!1}={}){let l=new Map,u=A(e,(f,x)=>l.set(f.path,x),null,{forConnectivity:s,parseOnly:s,compactCopper:s&&n}),p=Object.freeze({});return ee.set(p,{files:e.map(f=>({path:f.path,content:f.content})),parsed:l,records:s?null:u,forConnectivity:s}),p}function C(e,s,n){let l=ee.get(e);if(!l||!l.parsed.has(s))throw new Error("Prepared KiCad file is unavailable.");if(n!==void 0&&!l.files.some(u=>u.path===s&&u.content===n))throw new Error("Prepared KiCad file differs from source.");return l.parsed.get(s)}function A(e,s=null,n=null,{forConnectivity:l=!1,parseOnly:u=!1,compactCopper:p=!1}={}){if(n){let k=ee.get(n);if(!k||!Array.isArray(e)||e.length!==k.files.length||e.some((D,P)=>D?.path!==k.files[P].path||D?.content!==k.files[P].content))throw new Error("Prepared KiCad project differs from source.");if(k.forConnectivity!==l||!k.records){let D=[];for(let P of e)for(let $ of T(P.path,P.content,U=>s?.(P,U),{forConnectivity:l},k.parsed.get(P.path)))D.push($);return D}for(let D of e)s?.(D,k.parsed.get(D.path));return k.records.map(D=>({...D}))}if(!Array.isArray(e)||e.length>128)throw new Error("Too many KiCad files to compare.");let f=new Set,x=[],E=0;for(let k of e){if(!k||typeof k.path!="string"||typeof k.content!="string"||!/\.kicad_(?:sch|pcb)$/i.test(k.path)||f.has(k.path))throw new Error("Invalid or duplicate KiCad file entry.");f.add(k.path);let D=V(k.content);if(E+=D,D>268435456||E>536870912)throw new Error("KiCad project exceeds browser comparison size limits.");for(let P of T(k.path,k.content,$=>s?.(k,$),{forConnectivity:l,parseOnly:u,compactCopper:p}))x.push(P)}return x}function te(e,s){let n=A(e),l=A(s),u=new Map;for(let E of n)u.has(E.key)||u.set(E.key,{before:[],after:[]}),u.get(E.key).before.push(E);for(let E of l)u.has(E.key)||u.set(E.key,{before:[],after:[]}),u.get(E.key).after.push(E);let p=[],f={added:0,removed:0,modified:0},x=(E,k,D,P,$)=>{p.push({id:$,path:E.path,kind:E.kind,label:E.label,status:k,before:D?.metadata??null,after:P?.metadata??null}),f[k]++};for(let[E,k]of u){let D=[...k.before],P=[...k.after];for(let U=D.length-1;U>=0;U--){let y=P.findIndex(Y=>Y.signature===D[U].signature);y>=0&&(D.splice(U,1),P.splice(y,1))}D.sort((U,y)=>U.signature.localeCompare(y.signature)),P.sort((U,y)=>U.signature.localeCompare(y.signature));let $=Math.max(D.length,P.length);for(let U=0;U<$;U++){let y=D[U]||null,Y=P[U]||null;x(Y||y,y&&Y?"modified":y?"removed":"added",y,Y,$>1?`${E}#${U+1}`:E)}}return p.sort((E,k)=>E.path.localeCompare(k.path)||E.id.localeCompare(k.id)||E.status.localeCompare(k.status)),{changes:p,counts:f}}c.KiCadDesignDiff={compareProjects:te,projectObjects:A,parse:w,parseMetadata:G,sourceByteLimit:r,sourceByteLength:V,prepareProject:I,preparedFile:C,cubicBezierPoints:d,MAX_FILES:128,MAX_FILE_BYTES:268435456,MAX_PROJECT_BYTES:536870912,MAX_RENDER_PRIMITIVES:15e5,ruleAreaPoints:Q},typeof ae=="object"&&ae.exports&&(ae.exports=c.KiCadDesignDiff)})(typeof globalThis=="object"?globalThis:Ie)});var Le=be((Fe,he)=>{(c=>{"use strict";let t=c.KiCadDesignDiff||(typeof Ae=="function"?ye():null),r=d=>d&&typeof d=="object"&&!Array.isArray(d)?d.quoted:d,g=d=>Array.isArray(d)?String(r(d[0])):"",o=(d,h)=>Array.isArray(d)?d.filter(_=>g(_)===h):[],i=(d,h)=>o(d,h)[0],m=(d,h)=>r(i(d,h)?.[1]);function X(d,h){if(!Array.isArray(d)||d.length>1e5)throw new Error("BOM object limit exceeded.");let _=d.filter(F=>(!h||F.path===h)&&["symbol","footprint"].includes(F.kind)),N=new Map;for(let F of _){let L=JSON.stringify([F.path,F.kind==="footprint"?F.uuid||F.id:F.reference||F.uuid||F.id]);N.has(L)||N.set(L,F)}let w=[...N.values()],b=w.filter(F=>!F.excludeFromBom),M=new Map;for(let F of b){let L=F.properties||{},W=JSON.stringify([L.Value||"",L.Footprint||L["Library ID"]||"",F.populated!==!1]);M.has(W)||M.set(W,{value:L.Value||"",footprint:L.Footprint||L["Library ID"]||"",populated:F.populated!==!1,parts:[]}),M.get(W).parts.push(F)}return{parts:w,groups:[...M.values()].sort((F,L)=>F.value.localeCompare(L.value)),total:w.length,fitted:w.filter(F=>F.populated!==!1).length,dnp:w.filter(F=>F.populated===!1).length,excluded:w.length-b.length,eligible:b.length}}function Z(d){let h=N=>{let w=String(N??"");return/^[\s]*[=+@-]/.test(w)&&(w="'"+w),'"'+w.replace(/"/g,'""')+'"'},_=[["Reference","Value","Footprint","Population","File"]];for(let N of d.groups)for(let w of N.parts)_.push([w.reference||"",N.value,N.footprint,N.populated?"Fitted":"DNP",w.path]);return _.map(N=>N.map(h).join(",")).join(`\r
`)+`\r
`}function J(d){if(!Array.isArray(d)||d.length<3)return null;let h=0;for(let _=0;_<d.length;_++){let N=d[_],w=d[(_+1)%d.length];if(![N.x,N.y,w.x,w.y].every(Number.isFinite)||[N.x,N.y,w.x,w.y].some(b=>Math.abs(b)>1e5))return null;h+=N.x*w.y-w.x*N.y}return Math.abs(h)/2}let S=(d,h)=>{let _=i(d,h);return{x:Number(r(_?.[1])),y:Number(r(_?.[2]))}},z=d=>d&&[d.x,d.y].every(h=>Number.isFinite(h)&&Math.abs(h)<=1e5);function V(d,h,_){if(![d,h,_].every(z))return null;let N=h.x-d.x,w=h.y-d.y,b=_.x-d.x,M=_.y-d.y,F=2*(N*M-w*b);if(Math.abs(F)<=1e-12*Math.max(1,Math.hypot(N,w)*Math.hypot(b,M)))return null;let L=N*N+w*w,W=b*b+M*M,Q=(L*M-W*w)/F,a=(N*W-b*L)/F,B=Math.hypot(Q,a),K=2*Math.PI,v=G=>(G%K+K)%K,j=Math.atan2(-a,-Q),O=Math.atan2(w-a,N-Q),H=Math.atan2(M-a,b-Q),q=v(H-j),T=B*(v(O-j)<=q?q:K-q);return Number.isFinite(T)?T:null}function R(d){if(typeof d!="string"||new TextEncoder().encode(d).length>8*1024*1024)throw new Error("Board analytics source exceeds 8 MiB.");let h=t.parse(d);if(g(h)!=="kicad_pcb")throw new Error("Board analytics requires a saved PCB.");let _=I=>o(h,I).length,N=o(h,"footprint"),w=0,b=0,M=0,F=0,L=0;for(let I of N)for(let C of o(I,"pad")){w++,i(C,"drill")&&b++;let A=String(r(C[2]));A==="smd"&&M++,(A==="thru_hole"||A==="np_thru_hole")&&F++}let W=0,Q=[],a=new Map,B=[],K=new Map(o(h,"net").map(I=>[String(r(I[1])),String(r(I[2])||"")])),v=new Map,j=new Map,O=0,H=0;for(let I of["segment","arc"])for(let C of o(h,I)){let A=S(C,"start"),te=S(C,"end"),e=I==="arc"?V(A,S(C,"mid"),te):z(A)&&z(te)?Math.hypot(te.x-A.x,te.y-A.y):null;if(e===null){H++;continue}I==="arc"?O+=e:L+=e;let s=i(C,"net"),n=m(C,"net"),l=Number(m(h,"version"))>=20260206&&typeof n=="string"&&s?.length===2,u=l?`name:${n}`:String(n??"0"),p=String(m(C,"layer")||"Unspecified");v.has(u)||v.set(u,{code:u,name:l?n||"Unassigned":K.get(u)||(u==="0"?"Unassigned":`Net ${u}`),lengthMm:0,segments:0,arcs:0});let f=v.get(u);f.lengthMm+=e,f[I==="arc"?"arcs":"segments"]++,j.set(p,(j.get(p)||0)+e)}H&&Q.push(`${H} malformed or unsupported tracks omitted from lengths.`);let q=[],T=!1;for(let I of h.filter(C=>g(C).startsWith("gr_")&&m(C,"layer")==="Edge.Cuts")){let C=[];["gr_line","gr_rect"].includes(g(I))?C=[S(I,"start"),S(I,"end")]:g(I)==="gr_poly"?C=o(i(I,"pts"),"xy").map(A=>({x:Number(r(A[1])),y:Number(r(A[2]))})):T=!0,!C.length||!C.every(z)?T=!0:q.push(...C)}let G=null;if(q.length&&!T){G={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};for(let I of q)G.minX=Math.min(G.minX,I.x),G.maxX=Math.max(G.maxX,I.x),G.minY=Math.min(G.minY,I.y),G.maxY=Math.max(G.maxY,I.y)}let ee=[];for(let I of N){let C=S(I,"at"),A=[];z(C)?(C.x===0&&C.y===0&&A.push("Footprint origin at (0, 0)"),G&&(C.x<G.minX||C.x>G.maxX||C.y<G.minY||C.y>G.maxY)&&A.push("Footprint origin outside Edge.Cuts envelope")):A.push("No valid saved position"),A.length&&ee.push({uuid:m(I,"uuid")||m(I,"tstamp")||null,reference:String(r(o(I,"property").find(te=>r(te[1])==="Reference")?.[2])||r(o(I,"fp_text").find(te=>r(te[1])==="reference")?.[2])||""),position:z(C)?C:null,reasons:A})}T&&Q.push("Edge.Cuts envelope unavailable: curved or unsupported edge geometry.");for(let[I,C]of o(h,"zone").entries()){let A={index:I,uuid:m(C,"uuid")||m(C,"tstamp")||null,name:String(m(C,"name")||m(C,"net_name")||`Zone ${I+1}`),layers:[],outlineAreaMm2:0,fillAreaMm2:0,valid:!0};for(let[te,e]of[["polygon","outlineAreaMm2"],["filled_polygon","fillAreaMm2"]])for(let s of o(C,te)){let n=o(i(s,"pts"),"xy").map(u=>({x:Number(r(u[1])),y:Number(r(u[2]))}));if(W+=n.length,W>2e5)throw new Error("Zone analytics exceeds 200,000 polygon points.");let l=J(n);if(l===null){A.valid=!1,Q.push(`Zone ${I+1}: invalid polygon omitted.`);continue}if(A[e]+=l,te==="filled_polygon"){let u=String(m(s,"layer")||m(C,"layer")||"Unspecified");A.layers.includes(u)||A.layers.push(u),a.set(u,(a.get(u)||0)+l)}}o(C,"filled_polygon").length||Q.push(`Zone ${I+1}: no saved filled polygons.`),B.push(A)}return{footprints:N.length,pads:w,drilledPads:b,smdPads:M,throughHolePads:F,segments:_("segment"),arcs:_("arc"),vias:_("via"),zones:B,straightTrackLengthMm:L,arcTrackLengthMm:O,totalTrackLengthMm:L+O,omittedTracks:H,netTracks:[...v.values()].sort((I,C)=>C.lengthMm-I.lengthMm),layerTracks:[...j].map(([I,C])=>({layer:I,lengthMm:C})),edgeBounds:G,placementCandidates:ee,boardThicknessMm:Number(m(i(h,"general"),"thickness"))||null,layerFill:[...a].map(([I,C])=>({layer:I,areaMm2:C})),warnings:Q,limits:"Areas are sums of absolute shoelace areas of saved straight-edge polygons; overlaps are counted repeatedly and hole contours are not subtracted. They are not copper union, material mass, clearance checks or a fresh zone fill. Track lengths are saved segment and circular-arc centreline sums, not point-to-point electrical lengths; vias add no length. Placement candidates require review, not confirmed unplaced components; coordinates and envelope do not prove placement intent or containment. BOM counts saved file/reference identities; reused sheet instances are not expanded."}}c.KiCadBomAnalytics={bom:X,board:R,polygonArea:J,arcLength:V,csv:Z},typeof he=="object"&&he.exports&&(he.exports=c.KiCadBomAnalytics)})(typeof globalThis<"u"?globalThis:Fe)});var Qe=Ne(ye(),1),we=globalThis.KiCadDesignDiff,Be=we.MAX_FILE_BYTES,et=we.MAX_PROJECT_BYTES,tt=we.MAX_RENDER_PRIMITIVES;var st=Ne(Le(),1),Ve=globalThis.KiCadDesignDiff,xe=globalThis.KiCadBomAnalytics,ze=Be,qe=1e5,Ye=64,Je=32*1024*1024,Re=new WeakSet,re=c=>c&&typeof c=="object"&&!Array.isArray(c)?c.quoted:c,de=c=>Array.isArray(c)?String(re(c[0])):"",oe=(c,t)=>Array.isArray(c)?c.filter(r=>de(r)===t):[],me=(c,t)=>oe(c,t)[0],fe=(c,t)=>re(me(c,t)?.[1]);function Oe(c,t){if(typeof c!="string")throw new TypeError("Source must be KiCad text.");if(new TextEncoder().encode(c).length>ze)throw new Error("Source exceeds 256 MiB.");if(typeof t!="string"||!t||t.length>1024||/[\x00-\x1f\x7f]/.test(t))throw new TypeError("A source path of at most 1024 characters without control characters is required.");let r=Ve.parse(c),g=de(r);if(!["kicad_pcb","kicad_sch"].includes(g))throw new Error("Expected a saved KiCad PCB or schematic.");let o=0;for(let i of r)if(Array.isArray(i)&&(o++,de(i)==="footprint"&&(o+=oe(i,"pad").length),de(i)==="zone"&&(o+=oe(i,"polygon").length+oe(i,"filled_polygon").length),o>qe))throw new Error("Source exceeds the 100,000-object analytics limit.");return{ast:r,root:g}}function ve(c){if(c&&typeof c=="object"&&!Object.isFrozen(c)){for(let t of Object.values(c))ve(t);Object.freeze(c)}return c}function De(c,t){let r=me(c,t);if(!r)return null;if(r.length===1)return!0;let g=String(re(r[1])).toLowerCase();return["yes","true","1"].includes(g)?!0:["no","false","0"].includes(g)?!1:null}function He(c,t,r,g){let o=de(c),i={},m=oe(c,"property");for(let V of m){if(V.length<3)continue;let R=String(re(V[1]));["Reference","Value","Footprint"].includes(R)&&(i[R]=String(re(V[2])))}for(let V of m){if(V.length<3)continue;let R=String(re(V[1]));if(!Object.hasOwn(i,R)){if(Object.keys(i).length>=Ye){g.add("Part properties limited to 64 saved fields.");continue}Object.defineProperty(i,R,{value:String(re(V[2])),enumerable:!0,writable:!0,configurable:!0})}}if(o==="footprint")for(let[V,R]of[["reference","Reference"],["value","Value"]]){let d=oe(c,"fp_text").find(h=>re(h[1])===V);!Object.hasOwn(i,R)&&d?.length>=3&&(i[R]=String(re(d[2])))}let X=o==="symbol"?fe(c,"lib_id"):re(c[1]);X!==void 0&&!Object.hasOwn(i,"Library ID")&&(i["Library ID"]=String(X));let Z=me(c,"attr")?.slice(1).map(re).map(String)||[],J=V=>["yes","true","1","dnp","dni","do not populate","do not install"].includes(String(V??"").trim().toLowerCase()),S=m.some(V=>["dnp","do not populate","dni","do not install"].includes(String(re(V[1])).trim().toLowerCase())&&J(re(V[2]))),z=fe(c,"uuid")??fe(c,"tstamp")??null;return{id:z?`${t}#${String(z)}`:`${t}#object-${r}`,uuid:z===null?null:String(z),kind:o,path:t,reference:i.Reference||null,properties:i,populated:!(De(c,"dnp")===!0||Z.includes("dnp")||S),excludeFromBom:De(c,"in_bom")===!1||Z.includes("exclude_from_bom")}}function ke(c,{path:t="board.kicad_pcb"}={}){let{ast:r,root:g}=Oe(c,t);if(g!=="kicad_pcb")throw new Error("Board analytics requires a saved PCB.");let o=xe.board(c),i=fe(me(r,"general"),"thickness");return i!==void 0&&(!Number.isFinite(Number(i))||Number(i)<=0)&&(o.boardThicknessMm=null,o.warnings.push("Invalid or nonpositive saved board thickness omitted.")),ve({path:t,sourceKind:"pcb",...o})}function Ee(c,{path:t="drawing.kicad_pcb"}={}){let{ast:r,root:g}=Oe(c,t),o=new Set,m=oe(r,g==="kicad_pcb"?"footprint":"symbol").map((J,S)=>He(J,t,S+1,o));if(g==="kicad_pcb"){let J=new Map;for(let S of m)S.uuid&&J.set(S.uuid,(J.get(S.uuid)||0)+1);m.forEach((S,z)=>{if(S.uuid&&J.get(S.uuid)>1){for(S.savedUUID=S.uuid,S.uuid=null,S.id=t+"#object-"+(z+1);J.has(S.id);)S.id+="#";o.add("Duplicate saved PCB footprint UUIDs are ambiguous; affected parts cannot be selected by UUID.")}})}let X=xe.bom(m),Z=ve({path:t,sourceKind:g==="kicad_pcb"?"pcb":"schematic",...X,warnings:[...o],limits:"BOM counts saved file/reference identities; reused sheet instances are not expanded. Source is limited to 256 MiB and 100,000 objects; part properties are limited to 64 saved fields. CSV export is limited to 32 MiB UTF-8."});return Re.add(Z),Z}function _e(c){if(!c||!Re.has(c))throw new TypeError("Expected a report returned by buildBOM.");let t=new TextEncoder,r=0,g=o=>{r+=o.length*2+o.length-1+2;for(let i of o){let m=String(i??"");r+=t.encode(m).length,/^[\s]*[=+@-]/.test(m)&&r++;for(let X=0;X<m.length;X++)m[X]==='"'&&r++;if(r>Je)throw new Error("BOM CSV exceeds 32 MiB UTF-8.")}};g(["Reference","Value","Footprint","Population","File"]);for(let o of c.groups)for(let i of o.parts)g([i.reference||"",o.value,o.footprint,o.populated?"Fitted":"DNP",i.path]);return xe.csv(c)}var ge=new WeakMap;var se=(c,t=180)=>{let r=String(c??"");return r.length>t?r.slice(0,t)+"\u2026":r},pe=(c,t=3)=>Number.isFinite(c)?Number(c.toFixed(t)).toString():"Not available",We=".kw-bom{--bg:#14212c;--panel:#1b2d3b;--ink:#edf4f8;--muted:#b8c8d5;--line:#3d5668;--accent:#69dce3;background:var(--bg);color:var(--ink);border:1px solid var(--line);border-radius:10px;padding:12px;font:13px/1.5 system-ui;min-width:0;color-scheme:dark}.kw-bom[data-theme=light]{--bg:#fff;--panel:#eef4f8;--ink:#152534;--muted:#40566a;--line:#aebdca;--accent:#00727d;color-scheme:light}.kw-bom *{box-sizing:border-box}.kw-bom button,.kw-bom input{font:inherit;color:var(--ink);background:var(--panel);border:1px solid var(--line);border-radius:5px;padding:8px;min-height:40px;min-width:0;max-width:100%}.kw-bom button{cursor:pointer}.kw-bom button:disabled{opacity:.5;cursor:default}.kw-bom button[aria-pressed=true],.kw-bom .kw-bom-selected{border-color:var(--accent);box-shadow:inset 3px 0 var(--accent)}.kw-bom :focus-visible{outline:2px solid var(--accent);outline-offset:2px}.kw-bom-tools{display:flex;flex-wrap:wrap;gap:8px;align-items:center}.kw-bom-tools input[type=search]{flex:1 1 180px}.kw-bom label{display:flex;align-items:center;gap:6px}.kw-bom label input{min-height:0}.kw-bom p{overflow-wrap:anywhere;margin:8px 0}.kw-bom-small{color:var(--muted);font-size:12px}.kw-bom-list{display:grid;gap:7px;margin:12px 0;max-height:520px;overflow:auto;overscroll-behavior:contain}.kw-bom-row{padding:10px;border:1px solid var(--line);border-radius:6px;overflow-wrap:anywhere;background:var(--panel)}.kw-bom-row.kw-bom-hover{border-color:#d9902c;box-shadow:inset 3px 0 #d9902c}.kw-bom-row button{width:100%;text-align:left}.kw-bom-members{display:flex;flex-wrap:wrap;gap:6px;margin-top:8px}.kw-bom-members button{width:auto;max-width:100%}.kw-bom-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(130px,1fr));gap:8px}.kw-bom-grid>div{padding:10px;background:var(--panel);border:1px solid var(--line);border-radius:6px}.kw-bom [hidden]{display:none!important}.kw-bom details{border-top:1px solid var(--line);padding-top:8px;margin-top:12px}.kw-bom summary{cursor:pointer;min-height:40px}.kw-bom pre{white-space:pre-wrap;overflow-wrap:anywhere;max-height:250px;overflow:auto;background:var(--panel);padding:10px}@media(pointer:coarse){.kw-bom button,.kw-bom input,.kw-bom summary{min-height:44px}}",Me=class extends EventTarget{constructor(t,{viewer:r=null,theme:g="dark"}={}){if(super(),!["light","dark"].includes(g))throw new TypeError("Choose light or dark theme.");let o=typeof t=="string"?globalThis.document?.querySelector(t):t;if(!o?.ownerDocument)throw new TypeError("Choose a BOM mount element.");if(ge.has(o))throw new Error("This container already has a viewer.");this.host=o,this.doc=o.ownerDocument,this.theme=g,this.mode="parts",this.query="",this.grouped=!0,this.page=0,this.report=null,this.stats=null,this.source=null,this.path=null,this.selectedUUID=null,this.disposed=!1,this.make=(z,V)=>{let R=this.doc.createElement(z);return V!==void 0&&(R.textContent=String(V)),R};let i=this.make;this.root=i("section"),this.root.className="kw-bom",this.root.dataset.theme=g,this.root.setAttribute("aria-label","Saved BOM and board data");let m=i("style",We),X=i("div");X.className="kw-bom-tools",this.partsButton=this.button("BOM",()=>this.setMode("parts")),this.boardButton=this.button("Board data",()=>this.setMode("board")),this.downloadButton=this.button("Export full BOM CSV",()=>this.downloadCSV()),X.append(i("strong","Saved design data"),this.partsButton,this.boardButton,this.downloadButton),this.status=i("p","Load a saved KiCad PCB or schematic."),this.status.setAttribute("role","status"),this.summary=i("p"),this.filters=i("div"),this.filters.className="kw-bom-tools",this.search=i("input"),this.search.type="search",this.search.maxLength=200,this.search.placeholder="Reference, value or footprint",this.search.setAttribute("aria-label","Find an eligible BOM part"),this.search.oninput=()=>this.setQuery(this.search.value);let Z=i("label","Group equal value / footprint / population");this.groupInput=i("input"),this.groupInput.type="checkbox",this.groupInput.checked=!0,this.groupInput.onchange=()=>this.setGrouped(this.groupInput.checked),Z.append(this.groupInput),this.filters.append(this.search,Z),this.count=i("p"),this.count.className="kw-bom-small",this.list=i("div"),this.list.className="kw-bom-list",this.list.setAttribute("aria-label","Saved data rows"),this.pages=i("div"),this.pages.className="kw-bom-tools",this.previous=this.button("Previous rows",()=>{this.page--,this.render()}),this.next=this.button("Next rows",()=>{this.page++,this.render()}),this.pageText=i("span"),this.pages.append(this.previous,this.pageText,this.next);let J=i("details"),S=i("summary","Source and interpretation limits");this.limits=i("p"),this.warnings=i("pre"),J.append(S,this.limits,this.warnings),this.root.append(m,X,this.status,this.summary,this.filters,this.count,this.list,this.pages,J),this.host.append(this.root),ge.set(o,this),this.attachViewer(r),this.render()}button(t,r){let g=this.make("button",t);return g.type="button",g.onclick=()=>{try{r()}catch(o){this.fail(o)}},g}active(){if(this.disposed)throw new Error("BOM viewer is disposed.")}emit(t,r){this.dispatchEvent(new CustomEvent(t,{detail:r}))}fail(t){this.disposed||(this.status.textContent=t.message,this.emit("error",{message:t.message}))}sourceReady(){return!!(this.viewer&&!this.viewer.disposed&&this.viewer.source===this.source&&this.viewer.path===this.path)}attachViewer(t){if(this.active(),t&&(!t.addEventListener||!t.removeEventListener||typeof t.selectPart!="function"))throw new TypeError("Attach a native KiCad viewer.");if(this.stopViewer?.(),this.selectedUUID=null,this.hoveredUUID=null,this.viewer=t,t){let r=()=>{if(!this.disposed){this.markDrawingHover(null);try{if(typeof t.source!="string"||!["pcb","schematic"].includes(t.kind)){this.clear();return}t.source!==this.source||t.path!==this.path?this.loadSource(t.source,{path:t.path}):(this.status.textContent=this.bindingLabel(),this.render())}catch(i){this.fail(i),this.render()}}},g=()=>{let i=this.sourceReady()?t.getSelection?.():null;this.selectedUUID=i?.ownerUuid??i?.uuid??null,this.mode==="parts"&&this.render()};t.addEventListener("ready",r),t.addEventListener("select",g);let o=t.subscribePartHover?.(i=>this.markDrawingHover(this.sourceReady()?i:null));this.stopViewer=()=>{o?.(),t.hoverBomParts?.([]),t.removeEventListener("ready",r),t.removeEventListener("select",g)},t.source&&r()}else this.stopViewer=null;this.report&&(this.status.textContent=this.bindingLabel(),this.render())}markDrawingHover(t){if(this.hoveredUUID!==t){this.hoveredUUID=t;for(let[r,g]of this.visibleRows||[])r.classList.toggle("kw-bom-hover",!!(t&&g.has(t)))}}hoverParts(t){this.sourceReady()&&this.viewer.hoverBomParts?.(t.slice(0,50).map(r=>r.uuid).filter(r=>r&&this.uuidCounts.get(r)===1))}bindingLabel(){return se(this.path,240)+" \xB7 "+(this.sourceReady()?"Linked to the same saved source.":"Independent saved-source summary; selection links disabled.")}loadSource(t,{path:r="drawing.kicad_pcb"}={}){this.active();let g=Ee(t,{path:r});this.source=t,this.path=r,this.report=g,this.stats=null,this.page=0,this.selectedUUID=null;let o=i=>[i.reference,i.properties?.Value,i.properties?.Footprint,i.properties?.["Library ID"]].join(" ").toLowerCase();this.partRows=g.groups.flatMap(i=>i.parts.map(m=>({group:i,parts:[m],search:o(m)}))),this.groupRows=g.groups.map(i=>({group:i,parts:i.parts,search:i.parts.map(o).join(" ")})),this.uuidCounts=new Map;for(let i of g.parts)i.uuid&&this.uuidCounts.set(i.uuid,(this.uuidCounts.get(i.uuid)||0)+1);return g.sourceKind!=="pcb"&&(this.mode="parts"),this.status.textContent=this.bindingLabel(),this.render(),this.emit("ready",{path:r,kind:g.sourceKind,total:g.total,groups:g.groups.length}),!0}getBOM(){return this.active(),this.report}getBoardStatistics(){return this.active(),this.report?.sourceKind!=="pcb"?null:(this.stats||(this.stats=ke(this.source,{path:this.path})),this.stats)}setMode(t){if(this.active(),!["parts","board"].includes(t))throw new TypeError("Choose parts or board.");return t==="board"&&this.report?.sourceKind!=="pcb"?!1:(this.mode=t,this.page=0,this.render(),!0)}setQuery(t){if(this.active(),typeof t!="string"||t.length>200)throw new TypeError("Search text is limited to 200 characters.");this.query=t,this.search.value=t,this.page=0,this.render()}setGrouped(t){if(this.active(),typeof t!="boolean")throw new TypeError("Choose true or false for grouped rows.");this.grouped=t,this.groupInput.checked=t,this.page=0,this.render()}setTheme(t){if(this.active(),!["light","dark"].includes(t))throw new TypeError("Choose light or dark theme.");this.theme=t,this.root.dataset.theme=t}selectPart(t){if(this.active(),!this.sourceReady()||!t.uuid||this.uuidCounts.get(t.uuid)!==1)return!1;let r=this.viewer.selectPart(t.uuid,{locate:!0});return r&&this.emit("select",{uuid:t.uuid,reference:t.reference,path:this.path}),r}render(){if(this.disposed)return;let t=this.make;if(this.viewer?.hoverBomParts?.([]),this.visibleRows=new Map,this.list.replaceChildren(),this.partsButton.setAttribute("aria-pressed",String(this.mode==="parts")),this.boardButton.setAttribute("aria-pressed",String(this.mode==="board")),this.boardButton.disabled=this.report?.sourceKind!=="pcb",this.downloadButton.disabled=!this.report,this.filters.hidden=this.mode!=="parts",this.pages.hidden=this.mode!=="parts"||!this.report,!this.report){this.summary.textContent="",this.count.textContent="",this.limits.textContent="Read-only saved-source data. No edits, solver runs or manufacturing checks.",this.warnings.textContent="";return}let r=this.report;if(this.summary.textContent=r.total+" saved parts \xB7 "+r.fitted+" fitted \xB7 "+r.dnp+" DNP \xB7 "+r.excluded+" excluded from BOM",this.limits.textContent=r.limits,this.warnings.textContent=r.warnings.slice(0,24).map(m=>se(m,500)).join(`
`),this.mode==="board"){try{this.renderBoard(this.getBoardStatistics())}catch(m){this.fail(m)}return}let g=this.query.trim().toLowerCase(),o=(this.grouped?this.groupRows:this.partRows).filter(m=>!g||m.search.includes(g)),i=Math.max(1,Math.ceil(o.length/50));this.page=Math.max(0,Math.min(this.page,i-1)),this.previous.disabled=this.page===0,this.next.disabled=this.page+1>=i,this.pageText.textContent=this.page+1+" / "+i,this.count.textContent=o.length+" matching "+(this.grouped?"groups":"parts")+" \xB7 up to 50 rows per page. Group quantities include the whole matching group. Excluded parts are omitted; CSV exports every eligible saved part, including DNP, regardless of this filter.";for(let m of o.slice(this.page*50,this.page*50+50)){let X=t("div");X.className="kw-bom-row",this.selectedUUID&&m.parts.some(R=>R.uuid===this.selectedUUID)&&(X.className+=" kw-bom-selected");let Z=m.group;X.append(t("strong",se(Z.value||"No saved value")+" \xB7 "+m.parts.length+" \xD7 "+(Z.populated?"Fitted":"DNP")),t("p",se(Z.footprint||"No saved footprint",240)));let J=new Set(m.parts.map(R=>R.uuid).filter(R=>R&&this.uuidCounts.get(R)===1));this.visibleRows.set(X,J),this.hoveredUUID&&J.has(this.hoveredUUID)&&(X.className+=" kw-bom-hover"),X.onpointerenter=R=>{R.pointerType!=="touch"&&this.hoverParts(m.parts)},X.onpointerleave=()=>this.hoverParts([]);let S=t("div");S.className="kw-bom-members";let z=0,V=()=>{S.replaceChildren();for(let R of m.parts.slice(z*25,z*25+25)){let d=this.button("Select "+se(R.reference||"unnamed",80),()=>this.selectPart(R));d.disabled=!this.sourceReady()||!R.uuid||this.uuidCounts.get(R.uuid)!==1,d.onpointerenter=h=>{h.pointerType!=="touch"&&this.hoverParts([R])},d.onpointerleave=()=>this.hoverParts(m.parts),S.append(d)}z&&S.append(this.button("Previous parts",()=>{z--,V()})),(z+1)*25<m.parts.length&&S.append(this.button("More parts",()=>{z++,V()}))};if(m.parts.length>1){let R=t("details");R.append(t("summary",se(m.parts.slice(0,8).map(d=>d.reference||"?").join(", "),160)+(m.parts.length>8?" \u2026":"")+" \xB7 select a saved part"),S),R.ontoggle=()=>{R.open&&V()},X.append(R)}else V(),X.append(S);this.list.append(X)}o.length||this.list.append(t("p","No eligible saved BOM parts match this filter."))}renderBoard(t){let r=this.make,g=r("div");g.className="kw-bom-grid";for(let[S,z]of[["Footprints",t.footprints],["Pads",t.pads],["Drilled pads",t.drilledPads],["Vias",t.vias],["Saved track length (mm)",pe(t.totalTrackLengthMm)],["Saved thickness (mm)",pe(t.boardThicknessMm)]]){let V=r("div");V.append(r("small",S),r("p",z)),g.append(V)}this.list.append(g),this.count.textContent="Saved geometry summary \xB7 no DRC, copper union, zone refill or placement certification.",this.limits.textContent=t.limits,this.warnings.textContent=t.warnings.slice(0,24).map(S=>se(S,500)).join(`
`);let o=r("details");o.append(r("summary","Track length by saved net \xB7 "+t.netTracks.length+" entries"));let i=0,m=r("div");m.className="kw-bom-members";let X=()=>{let S=this.sourceReady()?this.viewer.getNets():[];m.replaceChildren();for(let z of t.netTracks.slice(i*50,i*50+50)){let V=String(z.code)==="0"||z.code==="name:"?[]:S.filter(d=>d.id===this.path+"/net:"+z.code),R=this.button(se(z.name,120)+" \xB7 "+pe(z.lengthMm)+" mm",()=>{this.sourceReady()&&V.length===1&&this.viewer.selectNet(V[0].id,{locate:!0})});R.disabled=V.length!==1,m.append(R)}i&&m.append(this.button("Previous nets",()=>{i--,X()})),(i+1)*50<t.netTracks.length&&m.append(this.button("More nets",()=>{i++,X()}))};o.ontoggle=()=>{o.open&&X()},o.append(m),this.list.append(o);let Z=r("details");Z.append(r("summary","Track length by saved layer \xB7 "+t.layerTracks.length+" entries"));for(let S of t.layerTracks.slice(0,256))Z.append(r("p",se(S.layer,120)+" \xB7 "+pe(S.lengthMm)+" mm"));t.layerTracks.length>256&&Z.append(r("p","First 256 layers shown; complete data is available through getBoardStatistics().")),this.list.append(Z);let J=r("details");J.append(r("summary","Saved zone polygon sums \xB7 "+t.zones.length+" zones")),J.append(r("p","Polygon sums count overlaps repeatedly and do not subtract holes. Invalid polygons are omitted; these are not copper-union areas."));for(let S of t.zones.slice(0,100))J.append(r("p",se(S.name,120)+" \xB7 "+pe(S.fillAreaMm2)+" mm\xB2 counted saved fill"+(S.valid?"":" \xB7 incomplete/invalid polygons omitted")));t.zones.length>100&&J.append(r("p","First 100 zones shown; complete data is available through getBoardStatistics().")),this.list.append(J)}exportCSV(){if(this.active(),!this.report)throw new Error("Load saved BOM data first.");return _e(this.report)}downloadCSV(){let t=this.exportCSV(),r=URL.createObjectURL(new Blob([t],{type:"text/csv;charset=utf-8"})),g=this.make("a");g.href=r,g.download="saved-bom.csv",g.click(),setTimeout(()=>URL.revokeObjectURL(r),0)}clear(){this.active(),this.source=null,this.path=null,this.report=this.stats=null,this.groupRows=this.partRows=null,this.uuidCounts?.clear(),this.selectedUUID=null,this.status.textContent="No saved BOM loaded.",this.render()}dispose(){this.disposed||(this.disposed=!0,this.stopViewer?.(),this.stopViewer=null,this.visibleRows?.clear(),this.list.replaceChildren(),this.root.replaceChildren(),this.uuidCounts?.clear(),this.root.remove(),this.source=null,this.report=this.stats=this.groupRows=this.partRows=this.viewer=null,this.search.oninput=this.groupInput.onchange=null,ge.delete(this.host))}};export{Me as BOMViewer,ke as analyzeBoard,_e as bomToCSV,Ee as buildBOM};