@flyfish-dev/cad-viewer 0.6.5 → 0.7.0

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.
@@ -1,12 +1,12 @@
1
- (function(v,M){typeof exports=="object"&&typeof module<"u"?M(exports,require("dwf-viewer")):typeof define=="function"&&define.amd?define(["exports","dwf-viewer"],M):(v=typeof globalThis<"u"?globalThis:v||self,M(v.LightweightCadViewer={},v.DwfViewerPackage))})(this,function(v,M){"use strict";var ur=Object.defineProperty;var mr=(v,M,T)=>M in v?ur(v,M,{enumerable:!0,configurable:!0,writable:!0,value:T}):v[M]=T;var u=(v,M,T)=>mr(v,typeof M!="symbol"?M+"":M,T);async function T(t){if(t.buffer instanceof Uint8Array)return t.buffer;if(t.buffer instanceof ArrayBuffer)return new Uint8Array(t.buffer);if(t.file)return new Uint8Array(await t.file.arrayBuffer());throw new Error("CadLoadInput requires a File, ArrayBuffer, or Uint8Array.")}function Rt(t){return t.byteOffset===0&&t.byteLength===t.buffer.byteLength?t.buffer:t.slice().buffer}function X(t){var r;const e=t.fileName??((r=t.file)==null?void 0:r.name)??"",n=e.lastIndexOf(".");return n>=0?e.slice(n+1).toLowerCase():""}function R(t,e){const n=X(t);if(n==="dwg")return"dwg";if(n==="dxf")return"dxf";if(n==="dwfx")return"dwfx";if(n==="xps")return"xps";if(n==="dwf")return"dwf";if(e&&e.byteLength>=6){const r=Xe(e.slice(0,6));if(/^AC10/.test(r))return"dwg";if(e[0]===80&&e[1]===75)return"dwfx";const i=Xe(e.slice(0,Math.min(e.byteLength,2048))).toUpperCase();if(i.includes("SECTION")&&i.includes("ENTITIES"))return"dxf";if(i.includes("DWF"))return"dwf"}return"unknown"}function Xe(t){return Array.from(t,e=>e>=32&&e<=126?String.fromCharCode(e):" ").join("")}class je{constructor(e=[]){u(this,"loaders",[]);for(const n of e)this.register(n)}register(e){const n=this.loaders.findIndex(r=>r.id===e.id);return n>=0?this.loaders.splice(n,1,e):this.loaders.push(e),this}unregister(e){const n=this.loaders.findIndex(r=>r.id===e);return n>=0&&this.loaders.splice(n,1),this}list(){return[...this.loaders]}async detect(e){const n=await T(e),r=R(e,n),i=this.loaders.find(s=>s.formats.includes(r)&&s.accepts(e,n));if(i)return{loader:i,bytes:n,format:r};const o=this.loaders.find(s=>s.accepts(e,n));if(o)return{loader:o,bytes:n,format:r};throw new Error(`No CAD loader registered for ${r==="unknown"?"this file":r.toUpperCase()}.`)}async load(e,n={}){const{loader:r,bytes:i}=await this.detect(e);return r.load({...e,buffer:i},n)}}const Ot="wasm/dwg-worker.js";class $e{constructor(){u(this,"worker");u(this,"sequence",0);u(this,"pending",new Map)}load(e,n,r={}){var l,f;if(!ie())throw new Error("Web Worker is not available in this runtime.");const i=this.ensureWorker(r),o=++this.sequence,s=Math.max(0,Number(r.workerTimeoutMs??0)),a=r.fileName??n.fileName??((l=n.file)==null?void 0:l.name),c=zt(e,n,r);return(f=r.onProgress)==null||f.call(r,{phase:"worker-start",format:"dwg",message:"Dispatching DWG parse to worker…",total:e.byteLength}),new Promise((h,d)=>{var g;if((g=r.signal)!=null&&g.aborted){d(oe());return}const m={resolve:h,reject:d,onProgress:r.onProgress,signal:r.signal};s>0&&(m.timer=setTimeout(()=>{this.pending.delete(o),this.resetWorker(),d(new Error(`DWG worker timed out after ${s} ms.`))},s)),r.signal&&(m.abortHandler=()=>{this.pending.delete(o),this.resetWorker(),d(oe())},r.signal.addEventListener("abort",m.abortHandler,{once:!0})),this.pending.set(o,m);try{i.postMessage({type:"load",requestId:o,bytes:c,fileName:a,options:Ge(r)},[c])}catch(S){this.pending.delete(o),se(m),d(S instanceof Error?S:new Error(String(S)))}})}preload(e={}){var o;if(!ie())return Promise.reject(new Error("Web Worker is not available in this runtime."));const n=this.ensureWorker(e),r=++this.sequence,i=Math.max(0,Number(e.workerTimeoutMs??0));return(o=e.onProgress)==null||o.call(e,{phase:"worker-start",format:"dwg",message:"Starting DWG worker warmup…"}),new Promise((s,a)=>{var l;if((l=e.signal)!=null&&l.aborted){a(oe());return}const c={resolve:()=>s(),reject:a,onProgress:e.onProgress,signal:e.signal};i>0&&(c.timer=setTimeout(()=>{this.pending.delete(r),this.resetWorker(),a(new Error(`DWG worker warmup timed out after ${i} ms.`))},i)),e.signal&&(c.abortHandler=()=>{this.pending.delete(r),this.resetWorker(),a(oe())},e.signal.addEventListener("abort",c.abortHandler,{once:!0})),this.pending.set(r,c);try{n.postMessage({type:"warmup",requestId:r,options:Ge(e)})}catch(f){this.pending.delete(r),se(c),a(f instanceof Error?f:new Error(String(f)))}})}terminate(){this.resetWorker()}ensureWorker(e){return this.worker||(this.worker=Wt(e),this.worker.onmessage=n=>this.handleMessage(n.data),this.worker.onerror=n=>{const r=n.message||"DWG worker failed.";this.rejectAll(new Error(r)),this.resetWorker(!1)},this.worker.onmessageerror=()=>{this.rejectAll(new Error("DWG worker returned a message that could not be cloned.")),this.resetWorker(!1)}),this.worker}handleMessage(e){var i,o;if(e.type==="ready")return;const n=this.pending.get(e.requestId);if(!n)return;if(e.type==="progress"){(i=n.onProgress)==null||i.call(n,e.progress);return}if(this.pending.delete(e.requestId),se(n),e.type==="result"){n.resolve(e.result);return}if(e.type==="warmup-result"){(o=n.onProgress)==null||o.call(n,{phase:"worker-ready",format:"dwg",message:"DWG worker warmup complete.",percent:100,elapsedMs:e.elapsedMs}),n.resolve(void 0);return}const r=new Error(e.error.message);r.name=e.error.name||"DwgWorkerError",e.error.stack&&(r.stack=e.error.stack),n.reject(r)}rejectAll(e){for(const[,n]of this.pending)se(n),n.reject(e);this.pending.clear()}resetWorker(e=!0){var n;e&&this.rejectAll(new Error("DWG worker was terminated.")),(n=this.worker)==null||n.terminate(),this.worker=void 0}}function ie(){return typeof Worker<"u"&&typeof URL<"u"}function Wt(t){return t.workerFactory?t.workerFactory():new Worker(Yt(t.workerUrl),{type:"module",name:"lightweight-cad-dwg-loader"})}function Ge(t){return{wasmPath:_t(t.wasmPath),includePaperSpace:t.includePaperSpace,maxInsertDepth:t.maxInsertDepth,keepRaw:!!t.keepRaw}}function zt(t,e,n){return!!e.file||n.transferInputBuffer===!0?Rt(t):t.slice().buffer}function se(t){t.timer&&clearTimeout(t.timer),t.signal&&t.abortHandler&&t.signal.removeEventListener("abort",t.abortHandler)}function oe(){if(typeof DOMException<"u")return new DOMException("DWG loading was aborted.","AbortError");const t=new Error("DWG loading was aborted.");return t.name="AbortError",t}function _t(t){const e=((t==null?void 0:t.trim())||"/wasm").replace(/\/+$/,"");return e===""?Ze():qe(e)?e:e.startsWith("/")?`${Ze()}${e}`:new URL(e,we()).href.replace(/\/+$/,"")}function Yt(t){if(t instanceof URL)return t;const e=(t==null?void 0:t.trim())||Ot;return qe(e)?e:new URL(e,we()).href}function we(){return typeof document<"u"&&document.baseURI?document.baseURI:typeof location<"u"&&location.href?location.href:"http://localhost/"}function Ze(){return typeof location<"u"&&location.origin?location.origin:new URL(we()).origin}function qe(t){return/^[a-z][a-z0-9+.-]*:/i.test(t)}class Ke{constructor(e={}){u(this,"id","dwg");u(this,"label","DWG / LibreDWG WebAssembly");u(this,"formats",["dwg"]);u(this,"defaults");u(this,"workerClient",new $e);this.defaults={useWorker:!0,...e}}accepts(e,n){return X(e)==="dwg"?!0:R(e,n)==="dwg"}async load(e,n={}){var s,a;const r={...this.defaults,...n};(s=r.onProgress)==null||s.call(r,{phase:"read",format:"dwg",message:"Reading DWG bytes…"});const i=await T(e),o=e.fileName??((a=e.file)==null?void 0:a.name);if(r.useWorker===!1)throw new Error("DWG main-thread parsing is intentionally not bundled by the default viewer. Keep useWorker enabled, or register a custom DWG loader for non-browser runtimes.");if(!ie())throw new Error("DWG loading requires Web Worker support in this build. Provide a custom loader for this runtime.");try{return await this.workerClient.load(i,e,{...r,fileName:o})}catch(c){throw Vt(c)?c:Ht(c)}}terminateWorker(){this.workerClient.terminate()}preload(e={}){const n={...this.defaults,...e};return n.useWorker===!1?Promise.reject(new Error("DWG preload requires worker mode in the default viewer.")):this.workerClient.preload(n)}}function Vt(t){return t instanceof Error&&t.name==="AbortError"}function Ht(t){const e=t instanceof Error?t.message:String(t);return new Error(`${e} If the worker asset cannot be resolved by your bundler/CDN, pass workerUrl or workerFactory to CadViewer.`)}function ae(t){return{format:t.format,sourceName:t.sourceName,units:t.units,header:t.header??{},layers:t.layers??{},lineTypes:t.lineTypes??{},blocks:t.blocks??{},entities:t.entities??[],pages:t.pages,savedView:t.savedView,metadata:t.metadata??{},warnings:t.warnings??[],raw:t.raw}}function O(t){switch(String(t??"").toUpperCase()){case"LINE":return"line";case"CIRCLE":return"circle";case"ARC":return"arc";case"LWPOLYLINE":case"POLYLINE":case"POLYLINE_2D":case"POLYLINE2D":case"POLYLINE_3D":case"POLYLINE3D":case"LEADER":case"MULTILEADER":return"polyline";case"ELLIPSE":return"ellipse";case"TEXT":case"MTEXT":case"ATTRIB":case"ATTDEF":case"DIMENSION":return"text";case"POINT":return"point";case"INSERT":return"insert";case"SOLID":case"TRACE":case"3DFACE":return"solid";case"HATCH":return"hatch";case"SPLINE":return"spline";case"PATH":case"XPS_PATH":case"DWF_PATH":return"path";case"IMAGE":case"RASTER_IMAGE":case"DWF_IMAGE":return"image";case"VIEWPORT":return"viewport";default:return"unsupported"}}function ce(t,e,n={}){const r=e??String(t.type??t.entityType??t.objectName??"UNKNOWN").toUpperCase(),i=n.includeUnknownProperties===!1?{type:r,kind:O(r)}:{...t,type:r,kind:O(r)};n.keepRaw&&(i.raw=t),i.handle=P(t.handle??t.id),i.layer=P(t.layer??t.layerName),i.lineType=P(t.lineType??t.linetype),i.lineTypeScale=b(t.lineTypeScale??t.linetypeScale??t.ltscale)??i.lineTypeScale,i.flag=b(t.flag??t.flags)??i.flag;const o=t.isClosed===!0||t.closed===!0||t.shape===!0,s=/^(POLYLINE|POLYLINE_2D|POLYLINE2D|POLYLINE_3D|POLYLINE3D|SPLINE)$/.test(r),a=r==="LWPOLYLINE";(o||s&&(Number(i.flag??0)&1)===1||a&&(Number(i.flag??0)&512)===512)&&(i.isClosed=!0);const c=n.numericColorMode??"auto",l=b(t.color),f=b(t.colorIndex??t.colorNumber??t.aci??t.aciColor??t.color_index);i.colorIndex=f??(c!=="rgb"&&l!==void 0&&Math.abs(l)<=257?l:void 0);const h=t.trueColor??t.true_color??t.truecolor??t.colorRGB??t.colorRgb??t.rgbColor??t.rgb,d=l!==void 0&&l>=0&&l<=16777215&&(c==="rgb"||c==="auto"&&Math.abs(l)>257);i.trueColor=h??(d?l:void 0),(typeof t.color=="string"||typeof t.color=="number")&&(i.color=t.color),i.colorNumber=b(t.colorNumber)??i.colorNumber,i.colorName=P(t.colorName??t.color_name)??i.colorName,i.fillColor=t.fillColor??t.fill_color,i.fillColorIndex=b(t.fillColorIndex??t.fill_color_index??t.fillColorNumber)??i.fillColorIndex,i.opacity=b(t.opacity??t.alpha)??i.opacity,i.lineweight=b(t.lineweight??t.lineWeight),i.isVisible=!(t.isVisible===!1||t.visible===!1),i.startPoint=N(t.startPoint??t.start??t.p0??t.from)??i.startPoint,i.endPoint=N(t.endPoint??t.end??t.p1??t.to)??i.endPoint,i.center=N(t.center??t.centerPoint)??i.center,i.insertionPoint=N(t.insertionPoint??t.position??t.location??t.point??t.basePoint)??i.insertionPoint,i.radius=b(t.radius)??i.radius,i.startAngle=b(t.startAngle??t.start_angle)??i.startAngle,i.endAngle=b(t.endAngle??t.end_angle)??i.endAngle,i.majorAxisEndPoint=N(t.majorAxisEndPoint??t.majorAxis??t.major)??i.majorAxisEndPoint,i.axisRatio=b(t.axisRatio??t.ratio)??i.axisRatio,i.height=b(t.height??t.textHeight)??i.height,i.textHeight=b(t.textHeight??t.height)??i.textHeight,i.rotation=b(t.rotation??t.angle)??i.rotation,i.text=P(t.text??t.value??t.string??t.contents)??i.text,i.name=P(t.name??t.blockName)??i.name,i.blockName=P(t.blockName??t.name)??i.blockName;const m=xe(t.vertices??t.points);m.length>0&&(i.vertices=m);const g=xe(t.controlPoints??t.control_points);g.length>0&&(i.controlPoints=g);const S=xe(t.fitPoints??t.fit_points);S.length>0&&(i.fitPoints=S);const y=t.attribs??t.attributes;return Array.isArray(y)&&(i.attribs=y.filter(x=>!!x&&typeof x=="object").map(x=>ce(x,void 0,n))),i}function N(t){if(!t||typeof t!="object")return;const e=t,n=Number(e.x??e.X??e[0]),r=Number(e.y??e.Y??e[1]),i=e.z??e.Z??e[2],o=i===void 0?void 0:Number(i);if(!(!Number.isFinite(n)||!Number.isFinite(r)))return Number.isFinite(o)?{x:n,y:r,z:o}:{x:n,y:r}}function xe(t){if(!Array.isArray(t))return[];const e=[];for(const n of t){const r=N(n);if(!r)continue;const i=n,o=r,s=b(i.bulge);s!==void 0&&(o.bulge=s);const a=b(i.startWidth??i.start_width);a!==void 0&&(o.startWidth=a);const c=b(i.endWidth??i.end_width);c!==void 0&&(o.endWidth=c),e.push(o)}return e}function J(t){var n;const e={};for(const r of t.entities){const i=String(r.type??"UNKNOWN").toUpperCase();e[i]=(e[i]??0)+1}return{format:t.format,sourceName:t.sourceName,entityCount:t.entities.length,layerCount:Object.keys(t.layers).length,blockCount:Object.keys(t.blocks).length,pageCount:((n=t.pages)==null?void 0:n.length)??0,byType:e,warnings:[...t.warnings]}}function Ce(t){if(t.isClosed===!0)return!0;const e=String(t.type??"").toUpperCase(),n=Number(t.flag??0);return e==="LWPOLYLINE"?(n&512)===512:/^(POLYLINE|POLYLINE_2D|POLYLINE2D|POLYLINE_3D|POLYLINE3D)$/.test(e)?(n&1)===1:!1}function Pe(t,e){e.name&&(t[e.name]=e,t[e.name.toLowerCase()]=e)}function Je(t,e){e.name&&(t[e.name]=e,t[e.name.toLowerCase()]=e)}function Ut(t,e){e.name&&(t[e.name]=e,t[e.name.toLowerCase()]=e,e.handle&&(t[e.handle]=e,t[e.handle.toLowerCase()]=e))}function Xt(t){return t!=null&&t.length?t.flatMap(e=>e.entities.map(n=>({...n,pageIndex:e.index}))):[]}function b(t){const e=Number(t);return Number.isFinite(e)?e:void 0}function P(t){if(typeof t!="string"&&typeof t!="number")return;const e=String(t);return e.length>0?e:void 0}function B(){return{minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function j(t){return Number.isFinite(t.minX)&&Number.isFinite(t.minY)&&Number.isFinite(t.maxX)&&Number.isFinite(t.maxY)&&t.maxX>=t.minX&&t.maxY>=t.minY}function C(t,e){p(e)&&(t.minX=Math.min(t.minX,e.x),t.minY=Math.min(t.minY,e.y),t.maxX=Math.max(t.maxX,e.x),t.maxY=Math.max(t.maxY,e.y))}function Qe(t,e,n){if(!p(e)||!Number.isFinite(n))return;const r=Math.abs(n);C(t,{x:e.x-r,y:e.y-r}),C(t,{x:e.x+r,y:e.y+r})}function et(t,e=.02,n=1e-6){if(!j(t))return{minX:-10,minY:-10,maxX:10,maxY:10};const r=Math.max((t.maxX-t.minX)*e,n),i=Math.max((t.maxY-t.minY)*e,n);return{minX:t.minX-r,minY:t.minY-i,maxX:t.maxX+r,maxY:t.maxY+i}}function p(t){return!!t&&typeof t=="object"&&Number.isFinite(t.x)&&Number.isFinite(t.y)}function k(t){return{x:t.x,y:t.y}}function W(t){return t*Math.PI/180}function Q(t,e,n,r,i=!0,o=64){if(!p(t)||!Number.isFinite(e))return[];let s=n,a=r;if(!Number.isFinite(s)||!Number.isFinite(a))return[];(Math.abs(s)>Math.PI*2+1e-6||Math.abs(a)>Math.PI*2+1e-6)&&(s=W(s),a=W(a)),i&&a<s&&(a+=Math.PI*2),!i&&s<a&&(s+=Math.PI*2);const c=a-s,l=Math.max(8,Math.min(256,Math.ceil(Math.abs(c)/(Math.PI*2)*o))),f=[];for(let h=0;h<=l;h++){const d=s+c*(h/l);f.push({x:t.x+Math.cos(d)*e,y:t.y+Math.sin(d)*e})}return f}function le(t,e,n=1,r=0,i=Math.PI*2,o=96){if(!p(t)||!p(e))return[];const s=Math.hypot(e.x,e.y);if(!Number.isFinite(s)||s<=0)return[];const a=s*(Number.isFinite(n)&&n>0?n:1),c=Math.atan2(e.y,e.x);let l=Number.isFinite(r)?r:0,f=Number.isFinite(i)?i:Math.PI*2;(Math.abs(l)>Math.PI*2+1e-6||Math.abs(f)>Math.PI*2+1e-6)&&(l=W(l),f=W(f)),f<l&&(f+=Math.PI*2);const h=Math.max(12,Math.min(256,Math.ceil(Math.abs(f-l)/(Math.PI*2)*o))),d=[],m=Math.cos(c),g=Math.sin(c);for(let S=0;S<=h;S++){const y=l+(f-l)*(S/h),x=Math.cos(y)*s,L=Math.sin(y)*a;d.push({x:t.x+x*m-L*g,y:t.y+x*g+L*m})}return d}function tt(t,e,n=0,r=16){if(!Number.isFinite(n)||Math.abs(n)<1e-12)return[k(t),k(e)];const i=Math.hypot(e.x-t.x,e.y-t.y);if(i<=1e-12)return[k(t),k(e)];const o=4*Math.atan(n),s=Math.abs(i/(2*Math.sin(o/2))),a={x:(t.x+e.x)/2,y:(t.y+e.y)/2},c=(e.x-t.x)/i,l=(e.y-t.y)/i,f=n>=0?1:-1,h=Math.sqrt(Math.max(s*s-(i/2)**2,0)),d={x:a.x-f*l*h,y:a.y+f*c*h},m=Math.atan2(t.y-d.y,t.x-d.x),g=Math.atan2(e.y-d.y,e.x-d.x);return Q(d,s,m,g,n>=0,r)}function nt(t){return t.replace(/\\P/g,`
2
- `).replace(/\\~|\\ /g," ").replace(/\\[A-Za-z][^;]*;/g,"").replace(/[{}]/g,"").replace(/\\[A-Za-z]/g,"").trim()}function $(t,e,n){return Math.min(n,Math.max(e,t))}class rt{constructor(e={}){u(this,"id","dxf");u(this,"label","DXF / JavaScript parser");u(this,"formats",["dxf"]);u(this,"defaults");this.defaults=e}accepts(e,n){return X(e)==="dxf"||R(e,n)==="dxf"}async load(e,n={}){var h;const r={...this.defaults,...n},i=performance.now(),o=await T(e),s=Qt(o,r.dxfEncoding),a=[];let c;try{c=await jt(s)}catch(d){a.push(`dxf-parser failed, using built-in fallback parser: ${d instanceof Error?d.message:String(d)}`),c=on(s)}const l=$t(c,e.fileName??((h=e.file)==null?void 0:h.name),a),f=performance.now()-i;return{document:l,raw:c,bytes:o.byteLength,elapsedMs:f,format:"dxf",warnings:l.warnings}}}async function jt(t){const e=await import("dxf-parser"),n=e.default??e.DxfParser;if(!n)throw new Error("dxf-parser did not expose a parser constructor.");return new n().parseSync(t)}function $t(t,e,n=[]){const r=t&&typeof t=="object"?t:{},i=Gt(r),o=Zt(r),a=(Array.isArray(r.entities)?r.entities:[]).filter(l=>!!l&&typeof l=="object").map(l=>ke(l)),c=ae({format:"dxf",sourceName:e,header:r.header&&typeof r.header=="object"?r.header:{},layers:i,blocks:o,entities:a,metadata:{parser:"dxf-parser + cad-viewer normalizer"},warnings:n,raw:t});return a.length===0&&c.warnings.push("DXF file did not expose any ENTITIES."),c}function ke(t){const e=String(t.type??t.entityType??"UNKNOWN").toUpperCase(),n=ce(t,e),r=b(t.colorIndex??t.colorNumber??t.aci),i=b(t.color);if(n.colorIndex=r??(i!==void 0&&Math.abs(i)<=257?i:void 0),n.trueColor=t.trueColor??t.true_color??t.colorRGB??t.trueColorValue??(i!==void 0&&Math.abs(i)>257?i:void 0),n.layer=P(t.layer??t.layerName)??"0",n.isClosed=!!(t.shape??t.closed??t.isClosed)||(Number(t.flag??t.flags??0)&1)===1,e==="LINE"&&(n.startPoint=N(t.startPoint??{x:t.x1??t.x,y:t.y1??t.y,z:t.z1??t.z})??n.startPoint,n.endPoint=N(t.endPoint??{x:t.x2,y:t.y2,z:t.z2})??n.endPoint),(e==="TEXT"||e==="MTEXT"||e==="ATTRIB"||e==="ATTDEF")&&(n.insertionPoint=N(t.startPoint??t.position??t.insertionPoint)??n.insertionPoint,n.text=sn(t.text??t.string??t.value)??n.text,n.textHeight=b(t.textHeight??t.height)??n.textHeight,n.rotation=st(t.rotation??t.angle)),(e==="ARC"||e==="ELLIPSE")&&(n.startAngle=ot(t.startAngle??t.start_angle),n.endAngle=ot(t.endAngle??t.end_angle)),e==="INSERT"){n.blockName=P(t.name??t.blockName)??n.blockName,n.insertionPoint=N(t.position??t.insertionPoint??t.point)??n.insertionPoint;const o=b(t.xScale??t.scaleX??t.xscale),s=b(t.yScale??t.scaleY??t.yscale),a=b(t.zScale??t.scaleZ??t.zscale);(o!==void 0||s!==void 0||a!==void 0)&&(n.scale={x:o??1,y:s??o??1,z:a??1}),n.rotation=st(t.rotation??t.angle)}if(e==="SPLINE"){const o=fe(t.controlPoints??t.control_points??t.points);o.length&&(n.controlPoints=o);const s=fe(t.fitPoints??t.fit_points);s.length&&(n.fitPoints=s)}return e==="HATCH"&&(n.loops=Jt(t),n.fillColorIndex=n.colorIndex),(e==="SOLID"||e==="TRACE"||e==="3DFACE")&&(n.vertices=Kt(t),n.fillColorIndex=n.colorIndex),n}function Gt(t){const e={},n=t.tables,r=t.layers??(n==null?void 0:n.layer)??(n==null?void 0:n.LAYER)??(n==null?void 0:n.layers),i=qt(r);for(const o of i){const s=o,a=P(s.name??s.layerName);a&&Pe(e,{name:a,color:s.color??s.colorNumber??s.colorIndex,colorIndex:b(s.colorNumber??s.colorIndex??s.color),lineType:P(s.lineType??s.linetype),isVisible:Number(s.colorNumber??s.colorIndex??s.color??1)>=0,isFrozen:!!s.frozen,isLocked:!!s.locked,raw:s})}return e[0]||Pe(e,{name:"0",colorIndex:7,isVisible:!0}),e}function Zt(t){const e={},n=t.blocks;if(!n||typeof n!="object")return e;if(Array.isArray(n))for(const r of n)it(e,r);else for(const[r,i]of Object.entries(n))it(e,i,r);return e}function it(t,e,n){if(!e||typeof e!="object")return;const r=e,i=P(r.name??r.blockName??n);if(!i)return;const s=(Array.isArray(r.entities)?r.entities:[]).filter(a=>!!a&&typeof a=="object").map(a=>ke(a));Je(t,{name:i,basePoint:N(r.basePoint??r.position)??{x:0,y:0},entities:s,raw:r})}function qt(t){if(!t)return[];if(Array.isArray(t))return t;if(typeof t!="object")return[];const e=t;return Array.isArray(e.entries)?e.entries:Array.isArray(e.records)?e.records:Array.isArray(e.layers)?e.layers:Object.values(e).filter(n=>n&&typeof n=="object")}function fe(t){return Array.isArray(t)?t.map(N).filter(e=>!!e):[]}function Kt(t){const e=fe(t.vertices??t.points);if(e.length)return e;const n=[];for(let r=0;r<4;r++){const i=N({x:t[`x${r}`]??t[`x${r+1}`],y:t[`y${r}`]??t[`y${r+1}`],z:t[`z${r}`]??t[`z${r+1}`]});i&&n.push(i)}return n}function Jt(t){const e=t.boundaryLoops??t.loops??t.paths;if(Array.isArray(e))return e.map(n=>{const r=n;return{vertices:fe(r.vertices??r.points),isClosed:!0}}).filter(n=>n.vertices&&n.vertices.length>0)}function st(t){const e=b(t);if(e!==void 0)return Math.abs(e)>Math.PI*2+1e-6?W(e):e}function ot(t){const e=b(t);if(e!==void 0)return Math.abs(e)>Math.PI*2+1e-6?W(e):e}function Qt(t,e){const n=Se(e);if(n)return z(t,n);const r=en(t);if(r)return z(t,r);const i=Se(tn(t));if(i)return z(t,i);const o=z(t,"utf-8");return o.includes("�")?nn(t):o}const at={ANSI_874:"windows-874",ANSI_932:"shift_jis",ANSI_936:"gb18030",ANSI_949:"euc-kr",ANSI_950:"big5",ANSI_1250:"windows-1250",ANSI_1251:"windows-1251",ANSI_1252:"windows-1252",ANSI_1253:"windows-1253",ANSI_1254:"windows-1254",ANSI_1255:"windows-1255",ANSI_1256:"windows-1256",ANSI_1257:"windows-1257",ANSI_1258:"windows-1258",BIG5:"big5",CP874:"windows-874",CP932:"shift_jis",CP936:"gb18030",CP949:"euc-kr",CP950:"big5",CP1250:"windows-1250",CP1251:"windows-1251",CP1252:"windows-1252",CP1253:"windows-1253",CP1254:"windows-1254",CP1255:"windows-1255",CP1256:"windows-1256",CP1257:"windows-1257",CP1258:"windows-1258",GB18030:"gb18030",GB2312:"gb18030",GBK:"gb18030",SHIFT_JIS:"shift_jis",SHIFTJIS:"shift_jis",SJIS:"shift_jis",UTF8:"utf-8",UTF_8:"utf-8",UTF16:"utf-16le",UTF_16:"utf-16le",UTF16LE:"utf-16le",UTF_16LE:"utf-16le",UTF16BE:"utf-16be",UTF_16BE:"utf-16be"};function en(t){if(t.length>=3&&t[0]===239&&t[1]===187&&t[2]===191)return"utf-8";if(t.length>=2&&t[0]===255&&t[1]===254)return"utf-16le";if(t.length>=2&&t[0]===254&&t[1]===255)return"utf-16be"}function tn(t){var r,i,o,s;const n=z(t.subarray(0,Math.min(t.byteLength,131072)),"iso-8859-1").replace(/\r\n/g,`
1
+ (function(x,D){typeof exports=="object"&&typeof module<"u"?D(exports,require("dwf-viewer")):typeof define=="function"&&define.amd?define(["exports","dwf-viewer"],D):(x=typeof globalThis<"u"?globalThis:x||self,D(x.LightweightCadViewer={},x.DwfViewerPackage))})(this,function(x,D){"use strict";var Hs=Object.defineProperty;var $s=(x,D,X)=>D in x?Hs(x,D,{enumerable:!0,configurable:!0,writable:!0,value:X}):x[D]=X;var m=(x,D,X)=>$s(x,typeof D!="symbol"?D+"":D,X);async function X(n){if(n.buffer instanceof Uint8Array)return n.buffer;if(n.buffer instanceof ArrayBuffer)return new Uint8Array(n.buffer);if(n.file)return new Uint8Array(await n.file.arrayBuffer());throw new Error("CadLoadInput requires a File, ArrayBuffer, or Uint8Array.")}function En(n){return n.byteOffset===0&&n.byteLength===n.buffer.byteLength?n.buffer:n.slice().buffer}function K(n){var i;const e=n.fileName??((i=n.file)==null?void 0:i.name)??"",t=e.lastIndexOf(".");return t>=0?e.slice(t+1).toLowerCase():""}function $(n,e){const t=K(n);if(t==="dwg")return"dwg";if(t==="dxf")return"dxf";if(t==="dwfx")return"dwfx";if(t==="xps")return"xps";if(t==="dwf")return"dwf";if(e&&e.byteLength>=6){const i=dt(e.slice(0,6));if(/^AC10/.test(i))return"dwg";if(e[0]===80&&e[1]===75)return"dwfx";const s=dt(e.slice(0,Math.min(e.byteLength,2048))).toUpperCase();if(s.includes("SECTION")&&s.includes("ENTITIES"))return"dxf";if(s.includes("DWF"))return"dwf"}return"unknown"}function dt(n){return Array.from(n,e=>e>=32&&e<=126?String.fromCharCode(e):" ").join("")}class ft{constructor(e=[]){m(this,"loaders",[]);for(const t of e)this.register(t)}register(e){const t=this.loaders.findIndex(i=>i.id===e.id);return t>=0?this.loaders.splice(t,1,e):this.loaders.push(e),this}unregister(e){const t=this.loaders.findIndex(i=>i.id===e);return t>=0&&this.loaders.splice(t,1),this}list(){return[...this.loaders]}async detect(e){const t=await X(e),i=$(e,t),s=this.loaders.find(o=>o.formats.includes(i)&&o.accepts(e,t));if(s)return{loader:s,bytes:t,format:i};const r=this.loaders.find(o=>o.accepts(e,t));if(r)return{loader:r,bytes:t,format:i};throw new Error(`No CAD loader registered for ${i==="unknown"?"this file":i.toUpperCase()}.`)}async load(e,t={}){const{loader:i,bytes:s}=await this.detect(e);return i.load({...e,buffer:s},t)}}const An="wasm/dwg-worker.js";class ut{constructor(){m(this,"worker");m(this,"sequence",0);m(this,"pending",new Map)}load(e,t,i={}){var h,l;if(!ge())throw new Error("Web Worker is not available in this runtime.");const s=this.ensureWorker(i),r=++this.sequence,o=Math.max(0,Number(i.workerTimeoutMs??0)),a=i.fileName??t.fileName??((h=t.file)==null?void 0:h.name),c=Ln(e,t,i);return(l=i.onProgress)==null||l.call(i,{phase:"worker-start",format:"dwg",message:"Dispatching DWG parse to worker…",total:e.byteLength}),new Promise((d,f)=>{var p;if((p=i.signal)!=null&&p.aborted){f(be());return}const u={resolve:d,reject:f,onProgress:i.onProgress,signal:i.signal};o>0&&(u.timer=setTimeout(()=>{this.pending.delete(r),this.resetWorker(),f(new Error(`DWG worker timed out after ${o} ms.`))},o)),i.signal&&(u.abortHandler=()=>{this.pending.delete(r),this.resetWorker(),f(be())},i.signal.addEventListener("abort",u.abortHandler,{once:!0})),this.pending.set(r,u);try{s.postMessage({type:"load",requestId:r,bytes:c,fileName:a,options:mt(i)},[c])}catch(w){this.pending.delete(r),ye(u),f(w instanceof Error?w:new Error(String(w)))}})}preload(e={}){var r;if(!ge())return Promise.reject(new Error("Web Worker is not available in this runtime."));const t=this.ensureWorker(e),i=++this.sequence,s=Math.max(0,Number(e.workerTimeoutMs??0));return(r=e.onProgress)==null||r.call(e,{phase:"worker-start",format:"dwg",message:"Starting DWG worker warmup…"}),new Promise((o,a)=>{var h;if((h=e.signal)!=null&&h.aborted){a(be());return}const c={resolve:()=>o(),reject:a,onProgress:e.onProgress,signal:e.signal};s>0&&(c.timer=setTimeout(()=>{this.pending.delete(i),this.resetWorker(),a(new Error(`DWG worker warmup timed out after ${s} ms.`))},s)),e.signal&&(c.abortHandler=()=>{this.pending.delete(i),this.resetWorker(),a(be())},e.signal.addEventListener("abort",c.abortHandler,{once:!0})),this.pending.set(i,c);try{t.postMessage({type:"warmup",requestId:i,options:mt(e)})}catch(l){this.pending.delete(i),ye(c),a(l instanceof Error?l:new Error(String(l)))}})}terminate(){this.resetWorker()}ensureWorker(e){return this.worker||(this.worker=In(e),this.worker.onmessage=t=>this.handleMessage(t.data),this.worker.onerror=t=>{const i=t.message||"DWG worker failed.";this.rejectAll(new Error(i)),this.resetWorker(!1)},this.worker.onmessageerror=()=>{this.rejectAll(new Error("DWG worker returned a message that could not be cloned.")),this.resetWorker(!1)}),this.worker}handleMessage(e){var s,r;if(e.type==="ready")return;const t=this.pending.get(e.requestId);if(!t)return;if(e.type==="progress"){(s=t.onProgress)==null||s.call(t,e.progress);return}if(this.pending.delete(e.requestId),ye(t),e.type==="result"){t.resolve(e.result);return}if(e.type==="warmup-result"){(r=t.onProgress)==null||r.call(t,{phase:"worker-ready",format:"dwg",message:"DWG worker warmup complete.",percent:100,elapsedMs:e.elapsedMs}),t.resolve(void 0);return}const i=new Error(e.error.message);i.name=e.error.name||"DwgWorkerError",e.error.stack&&(i.stack=e.error.stack),t.reject(i)}rejectAll(e){for(const[,t]of this.pending)ye(t),t.reject(e);this.pending.clear()}resetWorker(e=!0){var t;e&&this.rejectAll(new Error("DWG worker was terminated.")),(t=this.worker)==null||t.terminate(),this.worker=void 0}}function ge(){return typeof Worker<"u"&&typeof URL<"u"}function In(n){return n.workerFactory?n.workerFactory():new Worker(Dn(n.workerUrl),{type:"module",name:"lightweight-cad-dwg-loader"})}function mt(n){return{wasmPath:Fn(n.wasmPath),includePaperSpace:n.includePaperSpace,maxInsertDepth:n.maxInsertDepth,keepRaw:!!n.keepRaw}}function Ln(n,e,t){return!!e.file||t.transferInputBuffer===!0?En(n):n.slice().buffer}function ye(n){n.timer&&clearTimeout(n.timer),n.signal&&n.abortHandler&&n.signal.removeEventListener("abort",n.abortHandler)}function be(){if(typeof DOMException<"u")return new DOMException("DWG loading was aborted.","AbortError");const n=new Error("DWG loading was aborted.");return n.name="AbortError",n}function Fn(n){const e=((n==null?void 0:n.trim())||"/wasm").replace(/\/+$/,"");return e===""?pt():gt(e)?e:e.startsWith("/")?`${pt()}${e}`:new URL(e,Le()).href.replace(/\/+$/,"")}function Dn(n){if(n instanceof URL)return n;const e=(n==null?void 0:n.trim())||An;return gt(e)?e:new URL(e,Le()).href}function Le(){return typeof document<"u"&&document.baseURI?document.baseURI:typeof location<"u"&&location.href?location.href:"http://localhost/"}function pt(){return typeof location<"u"&&location.origin?location.origin:new URL(Le()).origin}function gt(n){return/^[a-z][a-z0-9+.-]*:/i.test(n)}class yt{constructor(e={}){m(this,"id","dwg");m(this,"label","DWG / LibreDWG WebAssembly");m(this,"formats",["dwg"]);m(this,"defaults");m(this,"workerClient",new ut);this.defaults={useWorker:!0,...e}}accepts(e,t){return K(e)==="dwg"?!0:$(e,t)==="dwg"}async load(e,t={}){var o,a;const i={...this.defaults,...t};(o=i.onProgress)==null||o.call(i,{phase:"read",format:"dwg",message:"Reading DWG bytes…"});const s=await X(e),r=e.fileName??((a=e.file)==null?void 0:a.name);if(i.useWorker===!1)throw new Error("DWG main-thread parsing is intentionally not bundled by the default viewer. Keep useWorker enabled, or register a custom DWG loader for non-browser runtimes.");if(!ge())throw new Error("DWG loading requires Web Worker support in this build. Provide a custom loader for this runtime.");try{return await this.workerClient.load(s,e,{...i,fileName:r})}catch(c){throw Bn(c)?c:Rn(c)}}terminateWorker(){this.workerClient.terminate()}preload(e={}){const t={...this.defaults,...e};return t.useWorker===!1?Promise.reject(new Error("DWG preload requires worker mode in the default viewer.")):this.workerClient.preload(t)}}function Bn(n){return n instanceof Error&&n.name==="AbortError"}function Rn(n){const e=n instanceof Error?n.message:String(n);return new Error(`${e} If the worker asset cannot be resolved by your bundler/CDN, pass workerUrl or workerFactory to CadViewer.`)}function xe(n){return{format:n.format,sourceName:n.sourceName,units:n.units,header:n.header??{},layers:n.layers??{},lineTypes:n.lineTypes??{},blocks:n.blocks??{},entities:n.entities??[],pages:n.pages,savedView:n.savedView,metadata:n.metadata??{},warnings:n.warnings??[],raw:n.raw}}function J(n){switch(String(n??"").toUpperCase()){case"LINE":return"line";case"CIRCLE":return"circle";case"ARC":return"arc";case"LWPOLYLINE":case"POLYLINE":case"POLYLINE_2D":case"POLYLINE2D":case"POLYLINE_3D":case"POLYLINE3D":case"LEADER":case"MULTILEADER":return"polyline";case"ELLIPSE":return"ellipse";case"TEXT":case"MTEXT":case"ATTRIB":case"ATTDEF":case"DIMENSION":return"text";case"POINT":return"point";case"INSERT":return"insert";case"SOLID":case"TRACE":case"3DFACE":return"solid";case"HATCH":return"hatch";case"SPLINE":return"spline";case"PATH":case"XPS_PATH":case"DWF_PATH":return"path";case"IMAGE":case"RASTER_IMAGE":case"DWF_IMAGE":return"image";case"VIEWPORT":return"viewport";default:return"unsupported"}}function ve(n,e,t={}){const i=e??String(n.type??n.entityType??n.objectName??"UNKNOWN").toUpperCase(),s=t.includeUnknownProperties===!1?{type:i,kind:J(i)}:{...n,type:i,kind:J(i)};t.keepRaw&&(s.raw=n),s.handle=M(n.handle??n.id),s.layer=M(n.layer??n.layerName),s.lineType=M(n.lineType??n.linetype),s.lineTypeScale=y(n.lineTypeScale??n.linetypeScale??n.ltscale)??s.lineTypeScale,s.flag=y(n.flag??n.flags)??s.flag,s.constantWidth=y(n.constantWidth??n.constWidth??n.const_width)??s.constantWidth,s.thickness=y(n.thickness)??s.thickness;const r=n.isClosed===!0||n.closed===!0||n.shape===!0,o=/^(POLYLINE|POLYLINE_2D|POLYLINE2D|POLYLINE_3D|POLYLINE3D|SPLINE)$/.test(i),a=i==="LWPOLYLINE";(r||o&&(Number(s.flag??0)&1)===1||a&&(Number(s.flag??0)&512)===512)&&(s.isClosed=!0);const c=t.numericColorMode??"auto",h=y(n.color),l=y(n.colorIndex??n.colorNumber??n.aci??n.aciColor??n.color_index);s.colorIndex=l??(c!=="rgb"&&h!==void 0&&Math.abs(h)<=257?h:void 0);const d=n.trueColor??n.true_color??n.truecolor??n.colorRGB??n.colorRgb??n.rgbColor??n.rgb,f=h!==void 0&&h>=0&&h<=16777215&&(c==="rgb"||c==="auto"&&Math.abs(h)>257);if(s.trueColor=d??(f?h:void 0),(typeof n.color=="string"||typeof n.color=="number")&&(s.color=n.color),s.colorNumber=y(n.colorNumber)??s.colorNumber,s.colorName=M(n.colorName??n.color_name)??s.colorName,s.fillColor=n.fillColor??n.fill_color,s.fillColorIndex=y(n.fillColorIndex??n.fill_color_index??n.fillColorNumber)??s.fillColorIndex,s.opacity=y(n.opacity??n.alpha)??s.opacity,s.lineweight=y(n.lineweight??n.lineWeight),s.isVisible=!(n.isVisible===!1||n.visible===!1),s.startPoint=E(n.startPoint??n.start??n.p0??n.from)??s.startPoint,s.endPoint=E(n.endPoint??n.end??n.p1??n.to)??s.endPoint,s.center=E(n.center??n.centerPoint)??s.center,s.insertionPoint=E(n.insertionPoint??n.position??n.location??n.point??n.basePoint)??s.insertionPoint,s.radius=y(n.radius)??s.radius,s.startAngle=y(n.startAngle??n.start_angle)??s.startAngle,s.endAngle=y(n.endAngle??n.end_angle)??s.endAngle,s.majorAxisEndPoint=E(n.majorAxisEndPoint??n.majorAxis??n.major)??s.majorAxisEndPoint,s.axisRatio=y(n.axisRatio??n.ratio)??s.axisRatio,s.height=y(n.height??n.textHeight)??s.height,s.textHeight=y(n.textHeight??n.height)??s.textHeight,s.xScale=y(n.xScale??n.widthFactor)??s.xScale,s.generationFlag=y(n.generationFlag??n.textGenerationFlag)??s.generationFlag,s.halign=y(n.halign??n.horizontalAlignment)??s.halign,s.valign=y(n.valign??n.verticalAlignment)??s.valign,s.extrusionDirection=E(n.extrusionDirection??n.extrusion)??s.extrusionDirection,s.rotation=y(n.rotation??n.angle)??s.rotation,s.text=M(n.text??n.value??n.string??n.contents)??s.text,s.name=M(n.name??n.blockName)??s.name,s.blockName=M(n.blockName??n.name)??s.blockName,i==="INSERT"){const g=E(n.scale);if(g)s.scale=g;else{const v=y(n.scaleX??n.xScale),C=y(n.scaleY??n.yScale)??v,S=y(n.scaleZ??n.zScale);v!==void 0&&C!==void 0&&(s.scale=S===void 0?{x:v,y:C}:{x:v,y:C,z:S})}}const u=Fe(n.vertices??n.points);u.length>0&&(s.vertices=u);const p=Fe(n.controlPoints??n.control_points);p.length>0&&(s.controlPoints=p);const w=Fe(n.fitPoints??n.fit_points);w.length>0&&(s.fitPoints=w);const P=n.attribs??n.attributes;return Array.isArray(P)&&(s.attribs=P.filter(g=>!!g&&typeof g=="object").map(g=>ve(g,void 0,t))),s}function E(n){if(!n||typeof n!="object")return;const e=n,t=Number(e.x??e.X??e[0]),i=Number(e.y??e.Y??e[1]),s=e.z??e.Z??e[2],r=s===void 0?void 0:Number(s);if(!(!Number.isFinite(t)||!Number.isFinite(i)))return Number.isFinite(r)?{x:t,y:i,z:r}:{x:t,y:i}}function Fe(n){if(!Array.isArray(n))return[];const e=[];for(const t of n){const i=E(t);if(!i)continue;const s=t,r=i,o=y(s.bulge);o!==void 0&&(r.bulge=o);const a=y(s.startWidth??s.start_width);a!==void 0&&(r.startWidth=a);const c=y(s.endWidth??s.end_width);c!==void 0&&(r.endWidth=c),e.push(r)}return e}function Q(n){var t;const e={};for(const i of n.entities){const s=String(i.type??"UNKNOWN").toUpperCase();e[s]=(e[s]??0)+1}return{format:n.format,sourceName:n.sourceName,entityCount:n.entities.length,layerCount:Object.keys(n.layers).length,blockCount:Object.keys(n.blocks).length,pageCount:((t=n.pages)==null?void 0:t.length)??0,byType:e,warnings:[...n.warnings]}}function De(n){if(n.isClosed===!0)return!0;const e=String(n.type??"").toUpperCase(),t=Number(n.flag??0),i=e==="LWPOLYLINE",s=/^(POLYLINE|POLYLINE_2D|POLYLINE2D|POLYLINE_3D|POLYLINE3D)$/.test(e);if(i&&(t&512)===512||s&&(t&1)===1)return!0;if(!i&&!s)return!1;const r=n.vertices??n.points;if(!Array.isArray(r)||r.length<3)return!1;const o=r[0],a=r[r.length-1];if(!o||!a)return!1;const c=r.reduce((h,l)=>Math.max(h,Math.abs(l.x),Math.abs(l.y)),1);return Math.hypot(o.x-a.x,o.y-a.y)<=Math.max(1e-9,c*1e-12)}function Be(n){let e=Oe(n.constantWidth);for(const t of n.vertices??[])e=Math.max(e,Oe(t.startWidth),Oe(t.endWidth));return e}function Re(n,e){e.name&&(n[e.name]=e,n[e.name.toLowerCase()]=e)}function bt(n,e){e.name&&(n[e.name]=e,n[e.name.toLowerCase()]=e)}function On(n,e){e.name&&(n[e.name]=e,n[e.name.toLowerCase()]=e,e.handle&&(n[e.handle]=e,n[e.handle.toLowerCase()]=e))}function Wn(n){return n!=null&&n.length?n.flatMap(e=>e.entities.map(t=>({...t,pageIndex:e.index}))):[]}function y(n){const e=Number(n);return Number.isFinite(e)?e:void 0}function M(n){if(typeof n!="string"&&typeof n!="number")return;const e=String(n);return e.length>0?e:void 0}function Oe(n){const e=Math.abs(Number(n));return Number.isFinite(e)?e:0}function z(){return{minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function R(n){return Number.isFinite(n.minX)&&Number.isFinite(n.minY)&&Number.isFinite(n.maxX)&&Number.isFinite(n.maxY)&&n.maxX>=n.minX&&n.maxY>=n.minY}function L(n,e){b(e)&&(n.minX=Math.min(n.minX,e.x),n.minY=Math.min(n.minY,e.y),n.maxX=Math.max(n.maxX,e.x),n.maxY=Math.max(n.maxY,e.y))}function Yn(n,e,t){if(!b(e)||!Number.isFinite(t))return;const i=Math.abs(t);L(n,{x:e.x-i,y:e.y-i}),L(n,{x:e.x+i,y:e.y+i})}function xt(n,e){R(e)&&(L(n,{x:e.minX,y:e.minY}),L(n,{x:e.maxX,y:e.maxY}))}function vt(n,e=.02,t=1e-6){if(!R(n))return{minX:-10,minY:-10,maxX:10,maxY:10};const i=Math.max((n.maxX-n.minX)*e,t),s=Math.max((n.maxY-n.minY)*e,t);return{minX:n.minX-i,minY:n.minY-s,maxX:n.maxX+i,maxY:n.maxY+s}}function b(n){return!!n&&typeof n=="object"&&Number.isFinite(n.x)&&Number.isFinite(n.y)}function A(n){return{x:n.x,y:n.y}}function V(n){return n*Math.PI/180}function he(n,e,t,i,s=!0,r=64){if(!b(n)||!Number.isFinite(e))return[];let o=t,a=i;if(!Number.isFinite(o)||!Number.isFinite(a))return[];(Math.abs(o)>Math.PI*2+1e-6||Math.abs(a)>Math.PI*2+1e-6)&&(o=V(o),a=V(a)),s&&a<o&&(a+=Math.PI*2),!s&&o<a&&(o+=Math.PI*2);const c=a-o,h=Math.max(8,Math.min(256,Math.ceil(Math.abs(c)/(Math.PI*2)*r))),l=[];for(let d=0;d<=h;d++){const f=o+c*(d/h);l.push({x:n.x+Math.cos(f)*e,y:n.y+Math.sin(f)*e})}return l}function We(n,e,t=1,i=0,s=Math.PI*2,r=96){if(!b(n)||!b(e))return[];const o=Math.hypot(e.x,e.y);if(!Number.isFinite(o)||o<=0)return[];const a=o*(Number.isFinite(t)&&t>0?t:1),c=Math.atan2(e.y,e.x);let h=Number.isFinite(i)?i:0,l=Number.isFinite(s)?s:Math.PI*2;(Math.abs(h)>Math.PI*2+1e-6||Math.abs(l)>Math.PI*2+1e-6)&&(h=V(h),l=V(l)),l<h&&(l+=Math.PI*2);const d=Math.max(12,Math.min(256,Math.ceil(Math.abs(l-h)/(Math.PI*2)*r))),f=[],u=Math.cos(c),p=Math.sin(c);for(let w=0;w<=d;w++){const P=h+(l-h)*(w/d),g=Math.cos(P)*o,v=Math.sin(P)*a;f.push({x:n.x+g*u-v*p,y:n.y+g*p+v*u})}return f}function wt(n,e,t=0,i=16){if(!Number.isFinite(t)||Math.abs(t)<1e-12)return[A(n),A(e)];const s=Math.hypot(e.x-n.x,e.y-n.y);if(s<=1e-12)return[A(n),A(e)];const r=4*Math.atan(t),o=Math.abs(s/(2*Math.sin(r/2))),a={x:(n.x+e.x)/2,y:(n.y+e.y)/2},c=(e.x-n.x)/s,h=(e.y-n.y)/s,l=t>=0?1:-1,d=Math.sqrt(Math.max(o*o-(s/2)**2,0)),f={x:a.x-l*h*d,y:a.y+l*c*d},u=Math.atan2(n.y-f.y,n.x-f.x),p=Math.atan2(e.y-f.y,e.x-f.x);return he(f,o,u,p,t>=0,i)}function Pt(n){return n.replace(/\\P/g,`
2
+ `).replace(/\\~|\\ /g," ").replace(/\\[A-Za-z][^;]*;/g,"").replace(/[{}]/g,"").replace(/\\[A-Za-z]/g,"").trim()}function ee(n,e,t){return Math.min(t,Math.max(e,n))}class Ct{constructor(e={}){m(this,"id","dxf");m(this,"label","DXF / JavaScript parser");m(this,"formats",["dxf"]);m(this,"defaults");this.defaults=e}accepts(e,t){return K(e)==="dxf"||$(e,t)==="dxf"}async load(e,t={}){var d;const i={...this.defaults,...t},s=performance.now(),r=await X(e),o=Gn(r,i.dxfEncoding),a=[];let c;try{c=await Xn(o)}catch(f){a.push(`dxf-parser failed, using built-in fallback parser: ${f instanceof Error?f.message:String(f)}`),c=Qn(o)}const h=zn(c,e.fileName??((d=e.file)==null?void 0:d.name),a),l=performance.now()-s;return{document:h,raw:c,bytes:r.byteLength,elapsedMs:l,format:"dxf",warnings:h.warnings}}}async function Xn(n){const e=await import("dxf-parser"),t=e.default??e.DxfParser;if(!t)throw new Error("dxf-parser did not expose a parser constructor.");return new t().parseSync(n)}function zn(n,e,t=[]){const i=n&&typeof n=="object"?n:{},s=Un(i),r=_n(i),a=(Array.isArray(i.entities)?i.entities:[]).filter(h=>!!h&&typeof h=="object").map(h=>Ye(h)),c=xe({format:"dxf",sourceName:e,header:i.header&&typeof i.header=="object"?i.header:{},layers:s,blocks:r,entities:a,metadata:{parser:"dxf-parser + cad-viewer normalizer"},warnings:t,raw:n});return a.length===0&&c.warnings.push("DXF file did not expose any ENTITIES."),c}function Ye(n){const e=String(n.type??n.entityType??"UNKNOWN").toUpperCase(),t=ve(n,e),i=y(n.colorIndex??n.colorNumber??n.aci),s=y(n.color);if(t.colorIndex=i??(s!==void 0&&Math.abs(s)<=257?s:void 0),t.trueColor=n.trueColor??n.true_color??n.colorRGB??n.trueColorValue??(s!==void 0&&Math.abs(s)>257?s:void 0),t.layer=M(n.layer??n.layerName)??"0",t.isClosed=!!(n.shape??n.closed??n.isClosed)||(Number(n.flag??n.flags??0)&1)===1,e==="LINE"&&(t.startPoint=E(n.startPoint??{x:n.x1??n.x,y:n.y1??n.y,z:n.z1??n.z})??t.startPoint,t.endPoint=E(n.endPoint??{x:n.x2,y:n.y2,z:n.z2})??t.endPoint),(e==="TEXT"||e==="MTEXT"||e==="ATTRIB"||e==="ATTDEF")&&(t.insertionPoint=E(n.startPoint??n.position??n.insertionPoint)??t.insertionPoint,t.text=Jn(n.text??n.string??n.value)??t.text,t.textHeight=y(n.textHeight??n.height)??t.textHeight,t.rotation=kt(n.rotation??n.angle)),(e==="ARC"||e==="ELLIPSE")&&(t.startAngle=Nt(n.startAngle??n.start_angle),t.endAngle=Nt(n.endAngle??n.end_angle)),e==="INSERT"){t.blockName=M(n.name??n.blockName)??t.blockName,t.insertionPoint=E(n.position??n.insertionPoint??n.point)??t.insertionPoint;const r=y(n.xScale??n.scaleX??n.xscale),o=y(n.yScale??n.scaleY??n.yscale),a=y(n.zScale??n.scaleZ??n.zscale);(r!==void 0||o!==void 0||a!==void 0)&&(t.scale={x:r??1,y:o??r??1,z:a??1}),t.rotation=kt(n.rotation??n.angle)}if(e==="SPLINE"){const r=we(n.controlPoints??n.control_points??n.points);r.length&&(t.controlPoints=r);const o=we(n.fitPoints??n.fit_points);o.length&&(t.fitPoints=o)}return e==="HATCH"&&(t.loops=Vn(n),t.fillColorIndex=t.colorIndex),(e==="SOLID"||e==="TRACE"||e==="3DFACE")&&(t.vertices=$n(n),t.fillColorIndex=t.colorIndex),t}function Un(n){const e={},t=n.tables,i=n.layers??(t==null?void 0:t.layer)??(t==null?void 0:t.LAYER)??(t==null?void 0:t.layers),s=Hn(i);for(const r of s){const o=r,a=M(o.name??o.layerName);a&&Re(e,{name:a,color:o.color??o.colorNumber??o.colorIndex,colorIndex:y(o.colorNumber??o.colorIndex??o.color),lineType:M(o.lineType??o.linetype),isVisible:Number(o.colorNumber??o.colorIndex??o.color??1)>=0,isFrozen:!!o.frozen,isLocked:!!o.locked,raw:o})}return e[0]||Re(e,{name:"0",colorIndex:7,isVisible:!0}),e}function _n(n){const e={},t=n.blocks;if(!t||typeof t!="object")return e;if(Array.isArray(t))for(const i of t)St(e,i);else for(const[i,s]of Object.entries(t))St(e,s,i);return e}function St(n,e,t){if(!e||typeof e!="object")return;const i=e,s=M(i.name??i.blockName??t);if(!s)return;const o=(Array.isArray(i.entities)?i.entities:[]).filter(a=>!!a&&typeof a=="object").map(a=>Ye(a));bt(n,{name:s,basePoint:E(i.basePoint??i.position)??{x:0,y:0},entities:o,raw:i})}function Hn(n){if(!n)return[];if(Array.isArray(n))return n;if(typeof n!="object")return[];const e=n;return Array.isArray(e.entries)?e.entries:Array.isArray(e.records)?e.records:Array.isArray(e.layers)?e.layers:Object.values(e).filter(t=>t&&typeof t=="object")}function we(n){return Array.isArray(n)?n.map(E).filter(e=>!!e):[]}function $n(n){const e=we(n.vertices??n.points);if(e.length)return e;const t=[];for(let i=0;i<4;i++){const s=E({x:n[`x${i}`]??n[`x${i+1}`],y:n[`y${i}`]??n[`y${i+1}`],z:n[`z${i}`]??n[`z${i+1}`]});s&&t.push(s)}return t}function Vn(n){const e=n.boundaryLoops??n.loops??n.paths;if(Array.isArray(e))return e.map(t=>{const i=t;return{vertices:we(i.vertices??i.points),isClosed:!0}}).filter(t=>t.vertices&&t.vertices.length>0)}function kt(n){const e=y(n);if(e!==void 0)return Math.abs(e)>Math.PI*2+1e-6?V(e):e}function Nt(n){const e=y(n);if(e!==void 0)return Math.abs(e)>Math.PI*2+1e-6?V(e):e}function Gn(n,e){const t=Xe(e);if(t)return G(n,t);const i=jn(n);if(i)return G(n,i);const s=Xe(qn(n));if(s)return G(n,s);const r=G(n,"utf-8");return r.includes("�")?Zn(n):r}const Mt={ANSI_874:"windows-874",ANSI_932:"shift_jis",ANSI_936:"gb18030",ANSI_949:"euc-kr",ANSI_950:"big5",ANSI_1250:"windows-1250",ANSI_1251:"windows-1251",ANSI_1252:"windows-1252",ANSI_1253:"windows-1253",ANSI_1254:"windows-1254",ANSI_1255:"windows-1255",ANSI_1256:"windows-1256",ANSI_1257:"windows-1257",ANSI_1258:"windows-1258",BIG5:"big5",CP874:"windows-874",CP932:"shift_jis",CP936:"gb18030",CP949:"euc-kr",CP950:"big5",CP1250:"windows-1250",CP1251:"windows-1251",CP1252:"windows-1252",CP1253:"windows-1253",CP1254:"windows-1254",CP1255:"windows-1255",CP1256:"windows-1256",CP1257:"windows-1257",CP1258:"windows-1258",GB18030:"gb18030",GB2312:"gb18030",GBK:"gb18030",SHIFT_JIS:"shift_jis",SHIFTJIS:"shift_jis",SJIS:"shift_jis",UTF8:"utf-8",UTF_8:"utf-8",UTF16:"utf-16le",UTF_16:"utf-16le",UTF16LE:"utf-16le",UTF_16LE:"utf-16le",UTF16BE:"utf-16be",UTF_16BE:"utf-16be"};function jn(n){if(n.length>=3&&n[0]===239&&n[1]===187&&n[2]===191)return"utf-8";if(n.length>=2&&n[0]===255&&n[1]===254)return"utf-16le";if(n.length>=2&&n[0]===254&&n[1]===255)return"utf-16be"}function qn(n){var i,s,r,o;const t=G(n.subarray(0,Math.min(n.byteLength,131072)),"iso-8859-1").replace(/\r\n/g,`
3
3
  `).replace(/\r/g,`
4
4
  `).split(`
5
- `);for(let a=0;a<n.length-3;a++)if(!(((r=n[a])==null?void 0:r.trim())!=="9"||((i=n[a+1])==null?void 0:i.trim().toUpperCase())!=="$DWGCODEPAGE"))for(let c=a+2;c<Math.min(a+10,n.length-1);c+=2){const l=(o=n[c])==null?void 0:o.trim(),f=(s=n[c+1])==null?void 0:s.trim();if(l==="3"&&f)return f}}function Se(t){const e=t==null?void 0:t.trim();if(!e)return;const n=e.replace(/[-\s]+/g,"_").toUpperCase();if(at[n])return at[n];const r=/^ANSI_(\d{3,4})$/.exec(n);if(r)return Se(`cp${r[1]}`);const i=/^CP(\d{3,4})$/.exec(n);return i?i[1]==="936"?"gb18030":i[1]==="950"?"big5":i[1]==="932"?"shift_jis":i[1]==="949"?"euc-kr":`windows-${i[1]}`:e}function z(t,e){try{return new TextDecoder(e,{fatal:!1}).decode(t)}catch{return new TextDecoder("utf-8",{fatal:!1}).decode(t)}}function nn(t){const e=["windows-1252","gb18030","big5","shift_jis","euc-kr","iso-8859-1"];let n="",r=Number.POSITIVE_INFINITY;for(const i of e){const o=z(t,i),s=rn(o,i);s<r&&(r=s,n=o)}return n||z(t,"utf-8")}function rn(t,e){const n=Ne(t,/\uFFFD/g),r=Ne(t,/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g),i=Ne(t,/[\u3400-\u9FFF\uF900-\uFAFF]/g),o=t.includes("SECTION")&&(t.includes("ENTITIES")||t.includes("HEADER"));let s=n*1e4+r*1e3;return o&&(s-=500),e==="windows-1252"&&(s-=2),e==="gb18030"&&i>=2&&(s-=50+Math.min(i,200)*2),s}function Ne(t,e){var n;return((n=t.match(e))==null?void 0:n.length)??0}function sn(t){const e=P(t);if(e!==void 0)return e.replace(/\\U\+([0-9a-fA-F]{4,6})/g,(n,r)=>{const i=Number.parseInt(r,16);return Number.isFinite(i)&&i>=0&&i<=1114111?String.fromCodePoint(i):n}).replace(/%%[cC]/g,"∅").replace(/%%[dD]/g,"°").replace(/%%[pP]/g,"±").replace(/\\P/g,`
6
- `)}function on(t){var l,f;const e=t.replace(/\r\n/g,`
5
+ `);for(let a=0;a<t.length-3;a++)if(!(((i=t[a])==null?void 0:i.trim())!=="9"||((s=t[a+1])==null?void 0:s.trim().toUpperCase())!=="$DWGCODEPAGE"))for(let c=a+2;c<Math.min(a+10,t.length-1);c+=2){const h=(r=t[c])==null?void 0:r.trim(),l=(o=t[c+1])==null?void 0:o.trim();if(h==="3"&&l)return l}}function Xe(n){const e=n==null?void 0:n.trim();if(!e)return;const t=e.replace(/[-\s]+/g,"_").toUpperCase();if(Mt[t])return Mt[t];const i=/^ANSI_(\d{3,4})$/.exec(t);if(i)return Xe(`cp${i[1]}`);const s=/^CP(\d{3,4})$/.exec(t);return s?s[1]==="936"?"gb18030":s[1]==="950"?"big5":s[1]==="932"?"shift_jis":s[1]==="949"?"euc-kr":`windows-${s[1]}`:e}function G(n,e){try{return new TextDecoder(e,{fatal:!1}).decode(n)}catch{return new TextDecoder("utf-8",{fatal:!1}).decode(n)}}function Zn(n){const e=["windows-1252","gb18030","big5","shift_jis","euc-kr","iso-8859-1"];let t="",i=Number.POSITIVE_INFINITY;for(const s of e){const r=G(n,s),o=Kn(r,s);o<i&&(i=o,t=r)}return t||G(n,"utf-8")}function Kn(n,e){const t=ze(n,/\uFFFD/g),i=ze(n,/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g),s=ze(n,/[\u3400-\u9FFF\uF900-\uFAFF]/g),r=n.includes("SECTION")&&(n.includes("ENTITIES")||n.includes("HEADER"));let o=t*1e4+i*1e3;return r&&(o-=500),e==="windows-1252"&&(o-=2),e==="gb18030"&&s>=2&&(o-=50+Math.min(s,200)*2),o}function ze(n,e){var t;return((t=n.match(e))==null?void 0:t.length)??0}function Jn(n){const e=M(n);if(e!==void 0)return e.replace(/\\U\+([0-9a-fA-F]{4,6})/g,(t,i)=>{const s=Number.parseInt(i,16);return Number.isFinite(s)&&s>=0&&s<=1114111?String.fromCodePoint(s):t}).replace(/%%[cC]/g,"∅").replace(/%%[dD]/g,"°").replace(/%%[pP]/g,"±").replace(/\\P/g,`
6
+ `)}function Qn(n){var h,l;const e=n.replace(/\r\n/g,`
7
7
  `).replace(/\r/g,`
8
8
  `).split(`
9
- `),n=[];for(let h=0;h<e.length-1;h+=2){const d=Number((l=e[h])==null?void 0:l.trim()),m=e[h+1]??"";Number.isFinite(d)&&n.push({code:d,value:m.trimEnd()})}const r=[],i={};let o="",s=[],a;for(let h=0;h<n.length;h++){const d=n[h];if(d.code===0&&d.value==="SECTION"){o=((f=n[h+1])==null?void 0:f.code)===2?n[h+1].value.toUpperCase():"",h++;continue}if(d.code===0&&d.value==="ENDSEC"){c(),o="";continue}o==="ENTITIES"&&(d.code===0?(c(),s=[d]):s.push(d))}return c(),{header:{},tables:{},entities:r,blocks:i};function c(){var m;if(!s.length)return;const h=(m=s[0])==null?void 0:m.value.toUpperCase();if(h==="VERTEX"&&a){const g=E(s,10,20,30);g&&(a.vertices??(a.vertices=[])).push({...g,bulge:w(s,42)}),s=[];return}if(h==="SEQEND"){a&&r.push(a),a=void 0,s=[];return}if(a&&(r.push(a),a=void 0),!h||h==="EOF"){s=[];return}const d=an(h,s);h==="POLYLINE"?a=d:r.push(d),s=[]}}function an(t,e){const n={type:t,handle:ee(e,5),layer:ee(e,8)??"0",colorIndex:w(e,62),trueColor:w(e,420),lineType:ee(e,6),lineweight:w(e,370)};switch(t){case"LINE":Object.assign(n,{startPoint:E(e,10,20,30),endPoint:E(e,11,21,31)});break;case"CIRCLE":Object.assign(n,{center:E(e,10,20,30),radius:w(e,40)});break;case"ARC":Object.assign(n,{center:E(e,10,20,30),radius:w(e,40),startAngle:he(w(e,50)),endAngle:he(w(e,51))});break;case"POINT":Object.assign(n,{point:E(e,10,20,30)});break;case"TEXT":case"MTEXT":Object.assign(n,{insertionPoint:E(e,10,20,30),text:fn(e),textHeight:w(e,40),rotation:he(w(e,50))});break;case"LWPOLYLINE":Object.assign(n,{vertices:ln(e),flag:w(e,70),isClosed:(Number(w(e,70)??0)&1)===1});break;case"POLYLINE":Object.assign(n,{vertices:[],flag:w(e,70),isClosed:(Number(w(e,70)??0)&1)===1});break;case"ELLIPSE":Object.assign(n,{center:E(e,10,20,30),majorAxisEndPoint:E(e,11,21,31),axisRatio:w(e,40),startAngle:w(e,41),endAngle:w(e,42)});break;case"SPLINE":Object.assign(n,{controlPoints:cn(e,10,20,30),degree:w(e,71),isClosed:(Number(w(e,70)??0)&1)===1});break;case"INSERT":Object.assign(n,{name:ee(e,2),blockName:ee(e,2),insertionPoint:E(e,10,20,30),rotation:he(w(e,50)),scale:{x:w(e,41)??1,y:w(e,42)??w(e,41)??1,z:w(e,43)??1}});break;case"SOLID":case"TRACE":case"3DFACE":Object.assign(n,{vertices:[E(e,10,20,30),E(e,11,21,31),E(e,12,22,32),E(e,13,23,33)].filter(Boolean)});break}return ke(n)}function w(t,e){var i;const n=(i=t.find(o=>o.code===e))==null?void 0:i.value,r=Number(n);return Number.isFinite(r)?r:void 0}function ee(t,e){var r;const n=(r=t.find(i=>i.code===e))==null?void 0:r.value;return n&&n.length>0?n:void 0}function E(t,e,n,r){const i=w(t,e),o=w(t,n),s=w(t,r);if(!(i===void 0||o===void 0))return s===void 0?{x:i,y:o}:{x:i,y:o,z:s}}function cn(t,e,n,r){const i=[];for(let o=0;o<t.length;o++){if(t[o].code!==e)continue;const s=Number(t[o].value),a=t.slice(o+1).find(h=>h.code===n),c=t.slice(o+1).find(h=>h.code===r),l=Number(a==null?void 0:a.value),f=Number(c==null?void 0:c.value);Number.isFinite(s)&&Number.isFinite(l)&&i.push(Number.isFinite(f)?{x:s,y:l,z:f}:{x:s,y:l})}return i}function ln(t){const e=[];for(let n=0;n<t.length;n++){if(t[n].code!==10)continue;const r=Number(t[n].value);let i,o;for(let s=n+1;s<t.length&&t[s].code!==10;s++)t[s].code===20&&(i=Number(t[s].value)),t[s].code===42&&(o=Number(t[s].value));Number.isFinite(r)&&Number.isFinite(i)&&e.push({x:r,y:i,bulge:Number.isFinite(o)?o:void 0})}return e}function fn(t){const e=t.filter(n=>n.code===1||n.code===3).map(n=>n.value);return e.length?e.join(""):void 0}function he(t){return typeof t=="number"&&Number.isFinite(t)?W(t):void 0}class ct{constructor(e={}){u(this,"id","dwf");u(this,"label","DWF/DWFx native viewer powered by dwf-viewer");u(this,"formats",["dwf","dwfx","xps"]);u(this,"nativeRenderer",!0);u(this,"defaults");u(this,"native");u(this,"host");u(this,"lastStats");this.defaults=e}accepts(e,n){const r=X(e);if(r==="dwf"||r==="dwfx"||r==="xps")return!0;const i=R(e,n);return i==="dwf"||i==="dwfx"||i==="xps"}async load(e,n={}){var h,d,m,g;const r={...this.defaults,...n},i=performance.now(),o=e.fileName??((h=e.file)==null?void 0:h.name),s=await T(e),a=ht(R(e,s),X(e));(d=r.onProgress)==null||d.call(r,{phase:"parse",format:a,message:"Opening DWF/DWFx with dwf-viewer…",percent:48});const c=await M.openDwfDocument(s,{fileName:o});(m=r.onProgress)==null||m.call(r,{phase:"normalize",format:a,message:"Reading DWF pages, sheets and model metadata…",percent:76});const l=lt(c,o,a,r.keepRaw===!0),f=performance.now()-i;return(g=r.onProgress)==null||g.call(r,{phase:"done",format:l.format,message:"DWF/DWFx document ready.",percent:100,elapsedMs:f}),{document:l,raw:r.keepRaw?c:void 0,bytes:s.byteLength,elapsedMs:f,format:l.format,warnings:l.warnings}}async mount(e,n,r={}){var y,x,L,D,A;const i={...this.defaults,...r},o=performance.now(),s=e.fileName??((y=e.file)==null?void 0:y.name),a=await T(e),c=ht(R(e,a),X(e)),l=pn(i),f=dt(i),h=gn(i,l,f),d=ut(i,l,f);(x=i.onProgress)==null||x.call(i,{phase:"native-render",format:c,message:"Mounting native DWF renderer…",percent:28}),this.unmount(),this.host=n,n.replaceChildren(),this.native=new M.DwfViewer(n,h),(L=i.onProgress)==null||L.call(i,{phase:"parse",format:c,message:"Parsing DWF package and page streams…",percent:58}),await this.native.load(a,{fileName:s,...d}),(D=i.onProgress)==null||D.call(i,{phase:"render",format:c,message:"Rendering DWF/DWFx with dwf-viewer…",percent:88}),this.lastStats=await this.native.render();const m=this.native.getDocument(),g=lt(m,s,c,i.keepRaw===!0);g.metadata.loaderMode="Native DWF",g.metadata.nativeRenderer="dwf-viewer",g.metadata.nativeRenderStats=this.lastStats?{...this.lastStats,warnings:this.lastStats.warnings.length}:void 0;const S=performance.now()-o;return(A=i.onProgress)==null||A.call(i,{phase:"done",format:g.format,message:"DWF/DWFx rendered.",percent:100,elapsedMs:S}),{document:g,raw:i.keepRaw?m:void 0,bytes:a.byteLength,elapsedMs:S,format:g.format,warnings:g.warnings}}unmount(){var e;(e=this.native)==null||e.dispose(),this.native=void 0,this.lastStats=void 0,this.host&&this.host.replaceChildren()}fit(){var e;(e=this.native)==null||e.fit()}zoomIn(){var n;const e=(n=this.native)==null?void 0:n.zoomInButton;e==null||e.click()}zoomOut(){var n;const e=(n=this.native)==null?void 0:n.zoomOutButton;e==null||e.click()}resize(){var e;(e=this.native)==null||e.render()}setNativeOptions(e){var r,i,o,s;const n=this.native;if(n){if(typeof e.dwfBackground=="string")n.background=e.dwfBackground;else{const a=dt(e);a&&(n.background=a)}typeof e.dwfPreferWebgl=="boolean"&&((r=n.setPreferWebgl)==null||r.call(n,e.dwfPreferWebgl)),typeof e.dwfPreferWasm=="boolean"&&((i=n.setPreferWasm)==null||i.call(n,e.dwfPreferWasm)),e.dwfLineWeightMode&&((o=n.setLineWeightMode)==null||o.call(n,e.dwfLineWeightMode)),de(n,"minStrokeCssPx",e.dwfMinStrokeCssPx),de(n,"maxOverviewStrokeCssPx",e.dwfMaxOverviewStrokeCssPx),de(n,"minTextCssPx",e.dwfMinTextCssPx),de(n,"minFilledAreaCssPx",e.dwfMinFilledAreaCssPx),(s=n.render)==null||s.call(n)}}getLastNativeStats(){return this.lastStats}}function lt(t,e,n,r){var a,c;const i=ft((t==null?void 0:t.diagnostics)??[]),o=((t==null?void 0:t.pageData)??[]).map((l,f)=>hn(l,f));for(const l of(t==null?void 0:t.pageData)??[])i.push(...ft(l.diagnostics));const s={parser:"dwf-viewer",nativeRenderer:"dwf-viewer",dwfKind:t==null?void 0:t.kind,packageEntries:((a=t==null?void 0:t.packageEntries)==null?void 0:a.length)??0,resources:((c=t==null?void 0:t.resources)==null?void 0:c.length)??0,pageKinds:vn(((t==null?void 0:t.pageData)??[]).map(l=>l.kind)),pageNames:((t==null?void 0:t.pages)??[]).map(l=>l.name)};return ae({format:n,sourceName:e,layers:{},blocks:{},pages:o,entities:Xt(o),metadata:s,warnings:wn(i),raw:r?t:void 0})}function hn(t,e){const n=dn(t,e);return{index:e,name:t.name||t.sourcePath||`${e+1}`,width:t.width||1e3,height:t.height||1e3,entities:n}}function dn(t,e){return t.kind==="w2d-text"?t.primitives.flatMap((n,r)=>un(n,e,r)):t.kind==="image"?[{type:"DWF_IMAGE_PAGE",kind:"image",pageIndex:e,width:t.width,height:t.height,imageSource:t.sourcePath}]:t.kind==="w3d-model"?t.model.meshes.map((n,r)=>({id:n.id,type:"W3D_MESH",kind:"solid",pageIndex:e,color:n.color?yn(n.color):void 0,name:n.name||`mesh-${r+1}`,raw:{vertexCount:n.vertexCount,triangleCount:n.triangleCount,materialId:n.materialId}})):t.kind==="xps-fixed-page"?[{type:"XPS_FIXED_PAGE",kind:"viewport",pageIndex:e,width:t.width,height:t.height,raw:{sourcePath:t.sourcePath}}]:[{type:"DWF_PAGE",kind:"viewport",pageIndex:e,width:t.width,height:t.height,raw:{sourcePath:t.sourcePath}}]}function un(t,e,n){const r={id:`dwf-${e}-${n}`,pageIndex:e,color:t.stroke,fillColor:t.fill,lineweight:t.lineWidth,raw:{matrix:t.matrix}};if(t.type==="polyline"||t.type==="polygon")return[{...r,type:t.type==="polygon"?"DWF_POLYGON":"DWF_POLYLINE",kind:"polyline",vertices:mn(t.points),isClosed:t.type==="polygon"}];if(t.type==="path")return[{...r,type:"DWF_PATH",kind:"path",commands:t.commands}];if(t.type==="text")return[{...r,type:"DWF_TEXT",kind:"text",insertionPoint:{x:t.x,y:t.y,z:0},text:t.text,textHeight:t.size}];if(t.type==="rect"){const i=t.x,o=t.y,s=t.width,a=t.height;return[{...r,type:"DWF_RECT",kind:"polyline",isClosed:!0,vertices:[{x:i,y:o,z:0},{x:i+s,y:o,z:0},{x:i+s,y:o+a,z:0},{x:i,y:o+a,z:0}]}]}return[]}function mn(t){const e=[];for(let n=0;n+1<t.length;n+=2)e.push({x:t[n],y:t[n+1],z:0});return e}function ft(t){return t.filter(e=>e.level!=="info").map(e=>`${e.code}: ${e.message}${e.source?` (${e.source})`:""}`)}function ht(t,e){return e==="dwf"||e==="dwfx"||e==="xps"?e:t==="dwf"||t==="dwfx"||t==="xps"?t:"dwf"}function pn(t){if(t.dwfWasmUrl)return t.dwfWasmUrl;if(typeof document>"u")return;const e=t.wasmPath?new URL(bn(t.wasmPath),document.baseURI).href:new URL("wasm/",document.baseURI).href;return new URL("dwfv-render.wasm",e).href}function dt(t){if(t.dwfBackground)return t.dwfBackground;const e=t.canvasOptions;return(e==null?void 0:e.background)??"#05070d"}function gn(t,e,n){return{...ut(t,e,n),maxDevicePixelRatio:t.dwfMaxDevicePixelRatio??2,maxCanvasPixels:t.dwfMaxCanvasPixels??16777216}}function ut(t,e,n){return{wasmUrl:e,preferWebgl:t.dwfPreferWebgl??!0,preferWasm:t.dwfPreferWasm??!0,background:n,maxGpuCacheBytes:t.dwfMaxGpuCacheBytes??160*1024*1024,maxCachedScenes:t.dwfMaxCachedScenes??2,lineWeightMode:t.dwfLineWeightMode??"adaptive",minStrokeCssPx:t.dwfMinStrokeCssPx,maxOverviewStrokeCssPx:t.dwfMaxOverviewStrokeCssPx,minTextCssPx:t.dwfMinTextCssPx,minFilledAreaCssPx:t.dwfMinFilledAreaCssPx}}function de(t,e,n){typeof n=="number"&&Number.isFinite(n)&&(t[e]=n)}function bn(t){return t.endsWith("/")?t:`${t}/`}function yn(t){const[e,n,r]=t.map(i=>Math.max(0,Math.min(255,Math.round(i*255))));return`#${Me(e)}${Me(n)}${Me(r)}`}function Me(t){return t.toString(16).padStart(2,"0")}function vn(t){const e={};for(const n of t)e[n]=(e[n]??0)+1;return e}function wn(t){return Array.from(new Set(t))}function mt(t={}){return new je([new Ke(t),new rt(t),new ct(t)])}function pt(t){const e=t;return e.nativeRenderer===!0&&typeof e.mount=="function"}const xn={1:"#ff0000",2:"#ffff00",3:"#00ff00",4:"#00ffff",5:"#0000ff",6:"#ff00ff",8:"#808080",9:"#c0c0c0",10:"#ff0000",11:"#ff7f7f",12:"#a50000",13:"#a55252",14:"#7f0000",15:"#7f3f3f",16:"#4c0000",17:"#4c2626",18:"#260000",19:"#261313",20:"#ff3f00",21:"#ff9f7f",22:"#a52900",23:"#a56752",24:"#7f1f00",25:"#7f4f3f",26:"#4c1300",27:"#4c2f26",28:"#260900",29:"#261713",30:"#ff7f00",31:"#ffbf7f",32:"#a55200",33:"#a57c52",34:"#7f3f00",35:"#7f5f3f",36:"#4c2600",37:"#4c3926",38:"#261300",39:"#261c13",40:"#ffbf00",41:"#ffdf7f",42:"#a57c00",43:"#a59152",44:"#7f5f00",45:"#7f6f3f",46:"#4c3900",47:"#4c4226",48:"#261c00",49:"#262113",50:"#ffff00",51:"#ffff7f",52:"#a5a500",53:"#a5a552",54:"#7f7f00",55:"#7f7f3f",56:"#4c4c00",57:"#4c4c26",58:"#262600",59:"#262613",60:"#bfff00",61:"#dfff7f",62:"#7ca500",63:"#91a552",64:"#5f7f00",65:"#6f7f3f",66:"#394c00",67:"#424c26",68:"#1c2600",69:"#212613",70:"#7fff00",71:"#bfff7f",72:"#52a500",73:"#7ca552",74:"#3f7f00",75:"#5f7f3f",76:"#264c00",77:"#394c26",78:"#132600",79:"#1c2613",80:"#3fff00",81:"#9fff7f",82:"#29a500",83:"#67a552",84:"#1f7f00",85:"#4f7f3f",86:"#134c00",87:"#2f4c26",88:"#092600",89:"#172613",90:"#00ff00",91:"#7fff7f",92:"#00a500",93:"#52a552",94:"#007f00",95:"#3f7f3f",96:"#004c00",97:"#264c26",98:"#002600",99:"#132613",100:"#00ff3f",101:"#7fff9f",102:"#00a529",103:"#52a567",104:"#007f1f",105:"#3f7f4f",106:"#004c13",107:"#264c2f",108:"#002609",109:"#132617",110:"#00ff7f",111:"#7fffbf",112:"#00a552",113:"#52a57c",114:"#007f3f",115:"#3f7f5f",116:"#004c26",117:"#264c39",118:"#002613",119:"#13261c",120:"#00ffbf",121:"#7fffdf",122:"#00a57c",123:"#52a591",124:"#007f5f",125:"#3f7f6f",126:"#004c39",127:"#264c42",128:"#00261c",129:"#132621",130:"#00ffff",131:"#7fffff",132:"#00a5a5",133:"#52a5a5",134:"#007f7f",135:"#3f7f7f",136:"#004c4c",137:"#264c4c",138:"#002626",139:"#132626",140:"#00bfff",141:"#7fdfff",142:"#007ca5",143:"#5291a5",144:"#005f7f",145:"#3f6f7f",146:"#00394c",147:"#26424c",148:"#001c26",149:"#132126",150:"#007fff",151:"#7fbfff",152:"#0052a5",153:"#527ca5",154:"#003f7f",155:"#3f5f7f",156:"#00264c",157:"#26394c",158:"#001326",159:"#131c26",160:"#003fff",161:"#7f9fff",162:"#0029a5",163:"#5267a5",164:"#001f7f",165:"#3f4f7f",166:"#00134c",167:"#262f4c",168:"#000926",169:"#131726",170:"#0000ff",171:"#7f7fff",172:"#0000a5",173:"#5252a5",174:"#00007f",175:"#3f3f7f",176:"#00004c",177:"#26264c",178:"#000026",179:"#131326",180:"#3f00ff",181:"#9f7fff",182:"#2900a5",183:"#6752a5",184:"#1f007f",185:"#4f3f7f",186:"#13004c",187:"#2f264c",188:"#090026",189:"#171326",190:"#7f00ff",191:"#bf7fff",192:"#5200a5",193:"#7c52a5",194:"#3f007f",195:"#5f3f7f",196:"#26004c",197:"#39264c",198:"#130026",199:"#1c1326",200:"#bf00ff",201:"#df7fff",202:"#7c00a5",203:"#9152a5",204:"#5f007f",205:"#6f3f7f",206:"#39004c",207:"#42264c",208:"#1c0026",209:"#211326",210:"#ff00ff",211:"#ff7fff",212:"#a500a5",213:"#a552a5",214:"#7f007f",215:"#7f3f7f",216:"#4c004c",217:"#4c264c",218:"#260026",219:"#261326",220:"#ff00bf",221:"#ff7fdf",222:"#a5007c",223:"#a55291",224:"#7f005f",225:"#7f3f6f",226:"#4c0039",227:"#4c2642",228:"#26001c",229:"#261321",230:"#ff007f",231:"#ff7fbf",232:"#a50052",233:"#a5527c",234:"#7f003f",235:"#7f3f5f",236:"#4c0026",237:"#4c2639",238:"#260013",239:"#26131c",240:"#ff003f",241:"#ff7f9f",242:"#a50029",243:"#a55267",244:"#7f001f",245:"#7f3f4f",246:"#4c0013",247:"#4c262f",248:"#260009",249:"#261317",250:"#333333",251:"#505050",252:"#696969",253:"#828282",254:"#bebebe",255:"#ffffff"};function F(t,e="#ffffff",n=e){if(typeof t!="number"||Number.isNaN(t))return e;const r=Math.abs(Math.trunc(t));return r===0||r===256||r===257?e:r===7?n:xn[r]??e}function G(t,e="rgb"){const n=Math.max(0,Math.trunc(t))&16777215,r=n>>16&255,i=n>>8&255,o=n&255;return`rgb(${e==="rgb"?r:o}, ${i}, ${e==="rgb"?o:r})`}function Z(t){if(typeof t=="string"){const e=t.trim();return e?/^(#|rgb\(|rgba\(|hsl\(|hsla\()/i.test(e)?Cn(e)??e:{red:"#ff0000",yellow:"#ffff00",green:"#00ff00",cyan:"#00ffff",blue:"#0000ff",magenta:"#ff00ff",white:"#ffffff",black:"#000000",grey:"#808080",gray:"#808080"}[e.toLowerCase()]:void 0}if(t&&typeof t=="object"){const e=t,n=Number(e.r??e.red),r=Number(e.g??e.green),i=Number(e.b??e.blue),o=Number(e.a??e.alpha??1);if([n,r,i].every(Number.isFinite))return Number.isFinite(o)&&o>=0&&o<1?`rgba(${n}, ${r}, ${i}, ${o})`:`rgb(${n}, ${r}, ${i})`}}function Cn(t){if(!t)return;const e=t.trim();if(/^#[0-9a-f]{8}$/i.test(e)){const n=parseInt(e.slice(1,3),16)/255,r=parseInt(e.slice(3,5),16),i=parseInt(e.slice(5,7),16),o=parseInt(e.slice(7,9),16);return n>=.999?`rgb(${r}, ${i}, ${o})`:`rgba(${r}, ${i}, ${o}, ${Ae(n)})`}if(/^#[0-9a-f]{6}$/i.test(e)||/^#[0-9a-f]{3}$/i.test(e))return e;if(/^sc#/i.test(e)){const n=e.slice(3).split(",").map(a=>Number(a.trim())),[r,i,o,s]=n.length===4?n:[1,...n];if([r,i,o,s].every(Number.isFinite))return`rgba(${Math.round(i*255)}, ${Math.round(o*255)}, ${Math.round(s*255)}, ${Ae(r)})`}}function _(t,e,n={}){const r=n.foreground??"#ffffff",i=r;let o;const s=Z(t.trueColor)??Z(t.color)??Z(t.colorName);if(s&&(o=s),!o){const a=En(t,["trueColor","true_color","truecolor","colorRGB","colorRgb","rgbColor","rgb"]);typeof a=="number"&&a>=0&&a<=16777215&&(o=G(a,n.trueColorByteOrder??"rgb"))}if(!o){const a=vt(t.colorIndex,t.colorNumber,t.aci);typeof a=="number"&&Math.abs(a)<=257&&a!==256&&a!==0&&a!==257&&(o=F(a,i,r))}if(!o&&typeof t.color=="number"){const a=Number(t.color);Math.abs(a)<=257?a!==0&&a!==256&&a!==257&&(o=F(a,i,r)):o=G(a,n.trueColorByteOrder??"rgb")}if(!o){const a=Mn(e,t.layer);o=kn(a,n)}return gt(o??i,n)}function Ee(t,e,n={}){let r;const i=Z(t.fillColor);if(i&&(r=i),!r&&typeof t.fillColor=="number"){const o=t.fillColor;r=Math.abs(o)<=257?F(o,n.foreground??"#ffffff",n.foreground??"#ffffff"):G(o,n.trueColorByteOrder??"rgb")}return!r&&typeof t.fillColorIndex=="number"&&(r=F(t.fillColorIndex,n.foreground??"#ffffff",n.foreground??"#ffffff")),r?gt(r,n):void 0}function gt(t,e={}){if(e.contrastMode!=="adaptive")return t;const n=e.background??"#0b1020",r=e.foreground??"#ffffff";return Pn(t,n,r,e.minColorContrast??2.4)}function Pn(t,e,n,r=2.4){const i=Le(n)??{r:255,g:255,b:255,a:1},o=Le(e)??{r:11,g:16,b:32,a:1},s=Le(t);if(!s)return t;const a=wt(s,o);if(Te(a,o)>=r)return t;const c=Ie(o),l=c<.5?{r:255,g:255,b:255,a:s.a}:{r:0,g:0,b:0,a:s.a};for(const f of[.25,.4,.55,.7,.85,1]){const h=Ln(s,l,f);if(Te(wt(h,o),o)>=r)return xt(h)}return Te(i,o)>=r?xt(i):c<.5?"#ffffff":"#000000"}function bt(t){return t?t.isVisible!==!1&&t.isFrozen!==!0:!0}function kn(t,e){if(!t)return;const n=e.foreground??"#ffffff",r=Z(t.trueColor);if(r)return r;if(typeof t.trueColor=="number"&&t.trueColor>=0&&t.trueColor<=16777215)return G(t.trueColor,e.trueColorByteOrder??"rgb");const i=Z(t.color);if(i)return i;if(Nn(t.colorIndex))return F(t.colorIndex,n,n);if(typeof t.color=="number"){const o=Number(t.color);return Math.abs(o)<=257?F(o,n,n):G(o,e.trueColorByteOrder??"rgb")}if(typeof t.colorIndex=="number")return F(t.colorIndex,n,n)}function Sn(t){return vt(t.colorIndex,t.colorNumber,t.aci)===0?!0:t.trueColor===void 0&&t.color===0}function yt(t,e,n,r={}){if(!Sn(t))return t;const i=_(e,n,r);return{...t,color:i,trueColor:void 0,colorIndex:void 0,colorNumber:void 0}}function Nn(t){return typeof t=="number"&&Number.isFinite(t)&&Math.abs(Math.trunc(t))>=1&&Math.abs(Math.trunc(t))<=255}function Mn(t,e){if(!(!t||!e))return t.layers[e]??t.layers[e.toLowerCase()]??Object.values(t.layers).find(n=>n.name.toLowerCase()===e.toLowerCase())}function vt(...t){for(const e of t)if(typeof e=="number"&&Number.isFinite(e))return e}function En(t,e){const n=t;for(const r of e){const i=n[r];if(typeof i=="number"&&Number.isFinite(i))return i}}function Le(t){const e=t.trim().toLowerCase();if(/^#[0-9a-f]{3}$/i.test(e))return{r:parseInt(e[1]+e[1],16),g:parseInt(e[2]+e[2],16),b:parseInt(e[3]+e[3],16),a:1};if(/^#[0-9a-f]{6}$/i.test(e))return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16),a:1};const n=e.match(/^rgba?\(([^)]+)\)$/i);if(n){const r=n[1].split(/[,\s/]+/).filter(Boolean).map(i=>Number(i.replace("%","")));if(r.length>=3&&r.slice(0,3).every(Number.isFinite)){const i=/%/.test(n[1]);return{r:q(i?r[0]*2.55:r[0]),g:q(i?r[1]*2.55:r[1]),b:q(i?r[2]*2.55:r[2]),a:Number.isFinite(r[3])?Math.max(0,Math.min(1,r[3])):1}}}}function wt(t,e){const n=t.a+e.a*(1-t.a);return n<=0?{r:0,g:0,b:0,a:0}:{r:(t.r*t.a+e.r*e.a*(1-t.a))/n,g:(t.g*t.a+e.g*e.a*(1-t.a))/n,b:(t.b*t.a+e.b*e.a*(1-t.a))/n,a:n}}function Ln(t,e,n){const r=Math.max(0,Math.min(1,n));return{r:t.r+(e.r-t.r)*r,g:t.g+(e.g-t.g)*r,b:t.b+(e.b-t.b)*r,a:t.a}}function Ie(t){const e=[t.r,t.g,t.b].map(n=>{const r=n/255;return r<=.03928?r/12.92:((r+.055)/1.055)**2.4});return .2126*e[0]+.7152*e[1]+.0722*e[2]}function Te(t,e){const n=Ie(t),r=Ie(e),i=Math.max(n,r),o=Math.min(n,r);return(i+.05)/(o+.05)}function xt(t){const e=q(t.r),n=q(t.g),r=q(t.b);return t.a<.999?`rgba(${e}, ${n}, ${r}, ${Ae(t.a)})`:`rgb(${e}, ${n}, ${r})`}function q(t){return Math.max(0,Math.min(255,Math.round(t)))}function Ae(t){return Math.round(t*1e3)/1e3}const Ct=1e5,Pt=new Set(["","bylayer","15"]),Be=new Set(["byblock","14"]),In=new Set(["continuous","16"]),K=t=>String(t??"").trim().toLowerCase();function Tn(t){return Be.has(K(t))}function Fe(t,e,n){if(!Tn(t.lineType))return t;const r=De(e,n);return{...t,lineType:r||"Continuous",lineTypeScale:te(t.lineTypeScale,1)*te(e.lineTypeScale,1)}}function De(t,e){var i;let n=String(t.lineType??"").trim();const r=K(n);return Pt.has(r)?n=((i=Rn(e,t.layer))==null?void 0:i.lineType)??"Continuous":Be.has(r)&&(n="Continuous"),n||"Continuous"}function ue(t,e){var h,d;if(!e)return;const n=De(t,e),r=K(n);if(In.has(r)||Pt.has(r)||Be.has(r))return;const i=Dn(e,n);if(!(i!=null&&i.pattern.length))return;const o=te(t.lineTypeScale,te((h=e.header)==null?void 0:h.CELTSCALE,1)),s=te((d=e.header)==null?void 0:d.LTSCALE,1)*o,a=Bn(i,s),c=a.reduce((m,g)=>m+g.length,0);if(!Number.isFinite(c)||c<=1e-9)return;const l=a.some(m=>!m.draw&&m.length>1e-12),f=a.some(m=>m.marker);if(!(!l&&!f))return{name:i.name,segments:Fn(a,l),runs:a,period:c}}function An(t,e,n){return me(t,e,n).segments}function me(t,e,n,r=Ct){const i=t.filter(y=>Number.isFinite(y.x)&&Number.isFinite(y.y));if(i.length<2||n.runs.length===0)return{segments:[],dots:[]};const o=[];for(let y=0;y<i.length-1;y++)o.push([i[y],i[y+1]]);e&&o.push([i[i.length-1],i[0]]);const s=Number.isFinite(r)?Math.max(1,Math.floor(r)):Ct,a=o.reduce((y,[x,L])=>y+Math.hypot(L.x-x.x,L.y-x.y),0),l=(n.period>1e-12?a/n.period:Number.POSITIVE_INFINITY)*Math.max(1,n.runs.length);if(!Number.isFinite(l)||l>s)return{segments:o,dots:[]};const f={segments:[],dots:[]};let h=0,d=n.runs[0].length,m=!0;const g=y=>{const x=f.dots[f.dots.length-1];x&&Math.hypot(x.x-y.x,x.y-y.y)<=1e-10||f.dots.push(y)},S=()=>{h=(h+1)%n.runs.length,d=n.runs[h].length,m=!0};for(const[y,x]of o){const L=x.x-y.x,D=x.y-y.y,A=Math.hypot(L,D);if(A<=1e-14)continue;let H=0;for(;H<A-1e-12;){let Ft=0;for(;d<=1e-12&&Ft<n.runs.length;){const U=n.runs[h];if(m&&U.marker){const re=H/A;g({x:y.x+L*re,y:y.y+D*re})}S(),Ft++}if(d<=1e-12)break;const Dt=n.runs[h];if(m){if(Dt.marker){const U=H/A;g({x:y.x+L*U,y:y.y+D*U})}m=!1}const ve=Math.min(d,A-H);if(Dt.draw&&ve>1e-12){const U=H/A,re=(H+ve)/A;f.segments.push([{x:y.x+L*U,y:y.y+D*U},{x:y.x+L*re,y:y.y+D*re}])}H+=ve,d-=ve,d<=1e-12&&S()}}return f}function Bn(t,e){const n=[];for(const r of t.pattern){const i=Number(r.length),o=Number(r.elementTypeFlag??0)!==0;Number.isFinite(i)&&n.push({draw:i>=0,length:Math.abs(i)*e,marker:i>=0&&(i===0||o)})}return n}function Fn(t,e){if(!e)return[];const n=[];for(const i of t){if(i.length<=1e-12)continue;const o=n[n.length-1];(o==null?void 0:o.draw)===i.draw?o.length+=i.length:n.push({draw:i.draw,length:i.length})}const r=[];for(const i of n){const o=r.length%2===0;i.draw!==o&&r.push(1e-9),r.push(i.length)}return r.length%2===1&&r.push(1e-9),r}function Dn(t,e){const n=K(e),r=t.lineTypes??{};return r[e]??r[n]??Object.values(r).find(i=>K(i.name)===n||K(i.handle)===n)}function Rn(t,e){if(!(!t||!e))return t.layers[e]??t.layers[e.toLowerCase()]??Object.values(t.layers).find(n=>n.name.toLowerCase()===e.toLowerCase())}function te(t,e){const n=Number(t);return Number.isFinite(n)&&n>0?n:e}const On={a:1,b:0,c:0,d:1,e:0,f:0};function pe(t,e){return{a:t.a*e.a+t.c*e.b,b:t.b*e.a+t.d*e.b,c:t.a*e.c+t.c*e.d,d:t.b*e.c+t.d*e.d,e:t.a*e.e+t.c*e.f+t.e,f:t.b*e.e+t.d*e.f+t.f}}function kt(t,e){return{a:1,b:0,c:0,d:1,e:t,f:e}}function St(t){const e=Math.cos(t),n=Math.sin(t);return{a:e,b:n,c:-n,d:e,e:0,f:0}}function Wn(t,e=t){return{a:t,b:0,c:0,d:e,e:0,f:0}}function I(t,e){return{x:t.x*e.a+t.y*e.c+e.e,y:t.x*e.b+t.y*e.d+e.f,z:"z"in t?t.z:void 0}}function Nt(t,e){if(t)return t.map(n=>({cmd:n.cmd,points:n.points.map(r=>I(r,e))}))}function ge(t,e={x:0,y:0}){const n=t.insertionPoint??{x:0,y:0},r=t.scale,i=Number(typeof r=="object"&&r?r.x??1:t.scaleX??1),o=Number(typeof r=="object"&&r?r.y??i:t.scaleY??i),s=Number(t.rotation??0);let a=kt(n.x,n.y);return a=pe(a,St(Number.isFinite(s)?s:0)),a=pe(a,Wn(Number.isFinite(i)?i:1,Number.isFinite(o)?o:1)),a=pe(a,kt(-e.x,-e.y)),a}function Y(t,e){const n={...t};if(t.startPoint&&(n.startPoint=I(t.startPoint,e)),t.endPoint&&(n.endPoint=I(t.endPoint,e)),t.center&&(n.center=I(t.center,e)),t.insertionPoint&&(n.insertionPoint=I(t.insertionPoint,e)),t.majorAxisEndPoint){const s=I({x:0,y:0},e),a=I(t.majorAxisEndPoint,e);n.majorAxisEndPoint={x:a.x-s.x,y:a.y-s.y,z:a.z}}t.vertices&&(n.vertices=t.vertices.map(s=>({...I(s,e),bulge:s.bulge,startWidth:s.startWidth,endWidth:s.endWidth}))),t.points&&(n.points=t.points.map(s=>I(s,e))),t.controlPoints&&(n.controlPoints=t.controlPoints.map(s=>I(s,e))),t.fitPoints&&(n.fitPoints=t.fitPoints.map(s=>I(s,e))),t.attribs&&(n.attribs=t.attribs.map(s=>Y(s,e))),t.commands&&(n.commands=Nt(t.commands,e)),t.loops&&(n.loops=t.loops.map(s=>{var a;return{...s,vertices:(a=s.vertices)==null?void 0:a.map(c=>I(c,e)),commands:Nt(s.commands,e)}}));const r=Math.sqrt(Math.abs(e.a*e.d-e.b*e.c));typeof t.radius=="number"&&Number.isFinite(r)&&(n.radius=t.radius*r);const i=Math.atan2(e.b,e.a),o=t.kind==="ellipse"||String(t.type??"").toUpperCase()==="ELLIPSE";return Number.isFinite(i)&&Math.abs(i)>1e-14&&((typeof t.rotation=="number"||t.kind==="text"||t.kind==="insert")&&(n.rotation=Number(t.rotation??0)+i),!o&&typeof t.startAngle=="number"&&(n.startAngle=t.startAngle+i),!o&&typeof t.endAngle=="number"&&(n.endAngle=t.endAngle+i)),e.a*e.d-e.b*e.c<0&&n.vertices&&(n.vertices=n.vertices.map(s=>({...s,bulge:typeof s.bulge=="number"?-s.bulge:void 0}))),n}const zn=t=>Math.abs(t.a-1)<1e-12&&Math.abs(t.b)<1e-12&&Math.abs(t.c)<1e-12&&Math.abs(t.d-1)<1e-12&&Math.abs(t.e)<1e-9&&Math.abs(t.f)<1e-9;function Re(t){var n,r,i;if(t.metadata.sceneTransformApplied===!0||((n=t.savedView)==null?void 0:n.sceneTransformApplied)===!1)return t;const e=((r=t.savedView)==null?void 0:r.sceneTransform)??On;return zn(e)?t:{...t,entities:t.entities.map(o=>Y(o,e)),pages:(i=t.pages)==null?void 0:i.map(o=>({...o,entities:o.entities.map(s=>Y(s,e))})),metadata:{...t.metadata,sceneTransformApplied:!0}}}const _n={background:"#0b1020",foreground:"#ffffff",showUnsupportedMarkers:!1,showImagePlaceholders:!0,showPageBounds:!0,minScale:1e-9,maxScale:1e9,wheelZoomFactor:1.14,trueColorByteOrder:"rgb",maxInsertDepth:16,contrastMode:"adaptive",minColorContrast:2.4,maxCurveSegments:96,spatialIndexCellCount:72,maxVerticesPerBatch:65536,textMinPixelHeight:4,maxVisibleTextLabels:2500,powerPreference:"high-performance",antialias:!0,preserveDrawingBuffer:!1,enableSpatialIndex:!0};class Oe{constructor(e,n={}){u(this,"canvas");u(this,"ctx");u(this,"opts");u(this,"sourceDocument");u(this,"document");u(this,"bounds",B());u(this,"view",{centerX:0,centerY:0,scale:1});u(this,"fitScale",1);u(this,"dpr",1);u(this,"isDragging",!1);u(this,"lastPointer");u(this,"resizeObserver");u(this,"imageCache",new Map);u(this,"stats",{total:0,drawn:0,skipped:0,byType:{},unsupported:{},renderElapsedMs:0,backend:"canvas2d"});u(this,"onStats");u(this,"onViewChange");const r=e.getContext("2d");if(!r)throw new Error("Canvas 2D context is not available.");this.canvas=e,this.ctx=r,this.opts={..._n,...n},this.canvas.classList.add("cad-viewer-canvas"),this.bindEvents(),typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(()=>this.resize()),this.resizeObserver.observe(e)),this.resize()}destroy(){var e;(e=this.resizeObserver)==null||e.disconnect()}clear(){this.sourceDocument=void 0,this.document=void 0,this.bounds=B(),this.view={centerX:0,centerY:0,scale:1},this.fitScale=1,this.render(),this.emitViewChange()}setDocument(e){this.sourceDocument=e,this.document=Re(e),this.bounds=this.computeBounds(this.document),this.fitToView()}getDocument(){return this.document}getSourceDocument(){return this.sourceDocument}setOptions(e){Object.assign(this.opts,e),this.render(),this.emitViewChange()}getOptions(){return{...this.opts}}fitToView(e=.92){if(!j(this.bounds)){this.view={centerX:0,centerY:0,scale:1},this.fitScale=1,this.render(),this.emitViewChange();return}const n=Math.max(1,this.cssWidth),r=Math.max(1,this.cssHeight),i=Math.max(this.bounds.maxX-this.bounds.minX,1e-9),o=Math.max(this.bounds.maxY-this.bounds.minY,1e-9),s=this.clampScale(Math.min(n/i,r/o)*e);this.fitScale=s,this.view={centerX:(this.bounds.minX+this.bounds.maxX)/2,centerY:(this.bounds.minY+this.bounds.maxY)/2,scale:s},this.render(),this.emitViewChange()}resize(){this.dpr=Math.max(1,window.devicePixelRatio||1);const e=Math.max(1,Math.floor(this.cssWidth*this.dpr)),n=Math.max(1,Math.floor(this.cssHeight*this.dpr));(this.canvas.width!==e||this.canvas.height!==n)&&(this.canvas.width=e,this.canvas.height=n),this.render(),this.emitViewChange()}zoom(e,n){if(!Number.isFinite(e)||e<=0)return;const r=n??{x:this.cssWidth/2,y:this.cssHeight/2},i=this.screenToWorld(r);this.view.scale=this.clampScale(this.view.scale*e);const o=this.screenToWorld(r);this.view.centerX+=i.x-o.x,this.view.centerY+=i.y-o.y,this.render(),this.emitViewChange()}zoomIn(){this.zoom(this.opts.wheelZoomFactor)}zoomOut(){this.zoom(1/this.opts.wheelZoomFactor)}panByScreenDelta(e,n){!Number.isFinite(e)||!Number.isFinite(n)||(this.view.centerX-=e/this.view.scale,this.view.centerY+=n/this.view.scale,this.render(),this.emitViewChange())}setViewState(e){if(![e.centerX,e.centerY,e.scale].every(Number.isFinite))throw new Error("Invalid view state.");this.view={...e,scale:this.clampScale(e.scale)},this.render(),this.emitViewChange()}getViewState(){return{...this.view}}getBounds(){return{...this.bounds}}getStats(){return Yn(this.stats)}getZoomRatio(){return Math.abs(this.fitScale)<1e-12?1:this.view.scale/this.fitScale}getZoomPercent(){return this.getZoomRatio()*100}worldToScreen(e){return{x:this.cssWidth/2+(e.x-this.view.centerX)*this.view.scale,y:this.cssHeight/2-(e.y-this.view.centerY)*this.view.scale}}screenToWorld(e){return{x:this.view.centerX+(e.x-this.cssWidth/2)/this.view.scale,y:this.view.centerY-(e.y-this.cssHeight/2)/this.view.scale}}render(){var n,r;const e=performance.now();if(this.stats={total:0,drawn:0,skipped:0,byType:{},unsupported:{},renderElapsedMs:0,backend:"canvas2d"},this.clearCanvas(),this.document){this.opts.showPageBounds&&((n=this.document.pages)!=null&&n.length)&&this.drawPageBounds(this.document);for(const i of this.document.entities)this.drawEntityTracked(i,0)}return this.stats.renderElapsedMs=performance.now()-e,(r=this.onStats)==null||r.call(this,this.getStats()),this.getStats()}get cssWidth(){return this.canvas.clientWidth||1}get cssHeight(){return this.canvas.clientHeight||1}bindEvents(){this.canvas.addEventListener("wheel",n=>{n.preventDefault();const r=n.deltaY<0?this.opts.wheelZoomFactor:1/this.opts.wheelZoomFactor;this.zoom(r,{x:n.offsetX,y:n.offsetY})},{passive:!1}),this.canvas.addEventListener("pointerdown",n=>{this.canvas.setPointerCapture(n.pointerId),this.isDragging=!0,this.lastPointer={x:n.clientX,y:n.clientY},this.canvas.classList.add("is-dragging")}),this.canvas.addEventListener("pointermove",n=>{!this.isDragging||!this.lastPointer||(this.panByScreenDelta(n.clientX-this.lastPointer.x,n.clientY-this.lastPointer.y),this.lastPointer={x:n.clientX,y:n.clientY})});const e=n=>{n&&this.canvas.hasPointerCapture(n.pointerId)&&this.canvas.releasePointerCapture(n.pointerId),this.isDragging=!1,this.lastPointer=void 0,this.canvas.classList.remove("is-dragging")};this.canvas.addEventListener("pointerup",e),this.canvas.addEventListener("pointercancel",()=>e())}clearCanvas(){const e=this.ctx;e.save(),e.setTransform(this.dpr,0,0,this.dpr,0,0),e.clearRect(0,0,this.cssWidth,this.cssHeight),e.fillStyle=this.opts.background,e.fillRect(0,0,this.cssWidth,this.cssHeight),e.restore()}drawPageBounds(e){const n=this.ctx;n.save(),n.setTransform(this.dpr,0,0,this.dpr,0,0),n.strokeStyle="rgba(148, 163, 184, 0.35)",n.lineWidth=1,n.setLineDash([8,6]);for(const r of e.pages??[]){const i=this.worldToScreen({x:0,y:0}),o=this.worldToScreen({x:r.width,y:r.height});n.strokeRect(Math.min(i.x,o.x),Math.min(i.y,o.y),Math.abs(o.x-i.x),Math.abs(o.y-i.y))}n.restore()}drawEntityTracked(e,n){this.stats.total++;const r=String(e.type??"UNKNOWN").toUpperCase();this.stats.byType[r]=(this.stats.byType[r]??0)+1;const i=this.lookupLayer(e.layer);if(e.isVisible===!1||!bt(i)){this.stats.skipped++;return}this.drawEntity(e,r,n)}drawEntity(e,n,r){switch(e.kind??O(n)){case"line":return this.drawLine(e);case"circle":return this.drawCircle(e);case"arc":return this.drawArc(e);case"polyline":return this.drawPolyline(e);case"ellipse":return this.drawEllipse(e);case"text":return this.drawText(e);case"point":return this.drawPoint(e);case"insert":return this.drawInsert(e,r);case"solid":return this.drawSolid(e);case"hatch":return this.drawHatch(e);case"spline":return this.drawSpline(e);case"path":return this.drawPath(e);case"image":return this.drawImage(e);case"viewport":return this.markSkipped(n);default:this.stats.unsupported[n]=(this.stats.unsupported[n]??0)+1,this.stats.skipped++,this.opts.showUnsupportedMarkers&&this.drawUnsupportedMarker(e)}}beginStyledPath(e,n=!1,r=!0){const i=this.ctx;i.save(),i.setTransform(this.dpr,0,0,this.dpr,0,0);const o=_(e,this.document,{foreground:this.opts.foreground,background:this.opts.background,trueColorByteOrder:this.opts.trueColorByteOrder,contrastMode:this.opts.contrastMode,minColorContrast:this.opts.minColorContrast}),s=Ee(e,this.document,{foreground:this.opts.foreground,background:this.opts.background,trueColorByteOrder:this.opts.trueColorByteOrder,contrastMode:this.opts.contrastMode,minColorContrast:this.opts.minColorContrast})??o;i.strokeStyle=o,i.fillStyle=n?s:o,i.globalAlpha=$(Number(e.opacity??1),0,1),i.lineCap="round",i.lineJoin="round";const a=typeof e.lineweight=="number"&&e.lineweight>0?e.lineweight:0;i.lineWidth=Math.max(1,Math.min(12,a>0?a/30:1));const c=r?ue(e,this.document):void 0;i.setLineDash(c?c.segments.map(l=>Math.max(.05,l*this.view.scale)):[]),i.beginPath()}finishStroke(){this.ctx.stroke(),this.ctx.restore(),this.stats.drawn++}finishFillStroke(e=!1){e&&this.ctx.fill(),this.ctx.stroke(),this.ctx.restore(),this.stats.drawn++}drawLine(e){const n=e.startPoint,r=e.endPoint;if(!p(n)||!p(r))return this.markSkipped("LINE");this.strokeWorldPolyline(e,[n,r],!1)}drawCircle(e){const n=e.center,r=Number(e.radius);if(!p(n)||!Number.isFinite(r))return this.markSkipped("CIRCLE");this.strokeWorldPolyline(e,Q(k(n),r,0,Math.PI*2,!0),!0)}drawArc(e){const n=e.center,r=Number(e.radius),i=Number(e.startAngle),o=Number(e.endAngle);if(!p(n)||!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(o))return this.markSkipped("ARC");this.strokeWorldPolyline(e,Q(k(n),r,i,o,!0),!1)}drawPolyline(e){const n=e.vertices??e.points;if(!Array.isArray(n)||n.length<2)return this.markSkipped(String(e.type));const r=Ce(e),i=[],o=r?n.length:n.length-1;for(let s=0;s<o;s++){const a=n[s],c=n[(s+1)%n.length];if(!p(a)||!p(c))continue;const l=tt(a,c,Number(a.bulge??0));i.length>0&&l.shift(),i.push(...l)}this.strokeWorldPolyline(e,i,r)}drawEllipse(e){const n=e.center,r=e.majorAxisEndPoint,i=Number(e.axisRatio??1);if(!p(n)||!p(r))return this.markSkipped("ELLIPSE");const o=le(n,r,i,Number(e.startAngle??0),Number(e.endAngle??Math.PI*2)),s=Math.abs(Number(e.endAngle??Math.PI*2)-Number(e.startAngle??0))>=Math.PI*2-1e-6;this.strokeWorldPolyline(e,o,s)}drawPoint(e){const n=e.point??e.location??e.center??e.insertionPoint;if(!p(n))return this.markSkipped("POINT");const r=this.worldToScreen(n);this.beginStyledPath(e),this.ctx.moveTo(r.x-3,r.y),this.ctx.lineTo(r.x+3,r.y),this.ctx.moveTo(r.x,r.y-3),this.ctx.lineTo(r.x,r.y+3),this.finishStroke()}drawText(e){const n=e.insertionPoint??e.startPoint??e.center,r=nt(String(e.text??e.value??"")),i=Number(e.textHeight??e.height??1);if(!p(n)||!r)return this.markSkipped(String(e.type));this.drawTextAt(e,n,r,i,Number(e.rotation??0))}drawInsert(e,n){const r=this.lookupBlock(e.blockName??e.name);if(r&&n<this.opts.maxInsertDepth){const a=ge(e,r.basePoint??{x:0,y:0});for(const c of r.entities){const l=yt(c,e,this.document,{foreground:this.opts.foreground,background:this.opts.background,trueColorByteOrder:this.opts.trueColorByteOrder,contrastMode:this.opts.contrastMode,minColorContrast:this.opts.minColorContrast}),f=Fe(l,e,this.document);this.drawEntityTracked(Y(f,a),n+1)}return}const i=e.insertionPoint;if(!p(i))return this.markSkipped("INSERT");const o=this.worldToScreen(i);this.beginStyledPath(e);const s=5;if(this.ctx.rect(o.x-s,o.y-s,s*2,s*2),this.finishStroke(),Array.isArray(e.attribs))for(const a of e.attribs)this.drawText(a)}drawSolid(e){const n=e.vertices??e.points;if(!Array.isArray(n)||n.length<3)return this.markSkipped(String(e.type));this.beginStyledPath(e,!0);const r=this.worldToScreen(n[0]);this.ctx.moveTo(r.x,r.y);for(const i of n.slice(1)){if(!p(i))continue;const o=this.worldToScreen(i);this.ctx.lineTo(o.x,o.y)}this.ctx.closePath(),this.finishFillStroke(!0)}drawHatch(e){var r,i;const n=e.loops;if(!Array.isArray(n)||n.length===0)return this.markSkipped("HATCH");this.beginStyledPath(e,!0);for(const o of n)if((r=o.commands)!=null&&r.length)this.addPathCommands(o.commands);else if((i=o.vertices)!=null&&i.length){const s=this.worldToScreen(o.vertices[0]);this.ctx.moveTo(s.x,s.y);for(const a of o.vertices.slice(1)){const c=this.worldToScreen(a);this.ctx.lineTo(c.x,c.y)}this.ctx.closePath()}this.finishFillStroke(!!Ee(e,this.document,{foreground:this.opts.foreground,background:this.opts.background,trueColorByteOrder:this.opts.trueColorByteOrder,contrastMode:this.opts.contrastMode,minColorContrast:this.opts.minColorContrast}))}drawSpline(e){var r;const n=(r=e.fitPoints)!=null&&r.length?e.fitPoints:e.controlPoints;if(!n||n.length<2)return this.markSkipped("SPLINE");this.strokeWorldPolyline(e,n,!!e.isClosed)}drawPath(e){var n;if(!((n=e.commands)!=null&&n.length))return this.markSkipped(String(e.type));this.beginStyledPath(e,!!e.fillColor),this.addPathCommands(e.commands),this.finishFillStroke(!!e.fillColor)}addPathCommands(e){for(const n of e)if(n.cmd==="M"){const r=this.worldToScreen(n.points[0]);this.ctx.moveTo(r.x,r.y)}else if(n.cmd==="L"){const r=this.worldToScreen(n.points[0]);this.ctx.lineTo(r.x,r.y)}else if(n.cmd==="C"){const[r,i,o]=n.points.map(s=>this.worldToScreen(s));this.ctx.bezierCurveTo(r.x,r.y,i.x,i.y,o.x,o.y)}else if(n.cmd==="Q"){const[r,i]=n.points.map(o=>this.worldToScreen(o));this.ctx.quadraticCurveTo(r.x,r.y,i.x,i.y)}else n.cmd==="Z"&&this.ctx.closePath()}drawImage(e){const n=e.insertionPoint;if(!p(n))return this.markSkipped(String(e.type));const r=Number(e.width??32),i=Number(e.height??32),o=this.worldToScreen(n),s=this.worldToScreen({x:n.x+r,y:n.y-i}),a=Math.min(o.x,s.x),c=Math.min(o.y,s.y),l=Math.abs(s.x-o.x),f=Math.abs(s.y-o.y),h=e.imageDataUrl;if(h){const d=this.getImage(h);if(d.complete&&d.naturalWidth>0){this.ctx.save(),this.ctx.setTransform(this.dpr,0,0,this.dpr,0,0),this.ctx.drawImage(d,a,c,l,f),this.ctx.restore(),this.stats.drawn++;return}d.onload=()=>this.render()}if(!this.opts.showImagePlaceholders)return this.markSkipped(String(e.type));this.beginStyledPath(e),this.ctx.rect(a,c,l,f),this.ctx.moveTo(a,c),this.ctx.lineTo(a+l,c+f),this.ctx.moveTo(a+l,c),this.ctx.lineTo(a,c+f),this.finishStroke()}getImage(e){let n=this.imageCache.get(e);return n||(n=new Image,n.src=e,this.imageCache.set(e,n)),n}drawUnsupportedMarker(e){const n=this.entityAnchor(e);if(!n)return;const r=this.worldToScreen(n);this.beginStyledPath(e),this.ctx.moveTo(r.x-4,r.y-4),this.ctx.lineTo(r.x+4,r.y+4),this.ctx.moveTo(r.x+4,r.y-4),this.ctx.lineTo(r.x-4,r.y+4),this.finishStroke()}drawTextAt(e,n,r,i,o){const s=this.ctx,a=this.worldToScreen(n);s.save(),s.setTransform(this.dpr,0,0,this.dpr,0,0),s.translate(a.x,a.y),s.rotate(-o);const c=Math.max(4,Math.min(256,Math.abs(i)*this.view.scale));s.font=`${c}px ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`,s.fillStyle=_(e,this.document,{foreground:this.opts.foreground,background:this.opts.background,trueColorByteOrder:this.opts.trueColorByteOrder,contrastMode:this.opts.contrastMode,minColorContrast:this.opts.minColorContrast}),s.globalAlpha=$(Number(e.opacity??1),0,1),s.textBaseline="alphabetic";for(const[l,f]of r.split(/\r?\n/g).entries())s.fillText(f,0,l*c*1.22);s.restore(),this.stats.drawn++}strokeWorldPolyline(e,n,r){const i=n.filter(p);if(i.length<2)return this.markSkipped(String(e.type));const o=ue(e,this.document);if(o){const a=me(i,r,o);this.beginStyledPath(e,!1,!1);for(const[c,l]of a.segments){const f=this.worldToScreen(c),h=this.worldToScreen(l);this.ctx.moveTo(f.x,f.y),this.ctx.lineTo(h.x,h.y)}if(this.ctx.stroke(),a.dots.length>0){this.ctx.setLineDash([]),this.ctx.beginPath();const c=Math.max(.5,this.ctx.lineWidth/2);for(const l of a.dots){const f=this.worldToScreen(l);this.ctx.moveTo(f.x+c,f.y),this.ctx.arc(f.x,f.y,c,0,Math.PI*2)}this.ctx.fillStyle=this.ctx.strokeStyle,this.ctx.fill()}this.ctx.restore(),this.stats.drawn++;return}this.beginStyledPath(e);const s=this.worldToScreen(i[0]);this.ctx.moveTo(s.x,s.y);for(const a of i.slice(1)){const c=this.worldToScreen(a);this.ctx.lineTo(c.x,c.y)}r&&this.ctx.closePath(),this.finishStroke()}markSkipped(e){this.stats.skipped++,this.stats.unsupported[e]=this.stats.unsupported[e]??0}entityAnchor(e){for(const n of["startPoint","insertionPoint","center","point","location"]){const r=e[n];if(p(r))return k(r)}if(Array.isArray(e.vertices)&&p(e.vertices[0]))return k(e.vertices[0]);if(Array.isArray(e.commands)&&e.commands.length){const n=e.commands.find(r=>r.points.length>0);if(n)return k(n.points[0])}}computeBounds(e){var r;const n=B();if((r=e.pages)!=null&&r.length)for(const i of e.pages)C(n,{x:0,y:0}),C(n,{x:i.width,y:i.height});for(const i of e.entities)this.includeEntityBounds(n,i,0);return et(n)}includeEntityBounds(e,n,r){const i=String(n.type??"").toUpperCase(),o=n.kind??O(i);if(o==="insert"){const s=this.lookupBlock(n.blockName??n.name);if(s&&r<this.opts.maxInsertDepth){const a=ge(n,s.basePoint??{x:0,y:0});for(const c of s.entities)this.includeEntityBounds(e,Y(c,a),r+1);return}}if(o==="line")p(n.startPoint)&&C(e,n.startPoint),p(n.endPoint)&&C(e,n.endPoint);else if(o==="circle"||o==="arc")p(n.center)&&Number.isFinite(n.radius)&&Qe(e,n.center,Number(n.radius));else if(o==="polyline"||o==="solid"||o==="spline")for(const s of[...n.vertices??[],...n.points??[],...n.controlPoints??[],...n.fitPoints??[]])p(s)&&C(e,s);else if(o==="ellipse")p(n.center)&&p(n.majorAxisEndPoint)&&le(n.center,n.majorAxisEndPoint,Number(n.axisRatio??1),Number(n.startAngle??0),Number(n.endAngle??Math.PI*2)).forEach(s=>C(e,s));else if(o==="path")for(const s of n.commands??[])for(const a of s.points)C(e,a);else if(o==="hatch")for(const s of n.loops??[]){for(const a of s.vertices??[])C(e,a);for(const a of s.commands??[])for(const c of a.points)C(e,c)}else{const s=this.entityAnchor(n);s&&C(e,s)}}lookupLayer(e){if(!(!this.document||!e))return this.document.layers[e]??this.document.layers[e.toLowerCase()]??Object.values(this.document.layers).find(n=>n.name.toLowerCase()===e.toLowerCase())}lookupBlock(e){if(!(!this.document||!e))return this.document.blocks[e]??this.document.blocks[e.toLowerCase()]??Object.values(this.document.blocks).find(n=>n.name.toLowerCase()===e.toLowerCase())}clampScale(e){return Math.min(this.opts.maxScale,Math.max(this.opts.minScale,e))}emitViewChange(){var e;(e=this.onViewChange)==null||e.call(this,{view:this.getViewState(),fitScale:this.fitScale,zoomRatio:this.getZoomRatio(),zoomPercent:this.getZoomPercent(),bounds:this.getBounds()})}}function Yn(t){return{total:t.total,drawn:t.drawn,skipped:t.skipped,byType:{...t.byType},unsupported:{...t.unsupported},renderElapsedMs:t.renderElapsedMs,backend:t.backend,primitiveCount:t.primitiveCount,visiblePrimitiveCount:t.visiblePrimitiveCount,culledPrimitiveCount:t.culledPrimitiveCount,gpuMemoryBytes:t.gpuMemoryBytes,buildElapsedMs:t.buildElapsedMs}}const Vn={background:"#0b1020",foreground:"#ffffff",showUnsupportedMarkers:!1,showImagePlaceholders:!0,showPageBounds:!0,minScale:1e-9,maxScale:1e9,wheelZoomFactor:1.14,trueColorByteOrder:"rgb",maxInsertDepth:16,contrastMode:"adaptive",minColorContrast:2.4,maxCurveSegments:96,spatialIndexCellCount:72,maxVerticesPerBatch:65536,textMinPixelHeight:4,maxVisibleTextLabels:2500,powerPreference:"high-performance",antialias:!0,preserveDrawingBuffer:!1,enableSpatialIndex:!0};class We{constructor(e,n={}){u(this,"canvas");u(this,"backend","webgl");u(this,"gl");u(this,"program");u(this,"eventController",new AbortController);u(this,"imageCache",new Map);u(this,"opts");u(this,"sourceDocument");u(this,"document");u(this,"bounds",B());u(this,"view",{centerX:0,centerY:0,scale:1});u(this,"fitScale",1);u(this,"dpr",1);u(this,"isDragging",!1);u(this,"lastPointer");u(this,"resizeObserver");u(this,"overlayCanvas");u(this,"overlayCtx");u(this,"scene");u(this,"stats",{total:0,drawn:0,skipped:0,byType:{},unsupported:{},renderElapsedMs:0,backend:"webgl",primitiveCount:0,visiblePrimitiveCount:0,culledPrimitiveCount:0,gpuMemoryBytes:0,buildElapsedMs:0});u(this,"rafHandle",0);u(this,"onStats");u(this,"onViewChange");const r=Hn(e,n);if(!r)throw new Error('WebGL is not available. Use renderer: "canvas2d" to force the Canvas2D fallback.');this.canvas=e,this.gl=r,this.program=Un(r),this.opts={...Vn,...n},this.canvas.classList.add("cad-viewer-canvas","cad-viewer-webgl-canvas"),this.createOverlayCanvas(),this.bindEvents(),typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(()=>this.resize()),this.resizeObserver.observe(e)),this.resize()}static isSupported(){return ze()}destroy(){var e,n;this.eventController.abort(),(e=this.resizeObserver)==null||e.disconnect(),this.cancelScheduledRender(),this.disposeScene(),(n=this.overlayCanvas)==null||n.remove()}clear(){this.sourceDocument=void 0,this.document=void 0,this.bounds=B(),this.view={centerX:0,centerY:0,scale:1},this.fitScale=1,this.disposeScene(),this.render(),this.emitViewChange()}setDocument(e){this.sourceDocument=e,this.document=Re(e),this.bounds=qn(this.document,this.opts),this.disposeScene();const n=jn(this.document,this.opts,this.bounds);this.scene=Xn(this.gl,n),this.stats=Jn(this.scene,0),this.fitToView()}getDocument(){return this.document}getSourceDocument(){return this.sourceDocument}setOptions(e){const n=Kn(this.opts,e);if(this.opts={...this.opts,...e},n&&(this.sourceDocument??this.document)){this.setDocument(this.sourceDocument??this.document);return}this.render(),this.emitViewChange()}getOptions(){return{...this.opts}}fitToView(e=.92){if(!j(this.bounds)){this.view={centerX:0,centerY:0,scale:1},this.fitScale=1,this.render(),this.emitViewChange();return}const n=Math.max(1,this.cssWidth),r=Math.max(1,this.cssHeight),i=Math.max(this.bounds.maxX-this.bounds.minX,1e-9),o=Math.max(this.bounds.maxY-this.bounds.minY,1e-9),s=this.clampScale(Math.min(n/i,r/o)*e);this.fitScale=s,this.view={centerX:(this.bounds.minX+this.bounds.maxX)/2,centerY:(this.bounds.minY+this.bounds.maxY)/2,scale:s},this.render(),this.emitViewChange()}resize(){this.dpr=Math.max(1,window.devicePixelRatio||1);const e=Math.max(1,Math.floor(this.cssWidth*this.dpr)),n=Math.max(1,Math.floor(this.cssHeight*this.dpr));(this.canvas.width!==e||this.canvas.height!==n)&&(this.canvas.width=e,this.canvas.height=n),this.resizeOverlay(e,n),this.render(),this.emitViewChange()}zoom(e,n){if(!Number.isFinite(e)||e<=0)return;const r=n??{x:this.cssWidth/2,y:this.cssHeight/2},i=this.screenToWorld(r);this.view.scale=this.clampScale(this.view.scale*e);const o=this.screenToWorld(r);this.view.centerX+=i.x-o.x,this.view.centerY+=i.y-o.y,this.scheduleRender(),this.emitViewChange()}zoomIn(){this.zoom(this.opts.wheelZoomFactor)}zoomOut(){this.zoom(1/this.opts.wheelZoomFactor)}panByScreenDelta(e,n){!Number.isFinite(e)||!Number.isFinite(n)||(this.view.centerX-=e/this.view.scale,this.view.centerY+=n/this.view.scale,this.scheduleRender(),this.emitViewChange())}setViewState(e){if(![e.centerX,e.centerY,e.scale].every(Number.isFinite))throw new Error("Invalid view state.");this.view={...e,scale:this.clampScale(e.scale)},this.render(),this.emitViewChange()}getViewState(){return{...this.view}}getBounds(){return{...this.bounds}}getStats(){return Qn(this.stats)}getZoomRatio(){return Math.abs(this.fitScale)<1e-12?1:this.view.scale/this.fitScale}getZoomPercent(){return this.getZoomRatio()*100}worldToScreen(e){return{x:this.cssWidth/2+(e.x-this.view.centerX)*this.view.scale,y:this.cssHeight/2-(e.y-this.view.centerY)*this.view.scale}}screenToWorld(e){return{x:this.view.centerX+(e.x-this.cssWidth/2)/this.view.scale,y:this.view.centerY-(e.y-this.cssHeight/2)/this.view.scale}}render(){return this.cancelScheduledRender(),this.renderNow()}renderNow(){var l;const e=performance.now(),n=this.gl;n.viewport(0,0,this.canvas.width,this.canvas.height);const r=Ve(this.opts.background,[11,16,32,255]);n.clearColor(r[0]/255,r[1]/255,r[2]/255,r[3]/255),n.clear(n.COLOR_BUFFER_BIT),n.disable(n.DEPTH_TEST),n.enable(n.BLEND),n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA);let i=0,o=0;const s=this.scene,a=this.visibleWorldBounds();if(s){n.useProgram(this.program.program),n.uniform2f(this.program.uViewCenter,this.view.centerX-s.origin.x,this.view.centerY-s.origin.y),n.uniform1f(this.program.uScale,this.view.scale*this.dpr),n.uniform2f(this.program.uViewport,this.canvas.width,this.canvas.height),n.uniform1f(this.program.uPointSize,Math.max(1,this.dpr));const f=this.drawBatches(s.lineBatches,n.LINES,a);i+=f.visible,o+=f.culled;const h=this.drawBatches(s.triangleBatches,n.TRIANGLES,a);i+=h.visible,o+=h.culled;const d=this.drawBatches(s.lineTypePointBatches,n.POINTS,a);i+=d.visible,o+=d.culled,n.uniform1f(this.program.uPointSize,Math.max(2,Math.min(12,4*this.dpr)));const m=this.drawBatches(s.pointBatches,n.POINTS,a);i+=m.visible,o+=m.culled}this.renderOverlay(a);const c=performance.now()-e;return this.stats=s?{...s.stats,renderElapsedMs:c,backend:"webgl",primitiveCount:s.primitiveCount,visiblePrimitiveCount:i,culledPrimitiveCount:o,gpuMemoryBytes:s.gpuMemoryBytes,buildElapsedMs:s.buildElapsedMs}:{total:0,drawn:0,skipped:0,byType:{},unsupported:{},renderElapsedMs:c,backend:"webgl",primitiveCount:0,visiblePrimitiveCount:0,culledPrimitiveCount:0,gpuMemoryBytes:0,buildElapsedMs:0},(l=this.onStats)==null||l.call(this,this.getStats()),this.getStats()}drawBatches(e,n,r){const i=this.gl;let o=0,s=0;for(const a of e){if(!Ye(a.bounds,r)){s+=a.primitiveCount;continue}i.bindBuffer(i.ARRAY_BUFFER,a.positionBuffer),i.enableVertexAttribArray(this.program.aPosition),i.vertexAttribPointer(this.program.aPosition,2,i.FLOAT,!1,0,0),i.bindBuffer(i.ARRAY_BUFFER,a.colorBuffer),i.enableVertexAttribArray(this.program.aColor),i.vertexAttribPointer(this.program.aColor,4,i.UNSIGNED_BYTE,!0,0,0),i.drawArrays(n,0,a.vertexCount),o+=a.primitiveCount}return{visible:o,culled:s}}scheduleRender(){this.rafHandle||(this.rafHandle=window.requestAnimationFrame(()=>{this.rafHandle=0,this.renderNow()}))}cancelScheduledRender(){this.rafHandle&&(window.cancelAnimationFrame(this.rafHandle),this.rafHandle=0)}renderOverlay(e){var i,o;const n=this.overlayCtx,r=this.overlayCanvas;!n||!r||(n.save(),n.setTransform(this.dpr,0,0,this.dpr,0,0),n.clearRect(0,0,this.cssWidth,this.cssHeight),this.opts.showPageBounds&&((o=(i=this.document)==null?void 0:i.pages)!=null&&o.length)&&this.drawPageBoundsOverlay(n),this.scene&&(this.drawImagesOverlay(n,this.scene.imageItems,e),this.drawTextOverlay(n,this.scene.textItems,e)),n.restore())}drawPageBoundsOverlay(e){var n,r;if((r=(n=this.document)==null?void 0:n.pages)!=null&&r.length){e.save(),e.strokeStyle="rgba(148, 163, 184, 0.34)",e.lineWidth=1,e.setLineDash([8,6]);for(const i of this.document.pages){const o=this.worldToScreen({x:0,y:0}),s=this.worldToScreen({x:i.width,y:i.height});e.strokeRect(Math.min(o.x,s.x),Math.min(o.y,s.y),Math.abs(s.x-o.x),Math.abs(s.y-o.y))}e.restore()}}drawTextOverlay(e,n,r){const i=this.opts.maxVisibleTextLabels;let o=0;for(const s of n){if(o>=i)break;if(!Ye(s.bounds,r))continue;const a=Math.abs(s.height)*this.view.scale;if(a<this.opts.textMinPixelHeight)continue;const c=this.worldToScreen(s.point);if(c.x<-512||c.y<-512||c.x>this.cssWidth+512||c.y>this.cssHeight+512)continue;e.save(),e.translate(c.x,c.y),e.rotate(-s.rotation);const l=Math.max(4,Math.min(256,a));e.font=`${l}px ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`,e.fillStyle=s.color,e.globalAlpha=s.opacity,e.textBaseline="alphabetic";for(const[f,h]of s.text.split(/\r?\n/g).entries())e.fillText(h,0,f*l*1.22);e.restore(),o++}}drawImagesOverlay(e,n,r){for(const i of n){if(!Ye(i.bounds,r))continue;const o=this.worldToScreen(i.point),s=this.worldToScreen({x:i.point.x+i.width,y:i.point.y-i.height}),a=Math.min(o.x,s.x),c=Math.min(o.y,s.y),l=Math.abs(s.x-o.x),f=Math.abs(s.y-o.y);if(!(l<1||f<1)){if(i.source){const h=this.getImage(i.source);if(h.complete&&h.naturalWidth>0){e.save(),e.globalAlpha=i.opacity,e.drawImage(h,a,c,l,f),e.restore();continue}h.onload=()=>this.scheduleRender()}this.opts.showImagePlaceholders&&(e.save(),e.strokeStyle=i.color,e.globalAlpha=i.opacity,e.lineWidth=1,e.strokeRect(a,c,l,f),e.beginPath(),e.moveTo(a,c),e.lineTo(a+l,c+f),e.moveTo(a+l,c),e.lineTo(a,c+f),e.stroke(),e.restore())}}}getImage(e){let n=this.imageCache.get(e);return n||(n=new Image,n.src=e,this.imageCache.set(e,n)),n}createOverlayCanvas(){const e=this.canvas.parentElement;if(!e||typeof document>"u")return;window.getComputedStyle(e).position==="static"&&(e.style.position="relative");const r=document.createElement("canvas");r.className="cad-viewer-text-overlay",r.setAttribute("aria-hidden","true"),r.style.position="absolute",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.pointerEvents="none",r.style.zIndex="1";const i=r.getContext("2d");i&&(e.appendChild(r),this.overlayCanvas=r,this.overlayCtx=i)}resizeOverlay(e,n){this.overlayCanvas&&(this.overlayCanvas.width!==e||this.overlayCanvas.height!==n)&&(this.overlayCanvas.width=e,this.overlayCanvas.height=n)}bindEvents(){const e=this.eventController.signal;this.canvas.addEventListener("wheel",r=>{r.preventDefault();const i=r.deltaY<0?this.opts.wheelZoomFactor:1/this.opts.wheelZoomFactor;this.zoom(i,{x:r.offsetX,y:r.offsetY})},{passive:!1,signal:e}),this.canvas.addEventListener("pointerdown",r=>{this.canvas.setPointerCapture(r.pointerId),this.isDragging=!0,this.lastPointer={x:r.clientX,y:r.clientY},this.canvas.classList.add("is-dragging")},{signal:e}),this.canvas.addEventListener("pointermove",r=>{!this.isDragging||!this.lastPointer||(this.panByScreenDelta(r.clientX-this.lastPointer.x,r.clientY-this.lastPointer.y),this.lastPointer={x:r.clientX,y:r.clientY})},{signal:e});const n=r=>{r&&this.canvas.hasPointerCapture(r.pointerId)&&this.canvas.releasePointerCapture(r.pointerId),this.isDragging=!1,this.lastPointer=void 0,this.canvas.classList.remove("is-dragging")};this.canvas.addEventListener("pointerup",n,{signal:e}),this.canvas.addEventListener("pointercancel",()=>n(),{signal:e}),this.canvas.addEventListener("webglcontextlost",r=>{r.preventDefault(),this.cancelScheduledRender()},{signal:e})}visibleWorldBounds(){const e=this.cssWidth/Math.max(this.view.scale,1e-12)/2,n=this.cssHeight/Math.max(this.view.scale,1e-12)/2;return{minX:this.view.centerX-e,maxX:this.view.centerX+e,minY:this.view.centerY-n,maxY:this.view.centerY+n}}get cssWidth(){return this.canvas.clientWidth||1}get cssHeight(){return this.canvas.clientHeight||1}clampScale(e){return Math.min(this.opts.maxScale,Math.max(this.opts.minScale,e))}disposeScene(){if(!this.scene)return;const e=this.gl;for(const n of[...this.scene.lineBatches,...this.scene.triangleBatches,...this.scene.lineTypePointBatches,...this.scene.pointBatches])e.deleteBuffer(n.positionBuffer),e.deleteBuffer(n.colorBuffer);this.scene=void 0}emitViewChange(){var e;(e=this.onViewChange)==null||e.call(this,{view:this.getViewState(),fitScale:this.fitScale,zoomRatio:this.getZoomRatio(),zoomPercent:this.getZoomPercent(),bounds:this.getBounds()})}}function ze(){if(typeof document>"u")return!1;const t=document.createElement("canvas");return!!(t.getContext("webgl2")??t.getContext("webgl")??t.getContext("experimental-webgl"))}function Hn(t,e){const n={alpha:!1,antialias:e.antialias??!0,depth:!1,stencil:!1,preserveDrawingBuffer:e.preserveDrawingBuffer??!1,powerPreference:e.powerPreference??"high-performance"};return t.getContext("webgl2",n)??t.getContext("webgl",n)??t.getContext("experimental-webgl",n)??void 0}function Un(t){const e=`
9
+ `),t=[];for(let d=0;d<e.length-1;d+=2){const f=Number((h=e[d])==null?void 0:h.trim()),u=e[d+1]??"";Number.isFinite(f)&&t.push({code:f,value:u.trimEnd()})}const i=[],s={};let r="",o=[],a;for(let d=0;d<t.length;d++){const f=t[d];if(f.code===0&&f.value==="SECTION"){r=((l=t[d+1])==null?void 0:l.code)===2?t[d+1].value.toUpperCase():"",d++;continue}if(f.code===0&&f.value==="ENDSEC"){c(),r="";continue}r==="ENTITIES"&&(f.code===0?(c(),o=[f]):o.push(f))}return c(),{header:{},tables:{},entities:i,blocks:s};function c(){var u;if(!o.length)return;const d=(u=o[0])==null?void 0:u.value.toUpperCase();if(d==="VERTEX"&&a){const p=B(o,10,20,30);p&&(a.vertices??(a.vertices=[])).push({...p,bulge:k(o,42)}),o=[];return}if(d==="SEQEND"){a&&i.push(a),a=void 0,o=[];return}if(a&&(i.push(a),a=void 0),!d||d==="EOF"){o=[];return}const f=ei(d,o);d==="POLYLINE"?a=f:i.push(f),o=[]}}function ei(n,e){const t={type:n,handle:le(e,5),layer:le(e,8)??"0",colorIndex:k(e,62),trueColor:k(e,420),lineType:le(e,6),lineweight:k(e,370)};switch(n){case"LINE":Object.assign(t,{startPoint:B(e,10,20,30),endPoint:B(e,11,21,31)});break;case"CIRCLE":Object.assign(t,{center:B(e,10,20,30),radius:k(e,40)});break;case"ARC":Object.assign(t,{center:B(e,10,20,30),radius:k(e,40),startAngle:Pe(k(e,50)),endAngle:Pe(k(e,51))});break;case"POINT":Object.assign(t,{point:B(e,10,20,30)});break;case"TEXT":case"MTEXT":Object.assign(t,{insertionPoint:B(e,10,20,30),text:ii(e),textHeight:k(e,40),rotation:Pe(k(e,50))});break;case"LWPOLYLINE":Object.assign(t,{vertices:ni(e),flag:k(e,70),isClosed:(Number(k(e,70)??0)&1)===1});break;case"POLYLINE":Object.assign(t,{vertices:[],flag:k(e,70),isClosed:(Number(k(e,70)??0)&1)===1});break;case"ELLIPSE":Object.assign(t,{center:B(e,10,20,30),majorAxisEndPoint:B(e,11,21,31),axisRatio:k(e,40),startAngle:k(e,41),endAngle:k(e,42)});break;case"SPLINE":Object.assign(t,{controlPoints:ti(e,10,20,30),degree:k(e,71),isClosed:(Number(k(e,70)??0)&1)===1});break;case"INSERT":Object.assign(t,{name:le(e,2),blockName:le(e,2),insertionPoint:B(e,10,20,30),rotation:Pe(k(e,50)),scale:{x:k(e,41)??1,y:k(e,42)??k(e,41)??1,z:k(e,43)??1}});break;case"SOLID":case"TRACE":case"3DFACE":Object.assign(t,{vertices:[B(e,10,20,30),B(e,11,21,31),B(e,12,22,32),B(e,13,23,33)].filter(Boolean)});break}return Ye(t)}function k(n,e){var s;const t=(s=n.find(r=>r.code===e))==null?void 0:s.value,i=Number(t);return Number.isFinite(i)?i:void 0}function le(n,e){var i;const t=(i=n.find(s=>s.code===e))==null?void 0:i.value;return t&&t.length>0?t:void 0}function B(n,e,t,i){const s=k(n,e),r=k(n,t),o=k(n,i);if(!(s===void 0||r===void 0))return o===void 0?{x:s,y:r}:{x:s,y:r,z:o}}function ti(n,e,t,i){const s=[];for(let r=0;r<n.length;r++){if(n[r].code!==e)continue;const o=Number(n[r].value),a=n.slice(r+1).find(d=>d.code===t),c=n.slice(r+1).find(d=>d.code===i),h=Number(a==null?void 0:a.value),l=Number(c==null?void 0:c.value);Number.isFinite(o)&&Number.isFinite(h)&&s.push(Number.isFinite(l)?{x:o,y:h,z:l}:{x:o,y:h})}return s}function ni(n){const e=[];for(let t=0;t<n.length;t++){if(n[t].code!==10)continue;const i=Number(n[t].value);let s,r;for(let o=t+1;o<n.length&&n[o].code!==10;o++)n[o].code===20&&(s=Number(n[o].value)),n[o].code===42&&(r=Number(n[o].value));Number.isFinite(i)&&Number.isFinite(s)&&e.push({x:i,y:s,bulge:Number.isFinite(r)?r:void 0})}return e}function ii(n){const e=n.filter(t=>t.code===1||t.code===3).map(t=>t.value);return e.length?e.join(""):void 0}function Pe(n){return typeof n=="number"&&Number.isFinite(n)?V(n):void 0}class Tt{constructor(e={}){m(this,"id","dwf");m(this,"label","DWF/DWFx native viewer powered by dwf-viewer");m(this,"formats",["dwf","dwfx","xps"]);m(this,"nativeRenderer",!0);m(this,"defaults");m(this,"native");m(this,"host");m(this,"lastStats");this.defaults=e}accepts(e,t){const i=K(e);if(i==="dwf"||i==="dwfx"||i==="xps")return!0;const s=$(e,t);return s==="dwf"||s==="dwfx"||s==="xps"}async load(e,t={}){var d,f,u,p;const i={...this.defaults,...t},s=performance.now(),r=e.fileName??((d=e.file)==null?void 0:d.name),o=await X(e),a=It($(e,o),K(e));(f=i.onProgress)==null||f.call(i,{phase:"parse",format:a,message:"Opening DWF/DWFx with dwf-viewer…",percent:48});const c=await D.openDwfDocument(o,{fileName:r});(u=i.onProgress)==null||u.call(i,{phase:"normalize",format:a,message:"Reading DWF pages, sheets and model metadata…",percent:76});const h=Et(c,r,a,i.keepRaw===!0),l=performance.now()-s;return(p=i.onProgress)==null||p.call(i,{phase:"done",format:h.format,message:"DWF/DWFx document ready.",percent:100,elapsedMs:l}),{document:h,raw:i.keepRaw?c:void 0,bytes:o.byteLength,elapsedMs:l,format:h.format,warnings:h.warnings}}async mount(e,t,i={}){var P,g,v,C,S;const s={...this.defaults,...i},r=performance.now(),o=e.fileName??((P=e.file)==null?void 0:P.name),a=await X(e),c=It($(e,a),K(e)),h=ci(s),l=Lt(s),d=hi(s,h,l),f=Ft(s,h,l);(g=s.onProgress)==null||g.call(s,{phase:"native-render",format:c,message:"Mounting native DWF renderer…",percent:28}),this.unmount(),this.host=t,t.replaceChildren(),this.native=new D.DwfViewer(t,d),(v=s.onProgress)==null||v.call(s,{phase:"parse",format:c,message:"Parsing DWF package and page streams…",percent:58}),await this.native.load(a,{fileName:o,...f}),(C=s.onProgress)==null||C.call(s,{phase:"render",format:c,message:"Rendering DWF/DWFx with dwf-viewer…",percent:88}),this.lastStats=await this.native.render();const u=this.native.getDocument(),p=Et(u,o,c,s.keepRaw===!0);p.metadata.loaderMode="Native DWF",p.metadata.nativeRenderer="dwf-viewer",p.metadata.nativeRenderStats=this.lastStats?{...this.lastStats,warnings:this.lastStats.warnings.length}:void 0;const w=performance.now()-r;return(S=s.onProgress)==null||S.call(s,{phase:"done",format:p.format,message:"DWF/DWFx rendered.",percent:100,elapsedMs:w}),{document:p,raw:s.keepRaw?u:void 0,bytes:a.byteLength,elapsedMs:w,format:p.format,warnings:p.warnings}}unmount(){var e;(e=this.native)==null||e.dispose(),this.native=void 0,this.lastStats=void 0,this.host&&this.host.replaceChildren()}fit(){var e;(e=this.native)==null||e.fit()}zoomIn(){var t;const e=(t=this.native)==null?void 0:t.zoomInButton;e==null||e.click()}zoomOut(){var t;const e=(t=this.native)==null?void 0:t.zoomOutButton;e==null||e.click()}resize(){var e;(e=this.native)==null||e.render()}setNativeOptions(e){var i,s,r,o;const t=this.native;if(t){if(typeof e.dwfBackground=="string")t.background=e.dwfBackground;else{const a=Lt(e);a&&(t.background=a)}typeof e.dwfPreferWebgl=="boolean"&&((i=t.setPreferWebgl)==null||i.call(t,e.dwfPreferWebgl)),typeof e.dwfPreferWasm=="boolean"&&((s=t.setPreferWasm)==null||s.call(t,e.dwfPreferWasm)),e.dwfLineWeightMode&&((r=t.setLineWeightMode)==null||r.call(t,e.dwfLineWeightMode)),Ce(t,"minStrokeCssPx",e.dwfMinStrokeCssPx),Ce(t,"maxOverviewStrokeCssPx",e.dwfMaxOverviewStrokeCssPx),Ce(t,"minTextCssPx",e.dwfMinTextCssPx),Ce(t,"minFilledAreaCssPx",e.dwfMinFilledAreaCssPx),(o=t.render)==null||o.call(t)}}getLastNativeStats(){return this.lastStats}}function Et(n,e,t,i){var a,c;const s=At((n==null?void 0:n.diagnostics)??[]),r=((n==null?void 0:n.pageData)??[]).map((h,l)=>si(h,l));for(const h of(n==null?void 0:n.pageData)??[])s.push(...At(h.diagnostics));const o={parser:"dwf-viewer",nativeRenderer:"dwf-viewer",dwfKind:n==null?void 0:n.kind,packageEntries:((a=n==null?void 0:n.packageEntries)==null?void 0:a.length)??0,resources:((c=n==null?void 0:n.resources)==null?void 0:c.length)??0,pageKinds:fi(((n==null?void 0:n.pageData)??[]).map(h=>h.kind)),pageNames:((n==null?void 0:n.pages)??[]).map(h=>h.name)};return xe({format:t,sourceName:e,layers:{},blocks:{},pages:r,entities:Wn(r),metadata:o,warnings:ui(s),raw:i?n:void 0})}function si(n,e){const t=ri(n,e);return{index:e,name:n.name||n.sourcePath||`${e+1}`,width:n.width||1e3,height:n.height||1e3,entities:t}}function ri(n,e){return n.kind==="w2d-text"?n.primitives.flatMap((t,i)=>oi(t,e,i)):n.kind==="image"?[{type:"DWF_IMAGE_PAGE",kind:"image",pageIndex:e,width:n.width,height:n.height,imageSource:n.sourcePath}]:n.kind==="w3d-model"?n.model.meshes.map((t,i)=>({id:t.id,type:"W3D_MESH",kind:"solid",pageIndex:e,color:t.color?di(t.color):void 0,name:t.name||`mesh-${i+1}`,raw:{vertexCount:t.vertexCount,triangleCount:t.triangleCount,materialId:t.materialId}})):n.kind==="xps-fixed-page"?[{type:"XPS_FIXED_PAGE",kind:"viewport",pageIndex:e,width:n.width,height:n.height,raw:{sourcePath:n.sourcePath}}]:[{type:"DWF_PAGE",kind:"viewport",pageIndex:e,width:n.width,height:n.height,raw:{sourcePath:n.sourcePath}}]}function oi(n,e,t){const i={id:`dwf-${e}-${t}`,pageIndex:e,color:n.stroke,fillColor:n.fill,lineweight:n.lineWidth,raw:{matrix:n.matrix}};if(n.type==="polyline"||n.type==="polygon")return[{...i,type:n.type==="polygon"?"DWF_POLYGON":"DWF_POLYLINE",kind:"polyline",vertices:ai(n.points),isClosed:n.type==="polygon"}];if(n.type==="path")return[{...i,type:"DWF_PATH",kind:"path",commands:n.commands}];if(n.type==="text")return[{...i,type:"DWF_TEXT",kind:"text",insertionPoint:{x:n.x,y:n.y,z:0},text:n.text,textHeight:n.size}];if(n.type==="rect"){const s=n.x,r=n.y,o=n.width,a=n.height;return[{...i,type:"DWF_RECT",kind:"polyline",isClosed:!0,vertices:[{x:s,y:r,z:0},{x:s+o,y:r,z:0},{x:s+o,y:r+a,z:0},{x:s,y:r+a,z:0}]}]}return[]}function ai(n){const e=[];for(let t=0;t+1<n.length;t+=2)e.push({x:n[t],y:n[t+1],z:0});return e}function At(n){return n.filter(e=>e.level!=="info").map(e=>`${e.code}: ${e.message}${e.source?` (${e.source})`:""}`)}function It(n,e){return e==="dwf"||e==="dwfx"||e==="xps"?e:n==="dwf"||n==="dwfx"||n==="xps"?n:"dwf"}function ci(n){if(n.dwfWasmUrl)return n.dwfWasmUrl;if(typeof document>"u")return;const e=n.wasmPath?new URL(li(n.wasmPath),document.baseURI).href:new URL("wasm/",document.baseURI).href;return new URL("dwfv-render.wasm",e).href}function Lt(n){if(n.dwfBackground)return n.dwfBackground;const e=n.canvasOptions;return(e==null?void 0:e.background)??"#05070d"}function hi(n,e,t){return{...Ft(n,e,t),maxDevicePixelRatio:n.dwfMaxDevicePixelRatio??2,maxCanvasPixels:n.dwfMaxCanvasPixels??16777216}}function Ft(n,e,t){return{wasmUrl:e,preferWebgl:n.dwfPreferWebgl??!0,preferWasm:n.dwfPreferWasm??!0,background:t,maxGpuCacheBytes:n.dwfMaxGpuCacheBytes??160*1024*1024,maxCachedScenes:n.dwfMaxCachedScenes??2,lineWeightMode:n.dwfLineWeightMode??"adaptive",minStrokeCssPx:n.dwfMinStrokeCssPx,maxOverviewStrokeCssPx:n.dwfMaxOverviewStrokeCssPx,minTextCssPx:n.dwfMinTextCssPx,minFilledAreaCssPx:n.dwfMinFilledAreaCssPx}}function Ce(n,e,t){typeof t=="number"&&Number.isFinite(t)&&(n[e]=t)}function li(n){return n.endsWith("/")?n:`${n}/`}function di(n){const[e,t,i]=n.map(s=>Math.max(0,Math.min(255,Math.round(s*255))));return`#${Ue(e)}${Ue(t)}${Ue(i)}`}function Ue(n){return n.toString(16).padStart(2,"0")}function fi(n){const e={};for(const t of n)e[t]=(e[t]??0)+1;return e}function ui(n){return Array.from(new Set(n))}function Dt(n={}){return new ft([new yt(n),new Ct(n),new Tt(n)])}class F{static byteToSByte(e){return(e&127)-(e&128?128:0)}constructor(e){this.position=0,this.data=new DataView(e)}readBytes(e=1){this.data.byteLength<this.position+e&&this.throwOutOfRangeError(this.position+e);const t=new Uint8Array(this.data.buffer,this.position,e);return this.position+=e,t}skip(e){this.data.byteLength<this.position+e&&this.throwOutOfRangeError(this.position+e),this.position+=e}readUint8(){this.data.byteLength<this.position+1&&this.throwOutOfRangeError(this.position+1);const e=this.data.getUint8(this.position);return this.position+=1,e}readInt8(){this.data.byteLength<this.position+1&&this.throwOutOfRangeError(this.position+1);const e=this.data.getInt8(this.position);return this.position+=1,e}readUint16(e=!0){this.data.byteLength<this.position+2&&this.throwOutOfRangeError(this.position+2);const t=this.data.getUint16(this.position,e);return this.position+=2,t}readInt16(){this.data.byteLength<this.position+2&&this.throwOutOfRangeError(this.position+2);const e=this.data.getInt16(this.position,!0);return this.position+=2,e}readUint32(){this.data.byteLength<this.position+4&&this.throwOutOfRangeError(this.position+4);const e=this.data.getUint32(this.position,!0);return this.position+=4,e}readInt32(){this.data.byteLength<this.position+4&&this.throwOutOfRangeError(this.position+4);const e=this.data.getInt32(this.position,!0);return this.position+=4,e}readFloat32(){this.data.byteLength<this.position+4&&this.throwOutOfRangeError(this.position+4);const e=this.data.getFloat32(this.position,!0);return this.position+=4,e}readFloat64(){this.data.byteLength<this.position+8&&this.throwOutOfRangeError(this.position+8);const e=this.data.getFloat64(this.position,!0);return this.position+=8,e}setPosition(e){this.data.byteLength<e&&this.throwOutOfRangeError(e),this.position=e}isEnd(){return this.position===this.data.byteLength-1}get currentPosition(){return this.position}get length(){return this.data.byteLength}throwOutOfRangeError(e){throw new Error(`Position ${e} is out of range for the data length ${this.data.byteLength}!`)}}var N=(n=>(n.SHAPES="shapes",n.BIGFONT="bigfont",n.UNIFONT="unifont",n))(N||{});class mi{parse(e){const t=this.parseHeader(e).split(" "),i=t[1].toLocaleLowerCase();if(!Object.values(N).includes(i))throw new Error(`Invalid font type: ${i}`);return{fileHeader:t[0],fontType:i,fileVersion:t[2]}}parseHeader(e){let t="",i=0;for(;e.currentPosition<e.length-2&&i<1024;){const s=e.readUint8();if(s===13){const r=e.currentPosition,o=e.readUint8(),a=e.readUint8();if(o===10&&a===26)break;e.setPosition(r),t+=String.fromCharCode(s)}else t+=String.fromCharCode(s);i++}return t.trim()}}const te=10,pi=[13,10,0];function Bt(n,e){if(e===0){n.orientation="horizontal";return}if(e===2){n.orientation="horizontal",n.dualOrientation=!0;return}n.orientation="vertical"}function Rt(n){const e={};for(const[t,i]of Object.entries(n))e[i]=t;return e}function Ot(n){const e=n.indexOf(0);return e<0?{name:null,bytecode:n}:{name:e>0?new TextDecoder("ascii").decode(n.subarray(0,e)):null,bytecode:n.subarray(e+1)}}class gi{parse(e){try{e.readBytes(4);const t=e.readInt16();if(t<=0)throw new Error("Invalid shape count in font file");const i=[];for(let c=0;c<t;c++){const h=e.readUint16(),l=e.readUint16();l>0&&i.push({code:h,length:l})}const s={};for(const c of i)try{const h=e.readBytes(c.length);h.length===c.length&&(s[c.code]=h)}catch{console.warn(`Failed to read shape data for code ${c.code}`)}const r={},o={};for(const[c,h]of Object.entries(s)){const l=Number(c);if(l===0){r[l]=h;continue}const{name:d,bytecode:f}=Ot(h);r[l]=f,d&&(o[d]=l)}const a={data:r,names:Object.keys(o).length>0?o:void 0,codeToName:Object.keys(o).length>0?Rt(o):void 0,info:"",baseUp:8,baseDown:2,height:te,width:te,orientation:"horizontal",isExtended:!1};if(0 in r){const c=r[0];try{const h=new TextDecoder().decode(c);let l=c.findIndex(d=>pi.includes(d));l>=0&&(a.info=h.substring(0,l),l+3<c.length&&(a.baseUp=c[l+1],a.baseDown=c[l+2],a.height=a.baseDown+a.baseUp,a.width=a.height,Bt(a,c[l+3])))}catch{console.warn("Failed to parse font info block")}}return a}catch(t){const i=t instanceof Error?t.message:String(t);throw new Error(`Failed to parse shape font: ${i}`)}}}class yi{parse(e){try{e.readInt16();const t=e.readInt16(),i=e.readInt16();if(t<=0)throw new Error("Invalid character count in font file");e.skip(i*4);const s=[];for(let a=0;a<t;a++){const c=e.readUint16(),h=e.readUint16(),l=e.readUint32();(c!==0||h!==0||l!==0)&&s.push({code:c,length:h,offset:l})}const r={};for(const a of s)try{e.setPosition(a.offset);const c=e.readBytes(a.length);c.length===a.length&&(r[a.code]=c)}catch{console.warn(`Failed to read bigfont data for code ${a.code}`)}const o={data:r,info:"",baseUp:8,baseDown:2,height:te,width:te,orientation:"horizontal",isExtended:!1};if(0 in r){const a=r[0];try{const c=this.utf8ArrayToStr(a);if(c.pos>=0){let h=c.text;for(;h.length>0&&h.charCodeAt(h.length-1)===0;)h=h.slice(0,-1);o.info=h;const l=this.parseBigfontMetrics(a,c.pos+1);l&&Object.assign(o,l)}}catch{console.warn("Failed to parse bigfont info block")}}return o}catch(t){const i=t instanceof Error?t.message:String(t);throw new Error(`Failed to parse big font: ${i}`)}}parseBigfontMetrics(e,t){let i=t;for(;i<e.length&&e[i]===0;)i++;const s=e.length-i;if(s<=0)return null;const r=o=>o===0?"horizontal":"vertical";if(s>=5){const o=e[i++];i++;const a=r(e[i++]),c=e[i++];return{baseUp:o,baseDown:0,height:o,width:c,orientation:a,isExtended:!0}}if(s===4&&e[i+1]===0&&e[i+3]>0&&e[i+3]!==e[i]){const o=e[i++];i++;const a=r(e[i++]),c=e[i];return{baseUp:o,baseDown:0,height:o,width:c,orientation:a,isExtended:!0}}if(s===4){const o=e[i++],a=e[i++],c=r(e[i++]);return{baseUp:o,baseDown:a,height:o+a,width:o+a,orientation:c,isExtended:!1}}if(s===3){const o=e[i++],a=e[i++],c=r(a),h=a===2;return{baseUp:o,baseDown:0,height:o,width:o,orientation:c,isExtended:h,verticalDualMode:h}}return null}utf8ArrayToStr(e){let t="",i=0;for(;i<e.length;){const s=e[i];switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:t+=String.fromCharCode(s);break;case 12:case 13:{const r=e[i++];t+=String.fromCharCode((s&31)<<6|r&63);break}case 14:{const r=e[i++],o=e[i++];t+=String.fromCharCode((s&15)<<12|(r&63)<<6|(o&63)<<0);break}}if(t.charCodeAt(t.length-1)===0)break;i++}return{text:t,pos:i}}}class bi{parse(e){try{const t=e.readInt32();if(t<=0)throw new Error("Invalid character count in font file");const i=e.readInt16(),s=e.readBytes(i),r={data:{},info:"",baseUp:8,baseDown:2,height:te,width:te,orientation:"horizontal",isExtended:!1};try{const c=new TextDecoder().decode(s);let h=c.indexOf("\0");h>=0&&(r.info=c.substring(0,h),h+3<s.length&&(r.baseUp=s[h+1],r.baseDown=s[h+2],r.height=r.baseUp+r.baseDown,r.width=r.height,Bt(r,s[h+3])))}catch{console.warn("Failed to parse unifont info block")}const o={},a={};for(let c=0;c<t-1;c++)try{const h=e.readUint16(),l=e.readUint16();if(l>0){const d=e.readBytes(l);if(d.length===l){const{name:f,bytecode:u}=Ot(d);u.length>0&&(o[h]=u,f&&(a[f]=h))}}}catch{console.warn("Failed to read unifont character data");break}return r.data=o,r.names=Object.keys(a).length>0?a:void 0,r.codeToName=Object.keys(a).length>0?Rt(a):void 0,r}catch(t){const i=t instanceof Error?t.message:String(t);throw new Error(`Failed to parse unifont: ${i}`)}}}class xi{static createParser(e){switch(e){case N.SHAPES:return new gi;case N.BIGFONT:return new yi;case N.UNIFONT:return new bi;default:throw new Error(`Unsupported font type: ${e}`)}}}const Wt=.2;class vi{markAlignedAdvanceExplicit(e){return!1}}class Se extends vi{constructor(e=Wt){super(),this.cellWidthFactor=e}static isCenterOriginGlyph(e){return e.bbox.minX<-1e-6}static computeAdvance(e,t,i=Wt){if(!e.polylines.some(o=>o.length>=2))return t*i;const s=t*i,{maxX:r}=e.bbox;return Se.isCenterOriginGlyph(e)?Math.max(r,t/2)+s:r+s}resolve(e,t){var i;return e.hasExplicitAdvance?((i=e.lastPoint)==null?void 0:i.x)??0:Se.computeAdvance(e,t,this.cellWidthFactor)}markAlignedAdvanceExplicit(e){return!0}}const de=new Se;class T{constructor(e=0,t=0){this.x=e,this.y=t}set(e,t){return this.x=e,this.y=t,this}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}normalize(){const e=this.length();return e!==0&&(this.x/=e,this.y/=e),this}clone(){return new T(this.x,this.y)}add(e){return this.x+=e.x,this.y+=e.y,this}subtract(e){return this.x-=e.x,this.y-=e.y,this}multiply(e){return this.x*=e,this.y*=e,this}divide(e){return e!==0&&(this.x/=e,this.y/=e),this}multiplyScalars(e,t){return this.x*=e,this.y*=t,this}divideScalars(e,t){return e!==0&&(this.x/=e),t!==0&&(this.y/=t),this}distanceTo(e){const t=this.x-e.x,i=this.y-e.y;return Math.sqrt(t*t+i*i)}}function Yt(n){const{width:e,capHeight:t,descenderHeight:i,origin:s="baseline"}=n,r=t+i;return s==="top"?{minX:-e/2,maxX:e/2,minY:-r,maxY:0}:{minX:0,maxX:e,minY:-i,maxY:t}}function wi(n){return[n.minX,n.minY,n.maxX,n.maxY].every(Number.isFinite)}function Pi(n,e,t=1e-6){return e.minX>=n.minX-t&&e.maxX<=n.maxX+t&&e.minY>=n.minY-t&&e.maxY<=n.maxY+t}function Ci(n,e){return{minX:Math.min(n.minX,e.minX),minY:Math.min(n.minY,e.minY),maxX:Math.max(n.maxX,e.maxX),maxY:Math.max(n.maxY,e.maxY)}}function Si(n,e,t){const i=n.maxX-n.minX,s=n.maxY-n.minY;return`<rect x="${n.minX}" y="${-n.maxY}" width="${i}" height="${s}" fill="none" stroke="${e}" stroke-width="${t}"/>`}function Xt(n,e){const t=n.maxX-n.minX,i=n.maxY-n.minY;return`<rect x="${n.minX}" y="${-n.maxY}" width="${t}" height="${i}" fill="${e}"/>`}function ki(n,e,t,i,s,r,o){const a=` stroke-dasharray="${o}"`;return`<line x1="${n}" y1="${-e}" x2="${t}" y2="${-i}" stroke="${s}" stroke-width="${r}"${a}/>`}function Ni(n,e,t){const{capHeight:i,descenderHeight:s,origin:r="baseline"}=n,o=i+s,a=Yt(n);let c,h,l;r==="top"?(i>0&&(c={minX:a.minX,maxX:a.maxX,minY:-i,maxY:0}),s>0&&(h={minX:a.minX,maxX:a.maxX,minY:-o,maxY:-i}),l=-i):(i>0&&(c={minX:a.minX,maxX:a.maxX,minY:0,maxY:i}),s>0&&(h={minX:a.minX,maxX:a.maxX,minY:-s,maxY:0}),l=0);const d=[c?Xt(c,"rgba(255, 0, 0, 0.06)"):"",h?Xt(h,"rgba(255, 0, 0, 0.14)"):"",Si(a,e,t)];return l!==void 0&&s>0&&i>0&&d.push(ki(a.minX,l,a.maxX,l,e,t,"4 2")),`<g>${d.join("")}</g>`}class ne{constructor(e,t=[],i=!1){this.lastPoint=e,this.polylines=t,this.hasExplicitAdvance=i}get bbox(){if(this._bbox)return this._bbox;let e=1/0,t=-1/0,i=1/0,s=-1/0;return this.polylines.forEach(r=>{r.forEach(o=>{e=Math.min(e,o.x),t=Math.max(t,o.x),i=Math.min(i,o.y),s=Math.max(s,o.y)})}),this._bbox={minX:e,minY:i,maxX:t,maxY:s},this._bbox}offset(e,t=!0){var i,s;return t?new ne((i=this.lastPoint)==null?void 0:i.clone().add(e),this.polylines.map(r=>r.map(o=>o.clone().add(e))),this.hasExplicitAdvance):((s=this.lastPoint)==null||s.add(e),this.polylines.forEach(r=>r.forEach(o=>o.add(e))),this._bbox&&(this._bbox.maxX+=e.x,this._bbox.minX+=e.x,this._bbox.maxY+=e.y,this._bbox.minY+=e.y),this)}normalizeToOrigin(e=!1){const t=this.bbox;return this.offset(new T(-t.minX,-t.minY),e)}toSVG(e={}){const{strokeWidth:t="0.5%",strokeColor:i="black",isAutoFit:s=!1,fontCell:r}=e;let o,a;const c=h=>this.polylines.map(l=>{let d="";return l.forEach((f,u)=>{const{x:p,y:w}=h(f);d+=u===0?`M ${p} ${w} `:`L ${p} ${w} `}),`<path d="${d}" stroke="${i}" stroke-width="${t}" fill="none"/>`}).join("");if(r){const{padding:h=.1,expandToFit:l=!1,showFrame:d=!1,frameColor:f="red",frameStrokeWidth:u="0.5%"}=r,p=Yt(r),w=this.bbox;let P=p;l&&wi(w)&&!Pi(p,w)&&(P=Ci(p,w));const g=P.maxX-P.minX,v=P.maxY-P.minY,C=g*h,S=v*h,I=P.minX-C,W=P.maxX+C,Ie=P.minY-S,Z=P.maxY+S;a=c(Y=>({x:Y.x,y:-Y.y}));const ce=d?Ni(r,f,u):"";return o=`${I} ${-Z} ${W-I} ${Z-Ie}`,`<svg width="100%" height="100%" viewBox="${o}" preserveAspectRatio="xMidYMid meet">${ce}${a}</svg>`}else if(s){const h=this.bbox,l=.2,d=h.maxX-h.minX,f=h.maxY-h.minY,u=d===0?f:d,p=f===0?d:f,w=h.minX-u*l,P=h.maxX+u*l,g=h.minY-p*l,v=h.maxY+p*l;a=c(C=>({x:C.x,y:-C.y})),o=`${w} ${-v} ${P-w} ${v-g}`}else o="0 0 20 20",a=c(h=>({x:h.x+5,y:-h.y+15}));return`<svg width="100%" height="100%" viewBox="${o}" preserveAspectRatio="xMidYMid meet">${a}</svg>`}}const zt=8,Ut=48,Mi=.4,Ti=[52164,45795,49829,50150,54992,47610,54754,46532,51906,53947,49332,51706,46532,54224,52946,52714,52219,45755,51403,46532,53947,50410,49332,52219,52141,46532,50150,51120,50150,54992,51663,50119,53186,46532,46525,51365,52149,47016,46532,51889,51706,46025,47037,55031,48122,50935,47531,48122,51965,55e3];function ke(n,e){const{height:t,width:i,baseUp:s,baseDown:r}=n,o=t>0?e/t:1,a=o*s,c=o*r;return{size:e,capHeight:a,descenderHeight:c,cellWidth:o*i,totalHeight:a+c}}function Ei(n,e,t){if(n.header.fontType!==N.SHAPES||!(0 in n.content.data))return!1;const i=-(t.descenderHeight+t.capHeight*.2);return e.bbox.minY<i}function _t(n,e){const t=-(e.descenderHeight+e.capHeight*.05);return!(n.bbox.minY<t||n.bbox.maxY-n.bbox.minY<e.capHeight*.05)}function Ai(n,e,t){if(n.header.fontType!==N.BIGFONT||n.content.baseDown>0)return 0;const{height:i}=n.content;if(i<=0)return 0;const s=i*Mi,r=[],o=new Set,a=h=>{if(o.has(h)||h<=255||!(h in n.content.data))return;o.add(h);const l=e(h);if(!l)return;const d=l.bbox.minY;d>0&&d<=s&&r.push(d)};for(const h of Ti)if(a(h),r.length>=Ut)break;if(r.length<zt){for(const h of Object.keys(n.content.data))if(a(Number(h)),r.length>=Ut)break}if(r.length<zt)return 0;r.sort((h,l)=>h-l);const c=Math.floor(r.length/2);return r.length%2===0?(r[c-1]+r[c])/2:r[c]}function Ii(n,e,t){if(n.header.fontType!==N.UNIFONT)return!1;if(n.content.dualOrientation)return!0;const i=ke(n.content,t);for(const s of[48,65,78,49]){if(!(s in n.content.data))continue;const r=e(s);if(r&&_t(r,i))return!0}return!1}function Li(n,e,t,i=de,s=!1,r=0){var o;let a=n;if(e.header.fontType===N.BIGFONT&&r>0){const l=e.content.height>0?t.size/e.content.height:1;a=a.offset(new T(0,-r*l),!0)}if(e.header.fontType===N.UNIFONT||Ei(e,n,t)){const l=e.header.fontType===N.UNIFONT&&(s||e.content.dualOrientation||_t(n,t));(e.header.fontType!==N.UNIFONT||!l)&&(a=a.offset(new T(0,t.capHeight),!0))}const c=i.resolve(a,t.cellWidth),h=i.markAlignedAdvanceExplicit(a)?!0:a.hasExplicitAdvance;return new ne(new T(c,((o=a.lastPoint)==null?void 0:o.y)??0),a.polylines,h)}function Fi(n,e,t,i=de,s=!1,r=0){const o=ke(e.content,t);return Li(n,e,o,i,s,r)}const Ht=Math.PI/4;class fe{static fromBulge(e,t,i){const s=Math.max(-1,Math.min(1,i));return new fe({start:e,end:t,bulge:s})}static fromOctant(e,t,i,s,r){return new fe({center:e,radius:t,startOctant:i,octantCount:s,isClockwise:r})}constructor(e){if(e.start&&e.end&&e.bulge!==void 0){this.start=e.start.clone(),this.end=e.end.clone(),this.bulge=e.bulge,this.isClockwise=e.bulge<0;const t=this.end.clone().subtract(this.start),i=t.length();if(Math.abs(this.bulge)*i/2===0){this.radius=0,this.center=this.start.clone(),this.startAngle=Math.atan2(t.y,t.x),this.endAngle=this.startAngle;return}const s=4*Math.atan(Math.abs(this.bulge));this.radius=i/(2*Math.sin(s/2));const r=this.start.clone().add(t.clone().divide(2)),o=new T(-t.y,t.x);o.normalize(),o.multiply(Math.abs(this.radius*Math.cos(s/2))),this.center=r.clone(),this.isClockwise?this.center.subtract(o):this.center.add(o),this.startAngle=Math.atan2(this.start.y-this.center.y,this.start.x-this.center.x),this.endAngle=Math.atan2(this.end.y-this.center.y,this.end.x-this.center.x),this.isClockwise?this.endAngle>=this.startAngle&&(this.endAngle-=2*Math.PI):this.endAngle<=this.startAngle&&(this.endAngle+=2*Math.PI)}else if(e.center&&e.radius!==void 0&&e.startOctant!==void 0&&e.octantCount!==void 0&&e.isClockwise!==void 0){this.center=e.center.clone(),this.radius=e.radius,this.isClockwise=e.isClockwise,this.startAngle=e.startOctant*Ht;const t=(e.octantCount===0?8:e.octantCount)*Ht;this.endAngle=this.startAngle+(this.isClockwise?-t:t),this.start=this.center.clone().add(new T(this.radius*Math.cos(this.startAngle),this.radius*Math.sin(this.startAngle))),this.end=this.center.clone().add(new T(this.radius*Math.cos(this.endAngle),this.radius*Math.sin(this.endAngle)))}else throw new Error("Invalid arc parameters")}tessellate(e=Math.PI/18){if(this.radius===0)return[this.start.clone(),this.end.clone()];const t=[this.start.clone()],i=Math.abs(this.endAngle-this.startAngle),s=Math.max(1,Math.floor(i/e));for(let r=1;r<s;r++){const o=r/s,a=this.isClockwise?this.startAngle-o*i:this.startAngle+o*i;t.push(this.center.clone().add(new T(this.radius*Math.cos(a),this.radius*Math.sin(a))))}return t.push(this.end?this.end.clone():this.center.clone().add(new T(this.radius*Math.cos(this.endAngle),this.radius*Math.sin(this.endAngle)))),t}}const Di=Math.PI/18,Bi=1e-6;class Ri{constructor(e){this.shapeCache=new Map,this.subshapeCache=new Map,this.shapeData=new Map,this.fontData=e}release(){this.shapeCache.clear(),this.subshapeCache.clear(),this.shapeData.clear()}getCharShape(e,t){const i=this.fontData.header.fontType===N.SHAPES&&!(0 in this.fontData.content.data)?t:t/this.fontData.content.height;return this.parseAndScale(e,{factor:i})}parseAndScale(e,t){if(e===0)return;let i;if(this.shapeCache.has(e))i=this.shapeCache.get(e);else{const s=this.fontData.content.data;if(s[e]){const r=this.prepareBigfontGlyphBytecode(e,s[e]),o=this.fontData.header.fontType!==N.BIGFONT;i=this.parseShape(r,{flushOnEnd:!0,initialPenDown:o}),this.shapeData.set(e,i),this.shapeCache.set(e,i)}}if(i){if(t.factor!==void 0)return this.scaleShapeByFactor(i,t.factor);if(t.height!==void 0){const s=t.width??t.height;return this.scaleShapeByHeightAndWidth(i,t.height,s)}else return i}}prepareBigfontGlyphBytecode(e,t){if(this.fontData.header.fontType!==N.BIGFONT||e<=255)return t;const i=e>>8&255,s=e&255;if(t.length>=2&&t[0]===i&&t[1]===s){let r=2;return t[r]===0&&r++,t.slice(r)}return t}isVerticalDualBigfontMarker(e,t,i){return this.fontData.content.verticalDualMode?i==="open"?e[t]===142:e[t]===143:!1}scaleShapeByFactor(e,t){var i;return new ne((i=e.lastPoint)==null?void 0:i.clone().multiply(t),e.polylines.map(s=>s.map(r=>r.clone().multiply(t))),e.hasExplicitAdvance)}scaleShapeByHeightAndWidth(e,t,i){var s;const r=e.bbox,o=r.maxY-r.minY,a=r.maxX-r.minX,c=o>0?t/o:1,h=a>0?i/a:1,l=(s=e.lastPoint)==null?void 0:s.clone();l&&(l.x*=h,l.y*=c);const d=e.polylines.map(f=>f.map(u=>{const p=u.clone();return p.x*=h,p.y*=c,p}));return new ne(l,d,e.hasExplicitAdvance)}shouldSkipVerticalFlagCommand(e=!1){const{content:t,header:i}=this.fontData;return i.fontType===N.BIGFONT?!t.verticalDualMode:t.dualOrientation?!e:t.orientation==="horizontal"}markAdvanceDefined(e){e.hasExplicitAdvance=!0}notePenUpPositioning(e){e.pendingTerminalAdvance=!0}clearPendingAdvance(e){e.pendingTerminalAdvance=!1}stateHasInk(e){return e.currentPolyline.length>1?!0:e.polylines.some(t=>t.length>=2)}finalizeAdvanceFlag(e){if(!e.pendingTerminalAdvance)return;const t=e.currentPoint.x;if(Math.abs(t)>Bi){e.hasExplicitAdvance=!0;return}this.stateHasInk(e)||(e.hasExplicitAdvance=!0)}parseShape(e,t={}){let i=new T;const s=[];let r=[];const o=[];let a=t.initialPenDown??!1;a&&r.push(i.clone());const c={currentPoint:i,polylines:s,currentPolyline:r,sp:o,isPenDown:a,scale:1,flushEndPolyline:t.flushOnEnd??!1,hasExplicitAdvance:!1,pendingTerminalAdvance:!1};for(let h=0;h<e.length;h++){const l=e[h];l<=15?h=this.handleSpecialCommand(l,e,h,c):(this.clearPendingAdvance(c),this.handleVectorCommand(l,c))}return this.finalizeAdvanceFlag(c),this.buildShapeFromState(c)}buildShapeFromState(e){const t=e.polylines.map(i=>i.map(s=>s.clone()));return e.currentPolyline.length>1&&t.push(e.currentPolyline.map(i=>i.clone())),new ne(e.currentPoint.clone(),t,e.hasExplicitAdvance)}handleSpecialCommand(e,t,i,s){let r=i;switch(e){case 0:this.finalizeAdvanceFlag(s),s.flushEndPolyline&&s.currentPolyline.length>1?(s.polylines.push(s.currentPolyline.slice()),s.currentPolyline=[]):s.flushEndPolyline&&(s.currentPolyline=[]),s.isPenDown=!1;break;case 1:this.clearPendingAdvance(s),s.isPenDown||s.currentPolyline.push(s.currentPoint.clone()),s.isPenDown=!0;break;case 2:s.isPenDown=!1,s.currentPolyline.length>1&&s.polylines.push(s.currentPolyline.slice()),s.currentPolyline=[];break;case 3:this.clearPendingAdvance(s),r++,s.scale/=t[r];break;case 4:this.clearPendingAdvance(s),r++,s.scale*=t[r];break;case 5:if(this.clearPendingAdvance(s),s.sp.length===4)throw new Error("The position stack is only four locations deep");s.sp.push(s.currentPoint.clone());break;case 6:this.clearPendingAdvance(s),s.currentPoint=s.sp.pop()??s.currentPoint,s.currentPolyline.length>1&&(s.polylines.push(s.currentPolyline.slice()),s.currentPolyline=[]),s.isPenDown&&s.currentPolyline.push(s.currentPoint.clone());break;case 7:this.clearPendingAdvance(s),r=this.handleSubshapeCommand(t,r,s);break;case 8:r=this.handleXYDisplacement(t,r,s);break;case 9:r=this.handleMultipleXYDisplacements(t,r,s);break;case 10:this.clearPendingAdvance(s),r=this.handleOctantArc(t,r,s);break;case 11:this.clearPendingAdvance(s),r=this.handleFractionalArc(t,r,s);break;case 12:this.clearPendingAdvance(s),r=this.handleBulgeArc(t,r,s);break;case 13:this.clearPendingAdvance(s),r=this.handleMultipleBulgeArcs(t,r,s);break;case 14:this.clearPendingAdvance(s),this.shouldSkipVerticalFlagCommand()&&(r=this.skipCode(t,++r));break}return r}handleVectorCommand(e,t){const i=(e&240)>>4,s=e&15,r=this.getVectorForDirection(s);t.currentPoint.add(r.multiply(i*t.scale)),t.isPenDown&&t.currentPolyline.push(t.currentPoint.clone())}getVectorForDirection(e){const t=new T;switch(e){case 0:t.x=1;break;case 1:t.x=1,t.y=.5;break;case 2:t.x=1,t.y=1;break;case 3:t.x=.5,t.y=1;break;case 4:t.y=1;break;case 5:t.x=-.5,t.y=1;break;case 6:t.x=-1,t.y=1;break;case 7:t.x=-1,t.y=.5;break;case 8:t.x=-1;break;case 9:t.x=-1,t.y=-.5;break;case 10:t.x=-1,t.y=-1;break;case 11:t.x=-.5,t.y=-1;break;case 12:t.y=-1;break;case 13:t.x=.5,t.y=-1;break;case 14:t.x=1,t.y=-1;break;case 15:t.x=1,t.y=-.5;break}return t}handleSubshapeCommand(e,t,i){let s=t,r=0,o,a=i.scale*this.fontData.content.baseUp,c=a;const h=i.currentPoint.clone();switch(i.currentPolyline.length>1&&(i.polylines.push(i.currentPolyline.slice()),i.currentPolyline=[]),this.fontData.header.fontType){case N.SHAPES:s++,r=e[s];break;case N.BIGFONT:if(s++,this.isVerticalDualBigfontMarker(e,s,"open"))return s;if(this.isVerticalDualBigfontMarker(e,s,"close"))return s+1;r=e[s],r===0&&(s++,r=e[s++]<<8|e[s++],h.x=F.byteToSByte(e[s++])*i.scale,h.y=F.byteToSByte(e[s++])*i.scale,this.fontData.content.isExtended?(c=e[s++]*i.scale,a=e[s]*i.scale):(a=e[s]*i.scale,c=a));break;case N.UNIFONT:s++,r=e[s++]<<8|e[s++],s--;break}if(r!==0)if(this.fontData.header.fontType===N.UNIFONT){const l=i.isPenDown;o=this.getScaledSubshapeAtInsertPoint(r,c,a,h,l),o!=null&&o.polylines.some(d=>d.length>=2)&&(i.polylines.push(...o.polylines.slice()),o.lastPoint&&(i.currentPoint=o.lastPoint.clone()),i.currentPolyline=[],i.isPenDown&&i.currentPolyline.push(i.currentPoint.clone()))}else if(this.fontData.header.fontType===N.SHAPES)o=this.getScaledSubshapeAtInsertPoint(r,c,a,h),o&&(i.polylines.push(...o.polylines.slice()),o.lastPoint&&(i.currentPoint=o.lastPoint.clone(),o.hasExplicitAdvance&&this.markAdvanceDefined(i))),i.currentPolyline=[],i.isPenDown&&i.currentPolyline.push(i.currentPoint.clone());else{if(o=this.getScaledSubshapeAtInsertPoint(r,c,a,h),o&&(i.polylines.push(...o.polylines.slice()),r===2&&o.lastPoint)){const l=o.lastPoint.x-h.x;l>i.currentPoint.x&&(i.currentPoint.x=l),this.markAdvanceDefined(i)}i.currentPolyline=[]}return s}handleXYDisplacement(e,t,i){let s=t;const r=new T;return r.x=F.byteToSByte(e[++s]),r.y=F.byteToSByte(e[++s]),i.currentPoint.add(r.multiply(i.scale)),i.isPenDown?i.currentPolyline.push(i.currentPoint.clone()):this.notePenUpPositioning(i),s}handleMultipleXYDisplacements(e,t,i){let s=t;for(;!(s+1>=e.length);){const r=new T;if(r.x=F.byteToSByte(e[++s]),r.y=F.byteToSByte(e[++s]),r.x===0&&r.y===0)break;i.currentPoint.add(r.multiply(i.scale)),i.isPenDown?i.currentPolyline.push(i.currentPoint.clone()):this.notePenUpPositioning(i)}return s}handleOctantArc(e,t,i){let s=t;const r=e[++s]*i.scale,o=F.byteToSByte(e[++s]),a=(o&112)>>4;let c=o&7;const h=o<0,l=Math.PI/4*a,d=i.currentPoint.clone().subtract(new T(Math.cos(l)*r,Math.sin(l)*r)),f=fe.fromOctant(d,r,a,c,h).tessellate();return i.isPenDown&&(i.currentPolyline.pop(),i.currentPolyline.push(...f.slice())),i.currentPoint=f[f.length-1].clone(),s}handleFractionalArc(e,t,i){let s=t;const r=e[++s],o=e[++s],a=e[++s],c=e[++s],h=(a*255+c)*i.scale,l=F.byteToSByte(e[++s]),d=(l&112)>>4;let f=l&7;f===0&&(f=8),o!==0&&f--;const u=Math.PI/4;let p=u*f,w=Di,P=1;l<0&&(w=-w,p=-p,P=-1);let g=u*d,v=g+p;g+=u*r/256*P,v+=u*o/256*P;const C=i.currentPoint.clone().subtract(new T(h*Math.cos(g),h*Math.sin(g)));if(i.currentPoint=C.clone().add(new T(h*Math.cos(v),h*Math.sin(v))),i.isPenDown){let S=g;const I=[];if(I.push(C.clone().add(new T(h*Math.cos(S),h*Math.sin(S)))),w>0)for(;S+w<v;)S+=w,I.push(C.clone().add(new T(h*Math.cos(S),h*Math.sin(S))));else for(;S+w>v;)S+=w,I.push(C.clone().add(new T(h*Math.cos(S),h*Math.sin(S))));I.push(C.clone().add(new T(h*Math.cos(v),h*Math.sin(v)))),i.currentPolyline.push(...I)}return s}handleBulgeArc(e,t,i){let s=t;const r=new T;r.x=F.byteToSByte(e[++s]),r.y=F.byteToSByte(e[++s]);const o=F.byteToSByte(e[++s]);return i.currentPoint=this.handleArcSegment(i.currentPoint,r,o,i.scale,i.isPenDown,i.currentPolyline),s}handleMultipleBulgeArcs(e,t,i){let s=t;for(;!(s+1>=e.length);){const r=new T;if(r.x=F.byteToSByte(e[++s]),r.y=F.byteToSByte(e[++s]),r.x===0&&r.y===0||s+1>=e.length)break;const o=F.byteToSByte(e[++s]);i.currentPoint=this.handleArcSegment(i.currentPoint,r,o,i.scale,i.isPenDown,i.currentPolyline)}return s}skipCode(e,t){switch(e[t]){case 0:break;case 1:break;case 2:break;case 3:case 4:t++;break;case 5:break;case 6:break;case 7:switch(this.fontData.header.fontType){case N.SHAPES:t++;break;case N.BIGFONT:t++,this.isVerticalDualBigfontMarker(e,t,"open")?t++:this.isVerticalDualBigfontMarker(e,t,"close")?t+=2:e[t]===0&&(t+=this.fontData.content.isExtended?6:5);break;case N.UNIFONT:t+=2;break}break;case 8:t+=2;break;case 9:for(;t++,!(t>=e.length);){const i=e[t];if(t++,t>=e.length)break;const s=e[t];if(i===0&&s===0)break}break;case 10:t+=2;break;case 11:t+=5;break;case 12:t+=3;break;case 13:for(;t++,!(t>=e.length);){const i=e[t];if(t++,t>=e.length)break;const s=e[t];if(i===0&&s===0)break;t++}break}return t}getScaledSubshapeAtInsertPoint(e,t,i,s,r=!1){let o;if(r){const h=this.fontData.content.data[e];if(!h)return;o=this.parseShape(h,{initialPenDown:!0,flushOnEnd:!0})}else if(o=this.subshapeCache.get(e),!o){const h=this.fontData.content.data[e];if(!h)return;const l=this.fontData.header.fontType!==N.BIGFONT;o=this.parseShape(h,{flushOnEnd:!1,initialPenDown:l}),this.shapeData.set(e,o),this.subshapeCache.set(e,o)}const a=this.fontData.header.fontType===N.BIGFONT?void 0:i/this.fontData.content.baseUp,c=o.polylines.some(h=>h.length>0);return(a!==void 0?this.scaleShapeByFactor(o,a):this.scaleShapeByHeightAndWidth(c?o.normalizeToOrigin(!0):o,i,t)).offset(s,!1)}handleArcSegment(e,t,i,s,r,o){t.x*=s,t.y*=s,i<-127&&(i=-127);const a=e.clone();if(r)if(i===0)o.push(a.clone().add(t));else{const c=a.clone().add(t),h=fe.fromBulge(a,c,i/127).tessellate();o.push(...h.slice(1))}return a.add(t),a}}class Oi{constructor(e){if(e instanceof ArrayBuffer){const t=new F(e),i=new mi().parse(t),s=xi.createParser(i.fontType).parse(t);this.fontData={header:i,content:s}}else this.fontData=e;this.shapeParser=new Ri(this.fontData)}hasChar(e){return this.fontData.content.data[e]!==void 0}hasShape(e){return this.getShapeCode(e)!==void 0}getShapeCode(e){const t=this.fontData.content.names;if(t)return t[e.toUpperCase()]}getShapeName(e){var t;const i=(t=this.fontData.content.codeToName)==null?void 0:t[e];if(i!==void 0)return i;const s=this.fontData.content.names;if(s){for(const[r,o]of Object.entries(s))if(o===e)return r}}getFontMetrics(e){return ke(this.fontData.content,e)}getLayoutCharShape(e,t,i=de){const s=this.getCharShape(e,t);if(s)return Fi(s,this.fontData,t,i,this.usesUnifontBaselineOriginFont(t),this.getBigfontBaselineInkPaddingNative())}getBigfontBaselineInkPaddingNative(){if(this.bigfontBaselineInkPaddingNative===void 0){const e=this.fontData.content.height;this.bigfontBaselineInkPaddingNative=Ai(this.fontData,t=>this.getCharShape(t,e))}return this.bigfontBaselineInkPaddingNative}usesUnifontBaselineOriginFont(e){return this.unifontBaselineOriginFont===void 0&&(this.unifontBaselineOriginFont=Ii(this.fontData,t=>this.getCharShape(t,e),e)),this.unifontBaselineOriginFont}getShapeByName(e,t){const i=this.getShapeCode(e);if(i!==void 0)return this.getCharShape(i,t)}getCharShape(e,t){return this.shapeParser.getCharShape(e,t)}release(){this.shapeParser.release()}}function Wi(n,e,t,i=de){const s=ke(e.content,t);return i.resolve(n,s.cellWidth)}function Yi(n,e,t=0){return n.offset(new T(e,t),!0)}function Xi(n,e=0,t={}){const i=t.advance??de;let s=0;const r=[];for(const{font:o,code:a,size:c}of n){const h=o.getLayoutCharShape(a,c,i);h&&(r.push({shape:Yi(h,s,e),x:s}),s+=Wi(h,o.fontData,c,i))}return r}const $t=Object.freeze({resolveShape:()=>{},resolveText:()=>{}}),Vt="Complex SHX linetype glyphs";class Gt{constructor(){m(this,"fonts",new Map);m(this,"requirements",[])}async add(e){var c;const t=_e(e.fileName??((c=e.file)==null?void 0:c.name));if(!t)throw new Error("A fileName is required when adding an SHX reference buffer.");if(!/\.shx$/i.test(t))throw new Error(`${t} is not an SHX reference file.`);if(!e.file&&!e.buffer)throw new Error(`No file content was provided for ${t}.`);const i=e.file?new Uint8Array(await e.file.arrayBuffer()):zi(e.buffer);if(i.byteLength===0)throw new Error(`${t} is empty.`);let s;try{s=new Oi(Ui(i))}catch(h){const l=h instanceof Error?h.message:String(h);throw new Error(`Unable to parse SHX reference ${t}: ${l}`)}const r=U(t),o=this.fonts.get(r),a={kind:"shx",fileName:t,bytes:i.byteLength,fontType:s.fontData.header.fontType,glyphCount:Object.keys(s.fontData.content.data).length};return this.fonts.set(r,{key:r,font:s,info:a,shapeCache:new Map,textCache:new Map}),o==null||o.font.release(),{...a}}setDocument(e){if(!e){this.requirements=[];return}const t=new Map,i=a=>{const c=_e(a),h=c?U(c):"*";let l=t.get(h);return l||(l={fileName:c||void 0,shapeNumbers:new Set,texts:new Set},t.set(h,l)),l};for(const a of new Set(Object.values(e.lineTypes??{})))for(const c of a.pattern){const h=Number(c.elementTypeFlag??0);if(h===0)continue;const l=i(c.fontName),d=Math.trunc(Number(c.shapeNumber));(h&4)===4&&Number.isFinite(d)&&l.shapeNumbers.add(d),(h&2)===2&&c.text&&l.texts.add(c.text)}const s=Array.isArray(e.metadata.requiredShxFonts)?e.metadata.requiredShxFonts:[];for(const a of s)i(String(a));const r=t.get("*"),o=[...t.entries()].filter(([a])=>a!=="*");if(r&&o.length===1){const a=o[0][1];for(const c of r.shapeNumbers)a.shapeNumbers.add(c);for(const c of r.texts)a.texts.add(c);t.delete("*")}this.requirements=[...t.values()]}has(e){return this.fonts.has(U(e))}remove(e){const t=U(e),i=this.fonts.get(t);return i?(i.font.release(),this.fonts.delete(t),!0):!1}clear(){for(const e of this.fonts.values())e.font.release();this.fonts.clear()}getState(){const e=[];for(const t of this.requirements){if(t.fileName){const s=this.fonts.get(U(t.fileName));s?Zt(s.font,t)||e.push({kind:"shx",fileName:t.fileName,identified:!0,reason:"incompatible"}):e.push({kind:"shx",fileName:t.fileName,identified:!0,reason:"not-loaded"});continue}[...this.fonts.values()].some(s=>Zt(s.font,t))||e.push({kind:"shx",fileName:"External SHX font",identified:!1,reason:this.fonts.size?"incompatible":"not-loaded"})}return{missing:e,loaded:[...this.fonts.values()].map(({info:t})=>({...t})).sort((t,i)=>t.fileName.localeCompare(i.fileName))}}resolveShape(e,t){const i=Math.trunc(Number(e));if(!Number.isFinite(i)||i<0)return;const s=this.resolveFont(t,a=>a.hasChar(i));if(!s)return;const r=s.shapeCache.get(i);if(r!==void 0)return r??void 0;let o;try{const a=s.font.getCharShape(i,1);o=a?qt(a.polylines):void 0}catch{o=void 0}return s.shapeCache.set(i,o??null),o}resolveText(e,t){if(!e)return;const i=Array.from(e,a=>a.codePointAt(0)??0),s=this.resolveFont(t,a=>i.every(c=>a.hasChar(c)));if(!s)return;const r=s.textCache.get(e);if(r!==void 0)return r??void 0;let o;try{const a=Xi(i.map(c=>({font:s.font,code:c,size:1})));o=qt(a.flatMap(({shape:c})=>c.polylines))}catch{o=void 0}return s.textCache.set(e,o??null),o}resolveFont(e,t){if(e){const r=this.fonts.get(U(e));return r&&t(r.font)?r:void 0}const i=this.requirements.map(({fileName:r})=>r?this.fonts.get(U(r)):void 0).filter(r=>r!==void 0&&t(r.font));if(i.length===1)return i[0];const s=[...this.fonts.values()].filter(r=>t(r.font));return s.length===1?s[0]:void 0}}function jt(n,e){const t=Array.isArray(n.metadata.requiredShxFonts)?n.metadata.requiredShxFonts.map(String):[];n.metadata.missingReferences=e.missing.map(s=>({...s})),n.metadata.loadedReferences=e.loaded.map(s=>({...s})),n.metadata.loadedShxFonts=t.filter(s=>e.loaded.some(r=>U(r.fileName)===U(s)));for(let s=n.warnings.length-1;s>=0;s--)n.warnings[s].startsWith(Vt)&&n.warnings.splice(s,1);if(e.missing.length===0)return;const i=e.missing.map(({fileName:s,reason:r})=>r==="incompatible"?`${s} (missing required glyphs)`:s);n.warnings.push(`${Vt} are using a dash/dot fallback until the missing reference${i.length===1?" is":"s are"} supplied: ${i.join(", ")}.`)}function _e(n){return String(n??"").trim().split(/[\\/]/).filter(Boolean).pop()??""}function U(n){return _e(n).toLocaleLowerCase("en-US")}function qt(n){const e=n.map(t=>t.filter(i=>Number.isFinite(i.x)&&Number.isFinite(i.y)).map(i=>({x:i.x,y:i.y}))).filter(t=>t.length>=2);return e.length>0?{polylines:e}:void 0}function Zt(n,e){for(const t of e.shapeNumbers)if(!n.hasChar(t))return!1;for(const t of e.texts)for(const i of t)if(!n.hasChar(i.codePointAt(0)??0))return!1;return!0}function zi(n){return n instanceof Uint8Array?n.slice():new Uint8Array(n.slice(0))}function Ui(n){return n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)}function Kt(n){const e=n;return e.nativeRenderer===!0&&typeof e.mount=="function"}const _i={1:"#ff0000",2:"#ffff00",3:"#00ff00",4:"#00ffff",5:"#0000ff",6:"#ff00ff",8:"#808080",9:"#c0c0c0",10:"#ff0000",11:"#ff7f7f",12:"#a50000",13:"#a55252",14:"#7f0000",15:"#7f3f3f",16:"#4c0000",17:"#4c2626",18:"#260000",19:"#261313",20:"#ff3f00",21:"#ff9f7f",22:"#a52900",23:"#a56752",24:"#7f1f00",25:"#7f4f3f",26:"#4c1300",27:"#4c2f26",28:"#260900",29:"#261713",30:"#ff7f00",31:"#ffbf7f",32:"#a55200",33:"#a57c52",34:"#7f3f00",35:"#7f5f3f",36:"#4c2600",37:"#4c3926",38:"#261300",39:"#261c13",40:"#ffbf00",41:"#ffdf7f",42:"#a57c00",43:"#a59152",44:"#7f5f00",45:"#7f6f3f",46:"#4c3900",47:"#4c4226",48:"#261c00",49:"#262113",50:"#ffff00",51:"#ffff7f",52:"#a5a500",53:"#a5a552",54:"#7f7f00",55:"#7f7f3f",56:"#4c4c00",57:"#4c4c26",58:"#262600",59:"#262613",60:"#bfff00",61:"#dfff7f",62:"#7ca500",63:"#91a552",64:"#5f7f00",65:"#6f7f3f",66:"#394c00",67:"#424c26",68:"#1c2600",69:"#212613",70:"#7fff00",71:"#bfff7f",72:"#52a500",73:"#7ca552",74:"#3f7f00",75:"#5f7f3f",76:"#264c00",77:"#394c26",78:"#132600",79:"#1c2613",80:"#3fff00",81:"#9fff7f",82:"#29a500",83:"#67a552",84:"#1f7f00",85:"#4f7f3f",86:"#134c00",87:"#2f4c26",88:"#092600",89:"#172613",90:"#00ff00",91:"#7fff7f",92:"#00a500",93:"#52a552",94:"#007f00",95:"#3f7f3f",96:"#004c00",97:"#264c26",98:"#002600",99:"#132613",100:"#00ff3f",101:"#7fff9f",102:"#00a529",103:"#52a567",104:"#007f1f",105:"#3f7f4f",106:"#004c13",107:"#264c2f",108:"#002609",109:"#132617",110:"#00ff7f",111:"#7fffbf",112:"#00a552",113:"#52a57c",114:"#007f3f",115:"#3f7f5f",116:"#004c26",117:"#264c39",118:"#002613",119:"#13261c",120:"#00ffbf",121:"#7fffdf",122:"#00a57c",123:"#52a591",124:"#007f5f",125:"#3f7f6f",126:"#004c39",127:"#264c42",128:"#00261c",129:"#132621",130:"#00ffff",131:"#7fffff",132:"#00a5a5",133:"#52a5a5",134:"#007f7f",135:"#3f7f7f",136:"#004c4c",137:"#264c4c",138:"#002626",139:"#132626",140:"#00bfff",141:"#7fdfff",142:"#007ca5",143:"#5291a5",144:"#005f7f",145:"#3f6f7f",146:"#00394c",147:"#26424c",148:"#001c26",149:"#132126",150:"#007fff",151:"#7fbfff",152:"#0052a5",153:"#527ca5",154:"#003f7f",155:"#3f5f7f",156:"#00264c",157:"#26394c",158:"#001326",159:"#131c26",160:"#003fff",161:"#7f9fff",162:"#0029a5",163:"#5267a5",164:"#001f7f",165:"#3f4f7f",166:"#00134c",167:"#262f4c",168:"#000926",169:"#131726",170:"#0000ff",171:"#7f7fff",172:"#0000a5",173:"#5252a5",174:"#00007f",175:"#3f3f7f",176:"#00004c",177:"#26264c",178:"#000026",179:"#131326",180:"#3f00ff",181:"#9f7fff",182:"#2900a5",183:"#6752a5",184:"#1f007f",185:"#4f3f7f",186:"#13004c",187:"#2f264c",188:"#090026",189:"#171326",190:"#7f00ff",191:"#bf7fff",192:"#5200a5",193:"#7c52a5",194:"#3f007f",195:"#5f3f7f",196:"#26004c",197:"#39264c",198:"#130026",199:"#1c1326",200:"#bf00ff",201:"#df7fff",202:"#7c00a5",203:"#9152a5",204:"#5f007f",205:"#6f3f7f",206:"#39004c",207:"#42264c",208:"#1c0026",209:"#211326",210:"#ff00ff",211:"#ff7fff",212:"#a500a5",213:"#a552a5",214:"#7f007f",215:"#7f3f7f",216:"#4c004c",217:"#4c264c",218:"#260026",219:"#261326",220:"#ff00bf",221:"#ff7fdf",222:"#a5007c",223:"#a55291",224:"#7f005f",225:"#7f3f6f",226:"#4c0039",227:"#4c2642",228:"#26001c",229:"#261321",230:"#ff007f",231:"#ff7fbf",232:"#a50052",233:"#a5527c",234:"#7f003f",235:"#7f3f5f",236:"#4c0026",237:"#4c2639",238:"#260013",239:"#26131c",240:"#ff003f",241:"#ff7f9f",242:"#a50029",243:"#a55267",244:"#7f001f",245:"#7f3f4f",246:"#4c0013",247:"#4c262f",248:"#260009",249:"#261317",250:"#333333",251:"#505050",252:"#696969",253:"#828282",254:"#bebebe",255:"#ffffff"};function _(n,e="#ffffff",t=e){if(typeof n!="number"||Number.isNaN(n))return e;const i=Math.abs(Math.trunc(n));return i===0||i===256||i===257?e:i===7?t:_i[i]??e}function ie(n,e="rgb"){const t=Math.max(0,Math.trunc(n))&16777215,i=t>>16&255,s=t>>8&255,r=t&255;return`rgb(${e==="rgb"?i:r}, ${s}, ${e==="rgb"?r:i})`}function se(n){if(typeof n=="string"){const e=n.trim();return e?/^(#|rgb\(|rgba\(|hsl\(|hsla\()/i.test(e)?Hi(e)??e:{red:"#ff0000",yellow:"#ffff00",green:"#00ff00",cyan:"#00ffff",blue:"#0000ff",magenta:"#ff00ff",white:"#ffffff",black:"#000000",grey:"#808080",gray:"#808080"}[e.toLowerCase()]:void 0}if(n&&typeof n=="object"){const e=n,t=Number(e.r??e.red),i=Number(e.g??e.green),s=Number(e.b??e.blue),r=Number(e.a??e.alpha??1);if([t,i,s].every(Number.isFinite))return Number.isFinite(r)&&r>=0&&r<1?`rgba(${t}, ${i}, ${s}, ${r})`:`rgb(${t}, ${i}, ${s})`}}function Hi(n){if(!n)return;const e=n.trim();if(/^#[0-9a-f]{8}$/i.test(e)){const t=parseInt(e.slice(1,3),16)/255,i=parseInt(e.slice(3,5),16),s=parseInt(e.slice(5,7),16),r=parseInt(e.slice(7,9),16);return t>=.999?`rgb(${i}, ${s}, ${r})`:`rgba(${i}, ${s}, ${r}, ${je(t)})`}if(/^#[0-9a-f]{6}$/i.test(e)||/^#[0-9a-f]{3}$/i.test(e))return e;if(/^sc#/i.test(e)){const t=e.slice(3).split(",").map(a=>Number(a.trim())),[i,s,r,o]=t.length===4?t:[1,...t];if([i,s,r,o].every(Number.isFinite))return`rgba(${Math.round(s*255)}, ${Math.round(r*255)}, ${Math.round(o*255)}, ${je(i)})`}}function j(n,e,t={}){const i=t.foreground??"#ffffff",s=i;let r;const o=se(n.trueColor)??se(n.color)??se(n.colorName);if(o&&(r=o),!r){const a=Zi(n,["trueColor","true_color","truecolor","colorRGB","colorRgb","rgbColor","rgb"]);typeof a=="number"&&a>=0&&a<=16777215&&(r=ie(a,t.trueColorByteOrder??"rgb"))}if(!r){const a=tn(n.colorIndex,n.colorNumber,n.aci);typeof a=="number"&&Math.abs(a)<=257&&a!==256&&a!==0&&a!==257&&(r=_(a,s,i))}if(!r&&typeof n.color=="number"){const a=Number(n.color);Math.abs(a)<=257?a!==0&&a!==256&&a!==257&&(r=_(a,s,i)):r=ie(a,t.trueColorByteOrder??"rgb")}if(!r){const a=qi(e,n.layer);r=Vi(a,t)}return Jt(r??s,t)}function He(n,e,t={}){let i;const s=se(n.fillColor);if(s&&(i=s),!i&&typeof n.fillColor=="number"){const r=n.fillColor;i=Math.abs(r)<=257?_(r,t.foreground??"#ffffff",t.foreground??"#ffffff"):ie(r,t.trueColorByteOrder??"rgb")}return!i&&typeof n.fillColorIndex=="number"&&(i=_(n.fillColorIndex,t.foreground??"#ffffff",t.foreground??"#ffffff")),i?Jt(i,t):void 0}function Jt(n,e={}){if(e.contrastMode!=="adaptive")return n;const t=e.background??"#0b1020",i=e.foreground??"#ffffff";return $i(n,t,i,e.minColorContrast??2.4)}function $i(n,e,t,i=2.4){const s=$e(t)??{r:255,g:255,b:255,a:1},r=$e(e)??{r:11,g:16,b:32,a:1},o=$e(n);if(!o)return n;const a=nn(o,r);if(Ge(a,r)>=i)return n;const c=Ve(r),h=c<.5?{r:255,g:255,b:255,a:o.a}:{r:0,g:0,b:0,a:o.a};for(const l of[.25,.4,.55,.7,.85,1]){const d=Ki(o,h,l);if(Ge(nn(d,r),r)>=i)return sn(d)}return Ge(s,r)>=i?sn(s):c<.5?"#ffffff":"#000000"}function Qt(n){return n?n.isVisible!==!1&&n.isFrozen!==!0:!0}function Vi(n,e){if(!n)return;const t=e.foreground??"#ffffff",i=se(n.trueColor);if(i)return i;if(typeof n.trueColor=="number"&&n.trueColor>=0&&n.trueColor<=16777215)return ie(n.trueColor,e.trueColorByteOrder??"rgb");const s=se(n.color);if(s)return s;if(ji(n.colorIndex))return _(n.colorIndex,t,t);if(typeof n.color=="number"){const r=Number(n.color);return Math.abs(r)<=257?_(r,t,t):ie(r,e.trueColorByteOrder??"rgb")}if(typeof n.colorIndex=="number")return _(n.colorIndex,t,t)}function Gi(n){return tn(n.colorIndex,n.colorNumber,n.aci)===0?!0:n.trueColor===void 0&&n.color===0}function en(n,e,t,i={}){if(!Gi(n))return n;const s=j(e,t,i);return{...n,color:s,trueColor:void 0,colorIndex:void 0,colorNumber:void 0}}function ji(n){return typeof n=="number"&&Number.isFinite(n)&&Math.abs(Math.trunc(n))>=1&&Math.abs(Math.trunc(n))<=255}function qi(n,e){if(!(!n||!e))return n.layers[e]??n.layers[e.toLowerCase()]??Object.values(n.layers).find(t=>t.name.toLowerCase()===e.toLowerCase())}function tn(...n){for(const e of n)if(typeof e=="number"&&Number.isFinite(e))return e}function Zi(n,e){const t=n;for(const i of e){const s=t[i];if(typeof s=="number"&&Number.isFinite(s))return s}}function $e(n){const e=n.trim().toLowerCase();if(/^#[0-9a-f]{3}$/i.test(e))return{r:parseInt(e[1]+e[1],16),g:parseInt(e[2]+e[2],16),b:parseInt(e[3]+e[3],16),a:1};if(/^#[0-9a-f]{6}$/i.test(e))return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16),a:1};const t=e.match(/^rgba?\(([^)]+)\)$/i);if(t){const i=t[1].split(/[,\s/]+/).filter(Boolean).map(s=>Number(s.replace("%","")));if(i.length>=3&&i.slice(0,3).every(Number.isFinite)){const s=/%/.test(t[1]);return{r:re(s?i[0]*2.55:i[0]),g:re(s?i[1]*2.55:i[1]),b:re(s?i[2]*2.55:i[2]),a:Number.isFinite(i[3])?Math.max(0,Math.min(1,i[3])):1}}}}function nn(n,e){const t=n.a+e.a*(1-n.a);return t<=0?{r:0,g:0,b:0,a:0}:{r:(n.r*n.a+e.r*e.a*(1-n.a))/t,g:(n.g*n.a+e.g*e.a*(1-n.a))/t,b:(n.b*n.a+e.b*e.a*(1-n.a))/t,a:t}}function Ki(n,e,t){const i=Math.max(0,Math.min(1,t));return{r:n.r+(e.r-n.r)*i,g:n.g+(e.g-n.g)*i,b:n.b+(e.b-n.b)*i,a:n.a}}function Ve(n){const e=[n.r,n.g,n.b].map(t=>{const i=t/255;return i<=.03928?i/12.92:((i+.055)/1.055)**2.4});return .2126*e[0]+.7152*e[1]+.0722*e[2]}function Ge(n,e){const t=Ve(n),i=Ve(e),s=Math.max(t,i),r=Math.min(t,i);return(s+.05)/(r+.05)}function sn(n){const e=re(n.r),t=re(n.g),i=re(n.b);return n.a<.999?`rgba(${e}, ${t}, ${i}, ${je(n.a)})`:`rgb(${e}, ${t}, ${i})`}function re(n){return Math.max(0,Math.min(255,Math.round(n)))}function je(n){return Math.round(n*1e3)/1e3}const Ji={a:1,b:0,c:0,d:1,e:0,f:0};function Ne(n,e){return{a:n.a*e.a+n.c*e.b,b:n.b*e.a+n.d*e.b,c:n.a*e.c+n.c*e.d,d:n.b*e.c+n.d*e.d,e:n.a*e.e+n.c*e.f+n.e,f:n.b*e.e+n.d*e.f+n.f}}function rn(n,e){return{a:1,b:0,c:0,d:1,e:n,f:e}}function on(n){const e=Math.cos(n),t=Math.sin(n);return{a:e,b:t,c:-t,d:e,e:0,f:0}}function Qi(n,e=n){return{a:n,b:0,c:0,d:e,e:0,f:0}}function O(n,e){return{x:n.x*e.a+n.y*e.c+e.e,y:n.x*e.b+n.y*e.d+e.f,z:"z"in n?n.z:void 0}}function an(n,e){if(n)return n.map(t=>({cmd:t.cmd,points:t.points.map(i=>O(i,e))}))}function qe(n,e={x:0,y:0}){const t=n.insertionPoint??{x:0,y:0},i=n.scale,s=Number(typeof i=="object"&&i?i.x??1:n.scaleX??1),r=Number(typeof i=="object"&&i?i.y??s:n.scaleY??s),o=Number(n.rotation??0);let a=rn(t.x,t.y);return a=Ne(a,on(Number.isFinite(o)?o:0)),a=Ne(a,Qi(Number.isFinite(s)?s:1,Number.isFinite(r)?r:1)),a=Ne(a,rn(-e.x,-e.y)),a}function oe(n,e){const t={...n},i=e.a*e.d-e.b*e.c,s=Math.sqrt(Math.abs(i)),r=Math.hypot(e.a,e.b),o=Math.hypot(e.c,e.d);if(n.startPoint&&(t.startPoint=O(n.startPoint,e)),n.endPoint&&(t.endPoint=O(n.endPoint,e)),n.center&&(t.center=O(n.center,e)),n.insertionPoint&&(t.insertionPoint=O(n.insertionPoint,e)),n.majorAxisEndPoint){const h=O({x:0,y:0},e),l=O(n.majorAxisEndPoint,e);t.majorAxisEndPoint={x:l.x-h.x,y:l.y-h.y,z:l.z}}n.vertices&&(t.vertices=n.vertices.map(h=>({...O(h,e),bulge:h.bulge,startWidth:cn(h.startWidth,s),endWidth:cn(h.endWidth,s)}))),n.points&&(t.points=n.points.map(h=>O(h,e))),n.controlPoints&&(t.controlPoints=n.controlPoints.map(h=>O(h,e))),n.fitPoints&&(t.fitPoints=n.fitPoints.map(h=>O(h,e))),n.attribs&&(t.attribs=n.attribs.map(h=>oe(h,e))),n.commands&&(t.commands=an(n.commands,e)),n.loops&&(t.loops=n.loops.map(h=>{var l;return{...h,vertices:(l=h.vertices)==null?void 0:l.map(d=>O(d,e)),commands:an(h.commands,e)}})),typeof n.radius=="number"&&Number.isFinite(s)&&(t.radius=n.radius*s),typeof n.constantWidth=="number"&&Number.isFinite(s)&&(t.constantWidth=n.constantWidth*s),typeof n.thickness=="number"&&Number.isFinite(s)&&(t.thickness=n.thickness*s),typeof n.lineTypeScale=="number"&&Number.isFinite(s)&&(t.lineTypeScale=n.lineTypeScale*s),(n.kind==="text"||/^(TEXT|MTEXT|ATTRIB|ATTDEF|DIMENSION)$/i.test(String(n.type??"")))&&(typeof n.textHeight=="number"&&Number.isFinite(o)&&(t.textHeight=n.textHeight*o),typeof n.height=="number"&&Number.isFinite(o)&&(t.height=n.height*o),typeof n.xScale=="number"&&o>1e-14&&Number.isFinite(r)&&(t.xScale=n.xScale*r/o));const a=Math.atan2(e.b,e.a),c=n.kind==="ellipse"||String(n.type??"").toUpperCase()==="ELLIPSE";return(typeof n.rotation=="number"||n.kind==="text"||n.kind==="insert")&&(t.rotation=es(Number(n.rotation??0)+(Number.isFinite(a)?a:0))),Number.isFinite(a)&&Math.abs(a)>1e-14&&(!c&&typeof n.startAngle=="number"&&(t.startAngle=n.startAngle+a),!c&&typeof n.endAngle=="number"&&(t.endAngle=n.endAngle+a)),i<0&&t.vertices&&(t.vertices=t.vertices.map(h=>({...h,bulge:typeof h.bulge=="number"?-h.bulge:void 0}))),t}function cn(n,e){return typeof n=="number"&&Number.isFinite(e)?n*e:n}function es(n){if(!Number.isFinite(n))return n;const e=Math.PI*2,t=((n+Math.PI)%e+e)%e-Math.PI;return Math.abs(t)<=1e-12?0:t}const ts=16,ns=96,is=.01;function Ze(n,e={}){const t=z();for(const s of n.pages??[])L(t,{x:0,y:0}),L(t,{x:s.width,y:s.height});const i=ln(n,e);for(const s of n.entities)xt(t,dn(s,i));return vt(t)}function Ke(n,e,t="auto",i={}){if(t==="extents")return e;const s=hn(n);if(!s)return e;if(t==="saved-view")return s;const r=z(),o=ln(n,i);let a=0;for(const c of n.entities){const h=os(dn(c,o),s);h&&(a++,xt(r,h))}return a===0||!as(r,s)?s:vt(r)}function hn(n){const e=n.savedView;if(!e||e.source!=="vport"||e.sceneTransformApplied!==!0||!b(e.center))return;const t=Number(e.viewHeight),i=Number(e.aspectRatio);if(!Number.isFinite(t)||t<=1e-9||!Number.isFinite(i)||i<=1e-9)return;const s=t*i;return{minX:e.center.x-s/2,minY:e.center.y-t/2,maxX:e.center.x+s/2,maxY:e.center.y+t/2}}function ln(n,e){return{document:n,maxInsertDepth:Math.max(0,Math.floor(e.maxInsertDepth??ts)),maxCurveSegments:Math.max(12,Math.floor(e.maxCurveSegments??ns))}}function dn(n,e,t=0){const i=z();return fn(i,n,e,t),i}function fn(n,e,t,i){const s=String(e.type??"").toUpperCase(),r=e.kind??J(s);if(r==="insert"){const o=rs(t.document,e.blockName??e.name);if(o&&i<t.maxInsertDepth){const a=qe(e,o.basePoint??{x:0,y:0});for(const c of o.entities)fn(n,oe(c,a),t,i+1);return}}if(r==="line")b(e.startPoint)&&L(n,e.startPoint),b(e.endPoint)&&L(n,e.endPoint);else if(r==="circle"||r==="arc")b(e.center)&&Number.isFinite(e.radius)&&Yn(n,e.center,Number(e.radius));else if(r==="polyline"||r==="solid"||r==="spline")for(const o of[...e.vertices??[],...e.points??[],...e.controlPoints??[],...e.fitPoints??[]])b(o)&&L(n,o);else if(r==="ellipse"){if(b(e.center)&&b(e.majorAxisEndPoint))for(const o of We(e.center,e.majorAxisEndPoint,Number(e.axisRatio??1),Number(e.startAngle??0),Number(e.endAngle??Math.PI*2),t.maxCurveSegments))L(n,o)}else if(r==="path")for(const o of e.commands??[])for(const a of o.points)L(n,a);else if(r==="hatch")for(const o of e.loops??[]){for(const a of o.vertices??[])L(n,a);for(const a of o.commands??[])for(const c of a.points)L(n,c)}else{const o=ss(e);o&&L(n,o)}}function ss(n){for(const e of["startPoint","insertionPoint","center","point","location"]){const t=n[e];if(b(t))return t}if(Array.isArray(n.vertices)&&b(n.vertices[0]))return n.vertices[0];if(Array.isArray(n.commands)){const e=n.commands.find(t=>t.points.length>0);if(e)return e.points[0]}}function rs(n,e){if(e)return n.blocks[e]??n.blocks[e.toLowerCase()]??Object.values(n.blocks).find(t=>t.name.toLowerCase()===e.toLowerCase())}function os(n,e){if(!R(n)||!R(e))return;const t={minX:Math.max(n.minX,e.minX),minY:Math.max(n.minY,e.minY),maxX:Math.min(n.maxX,e.maxX),maxY:Math.min(n.maxY,e.maxY)};return R(t)?t:void 0}function as(n,e){if(!R(n)||!R(e))return!1;const t=Math.hypot(n.maxX-n.minX,n.maxY-n.minY),i=Math.hypot(e.maxX-e.minX,e.maxY-e.minY);return i>1e-9&&t/i>=is}const un=1e5,mn=new Set(["","bylayer","15"]),Je=new Set(["byblock","14"]),cs=new Set(["continuous","16"]),ae=n=>String(n??"").trim().toLowerCase();function hs(n){return Je.has(ae(n))}function Qe(n,e,t){if(!hs(n.lineType))return n;const i=et(e,t);return{...n,lineType:i||"Continuous",lineTypeScale:ue(n.lineTypeScale,1)*ue(e.lineTypeScale,1)}}function et(n,e){var s;let t=String(n.lineType??"").trim();const i=ae(t);return mn.has(i)?t=((s=ps(e,n.layer))==null?void 0:s.lineType)??"Continuous":Je.has(i)&&(t="Continuous"),t||"Continuous"}function Me(n,e){var d,f;if(!e)return;const t=et(n,e),i=ae(t);if(cs.has(i)||mn.has(i)||Je.has(i))return;const s=ms(e,t);if(!(s!=null&&s.pattern.length))return;const r=ue(n.lineTypeScale,ue((d=e.header)==null?void 0:d.CELTSCALE,1)),o=ue((f=e.header)==null?void 0:f.LTSCALE,1)*r,a=ds(s,o),c=a.reduce((u,p)=>u+p.length,0);if(!Number.isFinite(c)||c<=1e-9)return;const h=a.some(u=>!u.draw&&u.length>1e-12),l=a.some(u=>u.marker);if(!(!h&&!l))return{name:s.name,segments:us(a,h),runs:a,period:c}}function ls(n,e,t){return Te(n,e,t).segments}function Te(n,e,t,i=un){const s=n.filter(g=>Number.isFinite(g.x)&&Number.isFinite(g.y));if(s.length<2||t.runs.length===0)return{segments:[],dots:[]};const r=[];for(let g=0;g<s.length-1;g++)r.push([s[g],s[g+1]]);e&&r.push([s[s.length-1],s[0]]);const o=Number.isFinite(i)?Math.max(1,Math.floor(i)):un,a=r.reduce((g,[v,C])=>g+Math.hypot(C.x-v.x,C.y-v.y),0),h=(t.period>1e-12?a/t.period:Number.POSITIVE_INFINITY)*Math.max(1,t.runs.length);if(!Number.isFinite(h)||h>o)return{segments:r,dots:[]};const l={segments:[],dots:[]};let d=0,f=t.runs[0].length,u=!0;const p=g=>{const v=l.dots[l.dots.length-1];v&&Math.hypot(v.x-g.x,v.y-g.y)<=1e-10||l.dots.push(g)},w=()=>{d=(d+1)%t.runs.length,f=t.runs[d].length,u=!0},P=(g,v,C,S,I)=>{const W=fs(g,v,C/I,S/I);p(v),W&&(l.markers??(l.markers=[])).push(W)};for(const[g,v]of r){const C=v.x-g.x,S=v.y-g.y,I=Math.hypot(C,S);if(I<=1e-14)continue;let W=0;for(;W<I-1e-12;){let Ie=0;for(;f<=1e-12&&Ie<t.runs.length;){const Y=t.runs[d];if(u&&Y.marker){const H=W/I,Tn={x:g.x+C*H,y:g.y+S*H};pn(Y)?P(Y,Tn,C,S,I):p(Tn)}w(),Ie++}if(f<=1e-12)break;const Z=t.runs[d];if(u){if(Z.marker){const Y=W/I,H={x:g.x+C*Y,y:g.y+S*Y};pn(Z)?P(Z,H,C,S,I):p(H)}u=!1}const ce=Math.min(f,I-W);if(Z.draw&&ce>1e-12){const Y=W/I,H=(W+ce)/I;l.segments.push([{x:g.x+C*Y,y:g.y+S*Y},{x:g.x+C*H,y:g.y+S*H}])}W+=ce,f-=ce,f<=1e-12&&w()}}return l}function ds(n,e){const t=[];for(const i of n.pattern){const s=Number(i.length),r=Number(i.elementTypeFlag??0)!==0;Number.isFinite(s)&&t.push({draw:s>=0,length:Math.abs(s)*e,marker:s>=0&&(s===0||r),element:i,globalScale:e})}return t}function tt(n,e){const t=Math.cos(n.angle),i=Math.sin(n.angle);return e.polylines.map(s=>s.map(r=>{const o=r.x*n.scale,a=r.y*n.scale;return{x:n.point.x+o*t-a*i,y:n.point.y+o*i+a*t}}))}function pn(n){var e;return Number(((e=n.element)==null?void 0:e.elementTypeFlag)??0)!==0}function fs(n,e,t,i){const s=n.element,r=Number((s==null?void 0:s.elementTypeFlag)??0);if(!s||r===0)return;const o=Ee(s.offsetX,0)*n.globalScale,a=Ee(s.offsetY,0)*n.globalScale,c=Ee(s.rotation,0),h=Math.atan2(i,t),l={x:e.x+t*o-i*a,y:e.y+i*o+t*a},d={fallbackPoint:e,point:l,angle:(r&1)===1?c:h+c,scale:Math.abs(Ee(s.scale,1)*n.globalScale),fontName:s.fontName},f=Number(s.shapeNumber);if((r&4)===4&&Number.isFinite(f))return{...d,kind:"shape",shapeNumber:Math.trunc(f)};if((r&2)===2&&s.text)return{...d,kind:"text",text:s.text}}function us(n,e){if(!e)return[];const t=[];for(const s of n){if(s.length<=1e-12)continue;const r=t[t.length-1];(r==null?void 0:r.draw)===s.draw?r.length+=s.length:t.push({draw:s.draw,length:s.length})}const i=[];for(const s of t){const r=i.length%2===0;s.draw!==r&&i.push(1e-9),i.push(s.length)}return i.length%2===1&&i.push(1e-9),i}function ms(n,e){const t=ae(e),i=n.lineTypes??{};return i[e]??i[t]??Object.values(i).find(s=>ae(s.name)===t||ae(s.handle)===t)}function ps(n,e){if(!(!n||!e))return n.layers[e]??n.layers[e.toLowerCase()]??Object.values(n.layers).find(t=>t.name.toLowerCase()===e.toLowerCase())}function ue(n,e){const t=Number(n);return Number.isFinite(t)&&t>0?t:e}function Ee(n,e){const t=Number(n);return Number.isFinite(t)?t:e}const gs=n=>Math.abs(n.a-1)<1e-12&&Math.abs(n.b)<1e-12&&Math.abs(n.c)<1e-12&&Math.abs(n.d-1)<1e-12&&Math.abs(n.e)<1e-9&&Math.abs(n.f)<1e-9;function nt(n){var t,i,s;if(n.metadata.sceneTransformApplied===!0||((t=n.savedView)==null?void 0:t.sceneTransformApplied)===!1)return n;const e=((i=n.savedView)==null?void 0:i.sceneTransform)??Ji;return gs(e)?n:{...n,entities:n.entities.map(r=>oe(r,e)),pages:(s=n.pages)==null?void 0:s.map(r=>({...r,entities:r.entities.map(o=>oe(o,e))})),metadata:{...n.metadata,sceneTransformApplied:!0}}}const ys={background:"#0b1020",foreground:"#ffffff",showUnsupportedMarkers:!1,showImagePlaceholders:!0,showPageBounds:!0,minScale:1e-9,maxScale:1e9,wheelZoomFactor:1.14,trueColorByteOrder:"rgb",maxInsertDepth:16,fitMode:"auto",contrastMode:"adaptive",minColorContrast:2.4,maxCurveSegments:96,spatialIndexCellCount:72,maxVerticesPerBatch:65536,textMinPixelHeight:4,maxVisibleTextLabels:2500,powerPreference:"high-performance",antialias:!0,preserveDrawingBuffer:!1,enableSpatialIndex:!0,shxGlyphResolver:$t};class it{constructor(e,t={}){m(this,"canvas");m(this,"ctx");m(this,"opts");m(this,"sourceDocument");m(this,"document");m(this,"bounds",z());m(this,"view",{centerX:0,centerY:0,scale:1});m(this,"fitScale",1);m(this,"dpr",1);m(this,"isDragging",!1);m(this,"lastPointer");m(this,"resizeObserver");m(this,"imageCache",new Map);m(this,"stats",{total:0,drawn:0,skipped:0,byType:{},unsupported:{},renderElapsedMs:0,backend:"canvas2d"});m(this,"onStats");m(this,"onViewChange");const i=e.getContext("2d");if(!i)throw new Error("Canvas 2D context is not available.");this.canvas=e,this.ctx=i,this.opts={...ys,...t},this.canvas.classList.add("cad-viewer-canvas"),this.bindEvents(),typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(()=>this.resize()),this.resizeObserver.observe(e)),this.resize()}destroy(){var e;(e=this.resizeObserver)==null||e.disconnect()}clear(){this.sourceDocument=void 0,this.document=void 0,this.bounds=z(),this.view={centerX:0,centerY:0,scale:1},this.fitScale=1,this.render(),this.emitViewChange()}setDocument(e){this.sourceDocument=e,this.document=nt(e),this.bounds=Ze(this.document,this.boundsOptions()),this.fitToView()}refreshReferences(){this.render(),this.emitViewChange()}getDocument(){return this.document}getSourceDocument(){return this.sourceDocument}setOptions(e){const t=e.fitMode!==void 0&&e.fitMode!==this.opts.fitMode;if(Object.assign(this.opts,e),t&&this.document){this.fitToView();return}this.render(),this.emitViewChange()}getOptions(){return{...this.opts}}fitToView(e=.92,t=this.opts.fitMode){const i=this.document?Ke(this.document,this.bounds,t,this.boundsOptions()):this.bounds;if(!R(i)){this.view={centerX:0,centerY:0,scale:1},this.fitScale=1,this.render(),this.emitViewChange();return}const s=Math.max(1,this.cssWidth),r=Math.max(1,this.cssHeight),o=Math.max(i.maxX-i.minX,1e-9),a=Math.max(i.maxY-i.minY,1e-9),c=this.clampScale(Math.min(s/o,r/a)*e);this.fitScale=c,this.view={centerX:(i.minX+i.maxX)/2,centerY:(i.minY+i.maxY)/2,scale:c},this.render(),this.emitViewChange()}resize(){this.dpr=Math.max(1,window.devicePixelRatio||1);const e=Math.max(1,Math.floor(this.cssWidth*this.dpr)),t=Math.max(1,Math.floor(this.cssHeight*this.dpr));(this.canvas.width!==e||this.canvas.height!==t)&&(this.canvas.width=e,this.canvas.height=t),this.render(),this.emitViewChange()}zoom(e,t){if(!Number.isFinite(e)||e<=0)return;const i=t??{x:this.cssWidth/2,y:this.cssHeight/2},s=this.screenToWorld(i);this.view.scale=this.clampScale(this.view.scale*e);const r=this.screenToWorld(i);this.view.centerX+=s.x-r.x,this.view.centerY+=s.y-r.y,this.render(),this.emitViewChange()}zoomIn(){this.zoom(this.opts.wheelZoomFactor)}zoomOut(){this.zoom(1/this.opts.wheelZoomFactor)}panByScreenDelta(e,t){!Number.isFinite(e)||!Number.isFinite(t)||(this.view.centerX-=e/this.view.scale,this.view.centerY+=t/this.view.scale,this.render(),this.emitViewChange())}setViewState(e){if(![e.centerX,e.centerY,e.scale].every(Number.isFinite))throw new Error("Invalid view state.");this.view={...e,scale:this.clampScale(e.scale)},this.render(),this.emitViewChange()}getViewState(){return{...this.view}}getBounds(){return{...this.bounds}}getStats(){return bs(this.stats)}getZoomRatio(){return Math.abs(this.fitScale)<1e-12?1:this.view.scale/this.fitScale}getZoomPercent(){return this.getZoomRatio()*100}worldToScreen(e){return{x:this.cssWidth/2+(e.x-this.view.centerX)*this.view.scale,y:this.cssHeight/2-(e.y-this.view.centerY)*this.view.scale}}screenToWorld(e){return{x:this.view.centerX+(e.x-this.cssWidth/2)/this.view.scale,y:this.view.centerY-(e.y-this.cssHeight/2)/this.view.scale}}render(){var t,i;const e=performance.now();if(this.stats={total:0,drawn:0,skipped:0,byType:{},unsupported:{},renderElapsedMs:0,backend:"canvas2d"},this.clearCanvas(),this.document){this.opts.showPageBounds&&((t=this.document.pages)!=null&&t.length)&&this.drawPageBounds(this.document);for(const s of this.document.entities)this.drawEntityTracked(s,0)}return this.stats.renderElapsedMs=performance.now()-e,(i=this.onStats)==null||i.call(this,this.getStats()),this.getStats()}get cssWidth(){return this.canvas.clientWidth||1}get cssHeight(){return this.canvas.clientHeight||1}bindEvents(){this.canvas.addEventListener("wheel",t=>{t.preventDefault();const i=t.deltaY<0?this.opts.wheelZoomFactor:1/this.opts.wheelZoomFactor;this.zoom(i,{x:t.offsetX,y:t.offsetY})},{passive:!1}),this.canvas.addEventListener("pointerdown",t=>{this.canvas.setPointerCapture(t.pointerId),this.isDragging=!0,this.lastPointer={x:t.clientX,y:t.clientY},this.canvas.classList.add("is-dragging")}),this.canvas.addEventListener("pointermove",t=>{!this.isDragging||!this.lastPointer||(this.panByScreenDelta(t.clientX-this.lastPointer.x,t.clientY-this.lastPointer.y),this.lastPointer={x:t.clientX,y:t.clientY})});const e=t=>{t&&this.canvas.hasPointerCapture(t.pointerId)&&this.canvas.releasePointerCapture(t.pointerId),this.isDragging=!1,this.lastPointer=void 0,this.canvas.classList.remove("is-dragging")};this.canvas.addEventListener("pointerup",e),this.canvas.addEventListener("pointercancel",()=>e())}clearCanvas(){const e=this.ctx;e.save(),e.setTransform(this.dpr,0,0,this.dpr,0,0),e.clearRect(0,0,this.cssWidth,this.cssHeight),e.fillStyle=this.opts.background,e.fillRect(0,0,this.cssWidth,this.cssHeight),e.restore()}drawPageBounds(e){const t=this.ctx;t.save(),t.setTransform(this.dpr,0,0,this.dpr,0,0),t.strokeStyle="rgba(148, 163, 184, 0.35)",t.lineWidth=1,t.setLineDash([8,6]);for(const i of e.pages??[]){const s=this.worldToScreen({x:0,y:0}),r=this.worldToScreen({x:i.width,y:i.height});t.strokeRect(Math.min(s.x,r.x),Math.min(s.y,r.y),Math.abs(r.x-s.x),Math.abs(r.y-s.y))}t.restore()}drawEntityTracked(e,t){this.stats.total++;const i=String(e.type??"UNKNOWN").toUpperCase();this.stats.byType[i]=(this.stats.byType[i]??0)+1;const s=this.lookupLayer(e.layer);if(e.isVisible===!1||!Qt(s)){this.stats.skipped++;return}this.drawEntity(e,i,t)}drawEntity(e,t,i){switch(e.kind??J(t)){case"line":return this.drawLine(e);case"circle":return this.drawCircle(e);case"arc":return this.drawArc(e);case"polyline":return this.drawPolyline(e);case"ellipse":return this.drawEllipse(e);case"text":return this.drawText(e);case"point":return this.drawPoint(e);case"insert":return this.drawInsert(e,i);case"solid":return this.drawSolid(e);case"hatch":return this.drawHatch(e);case"spline":return this.drawSpline(e);case"path":return this.drawPath(e);case"image":return this.drawImage(e);case"viewport":return this.markSkipped(t);default:this.stats.unsupported[t]=(this.stats.unsupported[t]??0)+1,this.stats.skipped++,this.opts.showUnsupportedMarkers&&this.drawUnsupportedMarker(e)}}beginStyledPath(e,t=!1,i=!0){const s=this.ctx;s.save(),s.setTransform(this.dpr,0,0,this.dpr,0,0);const r=j(e,this.document,{foreground:this.opts.foreground,background:this.opts.background,trueColorByteOrder:this.opts.trueColorByteOrder,contrastMode:this.opts.contrastMode,minColorContrast:this.opts.minColorContrast}),o=He(e,this.document,{foreground:this.opts.foreground,background:this.opts.background,trueColorByteOrder:this.opts.trueColorByteOrder,contrastMode:this.opts.contrastMode,minColorContrast:this.opts.minColorContrast})??r;s.strokeStyle=r,s.fillStyle=t?o:r,s.globalAlpha=ee(Number(e.opacity??1),0,1),s.lineCap="round",s.lineJoin="round";const a=typeof e.lineweight=="number"&&e.lineweight>0?e.lineweight/30:1,c=Be(e)*Math.abs(this.view.scale);s.lineWidth=Math.max(1,Math.min(256,Math.max(a,Number.isFinite(c)?c:0)));const h=i?Me(e,this.document):void 0;s.setLineDash(h?h.segments.map(l=>Math.max(.05,l*this.view.scale)):[]),s.beginPath()}finishStroke(){this.ctx.stroke(),this.ctx.restore(),this.stats.drawn++}finishFillStroke(e=!1){e&&this.ctx.fill(),this.ctx.stroke(),this.ctx.restore(),this.stats.drawn++}drawLine(e){const t=e.startPoint,i=e.endPoint;if(!b(t)||!b(i))return this.markSkipped("LINE");this.strokeWorldPolyline(e,[t,i],!1)}drawCircle(e){const t=e.center,i=Number(e.radius);if(!b(t)||!Number.isFinite(i))return this.markSkipped("CIRCLE");this.strokeWorldPolyline(e,he(A(t),i,0,Math.PI*2,!0),!0)}drawArc(e){const t=e.center,i=Number(e.radius),s=Number(e.startAngle),r=Number(e.endAngle);if(!b(t)||!Number.isFinite(i)||!Number.isFinite(s)||!Number.isFinite(r))return this.markSkipped("ARC");this.strokeWorldPolyline(e,he(A(t),i,s,r,!0),!1)}drawPolyline(e){const t=e.vertices??e.points;if(!Array.isArray(t)||t.length<2)return this.markSkipped(String(e.type));const i=De(e),s=[],r=i?t.length:t.length-1;for(let o=0;o<r;o++){const a=t[o],c=t[(o+1)%t.length];if(!b(a)||!b(c))continue;const h=wt(a,c,Number(a.bulge??0));s.length>0&&h.shift(),s.push(...h)}this.strokeWorldPolyline(e,s,i)}drawEllipse(e){const t=e.center,i=e.majorAxisEndPoint,s=Number(e.axisRatio??1);if(!b(t)||!b(i))return this.markSkipped("ELLIPSE");const r=We(t,i,s,Number(e.startAngle??0),Number(e.endAngle??Math.PI*2)),o=Math.abs(Number(e.endAngle??Math.PI*2)-Number(e.startAngle??0))>=Math.PI*2-1e-6;this.strokeWorldPolyline(e,r,o)}drawPoint(e){const t=e.point??e.location??e.center??e.insertionPoint;if(!b(t))return this.markSkipped("POINT");const i=this.worldToScreen(t);this.beginStyledPath(e),this.ctx.moveTo(i.x-3,i.y),this.ctx.lineTo(i.x+3,i.y),this.ctx.moveTo(i.x,i.y-3),this.ctx.lineTo(i.x,i.y+3),this.finishStroke()}drawText(e){const i=(Number(e.halign??0)!==0||Number(e.valign??0)!==0)&&b(e.endPoint)?e.endPoint:e.insertionPoint??e.startPoint??e.center,s=Pt(String(e.text??e.value??"")),r=Number(e.textHeight??e.height??1);if(!b(i)||!s)return this.markSkipped(String(e.type));this.drawTextAt(e,i,s,r,Number(e.rotation??0))}drawInsert(e,t){const i=this.lookupBlock(e.blockName??e.name);if(i&&t<this.opts.maxInsertDepth){const a=qe(e,i.basePoint??{x:0,y:0});for(const c of i.entities){const h=en(c,e,this.document,{foreground:this.opts.foreground,background:this.opts.background,trueColorByteOrder:this.opts.trueColorByteOrder,contrastMode:this.opts.contrastMode,minColorContrast:this.opts.minColorContrast}),l=Qe(h,e,this.document);this.drawEntityTracked(oe(l,a),t+1)}return}const s=e.insertionPoint;if(!b(s))return this.markSkipped("INSERT");const r=this.worldToScreen(s);this.beginStyledPath(e);const o=5;if(this.ctx.rect(r.x-o,r.y-o,o*2,o*2),this.finishStroke(),Array.isArray(e.attribs))for(const a of e.attribs)this.drawText(a)}drawSolid(e){const t=e.vertices??e.points;if(!Array.isArray(t)||t.length<3)return this.markSkipped(String(e.type));this.beginStyledPath(e,!0);const i=this.worldToScreen(t[0]);this.ctx.moveTo(i.x,i.y);for(const s of t.slice(1)){if(!b(s))continue;const r=this.worldToScreen(s);this.ctx.lineTo(r.x,r.y)}this.ctx.closePath(),this.finishFillStroke(!0)}drawHatch(e){var i,s;const t=e.loops;if(!Array.isArray(t)||t.length===0)return this.markSkipped("HATCH");this.beginStyledPath(e,!0);for(const r of t)if((i=r.commands)!=null&&i.length)this.addPathCommands(r.commands);else if((s=r.vertices)!=null&&s.length){const o=this.worldToScreen(r.vertices[0]);this.ctx.moveTo(o.x,o.y);for(const a of r.vertices.slice(1)){const c=this.worldToScreen(a);this.ctx.lineTo(c.x,c.y)}this.ctx.closePath()}this.finishFillStroke(!!He(e,this.document,{foreground:this.opts.foreground,background:this.opts.background,trueColorByteOrder:this.opts.trueColorByteOrder,contrastMode:this.opts.contrastMode,minColorContrast:this.opts.minColorContrast}))}drawSpline(e){var i;const t=(i=e.fitPoints)!=null&&i.length?e.fitPoints:e.controlPoints;if(!t||t.length<2)return this.markSkipped("SPLINE");this.strokeWorldPolyline(e,t,!!e.isClosed)}drawPath(e){var t;if(!((t=e.commands)!=null&&t.length))return this.markSkipped(String(e.type));this.beginStyledPath(e,!!e.fillColor),this.addPathCommands(e.commands),this.finishFillStroke(!!e.fillColor)}addPathCommands(e){for(const t of e)if(t.cmd==="M"){const i=this.worldToScreen(t.points[0]);this.ctx.moveTo(i.x,i.y)}else if(t.cmd==="L"){const i=this.worldToScreen(t.points[0]);this.ctx.lineTo(i.x,i.y)}else if(t.cmd==="C"){const[i,s,r]=t.points.map(o=>this.worldToScreen(o));this.ctx.bezierCurveTo(i.x,i.y,s.x,s.y,r.x,r.y)}else if(t.cmd==="Q"){const[i,s]=t.points.map(r=>this.worldToScreen(r));this.ctx.quadraticCurveTo(i.x,i.y,s.x,s.y)}else t.cmd==="Z"&&this.ctx.closePath()}drawImage(e){const t=e.insertionPoint;if(!b(t))return this.markSkipped(String(e.type));const i=Number(e.width??32),s=Number(e.height??32),r=this.worldToScreen(t),o=this.worldToScreen({x:t.x+i,y:t.y-s}),a=Math.min(r.x,o.x),c=Math.min(r.y,o.y),h=Math.abs(o.x-r.x),l=Math.abs(o.y-r.y),d=e.imageDataUrl;if(d){const f=this.getImage(d);if(f.complete&&f.naturalWidth>0){this.ctx.save(),this.ctx.setTransform(this.dpr,0,0,this.dpr,0,0),this.ctx.drawImage(f,a,c,h,l),this.ctx.restore(),this.stats.drawn++;return}f.onload=()=>this.render()}if(!this.opts.showImagePlaceholders)return this.markSkipped(String(e.type));this.beginStyledPath(e),this.ctx.rect(a,c,h,l),this.ctx.moveTo(a,c),this.ctx.lineTo(a+h,c+l),this.ctx.moveTo(a+h,c),this.ctx.lineTo(a,c+l),this.finishStroke()}getImage(e){let t=this.imageCache.get(e);return t||(t=new Image,t.src=e,this.imageCache.set(e,t)),t}drawUnsupportedMarker(e){const t=this.entityAnchor(e);if(!t)return;const i=this.worldToScreen(t);this.beginStyledPath(e),this.ctx.moveTo(i.x-4,i.y-4),this.ctx.lineTo(i.x+4,i.y+4),this.ctx.moveTo(i.x+4,i.y-4),this.ctx.lineTo(i.x-4,i.y+4),this.finishStroke()}drawTextAt(e,t,i,s,r){const o=this.ctx,a=this.worldToScreen(t);o.save(),o.setTransform(this.dpr,0,0,this.dpr,0,0),o.translate(a.x,a.y),o.rotate(-r);const c=Number(e.generationFlag??0),h=Number(e.xScale??1);o.scale((c&2?-1:1)*(Number.isFinite(h)&&Math.abs(h)>1e-9?Math.abs(h):1),c&4?-1:1);const l=Math.max(4,Math.min(256,Math.abs(s)*this.view.scale));o.font=`${l}px ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`,o.fillStyle=j(e,this.document,{foreground:this.opts.foreground,background:this.opts.background,trueColorByteOrder:this.opts.trueColorByteOrder,contrastMode:this.opts.contrastMode,minColorContrast:this.opts.minColorContrast}),o.globalAlpha=ee(Number(e.opacity??1),0,1);const d=Number(e.halign??0),f=Number(e.valign??0);o.textAlign=d===1||d===4?"center":d===2?"right":"left",o.textBaseline=f===1?"bottom":f===2?"middle":f===3?"top":"alphabetic";for(const[u,p]of i.split(/\r?\n/g).entries())o.fillText(p,0,u*l*1.22);o.restore(),this.stats.drawn++}strokeWorldPolyline(e,t,i){const s=t.filter(b);if(s.length<2)return this.markSkipped(String(e.type));const r=Me(e,this.document);if(r){const a=Te(s,i,r),c=[...a.dots];this.beginStyledPath(e,!1,!1);for(const[h,l]of a.segments){const d=this.worldToScreen(h),f=this.worldToScreen(l);this.ctx.moveTo(d.x,d.y),this.ctx.lineTo(f.x,f.y)}for(const h of a.markers??[]){const l=this.resolveLineTypeGlyph(h);if(l){xs(c,h.fallbackPoint);for(const d of tt(h,l)){if(d.length<2)continue;const f=this.worldToScreen(d[0]);this.ctx.moveTo(f.x,f.y);for(const u of d.slice(1)){const p=this.worldToScreen(u);this.ctx.lineTo(p.x,p.y)}}}}if(this.ctx.stroke(),c.length>0){this.ctx.setLineDash([]),this.ctx.beginPath();const h=Math.max(.5,this.ctx.lineWidth/2);for(const l of c){const d=this.worldToScreen(l);this.ctx.moveTo(d.x+h,d.y),this.ctx.arc(d.x,d.y,h,0,Math.PI*2)}this.ctx.fillStyle=this.ctx.strokeStyle,this.ctx.fill()}this.ctx.restore(),this.stats.drawn++;return}this.beginStyledPath(e);const o=this.worldToScreen(s[0]);this.ctx.moveTo(o.x,o.y);for(const a of s.slice(1)){const c=this.worldToScreen(a);this.ctx.lineTo(c.x,c.y)}i&&this.ctx.closePath(),this.finishStroke()}resolveLineTypeGlyph(e){return e.kind==="shape"?this.opts.shxGlyphResolver.resolveShape(Number(e.shapeNumber),e.fontName):this.opts.shxGlyphResolver.resolveText(String(e.text??""),e.fontName)}markSkipped(e){this.stats.skipped++,this.stats.unsupported[e]=this.stats.unsupported[e]??0}entityAnchor(e){for(const t of["startPoint","insertionPoint","center","point","location"]){const i=e[t];if(b(i))return A(i)}if(Array.isArray(e.vertices)&&b(e.vertices[0]))return A(e.vertices[0]);if(Array.isArray(e.commands)&&e.commands.length){const t=e.commands.find(i=>i.points.length>0);if(t)return A(t.points[0])}}lookupLayer(e){if(!(!this.document||!e))return this.document.layers[e]??this.document.layers[e.toLowerCase()]??Object.values(this.document.layers).find(t=>t.name.toLowerCase()===e.toLowerCase())}lookupBlock(e){if(!(!this.document||!e))return this.document.blocks[e]??this.document.blocks[e.toLowerCase()]??Object.values(this.document.blocks).find(t=>t.name.toLowerCase()===e.toLowerCase())}clampScale(e){return Math.min(this.opts.maxScale,Math.max(this.opts.minScale,e))}boundsOptions(){return{maxInsertDepth:this.opts.maxInsertDepth,maxCurveSegments:this.opts.maxCurveSegments}}emitViewChange(){var e;(e=this.onViewChange)==null||e.call(this,{view:this.getViewState(),fitScale:this.fitScale,zoomRatio:this.getZoomRatio(),zoomPercent:this.getZoomPercent(),bounds:this.getBounds()})}}function bs(n){return{total:n.total,drawn:n.drawn,skipped:n.skipped,byType:{...n.byType},unsupported:{...n.unsupported},renderElapsedMs:n.renderElapsedMs,backend:n.backend,primitiveCount:n.primitiveCount,visiblePrimitiveCount:n.visiblePrimitiveCount,culledPrimitiveCount:n.culledPrimitiveCount,gpuMemoryBytes:n.gpuMemoryBytes,buildElapsedMs:n.buildElapsedMs}}function xs(n,e){const t=Math.max(1,Math.abs(e.x),Math.abs(e.y)),i=Math.max(1e-9,t*1e-12),s=n.findIndex(r=>Math.hypot(r.x-e.x,r.y-e.y)<=i);s>=0&&n.splice(s,1)}const vs={background:"#0b1020",foreground:"#ffffff",showUnsupportedMarkers:!1,showImagePlaceholders:!0,showPageBounds:!0,minScale:1e-9,maxScale:1e9,wheelZoomFactor:1.14,trueColorByteOrder:"rgb",maxInsertDepth:16,fitMode:"auto",contrastMode:"adaptive",minColorContrast:2.4,maxCurveSegments:96,spatialIndexCellCount:72,maxVerticesPerBatch:65536,textMinPixelHeight:4,maxVisibleTextLabels:2500,powerPreference:"high-performance",antialias:!0,preserveDrawingBuffer:!1,enableSpatialIndex:!0,shxGlyphResolver:$t};class st{constructor(e,t={}){m(this,"canvas");m(this,"backend","webgl");m(this,"gl");m(this,"program");m(this,"eventController",new AbortController);m(this,"imageCache",new Map);m(this,"opts");m(this,"sourceDocument");m(this,"document");m(this,"bounds",z());m(this,"view",{centerX:0,centerY:0,scale:1});m(this,"fitScale",1);m(this,"dpr",1);m(this,"isDragging",!1);m(this,"lastPointer");m(this,"resizeObserver");m(this,"overlayCanvas");m(this,"overlayCtx");m(this,"scene");m(this,"stats",{total:0,drawn:0,skipped:0,byType:{},unsupported:{},renderElapsedMs:0,backend:"webgl",primitiveCount:0,visiblePrimitiveCount:0,culledPrimitiveCount:0,gpuMemoryBytes:0,buildElapsedMs:0});m(this,"rafHandle",0);m(this,"onStats");m(this,"onViewChange");const i=ws(e,t);if(!i)throw new Error('WebGL is not available. Use renderer: "canvas2d" to force the Canvas2D fallback.');this.canvas=e,this.gl=i,this.program=Ps(i),this.opts={...vs,...t},this.canvas.classList.add("cad-viewer-canvas","cad-viewer-webgl-canvas"),this.createOverlayCanvas(),this.bindEvents(),typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(()=>this.resize()),this.resizeObserver.observe(e)),this.resize()}static isSupported(){return rt()}destroy(){var e,t;this.eventController.abort(),(e=this.resizeObserver)==null||e.disconnect(),this.cancelScheduledRender(),this.disposeScene(),(t=this.overlayCanvas)==null||t.remove()}clear(){this.sourceDocument=void 0,this.document=void 0,this.bounds=z(),this.view={centerX:0,centerY:0,scale:1},this.fitScale=1,this.disposeScene(),this.render(),this.emitViewChange()}setDocument(e){this.sourceDocument=e,this.document=nt(e),this.bounds=Ze(this.document,this.boundsOptions()),this.disposeScene();const t=xn(this.document,this.opts,this.bounds);this.scene=yn(this.gl,t),this.stats=Cn(this.scene,0),this.fitToView()}refreshReferences(){if(!this.document)return;const e={...this.view},t=this.fitScale;this.disposeScene();const i=xn(this.document,this.opts,this.bounds);this.scene=yn(this.gl,i),this.stats=Cn(this.scene,0),this.view=e,this.fitScale=t,this.render(),this.emitViewChange()}getDocument(){return this.document}getSourceDocument(){return this.sourceDocument}setOptions(e){const t=Ts(this.opts,e),i=e.fitMode!==void 0&&e.fitMode!==this.opts.fitMode;if(this.opts={...this.opts,...e},t&&(this.sourceDocument??this.document)){this.setDocument(this.sourceDocument??this.document);return}if(i&&this.document){this.fitToView();return}this.render(),this.emitViewChange()}getOptions(){return{...this.opts}}fitToView(e=.92,t=this.opts.fitMode){const i=this.document?Ke(this.document,this.bounds,t,this.boundsOptions()):this.bounds;if(!R(i)){this.view={centerX:0,centerY:0,scale:1},this.fitScale=1,this.render(),this.emitViewChange();return}const s=Math.max(1,this.cssWidth),r=Math.max(1,this.cssHeight),o=Math.max(i.maxX-i.minX,1e-9),a=Math.max(i.maxY-i.minY,1e-9),c=this.clampScale(Math.min(s/o,r/a)*e);this.fitScale=c,this.view={centerX:(i.minX+i.maxX)/2,centerY:(i.minY+i.maxY)/2,scale:c},this.render(),this.emitViewChange()}resize(){this.dpr=Math.max(1,window.devicePixelRatio||1);const e=Math.max(1,Math.floor(this.cssWidth*this.dpr)),t=Math.max(1,Math.floor(this.cssHeight*this.dpr));(this.canvas.width!==e||this.canvas.height!==t)&&(this.canvas.width=e,this.canvas.height=t),this.resizeOverlay(e,t),this.render(),this.emitViewChange()}zoom(e,t){if(!Number.isFinite(e)||e<=0)return;const i=t??{x:this.cssWidth/2,y:this.cssHeight/2},s=this.screenToWorld(i);this.view.scale=this.clampScale(this.view.scale*e);const r=this.screenToWorld(i);this.view.centerX+=s.x-r.x,this.view.centerY+=s.y-r.y,this.scheduleRender(),this.emitViewChange()}zoomIn(){this.zoom(this.opts.wheelZoomFactor)}zoomOut(){this.zoom(1/this.opts.wheelZoomFactor)}panByScreenDelta(e,t){!Number.isFinite(e)||!Number.isFinite(t)||(this.view.centerX-=e/this.view.scale,this.view.centerY+=t/this.view.scale,this.scheduleRender(),this.emitViewChange())}setViewState(e){if(![e.centerX,e.centerY,e.scale].every(Number.isFinite))throw new Error("Invalid view state.");this.view={...e,scale:this.clampScale(e.scale)},this.render(),this.emitViewChange()}getViewState(){return{...this.view}}getBounds(){return{...this.bounds}}getStats(){return Es(this.stats)}getZoomRatio(){return Math.abs(this.fitScale)<1e-12?1:this.view.scale/this.fitScale}getZoomPercent(){return this.getZoomRatio()*100}worldToScreen(e){return{x:this.cssWidth/2+(e.x-this.view.centerX)*this.view.scale,y:this.cssHeight/2-(e.y-this.view.centerY)*this.view.scale}}screenToWorld(e){return{x:this.view.centerX+(e.x-this.cssWidth/2)/this.view.scale,y:this.view.centerY-(e.y-this.cssHeight/2)/this.view.scale}}render(){return this.cancelScheduledRender(),this.renderNow()}renderNow(){var h;const e=performance.now(),t=this.gl;t.viewport(0,0,this.canvas.width,this.canvas.height);const i=ct(this.opts.background,[11,16,32,255]);t.clearColor(i[0]/255,i[1]/255,i[2]/255,i[3]/255),t.clear(t.COLOR_BUFFER_BIT),t.disable(t.DEPTH_TEST),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA);let s=0,r=0;const o=this.scene,a=this.visibleWorldBounds();if(o){t.useProgram(this.program.program),t.uniform2f(this.program.uViewCenter,this.view.centerX-o.origin.x,this.view.centerY-o.origin.y),t.uniform1f(this.program.uScale,this.view.scale*this.dpr),t.uniform2f(this.program.uViewport,this.canvas.width,this.canvas.height),t.uniform1f(this.program.uPointSize,Math.max(1,this.dpr));const l=this.drawBatches(o.lineBatches,t.LINES,a);s+=l.visible,r+=l.culled;const d=this.drawBatches(o.triangleBatches,t.TRIANGLES,a);s+=d.visible,r+=d.culled;const f=this.drawBatches(o.lineTypePointBatches,t.POINTS,a);s+=f.visible,r+=f.culled,t.uniform1f(this.program.uPointSize,Math.max(2,Math.min(12,4*this.dpr)));const u=this.drawBatches(o.pointBatches,t.POINTS,a);s+=u.visible,r+=u.culled}this.renderOverlay(a);const c=performance.now()-e;return this.stats=o?{...o.stats,renderElapsedMs:c,backend:"webgl",primitiveCount:o.primitiveCount,visiblePrimitiveCount:s,culledPrimitiveCount:r,gpuMemoryBytes:o.gpuMemoryBytes,buildElapsedMs:o.buildElapsedMs}:{total:0,drawn:0,skipped:0,byType:{},unsupported:{},renderElapsedMs:c,backend:"webgl",primitiveCount:0,visiblePrimitiveCount:0,culledPrimitiveCount:0,gpuMemoryBytes:0,buildElapsedMs:0},(h=this.onStats)==null||h.call(this,this.getStats()),this.getStats()}drawBatches(e,t,i){const s=this.gl;let r=0,o=0;for(const a of e){if(!at(a.bounds,i)){o+=a.primitiveCount;continue}s.bindBuffer(s.ARRAY_BUFFER,a.positionBuffer),s.enableVertexAttribArray(this.program.aPosition),s.vertexAttribPointer(this.program.aPosition,2,s.FLOAT,!1,0,0),s.bindBuffer(s.ARRAY_BUFFER,a.colorBuffer),s.enableVertexAttribArray(this.program.aColor),s.vertexAttribPointer(this.program.aColor,4,s.UNSIGNED_BYTE,!0,0,0),s.drawArrays(t,0,a.vertexCount),r+=a.primitiveCount}return{visible:r,culled:o}}scheduleRender(){this.rafHandle||(this.rafHandle=window.requestAnimationFrame(()=>{this.rafHandle=0,this.renderNow()}))}cancelScheduledRender(){this.rafHandle&&(window.cancelAnimationFrame(this.rafHandle),this.rafHandle=0)}renderOverlay(e){var s,r;const t=this.overlayCtx,i=this.overlayCanvas;!t||!i||(t.save(),t.setTransform(this.dpr,0,0,this.dpr,0,0),t.clearRect(0,0,this.cssWidth,this.cssHeight),this.opts.showPageBounds&&((r=(s=this.document)==null?void 0:s.pages)!=null&&r.length)&&this.drawPageBoundsOverlay(t),this.scene&&(this.drawImagesOverlay(t,this.scene.imageItems,e),this.drawTextOverlay(t,this.scene.textItems,e)),t.restore())}drawPageBoundsOverlay(e){var t,i;if((i=(t=this.document)==null?void 0:t.pages)!=null&&i.length){e.save(),e.strokeStyle="rgba(148, 163, 184, 0.34)",e.lineWidth=1,e.setLineDash([8,6]);for(const s of this.document.pages){const r=this.worldToScreen({x:0,y:0}),o=this.worldToScreen({x:s.width,y:s.height});e.strokeRect(Math.min(r.x,o.x),Math.min(r.y,o.y),Math.abs(o.x-r.x),Math.abs(o.y-r.y))}e.restore()}}drawTextOverlay(e,t,i){const s=this.opts.maxVisibleTextLabels;let r=0;for(const o of t){if(r>=s)break;if(!at(o.bounds,i))continue;const a=Math.abs(o.height)*this.view.scale;if(a<this.opts.textMinPixelHeight)continue;const c=this.worldToScreen(o.point);if(c.x<-512||c.y<-512||c.x>this.cssWidth+512||c.y>this.cssHeight+512)continue;e.save(),e.translate(c.x,c.y),e.rotate(-o.rotation),e.scale((o.generationFlag&2?-1:1)*o.xScale,o.generationFlag&4?-1:1);const h=Math.max(4,Math.min(256,a));e.font=`${h}px ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`,e.fillStyle=o.color,e.globalAlpha=o.opacity,e.textAlign=o.halign===1||o.halign===4?"center":o.halign===2?"right":"left",e.textBaseline=o.valign===1?"bottom":o.valign===2?"middle":o.valign===3?"top":"alphabetic";for(const[l,d]of o.text.split(/\r?\n/g).entries())e.fillText(d,0,l*h*1.22);e.restore(),r++}}drawImagesOverlay(e,t,i){for(const s of t){if(!at(s.bounds,i))continue;const r=this.worldToScreen(s.point),o=this.worldToScreen({x:s.point.x+s.width,y:s.point.y-s.height}),a=Math.min(r.x,o.x),c=Math.min(r.y,o.y),h=Math.abs(o.x-r.x),l=Math.abs(o.y-r.y);if(!(h<1||l<1)){if(s.source){const d=this.getImage(s.source);if(d.complete&&d.naturalWidth>0){e.save(),e.globalAlpha=s.opacity,e.drawImage(d,a,c,h,l),e.restore();continue}d.onload=()=>this.scheduleRender()}this.opts.showImagePlaceholders&&(e.save(),e.strokeStyle=s.color,e.globalAlpha=s.opacity,e.lineWidth=1,e.strokeRect(a,c,h,l),e.beginPath(),e.moveTo(a,c),e.lineTo(a+h,c+l),e.moveTo(a+h,c),e.lineTo(a,c+l),e.stroke(),e.restore())}}}getImage(e){let t=this.imageCache.get(e);return t||(t=new Image,t.src=e,this.imageCache.set(e,t)),t}createOverlayCanvas(){const e=this.canvas.parentElement;if(!e||typeof document>"u")return;window.getComputedStyle(e).position==="static"&&(e.style.position="relative");const i=document.createElement("canvas");i.className="cad-viewer-text-overlay",i.setAttribute("aria-hidden","true"),i.style.position="absolute",i.style.inset="0",i.style.width="100%",i.style.height="100%",i.style.pointerEvents="none",i.style.zIndex="1";const s=i.getContext("2d");s&&(e.appendChild(i),this.overlayCanvas=i,this.overlayCtx=s)}resizeOverlay(e,t){this.overlayCanvas&&(this.overlayCanvas.width!==e||this.overlayCanvas.height!==t)&&(this.overlayCanvas.width=e,this.overlayCanvas.height=t)}bindEvents(){const e=this.eventController.signal;this.canvas.addEventListener("wheel",i=>{i.preventDefault();const s=i.deltaY<0?this.opts.wheelZoomFactor:1/this.opts.wheelZoomFactor;this.zoom(s,{x:i.offsetX,y:i.offsetY})},{passive:!1,signal:e}),this.canvas.addEventListener("pointerdown",i=>{this.canvas.setPointerCapture(i.pointerId),this.isDragging=!0,this.lastPointer={x:i.clientX,y:i.clientY},this.canvas.classList.add("is-dragging")},{signal:e}),this.canvas.addEventListener("pointermove",i=>{!this.isDragging||!this.lastPointer||(this.panByScreenDelta(i.clientX-this.lastPointer.x,i.clientY-this.lastPointer.y),this.lastPointer={x:i.clientX,y:i.clientY})},{signal:e});const t=i=>{i&&this.canvas.hasPointerCapture(i.pointerId)&&this.canvas.releasePointerCapture(i.pointerId),this.isDragging=!1,this.lastPointer=void 0,this.canvas.classList.remove("is-dragging")};this.canvas.addEventListener("pointerup",t,{signal:e}),this.canvas.addEventListener("pointercancel",()=>t(),{signal:e}),this.canvas.addEventListener("webglcontextlost",i=>{i.preventDefault(),this.cancelScheduledRender()},{signal:e})}visibleWorldBounds(){const e=this.cssWidth/Math.max(this.view.scale,1e-12)/2,t=this.cssHeight/Math.max(this.view.scale,1e-12)/2;return{minX:this.view.centerX-e,maxX:this.view.centerX+e,minY:this.view.centerY-t,maxY:this.view.centerY+t}}get cssWidth(){return this.canvas.clientWidth||1}get cssHeight(){return this.canvas.clientHeight||1}clampScale(e){return Math.min(this.opts.maxScale,Math.max(this.opts.minScale,e))}boundsOptions(){return{maxInsertDepth:this.opts.maxInsertDepth,maxCurveSegments:this.opts.maxCurveSegments}}disposeScene(){if(!this.scene)return;const e=this.gl;for(const t of[...this.scene.lineBatches,...this.scene.triangleBatches,...this.scene.lineTypePointBatches,...this.scene.pointBatches])e.deleteBuffer(t.positionBuffer),e.deleteBuffer(t.colorBuffer);this.scene=void 0}emitViewChange(){var e;(e=this.onViewChange)==null||e.call(this,{view:this.getViewState(),fitScale:this.fitScale,zoomRatio:this.getZoomRatio(),zoomPercent:this.getZoomPercent(),bounds:this.getBounds()})}}function rt(){if(typeof document>"u")return!1;const n=document.createElement("canvas");return!!(n.getContext("webgl2")??n.getContext("webgl")??n.getContext("experimental-webgl"))}function ws(n,e){const t={alpha:!1,antialias:e.antialias??!0,depth:!1,stencil:!1,preserveDrawingBuffer:e.preserveDrawingBuffer??!1,powerPreference:e.powerPreference??"high-performance"};return n.getContext("webgl2",t)??n.getContext("webgl",t)??n.getContext("experimental-webgl",t)??void 0}function Ps(n){const e=`
10
10
  attribute vec2 a_position;
11
11
  attribute vec4 a_color;
12
12
  uniform vec2 u_viewCenter;
@@ -24,11 +24,11 @@
24
24
  gl_PointSize = u_pointSize;
25
25
  v_color = a_color;
26
26
  }
27
- `,n=`
27
+ `,t=`
28
28
  precision mediump float;
29
29
  varying vec4 v_color;
30
30
  void main() {
31
31
  gl_FragColor = v_color;
32
32
  }
33
- `,r=Mt(t,t.VERTEX_SHADER,e),i=Mt(t,t.FRAGMENT_SHADER,n),o=t.createProgram();if(!o)throw new Error("Failed to create WebGL program.");if(t.attachShader(o,r),t.attachShader(o,i),t.linkProgram(o),!t.getProgramParameter(o,t.LINK_STATUS)){const f=t.getProgramInfoLog(o)??"Unknown WebGL program link error.";throw t.deleteProgram(o),new Error(f)}t.deleteShader(r),t.deleteShader(i);const s=t.getUniformLocation(o,"u_viewCenter"),a=t.getUniformLocation(o,"u_scale"),c=t.getUniformLocation(o,"u_viewport"),l=t.getUniformLocation(o,"u_pointSize");if(!s||!a||!c||!l)throw new Error("Failed to resolve WebGL shader uniforms.");return{program:o,aPosition:t.getAttribLocation(o,"a_position"),aColor:t.getAttribLocation(o,"a_color"),uViewCenter:s,uScale:a,uViewport:c,uPointSize:l}}function Mt(t,e,n){const r=t.createShader(e);if(!r)throw new Error("Failed to create WebGL shader.");if(t.shaderSource(r,n),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS)){const i=t.getShaderInfoLog(r)??"Unknown WebGL shader compile error.";throw t.deleteShader(r),new Error(i)}return r}function Xn(t,e){let n=0;const r=c=>c.map(l=>{const f=Et(t,l.positions),h=Et(t,l.colors),d=l.positions.byteLength+l.colors.byteLength;return n+=d,{positionBuffer:f,colorBuffer:h,vertexCount:l.positions.length/2,primitiveCount:l.primitiveCount,bounds:l.bounds,gpuBytes:d}}),i=r(e.lineBatches),o=r(e.triangleBatches),s=r(e.lineTypePointBatches),a=r(e.pointBatches);return{origin:e.origin,lineBatches:i,triangleBatches:o,lineTypePointBatches:s,pointBatches:a,textItems:e.textItems,imageItems:e.imageItems,stats:e.stats,primitiveCount:e.primitiveCount,gpuMemoryBytes:n,buildElapsedMs:e.buildElapsedMs}}function Et(t,e){const n=t.createBuffer();if(!n)throw new Error("Failed to create WebGL buffer.");return t.bindBuffer(t.ARRAY_BUFFER,n),t.bufferData(t.ARRAY_BUFFER,e,t.STATIC_DRAW),n}function jn(t,e,n){const r=performance.now(),i=j(n)?{x:(n.minX+n.maxX)/2,y:(n.minY+n.maxY)/2}:{x:0,y:0},o=new $n(t,e,n,i);for(const a of t.entities)o.addEntityTracked(a,0);const s=o.finalize();return s.buildElapsedMs=performance.now()-r,s}class $n{constructor(e,n,r,i){u(this,"lineBuckets",new Map);u(this,"triangleBuckets",new Map);u(this,"lineTypePointBuckets",new Map);u(this,"pointBuckets",new Map);u(this,"textItems",[]);u(this,"imageItems",[]);u(this,"stats",{total:0,drawn:0,skipped:0,byType:{},unsupported:{},backend:"webgl",primitiveCount:0,visiblePrimitiveCount:0,culledPrimitiveCount:0,gpuMemoryBytes:0,buildElapsedMs:0});u(this,"tileSize");u(this,"maxVerticesPerBatch");u(this,"primitiveCount",0);this.document=e,this.opts=n,this.bounds=r,this.origin=i;const o=j(r)?Math.max(r.maxX-r.minX,r.maxY-r.minY,1e-9):1;this.tileSize=n.enableSpatialIndex?o/Math.max(8,n.spatialIndexCellCount):Number.POSITIVE_INFINITY,this.maxVerticesPerBatch=Math.max(4096,Math.floor(n.maxVerticesPerBatch))}addEntityTracked(e,n){this.stats.total++;const r=String(e.type??"UNKNOWN").toUpperCase();this.stats.byType[r]=(this.stats.byType[r]??0)+1;const i=this.lookupLayer(e.layer);if(e.isVisible===!1||!bt(i)){this.stats.skipped++;return}this.addEntity(e,r,n)}finalize(){const e=be(this.lineBuckets,this.maxVerticesPerBatch),n=be(this.triangleBuckets,this.maxVerticesPerBatch),r=be(this.lineTypePointBuckets,this.maxVerticesPerBatch),i=be(this.pointBuckets,this.maxVerticesPerBatch);return this.stats.primitiveCount=this.primitiveCount,{origin:this.origin,lineBatches:e,triangleBatches:n,lineTypePointBatches:r,pointBatches:i,textItems:this.textItems,imageItems:this.imageItems,stats:this.stats,primitiveCount:this.primitiveCount,buildElapsedMs:0}}addEntity(e,n,r){switch(e.kind??O(n)){case"line":return this.addLineEntity(e);case"circle":return this.addCircleEntity(e);case"arc":return this.addArcEntity(e);case"polyline":return this.addPolylineEntity(e);case"ellipse":return this.addEllipseEntity(e);case"text":return this.addTextEntity(e);case"point":return this.addPointEntity(e);case"insert":return this.addInsertEntity(e,r);case"solid":return this.addSolidEntity(e);case"hatch":return this.addHatchEntity(e);case"spline":return this.addSplineEntity(e);case"path":return this.addPathEntity(e);case"image":return this.addImageEntity(e);case"viewport":return this.markSkipped(n);default:this.stats.unsupported[n]=(this.stats.unsupported[n]??0)+1,this.stats.skipped++,this.opts.showUnsupportedMarkers&&this.addUnsupportedMarker(e)}}addLineEntity(e){if(!p(e.startPoint)||!p(e.endPoint))return this.markSkipped("LINE");this.addPolyline([e.startPoint,e.endPoint],!1,this.strokeBytes(e),e),this.stats.drawn++}addCircleEntity(e){const n=e.center,r=Number(e.radius);if(!p(n)||!Number.isFinite(r))return this.markSkipped("CIRCLE");const i=Math.max(16,Math.min(this.opts.maxCurveSegments,Math.ceil(Math.sqrt(Math.abs(r))*12))),o=Q(n,r,0,Math.PI*2,!0,i);this.addPolyline(o,!0,this.strokeBytes(e),e),this.stats.drawn++}addArcEntity(e){const n=e.center,r=Number(e.radius),i=Number(e.startAngle),o=Number(e.endAngle);if(!p(n)||!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(o))return this.markSkipped("ARC");this.addPolyline(Q(n,r,i,o,!0,this.opts.maxCurveSegments),!1,this.strokeBytes(e),e),this.stats.drawn++}addPolylineEntity(e){const n=e.vertices??e.points;if(!Array.isArray(n)||n.length<2)return this.markSkipped(String(e.type));const r=Ce(e),i=[],o=r?n.length:n.length-1;for(let s=0;s<o;s++){const a=n[s],c=n[(s+1)%n.length];if(!p(a)||!p(c))continue;const l=tt(a,c,Number(a.bulge??0),Math.max(4,Math.min(24,this.opts.maxCurveSegments/4)));i.length>0&&l.shift(),i.push(...l)}if(i.length<2)return this.markSkipped(String(e.type));this.addPolyline(i,r,this.strokeBytes(e),e),this.stats.drawn++}addEllipseEntity(e){if(!p(e.center)||!p(e.majorAxisEndPoint))return this.markSkipped("ELLIPSE");const n=le(e.center,e.majorAxisEndPoint,Number(e.axisRatio??1),Number(e.startAngle??0),Number(e.endAngle??Math.PI*2),this.opts.maxCurveSegments),r=Math.abs(Number(e.endAngle??Math.PI*2)-Number(e.startAngle??0))>=Math.PI*2-1e-6;this.addPolyline(n,r,this.strokeBytes(e),e),this.stats.drawn++}addTextEntity(e){const n=e.insertionPoint??e.startPoint??e.center,r=nt(String(e.text??e.value??"")),i=Number(e.textHeight??e.height??1);if(!p(n)||!r||!Number.isFinite(i))return this.markSkipped(String(e.type));const o=k(n),s=Math.max(1,r.split(/\r?\n/g).reduce((c,l)=>Math.max(c,l.length),0))*Math.abs(i)*.62,a=Math.max(1,r.split(/\r?\n/g).length)*Math.abs(i)*1.22;this.textItems.push({point:o,text:r,height:i,rotation:Number(e.rotation??0),color:_(e,this.document,this.colorOptions()),opacity:$(Number(e.opacity??1),0,1),bounds:{minX:o.x-s*.1,minY:o.y-a,maxX:o.x+s,maxY:o.y+a}}),this.stats.drawn++}addPointEntity(e){const n=e.point??e.location??e.center??e.insertionPoint;if(!p(n))return this.markSkipped("POINT");this.addPoint(n,this.strokeBytes(e)),this.stats.drawn++}addInsertEntity(e,n){const r=this.lookupBlock(e.blockName??e.name);if(r&&n<this.opts.maxInsertDepth){const o=ge(e,r.basePoint??{x:0,y:0});for(const s of r.entities){const a=yt(s,e,this.document,this.colorOptions()),c=Fe(a,e,this.document);this.addEntityTracked(Y(c,o),n+1)}return}const i=e.insertionPoint;if(!p(i))return this.markSkipped("INSERT");if(this.addPoint(i,this.strokeBytes(e)),Array.isArray(e.attribs))for(const o of e.attribs)this.addTextEntity(o);this.stats.drawn++}addSolidEntity(e){const n=e.vertices??e.points;if(!Array.isArray(n)||n.length<3)return this.markSkipped(String(e.type));const r=n.filter(p).map(k);if(r.length<3)return this.markSkipped(String(e.type));const i=this.fillBytes(e)??this.strokeBytes(e);this.addTriangleFan(r,i),this.addPolyline(r,!0,this.strokeBytes(e),e),this.stats.drawn++}addHatchEntity(e){var s;const n=e.loops;if(!Array.isArray(n)||n.length===0)return this.markSkipped("HATCH");const r=this.strokeBytes(e),i=this.fillBytes(e);let o=!1;for(const a of n){const c=(s=a.commands)!=null&&s.length?Lt(a.commands,this.opts.maxCurveSegments):(a.vertices??[]).filter(p).map(k);c.length<2||(this.addPolyline(c,!0,r,e),i&&c.length>=3&&this.addTriangleFan(c,i),o=!0)}if(!o)return this.markSkipped("HATCH");this.stats.drawn++}addSplineEntity(e){var r;const n=(r=e.fitPoints)!=null&&r.length?e.fitPoints:e.controlPoints;if(!n||n.length<2)return this.markSkipped("SPLINE");this.addPolyline(n.filter(p).map(k),!!e.isClosed,this.strokeBytes(e),e),this.stats.drawn++}addPathEntity(e){var i;if(!((i=e.commands)!=null&&i.length))return this.markSkipped(String(e.type));const n=Lt(e.commands,this.opts.maxCurveSegments);if(n.length<2)return this.markSkipped(String(e.type));this.addPolyline(n,!1,this.strokeBytes(e),e);const r=this.fillBytes(e);r&&n.length>=3&&this.addTriangleFan(n,r),this.stats.drawn++}addImageEntity(e){const n=e.insertionPoint;if(!p(n))return this.markSkipped(String(e.type));const r=Number(e.width??32),i=Number(e.height??32);if(!Number.isFinite(r)||!Number.isFinite(i))return this.markSkipped(String(e.type));const o=k(n),s=_e([o,{x:o.x+r,y:o.y-i}]);this.imageItems.push({point:o,width:r,height:i,source:e.imageDataUrl??e.imageSource,color:_(e,this.document,this.colorOptions()),opacity:$(Number(e.opacity??1),0,1),bounds:s}),this.stats.drawn++}addUnsupportedMarker(e){const n=It(e);n&&this.addPoint(n,this.strokeBytes(e))}addPolyline(e,n,r,i){const o=e.filter(p).map(k);if(o.length<2)return;const s=i?ue(i,this.document):void 0;if(s){const a=me(o,n,s);for(const[c,l]of a.segments)this.addSegment(c,l,r);for(const c of a.dots)this.addLineTypePoint(c,r);return}for(let a=0;a<o.length-1;a++)this.addSegment(o[a],o[a+1],r);n&&this.addSegment(o[o.length-1],o[0],r)}addSegment(e,n,r){if(!p(e)||!p(n)||Math.hypot(e.x-n.x,e.y-n.y)<=1e-14)return;const i=this.batchFor(this.lineBuckets,_e([e,n]));V(i,e,r,this.origin),V(i,n,r,this.origin),i.primitiveCount++,this.primitiveCount++}addPoint(e,n){const r=this.batchFor(this.pointBuckets,Tt(e));V(r,e,n,this.origin),r.primitiveCount++,this.primitiveCount++}addLineTypePoint(e,n){const r=this.batchFor(this.lineTypePointBuckets,Tt(e));V(r,e,n,this.origin),r.primitiveCount++,this.primitiveCount++}addTriangleFan(e,n){const r=e.filter(p).map(k);if(r.length<3)return;const i=_e(r),o=this.batchFor(this.triangleBuckets,i);for(let s=1;s<r.length-1;s++)V(o,r[0],n,this.origin),V(o,r[s],n,this.origin),V(o,r[s+1],n,this.origin),o.primitiveCount++,this.primitiveCount++}batchFor(e,n){const r=this.bucketKey(n);let i=e.get(r);return i||(i=Gn(),e.set(r,i)),C(i.bounds,{x:n.minX,y:n.minY}),C(i.bounds,{x:n.maxX,y:n.maxY}),i}bucketKey(e){if(!Number.isFinite(this.tileSize))return"all";const n=(e.minX+e.maxX)/2,r=(e.minY+e.maxY)/2,i=Math.floor((n-this.bounds.minX)/this.tileSize),o=Math.floor((r-this.bounds.minY)/this.tileSize);return`${i}:${o}`}strokeBytes(e){return Ve(_(e,this.document,this.colorOptions()),[255,255,255,255],$(Number(e.opacity??1),0,1))}fillBytes(e){const n=Ee(e,this.document,this.colorOptions());return n?Ve(n,[255,255,255,255],$(Number(e.opacity??1),0,1)):void 0}colorOptions(){return{foreground:this.opts.foreground,background:this.opts.background,trueColorByteOrder:this.opts.trueColorByteOrder,contrastMode:this.opts.contrastMode,minColorContrast:this.opts.minColorContrast}}markSkipped(e){this.stats.skipped++,this.stats.unsupported[e]=this.stats.unsupported[e]??0}lookupLayer(e){if(e)return this.document.layers[e]??this.document.layers[e.toLowerCase()]??Object.values(this.document.layers).find(n=>n.name.toLowerCase()===e.toLowerCase())}lookupBlock(e){if(e)return this.document.blocks[e]??this.document.blocks[e.toLowerCase()]??Object.values(this.document.blocks).find(n=>n.name.toLowerCase()===e.toLowerCase())}}function Gn(){return{positions:[],colors:[],bounds:B(),primitiveCount:0}}function V(t,e,n,r){t.positions.push(e.x-r.x,e.y-r.y),t.colors.push(n[0],n[1],n[2],n[3])}function be(t,e){const n=[];for(const r of t.values()){const i=r.positions.length/2;if(i<=0||!j(r.bounds))continue;if(i<=e){n.push({positions:new Float32Array(r.positions),colors:new Uint8Array(r.colors),bounds:{...r.bounds},primitiveCount:r.primitiveCount});continue}const o=Zn(r),s=Math.max(o,Math.floor(e/o)*o);for(let a=0;a<i;a+=s){const c=Math.min(i,a+s),l=r.positions.slice(a*2,c*2),f=r.colors.slice(a*4,c*4),h=B();for(let d=0;d<l.length;d+=2)C(h,{x:l[d],y:l[d+1]});n.push({positions:new Float32Array(l),colors:new Uint8Array(f),bounds:{...r.bounds},primitiveCount:Math.floor((c-a)/o)})}}return n}function Zn(t){const e=t.positions.length/2;return e===t.primitiveCount?1:e===t.primitiveCount*3?3:2}function qn(t,e){var o;const n=B();if((o=t.pages)!=null&&o.length)for(const s of t.pages)C(n,{x:0,y:0}),C(n,{x:s.width,y:s.height});const r=s=>{if(s)return t.blocks[s]??t.blocks[s.toLowerCase()]??Object.values(t.blocks).find(a=>a.name.toLowerCase()===s.toLowerCase())},i=(s,a)=>{const c=String(s.type??"").toUpperCase(),l=s.kind??O(c);if(l==="insert"){const f=r(s.blockName??s.name);if(f&&a<e.maxInsertDepth){const h=ge(s,f.basePoint??{x:0,y:0});for(const d of f.entities)i(Y(d,h),a+1);return}}if(l==="line")p(s.startPoint)&&C(n,s.startPoint),p(s.endPoint)&&C(n,s.endPoint);else if(l==="circle"||l==="arc")p(s.center)&&Number.isFinite(s.radius)&&Qe(n,s.center,Number(s.radius));else if(l==="polyline"||l==="solid"||l==="spline")for(const f of[...s.vertices??[],...s.points??[],...s.controlPoints??[],...s.fitPoints??[]])p(f)&&C(n,f);else if(l==="ellipse")p(s.center)&&p(s.majorAxisEndPoint)&&le(s.center,s.majorAxisEndPoint,Number(s.axisRatio??1),Number(s.startAngle??0),Number(s.endAngle??Math.PI*2),e.maxCurveSegments).forEach(f=>C(n,f));else if(l==="path")for(const f of s.commands??[])for(const h of f.points)C(n,h);else if(l==="hatch")for(const f of s.loops??[]){for(const h of f.vertices??[])C(n,h);for(const h of f.commands??[])for(const d of h.points)C(n,d)}else{const f=It(s);f&&C(n,f)}};for(const s of t.entities)i(s,0);return et(n)}function Lt(t,e){const n=[];let r,i;const o=s=>{(!n.length||Math.hypot(n[n.length-1].x-s.x,n[n.length-1].y-s.y)>1e-12)&&n.push(k(s)),r=k(s)};for(const s of t)if(s.cmd==="M")r=k(s.points[0]),i=r,o(r);else if(s.cmd==="L")o(s.points[0]);else if(s.cmd==="Q"&&r&&s.points.length>=2){const a=r,[c,l]=s.points,f=Math.max(4,Math.min(e,24));for(let h=1;h<=f;h++){const d=h/f,m=1-d;o({x:m*m*a.x+2*m*d*c.x+d*d*l.x,y:m*m*a.y+2*m*d*c.y+d*d*l.y})}}else if(s.cmd==="C"&&r&&s.points.length>=3){const a=r,[c,l,f]=s.points,h=Math.max(6,Math.min(e,32));for(let d=1;d<=h;d++){const m=d/h,g=1-m;o({x:g**3*a.x+3*g*g*m*c.x+3*g*m*m*l.x+m**3*f.x,y:g**3*a.y+3*g*g*m*c.y+3*g*m*m*l.y+m**3*f.y})}}else s.cmd==="Z"&&i&&o(i);return n}function It(t){for(const e of["startPoint","insertionPoint","center","point","location"]){const n=t[e];if(p(n))return k(n)}if(Array.isArray(t.vertices)&&p(t.vertices[0]))return k(t.vertices[0]);if(Array.isArray(t.commands)&&t.commands.length){const e=t.commands.find(n=>n.points.length>0);if(e)return k(e.points[0])}}function _e(t){const e=B();for(const n of t)C(e,n);return e}function Tt(t){return{minX:t.x,minY:t.y,maxX:t.x,maxY:t.y}}function Ye(t,e){return t.minX<=e.maxX&&t.maxX>=e.minX&&t.minY<=e.maxY&&t.maxY>=e.minY}function Kn(t,e){return e.trueColorByteOrder!==void 0&&e.trueColorByteOrder!==t.trueColorByteOrder||e.contrastMode!==void 0&&e.contrastMode!==t.contrastMode||e.minColorContrast!==void 0&&e.minColorContrast!==t.minColorContrast||e.foreground!==void 0&&e.foreground!==t.foreground||e.background!==void 0&&e.background!==t.background||e.maxInsertDepth!==void 0&&e.maxInsertDepth!==t.maxInsertDepth||e.maxCurveSegments!==void 0&&e.maxCurveSegments!==t.maxCurveSegments||e.spatialIndexCellCount!==void 0&&e.spatialIndexCellCount!==t.spatialIndexCellCount||e.maxVerticesPerBatch!==void 0&&e.maxVerticesPerBatch!==t.maxVerticesPerBatch||e.enableSpatialIndex!==void 0&&e.enableSpatialIndex!==t.enableSpatialIndex}function Jn(t,e){return{...t.stats,renderElapsedMs:e,backend:"webgl",primitiveCount:t.primitiveCount,visiblePrimitiveCount:0,culledPrimitiveCount:0,gpuMemoryBytes:t.gpuMemoryBytes,buildElapsedMs:t.buildElapsedMs}}function Qn(t){return{total:t.total,drawn:t.drawn,skipped:t.skipped,byType:{...t.byType},unsupported:{...t.unsupported},renderElapsedMs:t.renderElapsedMs,backend:t.backend,primitiveCount:t.primitiveCount,visiblePrimitiveCount:t.visiblePrimitiveCount,culledPrimitiveCount:t.culledPrimitiveCount,gpuMemoryBytes:t.gpuMemoryBytes,buildElapsedMs:t.buildElapsedMs}}function Ve(t,e,n=1){const r=t.trim().toLowerCase();let i;if(/^#[0-9a-f]{3}$/i.test(r))i=[parseInt(r[1]+r[1],16),parseInt(r[2]+r[2],16),parseInt(r[3]+r[3],16),255];else if(/^#[0-9a-f]{6}$/i.test(r))i=[parseInt(r.slice(1,3),16),parseInt(r.slice(3,5),16),parseInt(r.slice(5,7),16),255];else{const s=r.match(/^rgba?\(([^)]+)\)$/i);if(s){const a=s[1].split(/[\s,\/]+/).filter(Boolean),c=a.slice(0,3).some(f=>f.includes("%")),l=a.map(f=>Number(f.replace("%","")));l.length>=3&&l.slice(0,3).every(Number.isFinite)&&(i=[ne(c?l[0]*2.55:l[0]),ne(c?l[1]*2.55:l[1]),ne(c?l[2]*2.55:l[2]),ne((Number.isFinite(l[3])?l[3]:1)*255)])}}const o=i??e;return[o[0],o[1],o[2],ne(o[3]*n)]}function ne(t){return Math.max(0,Math.min(255,Math.round(t)))}class At{constructor(e={}){u(this,"canvas");u(this,"renderer");u(this,"registry");u(this,"nativeHost");u(this,"options");u(this,"lastResult");u(this,"activeNativeLoader");var n;if(this.options={autoFit:!0,...e},this.registry=e.registry??mt(e),e.loaders)for(const r of e.loaders)this.registry.register(r);if(this.canvas=e.canvas??document.createElement("canvas"),this.canvas.classList.add("cad-viewer-canvas"),e.container)e.container.classList.add("cad-viewer-container"),e.canvas||(this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.display="block",e.container.appendChild(this.canvas)),this.nativeHost=e.nativeHost??document.createElement("div"),this.nativeHost.classList.add("cad-viewer-native-host"),e.nativeHost||e.container.appendChild(this.nativeHost);else if(e.nativeHost)this.nativeHost=e.nativeHost,this.nativeHost.classList.add("cad-viewer-native-host");else if((n=e.canvas)!=null&&n.parentElement){e.canvas.parentElement.classList.add("cad-viewer-container");const r=document.createElement("div");r.classList.add("cad-viewer-native-host"),e.canvas.parentElement.appendChild(r),this.nativeHost=r}this.renderer=nr(e.renderer??"auto",this.canvas,e.canvasOptions),this.renderer.onStats=r=>{var i,o;return(o=(i=this.options).onRenderStats)==null?void 0:o.call(i,r)},this.renderer.onViewChange=r=>{var i,o;return(o=(i=this.options).onViewChange)==null?void 0:o.call(i,r)}}registerLoader(e){return this.registry.register(e),this}async loadFile(e,n={}){var r,i;return(i=(r=this.options).onLoadStart)==null||i.call(r,e),this.loadThroughRegistry({file:e,fileName:e.name},n,e.name)}async loadBuffer(e,n,r={}){var i,o;return(o=(i=this.options).onLoadStart)==null||o.call(i,e),this.loadThroughRegistry({buffer:e,fileName:n},r,n)}async load(e,n={}){var r,i,o;return(i=(r=this.options).onLoadStart)==null||i.call(r,e),this.loadThroughRegistry(e,n,e.fileName??((o=e.file)==null?void 0:o.name))}setDocument(e,n){var i,o;this.deactivateNativeRenderer();const r={document:e,raw:e.raw,bytes:0,elapsedMs:0,format:e.format,warnings:e.warnings,summary:J(e),fileName:n};return this.renderer.setDocument(e),this.options.autoFit||this.renderer.render(),this.lastResult=r,(o=(i=this.options).onLoad)==null||o.call(i,r),r}fit(){var e,n;this.activeNativeLoader?(n=(e=this.activeNativeLoader).fit)==null||n.call(e):this.renderer.fitToView()}zoomIn(){var e,n;this.activeNativeLoader?(n=(e=this.activeNativeLoader).zoomIn)==null||n.call(e):this.renderer.zoomIn()}zoomOut(){var e,n;this.activeNativeLoader?(n=(e=this.activeNativeLoader).zoomOut)==null||n.call(e):this.renderer.zoomOut()}resize(){var e,n;this.activeNativeLoader?(n=(e=this.activeNativeLoader).resize)==null||n.call(e):this.renderer.resize()}setCanvasOptions(e){var n,r;this.options.canvasOptions={...this.options.canvasOptions??{},...e},this.renderer.setOptions(e),this.activeNativeLoader&&((r=(n=this.activeNativeLoader).setNativeOptions)==null||r.call(n,{...this.mergeLoadOptions({}),dwfBackground:e.background??this.options.dwfBackground}))}async preloadDwg(e={}){const n=this.registry.list().find(r=>r.id==="dwg");if(!(n!=null&&n.preload))throw new Error("The registered DWG loader does not support preload().");return n.preload(this.mergeLoadOptions(e))}clear(){this.lastResult=void 0,this.deactivateNativeRenderer(),this.renderer.clear()}destroy(){var e,n,r;this.deactivateNativeRenderer();for(const i of this.registry.list()){const o=i;(e=o.terminateWorker)==null||e.call(o),(n=o.unmount)==null||n.call(o),(r=o.destroy)==null||r.call(o)}this.renderer.destroy()}getLoadResult(){return this.lastResult}getDocument(){var e;return this.activeNativeLoader?(e=this.lastResult)==null?void 0:e.document:this.renderer.getDocument()}getSourceDocument(){var e;return this.activeNativeLoader?(e=this.lastResult)==null?void 0:e.document:this.renderer.getSourceDocument()}getZoomPercent(){return this.activeNativeLoader?100:this.renderer.getZoomPercent()}isNativeRendererActive(){return!!this.activeNativeLoader}async loadThroughRegistry(e,n,r){var i,o;try{const s=this.mergeLoadOptions(n);He(s.signal);const a=await this.registry.detect(e),c={...e,buffer:a.bytes};if(pt(a.loader))return await this.applyNativeLoadResult(a.loader,c,s,r);const l=await a.loader.load(c,s);return this.applyLoadResult(l,r)}catch(s){const a=tr(s);throw(o=(i=this.options).onError)==null||o.call(i,a),a}}applyLoadResult(e,n){var i,o,s,a;this.deactivateNativeRenderer(),(o=(i=this.options).onLoadProgress)==null||o.call(i,{phase:"render",format:e.format,message:"Rendering normalized CAD scene…",percent:96}),this.renderer.setDocument(e.document),this.options.autoFit||this.renderer.render();const r={...e,fileName:n,summary:J(e.document)};return this.lastResult=r,(a=(s=this.options).onLoad)==null||a.call(s,r),r}async applyNativeLoadResult(e,n,r,i){var o,s,a;if(!this.nativeHost)throw new Error("Native DWF rendering requires CadViewerOptions.container, nativeHost, or a canvas parent element.");He(r.signal),this.renderer.clear(),(o=this.activeNativeLoader)==null||o.unmount(),this.activeNativeLoader=e,this.canvas.style.display="none",this.nativeHost.classList.add("is-active");try{const c=await e.mount(n,this.nativeHost,r);He(r.signal);const l={...c,fileName:i,summary:J(c.document)};return this.lastResult=l,this.emitNativeRenderStats(c),(a=(s=this.options).onLoad)==null||a.call(s,l),l}catch(c){throw this.deactivateNativeRenderer(),c}}deactivateNativeRenderer(){var e,n;if(!this.activeNativeLoader&&!((e=this.nativeHost)!=null&&e.classList.contains("is-active"))){this.canvas.style.display="";return}(n=this.activeNativeLoader)==null||n.unmount(),this.activeNativeLoader=void 0,this.nativeHost&&(this.nativeHost.classList.remove("is-active"),this.nativeHost.replaceChildren()),this.canvas.style.display=""}emitNativeRenderStats(e){var s,a,c,l;const n=e.document.metadata,r=Number(((s=n.nativeRenderStats)==null?void 0:s.commands)??e.document.entities.length??0),o=String(((a=n.nativeRenderStats)==null?void 0:a.backend)??"webgl").includes("webgl")?"webgl":"canvas2d";(l=(c=this.options).onRenderStats)==null||l.call(c,{total:r,drawn:r,skipped:0,byType:J(e.document).byType,unsupported:{},renderElapsedMs:e.elapsedMs,backend:o,primitiveCount:r,visiblePrimitiveCount:r,culledPrimitiveCount:0,gpuMemoryBytes:void 0,buildElapsedMs:e.elapsedMs})}mergeLoadOptions(e){const n=this.options.onProgress,r=e.onProgress;return{...this.options,...e,onProgress:i=>{var o,s;(s=(o=this.options).onLoadProgress)==null||s.call(o,i),n==null||n(i),r&&r!==n&&r(i)}}}}function er(t={}){return new At(t)}function tr(t){return t instanceof Error?t:new Error(String(t))}function He(t){if(t!=null&&t.aborted)throw new DOMException("Loading cancelled.","AbortError")}function nr(t,e,n={}){if(t==="canvas2d")return new Oe(e,n);if(t==="webgl")return new We(e,n);if(ze())try{return new We(e,n)}catch{}return new Oe(e,n)}function rr(t,e,n,r={}){const i=t&&typeof t=="object"?t:{},o=or(i,r),s=ar(i,r),a=dr(i,r),c=sr(i.header,n),l=cr(i,c),f=l.view,h=Array.isArray(i.entities)?i.entities:[],d={keepRaw:!!r.keepRaw,includeUnknownProperties:!!r.keepRaw},m=h.filter(y=>!!y&&typeof y=="object").map(y=>Bt(y,d)),g=ae({format:"dwg",sourceName:e,header:c,layers:o,lineTypes:s,blocks:a,entities:m,savedView:f,metadata:{parser:"@mlightcad/libredwg-web",parserMode:"wasm",version:n,savedView:f},warnings:l.warning?[l.warning]:[],raw:r.keepRaw?t:void 0});return m.length===0&&g.warnings.push("DWG parsed successfully but no model-space entities were exposed by the converter. Check layout/paper-space content or unsupported proxy objects."),[...new Set(Object.values(s))].some(y=>y.pattern.some(x=>Number(x.elementTypeFlag??0)!==0))&&g.warnings.push("Complex SHX linetype glyphs are preserved in the normalized LTYPE definition and rendered as a dash/dot approximation; embedded shape glyph fidelity is not available yet."),g}function Bt(t,e){const n=ce(t,void 0,{...e,numericColorMode:"rgb"}),r=b(t.color);r!==void 0&&r>=0&&r<=16777215&&(n.color=r,n.trueColor=r),n.colorIndex=b(t.colorIndex??t.colorNumber??t.aci)??n.colorIndex,n.colorName=P(t.colorName??t.color_name)??n.colorName;const i=b(t.flag??t.flags);i!==void 0&&(n.flag=i);const o=String(t.type??t.entityType??"").toUpperCase(),s=/^(POLYLINE|POLYLINE_2D|POLYLINE2D|POLYLINE_3D|POLYLINE3D)$/.test(o);return(t.isClosed===!0||t.closed===!0||s&&(Number(i??0)&1)===1||o==="LWPOLYLINE"&&(Number(i??0)&512)===512)&&(n.isClosed=!0),n}function ir(t){return typeof t=="number"&&Number.isFinite(t)&&Math.abs(Math.trunc(t))>=1&&Math.abs(Math.trunc(t))<=255}function sr(t,e){const n=t&&typeof t=="object"?{...t}:{};return e&&(n.dwgVersion=e),n}function or(t,e){const n={},r=[],i=t.tables;for(const o of["LAYER","layer","layers"]){const s=t[o]??(i==null?void 0:i[o]);s&&r.push(s)}for(const o of r)for(const s of ye(o)){const a=s,c=P(a.name??a.layerName??a.entryName);if(!c)continue;const l=b(a.colorIndex??a.colorNumber),f=b(a.trueColor??a.true_color??a.truecolor??a.colorRGB??a.colorRgb??a.rgbColor??a.rgb),h=b(a.color),d=ir(l),m=f??(!d&&h!==void 0&&h>=0&&h<=16777215?h:void 0),g={name:c,color:d?void 0:a.color??a.colorName,colorIndex:l??(h!==void 0&&Math.abs(h)<=257?h:void 0),trueColor:m,lineType:P(a.lineType??a.linetype),lineweight:b(a.lineweight??a.lineWeight),isVisible:!(a.isVisible===!1||a.off===!0||Number(l??a.color??1)<0),isFrozen:!!(a.isFrozen??a.frozen),isLocked:!!(a.isLocked??a.locked),raw:e.keepRaw?a:void 0};Pe(n,g)}return n}function ar(t,e){const n={},r=t.tables,i=[t.LTYPE,t.ltype,t.lineTypes,r==null?void 0:r.LTYPE,r==null?void 0:r.ltype,r==null?void 0:r.lineTypes];for(const o of i)for(const s of ye(o)){const a=s,c=P(a.name??a.lineTypeName??a.entryName);if(!c)continue;const f=(Array.isArray(a.pattern)?a.pattern:Array.isArray(a.dashes)?a.dashes:[]).flatMap(h=>{if(typeof h=="number")return[{length:h}];if(!h||typeof h!="object")return[];const d=h,m=b(d.elementLength??d.length??d.dashLength);if(m===void 0)return[];const g=b(d.elementTypeFlag),S=b(d.shapeNumber),y=g!==void 0&&S!==void 0;return[{length:m,elementTypeFlag:y?S:b(d.typeFlag??d.elementTypeFlag),shapeNumber:y?g:b(d.shapeCode??d.shapeNumber),scale:b(d.scale),rotation:b(d.rotation),offsetX:b(d.offsetX),offsetY:b(d.offsetY),text:P(d.text)}]});Ut(n,{name:c,handle:P(a.handle??a.id),description:P(a.description),totalPatternLength:b(a.totalPatternLength??a.patternLength),pattern:f,raw:e.keepRaw?a:void 0})}return n}function cr(t,e){const n=t.tables,i=ye(t.VPORT??t.vports??(n==null?void 0:n.VPORT)??(n==null?void 0:n.vports)).filter(x=>!!x&&typeof x=="object").find(x=>String(x.name??"").trim().toLowerCase()==="*active"),o=i?"vport":"header-ucs",s=i??e,a=N(s.ucsOrigin??s.UCSORG??e.UCSORG),c=N(s.ucsXAxis??s.UCSXDIR??e.UCSXDIR),l=N(s.ucsYAxis??s.UCSYDIR??e.UCSYDIR),f=b(s.viewTwistAngle??s.twistAngle??s.VIEWTWIST)??0,h=N(s.viewDirectionFromTarget??s.viewDirection??s.direction??s.VIEWDIR),d=!hr(a,c,l);if(!(!!i||!!h||d||Math.abs(f)>1e-12))return{};const g=fr(h),S=g?lr(a,c,l,f):{a:1,b:0,c:0,d:1,e:0,f:0},y={source:o,name:P(s.name),handle:P(s.handle),center:N(s.center??s.VIEWCTR),target:N(s.viewTarget??s.target??s.TARGET),direction:h,viewHeight:b(s.viewHeight??s.height??s.VIEWSIZE),aspectRatio:b(s.aspectRatio),twistAngle:f,ucsOrigin:a,ucsXAxis:c,ucsYAxis:l,sceneTransformApplied:g,sceneTransform:S};return g?{view:y}:{view:y,warning:"The saved CAD view has a missing, non-finite, or tilted VIEWDIR. File Viewer kept world coordinates instead of applying an unsafe 2D UCS/PLAN rotation."}}function lr(t,e,n,r){const i=Ue(e)??{x:1,y:0},o=Ue(n)??{x:-i.y,y:i.x},s=i.x*o.x+i.y*o.y,a=Ue({x:o.x-i.x*s,y:o.y-i.y*s})??{x:-i.y,y:i.x},c={a:i.x,b:a.x,c:i.y,d:a.y,e:t?-(t.x*i.x+t.y*i.y):0,f:t?-(t.x*a.x+t.y*a.y):0};return pe(St(Number.isFinite(r)?r:0),c)}function Ue(t){if(!t||Math.abs(Number(t.z??0))>1e-6)return;const e=Math.hypot(t.x,t.y);if(!(!Number.isFinite(e)||e<1e-12))return{x:t.x/e,y:t.y/e}}function fr(t){if(!t||!Number.isFinite(t.x)||!Number.isFinite(t.y)||!Number.isFinite(t.z))return!1;const e=Math.hypot(t.x,t.y,Number(t.z));return!Number.isFinite(e)||e<1e-12?!1:Math.hypot(t.x,t.y)/e<=1e-4&&Math.abs(Number(t.z))/e>=1-1e-8}function hr(t,e,n){const r=(a,c)=>Number.isFinite(a)&&Math.abs(Number(a)-c)<=1e-10,i=!t||r(t.x,0)&&r(t.y,0)&&r(t.z??0,0),o=!e||r(e.x,1)&&r(e.y,0)&&r(e.z??0,0),s=!n||r(n.x,0)&&r(n.y,1)&&r(n.z??0,0);return i&&o&&s}function dr(t,e){const n={},r=[t.blocks,t.blockHeaders,t.block_records,t.blockRecords],i=t.tables;r.push(i==null?void 0:i.BLOCK,i==null?void 0:i.BLOCK_RECORD,i==null?void 0:i.blocks);const o={keepRaw:!!e.keepRaw,includeUnknownProperties:!!e.keepRaw};for(const s of r)for(const a of ye(s)){const c=a,l=P(c.name??c.blockName??c.name2);if(!l)continue;const h=(Array.isArray(c.entities)?c.entities:Array.isArray(c.ownedObjects)?c.ownedObjects:[]).filter(d=>!!d&&typeof d=="object").map(d=>Bt(d,o));Je(n,{name:l,basePoint:N(c.basePoint??c.origin)??{x:0,y:0},entities:h,raw:e.keepRaw?c:void 0})}return n}function ye(t){if(!t)return[];if(Array.isArray(t))return t;if(typeof t!="object")return[];const e=t,n=Object.values(e).filter(i=>i&&typeof i=="object"),r=["entries","records","items","values","layers","blocks"].flatMap(i=>Array.isArray(e[i])?e[i]:[]);return r.length>0?r:n}v.CadCanvasRenderer=Oe,v.CadLoaderRegistry=je,v.CadViewer=At,v.CadWebGLRenderer=We,v.DwfLoader=ct,v.DwgLoader=Ke,v.DwgWorkerClient=$e,v.DxfLoader=rt,v.applyByBlockLineTypeInheritance=Fe,v.colorFromAci=F,v.colorFromTrueColor=G,v.createCadDocument=ae,v.createCadSceneDocument=Re,v.createCadViewer=er,v.createDashedCadPrimitives=me,v.createDashedCadSegments=An,v.createDefaultLoaderRegistry=mt,v.detectCadFormat=R,v.inferEntityKind=O,v.isCadNativeRenderableLoader=pt,v.isCadPolylineClosed=Ce,v.isWebGLAvailable=ze,v.normalizeCadEntity=ce,v.normalizeDwgDatabase=rr,v.readInputBytes=T,v.resolveCadColor=_,v.resolveCadLinePattern=ue,v.resolveCadLineTypeReference=De,v.summarizeCadDocument=J,v.supportsDwgWorker=ie,Object.defineProperty(v,Symbol.toStringTag,{value:"Module"})});
33
+ `,i=gn(n,n.VERTEX_SHADER,e),s=gn(n,n.FRAGMENT_SHADER,t),r=n.createProgram();if(!r)throw new Error("Failed to create WebGL program.");if(n.attachShader(r,i),n.attachShader(r,s),n.linkProgram(r),!n.getProgramParameter(r,n.LINK_STATUS)){const l=n.getProgramInfoLog(r)??"Unknown WebGL program link error.";throw n.deleteProgram(r),new Error(l)}n.deleteShader(i),n.deleteShader(s);const o=n.getUniformLocation(r,"u_viewCenter"),a=n.getUniformLocation(r,"u_scale"),c=n.getUniformLocation(r,"u_viewport"),h=n.getUniformLocation(r,"u_pointSize");if(!o||!a||!c||!h)throw new Error("Failed to resolve WebGL shader uniforms.");return{program:r,aPosition:n.getAttribLocation(r,"a_position"),aColor:n.getAttribLocation(r,"a_color"),uViewCenter:o,uScale:a,uViewport:c,uPointSize:h}}function gn(n,e,t){const i=n.createShader(e);if(!i)throw new Error("Failed to create WebGL shader.");if(n.shaderSource(i,t),n.compileShader(i),!n.getShaderParameter(i,n.COMPILE_STATUS)){const s=n.getShaderInfoLog(i)??"Unknown WebGL shader compile error.";throw n.deleteShader(i),new Error(s)}return i}function yn(n,e){let t=0;const i=c=>c.map(h=>{const l=bn(n,h.positions),d=bn(n,h.colors),f=h.positions.byteLength+h.colors.byteLength;return t+=f,{positionBuffer:l,colorBuffer:d,vertexCount:h.positions.length/2,primitiveCount:h.primitiveCount,bounds:h.bounds,gpuBytes:f}}),s=i(e.lineBatches),r=i(e.triangleBatches),o=i(e.lineTypePointBatches),a=i(e.pointBatches);return{origin:e.origin,lineBatches:s,triangleBatches:r,lineTypePointBatches:o,pointBatches:a,textItems:e.textItems,imageItems:e.imageItems,stats:e.stats,primitiveCount:e.primitiveCount,gpuMemoryBytes:t,buildElapsedMs:e.buildElapsedMs}}function bn(n,e){const t=n.createBuffer();if(!t)throw new Error("Failed to create WebGL buffer.");return n.bindBuffer(n.ARRAY_BUFFER,t),n.bufferData(n.ARRAY_BUFFER,e,n.STATIC_DRAW),t}function xn(n,e,t){const i=performance.now(),s=R(t)?{x:(t.minX+t.maxX)/2,y:(t.minY+t.maxY)/2}:{x:0,y:0},r=new Cs(n,e,t,s);for(const a of n.entities)r.addEntityTracked(a,0);const o=r.finalize();return o.buildElapsedMs=performance.now()-i,o}class Cs{constructor(e,t,i,s){m(this,"lineBuckets",new Map);m(this,"triangleBuckets",new Map);m(this,"lineTypePointBuckets",new Map);m(this,"pointBuckets",new Map);m(this,"textItems",[]);m(this,"imageItems",[]);m(this,"stats",{total:0,drawn:0,skipped:0,byType:{},unsupported:{},backend:"webgl",primitiveCount:0,visiblePrimitiveCount:0,culledPrimitiveCount:0,gpuMemoryBytes:0,buildElapsedMs:0});m(this,"tileSize");m(this,"maxVerticesPerBatch");m(this,"primitiveCount",0);this.document=e,this.opts=t,this.bounds=i,this.origin=s;const r=R(i)?Math.max(i.maxX-i.minX,i.maxY-i.minY,1e-9):1;this.tileSize=t.enableSpatialIndex?r/Math.max(8,t.spatialIndexCellCount):Number.POSITIVE_INFINITY,this.maxVerticesPerBatch=Math.max(4096,Math.floor(t.maxVerticesPerBatch))}addEntityTracked(e,t){this.stats.total++;const i=String(e.type??"UNKNOWN").toUpperCase();this.stats.byType[i]=(this.stats.byType[i]??0)+1;const s=this.lookupLayer(e.layer);if(e.isVisible===!1||!Qt(s)){this.stats.skipped++;return}this.addEntity(e,i,t)}finalize(){const e=Ae(this.lineBuckets,this.maxVerticesPerBatch),t=Ae(this.triangleBuckets,this.maxVerticesPerBatch),i=Ae(this.lineTypePointBuckets,this.maxVerticesPerBatch),s=Ae(this.pointBuckets,this.maxVerticesPerBatch);return this.stats.primitiveCount=this.primitiveCount,{origin:this.origin,lineBatches:e,triangleBatches:t,lineTypePointBatches:i,pointBatches:s,textItems:this.textItems,imageItems:this.imageItems,stats:this.stats,primitiveCount:this.primitiveCount,buildElapsedMs:0}}addEntity(e,t,i){switch(e.kind??J(t)){case"line":return this.addLineEntity(e);case"circle":return this.addCircleEntity(e);case"arc":return this.addArcEntity(e);case"polyline":return this.addPolylineEntity(e);case"ellipse":return this.addEllipseEntity(e);case"text":return this.addTextEntity(e);case"point":return this.addPointEntity(e);case"insert":return this.addInsertEntity(e,i);case"solid":return this.addSolidEntity(e);case"hatch":return this.addHatchEntity(e);case"spline":return this.addSplineEntity(e);case"path":return this.addPathEntity(e);case"image":return this.addImageEntity(e);case"viewport":return this.markSkipped(t);default:this.stats.unsupported[t]=(this.stats.unsupported[t]??0)+1,this.stats.skipped++,this.opts.showUnsupportedMarkers&&this.addUnsupportedMarker(e)}}addLineEntity(e){if(!b(e.startPoint)||!b(e.endPoint))return this.markSkipped("LINE");this.addPolyline([e.startPoint,e.endPoint],!1,this.strokeBytes(e),e),this.stats.drawn++}addCircleEntity(e){const t=e.center,i=Number(e.radius);if(!b(t)||!Number.isFinite(i))return this.markSkipped("CIRCLE");const s=Math.max(16,Math.min(this.opts.maxCurveSegments,Math.ceil(Math.sqrt(Math.abs(i))*12))),r=he(t,i,0,Math.PI*2,!0,s);this.addPolyline(r,!0,this.strokeBytes(e),e),this.stats.drawn++}addArcEntity(e){const t=e.center,i=Number(e.radius),s=Number(e.startAngle),r=Number(e.endAngle);if(!b(t)||!Number.isFinite(i)||!Number.isFinite(s)||!Number.isFinite(r))return this.markSkipped("ARC");this.addPolyline(he(t,i,s,r,!0,this.opts.maxCurveSegments),!1,this.strokeBytes(e),e),this.stats.drawn++}addPolylineEntity(e){const t=e.vertices??e.points;if(!Array.isArray(t)||t.length<2)return this.markSkipped(String(e.type));const i=De(e),s=[],r=i?t.length:t.length-1;for(let o=0;o<r;o++){const a=t[o],c=t[(o+1)%t.length];if(!b(a)||!b(c))continue;const h=wt(a,c,Number(a.bulge??0),Math.max(4,Math.min(24,this.opts.maxCurveSegments/4)));s.length>0&&h.shift(),s.push(...h)}if(s.length<2)return this.markSkipped(String(e.type));this.addPolyline(s,i,this.strokeBytes(e),e),this.stats.drawn++}addEllipseEntity(e){if(!b(e.center)||!b(e.majorAxisEndPoint))return this.markSkipped("ELLIPSE");const t=We(e.center,e.majorAxisEndPoint,Number(e.axisRatio??1),Number(e.startAngle??0),Number(e.endAngle??Math.PI*2),this.opts.maxCurveSegments),i=Math.abs(Number(e.endAngle??Math.PI*2)-Number(e.startAngle??0))>=Math.PI*2-1e-6;this.addPolyline(t,i,this.strokeBytes(e),e),this.stats.drawn++}addTextEntity(e){const t=Number(e.halign??0),i=Number(e.valign??0),r=(t!==0||i!==0)&&b(e.endPoint)?e.endPoint:e.insertionPoint??e.startPoint??e.center,o=Pt(String(e.text??e.value??"")),a=Number(e.textHeight??e.height??1);if(!b(r)||!o||!Number.isFinite(a))return this.markSkipped(String(e.type));const c=A(r),h=Number(e.xScale??1),l=Number.isFinite(h)&&Math.abs(h)>1e-9?Math.abs(h):1,d=Math.max(1,o.split(/\r?\n/g).reduce((u,p)=>Math.max(u,p.length),0))*Math.abs(a)*.62*l,f=Math.max(1,o.split(/\r?\n/g).length)*Math.abs(a)*1.22;this.textItems.push({point:c,text:o,height:a,rotation:Number(e.rotation??0),xScale:l,generationFlag:Number(e.generationFlag??0),halign:t,valign:i,color:j(e,this.document,this.colorOptions()),opacity:ee(Number(e.opacity??1),0,1),bounds:{minX:c.x-d,minY:c.y-f,maxX:c.x+d,maxY:c.y+f}}),this.stats.drawn++}addPointEntity(e){const t=e.point??e.location??e.center??e.insertionPoint;if(!b(t))return this.markSkipped("POINT");this.addPoint(t,this.strokeBytes(e)),this.stats.drawn++}addInsertEntity(e,t){const i=this.lookupBlock(e.blockName??e.name);if(i&&t<this.opts.maxInsertDepth){const r=qe(e,i.basePoint??{x:0,y:0});for(const o of i.entities){const a=en(o,e,this.document,this.colorOptions()),c=Qe(a,e,this.document);this.addEntityTracked(oe(c,r),t+1)}return}const s=e.insertionPoint;if(!b(s))return this.markSkipped("INSERT");if(this.addPoint(s,this.strokeBytes(e)),Array.isArray(e.attribs))for(const r of e.attribs)this.addTextEntity(r);this.stats.drawn++}addSolidEntity(e){const t=e.vertices??e.points;if(!Array.isArray(t)||t.length<3)return this.markSkipped(String(e.type));const i=t.filter(b).map(A);if(i.length<3)return this.markSkipped(String(e.type));const s=this.fillBytes(e)??this.strokeBytes(e);this.addTriangleFan(i,s),this.addPolyline(i,!0,this.strokeBytes(e),e),this.stats.drawn++}addHatchEntity(e){var o;const t=e.loops;if(!Array.isArray(t)||t.length===0)return this.markSkipped("HATCH");const i=this.strokeBytes(e),s=this.fillBytes(e);let r=!1;for(const a of t){const c=(o=a.commands)!=null&&o.length?vn(a.commands,this.opts.maxCurveSegments):(a.vertices??[]).filter(b).map(A);c.length<2||(this.addPolyline(c,!0,i,e),s&&c.length>=3&&this.addTriangleFan(c,s),r=!0)}if(!r)return this.markSkipped("HATCH");this.stats.drawn++}addSplineEntity(e){var i;const t=(i=e.fitPoints)!=null&&i.length?e.fitPoints:e.controlPoints;if(!t||t.length<2)return this.markSkipped("SPLINE");this.addPolyline(t.filter(b).map(A),!!e.isClosed,this.strokeBytes(e),e),this.stats.drawn++}addPathEntity(e){var s;if(!((s=e.commands)!=null&&s.length))return this.markSkipped(String(e.type));const t=vn(e.commands,this.opts.maxCurveSegments);if(t.length<2)return this.markSkipped(String(e.type));this.addPolyline(t,!1,this.strokeBytes(e),e);const i=this.fillBytes(e);i&&t.length>=3&&this.addTriangleFan(t,i),this.stats.drawn++}addImageEntity(e){const t=e.insertionPoint;if(!b(t))return this.markSkipped(String(e.type));const i=Number(e.width??32),s=Number(e.height??32);if(!Number.isFinite(i)||!Number.isFinite(s))return this.markSkipped(String(e.type));const r=A(t),o=ot([r,{x:r.x+i,y:r.y-s}]);this.imageItems.push({point:r,width:i,height:s,source:e.imageDataUrl??e.imageSource,color:j(e,this.document,this.colorOptions()),opacity:ee(Number(e.opacity??1),0,1),bounds:o}),this.stats.drawn++}addUnsupportedMarker(e){const t=Ns(e);t&&this.addPoint(t,this.strokeBytes(e))}addPolyline(e,t,i,s){const r=e.filter(b).map(A);if(r.length<2||(t&&wn(r[0],r[r.length-1])&&r.pop(),r.length<2))return;const o=s?Be(s):0,a=s?Me(s,this.document):void 0;if(a){const c=Te(r,t,a),h=[...c.dots];for(const[l,d]of c.segments)this.addSegment(l,d,i),o>1e-9&&this.addWideSegment(l,d,o,i,!0);for(const l of c.markers??[]){const d=this.resolveLineTypeGlyph(l);if(!d)continue;Ms(h,l.fallbackPoint);let f=!1;for(const u of tt(l,d))for(let p=0;p<u.length-1;p++)this.addSegment(u[p],u[p+1],i),f=!0;f||h.push(l.point)}for(const l of h)this.addLineTypePoint(l,i);return}for(let c=0;c<r.length-1;c++)this.addSegment(r[c],r[c+1],i);t&&this.addSegment(r[r.length-1],r[0],i),o>1e-9&&this.addWidePolyline(r,t,o,i)}addWidePolyline(e,t,i,s){for(let r=0;r<e.length-1;r++)this.addWideSegment(e[r],e[r+1],i,s,!1);t&&this.addWideSegment(e[e.length-1],e[0],i,s,!1);for(const r of e)this.addWideDisc(r,i/2,s)}addWideSegment(e,t,i,s,r){const o=t.x-e.x,a=t.y-e.y,c=Math.hypot(o,a);if(!Number.isFinite(c)||c<=1e-14)return;const h=Math.abs(i)/2,l=-a/c*h,d=o/c*h;this.addTriangleFan([{x:e.x+l,y:e.y+d},{x:t.x+l,y:t.y+d},{x:t.x-l,y:t.y-d},{x:e.x-l,y:e.y-d}],s),r&&(this.addWideDisc(e,h,s),this.addWideDisc(t,h,s))}addWideDisc(e,t,i){if(!Number.isFinite(t)||t<=1e-9)return;const s=[],r=8;for(let o=0;o<r;o++){const a=o/r*Math.PI*2;s.push({x:e.x+Math.cos(a)*t,y:e.y+Math.sin(a)*t})}this.addTriangleFan([e,...s,s[0]],i)}addSegment(e,t,i){if(!b(e)||!b(t)||Math.hypot(e.x-t.x,e.y-t.y)<=1e-14)return;const s=this.batchFor(this.lineBuckets,ot([e,t]));q(s,e,i,this.origin),q(s,t,i,this.origin),s.primitiveCount++,this.primitiveCount++}addPoint(e,t){const i=this.batchFor(this.pointBuckets,Pn(e));q(i,e,t,this.origin),i.primitiveCount++,this.primitiveCount++}addLineTypePoint(e,t){const i=this.batchFor(this.lineTypePointBuckets,Pn(e));q(i,e,t,this.origin),i.primitiveCount++,this.primitiveCount++}resolveLineTypeGlyph(e){return e.kind==="shape"?this.opts.shxGlyphResolver.resolveShape(Number(e.shapeNumber),e.fontName):this.opts.shxGlyphResolver.resolveText(String(e.text??""),e.fontName)}addTriangleFan(e,t){const i=e.filter(b).map(A);if(i.length<3)return;const s=ot(i),r=this.batchFor(this.triangleBuckets,s);for(let o=1;o<i.length-1;o++)q(r,i[0],t,this.origin),q(r,i[o],t,this.origin),q(r,i[o+1],t,this.origin),r.primitiveCount++,this.primitiveCount++}batchFor(e,t){const i=this.bucketKey(t);let s=e.get(i);return s||(s=Ss(),e.set(i,s)),L(s.bounds,{x:t.minX,y:t.minY}),L(s.bounds,{x:t.maxX,y:t.maxY}),s}bucketKey(e){if(!Number.isFinite(this.tileSize))return"all";const t=(e.minX+e.maxX)/2,i=(e.minY+e.maxY)/2,s=Math.floor((t-this.bounds.minX)/this.tileSize),r=Math.floor((i-this.bounds.minY)/this.tileSize);return`${s}:${r}`}strokeBytes(e){return ct(j(e,this.document,this.colorOptions()),[255,255,255,255],ee(Number(e.opacity??1),0,1))}fillBytes(e){const t=He(e,this.document,this.colorOptions());return t?ct(t,[255,255,255,255],ee(Number(e.opacity??1),0,1)):void 0}colorOptions(){return{foreground:this.opts.foreground,background:this.opts.background,trueColorByteOrder:this.opts.trueColorByteOrder,contrastMode:this.opts.contrastMode,minColorContrast:this.opts.minColorContrast}}markSkipped(e){this.stats.skipped++,this.stats.unsupported[e]=this.stats.unsupported[e]??0}lookupLayer(e){if(e)return this.document.layers[e]??this.document.layers[e.toLowerCase()]??Object.values(this.document.layers).find(t=>t.name.toLowerCase()===e.toLowerCase())}lookupBlock(e){if(e)return this.document.blocks[e]??this.document.blocks[e.toLowerCase()]??Object.values(this.document.blocks).find(t=>t.name.toLowerCase()===e.toLowerCase())}}function Ss(){return{positions:[],colors:[],bounds:z(),primitiveCount:0}}function q(n,e,t,i){n.positions.push(e.x-i.x,e.y-i.y),n.colors.push(t[0],t[1],t[2],t[3])}function Ae(n,e){const t=[];for(const i of n.values()){const s=i.positions.length/2;if(s<=0||!R(i.bounds))continue;if(s<=e){t.push({positions:new Float32Array(i.positions),colors:new Uint8Array(i.colors),bounds:{...i.bounds},primitiveCount:i.primitiveCount});continue}const r=ks(i),o=Math.max(r,Math.floor(e/r)*r);for(let a=0;a<s;a+=o){const c=Math.min(s,a+o),h=i.positions.slice(a*2,c*2),l=i.colors.slice(a*4,c*4),d=z();for(let f=0;f<h.length;f+=2)L(d,{x:h[f],y:h[f+1]});t.push({positions:new Float32Array(h),colors:new Uint8Array(l),bounds:{...i.bounds},primitiveCount:Math.floor((c-a)/r)})}}return t}function ks(n){const e=n.positions.length/2;return e===n.primitiveCount?1:e===n.primitiveCount*3?3:2}function vn(n,e){const t=[];let i,s;const r=o=>{(!t.length||Math.hypot(t[t.length-1].x-o.x,t[t.length-1].y-o.y)>1e-12)&&t.push(A(o)),i=A(o)};for(const o of n)if(o.cmd==="M")i=A(o.points[0]),s=i,r(i);else if(o.cmd==="L")r(o.points[0]);else if(o.cmd==="Q"&&i&&o.points.length>=2){const a=i,[c,h]=o.points,l=Math.max(4,Math.min(e,24));for(let d=1;d<=l;d++){const f=d/l,u=1-f;r({x:u*u*a.x+2*u*f*c.x+f*f*h.x,y:u*u*a.y+2*u*f*c.y+f*f*h.y})}}else if(o.cmd==="C"&&i&&o.points.length>=3){const a=i,[c,h,l]=o.points,d=Math.max(6,Math.min(e,32));for(let f=1;f<=d;f++){const u=f/d,p=1-u;r({x:p**3*a.x+3*p*p*u*c.x+3*p*u*u*h.x+u**3*l.x,y:p**3*a.y+3*p*p*u*c.y+3*p*u*u*h.y+u**3*l.y})}}else o.cmd==="Z"&&s&&r(s);return t}function Ns(n){for(const e of["startPoint","insertionPoint","center","point","location"]){const t=n[e];if(b(t))return A(t)}if(Array.isArray(n.vertices)&&b(n.vertices[0]))return A(n.vertices[0]);if(Array.isArray(n.commands)&&n.commands.length){const e=n.commands.find(t=>t.points.length>0);if(e)return A(e.points[0])}}function ot(n){const e=z();for(const t of n)L(e,t);return e}function wn(n,e){const t=Math.max(1,Math.abs(n.x),Math.abs(n.y),Math.abs(e.x),Math.abs(e.y));return Math.hypot(n.x-e.x,n.y-e.y)<=Math.max(1e-9,t*1e-12)}function Ms(n,e){const t=n.findIndex(i=>wn(i,e));t>=0&&n.splice(t,1)}function Pn(n){return{minX:n.x,minY:n.y,maxX:n.x,maxY:n.y}}function at(n,e){return n.minX<=e.maxX&&n.maxX>=e.minX&&n.minY<=e.maxY&&n.maxY>=e.minY}function Ts(n,e){return e.trueColorByteOrder!==void 0&&e.trueColorByteOrder!==n.trueColorByteOrder||e.contrastMode!==void 0&&e.contrastMode!==n.contrastMode||e.minColorContrast!==void 0&&e.minColorContrast!==n.minColorContrast||e.foreground!==void 0&&e.foreground!==n.foreground||e.background!==void 0&&e.background!==n.background||e.maxInsertDepth!==void 0&&e.maxInsertDepth!==n.maxInsertDepth||e.maxCurveSegments!==void 0&&e.maxCurveSegments!==n.maxCurveSegments||e.spatialIndexCellCount!==void 0&&e.spatialIndexCellCount!==n.spatialIndexCellCount||e.maxVerticesPerBatch!==void 0&&e.maxVerticesPerBatch!==n.maxVerticesPerBatch||e.enableSpatialIndex!==void 0&&e.enableSpatialIndex!==n.enableSpatialIndex||e.shxGlyphResolver!==void 0&&e.shxGlyphResolver!==n.shxGlyphResolver}function Cn(n,e){return{...n.stats,renderElapsedMs:e,backend:"webgl",primitiveCount:n.primitiveCount,visiblePrimitiveCount:0,culledPrimitiveCount:0,gpuMemoryBytes:n.gpuMemoryBytes,buildElapsedMs:n.buildElapsedMs}}function Es(n){return{total:n.total,drawn:n.drawn,skipped:n.skipped,byType:{...n.byType},unsupported:{...n.unsupported},renderElapsedMs:n.renderElapsedMs,backend:n.backend,primitiveCount:n.primitiveCount,visiblePrimitiveCount:n.visiblePrimitiveCount,culledPrimitiveCount:n.culledPrimitiveCount,gpuMemoryBytes:n.gpuMemoryBytes,buildElapsedMs:n.buildElapsedMs}}function ct(n,e,t=1){const i=n.trim().toLowerCase();let s;if(/^#[0-9a-f]{3}$/i.test(i))s=[parseInt(i[1]+i[1],16),parseInt(i[2]+i[2],16),parseInt(i[3]+i[3],16),255];else if(/^#[0-9a-f]{6}$/i.test(i))s=[parseInt(i.slice(1,3),16),parseInt(i.slice(3,5),16),parseInt(i.slice(5,7),16),255];else{const o=i.match(/^rgba?\(([^)]+)\)$/i);if(o){const a=o[1].split(/[\s,\/]+/).filter(Boolean),c=a.slice(0,3).some(l=>l.includes("%")),h=a.map(l=>Number(l.replace("%","")));h.length>=3&&h.slice(0,3).every(Number.isFinite)&&(s=[me(c?h[0]*2.55:h[0]),me(c?h[1]*2.55:h[1]),me(c?h[2]*2.55:h[2]),me((Number.isFinite(h[3])?h[3]:1)*255)])}}const r=s??e;return[r[0],r[1],r[2],me(r[3]*t)]}function me(n){return Math.max(0,Math.min(255,Math.round(n)))}class Sn{constructor(e={}){m(this,"canvas");m(this,"renderer");m(this,"registry");m(this,"nativeHost");m(this,"options");m(this,"referenceRegistry",new Gt);m(this,"shxGlyphResolver");m(this,"externalShxGlyphResolver");m(this,"lastResult");m(this,"activeNativeLoader");var t,i;if(this.options={autoFit:!0,...e},this.externalShxGlyphResolver=(t=e.canvasOptions)==null?void 0:t.shxGlyphResolver,this.shxGlyphResolver={resolveShape:(s,r)=>{var o;return this.referenceRegistry.resolveShape(s,r)??((o=this.externalShxGlyphResolver)==null?void 0:o.resolveShape(s,r))},resolveText:(s,r)=>{var o;return this.referenceRegistry.resolveText(s,r)??((o=this.externalShxGlyphResolver)==null?void 0:o.resolveText(s,r))}},this.registry=e.registry??Dt(e),e.loaders)for(const s of e.loaders)this.registry.register(s);if(this.canvas=e.canvas??document.createElement("canvas"),this.canvas.classList.add("cad-viewer-canvas"),e.container)e.container.classList.add("cad-viewer-container"),e.canvas||(this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.display="block",e.container.appendChild(this.canvas)),this.nativeHost=e.nativeHost??document.createElement("div"),this.nativeHost.classList.add("cad-viewer-native-host"),e.nativeHost||e.container.appendChild(this.nativeHost);else if(e.nativeHost)this.nativeHost=e.nativeHost,this.nativeHost.classList.add("cad-viewer-native-host");else if((i=e.canvas)!=null&&i.parentElement){e.canvas.parentElement.classList.add("cad-viewer-container");const s=document.createElement("div");s.classList.add("cad-viewer-native-host"),e.canvas.parentElement.appendChild(s),this.nativeHost=s}this.renderer=Is(e.renderer??"auto",this.canvas,{...e.canvasOptions,shxGlyphResolver:this.shxGlyphResolver}),this.renderer.onStats=s=>{var r,o;return(o=(r=this.options).onRenderStats)==null?void 0:o.call(r,s)},this.renderer.onViewChange=s=>{var r,o;return(o=(r=this.options).onViewChange)==null?void 0:o.call(r,s)}}registerLoader(e){return this.registry.register(e),this}async loadFile(e,t={}){var i,s;return(s=(i=this.options).onLoadStart)==null||s.call(i,e),this.loadThroughRegistry({file:e,fileName:e.name},t,e.name)}async loadBuffer(e,t,i={}){var s,r;return(r=(s=this.options).onLoadStart)==null||r.call(s,e),this.loadThroughRegistry({buffer:e,fileName:t},i,t)}async load(e,t={}){var i,s,r;return(s=(i=this.options).onLoadStart)==null||s.call(i,e),this.loadThroughRegistry(e,t,e.fileName??((r=e.file)==null?void 0:r.name))}async addReference(e){var t,i;try{const s=await this.referenceRegistry.add(e);return this.refreshCurrentReferences(),s}catch(s){const r=kn(s);throw(i=(t=this.options).onError)==null||i.call(t,r),r}}async addReferenceFile(e){return this.addReference({file:e,fileName:e.name})}async addReferenceBuffer(e,t){return this.addReference({buffer:e,fileName:t})}removeReference(e){const t=this.referenceRegistry.remove(e);return t&&this.refreshCurrentReferences(),t}clearReferences(){this.referenceRegistry.clear(),this.refreshCurrentReferences()}getReferenceState(){return this.referenceRegistry.getState()}getMissingReferences(){return this.getReferenceState().missing}getLoadedReferences(){return this.getReferenceState().loaded}setDocument(e,t){var s,r;this.deactivateNativeRenderer(),this.activateDocumentReferences(e);const i={document:e,raw:e.raw,bytes:0,elapsedMs:0,format:e.format,warnings:e.warnings,summary:Q(e),fileName:t};return this.renderer.setDocument(e),this.options.autoFit||this.renderer.render(),this.lastResult=i,(r=(s=this.options).onLoad)==null||r.call(s,i),i}fit(e){var t,i;this.activeNativeLoader?(i=(t=this.activeNativeLoader).fit)==null||i.call(t):this.renderer.fitToView(.92,e)}zoomIn(){var e,t;this.activeNativeLoader?(t=(e=this.activeNativeLoader).zoomIn)==null||t.call(e):this.renderer.zoomIn()}zoomOut(){var e,t;this.activeNativeLoader?(t=(e=this.activeNativeLoader).zoomOut)==null||t.call(e):this.renderer.zoomOut()}resize(){var e,t;this.activeNativeLoader?(t=(e=this.activeNativeLoader).resize)==null||t.call(e):this.renderer.resize()}setCanvasOptions(e){var t,i;this.options.canvasOptions={...this.options.canvasOptions??{},...e},e.shxGlyphResolver&&(this.externalShxGlyphResolver=e.shxGlyphResolver),this.renderer.setOptions({...e,shxGlyphResolver:this.shxGlyphResolver}),this.activeNativeLoader&&((i=(t=this.activeNativeLoader).setNativeOptions)==null||i.call(t,{...this.mergeLoadOptions({}),dwfBackground:e.background??this.options.dwfBackground}))}async preloadDwg(e={}){const t=this.registry.list().find(i=>i.id==="dwg");if(!(t!=null&&t.preload))throw new Error("The registered DWG loader does not support preload().");return t.preload(this.mergeLoadOptions(e))}clear(){this.lastResult=void 0,this.deactivateNativeRenderer(),this.renderer.clear(),this.referenceRegistry.setDocument(void 0),this.emitReferenceState()}destroy(){var e,t,i;this.deactivateNativeRenderer();for(const s of this.registry.list()){const r=s;(e=r.terminateWorker)==null||e.call(r),(t=r.unmount)==null||t.call(r),(i=r.destroy)==null||i.call(r)}this.referenceRegistry.clear(),this.renderer.destroy()}getLoadResult(){return this.lastResult}getDocument(){var e;return this.activeNativeLoader?(e=this.lastResult)==null?void 0:e.document:this.renderer.getDocument()}getSourceDocument(){var e;return this.activeNativeLoader?(e=this.lastResult)==null?void 0:e.document:this.renderer.getSourceDocument()}getZoomPercent(){return this.activeNativeLoader?100:this.renderer.getZoomPercent()}isNativeRendererActive(){return!!this.activeNativeLoader}async loadThroughRegistry(e,t,i){var s,r;try{const o=this.mergeLoadOptions(t);ht(o.signal);const a=await this.registry.detect(e),c={...e,buffer:a.bytes};if(Kt(a.loader))return await this.applyNativeLoadResult(a.loader,c,o,i);const h=await a.loader.load(c,o);return this.applyLoadResult(h,i)}catch(o){const a=kn(o);throw(r=(s=this.options).onError)==null||r.call(s,a),a}}applyLoadResult(e,t){var s,r,o,a;this.deactivateNativeRenderer(),(r=(s=this.options).onLoadProgress)==null||r.call(s,{phase:"render",format:e.format,message:"Rendering normalized CAD scene…",percent:96}),this.activateDocumentReferences(e.document),e.warnings=e.document.warnings,this.renderer.setDocument(e.document),this.options.autoFit||this.renderer.render();const i={...e,fileName:t,summary:Q(e.document)};return this.lastResult=i,(a=(o=this.options).onLoad)==null||a.call(o,i),i}async applyNativeLoadResult(e,t,i,s){var r,o,a;if(!this.nativeHost)throw new Error("Native DWF rendering requires CadViewerOptions.container, nativeHost, or a canvas parent element.");ht(i.signal),this.renderer.clear(),(r=this.activeNativeLoader)==null||r.unmount(),this.activeNativeLoader=e,this.canvas.style.display="none",this.nativeHost.classList.add("is-active");try{const c=await e.mount(t,this.nativeHost,i);ht(i.signal),this.activateDocumentReferences(c.document),c.warnings=c.document.warnings;const h={...c,fileName:s,summary:Q(c.document)};return this.lastResult=h,this.emitNativeRenderStats(c),(a=(o=this.options).onLoad)==null||a.call(o,h),h}catch(c){throw this.deactivateNativeRenderer(),c}}deactivateNativeRenderer(){var e,t;if(!this.activeNativeLoader&&!((e=this.nativeHost)!=null&&e.classList.contains("is-active"))){this.canvas.style.display="";return}(t=this.activeNativeLoader)==null||t.unmount(),this.activeNativeLoader=void 0,this.nativeHost&&(this.nativeHost.classList.remove("is-active"),this.nativeHost.replaceChildren()),this.canvas.style.display=""}emitNativeRenderStats(e){var o,a,c,h;const t=e.document.metadata,i=Number(((o=t.nativeRenderStats)==null?void 0:o.commands)??e.document.entities.length??0),r=String(((a=t.nativeRenderStats)==null?void 0:a.backend)??"webgl").includes("webgl")?"webgl":"canvas2d";(h=(c=this.options).onRenderStats)==null||h.call(c,{total:i,drawn:i,skipped:0,byType:Q(e.document).byType,unsupported:{},renderElapsedMs:e.elapsedMs,backend:r,primitiveCount:i,visiblePrimitiveCount:i,culledPrimitiveCount:0,gpuMemoryBytes:void 0,buildElapsedMs:e.elapsedMs})}mergeLoadOptions(e){const t=this.options.onProgress,i=e.onProgress;return{...this.options,...e,onProgress:s=>{var r,o;(o=(r=this.options).onLoadProgress)==null||o.call(r,s),t==null||t(s),i&&i!==t&&i(s)}}}activateDocumentReferences(e){this.referenceRegistry.setDocument(e),jt(e,this.referenceRegistry.getState()),this.emitReferenceState()}refreshCurrentReferences(){var t;const e=(t=this.lastResult)==null?void 0:t.document;e&&(this.referenceRegistry.setDocument(e),jt(e,this.referenceRegistry.getState()),this.lastResult.warnings=e.warnings,this.lastResult.summary=Q(e),this.activeNativeLoader||this.renderer.refreshReferences()),this.emitReferenceState()}emitReferenceState(){var e,t;(t=(e=this.options).onReferenceStateChange)==null||t.call(e,this.referenceRegistry.getState())}}function As(n={}){return new Sn(n)}function kn(n){return n instanceof Error?n:new Error(String(n))}function ht(n){if(n!=null&&n.aborted)throw new DOMException("Loading cancelled.","AbortError")}function Is(n,e,t={}){if(n==="canvas2d")return new it(e,t);if(n==="webgl")return new st(e,t);if(rt())try{return new st(e,t)}catch{}return new it(e,t)}function Ls(n,e,t,i={}){const s=n&&typeof n=="object"?n:{},r=Os(s,i),o=Ds(s),a=Ws(s,i,o),c=_s(s,i),h=Rs(s.header,t),l=Fs(a),d=Ys(s,h),f=d.view,u=Array.isArray(s.entities)?s.entities:[],p={keepRaw:!!i.keepRaw,includeUnknownProperties:!!i.keepRaw},w=u.filter(v=>!!v&&typeof v=="object").map(v=>Nn(v,p)),P=xe({format:"dwg",sourceName:e,header:h,layers:r,lineTypes:a,blocks:c,entities:w,savedView:f,metadata:{parser:"@mlightcad/libredwg-web",parserMode:"wasm",version:t,savedView:f,requiredShxFonts:l},warnings:d.warning?[d.warning]:[],raw:i.keepRaw?n:void 0});if(w.length===0&&P.warnings.push("DWG parsed successfully but no model-space entities were exposed by the converter. Check layout/paper-space content or unsupported proxy objects."),[...new Set(Object.values(a))].some(v=>v.pattern.some(C=>Number(C.elementTypeFlag??0)!==0))){const v=l.length>0?` This drawing references external shape font${l.length===1?"":"s"} ${l.join(", ")}, whose outlines are not embedded in the DWG.`:"";P.warnings.push(`Complex SHX linetype glyphs are preserved in the normalized LTYPE definition and rendered as a dash/dot approximation.${v}`)}return P}function Fs(n){const e=new Set;for(const t of new Set(Object.values(n)))for(const i of t.pattern)Number(i.elementTypeFlag??0)!==0&&i.fontName&&e.add(i.fontName);return[...e].sort((t,i)=>t.localeCompare(i))}function Ds(n){const e=n.tables,t=[n.STYLE,n.styles,e==null?void 0:e.STYLE,e==null?void 0:e.styles],i=new Map,s=new Set;for(const r of t)for(const o of pe(r)){if(!o||typeof o!="object")continue;const a=o,c=M(a.font??a.fontFileName??a.primaryFontFileName);if(!c||!/\.shx$/i.test(c))continue;((y(a.standardFlag??a.flag)??0)&1)===1&&s.add(c);for(const l of[a.handle,a.id,a.name]){const d=Mn(l);d&&i.set(d,c)}}return{byReference:i,shapeFonts:[...s]}}function Nn(n,e){const t=ve(n,void 0,{...e,numericColorMode:"rgb"}),i=y(n.color);i!==void 0&&i>=0&&i<=16777215&&(t.color=i,t.trueColor=i),t.colorIndex=y(n.colorIndex??n.colorNumber??n.aci)??t.colorIndex,t.colorName=M(n.colorName??n.color_name)??t.colorName;const s=y(n.flag??n.flags);s!==void 0&&(t.flag=s);const r=String(n.type??n.entityType??"").toUpperCase(),o=/^(POLYLINE|POLYLINE_2D|POLYLINE2D|POLYLINE_3D|POLYLINE3D)$/.test(r);return(n.isClosed===!0||n.closed===!0||o&&(Number(s??0)&1)===1||r==="LWPOLYLINE"&&(Number(s??0)&512)===512)&&(t.isClosed=!0),t}function Bs(n){return typeof n=="number"&&Number.isFinite(n)&&Math.abs(Math.trunc(n))>=1&&Math.abs(Math.trunc(n))<=255}function Rs(n,e){const t=n&&typeof n=="object"?{...n}:{};return e&&(t.dwgVersion=e),t}function Os(n,e){const t={},i=[],s=n.tables;for(const r of["LAYER","layer","layers"]){const o=n[r]??(s==null?void 0:s[r]);o&&i.push(o)}for(const r of i)for(const o of pe(r)){const a=o,c=M(a.name??a.layerName??a.entryName);if(!c)continue;const h=y(a.colorIndex??a.colorNumber),l=y(a.trueColor??a.true_color??a.truecolor??a.colorRGB??a.colorRgb??a.rgbColor??a.rgb),d=y(a.color),f=Bs(h),u=l??(!f&&d!==void 0&&d>=0&&d<=16777215?d:void 0),p={name:c,color:f?void 0:a.color??a.colorName,colorIndex:h??(d!==void 0&&Math.abs(d)<=257?d:void 0),trueColor:u,lineType:M(a.lineType??a.linetype),lineweight:y(a.lineweight??a.lineWeight),isVisible:!(a.isVisible===!1||a.off===!0||Number(h??a.color??1)<0),isFrozen:!!(a.isFrozen??a.frozen),isLocked:!!(a.isLocked??a.locked),raw:e.keepRaw?a:void 0};Re(t,p)}return t}function Ws(n,e,t){const i={},s=n.tables,r=[n.LTYPE,n.ltype,n.lineTypes,s==null?void 0:s.LTYPE,s==null?void 0:s.ltype,s==null?void 0:s.lineTypes];for(const o of r)for(const a of pe(o)){const c=a,h=M(c.name??c.lineTypeName??c.entryName);if(!h)continue;const d=(Array.isArray(c.pattern)?c.pattern:Array.isArray(c.dashes)?c.dashes:[]).flatMap(f=>{if(typeof f=="number")return[{length:f}];if(!f||typeof f!="object")return[];const u=f,p=y(u.elementLength??u.length??u.dashLength);if(p===void 0)return[];const w=y(u.elementTypeFlag),P=y(u.shapeNumber),g=w!==void 0&&P!==void 0,v=g?P:y(u.typeFlag??u.elementTypeFlag),C=M(u.styleObjectId??u.styleHandle??u.style),S=(C?t.byReference.get(Mn(C)):void 0)??((Number(v??0)&4)===4&&t.shapeFonts.length===1?t.shapeFonts[0]:void 0);return[{length:p,elementTypeFlag:v,shapeNumber:g?w:y(u.shapeCode??u.shapeNumber),scale:y(u.scale),rotation:y(u.rotation),offsetX:y(u.offsetX),offsetY:y(u.offsetY),text:M(u.text),styleHandle:C,fontName:S}]});On(i,{name:h,handle:M(c.handle??c.id),description:M(c.description),totalPatternLength:y(c.totalPatternLength??c.patternLength),pattern:d,raw:e.keepRaw?c:void 0})}return i}function Mn(n){return String(n??"").trim().replace(/^0x/i,"").replace(/^0+(?=[0-9a-f])/i,"").toLowerCase()}function Ys(n,e){const t=n.tables,s=pe(n.VPORT??n.vports??(t==null?void 0:t.VPORT)??(t==null?void 0:t.vports)).filter(g=>!!g&&typeof g=="object").find(g=>String(g.name??"").trim().toLowerCase()==="*active"),r=s?"vport":"header-ucs",o=s??e,a=E(o.ucsOrigin??o.UCSORG??e.UCSORG),c=E(o.ucsXAxis??o.UCSXDIR??e.UCSXDIR),h=E(o.ucsYAxis??o.UCSYDIR??e.UCSYDIR),l=y(o.viewTwistAngle??o.twistAngle??o.VIEWTWIST)??0,d=E(o.viewDirectionFromTarget??o.viewDirection??o.direction??o.VIEWDIR),f=!Us(a,c,h);if(!(!!s||!!d||f||Math.abs(l)>1e-12))return{};const p=zs(d),w=p?Xs(a,c,h,l):{a:1,b:0,c:0,d:1,e:0,f:0},P={source:r,name:M(o.name),handle:M(o.handle),center:E(o.center??o.VIEWCTR),target:E(o.viewTarget??o.target??o.TARGET),direction:d,viewHeight:y(o.viewHeight??o.height??o.VIEWSIZE),aspectRatio:y(o.aspectRatio),twistAngle:l,ucsOrigin:a,ucsXAxis:c,ucsYAxis:h,sceneTransformApplied:p,sceneTransform:w};return p?{view:P}:{view:P,warning:"The saved CAD view has a missing, non-finite, or tilted VIEWDIR. File Viewer kept world coordinates instead of applying an unsafe 2D UCS/PLAN rotation."}}function Xs(n,e,t,i){const s=lt(e)??{x:1,y:0},r=lt(t)??{x:-s.y,y:s.x},o=s.x*r.x+s.y*r.y,a=lt({x:r.x-s.x*o,y:r.y-s.y*o})??{x:-s.y,y:s.x},c={a:s.x,b:a.x,c:s.y,d:a.y,e:n?-(n.x*s.x+n.y*s.y):0,f:n?-(n.x*a.x+n.y*a.y):0};return Ne(on(Number.isFinite(i)?i:0),c)}function lt(n){if(!n||Math.abs(Number(n.z??0))>1e-6)return;const e=Math.hypot(n.x,n.y);if(!(!Number.isFinite(e)||e<1e-12))return{x:n.x/e,y:n.y/e}}function zs(n){if(!n||!Number.isFinite(n.x)||!Number.isFinite(n.y)||!Number.isFinite(n.z))return!1;const e=Math.hypot(n.x,n.y,Number(n.z));return!Number.isFinite(e)||e<1e-12?!1:Math.hypot(n.x,n.y)/e<=1e-4&&Math.abs(Number(n.z))/e>=1-1e-8}function Us(n,e,t){const i=(a,c)=>Number.isFinite(a)&&Math.abs(Number(a)-c)<=1e-10,s=!n||i(n.x,0)&&i(n.y,0)&&i(n.z??0,0),r=!e||i(e.x,1)&&i(e.y,0)&&i(e.z??0,0),o=!t||i(t.x,0)&&i(t.y,1)&&i(t.z??0,0);return s&&r&&o}function _s(n,e){const t={},i=[n.blocks,n.blockHeaders,n.block_records,n.blockRecords],s=n.tables;i.push(s==null?void 0:s.BLOCK,s==null?void 0:s.BLOCK_RECORD,s==null?void 0:s.blocks);const r={keepRaw:!!e.keepRaw,includeUnknownProperties:!!e.keepRaw};for(const o of i)for(const a of pe(o)){const c=a,h=M(c.name??c.blockName??c.name2);if(!h)continue;const d=(Array.isArray(c.entities)?c.entities:Array.isArray(c.ownedObjects)?c.ownedObjects:[]).filter(f=>!!f&&typeof f=="object").map(f=>Nn(f,r));bt(t,{name:h,basePoint:E(c.basePoint??c.origin)??{x:0,y:0},entities:d,raw:e.keepRaw?c:void 0})}return t}function pe(n){if(!n)return[];if(Array.isArray(n))return n;if(typeof n!="object")return[];const e=n,t=Object.values(e).filter(s=>s&&typeof s=="object"),i=["entries","records","items","values","layers","blocks"].flatMap(s=>Array.isArray(e[s])?e[s]:[]);return i.length>0?i:t}x.CadCanvasRenderer=it,x.CadLoaderRegistry=ft,x.CadShxFontRegistry=Gt,x.CadViewer=Sn,x.CadWebGLRenderer=st,x.DwfLoader=Tt,x.DwgLoader=yt,x.DwgWorkerClient=ut,x.DxfLoader=Ct,x.applyByBlockLineTypeInheritance=Qe,x.cadEntityWorldStrokeWidth=Be,x.colorFromAci=_,x.colorFromTrueColor=ie,x.computeCadDocumentBounds=Ze,x.createCadDocument=xe,x.createCadSceneDocument=nt,x.createCadViewer=As,x.createDashedCadPrimitives=Te,x.createDashedCadSegments=ls,x.createDefaultLoaderRegistry=Dt,x.detectCadFormat=$,x.inferEntityKind=J,x.isCadNativeRenderableLoader=Kt,x.isCadPolylineClosed=De,x.isWebGLAvailable=rt,x.normalizeCadEntity=ve,x.normalizeDwgDatabase=Ls,x.readInputBytes=X,x.resolveCadColor=j,x.resolveCadFitBounds=Ke,x.resolveCadLinePattern=Me,x.resolveCadLineTypeReference=et,x.resolveCadSavedViewBounds=hn,x.summarizeCadDocument=Q,x.supportsDwgWorker=ge,x.transformCadLineTypeGlyph=tt,Object.defineProperty(x,Symbol.toStringTag,{value:"Module"})});
34
34
  //# sourceMappingURL=cad-viewer.umd.cjs.map