@selvajs/compute 3.1.0-beta.14 → 3.1.0-beta.16

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.
@@ -0,0 +1,120 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkH3FZW6OXcjs = require('./chunk-H3FZW6OX.cjs');var zn={};_chunkH3FZW6OXcjs.a.call(void 0, zn,{CONCRETE_MATERIAL:()=>xt,EMISSIVE_MATERIAL:()=>Tt,GLASS_MATERIAL:()=>wt,METAL_MATERIAL:()=>Rt,PLASTIC_MATERIAL:()=>vt,RUBBER_MATERIAL:()=>Mt,SHARED_MATERIALS:()=>Ye,WOOD_MATERIAL:()=>Ht});var _three = require('three'); var z = _interopRequireWildcard(_three); var oe = _interopRequireWildcard(_three); var $ = _interopRequireWildcard(_three); var Ee = _interopRequireWildcard(_three); var W = _interopRequireWildcard(_three); var J = _interopRequireWildcard(_three); var Z = _interopRequireWildcard(_three); var N = _interopRequireWildcard(_three); var Zt = _interopRequireWildcard(_three); var U = _interopRequireWildcard(_three); var Ge = _interopRequireWildcard(_three); var w = _interopRequireWildcard(_three); var Ae = _interopRequireWildcard(_three); var Q = _interopRequireWildcard(_three); var V = _interopRequireWildcard(_three);var Tt=new z.MeshPhysicalMaterial({color:0,emissive:new z.Color(16777215),emissiveIntensity:5,metalness:0,roughness:.2,clearcoat:.3,clearcoatRoughness:.2,depthWrite:!0,depthTest:!0,transparent:!1,alphaTest:0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1,side:z.FrontSide,dithering:!0}),Rt=new z.MeshPhysicalMaterial({color:new z.Color(0),metalness:.9,roughness:.3,envMapIntensity:1.2,clearcoat:.3,clearcoatRoughness:.2,reflectivity:1,ior:2.5,thickness:1,depthWrite:!0,transparent:!1,alphaTest:0,depthTest:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1,side:z.FrontSide,dithering:!0}),xt=new z.MeshPhysicalMaterial({color:new z.Color(13421772),metalness:0,roughness:.92,envMapIntensity:.15,clearcoat:.05,clearcoatRoughness:.9,reflectivity:.15,transmission:0,ior:1.45,thickness:0,depthWrite:!0,transparent:!1,alphaTest:0,depthTest:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1,side:z.FrontSide,dithering:!0}),vt=new z.MeshPhysicalMaterial({color:new z.Color(16777215),metalness:0,roughness:.3,envMapIntensity:.5,clearcoat:.5,clearcoatRoughness:.1,reflectivity:.5,ior:1.4,transmission:0,transparent:!1,depthWrite:!0,side:z.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),wt=new z.MeshPhysicalMaterial({color:new z.Color(16777215),metalness:0,roughness:0,transmission:.95,transparent:!0,depthWrite:!1,envMapIntensity:1,clearcoat:1,clearcoatRoughness:0,ior:1.52,reflectivity:.9,thickness:1,side:z.DoubleSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Mt=new z.MeshPhysicalMaterial({color:new z.Color(1710618),metalness:0,roughness:.9,envMapIntensity:.2,clearcoat:.1,clearcoatRoughness:.8,reflectivity:.2,ior:1.3,transmission:0,depthWrite:!0,side:z.FrontSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Ht=new z.MeshPhysicalMaterial({color:new z.Color(8934707),metalness:0,roughness:.7,envMapIntensity:.3,clearcoat:.3,clearcoatRoughness:.4,reflectivity:.3,ior:1.3,transmission:0,depthWrite:!0,side:z.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Ye=new Set([Tt,Rt,xt,vt,wt,Mt,Ht]);function we(e){let n=e.clone().normalize(),t=new oe.Vector3(0,0,1),r=new oe.Vector3(0,1,0),a=Math.abs(n.dot(t))>.9?r:t,o=new oe.Vector3().crossVectors(a,n).normalize(),i=new oe.Vector3().crossVectors(n,o).normalize();return{up:n,forward:i,right:o}}function Oe(e,n){let{forward:t,right:r,up:a}=we(e);return t.clone().multiplyScalar(-1).add(r.clone().multiplyScalar(-1)).add(a).normalize().multiplyScalar(n)}function Ct(e,n,t){let{forward:r,right:a,up:o}=we(e);return a.clone().multiplyScalar(n).add(r.clone().multiplyScalar(n)).add(o.clone().multiplyScalar(t))}function At(e){let n=e.clone().normalize(),t=new oe.Vector3(0,1,0);if(n.dot(t)>.9999)return new oe.Euler;if(n.dot(t)<-.9999)return new oe.Euler(Math.PI,0,0);let r=new oe.Quaternion().setFromUnitVectors(t,n);return new oe.Euler().setFromQuaternion(r)}function Xe(e){let n=Math.abs(e.x),t=Math.abs(e.y),r=Math.abs(e.z);return n>=t&&n>=r?"x":t>=r?"y":"z"}var se={HUGE_THRESHOLD:1e4,LARGE_THRESHOLD:1e3,SCALE_RATIO_THRESHOLD:100,NEAR_PLANE_FACTOR:{TINY:1e-4,SMALL:.001,NORMAL:.01},FAR_PLANE_FACTOR:{HUGE:100,LARGE:50,NORMAL:20},INITIAL_DISTANCE_MULTIPLIER:4};function La(e,n,t,r,a){if(Wn(e),n.length===0)return;n.forEach(u=>{e.add(u)});let o=Ke(n),i=o.getCenter(new $.Vector3),l=o.getSize(new $.Vector3),s=Math.max(l.x,l.y,l.z);if(s/Math.min(l.x||1,l.y||1,l.z||1)>se.SCALE_RATIO_THRESHOLD||s>se.HUGE_THRESHOLD?(t.near=s*se.NEAR_PLANE_FACTOR.TINY,t.far=s*se.FAR_PLANE_FACTOR.HUGE):s>se.LARGE_THRESHOLD?(t.near=s*se.NEAR_PLANE_FACTOR.SMALL,t.far=s*se.FAR_PLANE_FACTOR.LARGE):(t.near=Math.max(.01,s*se.NEAR_PLANE_FACTOR.NORMAL),t.far=Math.max(2e3,s*se.FAR_PLANE_FACTOR.NORMAL)),t.updateProjectionMatrix(),!a){let u=s*se.INITIAL_DISTANCE_MULTIPLIER;t.position.copy(i).add(Oe(t.up,u)),r.target.copy(i),r.update()}}function St(e){if(!e||typeof e!="string")return _chunkH3FZW6OXcjs.e.call(void 0, ).warn(`Invalid color input: ${e}, using white`),new $.Color(16777215);let n=e.trim();if(/^#?[0-9A-Fa-f]{6}$/.test(n))try{let r=n.startsWith("#")?n:`#${n}`;return new $.Color(r)}catch (e2){return _chunkH3FZW6OXcjs.e.call(void 0, ).warn(`Invalid hex color: ${e}, using white`),new $.Color(16777215)}if(n.includes(",")){let r=n.split(",").map(a=>parseInt(a.trim(),10));if(r.length===3&&r.every(a=>!isNaN(a)&&a>=0&&a<=255))return new $.Color(r[0]/255,r[1]/255,r[2]/255)}let t=n.toLowerCase();return t in $.Color.NAMES?new $.Color($.Color.NAMES[t]):(_chunkH3FZW6OXcjs.e.call(void 0, ).warn(`Invalid color string: ${e}, using white`),new $.Color(16777215))}function Dt(e,n,t="z"){e.forEach(r=>{r.position[t]-=n})}function Ke(e){let n=new $.Box3;return e.length===0||e.forEach(t=>{t.updateMatrixWorld(!0);let r=new $.Box3().setFromObject(t);n.union(r)}),n}var Gn=new Set(["grid","floor","label-layer","measure"]);function Nn(e){let n=e;for(;n;){if(typeof n.userData.id=="string"&&Gn.has(n.userData.id))return!0;n=n.parent}return!1}function ce(e){e.updateMatrixWorld(!0);let n=new $.Box3;return e.traverse(t=>{let r=t;t.visible&&!Nn(t)&&r.geometry&&n.expandByObject(t)}),n}var jn=new Set(["floor","grid","label-layer"]),Ie="selvaGeometryCache";function Wn(e){[...e.children].forEach(t=>{jn.has(t.userData.id)||t.userData.source!=="user"&&(t.traverse(r=>{let a=r;if(!a.geometry&&!a.material)return;_optionalChain([a, 'access', _2 => _2.geometry, 'optionalAccess', _3 => _3.userData, 'optionalAccess', _4 => _4[Ie]])||_optionalChain([a, 'access', _5 => _5.geometry, 'optionalAccess', _6 => _6.dispose, 'call', _7 => _7()]);let o=a.material;if(!o)return;(Array.isArray(o)?o:[o]).forEach(l=>{if(!Ye.has(l)){for(let s of Object.values(l))s instanceof $.Texture&&s.dispose();l.dispose()}})}),t.removeFromParent())})}function $n(e){let{up:n,forward:t,right:r}=we(e),a=t.clone().negate(),o=r.clone();return{top:n.clone(),bottom:n.clone().negate(),front:a.clone(),back:a.clone().negate(),right:o.clone(),left:o.clone().negate(),iso:a.clone().multiplyScalar(1.2).add(o.clone()).add(n.clone()).normalize()}}function Lt(e){let{scene:n,perspective:t,controls:r,onActiveCameraChange:a}=e,o=(_nullishCoalesce(e.up, () => (t.up))).clone().normalize(),i=$n(o),l=new Ee.OrthographicCamera(-1,1,1,-1,t.near,t.far);l.up.copy(o);let s="perspective",c=t.aspect,u=()=>s==="perspective"?t:l,d=null,p=()=>{_optionalChain([d, 'optionalAccess', _8 => _8.cancel, 'call', _9 => _9()]),d=null},T=()=>{let h=(s==="orthographic"?l:t).position.distanceTo(r.target)*Math.tan(t.fov*Math.PI/360),y=h*c;l.left=-y,l.right=y,l.top=h,l.bottom=-h,l.near=t.near,l.far=t.far,l.updateProjectionMatrix()},v=E=>{if(E!==s){if(p(),E==="orthographic")l.position.copy(t.position),l.up.copy(t.up),l.lookAt(r.target),l.zoom=1,T();else{let h=(l.top-l.bottom)/(2*l.zoom)/Math.tan(t.fov*Math.PI/360),y=l.position.clone().sub(r.target);y.lengthSq()<1e-12&&y.copy(o),y.normalize(),t.position.copy(r.target).add(y.multiplyScalar(h))}s=E,r.object=u(),r.update(),a(u())}},R=(E,f,h,y)=>{let C=t.fov*(Math.PI/180),M=f/(2*Math.tan(C/2))*1.5,L=qn(h,o),I=E.clone().add(L.clone().multiplyScalar(M)),k=u();s==="orthographic"&&(l.zoom=1),p(),y?d=Xn(k,r,I,E,()=>{s==="orthographic"&&T()}):(k.position.copy(I),r.target.copy(E),s==="orthographic"&&T(),r.update())},m=(E,f=!0)=>{let h=ce(n),y=h.isEmpty()?r.target.clone():h.getCenter(new Ee.Vector3),C=h.isEmpty()?new Ee.Vector3(1,1,1):h.getSize(new Ee.Vector3),M=Math.max(C.x,C.y,C.z)||1;R(y,M,E,f)};return{getActiveCamera:u,getProjection:()=>s,setProjection:v,toggleProjection:()=>(v(s==="perspective"?"orthographic":"perspective"),s),setView:(E,f=!0)=>{m(i[E],f)},setViewDirection:m,frameBounds:(E,f=!0)=>{if(E.isEmpty())return;let h=E.getCenter(new Ee.Vector3),y=E.getSize(new Ee.Vector3),C=Math.max(y.x,y.y,y.z)||1,M=u().position.clone().sub(r.target);M.lengthSq()<1e-12&&M.copy(i.iso),R(h,C,M.normalize(),f)},setRotateEnabled:E=>{r.enableRotate=E},isRotateEnabled:()=>r.enableRotate,updateAspect:(E,f)=>{c=f===0?c:E/f,s==="orthographic"&&T()},dispose:p}}function qn(e,n){let{up:t,forward:r}=we(n),a=e.clone().normalize();if(Math.abs(a.dot(t))<.9999)return e;let o=r.clone().negate(),i=.5*Math.PI/180;return a.multiplyScalar(Math.cos(i)).add(o.multiplyScalar(Math.sin(i))).normalize()}var Yn=e=>1-Math.pow(1-e,3);function Xn(e,n,t,r,a,o=250){let i=e.position.clone(),l=n.target.clone(),s=performance.now(),c=null,u=()=>{c=null;let d=Yn(Math.min((performance.now()-s)/o,1));e.position.lerpVectors(i,t,d),n.target.lerpVectors(l,r,d),a(),n.update(),d<1&&(c=requestAnimationFrame(u))};return c=requestAnimationFrame(u),{cancel:()=>{c!==null&&(cancelAnimationFrame(c),c=null)}}}function Kn(e){if(!(e>0)||!Number.isFinite(e))return 1;let n=Math.floor(Math.log10(e)),t=Math.pow(10,n),r=e/t;return(r>=5?5:r>=2?2:1)*t}var Zn=`
2
+ varying vec3 vWorldPos;
3
+ void main() {
4
+ vec4 world = modelMatrix * vec4(position, 1.0);
5
+ vWorldPos = world.xyz;
6
+ gl_Position = projectionMatrix * viewMatrix * world;
7
+ }
8
+ `,Jn=`
9
+ precision highp float;
10
+ varying vec3 vWorldPos;
11
+
12
+ uniform vec2 uAxes; // indices (0=x,1=y,2=z) of the two in-plane world axes
13
+ uniform float uCell;
14
+ uniform float uMajor;
15
+ uniform vec3 uCellColor;
16
+ uniform vec3 uMajorColor;
17
+ uniform vec3 uCenter; // fade center (camera position), projected onto plane
18
+ uniform float uFade;
19
+
20
+ // Antialiased grid line intensity for a given spacing, using screen-space derivatives so lines
21
+ // stay ~1px regardless of zoom (the standard "pristine grid" technique).
22
+ float gridLine(vec2 coord, float spacing) {
23
+ vec2 c = coord / spacing;
24
+ vec2 d = fwidth(c);
25
+ vec2 g = abs(fract(c - 0.5) - 0.5) / max(d, 1e-6);
26
+ float line = min(g.x, g.y);
27
+ return 1.0 - clamp(line, 0.0, 1.0);
28
+ }
29
+
30
+ // Index a vec3 by a float axis id (0/1/2) without dynamic indexing (WebGL1-safe).
31
+ float axis(vec3 v, float i) {
32
+ return i < 0.5 ? v.x : (i < 1.5 ? v.y : v.z);
33
+ }
34
+
35
+ void main() {
36
+ // Pick the two in-plane world coordinates.
37
+ vec2 coord = vec2(axis(vWorldPos, uAxes.x), axis(vWorldPos, uAxes.y));
38
+
39
+ float minor = gridLine(coord, uCell);
40
+ float major = gridLine(coord, uCell * uMajor);
41
+
42
+ vec3 color = mix(uCellColor, uMajorColor, major);
43
+ float alpha = max(minor, major);
44
+
45
+ // Radial fade from the camera-projected center.
46
+ float dist = distance(vWorldPos, uCenter);
47
+ float fade = 1.0 - clamp(dist / uFade, 0.0, 1.0);
48
+ alpha *= fade * fade;
49
+
50
+ if (alpha < 0.001) discard;
51
+ gl_FragColor = vec4(color, alpha);
52
+ }
53
+ `;function Ot(e={}){let{cellSize:n=1,majorEvery:t=10,cellColor:r=8947848,majorColor:a=4473924,fadeDistance:o=100,plane:i="y"}=e,l=i==="y"?new W.Vector2(0,2):i==="z"?new W.Vector2(0,1):new W.Vector2(1,2),s=2.5,c=new W.PlaneGeometry(1,1);i==="y"?c.rotateX(-Math.PI/2):i==="x"&&c.rotateY(Math.PI/2);let u=new W.ShaderMaterial({vertexShader:Zn,fragmentShader:Jn,transparent:!0,depthWrite:!1,side:W.DoubleSide,uniforms:{uAxes:{value:l},uCell:{value:n},uMajor:{value:t},uCellColor:{value:new W.Color(r)},uMajorColor:{value:new W.Color(a)},uCenter:{value:new W.Vector3},uFade:{value:o}}}),d=new W.Mesh(c,u);d.name="grid",d.userData.id="grid",d.renderOrder=-1;let p=o,T=o*s,v=new W.Vector3;return{object:d,update:R=>{i==="y"?(d.position.set(R.x,0,R.z),v.set(R.x,0,R.z)):i==="z"?(d.position.set(R.x,R.y,0),v.set(R.x,R.y,0)):(d.position.set(0,R.y,R.z),v.set(0,R.y,R.z)),u.uniforms.uCenter.value.copy(v),d.scale.setScalar(T)},fitToContent:R=>{if(R.isEmpty())return;let m=R.getSize(new W.Vector3),g=(H,E)=>E===0?H.x:E===1?H.y:H.z,b=Math.max(g(m,l.x),g(m,l.y));if(!(b>0)||!Number.isFinite(b))return;let x=20;u.uniforms.uCell.value=Kn(b/x),p=b*2,u.uniforms.uFade.value=p,T=p*s},setVisible:R=>{d.visible=R},dispose:()=>{d.removeFromParent(),c.dispose(),u.dispose()}}}var _ViewHelperjs = require('three/addons/helpers/ViewHelper.js');function It(e){let{camera:n,domElement:t,controller:r}=e,a=new (0, _ViewHelperjs.ViewHelper)(n,t);a.setLabels("X","Y","Z");let o=!0,i=128,l=new J.Raycaster,s=new J.OrthographicCamera(-2,2,2,-2,0,4);s.position.set(0,0,2),s.updateMatrixWorld();let c={posX:new J.Vector3(1,0,0),negX:new J.Vector3(-1,0,0),posY:new J.Vector3(0,1,0),negY:new J.Vector3(0,-1,0),posZ:new J.Vector3(0,0,1),negZ:new J.Vector3(0,0,-1)},u=p=>{let T=t.getBoundingClientRect(),v=T.left+t.offsetWidth-i-a.location.right,R=T.top+t.offsetHeight-i-a.location.bottom,m=new J.Vector2((p.clientX-v)/i*2-1,-((p.clientY-R)/i)*2+1);if(Math.abs(m.x)>1||Math.abs(m.y)>1)return null;a.quaternion.copy(n.quaternion).invert(),a.updateMatrixWorld(),l.setFromCamera(m,s);let g=l.intersectObjects(a.children,!1);for(let b of g){let x=_optionalChain([b, 'access', _10 => _10.object, 'access', _11 => _11.userData, 'optionalAccess', _12 => _12.type]);if(typeof x=="string"&&x in c)return x}return null};return{render:p=>{if(!o)return;let T=p.autoClear;p.autoClear=!1,a.render(p),p.autoClear=T},update:()=>{},handleClick:p=>{if(!o)return!1;let T=u(p);return T?(r.getProjection()==="orthographic"&&r.setProjection("perspective"),r.setViewDirection(c[T],!1),!0):!1},isAnimating:!1,setVisible:p=>{o=p},isVisible:()=>o,dispose:()=>a.dispose()}}var _LineSegmentsGeometryjs = require('three/addons/lines/LineSegmentsGeometry.js');var _LineSegments2js = require('three/addons/lines/LineSegments2.js');var _LineMaterialjs = require('three/addons/lines/LineMaterial.js');function Pe(e,n,t){let o=Math.cos(Math.PI/180*t),i=e.length/3;if(i>=67108864)throw new Error(`extractEdgeSegments: ${i} vertices exceeds 2^26 limit`);let l=new Float64Array(i),s=new Float64Array(i),c=new Float64Array(i);for(let f=0;f<i;f++)l[f]=Math.round(e[3*f]*1e4),s[f]=Math.round(e[3*f+1]*1e4),c[f]=Math.round(e[3*f+2]*1e4);let u=16;for(;u<i*2;)u<<=1;let d=u-1,p=new Int32Array(u).fill(-1),T=new Int32Array(i);for(let f=0;f<i;f++){let h=(Math.imul(l[f]|0,73856093)^Math.imul(s[f]|0,19349663)^Math.imul(c[f]|0,83492791))&d;for(;;){let y=p[h];if(y===-1){p[h]=f,T[f]=f;break}if(l[y]===l[f]&&s[y]===s[f]&&c[y]===c[f]){T[f]=y;break}h=h+1&d}}let v=new Float32Array(4096),R=0,m=(f,h)=>{if(R+6>v.length){let y=new Float32Array(v.length*2);y.set(v),v=y}v[R++]=e[3*f],v[R++]=e[3*f+1],v[R++]=e[3*f+2],v[R++]=e[3*h],v[R++]=e[3*h+1],v[R++]=e[3*h+2]},g=new Map,b=[],x=[],H=[],E=(n?n.length:i)/3;for(let f=0;f<E;f++){let h=n?n[3*f]:3*f,y=n?n[3*f+1]:3*f+1,C=n?n[3*f+2]:3*f+2,M=T[h],L=T[y],I=T[C];if(M===L||L===I||I===M)continue;let k=e[3*C]-e[3*y],O=e[3*C+1]-e[3*y+1],F=e[3*C+2]-e[3*y+2],S=e[3*h]-e[3*y],D=e[3*h+1]-e[3*y+1],G=e[3*h+2]-e[3*y+2],_=O*G-F*D,q=F*S-k*G,Y=k*D-O*S,fe=_*_+q*q+Y*Y;if(fe>0){let ee=1/Math.sqrt(fe);_*=ee,q*=ee,Y*=ee}else _=0,q=0,Y=0;for(let ee=0;ee<3;ee++){let pe,j,te,ne;ee===0?(pe=h,j=y,te=M,ne=L):ee===1?(pe=y,j=C,te=L,ne=I):(pe=C,j=h,te=I,ne=M);let xe=ne*67108864+te,he=g.get(xe);if(he!==void 0&&he!==-1)_*H[3*he]+q*H[3*he+1]+Y*H[3*he+2]<=o&&m(pe,j),g.set(xe,-1);else{let ie=te*67108864+ne;if(!g.has(ie)){let ve=b.length;g.set(ie,ve),b.push(pe),x.push(j),H.push(_,q,Y)}}}}for(let f of g.values())f!==-1&&m(b[f],x[f]);return v.slice(0,R)}function Pt(){return[`const extract = ${Pe.toString()};`,"self.onmessage = (event) => {"," const { id, positions, index, thresholdAngle } = event.data;"," try {"," const segments = extract(positions, index, thresholdAngle);"," self.postMessage({ id, segments }, [segments.buffer]);"," } catch (error) {"," self.postMessage({ id, error: String((error && error.message) || error) });"," }","};"].join(`
54
+ `)}var He="edge-overlay",rt= exports.o ="triangle-cap",rr=2236962,or=1.5,ar=44,ir=.75,sr=4e6,lr=2e6,cr=25e3,Ft=128*1024*1024,ur=80,Bt=20,dr=1,mr=2;function Ut(e,n){let t=Array.isArray(e.material)?e.material:[e.material];for(let r of t)r&&(r.polygonOffset=n,r.polygonOffsetFactor=n?dr:0,r.polygonOffsetUnits=n?mr:0)}function Je(e){let n=e.getAttribute("position");return n?(e.index?e.index.count:n.count)/3:0}function Vt(e){let n=e.getAttribute("position");if(!n||n.isInterleavedBufferAttribute||n.itemSize!==3||!(n.array instanceof Float32Array)||n.count>=67108864)return null;let t=e.index;return t&&!(t.array instanceof Uint32Array)&&!(t.array instanceof Uint16Array)?null:{positions:n.array,index:t?t.array:null}}function _t(e,n){let r=2166136261,a=s=>{r^=s,r=Math.imul(r,16777619)},o=new Uint32Array(e.positions.buffer,e.positions.byteOffset,e.positions.length),i=Math.min(4096,o.length);for(let s=0;s<i;s++)a(o[s]);for(let s=Math.max(i,o.length-4096);s<o.length;s++)a(o[s]);let l=0;if(e.index){l=e.index.length;let s=Math.min(4096,l);for(let c=0;c<s;c++)a(e.index[c]);for(let c=Math.max(s,l-4096);c<l;c++)a(e.index[c])}return`${n}:${e.positions.length}:${l}:${r>>>0}`}var ue=new Map,Fe=0;function zt(e){let n=ue.get(e);return n&&(ue.delete(e),ue.set(e,n)),n}function Gt(e,n){if(n.byteLength>Ft)return;let t=ue.get(e);for(t&&(Fe-=t.byteLength,ue.delete(e)),ue.set(e,n),Fe+=n.byteLength;Fe>Ft;){let r=ue.keys().next().value;Fe-=ue.get(r).byteLength,ue.delete(r)}}function fr(e,n){let t=new Z.EdgesGeometry(e,n),r=t.attributes.position?t.attributes.position.array:new Float32Array(0);return t.dispose(),r}function Qe(e,n){let t=Vt(e);if(!t)return fr(e,n);let r=_t(t,n),a=zt(r);if(a)return a;let o=Pe(t.positions,t.index,n);return Gt(r,o),o}var ye,Me=new Map,pr=1;function Er(){if(ye!==void 0)return ye;if(typeof Worker>"u"||typeof Blob>"u"||typeof URL>"u"||typeof URL.createObjectURL!="function")return ye=null,null;try{let e=URL.createObjectURL(new Blob([Pt()],{type:"text/javascript"})),n=new Worker(e);n.onmessage=t=>{let{id:r,segments:a,error:o}=t.data,i=Me.get(r);i&&(Me.delete(r),a?i.resolve(a):i.reject(new Error(_nullishCoalesce(o, () => ("edge extraction failed in worker")))))},n.onerror=()=>{for(let t of Me.values())t.reject(new Error("edge extraction worker crashed"));Me.clear(),n.terminate(),ye=null},ye=n}catch (e3){ye=null}return ye}function hr(e,n,t){return new Promise((r,a)=>{let o=pr++;Me.set(o,{resolve:r,reject:a});let i=n.positions.slice(),l=n.index?n.index.slice():null,s=[i.buffer];l&&s.push(l.buffer),e.postMessage({id:o,positions:i,index:l,thresholdAngle:t},s)})}var Ze=new Map;function gr(e,n){let t=Vt(e);if(!t||Je(e)<cr)return Promise.resolve(Qe(e,n));let r=_t(t,n),a=zt(r);if(a)return Promise.resolve(a);let o=Ze.get(r);if(o)return o;let i=Er();if(!i)return Promise.resolve(Qe(e,n));let l=hr(i,t,n).catch(()=>Pe(t.positions,t.index,n)).then(s=>(Gt(r,s),s)).finally(()=>{Ze.delete(r)});return Ze.set(r,l),l}var Be=new WeakMap;function et(e,n){return _optionalChain([Be, 'access', _13 => _13.get, 'call', _14 => _14(e), 'optionalAccess', _15 => _15.get, 'call', _16 => _16(n)])}function Nt(e,n,t){let r=Be.get(e);r||(r=new Map,Be.set(e,r));let a=new _LineSegmentsGeometryjs.LineSegmentsGeometry;a.setPositions(t);let o={geometry:a,refCount:0,segmentCount:t.length/6};return r.set(n,o),o}function yr(e){let n=e.userData,t=n.edgeSource&&Be.get(n.edgeSource),r=n.edgeThresholdAngle!=null?_optionalChain([t, 'optionalAccess', _17 => _17.get, 'call', _18 => _18(n.edgeThresholdAngle)]):void 0;if(!r||r.geometry!==e.geometry){e.geometry.dispose();return}r.refCount-=1,r.refCount<=0&&(r.geometry.dispose(),t.delete(n.edgeThresholdAngle))}function jt(e){return{forcedColor:e.color!=null?new Z.Color(e.color):null,darken:Z.MathUtils.clamp(_nullishCoalesce(e.darken, () => (ir)),0,1),width:_nullishCoalesce(e.width, () => (or)),thresholdAngle:_nullishCoalesce(e.thresholdAngle, () => (ar)),distanceFade:_nullishCoalesce(e.distanceFade, () => (!0)),maxTriangles:_nullishCoalesce(e.maxTriangles, () => (sr)),maxSegments:_nullishCoalesce(e.maxSegments, () => (lr))}}function br(e,n){let r=_optionalChain([(Array.isArray(e.material)?e.material[0]:e.material), 'optionalAccess', _19 => _19.color]);return r?r.clone().multiplyScalar(1-n):new Z.Color(rr)}var ke=class{constructor(n){_chunkH3FZW6OXcjs.b.call(void 0, this,"options",n);_chunkH3FZW6OXcjs.b.call(void 0, this,"byKey",new Map)}for(n,t){let r=_nullishCoalesce(this.options.forcedColor, () => (br(n,this.options.darken))),a=r.getHex()*2+(t?1:0),o=this.byKey.get(a);return o||(o=Tr(r,this.options.width,t),this.byKey.set(a,o)),o}disposeUnused(n){let t=new Set(n.map(r=>r.material));for(let r of this.byKey.values())t.has(r)||r.dispose()}};function Tr(e,n,t){let r=new (0, _LineMaterialjs.LineMaterial)({color:e});return r.linewidth=n,t&&(r.transparent=!0),r}function Rr(e,n,t,r,a){n.refCount+=1;let o=new (0, _LineSegments2js.LineSegments2)(n.geometry,t);return o.userData.kind=He,o.userData.edgeSource=e,o.userData.edgeThresholdAngle=r,o.raycast=()=>{},a&&wr(o),o}var kt=new Z.Vector3,xr=new Z.Vector3;function vr(e,n,t){e.geometry.boundingSphere||e.geometry.computeBoundingSphere();let r=e.geometry.boundingSphere;if(!r||r.radius<=0)return 1/0;let a=r.radius*e.matrixWorld.getMaxScaleOnAxis();if(kt.copy(r.center).applyMatrix4(e.matrixWorld),n.isPerspectiveCamera){let o=n,i=xr.setFromMatrixPosition(n.matrixWorld).distanceTo(kt);if(i<=a)return 1/0;let l=Math.tan(Z.MathUtils.degToRad(o.fov)*.5);return a/(i*l)*t}if(n.isOrthographicCamera){let o=n,i=(o.top-o.bottom)/o.zoom;return i>0?2*a/i*t:1/0}return 1/0}function wr(e){e.onBeforeRender=(n,t,r)=>{_LineSegments2js.LineSegments2.prototype.onBeforeRender.call(e,n);let a=e.material,o=vr(e,r,a.resolution.y);a.opacity=Z.MathUtils.clamp((o-Bt)/(ur-Bt),0,1)}}function Mr(e){return _optionalChain([e, 'access', _20 => _20.userData, 'optionalAccess', _21 => _21.kind])===He}function Wt(e,n){let t=[];return e.traverse(r=>{if(r instanceof Z.Mesh&&!(r.userData.id==="floor"||r.userData.id==="grid")&&r.userData.kind!==He&&!r.children.some(a=>_optionalChain([a, 'access', _22 => _22.userData, 'optionalAccess', _23 => _23.kind])===He)&&r.geometry){if(Je(r.geometry)>n){r.userData.edgesSkipped=rt,console.debug(`[edges] skipping mesh over triangle cap (${Je(r.geometry)} > ${n})`);return}delete r.userData.edgesSkipped,t.push(r)}}),t}function $t(e,n,t,r){let a=r.distanceFade&&n.segmentCount<=r.maxSegments,o=Rr(e.geometry,n,t.for(e,a),r.thresholdAngle,a);return e.add(o),Ut(e,!0),o}function ja(e,n={}){let t=jt(n),r=new ke(t),a=[];for(let o of Wt(e,t.maxTriangles)){let i=_nullishCoalesce(et(o.geometry,t.thresholdAngle), () => (Nt(o.geometry,t.thresholdAngle,Qe(o.geometry,t.thresholdAngle))));a.push($t(o,i,r,t))}return r.disposeUnused(a),a}var qt=new WeakMap;function tt(e){return _nullishCoalesce(qt.get(e), () => (0))}function Hr(e,n){for(let t=e;t;t=t.parent)if(t===n)return!0;return!1}async function Yt(e,n={}){let t=jt(n),r=new ke(t),a=tt(e),o=[],i=Wt(e,t.maxTriangles).map(async l=>{let s=et(l.geometry,t.thresholdAngle);if(!s){let c=await gr(l.geometry,t.thresholdAngle);if(tt(e)!==a||!Hr(l,e)||l.children.some(u=>_optionalChain([u, 'access', _24 => _24.userData, 'optionalAccess', _25 => _25.kind])===He))return;s=et(l.geometry,t.thresholdAngle),s||(s=Nt(l.geometry,t.thresholdAngle,c))}o.push($t(l,s,r,t))});return await Promise.all(i),r.disposeUnused(o),o}function Xt(e){qt.set(e,tt(e)+1);let n=[];e.traverse(r=>{r instanceof _LineSegments2js.LineSegments2&&Mr(r)&&n.push(r)});let t=new Set;for(let r of n)yr(r),t.add(r.material),r.parent instanceof Z.Mesh&&Ut(r.parent,!1),r.removeFromParent();return t.forEach(r=>r.dispose()),n.length}var _Passjs = require('three/addons/postprocessing/Pass.js');var ot={uniforms:{tDiffuse:{value:null},tNormal:{value:null},tDepth:{value:null},uResolution:{value:new N.Vector2(1,1)},uColor:{value:new N.Color(2236962)},uOpacity:{value:1},uNormalThreshold:{value:.4},uDepthThreshold:{value:.02},uThickness:{value:1},uNear:{value:.1},uFar:{value:1e3},uPerspective:{value:1}},vertexShader:`
55
+ varying vec2 vUv;
56
+ void main() {
57
+ vUv = uv;
58
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
59
+ }
60
+ `,fragmentShader:`
61
+ uniform sampler2D tDiffuse;
62
+ uniform sampler2D tNormal;
63
+ uniform sampler2D tDepth;
64
+ uniform vec2 uResolution;
65
+ uniform vec3 uColor;
66
+ uniform float uOpacity;
67
+ uniform float uNormalThreshold;
68
+ uniform float uDepthThreshold;
69
+ uniform float uThickness;
70
+ uniform float uNear;
71
+ uniform float uFar;
72
+ uniform float uPerspective;
73
+ varying vec2 vUv;
74
+
75
+ float viewZOf(const in float depth) {
76
+ float perspective = (uNear * uFar) / ((uFar - uNear) * depth - uFar);
77
+ float orthographic = -(depth * (uFar - uNear) + uNear);
78
+ return mix(orthographic, perspective, uPerspective);
79
+ }
80
+
81
+ void main() {
82
+ vec4 color = texture2D(tDiffuse, vUv);
83
+ vec2 texel = uThickness / uResolution;
84
+
85
+ // Roberts cross over the two diagonal pairs.
86
+ vec2 offsetA = vec2(texel.x, texel.y);
87
+ vec2 offsetB = vec2(texel.x, -texel.y);
88
+
89
+ float z0 = viewZOf(texture2D(tDepth, vUv + offsetA).x);
90
+ float z1 = viewZOf(texture2D(tDepth, vUv - offsetA).x);
91
+ float z2 = viewZOf(texture2D(tDepth, vUv + offsetB).x);
92
+ float z3 = viewZOf(texture2D(tDepth, vUv - offsetB).x);
93
+ float zCenter = viewZOf(texture2D(tDepth, vUv).x);
94
+ // Relative difference: a constant threshold in absolute Z turns distant geometry into
95
+ // noise (depth precision) and near geometry blind; normalizing by the center depth keeps
96
+ // the response scale-invariant across the viewer's mm\u2192m scenes.
97
+ float depthDelta = (abs(z0 - z1) + abs(z2 - z3)) / max(abs(zCenter), 1e-6);
98
+ float depthEdge = step(uDepthThreshold, depthDelta);
99
+
100
+ vec3 n0 = texture2D(tNormal, vUv + offsetA).rgb * 2.0 - 1.0;
101
+ vec3 n1 = texture2D(tNormal, vUv - offsetA).rgb * 2.0 - 1.0;
102
+ vec3 n2 = texture2D(tNormal, vUv + offsetB).rgb * 2.0 - 1.0;
103
+ vec3 n3 = texture2D(tNormal, vUv - offsetB).rgb * 2.0 - 1.0;
104
+ float normalDelta = (1.0 - dot(n0, n1)) + (1.0 - dot(n2, n3));
105
+ float normalEdge = step(uNormalThreshold, normalDelta);
106
+
107
+ float edge = max(depthEdge, normalEdge) * uOpacity;
108
+ gl_FragColor = vec4(mix(color.rgb, uColor, edge), color.a);
109
+ }
110
+ `},Ue= exports.t =class extends _Passjs.Pass{constructor(t,r,a,o,i={}){super();_chunkH3FZW6OXcjs.b.call(void 0, this,"camera");_chunkH3FZW6OXcjs.b.call(void 0, this,"scene");_chunkH3FZW6OXcjs.b.call(void 0, this,"normalMaterial");_chunkH3FZW6OXcjs.b.call(void 0, this,"edgeMaterial");_chunkH3FZW6OXcjs.b.call(void 0, this,"fsQuad");_chunkH3FZW6OXcjs.b.call(void 0, this,"normalTarget",null);_chunkH3FZW6OXcjs.b.call(void 0, this,"width");_chunkH3FZW6OXcjs.b.call(void 0, this,"height");this.scene=t,this.camera=r,this.width=Math.max(1,a),this.height=Math.max(1,o),this.normalMaterial=new N.MeshNormalMaterial,this.normalMaterial.blending=N.NoBlending,this.edgeMaterial=new N.ShaderMaterial({uniforms:N.UniformsUtils.clone(ot.uniforms),vertexShader:ot.vertexShader,fragmentShader:ot.fragmentShader});let l=this.edgeMaterial.uniforms;l.uColor.value=new N.Color(_nullishCoalesce(i.color, () => (2236962))),l.uOpacity.value=_nullishCoalesce(i.opacity, () => (1)),l.uNormalThreshold.value=_nullishCoalesce(i.normalThreshold, () => (.4)),l.uDepthThreshold.value=_nullishCoalesce(i.depthThreshold, () => (.02)),l.uThickness.value=_nullishCoalesce(i.thickness, () => (1)),this.fsQuad=new (0, _Passjs.FullScreenQuad)(this.edgeMaterial),this.needsSwap=!0}acquireNormalTarget(){if(!this.normalTarget){let t=new N.DepthTexture(this.width,this.height);this.normalTarget=new N.WebGLRenderTarget(this.width,this.height,{minFilter:N.NearestFilter,magFilter:N.NearestFilter,depthTexture:t})}return this.normalTarget}setSize(t,r){this.width=Math.max(1,t),this.height=Math.max(1,r),_optionalChain([this, 'access', _26 => _26.normalTarget, 'optionalAccess', _27 => _27.setSize, 'call', _28 => _28(this.width,this.height)])}render(t,r,a){let o=this.acquireNormalTarget(),i=t.getRenderTarget(),l=t.autoClear,s=t.getClearColor(new N.Color),c=t.getClearAlpha(),u=this.scene.overrideMaterial;t.setRenderTarget(o),t.setClearColor(7829503,1),t.autoClear=!0,this.scene.overrideMaterial=this.normalMaterial,t.render(this.scene,this.camera),this.scene.overrideMaterial=u,t.setClearColor(s,c),t.autoClear=l;let d=this.edgeMaterial.uniforms;d.tDiffuse.value=a.texture,d.tNormal.value=o.texture,d.tDepth.value=o.depthTexture,d.uResolution.value.set(this.width,this.height);let p=this.camera;d.uPerspective.value=p.isPerspectiveCamera?1:0,d.uNear.value=_nullishCoalesce(this.camera.near, () => (.1)),d.uFar.value=_nullishCoalesce(this.camera.far, () => (1e3)),t.setRenderTarget(this.renderToScreen?null:r),this.fsQuad.render(t),t.setRenderTarget(i)}dispose(){_optionalChain([this, 'access', _29 => _29.normalTarget, 'optionalAccess', _30 => _30.dispose, 'call', _31 => _31()]),this.normalMaterial.dispose(),this.edgeMaterial.dispose(),this.fsQuad.dispose()}};var _EffectComposerjs = require('three/addons/postprocessing/EffectComposer.js');var _RenderPassjs = require('three/addons/postprocessing/RenderPass.js');var _GTAOPassjs = require('three/addons/postprocessing/GTAOPass.js');var _SMAAPassjs = require('three/addons/postprocessing/SMAAPass.js');var _OutputPassjs = require('three/addons/postprocessing/OutputPass.js');function Kt(e,n,t,r,a,o){let i=new (0, _EffectComposerjs.EffectComposer)(e),l=new (0, _RenderPassjs.RenderPass)(n,t);i.addPass(l);let s=null;(_nullishCoalesce(o.ambientOcclusion, () => (!0)))&&(s=new (0, _GTAOPassjs.GTAOPass)(n,t,r,a),s.blendIntensity=_nullishCoalesce(o.aoIntensity, () => (1)),s.updateGtaoMaterial({screenSpaceRadius:!0}),i.addPass(s));let c=typeof o.edgeDetection=="object"?o.edgeDetection:{},u=new Ue(n,t,r,a,c);u.enabled=!!o.edgeDetection,i.addPass(u);let d=new _SMAAPassjs.SMAAPass;i.addPass(d);let p=new _OutputPassjs.OutputPass;i.addPass(p),e.toneMapping=o.toneMapping,e.toneMappingExposure=o.toneMappingExposure;let T=_nullishCoalesce(o.aoPixelRatio, () => (1));return i.setSize(r,a),{render:v=>i.render(v),setSize:(v,R,m)=>{i.setPixelRatio(Math.min(m,T)),i.setSize(v,R)},setCamera:v=>{if(l.camera=v,u.camera=v,!s)return;s.camera=v;let R=v.isPerspectiveCamera?1:0;s.gtaoMaterial.defines.PERSPECTIVE_CAMERA!==R&&(s.gtaoMaterial.defines.PERSPECTIVE_CAMERA=R,s.gtaoMaterial.needsUpdate=!0)},setEdgeDetection:v=>{u.enabled=v},edgeDetectionEnabled:()=>u.enabled,dispose:()=>{i.dispose(),_optionalChain([s, 'optionalAccess', _32 => _32.dispose, 'call', _33 => _33()]),u.dispose(),d.dispose(),p.dispose()}}}var _CSS2DRendererjs = require('three/addons/renderers/CSS2DRenderer.js');function Jt(e,n){let t=new _CSS2DRendererjs.CSS2DRenderer,r=t.domElement;r.style.position="absolute",r.style.top="0",r.style.left="0",r.style.overflow="hidden",r.style.pointerEvents="none",r.style.zIndex="30",getComputedStyle(e).position==="static"&&(e.style.position="relative"),e.appendChild(r);let a={width:e.clientWidth||1,height:e.clientHeight||1};t.setSize(a.width,a.height);let o=new Zt.Group;o.name="label-layer",o.userData.id="label-layer",n.add(o);let i=new Set;return{addLabel:(s,c,u)=>{let d=document.createElement("div");d.textContent=s,u?d.className=u:Object.assign(d.style,{padding:"2px 6px",borderRadius:"4px",background:"rgba(20, 20, 20, 0.78)",color:"#fff",font:"12px/1.3 system-ui, sans-serif",whiteSpace:"pre",textAlign:"center",userSelect:"none"}),d.style.pointerEvents="none";let p=new (0, _CSS2DRendererjs.CSS2DObject)(d);return p.position.copy(c),o.add(p),i.add(p),{object:p,setPosition:T=>p.position.copy(T),setText:T=>{d.textContent=T},remove:()=>{p.removeFromParent(),d.remove(),i.delete(p)}}},render:(s,c)=>t.render(s,c),setSize:(s,c)=>t.setSize(s,c),dispose:()=>{i.forEach(s=>{s.removeFromParent(),s.element.remove()}),i.clear(),o.removeFromParent(),r.remove()}}}var _Line2js = require('three/addons/lines/Line2.js');var _LineGeometryjs = require('three/addons/lines/LineGeometry.js');var Vr=12,_r=16763904,Qt=.015,en={Millimeters:{metersPerUnit:1/1e3,suffix:"mm"},Centimeters:{metersPerUnit:1/100,suffix:"cm"},Meters:{metersPerUnit:1,suffix:"m"},Inches:{metersPerUnit:1/39.37,suffix:"in"},Feet:{metersPerUnit:1/3.28084,suffix:"ft"}};function zr(e){let n=e&&en[e]||en.Meters;return t=>`${(t/n.metersPerUnit).toPrecision(3)} ${n.suffix}`}function Gr(e,n){if(e.isOrthographicCamera){let r=e;return Math.abs(r.top-r.bottom)/(r.zoom||1)*Qt}return((n?e.position.distanceTo(n):e.position.length())||1)*Qt}function Nr(e){let n=e.object;if(n instanceof U.Mesh)return e.face?[e.face.a,e.face.b,e.face.c]:null;if(n instanceof U.Points)return e.index!=null?[e.index]:null;if(n instanceof U.Line){if(e.index==null)return null;let t=n.geometry.index;return t?e.index+1>=t.count?null:[t.getX(e.index),t.getX(e.index+1)]:[e.index,e.index+1]}return null}function jr(e,n,t,r){let a=e.point.clone(),o=e.object,i=Nr(e);if(!i||!o.geometry)return a;let l=o.geometry.attributes.position;if(!l)return a;let s=p=>{let T=p.clone().project(n);return new U.Vector2((T.x+1)/2*t.width,(1-T.y)/2*t.height)},c=s(a),u=a,d=r;for(let p of i){if(p>=l.count)continue;let v=new U.Vector3().fromBufferAttribute(l,p).applyMatrix4(o.matrixWorld),R=s(v).distanceTo(c);R<d&&(d=R,u=v)}return u}function tn(e){let{canvas:n,scene:t,getActiveCamera:r,getViewTarget:a,labelLayer:o,options:i={}}=e,l=_nullishCoalesce(i.snapPixels, () => (Vr)),s=new U.Color(_nullishCoalesce(i.color, () => (_r))),c=zr(i.displayUnit),u=(S,D)=>`${c(S)}
111
+ \u0394x ${c(D.x)} \u0394y ${c(D.y)} \u0394z ${c(D.z)}`,d=_nullishCoalesce(i.format, () => (u)),p=new U.Raycaster,T=new U.Vector2,v=!1,R=[],m=[],g=null,b=null,x=new U.PointsMaterial({color:s,size:8,sizeAttenuation:!1,depthTest:!1}),H=new U.PointsMaterial({color:s,size:11,sizeAttenuation:!1,depthTest:!1,transparent:!0,opacity:.5}),E=null,f=S=>{if(!S){E&&(E.visible=!1);return}if(!E){let D=new U.BufferGeometry;D.setAttribute("position",new U.Float32BufferAttribute([0,0,0],3)),E=new U.Points(D,H),E.renderOrder=1e3,E.userData.id="measure",E.raycast=()=>{},t.add(E)}E.position.copy(S),E.visible=!0},h=S=>{let D=new U.BufferGeometry;D.setAttribute("position",new U.Float32BufferAttribute([S.x,S.y,S.z],3));let G=new U.Points(D,x);return G.renderOrder=999,G.userData.id="measure",G.raycast=()=>{},t.add(G),G},y=()=>{R.length=0,m.forEach(S=>{S.geometry.dispose(),S.removeFromParent()}),m.length=0,g&&(g.geometry.dispose(),g.material.dispose(),g.removeFromParent(),g=null),_optionalChain([b, 'optionalAccess', _34 => _34.remove, 'call', _35 => _35()]),b=null},C=()=>{if(R.length!==2)return;let[S,D]=R,G=new _LineGeometryjs.LineGeometry;G.setPositions([S.x,S.y,S.z,D.x,D.y,D.z]);let _=new (0, _LineMaterialjs.LineMaterial)({color:s});_.linewidth=2,_.depthTest=!1,g=new (0, _Line2js.Line2)(G,_),g.renderOrder=998,g.userData.id="measure",g.raycast=()=>{},t.add(g);let q=S.clone().add(D).multiplyScalar(.5),Y=new U.Vector3(Math.abs(D.x-S.x),Math.abs(D.y-S.y),Math.abs(D.z-S.z));b=o.addLabel(d(S.distanceTo(D),Y),q,i.labelClassName)},M=S=>{let D=n.getBoundingClientRect();T.x=(S.clientX-D.left)/D.width*2-1,T.y=-((S.clientY-D.top)/D.height)*2+1;let G=r();p.setFromCamera(T,G);let _=Gr(G,_optionalChain([a, 'optionalCall', _36 => _36()]));p.params.Line.threshold=_,p.params.Points.threshold=_;let q=p.intersectObjects(t.children,!0).filter(Y=>Y.object.userData.id!=="measure"&&Y.object.userData.id!=="grid");return q.length===0?null:jr(q[0],G,{width:D.width,height:D.height},l)},L=null,I=0,k=()=>{I&&(cancelAnimationFrame(I),I=0),L=null};return{setEnabled:S=>{v=S,S||(k(),y(),f(null))},isEnabled:()=>v,handleClick:S=>{if(!v)return!1;R.length===2&&y();let D=M(S);return D===null||(R.push(D),m.push(h(D)),R.length===2&&C()),!0},handleMove:S=>{v&&(L=S,!I&&(I=requestAnimationFrame(()=>{I=0;let D=L;L=null,!(!v||!D)&&f(M(D))})))},clear:y,dispose:()=>{k(),y(),E&&(E.geometry.dispose(),E.removeFromParent(),E=null),x.dispose(),H.dispose()}}}var Wr=64,$r=256,ae=new Map,Ce=new Map,Ve=0,ze=class extends Error{constructor(n){super(`Texture load for ${n} resolved after clearTextureCache(); texture disposed.`),this.name="StaleTextureLoadError"}},_e=1;function nn(e){_e=Math.max(1,e);for(let n of ae.values())n.anisotropy!==_e&&(n.anisotropy=_e,n.needsUpdate=!0)}function rn(e,n){let t=qr(n),r=ae.get(t);if(r){ae.delete(t),ae.set(t,r),e.map=r,e.needsUpdate=!0;return}typeof document>"u"||Kr(n,t).then(a=>{e.map=a,e.needsUpdate=!0}).catch(a=>{a instanceof ze||_chunkH3FZW6OXcjs.e.call(void 0, ).warn(`Failed to load material texture ${n}:`,a)})}function ui(){Ve++;for(let e of ae.values())e.dispose();ae.clear(),Ce.clear()}function qr(e){return e.length<=$r?e:`data-uri:${Yr(e).toString(16)}:${e.length}`}function Yr(e){let n=2166136261;for(let t=0;t<e.length;t++)n^=e.charCodeAt(t),n=Math.imul(n,16777619);return n>>>0}function Xr(e,n){for(ae.set(e,n);ae.size>Wr;){let t=ae.keys().next().value,r=ae.get(t);ae.delete(t),r.dispose()}}function Kr(e,n){let t=Ce.get(n);if(!t){let r=Ve;t=new Promise((a,o)=>{new Ge.TextureLoader().load(e,i=>{if(r!==Ve){i.dispose(),o(new ze(e));return}i.colorSpace=Ge.SRGBColorSpace,i.anisotropy=_e,Xr(n,i),Ce.delete(n),a(i)},void 0,i=>{r===Ve&&Ce.delete(n),o(i)})}),Ce.set(n,t)}return t}var _OrbitControlsjs = require('three/addons/controls/OrbitControls.js');var _HDRLoaderjs = require('three/addons/loaders/HDRLoader.js');var Zr=.5,Jr=.01,Qr=.05,eo=[];function on({camera:e,scene:n,groundNormals:t=()=>eo}){let r=e.near,a=e.near,o=new Ae.Vector3,i=new Ae.Vector3;return{update:()=>{e.near!==a&&(r=e.near);let s=ce(n),c=r;if(!s.isEmpty()){let u=s.getSize(i).length()*.5,d=e.position.distanceTo(s.getCenter(o))-u;for(let p of t())d=Math.min(d,Math.abs(e.position.dot(p)));c=Ae.MathUtils.clamp(d*Zr,r,e.far*Jr)}Math.abs(c-a)>a*Qr&&(e.near=c,e.updateProjectionMatrix(),a=c)}}}var de=new w.Vector3(0,0,1),ro="technical",at={studio:{toneMapping:w.ACESFilmicToneMapping,toneMappingExposure:1,envMapIntensity:1,environmentIntensity:1,hemisphereIntensity:.75,ambientIntensity:.4,cullBackfaces:!1,ambientOcclusion:!1},technical:{toneMapping:w.NeutralToneMapping,toneMappingExposure:1,envMapIntensity:.9,environmentIntensity:1,hemisphereIntensity:.35,ambientIntensity:.25,cullBackfaces:!1,ambientOcclusion:!1},showcase:{toneMapping:w.ACESFilmicToneMapping,toneMappingExposure:1.15,envMapIntensity:1.4,environmentIntensity:1.25,hemisphereIntensity:.35,ambientIntensity:.15,cullBackfaces:!1,ambientOcclusion:!1}};function oo(e){let n=at[e];return{envMapIntensity:n.envMapIntensity,cullBackfaces:n.cullBackfaces}}var Ai=function(e,n){let t=ao(n||{}),r=_optionalChain([t, 'access', _37 => _37.environment, 'optionalAccess', _38 => _38.sceneUp])||de,a=_nullishCoalesce(t.render.pixelRatio, () => (Math.min(window.devicePixelRatio,2))),o=so(t),i=fo(t,e);i.up.copy(r);let l=po(e,t,a);nn(l.capabilities.getMaxAnisotropy());let s=ho(i,e,t),c=Lt({scene:o,perspective:i,controls:s,onActiveCameraChange:()=>{},up:r}),u=()=>c.getActiveCamera(),d=!1;co(o,l,t,()=>d);let p=uo(o,t),T=p.sun,v=()=>{T&&io(T,ce(o))};_optionalChain([t, 'access', _39 => _39.floor, 'optionalAccess', _40 => _40.enabled])&&mo(o,t);let R=_optionalChain([t, 'access', _41 => _41.floor, 'optionalAccess', _42 => _42.enabled])?_nullishCoalesce(o.children.find(A=>A.userData.id==="floor"), () => (null)):null,m=t.grid.enabled?Ot({cellSize:t.grid.cellSize,majorEvery:t.grid.majorEvery,cellColor:t.grid.cellColor,majorColor:t.grid.majorColor,fadeDistance:t.grid.fadeDistance,plane:t.grid.plane}):null;m&&o.add(m.object);let g=()=>{m&&m.fitToContent(ce(o))},b=t.gizmo.enabled?It({camera:i,domElement:e,controller:c}):null,x=_nullishCoalesce(t.grid.plane, () => (Xe(r))),H=new w.Vector3(x==="x"?1:0,x==="y"?1:0,x==="z"?1:0),E=r.clone().normalize(),f=()=>{let A=[];return _optionalChain([m, 'optionalAccess', _43 => _43.object, 'access', _44 => _44.visible])&&A.push(H),t.floor.enabled&&_optionalChain([R, 'optionalAccess', _45 => _45.visible])&&A.push(E),A},h=t.camera.dynamicNear?on({camera:i,scene:o,groundNormals:f}):null,y=_nullishCoalesce(e.parentElement, () => (e)),C=t.measure.enabled?Jt(y,o):null,M=t.measure.enabled&&C?tn({canvas:e,scene:o,getActiveCamera:u,labelLayer:C,options:{snapPixels:t.measure.snapPixels,color:t.measure.color,labelClassName:t.measure.labelClassName,displayUnit:t.measure.displayUnit,format:t.measure.format}}):null,L=t.events.enableEventHandlers!==!1?Eo(e,o,c,t):{dispose:()=>{},fitToView:()=>{},clearSelection:()=>{}},I=5,k=0,O=0,F=A=>{k=A.clientX,O=A.clientY},S=A=>Math.hypot(A.clientX-k,A.clientY-O)>I,D=A=>{if(!S(A)){if(_optionalChain([M, 'optionalAccess', _46 => _46.handleClick, 'call', _47 => _47(A)])){A.stopImmediatePropagation();return}_optionalChain([b, 'optionalAccess', _48 => _48.handleClick, 'call', _49 => _49(A)])&&A.stopImmediatePropagation()}};(b||M)&&(e.addEventListener("mousedown",F,{capture:!0}),e.addEventListener("click",D,{capture:!0}));let G=A=>_optionalChain([M, 'optionalAccess', _50 => _50.handleMove, 'call', _51 => _51(A)]);M&&e.addEventListener("mousemove",G,{passive:!0});let _=()=>{},q=A=>{Yt(A,{color:t.edges.color,darken:t.edges.darken,width:t.edges.width,thresholdAngle:t.edges.thresholdAngle,distanceFade:t.edges.distanceFade,maxTriangles:t.edges.maxTriangles,maxSegments:t.edges.maxSegments}).then(()=>{Y(A),_()})},Y=A=>{if(t.edges.screenSpaceFallback===!1)return;let B=!1;A.traverse(K=>{_optionalChain([K, 'access', _52 => _52.userData, 'optionalAccess', _53 => _53.edgesSkipped])===rt&&(B=!0)}),B!==ne&&(ne=B,ie())},fe=A=>{Xt(A),ne&&(ne=!1,ie()),_()},ee=e.parentElement,pe=()=>ee?{width:ee.clientWidth,height:ee.clientHeight}:{width:window.innerWidth,height:window.innerHeight},j=null,te=!!t.render.ambientOcclusion,ne=!1,xe=!1,he=A=>{let{width:B,height:K}=pe(),ge=Kt(l,o,u(),Math.max(1,B),Math.max(1,K),{toneMapping:_nullishCoalesce(t.render.toneMapping, () => (w.NeutralToneMapping)),toneMappingExposure:_nullishCoalesce(t.render.toneMappingExposure, () => (1)),ambientOcclusion:A,aoIntensity:t.render.aoIntensity,aoPixelRatio:t.render.aoPixelRatio,edgeDetection:!1});return ge.setSize(Math.max(1,B),Math.max(1,K),a),ge},ie=()=>{if(!(te||ne)){_optionalChain([j, 'optionalAccess', _54 => _54.dispose, 'call', _55 => _55()]),j=null,_();return}(!j||xe!==te)&&(_optionalChain([j, 'optionalAccess', _56 => _56.dispose, 'call', _57 => _57()]),j=he(te),xe=te),j.setEdgeDetection(ne),_()},ve=()=>{_optionalChain([j, 'optionalAccess', _58 => _58.dispose, 'call', _59 => _59()]),j=null,ie()},Sn=A=>{te=A,ie()};ie();let ft=A=>{A.ambientIntensity!==void 0&&(p.ambient.intensity=A.ambientIntensity),A.hemisphereIntensity!==void 0&&!p.hemisphere&&A.hemisphereIntensity>0&&(p.hemisphere=new w.HemisphereLight(_nullishCoalesce(A.hemisphereSkyColor, () => (t.lighting.hemisphereSkyColor)),_nullishCoalesce(A.hemisphereGroundColor, () => (t.lighting.hemisphereGroundColor)),A.hemisphereIntensity),p.hemisphere.position.copy(_nullishCoalesce(t.environment.sceneUp, () => (de))),o.add(p.hemisphere)),p.hemisphere&&(A.hemisphereIntensity!==void 0&&(p.hemisphere.intensity=A.hemisphereIntensity),A.hemisphereSkyColor!==void 0&&p.hemisphere.color.set(A.hemisphereSkyColor),A.hemisphereGroundColor!==void 0&&p.hemisphere.groundColor.set(A.hemisphereGroundColor)),_()},pt=A=>{t.environment.environmentIntensity=A,o.environmentIntensity=A,_()},Dn=A=>{t.render.toneMappingExposure=A,l.toneMappingExposure=A,j&&ve()},Ln=A=>{t.render.aoIntensity=A,j&&ve()},On=A=>{let B=at[A];Et=A,l.toneMapping=B.toneMapping,l.toneMappingExposure=B.toneMappingExposure,t.render.toneMapping=B.toneMapping,t.render.toneMappingExposure=B.toneMappingExposure,ft({hemisphereIntensity:B.hemisphereIntensity,ambientIntensity:B.ambientIntensity}),pt(B.environmentIntensity),te=B.ambientOcclusion,j?ve():ie(),o.traverse(K=>{if(K.userData.source!=="compute")return;let ge=K,Vn=Array.isArray(ge.material)?ge.material:ge.material?[ge.material]:[];for(let yt of Vn)"envMapIntensity"in yt&&(yt.envMapIntensity=B.envMapIntensity)}),_()},Et=t.look,In=()=>oo(Et),{animate:Pn,dispose:Fn,invalidate:ht}=lo(l,o,i,u,c,s,pe,a,t.events.onFrame,m,b,()=>j,C,h,_nullishCoalesce(t.render.onDemand, () => (!0)));_=ht,Pn(),o.up.set(r.x,r.y,r.z),v(),g();let gt=A=>{A.traverse(B=>{let K=B;!K.geometry&&!K.material||(_optionalChain([K, 'access', _60 => _60.geometry, 'optionalAccess', _61 => _61.dispose, 'call', _62 => _62()]),Array.isArray(K.material)?K.material.forEach(Ne):K.material&&Ne(K.material))})},Bn=A=>{A.userData.source="user",o.add(A)},kn=A=>{A.removeFromParent(),gt(A)},Un=()=>{o.children.filter(B=>B.userData.source==="user").forEach(B=>{B.removeFromParent(),gt(B)})};return{scene:o,camera:i,controls:s,renderer:l,cameraController:c,grid:m,gizmo:b,measureTool:M,applyEdges:q,clearEdges:fe,invalidate:ht,setAmbientOcclusion:Sn,setLook:On,setFillLights:ft,setEnvironmentIntensity:pt,setToneMappingExposure:Dn,setAoIntensity:Ln,getMaterialAppearance:In,updateShadowBounds:v,updateGridScale:g,dispose:()=>{d||(d=!0,Fn(),L.dispose(),(b||M)&&(e.removeEventListener("mousedown",F,{capture:!0}),e.removeEventListener("click",D,{capture:!0})),M&&e.removeEventListener("mousemove",G),_optionalChain([M, 'optionalAccess', _63 => _63.dispose, 'call', _64 => _64()]),_optionalChain([C, 'optionalAccess', _65 => _65.dispose, 'call', _66 => _66()]),_optionalChain([b, 'optionalAccess', _67 => _67.dispose, 'call', _68 => _68()]),_optionalChain([m, 'optionalAccess', _69 => _69.dispose, 'call', _70 => _70()]),_optionalChain([j, 'optionalAccess', _71 => _71.dispose, 'call', _72 => _72()]),c.dispose(),s.dispose(),l.dispose(),l.forceContextLoss(),o.traverse(A=>{let B=A;!B.geometry&&!B.material||(_optionalChain([B, 'access', _73 => _73.geometry, 'optionalAccess', _74 => _74.dispose, 'call', _75 => _75()]),Array.isArray(B.material)?B.material.forEach(Ne):B.material&&Ne(B.material))}),_optionalChain([o, 'access', _76 => _76.environment, 'optionalAccess', _77 => _77.dispose, 'call', _78 => _78()]),o.background instanceof w.Texture&&o.background.dispose())},fitToView:L.fitToView,clearSelection:L.clearSelection,addUserGeometry:Bn,removeUserGeometry:kn,clearUserGeometry:Un}};function ao(e){let n=e.sceneScale||"m",r={mm:{cameraDistance:20,near:.1,far:2e3,floorSize:100,lightDistance:10,lightHeight:20,minDistance:.1,shadowSize:100,scaleFactor:1e3},cm:{cameraDistance:20,near:.1,far:2e3,floorSize:100,lightDistance:25,lightHeight:50,minDistance:.1,shadowSize:100,scaleFactor:100},m:{cameraDistance:10,near:.01,far:2e3,floorSize:50,lightDistance:25,lightHeight:50,minDistance:.001,shadowSize:100,scaleFactor:1},inches:{cameraDistance:15,near:.1,far:2e3,floorSize:80,lightDistance:20,lightHeight:40,minDistance:.1,shadowSize:80,scaleFactor:39.37},feet:{cameraDistance:8,near:.1,far:2e3,floorSize:40,lightDistance:15,lightHeight:30,minDistance:.1,shadowSize:60,scaleFactor:3.28084}}[n],a=_nullishCoalesce(e.look, () => (ro)),o=at[a];return{sceneScale:n,look:a,camera:{position:_optionalChain([e, 'access', _79 => _79.camera, 'optionalAccess', _80 => _80.position])||Oe(_nullishCoalesce(_optionalChain([e, 'access', _81 => _81.environment, 'optionalAccess', _82 => _82.sceneUp]), () => (de)),r.cameraDistance*Math.sqrt(3)),fov:_optionalChain([e, 'access', _83 => _83.camera, 'optionalAccess', _84 => _84.fov])||20,near:_optionalChain([e, 'access', _85 => _85.camera, 'optionalAccess', _86 => _86.near])||r.near,far:_optionalChain([e, 'access', _87 => _87.camera, 'optionalAccess', _88 => _88.far])||r.far,target:_optionalChain([e, 'access', _89 => _89.camera, 'optionalAccess', _90 => _90.target])||new w.Vector3(0,0,0),dynamicNear:_nullishCoalesce(_optionalChain([e, 'access', _91 => _91.camera, 'optionalAccess', _92 => _92.dynamicNear]), () => (!0))},lighting:{enableSunlight:_nullishCoalesce(_optionalChain([e, 'access', _93 => _93.lighting, 'optionalAccess', _94 => _94.enableSunlight]), () => (!0)),sunlightIntensity:_nullishCoalesce(_optionalChain([e, 'access', _95 => _95.lighting, 'optionalAccess', _96 => _96.sunlightIntensity]), () => (1)),sunlightPosition:_optionalChain([e, 'access', _97 => _97.lighting, 'optionalAccess', _98 => _98.sunlightPosition])||Ct(_nullishCoalesce(_optionalChain([e, 'access', _99 => _99.environment, 'optionalAccess', _100 => _100.sceneUp]), () => (de)),r.lightDistance,r.lightHeight),ambientLightColor:_optionalChain([e, 'access', _101 => _101.lighting, 'optionalAccess', _102 => _102.ambientLightColor])||new w.Color(4210752),ambientLightIntensity:_nullishCoalesce(_optionalChain([e, 'access', _103 => _103.lighting, 'optionalAccess', _104 => _104.ambientLightIntensity]), () => (o.ambientIntensity)),sunlightColor:_optionalChain([e, 'access', _105 => _105.lighting, 'optionalAccess', _106 => _106.sunlightColor])||16777215,enableHemisphereLight:_nullishCoalesce(_optionalChain([e, 'access', _107 => _107.lighting, 'optionalAccess', _108 => _108.enableHemisphereLight]), () => (o.hemisphereIntensity>0)),hemisphereSkyColor:_nullishCoalesce(_optionalChain([e, 'access', _109 => _109.lighting, 'optionalAccess', _110 => _110.hemisphereSkyColor]), () => (14673663)),hemisphereGroundColor:_nullishCoalesce(_optionalChain([e, 'access', _111 => _111.lighting, 'optionalAccess', _112 => _112.hemisphereGroundColor]), () => (7036754)),hemisphereIntensity:_nullishCoalesce(_optionalChain([e, 'access', _113 => _113.lighting, 'optionalAccess', _114 => _114.hemisphereIntensity]), () => (o.hemisphereIntensity))},environment:{hdrPath:_optionalChain([e, 'access', _115 => _115.environment, 'optionalAccess', _116 => _116.hdrPath])||"/baseHDR.hdr",backgroundColor:_optionalChain([e, 'access', _117 => _117.environment, 'optionalAccess', _118 => _118.backgroundColor])||new w.Color(15790320),enableEnvironmentLighting:_nullishCoalesce(_optionalChain([e, 'access', _119 => _119.environment, 'optionalAccess', _120 => _120.enableEnvironmentLighting]), () => (!0)),sceneUp:_optionalChain([e, 'access', _121 => _121.environment, 'optionalAccess', _122 => _122.sceneUp])||de,showEnvironment:_nullishCoalesce(_optionalChain([e, 'access', _123 => _123.environment, 'optionalAccess', _124 => _124.showEnvironment]), () => (!1)),environmentIntensity:_nullishCoalesce(_optionalChain([e, 'access', _125 => _125.environment, 'optionalAccess', _126 => _126.environmentIntensity]), () => (o.environmentIntensity))},floor:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _127 => _127.floor, 'optionalAccess', _128 => _128.enabled]), () => (!1)),size:_optionalChain([e, 'access', _129 => _129.floor, 'optionalAccess', _130 => _130.size])||r.floorSize,color:_optionalChain([e, 'access', _131 => _131.floor, 'optionalAccess', _132 => _132.color])||new w.Color(8421504),roughness:_nullishCoalesce(_optionalChain([e, 'access', _133 => _133.floor, 'optionalAccess', _134 => _134.roughness]), () => (.7)),metalness:_nullishCoalesce(_optionalChain([e, 'access', _135 => _135.floor, 'optionalAccess', _136 => _136.metalness]), () => (0)),receiveShadow:_nullishCoalesce(_optionalChain([e, 'access', _137 => _137.floor, 'optionalAccess', _138 => _138.receiveShadow]), () => (!0))},render:{enableShadows:_nullishCoalesce(_optionalChain([e, 'access', _139 => _139.render, 'optionalAccess', _140 => _140.enableShadows]), () => (!0)),shadowMapSize:_optionalChain([e, 'access', _141 => _141.render, 'optionalAccess', _142 => _142.shadowMapSize])||2048,antialias:_nullishCoalesce(_optionalChain([e, 'access', _143 => _143.render, 'optionalAccess', _144 => _144.antialias]), () => (!0)),pixelRatio:_optionalChain([e, 'access', _145 => _145.render, 'optionalAccess', _146 => _146.pixelRatio])||Math.min(window.devicePixelRatio,2),toneMapping:_nullishCoalesce(_optionalChain([e, 'access', _147 => _147.render, 'optionalAccess', _148 => _148.toneMapping]), () => (o.toneMapping)),toneMappingExposure:_nullishCoalesce(_optionalChain([e, 'access', _149 => _149.render, 'optionalAccess', _150 => _150.toneMappingExposure]), () => (o.toneMappingExposure)),preserveDrawingBuffer:_nullishCoalesce(_optionalChain([e, 'access', _151 => _151.render, 'optionalAccess', _152 => _152.preserveDrawingBuffer]), () => (!1)),ambientOcclusion:_nullishCoalesce(_optionalChain([e, 'access', _153 => _153.render, 'optionalAccess', _154 => _154.ambientOcclusion]), () => (o.ambientOcclusion)),aoIntensity:_nullishCoalesce(_optionalChain([e, 'access', _155 => _155.render, 'optionalAccess', _156 => _156.aoIntensity]), () => (1)),aoPixelRatio:_nullishCoalesce(_optionalChain([e, 'access', _157 => _157.render, 'optionalAccess', _158 => _158.aoPixelRatio]), () => (1)),onDemand:_nullishCoalesce(_optionalChain([e, 'access', _159 => _159.render, 'optionalAccess', _160 => _160.onDemand]), () => (!0))},controls:{enableDamping:_nullishCoalesce(_optionalChain([e, 'access', _161 => _161.controls, 'optionalAccess', _162 => _162.enableDamping]), () => (!1)),dampingFactor:_optionalChain([e, 'access', _163 => _163.controls, 'optionalAccess', _164 => _164.dampingFactor])||.05,autoRotate:_nullishCoalesce(_optionalChain([e, 'access', _165 => _165.controls, 'optionalAccess', _166 => _166.autoRotate]), () => (!1)),autoRotateSpeed:_optionalChain([e, 'access', _167 => _167.controls, 'optionalAccess', _168 => _168.autoRotateSpeed])||.5,enableZoom:_nullishCoalesce(_optionalChain([e, 'access', _169 => _169.controls, 'optionalAccess', _170 => _170.enableZoom]), () => (!0)),enablePan:_nullishCoalesce(_optionalChain([e, 'access', _171 => _171.controls, 'optionalAccess', _172 => _172.enablePan]), () => (!0)),minDistance:_optionalChain([e, 'access', _173 => _173.controls, 'optionalAccess', _174 => _174.minDistance])||r.minDistance,maxDistance:_optionalChain([e, 'access', _175 => _175.controls, 'optionalAccess', _176 => _176.maxDistance])||1/0},grid:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _177 => _177.grid, 'optionalAccess', _178 => _178.enabled]), () => (!1)),cellSize:_nullishCoalesce(_optionalChain([e, 'access', _179 => _179.grid, 'optionalAccess', _180 => _180.cellSize]), () => (1)),majorEvery:_nullishCoalesce(_optionalChain([e, 'access', _181 => _181.grid, 'optionalAccess', _182 => _182.majorEvery]), () => (10)),cellColor:_nullishCoalesce(_optionalChain([e, 'access', _183 => _183.grid, 'optionalAccess', _184 => _184.cellColor]), () => (8947848)),majorColor:_nullishCoalesce(_optionalChain([e, 'access', _185 => _185.grid, 'optionalAccess', _186 => _186.majorColor]), () => (4473924)),fadeDistance:_nullishCoalesce(_optionalChain([e, 'access', _187 => _187.grid, 'optionalAccess', _188 => _188.fadeDistance]), () => (100)),plane:_nullishCoalesce(_optionalChain([e, 'access', _189 => _189.grid, 'optionalAccess', _190 => _190.plane]), () => (Xe(_nullishCoalesce(_optionalChain([e, 'access', _191 => _191.environment, 'optionalAccess', _192 => _192.sceneUp]), () => (de)))))},gizmo:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _193 => _193.gizmo, 'optionalAccess', _194 => _194.enabled]), () => (!1))},edges:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _195 => _195.edges, 'optionalAccess', _196 => _196.enabled]), () => (!1)),color:_optionalChain([e, 'access', _197 => _197.edges, 'optionalAccess', _198 => _198.color]),darken:_optionalChain([e, 'access', _199 => _199.edges, 'optionalAccess', _200 => _200.darken]),width:_nullishCoalesce(_optionalChain([e, 'access', _201 => _201.edges, 'optionalAccess', _202 => _202.width]), () => (1.5)),thresholdAngle:_nullishCoalesce(_optionalChain([e, 'access', _203 => _203.edges, 'optionalAccess', _204 => _204.thresholdAngle]), () => (44)),distanceFade:_nullishCoalesce(_optionalChain([e, 'access', _205 => _205.edges, 'optionalAccess', _206 => _206.distanceFade]), () => (!0))},measure:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _207 => _207.measure, 'optionalAccess', _208 => _208.enabled]), () => (!1)),snapPixels:_optionalChain([e, 'access', _209 => _209.measure, 'optionalAccess', _210 => _210.snapPixels]),color:_optionalChain([e, 'access', _211 => _211.measure, 'optionalAccess', _212 => _212.color]),labelClassName:_optionalChain([e, 'access', _213 => _213.measure, 'optionalAccess', _214 => _214.labelClassName]),displayUnit:_optionalChain([e, 'access', _215 => _215.measure, 'optionalAccess', _216 => _216.displayUnit]),format:_optionalChain([e, 'access', _217 => _217.measure, 'optionalAccess', _218 => _218.format])},events:{onBackgroundClicked:_optionalChain([e, 'access', _219 => _219.events, 'optionalAccess', _220 => _220.onBackgroundClicked]),onObjectSelected:_optionalChain([e, 'access', _221 => _221.events, 'optionalAccess', _222 => _222.onObjectSelected]),onMeshMetadataClicked:_optionalChain([e, 'access', _223 => _223.events, 'optionalAccess', _224 => _224.onMeshMetadataClicked]),onMeshDoubleClicked:_optionalChain([e, 'access', _225 => _225.events, 'optionalAccess', _226 => _226.onMeshDoubleClicked]),selectionColor:_optionalChain([e, 'access', _227 => _227.events, 'optionalAccess', _228 => _228.selectionColor])||"#ff0000",enableEventHandlers:_nullishCoalesce(_optionalChain([e, 'access', _229 => _229.events, 'optionalAccess', _230 => _230.enableEventHandlers]), () => (!0)),enableKeyboardControls:_nullishCoalesce(_optionalChain([e, 'access', _231 => _231.events, 'optionalAccess', _232 => _232.enableKeyboardControls]), () => (!0)),enableClickToFocus:_nullishCoalesce(_optionalChain([e, 'access', _233 => _233.events, 'optionalAccess', _234 => _234.enableClickToFocus]), () => (!0)),enableDoubleClickZoom:_nullishCoalesce(_optionalChain([e, 'access', _235 => _235.events, 'optionalAccess', _236 => _236.enableDoubleClickZoom]), () => (!0)),onReady:_optionalChain([e, 'access', _237 => _237.events, 'optionalAccess', _238 => _238.onReady]),onFrame:_optionalChain([e, 'access', _239 => _239.events, 'optionalAccess', _240 => _240.onFrame])}}}function Ne(e){for(let n of Object.values(e))n instanceof w.Texture&&n.dispose();e.dispose()}function io(e,n){if(n.isEmpty())return;let t=n.getCenter(new w.Vector3),r=n.getSize(new w.Vector3).length()*.5*1.2,a=e.shadow.camera;a.left=-r,a.right=r,a.top=r,a.bottom=-r,e.target.position.copy(t),e.target.updateMatrixWorld();let o=e.position.distanceTo(t);a.near=Math.max(r*.01,o-r),a.far=o+r,a.updateProjectionMatrix()}function so(e){let n=new w.Scene,t=typeof e.environment.backgroundColor=="string"?new w.Color(e.environment.backgroundColor):e.environment.backgroundColor;return n.background=t||null,n}function lo(e,n,t,r,a,o,i,l,s,c,u,d,p,T,v=!0){let R=null,m=performance.now(),g=!0,b=0,x=500,H=new w.Matrix4,E=new w.Matrix4,f=null,h=()=>{g=!0},y=O=>{O.updateMatrixWorld();let F=f!==O||!H.equals(O.matrixWorld)||!E.equals(O.projectionMatrix);return F&&(f=O,H.copy(O.matrixWorld),E.copy(O.projectionMatrix)),F},C=e.domElement,M=["pointerdown","pointerup","wheel"];if(v)for(let O of M)C.addEventListener(O,h,{passive:!0});let L=()=>{let{width:O,height:F}=i();if(O===0||F===0)return;let S=Math.floor(O*l),D=Math.floor(F*l);(e.domElement.width!==S||e.domElement.height!==D)&&(e.setPixelRatio(l),e.setSize(O,F,!1),t.aspect=O/F,t.updateProjectionMatrix(),a.updateAspect(O,F),_optionalChain([d, 'optionalCall', _241 => _241(), 'optionalAccess', _242 => _242.setSize, 'call', _243 => _243(O,F,l)]),_optionalChain([p, 'optionalAccess', _244 => _244.setSize, 'call', _245 => _245(O,F)]),h())},I=function(){R=requestAnimationFrame(I);let O=performance.now(),F=(O-m)/1e3;m=O,L(),(o.enableDamping||o.autoRotate)&&o.update(),c&&c.update(r().position),u&&u.update(F),T&&T.update(),_optionalChain([s, 'optionalCall', _246 => _246(F)]);let S=r();if(v){if(!(g||y(S)||O-b>=x))return;g=!1,b=O}let D=_optionalChain([d, 'optionalCall', _247 => _247()]);D?(D.setCamera(S),D.render(F)):e.render(n,S),p&&p.render(n,S),u&&u.render(e)};return{animate:I,dispose:()=>{if(R!==null&&(cancelAnimationFrame(R),R=null),v)for(let O of M)C.removeEventListener(O,h)},invalidate:h}}function co(e,n,t,r){t.environment.enableEnvironmentLighting?new (0, _HDRLoaderjs.HDRLoader)().load(t.environment.hdrPath||"/baseHDR.hdr",function(a){if(r()){a.dispose();return}if(!_optionalChain([a, 'optionalAccess', _248 => _248.image])){_chunkH3FZW6OXcjs.e.call(void 0, ).warn("HDR loaded without image data; skipping environment map."),_optionalChain([a, 'optionalAccess', _249 => _249.dispose, 'call', _250 => _250()]),_optionalChain([t, 'access', _251 => _251.events, 'access', _252 => _252.onReady, 'optionalCall', _253 => _253()]);return}a.mapping=w.EquirectangularReflectionMapping;let o=new w.PMREMGenerator(n);o.compileEquirectangularShader();let i=o.fromEquirectangular(a).texture;o.dispose(),e.environment=i,e.environmentIntensity=_nullishCoalesce(t.environment.environmentIntensity, () => (1));let l=At(_nullishCoalesce(t.environment.sceneUp, () => (de)));e.environmentRotation.copy(l),t.environment.showEnvironment?(e.background=a,e.backgroundRotation.copy(l)):a.dispose(),_optionalChain([t, 'access', _254 => _254.events, 'access', _255 => _255.onReady, 'optionalCall', _256 => _256()])},void 0,function(a){r()||(_chunkH3FZW6OXcjs.e.call(void 0, ).warn("HDR texture could not be loaded, falling back to basic lighting:",a),_optionalChain([t, 'access', _257 => _257.events, 'access', _258 => _258.onReady, 'optionalCall', _259 => _259()]))}):_optionalChain([t, 'access', _260 => _260.events, 'access', _261 => _261.onReady, 'optionalCall', _262 => _262()])}function uo(e,n){let t=new w.AmbientLight(n.lighting.ambientLightColor,n.lighting.ambientLightIntensity);e.add(t);let r=null;if(n.lighting.enableHemisphereLight){r=new w.HemisphereLight(n.lighting.hemisphereSkyColor,n.lighting.hemisphereGroundColor,n.lighting.hemisphereIntensity);let i=_nullishCoalesce(n.environment.sceneUp, () => (de));r.position.copy(i),e.add(r)}if(!n.lighting.enableSunlight)return{ambient:t,hemisphere:r,sun:null};let a=new w.DirectionalLight(_nullishCoalesce(n.lighting.sunlightColor, () => (16777215)),n.lighting.sunlightIntensity),o=n.lighting.sunlightPosition;return o&&a.position.set(o.x,o.y,o.z),n.render.enableShadows?(a.castShadow=!0,a.shadow.mapSize.width=n.render.shadowMapSize||2048,a.shadow.mapSize.height=n.render.shadowMapSize||2048,a.shadow.bias=-1e-4,a.shadow.normalBias=.02,a.shadow.radius=4,e.add(a),e.add(a.target),{ambient:t,hemisphere:r,sun:a}):(e.add(a),{ambient:t,hemisphere:r,sun:null})}function mo(e,n){let t=n.floor.size,r=new w.PlaneGeometry(t,t),a=typeof n.floor.color=="string"?new w.Color(n.floor.color):n.floor.color,o=new w.MeshStandardMaterial({color:a,roughness:n.floor.roughness,metalness:n.floor.metalness,side:w.DoubleSide}),i=new w.Mesh(r,o);i.userData.id="floor",i.name="floor";let l=(_optionalChain([n, 'access', _263 => _263.environment, 'optionalAccess', _264 => _264.sceneUp])||de).clone().normalize();i.quaternion.setFromUnitVectors(new w.Vector3(0,0,1),l),i.position.set(0,0,0),n.floor.receiveShadow&&n.render.enableShadows&&(i.receiveShadow=!0),e.add(i)}function fo(e,n){let t=n.parentElement,r=t?t.clientWidth:window.innerWidth,a=t?t.clientHeight:window.innerHeight,o=new w.PerspectiveCamera(e.camera.fov,r/a,e.camera.near,e.camera.far),i=e.camera.position;return i&&o.position.set(i.x,i.y,i.z),o}function po(e,n,t){let r=new w.WebGLRenderer({antialias:n.render.antialias,canvas:e,alpha:!0,powerPreference:"high-performance",preserveDrawingBuffer:n.render.preserveDrawingBuffer,logarithmicDepthBuffer:!1}),a=e.parentElement,o=a?a.clientWidth:window.innerWidth,i=a?a.clientHeight:window.innerHeight;return a&&(e.style.width="100%",e.style.height="100%",e.style.display="block"),r.setSize(o,i,!1),r.setPixelRatio(t),n.render.enableShadows&&(r.shadowMap.enabled=!0,r.shadowMap.type=w.VSMShadowMap),r.toneMapping=n.render.toneMapping,r.toneMappingExposure=_nullishCoalesce(n.render.toneMappingExposure, () => (1)),r.outputColorSpace=w.SRGBColorSpace,r.sortObjects=!0,r}function Eo(e,n,t,r){let a=new Set,o=new Map,i=new w.Raycaster,l=new w.Vector2,s=new w.Vector2,c=()=>t.getActiveCamera(),u=E=>{let f=E;for(;f;){if(!f.visible)return!1;f=f.parent}return!0},d=()=>{let E=ce(n);if(E.isEmpty()){_chunkH3FZW6OXcjs.e.call(void 0, ).warn("No objects to fit to view");return}t.frameBounds(E,!1)},p=typeof r.events.selectionColor=="string"?new w.Color(r.events.selectionColor):r.events.selectionColor instanceof w.Color?r.events.selectionColor:new w.Color("#ff0000"),T=()=>{a.forEach(E=>{let f=E;if(o.has(E)){let h=o.get(E),y=f.material;y instanceof w.Material?y.dispose():Array.isArray(y)&&y.forEach(M=>M.dispose()),f.material=h,o.delete(E);let C=E;for(;C.parent;)C=C.parent;C!==n&&(h instanceof w.Material?h.dispose():h.forEach(M=>M.dispose()))}}),a.clear()},v=E=>{let f=E;if(!(f.material instanceof w.Material))return!1;o.set(E,f.material);let h=f.material.clone();return E instanceof w.Mesh&&"emissive"in h?h.emissive=p.clone():"color"in h&&(h.color=p.clone()),f.material=h,!0},R=()=>{let E=ce(n),f=E.isEmpty()?1:E.getSize(new w.Vector3).length();i.params.Points.threshold=f*.01},m=E=>{s.set(E.clientX,E.clientY)},g=E=>{let f=new w.Vector2(E.clientX,E.clientY);if(s.distanceTo(f)>5)return;let h=e.getBoundingClientRect();l.x=(E.clientX-h.left)/h.width*2-1,l.y=-((E.clientY-h.top)/h.height)*2+1,R(),i.setFromCamera(l,c());let y=i.intersectObjects(n.children,!0).filter(C=>u(C.object));if(y.length>0){let C=y[0].object;a.has(C)||(T(),a.add(C),v(C),_optionalChain([r, 'access', _265 => _265.events, 'optionalAccess', _266 => _266.onObjectSelected, 'optionalCall', _267 => _267(C)]),C instanceof w.Mesh&&Object.keys(C.userData).length>0&&_optionalChain([r, 'access', _268 => _268.events, 'optionalAccess', _269 => _269.onMeshMetadataClicked, 'optionalCall', _270 => _270(C.userData)]))}else T(),_optionalChain([r, 'access', _271 => _271.events, 'optionalAccess', _272 => _272.onBackgroundClicked, 'optionalCall', _273 => _273({x:l.x,y:l.y})])},b=E=>{let f=e.getBoundingClientRect();l.x=(E.clientX-f.left)/f.width*2-1,l.y=-((E.clientY-f.top)/f.height)*2+1,R(),i.setFromCamera(l,c());let h=i.intersectObjects(n.children,!0).filter(M=>u(M.object));if(h.length===0)return;let y=h[0].object;if(_optionalChain([r, 'access', _274 => _274.events, 'optionalAccess', _275 => _275.onMeshDoubleClicked, 'optionalCall', _276 => _276(y)]),!_optionalChain([r, 'access', _277 => _277.events, 'optionalAccess', _278 => _278.enableDoubleClickZoom]))return;let C=new w.Box3().setFromObject(y);C.isEmpty()||t.frameBounds(C,!0)},x=E=>{if(_optionalChain([r, 'access', _279 => _279.events, 'optionalAccess', _280 => _280.enableKeyboardControls]))switch(E.key.toLowerCase()){case"f":E.preventDefault(),d();break;case"escape":E.preventDefault(),T();break;case" ":E.preventDefault(),d();break}};return _optionalChain([r, 'access', _281 => _281.events, 'optionalAccess', _282 => _282.enableClickToFocus])&&(e.addEventListener("mousedown",m),e.addEventListener("click",g),e.addEventListener("dblclick",b)),_optionalChain([r, 'access', _283 => _283.events, 'optionalAccess', _284 => _284.enableKeyboardControls])&&(e.setAttribute("tabindex","0"),e.addEventListener("keydown",x)),{dispose:()=>{e.removeEventListener("mousedown",m),e.removeEventListener("click",g),e.removeEventListener("dblclick",b),e.removeEventListener("keydown",x),T()},fitToView:d,clearSelection:T}}function ho(e,n,t){let r=new (0, _OrbitControlsjs.OrbitControls)(e,n),a=t.camera.target;return a&&r.target.set(a.x,a.y,a.z),r.enableDamping=t.controls.enableDamping||!1,r.dampingFactor=t.controls.dampingFactor||.05,r.autoRotate=t.controls.autoRotate||!1,r.autoRotateSpeed=t.controls.autoRotateSpeed||.5,r.enableZoom=_nullishCoalesce(t.controls.enableZoom, () => (!0)),r.enablePan=_nullishCoalesce(t.controls.enablePan, () => (!0)),r.minDistance=t.controls.minDistance||.001,r.maxDistance=t.controls.maxDistance||1/0,r.screenSpacePanning=!1,r.maxPolarAngle=Math.PI,r.update(),r}var Di=["technical","studio","showcase"];function je(e,n,t,r=!0){return{x:e,y:n,z:t}}var To="#ffffff",an=12,Ro=4e-4,xo=12,vo=.05;function sn(e,n={}){if(!e||e.length===0)return[];let{rhino:t,applyTransforms:r=!0}=n,a=[];for(let o of e)switch(o.kind){case"curve":{let i=Mo(o,t,r);i&&a.push(i);break}case"point":{let i=Ho(o,r);i&&a.push(i);break}default:{let l=o;_chunkH3FZW6OXcjs.e.call(void 0, ).warn(`Skipping unknown display item kind: ${String(l.kind)}`);break}}return a}var wo=2;function Mo(e,n,t){if(!n)return _chunkH3FZW6OXcjs.e.call(void 0, ).warn("No rhino3dm instance provided; skipping curve display item."),null;let r=Co(e.json,n);if(!r)return null;let a;try{a=Ao(r,t)}catch(d){return _chunkH3FZW6OXcjs.e.call(void 0, ).warn("Failed to tessellate curve display item; skipping.",d),null}finally{Se(r)}if(a.length<2)return null;let o=[];for(let d of a)o.push(d.x,d.y,d.z);let i=new _LineGeometryjs.LineGeometry;i.setPositions(o);let l=ln(e.color,e.opacity),s=new (0, _LineMaterialjs.LineMaterial)({color:l.color}),c=s;c.linewidth=_nullishCoalesce(e.width, () => (wo)),c.transparent=l.transparent,c.opacity=l.opacity;let u=new (0, _Line2js.Line2)(i,s);return u.computeLineDistances(),u.name=e.name,u.userData={source:"compute",id:e.id,layer:e.layer,kind:"curve",metadata:e.metadata},u}function Ho(e,n){let{position:t}=e;if(!t||typeof t.X!="number"||!Number.isFinite(t.X)||typeof t.Y!="number"||!Number.isFinite(t.Y)||typeof t.Z!="number"||!Number.isFinite(t.Z))return _chunkH3FZW6OXcjs.e.call(void 0, ).warn(`Skipping point display item with missing or non-finite position (id: ${String(e.id)}).`),null;let{x:r,y:a,z:o}=je(t.X,t.Y,t.Z,n),i=new Q.BufferGeometry;i.setAttribute("position",new Q.Float32BufferAttribute([r,a,o],3));let l=new Q.PointsMaterial({...ln(e.color,e.opacity),size:6,sizeAttenuation:!1}),s=new Q.Points(i,l);return s.name=e.name,s.userData={source:"compute",id:e.id,layer:e.layer,kind:"point",metadata:e.metadata},s}function Se(e){_optionalChain([e, 'optionalAccess', _285 => _285.delete, 'optionalCall', _286 => _286()])}function Co(e,n){try{let t=JSON.parse(e),r=n.CommonObject.decode(t);return r&&typeof r.pointAt=="function"?r:(Se(r),_chunkH3FZW6OXcjs.e.call(void 0, ).warn("Decoded display-item JSON is not a curve; skipping."),null)}catch(t){return _chunkH3FZW6OXcjs.e.call(void 0, ).warn("Failed to decode curve display item JSON:",t),null}}function Ao(e,n){let t=So(e,n);return t||Do(e,n)}function So(e,n){if(!e.isPolyline())return null;let t=e.tryGetPolyline(),r=Array.isArray(t)?t[1]:t;if(!r||typeof r.count!="number"||r.count<2)return Se(r),null;let a=[];for(let o=0;o<r.count;o++){let i=r.get(o),{x:l,y:s,z:c}=je(i[0],i[1],i[2],n);a.push(new Q.Vector3(l,s,c))}return Se(r),a}function Do(e,n){let t=e.domain,r=t[0],o=t[1]-r,i=d=>{let p=e.pointAt(d),{x:T,y:v,z:R}=je(p[0],p[1],p[2],n);return new Q.Vector3(T,v,R)},l=Lo(e),s=r,c=i(r),u=[c];for(let d=0;d<an;d++){let p=r+o*(d+1)/an,T=i(p);it(s,c,p,T,i,l,xo,u),u.push(T),s=p,c=T}return u}function it(e,n,t,r,a,o,i,l){if(i<=0)return;let s=(e+t)/2,c=a(s),u=Io(c,n,r),d=Oo(n,c,r);u<=o&&d<=vo||(it(e,n,s,c,a,o,i-1,l),l.push(c),it(s,c,t,r,a,o,i-1,l))}function Lo(e){let n=e.getBoundingBox(),t=n.min,r=n.max;Se(n);let a=Math.hypot(r[0]-t[0],r[1]-t[1],r[2]-t[2]);return Math.max(a*Ro,1e-6)}function Oo(e,n,t){let r=n.x-e.x,a=n.y-e.y,o=n.z-e.z,i=t.x-n.x,l=t.y-n.y,s=t.z-n.z,c=Math.sqrt(r*r+a*a+o*o),u=Math.sqrt(i*i+l*l+s*s);if(c===0||u===0)return 0;let d=r*i+a*l+o*s,p=Math.max(-1,Math.min(1,d/(c*u)));return Math.acos(p)}function Io(e,n,t){let r=t.x-n.x,a=t.y-n.y,o=t.z-n.z,i=r*r+a*a+o*o;if(i===0)return e.distanceTo(n);let l=e.x-n.x,s=e.y-n.y,c=e.z-n.z,u=Math.max(0,Math.min(1,(l*r+s*a+c*o)/i)),d=l-r*u,p=s-a*u,T=c-o*u;return Math.sqrt(d*d+p*p+T*T)}function ln(e,n){let t=_nullishCoalesce(n, () => (1));return{color:new Q.Color(_nullishCoalesce(e, () => (To))),transparent:t<1,opacity:t}}var _fflate = require('fflate');var cn=1096174675,Fo= exports.G =1515605075,un= exports.H =3,dn= exports.I =1,lt= exports.J =1,Bo= exports.K =2,ko= exports.L =4,Uo= exports.M =8,Vo= exports.N =16,Gi= exports.O =0,_o= exports.P =1,mn=12,fn=56,zo=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1;function ct(e){let n=ut(e),t;n.isFloat32?t=n.vertexData:n.deltaEncoded?t=Ko(n.vertexData):t=n.vertexData;let r=n.indexData;return n.deltaEncoded&&(r=r instanceof Uint16Array?Zo(r):Jo(r)),Xo(r,n.vertexCount),{metadata:n.metadata,flags:n.flags,vertices:t,indices:r,origin:n.origin,scale:n.scale,uvs:n.uvs,colors:n.colors}}function ut(e){if(!zo)throw new (0, _chunkH3FZW6OXcjs.d)("SLVA parsing requires a little-endian host: the zero-copy geometry readers view the wire bytes in host byte order.",_chunkH3FZW6OXcjs.c.ENVIRONMENT_ERROR);let n=Wo(jo(e)),t=new DataView(n.buffer,n.byteOffset,n.byteLength);if(n.byteLength<mn)throw X("Blob too small to contain SLVA header.",{expectedBytes:mn,availableBytes:n.byteLength});let r=0,a=t.getUint32(r,!0);if(r+=4,a!==cn)throw X(`Invalid SLVA magic: 0x${a.toString(16)}`,{expectedMagic:`0x${cn.toString(16)}`,actualMagic:`0x${a.toString(16)}`});let o=t.getUint32(r,!0);if(r+=4,o<dn||o>un)throw X(`Unsupported SLVA version: ${o}`,{minSupportedVersion:dn,maxSupportedVersion:un,actualVersion:o});let i=t.getUint32(r,!0);if(r+=4,r+i>n.byteLength)throw X("Insufficient data to read metadata JSON.",{expectedBytes:i,availableBytes:n.byteLength-r,offset:r});let l=n.subarray(r,r+i);r+=i;let s;try{s=JSON.parse($o(l))}catch(F){throw X(`Failed to parse metadata JSON: ${F instanceof Error?F.message:String(F)}`,{metadataLen:i})}if(r+fn>n.byteLength)throw X("Insufficient data to read geometry header.",{expectedBytes:fn,availableBytes:n.byteLength-r,offset:r});let c=t.getUint32(r,!0);r+=4;let u=t.getFloat64(r,!0);r+=8;let d=t.getFloat64(r,!0);r+=8;let p=t.getFloat64(r,!0);r+=8;let T=t.getFloat64(r,!0);r+=8;let v=t.getFloat64(r,!0);r+=8;let R=t.getFloat64(r,!0);r+=8;let m=t.getUint32(r,!0);r+=4;let g=(c&lt)!==0,b=(c&ko)!==0,x=m*3,E=x*(g?4:2);if(r+E>n.byteLength)throw X("Insufficient data to read vertices.",{expectedBytes:E,availableBytes:n.byteLength-r,offset:r,useFloat32:g,vertexCount:m});let f=n.byteOffset+r,h;if(g?h=En(n.buffer,f,x):b?h=st(n.buffer,f,x):h=qo(n.buffer,f,x),r+=E,r+4>n.byteLength)throw X("Insufficient data to read index count.",{expectedBytes:4,availableBytes:n.byteLength-r,offset:r});let y=t.getUint32(r,!0);r+=4;let C=(c&Bo)!==0,L=y*(C?2:4);if(r+L>n.byteLength)throw X("Insufficient data to read indices.",{expectedBytes:L,availableBytes:n.byteLength-r,offset:r,indexCount:y,useUint16Indices:C});let I=C?st(n.buffer,n.byteOffset+r,y):Yo(n.buffer,n.byteOffset+r,y);r+=L;let k=null;if((c&Uo)!==0){let F=Go(n,t,r,m,b);k=F.uvs,r=F.offset}let O=null;return(c&Vo)!==0&&(O=No(n,r,m,b)),{metadata:s,flags:c,vertexData:h,indexData:I,isFloat32:g,deltaEncoded:b,vertexCount:m,origin:[u,d,p],scale:[T,v,R],uvs:k,colors:O}}var pn=36;function Go(e,n,t,r,a){if(t+pn>e.byteLength)throw X("Insufficient data to read UV chunk header.",{expectedBytes:pn,availableBytes:e.byteLength-t,offset:t});let o=n.getUint32(t,!0);t+=4;let i=n.getFloat64(t,!0);t+=8;let l=n.getFloat64(t,!0);t+=8;let s=n.getFloat64(t,!0);t+=8;let c=n.getFloat64(t,!0);t+=8;let u=r*2,d=o===_o,p=u*(d?4:2);if(t+p>e.byteLength)throw X("Insufficient data to read UV chunk.",{expectedBytes:p,availableBytes:e.byteLength-t,offset:t,uvFormat:o,vertexCount:r});let T=e.byteOffset+t,v;if(d)v=En(e.buffer,T,u).slice();else{let R=st(e.buffer,T,u);v=new Float32Array(u);let m=0,g=0;for(let b=0;b<u;b+=2)a?(m=m+le(R[b])&65535,g=g+le(R[b+1])&65535):(m=R[b],g=R[b+1]),v[b]=i+m*s,v[b+1]=l+g*c}return{uvs:v,offset:t+p}}function No(e,n,t,r){let a=t*3;if(n+a>e.byteLength)throw X("Insufficient data to read vertex-color chunk.",{expectedBytes:a,availableBytes:e.byteLength-n,offset:n,vertexCount:t});let o=e.subarray(n,n+a);if(!r)return o.slice();let i=new Uint8Array(a),l=0,s=0,c=0;for(let u=0;u<a;u+=3)l=l+le(o[u])&255,s=s+le(o[u+1])&255,c=c+le(o[u+2])&255,i[u]=l,i[u+1]=s,i[u+2]=c;return i}function jo(e){return typeof e=="string"?_chunkH3FZW6OXcjs.j.call(void 0, e):e instanceof Uint8Array?e:new Uint8Array(e)}function Wo(e){if(e.byteLength<8)return e;let n=new DataView(e.buffer,e.byteOffset,e.byteLength);if(n.getUint32(0,!0)!==Fo)return e;let t=n.getUint32(4,!0),r=e.subarray(8),a=Math.max(r.byteLength*1032+1024,1<<20);if(t>a)throw X("SLVZ header declares an implausible uncompressed length",{uncompressedLen:t,deflatedBytes:r.byteLength,maxPlausibleLen:a});let o;try{o=_fflate.inflateSync.call(void 0, r,{out:new Uint8Array(t+1)})}catch(i){throw X(`Failed to inflate SLVZ blob: ${i instanceof Error?i.message:String(i)}`,{uncompressedLen:t,deflatedBytes:r.byteLength})}if(o.byteLength!==t)throw X("SLVZ payload inflated to a different size than the header declares.",{declaredLen:t,actualLen:o.byteLength,deflatedBytes:r.byteLength});return o}function $o(e){if(typeof TextDecoder<"u")return new TextDecoder("utf-8").decode(e);if(typeof globalThis.Buffer<"u")return globalThis.Buffer.from(e).toString("utf-8");throw new (0, _chunkH3FZW6OXcjs.d)("No UTF-8 decoder available in this environment.",_chunkH3FZW6OXcjs.c.INVALID_STATE)}function qo(e,n,t){if(t===0)return new Int16Array(0);if(n%2===0)return new Int16Array(e,n,t);let r=new Uint8Array(t*2);return r.set(new Uint8Array(e,n,t*2)),new Int16Array(r.buffer)}function En(e,n,t){if(t===0)return new Float32Array(0);if(n%4===0)return new Float32Array(e,n,t);let r=new Uint8Array(t*4);return r.set(new Uint8Array(e,n,t*4)),new Float32Array(r.buffer)}function st(e,n,t){if(t===0)return new Uint16Array(0);if(n%2===0)return new Uint16Array(e,n,t);let r=new Uint8Array(t*2);return r.set(new Uint8Array(e,n,t*2)),new Uint16Array(r.buffer)}function Yo(e,n,t){if(t===0)return new Uint32Array(0);if(n%4===0)return new Uint32Array(e,n,t);let r=new Uint8Array(t*4);return r.set(new Uint8Array(e,n,t*4)),new Uint32Array(r.buffer)}function Xo(e,n){if(e.length!==0&&!(e instanceof Uint16Array&&n>65535)){for(let t=0;t<e.length;t++)if(e[t]>=n)throw X("Index out of range of vertexCount.",{indexPosition:t,indexValue:e[t],vertexCount:n})}}function le(e){return e>>>1^-(e&1)}function Ko(e){let n=new Int16Array(e.length),t=0,r=0,a=0;for(let o=0;o<e.length;o+=3)t=t+le(e[o])<<16>>16,r=r+le(e[o+1])<<16>>16,a=a+le(e[o+2])<<16>>16,n[o]=t,n[o+1]=r,n[o+2]=a;return n}function Zo(e){let n=new Uint16Array(e.length),t=0;for(let r=0;r<e.length;r++)t=t+le(e[r])&65535,n[r]=t;return n}function Jo(e){let n=new Uint32Array(e.length),t=0;for(let r=0;r<e.length;r++)t=t+le(e[r])>>>0,n[r]=t;return n}function X(e,n){return new (0, _chunkH3FZW6OXcjs.d)(e,_chunkH3FZW6OXcjs.c.VALIDATION_ERROR,{context:n})}var hn=256*1024*1024,We=1024,me=new Map,dt=0;function gn(e,n){let t=2166136261,r=a=>{t^=a,t=Math.imul(t,16777619)};for(let a=0;a<n.length;a++)r(n.charCodeAt(a));for(let a of e){if(!a){r(57005);continue}let o=a.byteLength;if(r(o),(a.byteOffset&3)===0&&(o&3)===0){let i=new Uint32Array(a.buffer,a.byteOffset,o>>2),l=Math.min(We,i.length);for(let s=0;s<l;s++)r(i[s]);for(let s=Math.max(l,i.length-We);s<i.length;s++)r(i[s])}else{let i=new Uint8Array(a.buffer,a.byteOffset,o),l=Math.min(We*4,i.length);for(let s=0;s<l;s++)r(i[s]);for(let s=Math.max(l,i.length-We*4);s<i.length;s++)r(i[s])}}return`${(t>>>0).toString(36)}:${e.length}`}function Qo(e){let n=_nullishCoalesce(_optionalChain([e, 'access', _287 => _287.index, 'optionalAccess', _288 => _288.array, 'access', _289 => _289.byteLength]), () => (0));for(let t of Object.values(e.attributes))n+=t.array.byteLength;return n}function $e(e){let n=me.get(e);if(n)return me.delete(e),me.set(e,n),n.geometry}function qe(e,n){let t=Qo(n);if(!(t>hn||(n.userData[Ie]=!0,me.get(e))))for(me.set(e,{geometry:n,bytes:t}),dt+=t;dt>hn&&me.size>1;){let a=me.keys().next().value,o=me.get(a);me.delete(a),dt-=o.bytes,delete o.geometry.userData[Ie],o.geometry.dispose()}}function ea(e){let{isFloat32:n,deltaEncoded:t,origin:r,scale:a,uvs:o,colors:i,jobs:l}=e,s=m=>m>>>1^-(m&1),c;if(n)c=e.vertexData;else{let m;if(t){let h=e.vertexData;m=new Int16Array(h.length);let y=0,C=0,M=0;for(let L=0;L<h.length;L+=3)y=y+s(h[L])<<16>>16,C=C+s(h[L+1])<<16>>16,M=M+s(h[L+2])<<16>>16,m[L]=y,m[L+1]=C,m[L+2]=M}else m=e.vertexData;c=new Float32Array(m.length);let g=r[0],b=r[1],x=r[2],H=a[0],E=a[1],f=a[2];for(let h=0;h<m.length;h+=3)c[h]=g+(m[h]+32767)*H,c[h+1]=b+(m[h+1]+32767)*E,c[h+2]=x+(m[h+2]+32767)*f}let u;if(t){let m=e.indexData;if(m instanceof Uint16Array){let g=new Uint16Array(m.length),b=0;for(let x=0;x<m.length;x++)b=b+s(m[x])&65535,g[x]=b;u=g}else{let g=new Uint32Array(m.length),b=0;for(let x=0;x<m.length;x++)b=b+s(m[x])>>>0,g[x]=b;u=g}}else u=e.indexData;let d=c.length/3;for(let m=0;m<u.length;m++)if(u[m]>=d)throw new Error(`Index ${u[m]} out of range of vertexCount ${d}`);let p=1024,T=(m,g)=>{let b=2166136261,x=H=>{b^=H,b=Math.imul(b,16777619)};for(let H=0;H<g.length;H++)x(g.charCodeAt(H));for(let H of m){if(!H){x(57005);continue}let E=H.byteLength;if(x(E),(H.byteOffset&3)===0&&(E&3)===0){let f=new Uint32Array(H.buffer,H.byteOffset,E>>2),h=Math.min(p,f.length);for(let y=0;y<h;y++)x(f[y]);for(let y=Math.max(h,f.length-p);y<f.length;y++)x(f[y])}else{let f=new Uint8Array(H.buffer,H.byteOffset,E),h=Math.min(p*4,f.length);for(let y=0;y<h;y++)x(f[y]);for(let y=Math.max(h,f.length-p*4);y<f.length;y++)x(f[y])}}return`${(b>>>0).toString(36)}:${m.length}`},v=(m,g)=>{let b=[],x=m;for(let H of g){x+=`|${H.vertexStart},${H.vertexCount},${H.indexStart},${H.indexCount}`;let E=H.vertexStart*3,f=E+H.vertexCount*3;b.push(c.subarray(E,f)),b.push(u.subarray(H.indexStart,H.indexStart+H.indexCount)),b.push(o?o.subarray(H.vertexStart*2,(H.vertexStart+H.vertexCount)*2):null),b.push(i?i.subarray(E,f):null)}return T(b,x)},R=[];for(let m of l){let g=0,b=0;for(let M of m.windows)g+=M.vertexCount,b+=M.indexCount;let x=new Float32Array(g*3),H=new Uint32Array(b),E=o?new Float32Array(g*2):null,f=i?new Uint8Array(g*3):null,h=0,y=0;for(let M of m.windows){let L=M.vertexStart*3;x.set(c.subarray(L,L+M.vertexCount*3),h*3),E&&o&&E.set(o.subarray(M.vertexStart*2,(M.vertexStart+M.vertexCount)*2),h*2),f&&i&&f.set(i.subarray(L,L+M.vertexCount*3),h*3);let I=M.vertexStart,k=M.vertexStart+M.vertexCount,O=h-M.vertexStart;for(let F=0;F<M.indexCount;F++){let S=u[M.indexStart+F];if(S<I||S>=k)throw new Error(`Index ${S} outside vertex window [${I}, ${k})`);H[y+F]=S+O}h+=M.vertexCount,y+=M.indexCount}let C=new Float32Array(g*3);for(let M=0;M<H.length;M+=3){let L=H[M]*3,I=H[M+1]*3,k=H[M+2]*3,O=x[k]-x[I],F=x[k+1]-x[I+1],S=x[k+2]-x[I+2],D=x[L]-x[I],G=x[L+1]-x[I+1],_=x[L+2]-x[I+2],q=F*_-S*G,Y=S*D-O*_,fe=O*G-F*D;C[L]+=q,C[L+1]+=Y,C[L+2]+=fe,C[I]+=q,C[I+1]+=Y,C[I+2]+=fe,C[k]+=q,C[k+1]+=Y,C[k+2]+=fe}for(let M=0;M<C.length;M+=3){let L=C[M],I=C[M+1],k=C[M+2],O=Math.sqrt(L*L+I*I+k*k)||1;C[M]=L/O,C[M+1]=I/O,C[M+2]=k/O}R.push({key:v(m.kind,m.windows),positions:x,normals:C,indices:H,uvs:E,colors:f})}return R}function yn(){return[`const assemble = ${ea.toString()};`,"self.onmessage = (event) => {"," const { id, input } = event.data;"," try {"," const geometries = assemble(input);"," const transfer = [];"," for (const g of geometries) {"," transfer.push(g.positions.buffer, g.normals.buffer, g.indices.buffer);"," if (g.uvs) transfer.push(g.uvs.buffer);"," if (g.colors) transfer.push(g.colors.buffer);"," }"," self.postMessage({ id, geometries }, transfer);"," } catch (error) {"," self.postMessage({ id, error: String((error && error.message) || error) });"," }","};"].join(`
112
+ `)}async function es(e,n){let{debug:t=!1}=_nullishCoalesce(n, () => ({})),r=t?performance.now():0,a,o=performance.now();try{a=JSON.parse(e)}catch(l){return _chunkH3FZW6OXcjs.e.call(void 0, ).error("Error parsing mesh batch envelope JSON:",l),[]}let i=performance.now()-o;return await mt(a,n,{parseTime:i,perfStart:r})}async function mt(e,n,t){let{mergeByMaterial:r=!0,applyTransforms:a=!0,debug:o=!1,material:i}=_nullishCoalesce(n, () => ({})),{parseTime:l=0,perfStart:s=o?performance.now():0}=_nullishCoalesce(t, () => ({}));if(!e.compressedData)return[];let c=await vn(e.compressedData,{mergeByMaterial:r,applyTransforms:a,debug:o,material:i,fallback:{materials:e.materials,groups:e.groups,sourceComponentId:e.sourceComponentId}});if(c)return c;let u=performance.now(),d=ct(e.compressedData),p=performance.now()-u,T=o?fa(e.compressedData):0;return bn(d,{mergeByMaterial:r,applyTransforms:a,debug:o,material:i,parseTime:l,decodeTime:p,perfStart:s,blobBytes:T,fallback:{materials:e.materials,groups:e.groups,sourceComponentId:e.sourceComponentId}})}async function ts(e,n){let{mergeByMaterial:t=!0,applyTransforms:r=!0,debug:a=!1,material:o}=_nullishCoalesce(n, () => ({})),i=a?performance.now():0,l=await vn(e,{mergeByMaterial:t,applyTransforms:r,debug:a,material:o});if(l)return l;let s=performance.now(),c=ct(e),u=performance.now()-s,d=e.byteLength;return bn(c,{mergeByMaterial:t,applyTransforms:r,debug:a,material:o,parseTime:0,decodeTime:u,perfStart:i,blobBytes:d})}function bn(e,n){let{mergeByMaterial:t,applyTransforms:r,debug:a,material:o,parseTime:i,decodeTime:l,perfStart:s,blobBytes:c,fallback:u}=n,d=_nullishCoalesce(_nullishCoalesce(e.metadata.materials, () => (_optionalChain([u, 'optionalAccess', _290 => _290.materials]))), () => ([])),p=_nullishCoalesce(_nullishCoalesce(e.metadata.groups, () => (_optionalChain([u, 'optionalAccess', _291 => _291.groups]))), () => ([])),T=_nullishCoalesce(_optionalChain([u, 'optionalAccess', _292 => _292.sourceComponentId]), () => (e.metadata.sourceComponentId)),v=(e.flags&lt)!==0;Tn(p,d.length,e.vertices.length/3,e.indices.length);let R=v?na(e.vertices,r):ta(e.vertices,e.origin,e.scale,r);if(a){let H=e.vertices.byteLength+e.indices.byteLength;_chunkH3FZW6OXcjs.e.call(void 0, ).debug("Mesh Batch Stats:"),_chunkH3FZW6OXcjs.e.call(void 0, ).debug(` Materials: ${d.length} | Groups: ${p.length}`),_chunkH3FZW6OXcjs.e.call(void 0, ).debug(` Vertices: ${e.vertices.length/3} | Indices: ${e.indices.length}`),_chunkH3FZW6OXcjs.e.call(void 0, ).debug(` Format: ${v?"float32":"int16 quantized"}`),_chunkH3FZW6OXcjs.e.call(void 0, ).debug(` Blob: ${(c/1024/1024).toFixed(2)} MB | Geometry on wire: ${(H/1024/1024).toFixed(2)} MB`)}let m=performance.now(),g=d.map(H=>wn(H,{vertexColors:e.colors!=null,appearance:o})),b=[];for(let H of p)if(t&&H.meshes.length>1){let E=da(H,R,e.indices,g,e.uvs,e.colors);E.userData.sourceComponentId=_nullishCoalesce(T, () => (null)),b.push(E)}else{let E=ma(H,R,e.indices,g,e.uvs,e.colors);for(let f of E)f.userData.sourceComponentId=_nullishCoalesce(T, () => (null));b.push(...E)}let x=performance.now()-m;if(a){let H=performance.now()-s;_chunkH3FZW6OXcjs.e.call(void 0, ).debug("Performance:"),i>0&&_chunkH3FZW6OXcjs.e.call(void 0, ).debug(` Parse JSON: ${i.toFixed(2)}ms`),_chunkH3FZW6OXcjs.e.call(void 0, ).debug(` Decode binary: ${l.toFixed(2)}ms`),_chunkH3FZW6OXcjs.e.call(void 0, ).debug(` Create Meshes: ${x.toFixed(2)}ms`),_chunkH3FZW6OXcjs.e.call(void 0, ).debug(` Total: ${H.toFixed(2)}ms`)}return Promise.resolve(b)}function De(e,n){return new (0, _chunkH3FZW6OXcjs.d)(e,_chunkH3FZW6OXcjs.c.VALIDATION_ERROR,{context:n})}function Tn(e,n,t,r){for(let a of e){if(!Number.isInteger(a.materialId)||a.materialId<0||a.materialId>=n)throw De("Group materialId out of range of the materials array.",{materialId:a.materialId,materialCount:n});for(let o of a.meshes){let i={vertexStart:o.vertexStart,vertexCount:o.vertexCount,indexStart:o.indexStart,indexCount:o.indexCount};for(let[l,s]of Object.entries(i))if(!Number.isInteger(s)||s<0)throw De(`Mesh metadata field "${l}" must be a non-negative integer.`,{meshName:o.name,field:l,value:s});if(o.vertexStart+o.vertexCount>t)throw De("Mesh vertex window exceeds the batch vertex buffer.",{meshName:o.name,vertexStart:o.vertexStart,vertexCount:o.vertexCount,totalVertexCount:t});if(o.indexStart+o.indexCount>r)throw De("Mesh index window exceeds the batch index buffer.",{meshName:o.name,indexStart:o.indexStart,indexCount:o.indexCount,totalIndexCount:r})}}}function Rn(e,n){return De("Index references a vertex outside its mesh's vertex window.",{meshName:n.name,indexValue:e,vertexStart:n.vertexStart,vertexCount:n.vertexCount})}function xn(e,n,t,r,a,o){let i=[],l=e;for(let s of n){l+=`|${s.vertexStart},${s.vertexCount},${s.indexStart},${s.indexCount}`;let c=s.vertexStart*3,u=c+s.vertexCount*3;i.push(t.subarray(c,u)),i.push(r.subarray(s.indexStart,s.indexStart+s.indexCount)),i.push(a?a.subarray(s.vertexStart*2,(s.vertexStart+s.vertexCount)*2):null),i.push(o?o.subarray(c,u):null)}return gn(i,l)}function ta(e,n,t,r){let a=new Float32Array(e.length),o=n[0],i=n[1],l=n[2],s=t[0],c=t[1],u=t[2];for(let d=0;d<e.length;d+=3)a[d]=o+(e[d]+32767)*s,a[d+1]=i+(e[d+1]+32767)*c,a[d+2]=l+(e[d+2]+32767)*u;return a}function na(e,n){return e}var ra=5e4,be,Le=new Map,oa=1;function aa(){if(be!==void 0)return be;if(typeof Worker>"u"||typeof Blob>"u"||typeof URL>"u"||typeof URL.createObjectURL!="function")return be=null,null;try{let e=URL.createObjectURL(new Blob([yn()],{type:"text/javascript"})),n=new Worker(e);n.onmessage=t=>{let{id:r,geometries:a,error:o}=t.data,i=Le.get(r);i&&(Le.delete(r),a?i.resolve(a):i.reject(new Error(_nullishCoalesce(o, () => ("mesh assembly failed in worker")))))},n.onerror=()=>{for(let t of Le.values())t.reject(new Error("mesh assembly worker crashed"));Le.clear(),n.terminate(),be=null},be=n}catch (e4){be=null}return be}function ia(e,n,t){return new Promise((r,a)=>{let o=oa++;Le.set(o,{resolve:r,reject:a}),e.postMessage({id:o,input:n},t)})}async function vn(e,n){if(typeof Worker>"u")return null;let t=ut(e);if(t.indexData.length/3<ra)return null;let r=aa();if(!r)return null;let a=_nullishCoalesce(_nullishCoalesce(t.metadata.materials, () => (_optionalChain([n, 'access', _293 => _293.fallback, 'optionalAccess', _294 => _294.materials]))), () => ([])),o=_nullishCoalesce(_nullishCoalesce(t.metadata.groups, () => (_optionalChain([n, 'access', _295 => _295.fallback, 'optionalAccess', _296 => _296.groups]))), () => ([])),i=_nullishCoalesce(_optionalChain([n, 'access', _297 => _297.fallback, 'optionalAccess', _298 => _298.sourceComponentId]), () => (t.metadata.sourceComponentId));Tn(o,a.length,t.vertexCount,t.indexData.length);let l=m=>({vertexStart:m.vertexStart,vertexCount:m.vertexCount,indexStart:m.indexStart,indexCount:m.indexCount}),s=[],c=[];for(let m of o)if(n.mergeByMaterial&&m.meshes.length>1)s.push({kind:"merged",windows:m.meshes.map(l)}),c.push({kind:"merged",group:m});else for(let g of m.meshes)s.push({kind:"single",windows:[l(g)]}),c.push({kind:"single",group:m,meshMeta:g});let u=t.vertexData.slice(),d=t.indexData.slice(),p=[u.buffer,d.buffer];t.uvs&&p.push(t.uvs.buffer),t.colors&&p.push(t.colors.buffer);let T;try{T=await ia(r,{vertexData:u,isFloat32:t.isFloat32,deltaEncoded:t.deltaEncoded,origin:t.origin,scale:t.scale,indexData:d,uvs:t.uvs,colors:t.colors,jobs:s},p)}catch(m){return _chunkH3FZW6OXcjs.e.call(void 0, ).warn("Mesh assembly worker failed; falling back to main-thread parse.",m),null}if(T.length!==s.length)return null;let v=a.map(m=>wn(m,{vertexColors:t.colors!=null,appearance:n.material})),R=[];for(let m=0;m<T.length;m++){let g=T[m],b=c[m],x=$e(g.key);x||(x=new V.BufferGeometry,x.setAttribute("position",new V.BufferAttribute(g.positions,3)),x.setAttribute("normal",new V.BufferAttribute(g.normals,3)),x.setIndex(new V.BufferAttribute(g.indices,1)),g.uvs&&x.setAttribute("uv",new V.BufferAttribute(g.uvs,2)),g.colors&&x.setAttribute("color",new V.BufferAttribute(g.colors,3,!0)),qe(g.key,x));let H=b.kind==="merged"?Mn(x,b.group,v):Hn(x,b.meshMeta,b.group,v);H.userData.sourceComponentId=_nullishCoalesce(i, () => (null)),R.push(H)}return n.debug&&_chunkH3FZW6OXcjs.e.call(void 0, ).debug(`Mesh batch assembled off-thread: ${R.length} meshes, ${t.indexData.length/3} triangles`),R}var sa=.5,la=.5,ca=.3;function wn(e,n){let t=St(e.color),r=_nullishCoalesce(_optionalChain([n, 'optionalAccess', _299 => _299.vertexColors]), () => (!1)),a=_optionalChain([n, 'optionalAccess', _300 => _300.appearance]),o=new V.MeshPhysicalMaterial({color:t,metalness:e.metalness,roughness:e.roughness,opacity:e.opacity,transparent:e.transparent,vertexColors:r,side:_optionalChain([a, 'optionalAccess', _301 => _301.cullBackfaces])?V.FrontSide:V.DoubleSide,polygonOffset:!0,polygonOffsetFactor:.5,polygonOffsetUnits:.5,depthWrite:!0,depthTest:!0});return _optionalChain([a, 'optionalAccess', _302 => _302.envMapIntensity])!=null&&(o.envMapIntensity=a.envMapIntensity),e.metalness>sa&&(o.clearcoat=la,o.clearcoatRoughness=ca),r&&ua(o),e.map&&rn(o,e.map),o}function ua(e){e.onBeforeCompile=n=>{n.vertexShader=n.vertexShader.replace("#include <color_vertex>",`#include <color_vertex>
113
+ #if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )
114
+ vColor.rgb = mix(
115
+ vColor.rgb / 12.92,
116
+ pow( ( vColor.rgb + 0.055 ) / 1.055, vec3( 2.4 ) ),
117
+ step( vec3( 0.04045 ), vColor.rgb )
118
+ );
119
+ #endif`)}}function da(e,n,t,r,a=null,o=null){let i=xn("merged",e.meshes,n,t,a,o),l=$e(i);if(!l){let s=0,c=0;for(let m of e.meshes)s+=m.vertexCount,c+=m.indexCount;let u=new Float32Array(s*3),d=new Uint32Array(c),p=a?new Float32Array(s*2):null,T=o?new Uint8Array(s*3):null,v=0,R=0;for(let m of e.meshes){let g=m.vertexStart*3,b=m.vertexCount*3;if(u.set(n.subarray(g,g+b),v*3),p&&a){let h=m.vertexStart*2;p.set(a.subarray(h,h+m.vertexCount*2),v*2)}T&&o&&T.set(o.subarray(g,g+b),v*3);let x=t.subarray(m.indexStart,m.indexStart+m.indexCount),H=v-m.vertexStart,E=m.vertexStart,f=m.vertexStart+m.vertexCount;for(let h=0;h<x.length;h++){let y=x[h];if(y<E||y>=f)throw Rn(y,m);d[R+h]=y+H}v+=m.vertexCount,R+=m.indexCount}l=new V.BufferGeometry,l.setAttribute("position",new V.BufferAttribute(u,3)),l.setIndex(new V.BufferAttribute(d,1)),p&&l.setAttribute("uv",new V.BufferAttribute(p,2)),T&&l.setAttribute("color",new V.BufferAttribute(T,3,!0)),l.computeVertexNormals(),qe(i,l)}return Mn(l,e,r)}function Mn(e,n,t){let r=new V.Mesh(e,t[n.materialId]),a=n.meshes[0],o=n.meshes.map(i=>i.name).filter(i=>i&&i.length>0);return r.name=o.length>0?o[0]:`merged_material_${n.materialId}`,r.castShadow=!0,r.receiveShadow=!0,r.userData={source:"compute",name:r.name,layer:_nullishCoalesce(_optionalChain([a, 'optionalAccess', _303 => _303.layer]), () => ("")),originalIndex:_nullishCoalesce(_optionalChain([a, 'optionalAccess', _304 => _304.originalIndex]), () => (0)),metadata:_nullishCoalesce(_optionalChain([a, 'optionalAccess', _305 => _305.metadata]), () => ({})),mergedFrom:n.meshes.slice(1).map(i=>({name:i.name,layer:i.layer,originalIndex:i.originalIndex}))},r}function ma(e,n,t,r,a=null,o=null){let i=[];for(let l of e.meshes){let s=l.vertexStart*3,c=l.vertexCount*3,u=xn("single",[l],n,t,a,o),d=$e(u);if(!d){let p=n.slice(s,s+c),T=t.subarray(l.indexStart,l.indexStart+l.indexCount),v=new Uint32Array(T.length),R=l.vertexStart,m=l.vertexStart+l.vertexCount;for(let g=0;g<T.length;g++){let b=T[g];if(b<R||b>=m)throw Rn(b,l);v[g]=b-R}if(d=new V.BufferGeometry,d.setAttribute("position",new V.BufferAttribute(p,3)),d.setIndex(new V.BufferAttribute(v,1)),a){let g=l.vertexStart*2,b=a.slice(g,g+l.vertexCount*2);d.setAttribute("uv",new V.BufferAttribute(b,2))}if(o){let g=o.slice(s,s+c);d.setAttribute("color",new V.BufferAttribute(g,3,!0))}d.computeVertexNormals(),qe(u,d)}i.push(Hn(d,l,e,r))}return i}function Hn(e,n,t,r){let a=new V.Mesh(e,r[t.materialId]);return a.name=n.name,a.userData={source:"compute",name:n.name,layer:_nullishCoalesce(n.layer, () => ("")),originalIndex:n.originalIndex,metadata:_nullishCoalesce(n.metadata, () => ({}))},a.castShadow=!0,a.receiveShadow=!0,a}function fa(e){return Math.floor(e.length*3/4)}var Cn={Angstroms:1e-10,Nanometers:1e-9,Microns:1e-6,Millimeters:.001,Centimeters:.01,Decimeters:.1,Meters:1,Dekameters:10,Hectometers:100,Kilometers:1e3,Megameters:1e6,Gigameters:1e9,Microinches:254e-10,Mils:254e-7,Inches:.0254,Feet:.3048,Yards:.9144,Miles:1609.344,NauticalMiles:1852},pa="Display",Ea="DisplayBatch";function ha(e){let n=e.split(".");return n.includes(pa)||n.includes(Ea)}var An=new Set;async function ss(e,n){let t=performance.now(),r=[],{allowScaling:a=!0,allowAutoPosition:o=!1,groundAxis:i="z",rhino:l,debug:s=!1,parsing:c={}}=_nullishCoalesce(n, () => ({}));try{let u=a?ga(e.modelunits):1;return await ya(e,r,u,c,l,s),o&&xa(r,i),r}catch(u){throw va(u,r),u}finally{s&&Ma(t)}}function ga(e){let n=Cn[e];return n!==void 0?n:(An.has(e)||(An.add(e),_chunkH3FZW6OXcjs.e.call(void 0, ).warn(`Unknown Rhino model unit "${e}" \u2014 geometry will not be scaled (factor 1). Known units: ${Object.keys(Cn).join(", ")}.`)),1)}async function ya(e,n,t,r,a,o){for(let i of e.values){let l=i.InnerTree;for(let s in l){let c=l[s];c&&await ba(c,n,t,r,a,o)}}}async function ba(e,n,t,r,a,o){for(let i of e){if(!ha(i.type))continue;let l={mergeByMaterial:!0,applyTransforms:!0,debug:!1,...r},s=Ta(i.data);if(!s){_chunkH3FZW6OXcjs.e.call(void 0, ).error("Error parsing display batch envelope: invalid JSON");continue}let c=await mt(s,l),u=sn(s.items,{rhino:a,applyTransforms:l.applyTransforms}),d=[...c,...u];if(t!==1)for(let p of d)p.scale.set(t,t,t);n.push(...d),o&&_chunkH3FZW6OXcjs.e.call(void 0, ).debug(`Extracted ${c.length} meshes and ${u.length} items from batch`)}}function Ta(e){return typeof e=="string"?Ra(e):e}function Ra(e){try{return JSON.parse(e)}catch (e5){return}}function xa(e,n){if(e.length===0)return;let t=Ke(e);Dt(e,t.min[n],n)}function va(e,n){_chunkH3FZW6OXcjs.e.call(void 0, ).error("An unexpected error occurred:",e),wa(n)}function wa(e){for(let n of e){let t=n;t.geometry&&t.geometry.dispose(),t.material&&(Array.isArray(t.material)?t.material.forEach(r=>r.dispose()):t.material.dispose())}}function Ma(e){let n=performance.now()-e;_chunkH3FZW6OXcjs.e.call(void 0, ).info("Time to process meshes:",`${n.toFixed(2)}ms`)}exports.a = zn; exports.b = we; exports.c = Oe; exports.d = Ct; exports.e = At; exports.f = Xe; exports.g = La; exports.h = St; exports.i = Dt; exports.j = Ke; exports.k = Lt; exports.l = Ot; exports.m = It; exports.n = He; exports.o = rt; exports.p = Mr; exports.q = ja; exports.r = Yt; exports.s = Xt; exports.t = Ue; exports.u = Kt; exports.v = Jt; exports.w = jr; exports.x = tn; exports.y = Wr; exports.z = nn; exports.A = ui; exports.B = oo; exports.C = Ai; exports.D = Di; exports.E = sn; exports.F = cn; exports.G = Fo; exports.H = un; exports.I = dn; exports.J = lt; exports.K = Bo; exports.L = ko; exports.M = Uo; exports.N = Vo; exports.O = Gi; exports.P = _o; exports.Q = ct; exports.R = es; exports.S = mt; exports.T = ts; exports.U = Cn; exports.V = ss;
120
+ //# sourceMappingURL=chunk-E4WV5HRX.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["d:\\Coding\\selva\\packages\\compute\\dist\\chunk-E4WV5HRX.cjs"],"names":[],"mappings":"AAAA,2/BAAgF,IAAK,EAAE,CAAC,CAAC,CAAC,CAAC,iCAAE,EAAG,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,iBAAiB,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,cAAc,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,cAAc,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,gBAAgB,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,eAAe,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,gBAAgB,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,aAAa,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,0oBAAuB,IAAK,EAAE,CAAC,IAAI,CAAC,CAAC,oBAAoB,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,EAAE,CAAC,SAAS,CAAC,EAAE,CAAC,kBAAkB,CAAC,EAAE,CAAC,UAAU,CAAC,CAAC,CAAC,C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,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAA;AACA,QAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAA","file":"D:\\Coding\\selva\\packages\\compute\\dist\\chunk-E4WV5HRX.cjs","sourcesContent":[null]}
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/selva/selva/packages/compute/dist/chunk-H3FZW6OX.cjs","../src/core/errors.ts","../src/core/compute-fetch/compute-fetch.ts"],"names":["ErrorCodes","RhinoComputeError","_RhinoComputeError","message","code","options","__publicField","inputName","expectedType","context"],"mappings":"AAAA,u8BAAI,CAAC,CAAC,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,C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CAAAA,CAAA,IAAA,CAAgB,MAAA,CAAA,CAChBA,CAAAA,CAAA,IAAA,CAAgB,YAAA,CAAA,CAChBA,CAAAA,CAAA,IAAA,CAAgB,SAAA,CAAA,CAChBA,CAAAA,CAAA,IAAA,CAAgB,eAAA,CAAA,CAQf,IAAA,CAAK,IAAA,CAAO,mBAAA,CACZ,IAAA,CAAK,IAAA,CAAOF,CAAAA,CACZ,IAAA,CAAK,UAAA,iBAAaC,CAAAA,6BAAS,YAAA,CAC3B,IAAA,CAAK,OAAA,iBAAUA,CAAAA,6BAAS,SAAA,CACxB,IAAA,CAAK,aAAA,iBAAgBA,CAAAA,6BAAS,eAAA,iBAC1BA,CAAAA,6BAAS,eAAA,EAAA,CACX,IAAA,CAA6B,KAAA,CAAQA,CAAAA,CAAQ,aAAA,CAEhD,CAKA,OAAO,aAAA,CACNE,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACC,CACD,OAAO,IAAIP,CAAAA,CACV,CAAA,OAAA,EAAUK,CAAS,CAAA,uBAAA,EAA0BC,CAAAA,CAAe,CAAA,WAAA,EAAcA,CAAY,CAAA,CAAA,CAAA,CAAM,EAAE,CAAA,CAAA;AC4VzC;AA2IU","file":"/home/runner/work/selva/selva/packages/compute/dist/chunk-H3FZW6OX.cjs","sourcesContent":[null,"export const ErrorCodes = {\n\tNETWORK_ERROR: 'NETWORK_ERROR',\n\tAUTH_ERROR: 'AUTH_ERROR',\n\tVALIDATION_ERROR: 'VALIDATION_ERROR',\n\tCOMPUTATION_ERROR: 'COMPUTATION_ERROR',\n\tTIMEOUT_ERROR: 'TIMEOUT_ERROR',\n\tCORS_ERROR: 'CORS_ERROR',\n\t/** HTTP 404 — the endpoint path does not exist on the server (usually a typo'd route or wrong server). Never retried. */\n\tNOT_FOUND: 'NOT_FOUND',\n\t/** HTTP 429 — the server is rate-limiting requests. Retried by default (honors `Retry-After`); see `RetryPolicy.retryOn429`. */\n\tRATE_LIMIT: 'RATE_LIMIT',\n\t/**\n\t * The server answered 2xx but the body is deterministically not JSON (the\n\t * response declared a non-JSON `Content-Type`, e.g. an HTML captive-portal or\n\t * proxy login page, or a misconfigured endpoint). Never retried — refetching\n\t * returns the same page.\n\t */\n\tINVALID_RESPONSE: 'INVALID_RESPONSE',\n\tUNKNOWN_ERROR: 'UNKNOWN_ERROR',\n\tINVALID_STATE: 'INVALID_STATE',\n\tINVALID_INPUT: 'INVALID_INPUT',\n\tINVALID_CONFIG: 'INVALID_CONFIG',\n\tBROWSER_ONLY: 'BROWSER_ONLY',\n\tENVIRONMENT_ERROR: 'ENVIRONMENT_ERROR',\n\tENCODING_ERROR: 'ENCODING_ERROR',\n\t/** An input's `default` had a shape the normalizer didn't recognize (no innerTree key). */\n\tMALFORMED_DEFAULT: 'MALFORMED_DEFAULT',\n\t/** Scheduler latest-wins: this call was replaced by a newer one. */\n\tSUPERSEDED: 'SUPERSEDED',\n\t/** Scheduler / caller-supplied AbortSignal: this call was aborted. */\n\tABORTED: 'ABORTED',\n\t/**\n\t * Scheduler backpressure: the queue was already at `maxQueueDepth` when this\n\t * call arrived, so it was shed immediately rather than queued. Retryable — the\n\t * caller (or an HTTP layer, as 503 + Retry-After) should back off and retry.\n\t * The error `context` carries `{ queueDepth, maxQueueDepth }`.\n\t */\n\tQUEUE_FULL: 'QUEUE_FULL',\n\t/**\n\t * Scheduler backpressure: this call sat queued longer than `queueWaitMs`\n\t * without starting, so it was shed before wasting compute on a stale request.\n\t * Retryable. The error `context` carries `{ waitedMs, queueWaitMs }`.\n\t */\n\tQUEUE_TIMEOUT: 'QUEUE_TIMEOUT',\n\t/**\n\t * A solve referenced a definition by `pointer` (server-side cache key), but the\n\t * server no longer holds that definition (evicted / GC'd / a different child in\n\t * the pool / server restarted). The caller should retry with the full\n\t * definition. Surfaced when the server tags its error body with\n\t * `code: \"definition_not_cached\"`, so it survives production message-scrubbing.\n\t */\n\tDEFINITION_NOT_CACHED: 'DEFINITION_NOT_CACHED'\n} as const;\n\nexport type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];\n\n/**\n * Simplified error for Rhino Compute operations\n *\n * @public Use this for error handling with error codes and context.\n */\nexport class RhinoComputeError extends Error {\n\tpublic readonly code: ErrorCode;\n\tpublic readonly statusCode?: number;\n\tpublic readonly context?: Record<string, unknown>;\n\tpublic readonly originalError?: Error;\n\n\tconstructor(\n\t\tmessage: string,\n\t\tcode: ErrorCode = ErrorCodes.UNKNOWN_ERROR,\n\t\toptions?: { statusCode?: number; context?: Record<string, unknown>; originalError?: Error }\n\t) {\n\t\tsuper(message);\n\t\tthis.name = 'RhinoComputeError';\n\t\tthis.code = code;\n\t\tthis.statusCode = options?.statusCode;\n\t\tthis.context = options?.context;\n\t\tthis.originalError = options?.originalError;\n\t\tif (options?.originalError) {\n\t\t\t(this as { cause?: unknown }).cause = options.originalError;\n\t\t}\n\t}\n\n\t/**\n\t * Create an error for missing/empty values\n\t */\n\tstatic missingValues(\n\t\tinputName: string,\n\t\texpectedType?: string,\n\t\tcontext?: Record<string, unknown>\n\t) {\n\t\treturn new RhinoComputeError(\n\t\t\t`Input \"${inputName}\" has no values defined${expectedType ? ` (expected ${expectedType})` : ''}`,\n\t\t\tErrorCodes.INVALID_INPUT,\n\t\t\t{ context: { inputName, expectedType, ...context } }\n\t\t);\n\t}\n\n\t/**\n\t * Create an error for unknown parameter type\n\t */\n\tstatic unknownParamType(\n\t\tparamType: string,\n\t\tparamName?: string,\n\t\tcontext?: Record<string, unknown>\n\t) {\n\t\treturn new RhinoComputeError(`Unknown paramType: ${paramType}`, ErrorCodes.VALIDATION_ERROR, {\n\t\t\tcontext: { receivedParamType: paramType, paramName, ...context }\n\t\t});\n\t}\n}\n","import { RhinoComputeError, ErrorCodes, type ErrorCode } from '../errors';\nimport { getLogger } from '../utils/logger';\nimport { utf8ByteLength } from '../utils/encoding';\nimport { setResponseWireSize } from './wire-size';\n\nimport type { ComputeConfig, RetryPolicy, ServerTiming } from '../types';\n\n/**\n * Parse a `Server-Timing` header value into typed durations (ms).\n *\n * Header grammar (RFC 9110 §10.1.10), as emitted by the solve endpoint:\n * `decode;dur=3, solve;dur=120, encode;dur=8`\n *\n * Returns null when the header is absent or carries no recognizable metric, so\n * the caller can skip the callback entirely.\n *\n * @internal exported for tests\n */\nexport function parseServerTiming(headerValue: string | null): ServerTiming | null {\n\tif (!headerValue) return null;\n\tconst timing: ServerTiming = { raw: headerValue };\n\tlet sawMetric = false;\n\tfor (const part of headerValue.split(',')) {\n\t\tconst [name, ...params] = part.trim().split(';');\n\t\tconst durParam = params.find((p) => p.trim().toLowerCase().startsWith('dur'));\n\t\tif (!durParam) continue;\n\t\tconst dur = Number(durParam.split('=')[1]);\n\t\tif (!Number.isFinite(dur)) continue;\n\t\tconst key = name.trim().toLowerCase();\n\t\tif (key === 'decode' || key === 'solve' || key === 'encode') {\n\t\t\ttiming[key] = dur;\n\t\t\tsawMetric = true;\n\t\t}\n\t}\n\treturn sawMetric ? timing : null;\n}\n\nconst DEFAULT_RETRY: Required<RetryPolicy> = {\n\tattempts: 0,\n\tbaseDelayMs: 500,\n\tmaxDelayMs: 30_000,\n\tretryOn429: true\n};\n\nconst RETRYABLE_STATUS = new Set([502, 503, 504]);\n\n/**\n * Absolute ceiling for a server-supplied `Retry-After` wait. The server's\n * stated window wins over `retryPolicy.maxDelayMs` (retrying earlier all but\n * guarantees another 429), but a bad/hostile header must not park the client\n * for minutes — anything above this cap is clamped.\n */\nconst RETRY_AFTER_CAP_MS = 60_000;\n\n/** Upper bound for the raw server body stored on error `context.responseBody`. */\nconst MAX_CONTEXT_BODY_CHARS = 4096;\n\nfunction resolveRetryPolicy(policy: RetryPolicy | undefined): Required<RetryPolicy> {\n\tif (!policy) return DEFAULT_RETRY;\n\treturn {\n\t\tattempts: policy.attempts ?? DEFAULT_RETRY.attempts,\n\t\tbaseDelayMs: policy.baseDelayMs ?? DEFAULT_RETRY.baseDelayMs,\n\t\tmaxDelayMs: policy.maxDelayMs ?? DEFAULT_RETRY.maxDelayMs,\n\t\tretryOn429: policy.retryOn429 ?? DEFAULT_RETRY.retryOn429\n\t};\n}\n\n/**\n * Parse a Retry-After header value (seconds-int or HTTP-date) into ms.\n * Returns null if the header is missing or unparseable.\n */\nfunction parseRetryAfter(headerValue: string | null): number | null {\n\tif (!headerValue) return null;\n\tconst seconds = Number(headerValue);\n\tif (Number.isFinite(seconds) && seconds >= 0) return seconds * 1000;\n\tconst dateMs = Date.parse(headerValue);\n\tif (Number.isFinite(dateMs)) {\n\t\tconst delta = dateMs - Date.now();\n\t\treturn delta > 0 ? delta : 0;\n\t}\n\treturn null;\n}\n\nfunction backoffDelay(attempt: number, policy: Required<RetryPolicy>): number {\n\tconst exponential = policy.baseDelayMs * Math.pow(2, attempt);\n\tconst jitter = Math.random() * policy.baseDelayMs;\n\treturn Math.min(exponential + jitter, policy.maxDelayMs);\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(new DOMException('Aborted', 'AbortError'));\n\t\t\treturn;\n\t\t}\n\t\tconst id = setTimeout(() => {\n\t\t\tsignal?.removeEventListener('abort', onAbort);\n\t\t\tresolve();\n\t\t}, ms);\n\t\tconst onAbort = () => {\n\t\t\tclearTimeout(id);\n\t\t\treject(new DOMException('Aborted', 'AbortError'));\n\t\t};\n\t\tsignal?.addEventListener('abort', onAbort, { once: true });\n\t});\n}\n\n/** Truncate a server body for storage on error context — bounded, with an honest marker. */\nfunction truncateBody(body: string): string {\n\tif (body.length <= MAX_CONTEXT_BODY_CHARS) return body;\n\treturn `${body.slice(0, MAX_CONTEXT_BODY_CHARS)}… [truncated ${body.length - MAX_CONTEXT_BODY_CHARS} chars]`;\n}\n\nfunction throwHttpError(\n\tresponse: Response,\n\tfullUrl: string,\n\trequestId: string,\n\trequestSize: number,\n\tserverUrl: string,\n\terrorBody: string,\n\tserverCode?: string,\n\trawBody?: string\n): never {\n\tconst { status, statusText } = response;\n\n\tconst responseHeaders: Record<string, string> = {};\n\tresponse.headers.forEach((value, key) => {\n\t\tresponseHeaders[key] = value;\n\t});\n\n\tconst trimmed = errorBody.trim();\n\tconst bodyHint = trimmed ? ` — ${trimmed.slice(0, 200)}${trimmed.length > 200 ? '…' : ''}` : '';\n\n\t// context.responseBody holds the RAW server body (what actually came over the\n\t// wire), bounded to MAX_CONTEXT_BODY_CHARS so a huge body isn't pinned for the\n\t// error's lifetime. `errorBody` may have been rewritten into a synthesized\n\t// message (500 exception shape) — that goes in the message, not the context.\n\tconst storedBody = rawBody ?? errorBody;\n\tconst context = {\n\t\turl: fullUrl,\n\t\trequestId,\n\t\tmethod: 'POST',\n\t\trequestSize,\n\t\tserverUrl,\n\t\tresponseBody: storedBody ? truncateBody(storedBody) : undefined,\n\t\tresponseHeaders\n\t};\n\n\tconst errorMap: Record<number, { message: string; code: ErrorCode }> = {\n\t\t401: { message: `HTTP ${status}: ${statusText}${bodyHint}`, code: ErrorCodes.AUTH_ERROR },\n\t\t403: { message: `HTTP ${status}: ${statusText}${bodyHint}`, code: ErrorCodes.AUTH_ERROR },\n\t\t404: { message: `Endpoint not found: ${fullUrl}`, code: ErrorCodes.NOT_FOUND },\n\t\t413: {\n\t\t\tmessage: `Request too large: ${(requestSize / 1024).toFixed(2)}KB`,\n\t\t\tcode: ErrorCodes.VALIDATION_ERROR\n\t\t},\n\t\t429: { message: `Rate limit exceeded${bodyHint}`, code: ErrorCodes.RATE_LIMIT },\n\t\t500: { message: `Server error: ${statusText}${bodyHint}`, code: ErrorCodes.COMPUTATION_ERROR },\n\t\t502: {\n\t\t\tmessage: `Service unavailable: ${statusText}${bodyHint}`,\n\t\t\tcode: ErrorCodes.NETWORK_ERROR\n\t\t},\n\t\t503: {\n\t\t\tmessage: `Service unavailable: ${statusText}${bodyHint}`,\n\t\t\tcode: ErrorCodes.NETWORK_ERROR\n\t\t},\n\t\t504: {\n\t\t\tmessage: `Service unavailable: ${statusText}${bodyHint}`,\n\t\t\tcode: ErrorCodes.NETWORK_ERROR\n\t\t}\n\t};\n\n\tconst error = errorMap[status] || {\n\t\tmessage: `HTTP ${status}: ${statusText}${bodyHint}`,\n\t\tcode: ErrorCodes.UNKNOWN_ERROR\n\t};\n\n\t// A machine code in the server's error body (e.g. \"definition_not_cached\")\n\t// outranks the status-based mapping: it's stable across the server's\n\t// production message-scrubbing, where the human message is replaced with a\n\t// generic string. Keep the status-derived message for context.\n\tconst code = mapServerErrorCode(serverCode) ?? error.code;\n\n\tthrow new RhinoComputeError(error.message, code, { statusCode: status, context });\n}\n\n/**\n * Map a server-supplied error code (from the JSON error body's `code` field) to\n * one of our {@link ErrorCodes}. Returns `undefined` for an absent or unknown\n * code so the caller falls back to its status-based mapping.\n */\nfunction mapServerErrorCode(serverCode?: string): ErrorCode | undefined {\n\tswitch (serverCode) {\n\t\tcase 'definition_not_cached':\n\t\t\treturn ErrorCodes.DEFINITION_NOT_CACHED;\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\nfunction buildUrl(endpoint: string, serverUrl: string): string {\n\tconst base = serverUrl.replace(/\\/+$/, '');\n\tconst path = endpoint.replace(/^\\/+/, '');\n\treturn `${base}/${path}`;\n}\n\nfunction isLocalhost(serverUrl: string): boolean {\n\ttry {\n\t\t// `hostname` (not `host`) strips the port; IPv6 hostnames keep their\n\t\t// brackets, so `http://[::1]:6500` yields `[::1]`.\n\t\tconst hostname = new URL(serverUrl).hostname.toLowerCase();\n\t\treturn hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '[::1]';\n\t} catch {\n\t\treturn /(localhost|127\\.0\\.0\\.1|\\[::1\\])/i.test(serverUrl);\n\t}\n}\n\n/** Server URLs already warned about missing auth — warn once per server, not per request. */\nconst warnedNoAuth = new Set<string>();\n\nfunction buildHeaders(requestId: string, config: ComputeConfig): HeadersInit {\n\tconst headers: HeadersInit = {\n\t\t// Caller headers first so the transport's own headers below OVERWRITE them —\n\t\t// a caller can never clobber the request id, content type, or auth.\n\t\t...config.headers,\n\t\t'X-Request-ID': requestId,\n\t\t'Content-Type': 'application/json',\n\t\t...(config.authToken && { Authorization: config.authToken }),\n\t\t...(config.apiKey && { RhinoComputeKey: config.apiKey })\n\t};\n\n\tif (\n\t\t!config.apiKey &&\n\t\t!config.authToken &&\n\t\t!warnedNoAuth.has(config.serverUrl) &&\n\t\t!isLocalhost(config.serverUrl)\n\t) {\n\t\twarnedNoAuth.add(config.serverUrl);\n\t\tgetLogger().warn(\n\t\t\t`⚠️ [Rhino Compute] Request [${requestId}] targets remote server (${config.serverUrl}) but no API key or auth token is configured. Requests may fail or be rate-limited. (warned once per server)`\n\t\t);\n\t}\n\n\treturn headers;\n}\n\nfunction generateRequestId(): string {\n\treturn `${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;\n}\n\nfunction log(message: string, debug?: boolean): void {\n\tif (debug) getLogger().debug(message);\n}\n\n/**\n * Compose a caller-supplied AbortSignal with an optional timeout. Returns a\n * combined signal, or `undefined` if neither was given.\n *\n * Uses `AbortSignal.timeout` (not setTimeout) so the timer is not throttled\n * when the tab is hidden. Falls back to a manual timer for older runtimes.\n *\n * @internal exported for tests\n */\nexport function composeSignal(\n\tcallerSignal: AbortSignal | undefined,\n\ttimeoutMs: number | undefined\n): { signal: AbortSignal | undefined; cleanup: () => void } {\n\tconst noCleanup = () => {};\n\tconst wantsTimeout = typeof timeoutMs === 'number' && timeoutMs > 0;\n\n\tif (!callerSignal && !wantsTimeout) return { signal: undefined, cleanup: noCleanup };\n\tif (callerSignal && !wantsTimeout) return { signal: callerSignal, cleanup: noCleanup };\n\n\tconst supportsTimeout =\n\t\ttypeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function';\n\n\t// Timeout only: nothing is registered on a caller signal, so there is nothing to clean up on\n\t// the modern path (the pending timer is small and self-expires at timeoutMs).\n\tif (!callerSignal) {\n\t\tif (supportsTimeout) return { signal: AbortSignal.timeout(timeoutMs!), cleanup: noCleanup };\n\t\tconst ctrl = new AbortController();\n\t\tconst id = setTimeout(() => ctrl.abort(), timeoutMs);\n\t\treturn { signal: ctrl.signal, cleanup: () => clearTimeout(id) };\n\t}\n\n\t// Caller signal + timeout: composed manually rather than with AbortSignal.any — `any` offers no\n\t// way to unregister its dependent link on the caller's signal, so an app reusing one long-lived\n\t// signal across many solves accumulates a registration per attempt for the full timeoutMs after\n\t// each response (and forever on Node versions with the known AbortSignal.any leak).\n\tconst ctrl = new AbortController();\n\n\tlet timeoutSignal: AbortSignal;\n\tlet timerId: ReturnType<typeof setTimeout> | undefined;\n\tif (supportsTimeout) {\n\t\ttimeoutSignal = AbortSignal.timeout(timeoutMs!);\n\t} else {\n\t\tconst timeoutCtrl = new AbortController();\n\t\ttimerId = setTimeout(() => timeoutCtrl.abort(), timeoutMs);\n\t\ttimeoutSignal = timeoutCtrl.signal;\n\t}\n\n\tconst sources = [callerSignal, timeoutSignal];\n\t// Forward the source's reason so fetch rejects with the right error name\n\t// ('TimeoutError' vs 'AbortError'), matching AbortSignal.any semantics.\n\tconst onAbort = function (this: AbortSignal) {\n\t\tctrl.abort(this.reason);\n\t};\n\n\tfor (const s of sources) {\n\t\tif (s.aborted) {\n\t\t\tctrl.abort(s.reason);\n\t\t\tbreak;\n\t\t}\n\t\ts.addEventListener('abort', onAbort, { once: true });\n\t}\n\n\treturn {\n\t\tsignal: ctrl.signal,\n\t\tcleanup: () => {\n\t\t\tif (timerId !== undefined) clearTimeout(timerId);\n\t\t\tfor (const s of sources) s.removeEventListener('abort', onAbort);\n\t\t}\n\t};\n}\n\n/**\n * Surface the server's per-request timing breakdown (if it sent one and a\n * caller is listening). Best-effort: a throwing callback must not fail the\n * request. Called on the success path AND the 500-with-values partial-success\n * path — solves that completed with Grasshopper errors carry real timings too.\n */\nfunction fireServerTiming(\n\tresponse: Response,\n\trequestId: string,\n\tonServerTiming: ((timing: ServerTiming, requestId: string) => void) | undefined,\n\tdebug?: boolean\n): void {\n\tif (!onServerTiming) return;\n\tconst timing = parseServerTiming(response.headers.get('Server-Timing'));\n\tif (!timing) return;\n\ttry {\n\t\tonServerTiming(timing, requestId);\n\t} catch (err) {\n\t\tif (debug) log(` onServerTiming callback threw: ${err}`, true);\n\t}\n}\n\nasync function handleResponse(\n\tresponse: Response,\n\tfullUrl: string,\n\trequestId: string,\n\trequestSize: number,\n\tserverUrl: string,\n\tstartTime: number,\n\tdebug?: boolean,\n\tonServerTiming?: (timing: ServerTiming, requestId: string) => void\n): Promise<any> {\n\tconst responseTime = Math.round(performance.now() - startTime);\n\n\tif (!response.ok) {\n\t\t// Read body once and reuse. `rawBody` stays what came over the wire (stored\n\t\t// on error context); `errorBody` may be rewritten into a friendlier message.\n\t\tconst rawBody = await response.text();\n\t\tlet errorBody = rawBody;\n\n\t\t// Enhanced logging for errors\n\t\tif (debug) {\n\t\t\tlog(\n\t\t\t\t`❌ Request [${requestId}] failed with HTTP ${response.status} in ${responseTime}ms`,\n\t\t\t\ttrue\n\t\t\t);\n\t\t\tlog(` URL: ${fullUrl}`, true);\n\t\t\tlog(` Status: ${response.status} ${response.statusText}`, true);\n\t\t\tif (errorBody) {\n\t\t\t\tlog(\n\t\t\t\t\t` Response body: ${errorBody.substring(0, 500)}${errorBody.length > 500 ? '...' : ''}`,\n\t\t\t\t\ttrue\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// A machine-readable code the server may tag onto its error body (e.g.\n\t\t// \"definition_not_cached\"). Unlike the human `message`, it isn't scrubbed in\n\t\t// the server's production (non-debug) mode, so it's the reliable signal for\n\t\t// classifying the error (see throwHttpError → mapServerErrorCode). It can\n\t\t// ride any error status, not just 500, so read it here.\n\t\tlet serverCode: string | undefined;\n\n\t\ttry {\n\t\t\tconst parsedForCode = JSON.parse(errorBody);\n\t\t\tif (typeof parsedForCode?.code === 'string') serverCode = parsedForCode.code;\n\t\t} catch {\n\t\t\t// Non-JSON body — nothing to extract.\n\t\t}\n\n\t\t// Check if it's a valid compute response with errors/warnings\n\t\tif (response.status === 500) {\n\t\t\ttry {\n\t\t\t\tconst parsed = JSON.parse(errorBody);\n\t\t\t\t// If it has values, it's a partial success with errors\n\t\t\t\tif (parsed?.values && (parsed.errors || parsed.warnings)) {\n\t\t\t\t\tsetResponseWireSize(parsed, errorBody.length);\n\t\t\t\t\tif (debug) {\n\t\t\t\t\t\tlog(\n\t\t\t\t\t\t\t`⚠️ Request [${requestId}] completed with Grasshopper errors in ${responseTime}ms`,\n\t\t\t\t\t\t\ttrue\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (parsed.errors?.length > 0) {\n\t\t\t\t\t\t\tlog(` Errors: ${JSON.stringify(parsed.errors, null, 2)}`, true);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (parsed.warnings?.length > 0) {\n\t\t\t\t\t\t\tlog(` Warnings: ${JSON.stringify(parsed.warnings, null, 2)}`, true);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfireServerTiming(response, requestId, onServerTiming, debug);\n\t\t\t\t\treturn parsed;\n\t\t\t\t}\n\n\t\t\t\t// Raw server-side exception. The Compute8 server's exception handler\n\t\t\t\t// (compute.geometry Startup.cs) emits:\n\t\t\t\t// { error: \"Internal Server Error\", message: \"<category>: <detail>\",\n\t\t\t\t// stackTrace?: string[] } // stackTrace only when Config.Debug\n\t\t\t\t// The actionable part is `message` — surface it, with the optional\n\t\t\t\t// stack appended for debugging. We prefer `message`/`error` (current\n\t\t\t\t// server) and keep `Message`/`ExceptionType`/`StackTrace` (old\n\t\t\t\t// PascalCase .NET shape) as a back-compat fallback so an older server\n\t\t\t\t// still produces a useful message.\n\t\t\t\tconst serverMessage =\n\t\t\t\t\t(typeof parsed?.message === 'string' && parsed.message) ||\n\t\t\t\t\t(typeof parsed?.Message === 'string' && parsed.Message) ||\n\t\t\t\t\t'';\n\t\t\t\tconst exceptionType =\n\t\t\t\t\t(typeof parsed?.ExceptionType === 'string' && parsed.ExceptionType) || '';\n\t\t\t\tconst stack = parsed?.stackTrace ?? parsed?.StackTrace;\n\t\t\t\tconst stackStr = Array.isArray(stack) ? stack.join('\\n') : stack || '';\n\n\t\t\t\tif (serverMessage) {\n\t\t\t\t\t// Don't repeat the generic \"Internal Server Error\" label when the\n\t\t\t\t\t// message already carries the real detail.\n\t\t\t\t\tconst prefix = exceptionType ? `${exceptionType}: ` : '';\n\t\t\t\t\terrorBody = `${prefix}${serverMessage}${stackStr ? `\\n${stackStr}` : ''}`;\n\t\t\t\t} else if (parsed?.error) {\n\t\t\t\t\terrorBody =\n\t\t\t\t\t\ttypeof parsed.error === 'string' ? parsed.error : JSON.stringify(parsed.error, null, 2);\n\t\t\t\t}\n\t\t\t} catch (e) {\n\t\t\t\tif (debug) {\n\t\t\t\t\tlog(` Failed to parse error body as JSON: ${e}`, true);\n\t\t\t\t}\n\t\t\t\t// Not valid JSON, proceed with HTTP error\n\t\t\t}\n\t\t}\n\n\t\tthrowHttpError(\n\t\t\tresponse,\n\t\t\tfullUrl,\n\t\t\trequestId,\n\t\t\trequestSize,\n\t\t\tserverUrl,\n\t\t\terrorBody,\n\t\t\tserverCode,\n\t\t\trawBody\n\t\t);\n\t}\n\n\tlog(`✅ Request [${requestId}] completed in ${responseTime}ms`, debug);\n\n\tfireServerTiming(response, requestId, onServerTiming, debug);\n\n\ttry {\n\t\t// text-then-parse (what `response.json()` does internally) so the body's\n\t\t// wire size rides along with the parsed object — downstream byte-budgeted\n\t\t// caches read it instead of re-serializing a potentially huge tree.\n\t\tconst rawBody = await response.text();\n\t\tconst parsed = JSON.parse(rawBody);\n\t\tsetResponseWireSize(parsed, rawBody.length);\n\t\treturn parsed;\n\t} catch (error) {\n\t\t// Classify by the declared Content-Type (issue 87). A 2xx that DECLARES a\n\t\t// non-JSON body (HTML from a captive portal, a reverse-proxy login page, a\n\t\t// misconfigured endpoint) is deterministic — refetching returns the same\n\t\t// page — so fail immediately with INVALID_RESPONSE (never retried). A body\n\t\t// that fails to parse under a JSON (or absent) Content-Type means the\n\t\t// stream was likely cut mid-body — as transient as any network error — and\n\t\t// keeps the retryable NETWORK_ERROR classification.\n\t\tconst contentType = (response.headers.get('Content-Type') ?? '').toLowerCase();\n\t\tconst declaredNonJson = contentType !== '' && !contentType.includes('json');\n\t\tif (declaredNonJson) {\n\t\t\tthrow new RhinoComputeError(\n\t\t\t\t`Server returned a non-JSON response (Content-Type: ${contentType}) — check the server URL / proxy configuration`,\n\t\t\t\tErrorCodes.INVALID_RESPONSE,\n\t\t\t\t{\n\t\t\t\t\tstatusCode: response.status,\n\t\t\t\t\tcontext: { url: fullUrl, requestId, contentType },\n\t\t\t\t\toriginalError: error instanceof Error ? error : new Error(String(error))\n\t\t\t\t}\n\t\t\t);\n\t\t}\n\t\tthrow new RhinoComputeError('Failed to parse JSON response', ErrorCodes.NETWORK_ERROR, {\n\t\t\tstatusCode: response.status,\n\t\t\tcontext: {\n\t\t\t\turl: fullUrl,\n\t\t\t\trequestId\n\t\t\t},\n\t\t\toriginalError: error instanceof Error ? error : new Error(String(error))\n\t\t});\n\t}\n}\n\ninterface AttemptContext {\n\tendpoint: string;\n\tbody: string;\n\trequestSize: number;\n\tfullUrl: string;\n\trequestId: string;\n\theaders: HeadersInit;\n\tconfig: ComputeConfig;\n}\n\ninterface AttemptResult {\n\tok: true;\n\tvalue: any;\n}\n\ninterface AttemptRetry {\n\tok: false;\n\tretry: true;\n\tdelayMs: number;\n\tcause: RhinoComputeError;\n}\n\ninterface AttemptFatal {\n\tok: false;\n\tretry: false;\n\tcause: RhinoComputeError;\n}\n\nasync function attemptFetch(\n\tctx: AttemptContext,\n\tretryPolicy: Required<RetryPolicy>,\n\tattempt: number,\n\ttotalAttempts: number\n): Promise<AttemptResult | AttemptRetry | AttemptFatal> {\n\tconst { signal, cleanup } = composeSignal(ctx.config.signal, ctx.config.timeoutMs);\n\tconst startTime = performance.now();\n\n\ttry {\n\t\tconst response = await fetch(ctx.fullUrl, {\n\t\t\tmethod: 'POST',\n\t\t\tbody: ctx.body,\n\t\t\theaders: ctx.headers,\n\t\t\tsignal\n\t\t});\n\n\t\t// 429 with Retry-After or retryable 5xx → maybe retry\n\t\tconst isRetryableStatus =\n\t\t\tRETRYABLE_STATUS.has(response.status) || (retryPolicy.retryOn429 && response.status === 429);\n\n\t\tif (isRetryableStatus && attempt < totalAttempts - 1) {\n\t\t\tconst retryAfterMs = parseRetryAfter(response.headers.get('Retry-After'));\n\t\t\t// The server's stated Retry-After window wins over maxDelayMs — retrying\n\t\t\t// before it all but guarantees another 429 and burns an attempt. It is\n\t\t\t// only clamped by the absolute RETRY_AFTER_CAP_MS safety cap (or by a\n\t\t\t// caller-configured maxDelayMs that is even larger), so a bad header\n\t\t\t// can't force a pathological sleep. backoffDelay already clamps itself.\n\t\t\tconst delayMs =\n\t\t\t\tretryAfterMs !== null\n\t\t\t\t\t? Math.min(retryAfterMs, Math.max(retryPolicy.maxDelayMs, RETRY_AFTER_CAP_MS))\n\t\t\t\t\t: backoffDelay(attempt, retryPolicy);\n\t\t\t// Drain the body so the connection can be reused on the next attempt.\n\t\t\t// On the *final* attempt we deliberately fall through — handleResponse\n\t\t\t// reads the body itself to surface the error context.\n\t\t\tawait response.text().catch(() => {});\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tretry: true,\n\t\t\t\tdelayMs,\n\t\t\t\tcause: new RhinoComputeError(\n\t\t\t\t\t`HTTP ${response.status} ${response.statusText} (will retry)`,\n\t\t\t\t\tresponse.status === 429 ? ErrorCodes.RATE_LIMIT : ErrorCodes.NETWORK_ERROR,\n\t\t\t\t\t{ statusCode: response.status, context: { requestId: ctx.requestId } }\n\t\t\t\t)\n\t\t\t};\n\t\t}\n\n\t\tconst value = await handleResponse(\n\t\t\tresponse,\n\t\t\tctx.fullUrl,\n\t\t\tctx.requestId,\n\t\t\tctx.requestSize,\n\t\t\tctx.config.serverUrl,\n\t\t\tstartTime,\n\t\t\tctx.config.debug,\n\t\t\tctx.config.onServerTiming\n\t\t);\n\t\treturn { ok: true, value };\n\t} catch (error) {\n\t\t// Caller-aborted vs timeout-aborted distinction\n\t\tif (error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError')) {\n\t\t\tconst callerAborted = ctx.config.signal?.aborted === true;\n\n\t\t\tif (callerAborted) {\n\t\t\t\t// Caller cancellation is never retried — propagate immediately\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tretry: false,\n\t\t\t\t\tcause: new RhinoComputeError('Request aborted by caller', ErrorCodes.ABORTED, {\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\tendpoint: ctx.endpoint,\n\t\t\t\t\t\t\trequestId: ctx.requestId,\n\t\t\t\t\t\t\trequestSize: ctx.requestSize\n\t\t\t\t\t\t},\n\t\t\t\t\t\toriginalError: error\n\t\t\t\t\t})\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Only claim a timeout when we actually armed one (issue 88). Without a\n\t\t\t// configured timeoutMs, a non-caller abort came from the runtime itself\n\t\t\t// (e.g. an undici socket teardown) — as transient as any network drop, so\n\t\t\t// it stays retryable, but it is NOT a timeout: report it truthfully\n\t\t\t// instead of \"timed out after undefinedms\" / TIMEOUT_ERROR.\n\t\t\tconst timeoutArmed = typeof ctx.config.timeoutMs === 'number' && ctx.config.timeoutMs > 0;\n\t\t\tconst fatal = timeoutArmed\n\t\t\t\t? new RhinoComputeError(\n\t\t\t\t\t\t`Request timed out after ${ctx.config.timeoutMs}ms`,\n\t\t\t\t\t\tErrorCodes.TIMEOUT_ERROR,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\t\tserverUrl: ctx.config.serverUrl,\n\t\t\t\t\t\t\t\ttimeoutMs: ctx.config.timeoutMs,\n\t\t\t\t\t\t\t\turl: ctx.fullUrl,\n\t\t\t\t\t\t\t\trequestId: ctx.requestId,\n\t\t\t\t\t\t\t\tendpoint: ctx.endpoint,\n\t\t\t\t\t\t\t\trequestSize: ctx.requestSize\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\toriginalError: error\n\t\t\t\t\t\t}\n\t\t\t\t\t)\n\t\t\t\t: new RhinoComputeError(\n\t\t\t\t\t\t`Request aborted by the runtime (${error.name}): ${error.message}`,\n\t\t\t\t\t\tErrorCodes.NETWORK_ERROR,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\t\tserverUrl: ctx.config.serverUrl,\n\t\t\t\t\t\t\t\turl: ctx.fullUrl,\n\t\t\t\t\t\t\t\trequestId: ctx.requestId,\n\t\t\t\t\t\t\t\tendpoint: ctx.endpoint,\n\t\t\t\t\t\t\t\trequestSize: ctx.requestSize\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\toriginalError: error\n\t\t\t\t\t\t}\n\t\t\t\t\t);\n\t\t\tif (attempt < totalAttempts - 1) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tretry: true,\n\t\t\t\t\tdelayMs: backoffDelay(attempt, retryPolicy),\n\t\t\t\t\tcause: fatal\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: false, retry: false, cause: fatal };\n\t\t}\n\n\t\t// Network error (TypeError) — retryable (issue 90).\n\t\t//\n\t\t// Duplicate-POST caveat: a connection reset can strike after the body was\n\t\t// sent, in which case the server may already have executed this POST and a\n\t\t// retry runs it again. Compute solves are deterministic, so a duplicate is\n\t\t// wasted work rather than corruption; RetryPolicy documents the risk and\n\t\t// defaults to attempts: 0.\n\t\t//\n\t\t// In a real browser, a fetch TypeError with no response is most often a\n\t\t// CORS misconfiguration (the browser hides the details by design), so it is\n\t\t// classified CORS_ERROR there to stop callers chasing phantom network\n\t\t// failures. Retries are kept in both environments: the same TypeError is\n\t\t// also what a flaky/offline network produces, and there is no way to tell\n\t\t// them apart.\n\t\tif (error instanceof TypeError) {\n\t\t\tconst inBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';\n\t\t\tconst errorContext = {\n\t\t\t\tserverUrl: ctx.config.serverUrl,\n\t\t\t\turl: ctx.fullUrl,\n\t\t\t\trequestId: ctx.requestId,\n\t\t\t\tendpoint: ctx.endpoint,\n\t\t\t\trequestSize: ctx.requestSize\n\t\t\t};\n\t\t\tconst fatal = inBrowser\n\t\t\t\t? new RhinoComputeError(\n\t\t\t\t\t\t`Request failed: ${error.message} — in a browser this usually means a CORS misconfiguration on the server (or a network failure; the browser does not distinguish them)`,\n\t\t\t\t\t\tErrorCodes.CORS_ERROR,\n\t\t\t\t\t\t{ context: errorContext, originalError: error }\n\t\t\t\t\t)\n\t\t\t\t: new RhinoComputeError(`Network error: ${error.message}`, ErrorCodes.NETWORK_ERROR, {\n\t\t\t\t\t\tcontext: errorContext,\n\t\t\t\t\t\toriginalError: error\n\t\t\t\t\t});\n\t\t\tif (attempt < totalAttempts - 1) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tretry: true,\n\t\t\t\t\tdelayMs: backoffDelay(attempt, retryPolicy),\n\t\t\t\t\tcause: fatal\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: false, retry: false, cause: fatal };\n\t\t}\n\t\t// RhinoComputeError thrown from handleResponse — already has full context.\n\t\t// Retryable only if it carries a retryable status code.\n\t\tif (error instanceof RhinoComputeError) {\n\t\t\tconst status = error.statusCode;\n\t\t\t// A 2xx whose body failed to parse UNDER A JSON CONTENT-TYPE\n\t\t\t// (NETWORK_ERROR from handleResponse) means the stream was cut mid-body —\n\t\t\t// as transient as any network error. A 2xx that declared a non-JSON body\n\t\t\t// arrives here as INVALID_RESPONSE (deterministic — captive portal /\n\t\t\t// login page) and deliberately does NOT match: it is never retried.\n\t\t\tconst isTruncatedSuccess =\n\t\t\t\terror.code === ErrorCodes.NETWORK_ERROR &&\n\t\t\t\tstatus !== undefined &&\n\t\t\t\tstatus >= 200 &&\n\t\t\t\tstatus < 300;\n\t\t\tconst retryable =\n\t\t\t\tisTruncatedSuccess ||\n\t\t\t\t(status !== undefined &&\n\t\t\t\t\t(RETRYABLE_STATUS.has(status) || (retryPolicy.retryOn429 && status === 429)));\n\t\t\tif (retryable && attempt < totalAttempts - 1) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tretry: true,\n\t\t\t\t\tdelayMs: backoffDelay(attempt, retryPolicy),\n\t\t\t\t\tcause: error\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: false, retry: false, cause: error };\n\t\t}\n\n\t\t// Unknown — wrap and don't retry\n\t\treturn {\n\t\t\tok: false,\n\t\t\tretry: false,\n\t\t\tcause: new RhinoComputeError(\n\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t\tErrorCodes.UNKNOWN_ERROR,\n\t\t\t\t{\n\t\t\t\t\tcontext: { endpoint: ctx.endpoint, requestId: ctx.requestId },\n\t\t\t\t\toriginalError: error instanceof Error ? error : new Error(String(error))\n\t\t\t\t}\n\t\t\t)\n\t\t};\n\t} finally {\n\t\tcleanup();\n\t}\n}\n\n/**\n * Generic Rhino Compute fetch function.\n * Sends a POST request to any Compute endpoint with pre-prepared arguments.\n *\n * Use this for advanced, low-level control over compute requests. For most use cases, prefer higher-level APIs.\n *\n * The transport is response-type-agnostic: it does not know which response a\n * given endpoint returns. Callers supply the response type via `R` (defaulting\n * to `unknown`, which forces an explicit narrowing before use).\n *\n * Timeout semantics: `config.timeoutMs` is a PER-ATTEMPT timeout, re-armed for\n * every retry. With `retry: { attempts: N }` the worst-case wall clock is\n * `(N + 1) × timeoutMs` plus backoff sleeps (and a server `Retry-After` can\n * stretch a single sleep up to 60s). For a hard overall deadline, pass\n * `config.signal` (e.g. `AbortSignal.timeout(totalMs)`) — a caller abort wins\n * immediately, including during backoff.\n *\n * Retry caveats: requests are POSTs, so a retry after a mid-flight connection\n * loss may re-execute a request the server already ran (see {@link RetryPolicy}).\n * A 2xx response that declares a non-JSON `Content-Type` (captive portal,\n * proxy login page) fails immediately with `INVALID_RESPONSE` and is never\n * retried; a body that fails to parse under a JSON content-type is treated as\n * a truncated stream and is retried.\n *\n * @typeParam R - The expected response shape. The caller names it at the call site.\n * @param endpoint - The Compute API endpoint (e.g., 'grasshopper', 'io', 'mesh').\n * @param args - Pre-prepared arguments for the request body.\n * @param config - Compute configuration (server URL, API key, timeout, debug, retry, signal).\n * @returns The parsed JSON response from the server, typed as `R`.\n *\n * @example\n * // Basic usage for the Grasshopper endpoint:\n * const response = await fetchRhinoCompute(\n * 'grasshopper',\n * { ... },\n * {\n * serverUrl: 'https://my-server.com',\n * debug: true,\n * timeoutMs: 30_000,\n * retry: { attempts: 2 },\n * signal: controller.signal,\n * }\n * );\n */\nexport async function fetchRhinoCompute<R = unknown>(\n\tendpoint: string,\n\targs: Record<string, any>,\n\tconfig: ComputeConfig\n): Promise<R> {\n\tconst requestId = generateRequestId();\n\tconst body = JSON.stringify(args);\n\t// Wire size in UTF-8 bytes — `body.length` counts UTF-16 code units and\n\t// undercounts non-ASCII payloads (matters for the 413 message and size logs).\n\tconst requestSize = utf8ByteLength(body);\n\tconst fullUrl = buildUrl(endpoint, config.serverUrl);\n\tconst headers = buildHeaders(requestId, config);\n\tconst retryPolicy = resolveRetryPolicy(config.retry);\n\tconst totalAttempts = retryPolicy.attempts + 1;\n\n\tif (config.debug) {\n\t\tconst sizeKb = (requestSize / 1024).toFixed(2);\n\t\tconst emoji = requestSize > 100000 ? '⚠️' : '🚀';\n\t\tlog(`${emoji} Starting compute request [${requestId}]: ${endpoint} (${sizeKb}KB)`, true);\n\t}\n\n\tconst ctx: AttemptContext = {\n\t\tendpoint,\n\t\tbody,\n\t\trequestSize,\n\t\tfullUrl,\n\t\trequestId,\n\t\theaders,\n\t\tconfig\n\t};\n\n\t// Every iteration ends in `return` or `throw` (issue 105): attemptFetch never\n\t// asks to retry on the final attempt (all its retry branches are gated on\n\t// `attempt < totalAttempts - 1`), so the exhausted-retries error is the final\n\t// attempt's own `result.cause` — there is no post-loop fallback to reach.\n\tfor (let attempt = 0; ; attempt++) {\n\t\tconst result = await attemptFetch(ctx, retryPolicy, attempt, totalAttempts);\n\n\t\tif (result.ok) return result.value as R;\n\n\t\tif (!result.retry) throw result.cause;\n\n\t\tif (config.debug) {\n\t\t\tlog(\n\t\t\t\t`🔁 Request [${requestId}] retrying after ${result.delayMs}ms (attempt ${attempt + 2}/${totalAttempts}): ${result.cause.message}`,\n\t\t\t\ttrue\n\t\t\t);\n\t\t}\n\n\t\ttry {\n\t\t\tawait sleep(result.delayMs, config.signal);\n\t\t} catch {\n\t\t\t// Caller cancelled during backoff\n\t\t\tthrow new RhinoComputeError('Request aborted by caller', ErrorCodes.ABORTED, {\n\t\t\t\tcontext: { endpoint, requestId, requestSize },\n\t\t\t\toriginalError: result.cause\n\t\t\t});\n\t\t}\n\t}\n}\n"]}
1
+ {"version":3,"sources":["d:\\Coding\\selva\\packages\\compute\\dist\\chunk-H3FZW6OX.cjs"],"names":[],"mappings":"AAAA,u8BAAI,CAAC,CAAC,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,EAAE,QAAQ,CAAC,CAAC,CAAC,EAAE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