@selvajs/compute 3.1.0-beta.9 → 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/dist/chunk-FQKQISPG.cjs +2 -0
- package/dist/chunk-FQKQISPG.cjs.map +1 -0
- package/dist/chunk-H3FZW6OX.cjs +4 -0
- package/dist/chunk-H3FZW6OX.cjs.map +1 -0
- package/dist/chunk-N2WCSETE.js +120 -0
- package/dist/chunk-N2WCSETE.js.map +1 -0
- package/dist/chunk-RFE763NG.cjs +120 -0
- package/dist/chunk-RFE763NG.cjs.map +1 -0
- package/dist/chunk-S3VUIIRE.js +2 -0
- package/dist/chunk-S3VUIIRE.js.map +1 -0
- package/dist/chunk-Y3M7P3BW.js +4 -0
- package/dist/chunk-Y3M7P3BW.js.map +1 -0
- package/dist/core.cjs +1 -1
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.cts +22 -1
- package/dist/core.d.ts +22 -1
- package/dist/core.js +1 -1
- package/dist/grasshopper.cjs +1 -1
- package/dist/grasshopper.cjs.map +1 -1
- package/dist/grasshopper.d.cts +22 -2
- package/dist/grasshopper.d.ts +22 -2
- package/dist/grasshopper.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/{types-Dtok-mVq.d.ts → types-4FMvnx2j.d.ts} +14 -1
- package/dist/{types-C8XWc4Ab.d.cts → types-BpOl6U02.d.cts} +14 -1
- package/dist/visualization-E6BTQZCA.cjs +2 -0
- package/dist/visualization-E6BTQZCA.cjs.map +1 -0
- package/dist/visualization-HDBKPJGQ.js +2 -0
- package/dist/visualization.cjs +1 -1
- package/dist/visualization.cjs.map +1 -1
- package/dist/visualization.d.cts +331 -29
- package/dist/visualization.d.ts +331 -29
- package/dist/visualization.js +1 -1
- package/package.json +55 -34
- package/dist/chunk-CUQQ3ZBV.cjs +0 -4
- package/dist/chunk-CUQQ3ZBV.cjs.map +0 -1
- package/dist/chunk-GFY3L653.cjs +0 -62
- package/dist/chunk-GFY3L653.cjs.map +0 -1
- package/dist/chunk-MJOXUCDH.js +0 -62
- package/dist/chunk-MJOXUCDH.js.map +0 -1
- package/dist/chunk-WPB2LKCD.js +0 -4
- package/dist/chunk-WPB2LKCD.js.map +0 -1
- package/dist/chunk-WWD655BZ.cjs +0 -2
- package/dist/chunk-WWD655BZ.cjs.map +0 -1
- package/dist/chunk-YREXY7GT.js +0 -2
- package/dist/chunk-YREXY7GT.js.map +0 -1
- package/dist/visualization-4PVR5P7N.js +0 -2
- package/dist/visualization-LS3Z7Q3N.cjs +0 -2
- package/dist/visualization-LS3Z7Q3N.cjs.map +0 -1
- /package/dist/{visualization-4PVR5P7N.js.map → visualization-HDBKPJGQ.js.map} +0 -0
package/package.json
CHANGED
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@selvajs/compute",
|
|
3
|
-
"version": "3.1.0
|
|
3
|
+
"version": "3.1.0",
|
|
4
4
|
"description": "TypeScript library for Rhino Compute Server - Grasshopper and RhinoCommon",
|
|
5
5
|
"author": "VektorNode",
|
|
6
6
|
"license": "MIT",
|
|
7
|
+
"homepage": "https://github.com/VektorNode/selva#readme",
|
|
8
|
+
"bugs": "https://github.com/VektorNode/selva/issues",
|
|
7
9
|
"repository": {
|
|
8
10
|
"type": "git",
|
|
9
|
-
"url": "git+https://github.com/VektorNode/selva
|
|
11
|
+
"url": "git+https://github.com/VektorNode/selva.git",
|
|
12
|
+
"directory": "packages/compute"
|
|
10
13
|
},
|
|
11
14
|
"type": "module",
|
|
12
15
|
"keywords": [
|
|
@@ -32,33 +35,53 @@
|
|
|
32
35
|
"types": "./dist/index.d.ts",
|
|
33
36
|
"exports": {
|
|
34
37
|
".": {
|
|
35
|
-
"
|
|
36
|
-
|
|
37
|
-
|
|
38
|
+
"import": {
|
|
39
|
+
"types": "./dist/index.d.ts",
|
|
40
|
+
"default": "./dist/index.js"
|
|
41
|
+
},
|
|
42
|
+
"require": {
|
|
43
|
+
"types": "./dist/index.d.cts",
|
|
44
|
+
"default": "./dist/index.cjs"
|
|
45
|
+
}
|
|
38
46
|
},
|
|
39
47
|
"./grasshopper": {
|
|
40
|
-
"
|
|
41
|
-
|
|
42
|
-
|
|
48
|
+
"import": {
|
|
49
|
+
"types": "./dist/grasshopper.d.ts",
|
|
50
|
+
"default": "./dist/grasshopper.js"
|
|
51
|
+
},
|
|
52
|
+
"require": {
|
|
53
|
+
"types": "./dist/grasshopper.d.cts",
|
|
54
|
+
"default": "./dist/grasshopper.cjs"
|
|
55
|
+
}
|
|
43
56
|
},
|
|
44
57
|
"./visualization": {
|
|
45
|
-
"
|
|
46
|
-
|
|
47
|
-
|
|
58
|
+
"import": {
|
|
59
|
+
"types": "./dist/visualization.d.ts",
|
|
60
|
+
"default": "./dist/visualization.js"
|
|
61
|
+
},
|
|
62
|
+
"require": {
|
|
63
|
+
"types": "./dist/visualization.d.cts",
|
|
64
|
+
"default": "./dist/visualization.cjs"
|
|
65
|
+
}
|
|
48
66
|
},
|
|
49
67
|
"./core": {
|
|
50
|
-
"
|
|
51
|
-
|
|
52
|
-
|
|
68
|
+
"import": {
|
|
69
|
+
"types": "./dist/core.d.ts",
|
|
70
|
+
"default": "./dist/core.js"
|
|
71
|
+
},
|
|
72
|
+
"require": {
|
|
73
|
+
"types": "./dist/core.d.cts",
|
|
74
|
+
"default": "./dist/core.cjs"
|
|
75
|
+
}
|
|
53
76
|
}
|
|
54
77
|
},
|
|
55
78
|
"files": [
|
|
56
79
|
"dist",
|
|
57
80
|
"README.md",
|
|
58
|
-
"LICENSE
|
|
81
|
+
"LICENSE"
|
|
59
82
|
],
|
|
60
83
|
"engines": {
|
|
61
|
-
"node": ">=
|
|
84
|
+
"node": ">=22.0.0"
|
|
62
85
|
},
|
|
63
86
|
"publishConfig": {
|
|
64
87
|
"access": "public",
|
|
@@ -82,30 +105,28 @@
|
|
|
82
105
|
}
|
|
83
106
|
},
|
|
84
107
|
"devDependencies": {
|
|
85
|
-
"@changesets/cli": "^2.30.0",
|
|
86
108
|
"@eslint/js": "^10.0.1",
|
|
87
|
-
"@types/node": "^
|
|
88
|
-
"@types/three": "^0.184.
|
|
89
|
-
"@vitest/coverage-v8": "^3.2.
|
|
90
|
-
"eslint": "^10.
|
|
109
|
+
"@types/node": "^22.20.1",
|
|
110
|
+
"@types/three": "^0.184.0",
|
|
111
|
+
"@vitest/coverage-v8": "^3.2.6",
|
|
112
|
+
"eslint": "^10.7.0",
|
|
91
113
|
"eslint-config-prettier": "^10.1.8",
|
|
92
|
-
"eslint-plugin-svelte": "^3.
|
|
93
|
-
"globals": "^17.
|
|
94
|
-
"husky": "^9.1.7",
|
|
114
|
+
"eslint-plugin-svelte": "^3.20.0",
|
|
115
|
+
"globals": "^17.5.0",
|
|
95
116
|
"lint-staged": "^17.0.7",
|
|
96
|
-
"prettier": "^3.8.
|
|
97
|
-
"prettier-plugin-svelte": "^
|
|
98
|
-
"prettier-plugin-tailwindcss": "^0.
|
|
99
|
-
"svelte": "
|
|
100
|
-
"three": "^0.
|
|
117
|
+
"prettier": "^3.8.3",
|
|
118
|
+
"prettier-plugin-svelte": "^3.5.1",
|
|
119
|
+
"prettier-plugin-tailwindcss": "^0.7.3",
|
|
120
|
+
"svelte": "5.56.4",
|
|
121
|
+
"three": "^0.184.0",
|
|
101
122
|
"tsup": "^8.5.1",
|
|
102
123
|
"typedoc": "^0.28.17",
|
|
103
124
|
"typedoc-plugin-extras": "^4.0.1",
|
|
104
125
|
"typedoc-plugin-missing-exports": "^4.1.2",
|
|
105
126
|
"typescript": "^6.0.3",
|
|
106
|
-
"typescript-eslint": "^8.
|
|
107
|
-
"vite": "^8.
|
|
108
|
-
"vitest": "^3.2.
|
|
127
|
+
"typescript-eslint": "^8.64.0",
|
|
128
|
+
"vite": "^8.1.4",
|
|
129
|
+
"vitest": "^3.2.7"
|
|
109
130
|
},
|
|
110
131
|
"scripts": {
|
|
111
132
|
"build": " pnpm type-check && pnpm clean && tsup",
|
|
@@ -118,13 +139,13 @@
|
|
|
118
139
|
"format:check": "prettier --check .",
|
|
119
140
|
"test": "vitest",
|
|
120
141
|
"test:watch": "vitest watch",
|
|
142
|
+
"bench": "vitest bench --run",
|
|
121
143
|
"contract:snapshot": "node scripts/fetch-server-contract.mjs",
|
|
122
144
|
"contract:check": "node scripts/fetch-server-contract.mjs --check",
|
|
123
145
|
"test:seams": "vitest run tests/contract",
|
|
124
146
|
"test:seams:live": "RUN_LIVE_CONTRACT=1 vitest run tests/contract/server-contract.live.test.ts",
|
|
125
147
|
"test:stats:live": "vitest run tests/contract/compute-server-stats.live.test.ts",
|
|
126
148
|
"type-check": "tsc --noEmit",
|
|
127
|
-
"build-docs": "typedoc"
|
|
128
|
-
"release": "changeset publish"
|
|
149
|
+
"build-docs": "typedoc"
|
|
129
150
|
}
|
|
130
151
|
}
|
package/dist/chunk-CUQQ3ZBV.cjs
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
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 M=Object.defineProperty;var Z=(t,e,r)=>e in t?M(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var Ne=(t,e)=>{for(var r in e)M(t,r,{get:e[r],enumerable:!0})};var h=(t,e,r)=>Z(t,typeof e!="symbol"?e+"":e,r);var u={NETWORK_ERROR:"NETWORK_ERROR",AUTH_ERROR:"AUTH_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",COMPUTATION_ERROR:"COMPUTATION_ERROR",TIMEOUT_ERROR:"TIMEOUT_ERROR",CORS_ERROR:"CORS_ERROR",NOT_FOUND:"NOT_FOUND",RATE_LIMIT:"RATE_LIMIT",INVALID_RESPONSE:"INVALID_RESPONSE",UNKNOWN_ERROR:"UNKNOWN_ERROR",INVALID_STATE:"INVALID_STATE",INVALID_INPUT:"INVALID_INPUT",INVALID_CONFIG:"INVALID_CONFIG",BROWSER_ONLY:"BROWSER_ONLY",ENVIRONMENT_ERROR:"ENVIRONMENT_ERROR",ENCODING_ERROR:"ENCODING_ERROR",MALFORMED_DEFAULT:"MALFORMED_DEFAULT",SUPERSEDED:"SUPERSEDED",ABORTED:"ABORTED",QUEUE_FULL:"QUEUE_FULL",QUEUE_TIMEOUT:"QUEUE_TIMEOUT",DEFINITION_NOT_CACHED:"DEFINITION_NOT_CACHED"},p= exports.d =class t extends Error{constructor(r,n=u.UNKNOWN_ERROR,o){super(r);h(this,"code");h(this,"statusCode");h(this,"context");h(this,"originalError");this.name="RhinoComputeError",this.code=n,this.statusCode=_optionalChain([o, 'optionalAccess', _2 => _2.statusCode]),this.context=_optionalChain([o, 'optionalAccess', _3 => _3.context]),this.originalError=_optionalChain([o, 'optionalAccess', _4 => _4.originalError]),_optionalChain([o, 'optionalAccess', _5 => _5.originalError])&&(this.cause=o.originalError)}static missingValues(r,n,o){return new t(`Input "${r}" has no values defined${n?` (expected ${n})`:""}`,u.INVALID_INPUT,{context:{inputName:r,expectedType:n,...o}})}static unknownParamType(r,n,o){return new t(`Unknown paramType: ${r}`,u.VALIDATION_ERROR,{context:{receivedParamType:r,paramName:n,...o}})}};var O=class{debug(){}info(){}warn(){}error(){}},$=class{debug(e,...r){console.debug(e,...r)}info(e,...r){console.info(e,...r)}warn(e,...r){console.warn(e,...r)}error(e,...r){console.error(e,...r)}},_=new O;function m(){return _}function F(t){if(t===null){_=new O;return}let e=["debug","info","warn","error"].filter(r=>typeof t[r]!="function");if(e.length>0)throw new p(`Logger is missing required method(s): ${e.join(", ")}. A logger must implement debug, info, warn and error.`,u.INVALID_CONFIG,{context:{missingMethods:e}});_=t}function Q(){F(new $)}function I(){let t=globalThis.Buffer;return typeof t=="function"?t:void 0}function Me(t){let e=I();return e?e.from(t,"utf-8").toString("base64"):te(new TextEncoder().encode(t))}var X=64,ee="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function Fe(t){if(!t)return null;let e=t.replace(/[\t\n\f\r ]/g,"");e.length%4===0&&(e=e.replace(/={1,2}$/,""));let r=e.length%4;if(r===1||e.length<X||!/^[A-Za-z0-9+/]*$/.test(e))return null;let n=ee.indexOf(e.charAt(e.length-1));return r===2&&(n&15)!==0||r===3&&(n&3)!==0?null:r===0?e:e+"==".slice(0,4-r)}function k(t){let e=t.replace(/[\t\n\f\r ]/g,"");if(e.length%4===0&&(e=e.replace(/={1,2}$/,"")),e.length%4===1||!/^[A-Za-z0-9+/]*$/.test(e))throw new p("Invalid base64 input.",u.ENCODING_ERROR,{context:{inputLength:t.length}});let r=I();if(r)return new Uint8Array(r.from(e,"base64"));if(typeof globalThis.atob=="function"){let n=globalThis.atob(e),o=new Uint8Array(n.length);for(let s=0;s<n.length;s++)o[s]=n.charCodeAt(s)&255;return o}throw new p("Base64 decoding not supported in this environment.",u.INVALID_STATE,{context:{environmentInfo:"atob or Buffer not available"}})}function x(t){let e=I();if(e)return e.byteLength(t,"utf-8");let r=0;for(let n=0;n<t.length;n++){let o=t.charCodeAt(n);o<128?r+=1:o<2048?r+=2:o>=55296&&o<=56319&&n+1<t.length&&(t.charCodeAt(n+1)&64512)===56320?(r+=4,n++):r+=3}return r}function te(t){let e=I();if(e)return e.from(t).toString("base64");if(typeof globalThis.btoa=="function"){let n=[];for(let o=0;o<t.length;o+=32766)n.push(globalThis.btoa(String.fromCharCode.apply(null,t.subarray(o,o+32766))));return n.join("")}throw new p("Base64 encoding not supported in this environment.",u.INVALID_STATE,{context:{environmentInfo:"btoa or Buffer not available"}})}function re(t){if(!t)return null;let e={raw:t},r=!1;for(let n of t.split(",")){let[o,...s]=n.trim().split(";"),l=s.find(f=>f.trim().toLowerCase().startsWith("dur"));if(!l)continue;let i=Number(l.split("=")[1]);if(!Number.isFinite(i))continue;let a=o.trim().toLowerCase();(a==="decode"||a==="solve"||a==="encode")&&(e[a]=i,r=!0)}return r?e:null}var v={attempts:0,baseDelayMs:500,maxDelayMs:3e4,retryOn429:!0},P=new Set([502,503,504]),ne=6e4,U=4096;function oe(t){return t?{attempts:_nullishCoalesce(t.attempts, () => (v.attempts)),baseDelayMs:_nullishCoalesce(t.baseDelayMs, () => (v.baseDelayMs)),maxDelayMs:_nullishCoalesce(t.maxDelayMs, () => (v.maxDelayMs)),retryOn429:_nullishCoalesce(t.retryOn429, () => (v.retryOn429))}:v}function se(t){if(!t)return null;let e=Number(t);if(Number.isFinite(e)&&e>=0)return e*1e3;let r=Date.parse(t);if(Number.isFinite(r)){let n=r-Date.now();return n>0?n:0}return null}function C(t,e){let r=e.baseDelayMs*Math.pow(2,t),n=Math.random()*e.baseDelayMs;return Math.min(r+n,e.maxDelayMs)}function ie(t,e){return new Promise((r,n)=>{if(_optionalChain([e, 'optionalAccess', _6 => _6.aborted])){n(new DOMException("Aborted","AbortError"));return}let o=setTimeout(()=>{_optionalChain([e, 'optionalAccess', _7 => _7.removeEventListener, 'call', _8 => _8("abort",s)]),r()},t),s=()=>{clearTimeout(o),n(new DOMException("Aborted","AbortError"))};_optionalChain([e, 'optionalAccess', _9 => _9.addEventListener, 'call', _10 => _10("abort",s,{once:!0})])})}function ae(t){return t.length<=U?t:`${t.slice(0,U)}\u2026 [truncated ${t.length-U} chars]`}function ue(t,e,r,n,o,s,l,i){let{status:a,statusText:f}=t,c={};t.headers.forEach((G,Y)=>{c[Y]=G});let g=s.trim(),d=g?` \u2014 ${g.slice(0,200)}${g.length>200?"\u2026":""}`:"",E=_nullishCoalesce(i, () => (s)),T={url:e,requestId:r,method:"POST",requestSize:n,serverUrl:o,responseBody:E?ae(E):void 0,responseHeaders:c},b={401:{message:`HTTP ${a}: ${f}${d}`,code:u.AUTH_ERROR},403:{message:`HTTP ${a}: ${f}${d}`,code:u.AUTH_ERROR},404:{message:`Endpoint not found: ${e}`,code:u.NOT_FOUND},413:{message:`Request too large: ${(n/1024).toFixed(2)}KB`,code:u.VALIDATION_ERROR},429:{message:`Rate limit exceeded${d}`,code:u.RATE_LIMIT},500:{message:`Server error: ${f}${d}`,code:u.COMPUTATION_ERROR},502:{message:`Service unavailable: ${f}${d}`,code:u.NETWORK_ERROR},503:{message:`Service unavailable: ${f}${d}`,code:u.NETWORK_ERROR},504:{message:`Service unavailable: ${f}${d}`,code:u.NETWORK_ERROR}}[a]||{message:`HTTP ${a}: ${f}${d}`,code:u.UNKNOWN_ERROR},D=_nullishCoalesce(le(l), () => (b.code));throw new p(b.message,D,{statusCode:a,context:T})}function le(t){if(t==="definition_not_cached")return u.DEFINITION_NOT_CACHED}function ce(t,e){let r=e.replace(/\/+$/,""),n=t.replace(/^\/+/,"");return`${r}/${n}`}function de(t){try{let e=new URL(t).hostname.toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}catch (e2){return/(localhost|127\.0\.0\.1|\[::1\])/i.test(t)}}var B=new Set;function fe(t,e){let r={...e.headers,"X-Request-ID":t,"Content-Type":"application/json",...e.authToken&&{Authorization:e.authToken},...e.apiKey&&{RhinoComputeKey:e.apiKey}};return!e.apiKey&&!e.authToken&&!B.has(e.serverUrl)&&!de(e.serverUrl)&&(B.add(e.serverUrl),m().warn(`\u26A0\uFE0F [Rhino Compute] Request [${t}] targets remote server (${e.serverUrl}) but no API key or auth token is configured. Requests may fail or be rate-limited. (warned once per server)`)),r}function pe(){return`${Date.now()}-${Math.random().toString(36).substring(2,11)}`}function y(t,e){e&&m().debug(t)}function me(t,e){let r=()=>{},n=typeof e=="number"&&e>0;if(!t&&!n)return{signal:void 0,cleanup:r};if(t&&!n)return{signal:t,cleanup:r};let o=typeof AbortSignal<"u"&&typeof AbortSignal.timeout=="function";if(!t){if(o)return{signal:AbortSignal.timeout(e),cleanup:r};let c=new AbortController,g=setTimeout(()=>c.abort(),e);return{signal:c.signal,cleanup:()=>clearTimeout(g)}}let s=new AbortController,l,i;if(o)l=AbortSignal.timeout(e);else{let c=new AbortController;i=setTimeout(()=>c.abort(),e),l=c.signal}let a=[t,l],f=function(){s.abort(this.reason)};for(let c of a){if(c.aborted){s.abort(c.reason);break}c.addEventListener("abort",f,{once:!0})}return{signal:s.signal,cleanup:()=>{i!==void 0&&clearTimeout(i);for(let c of a)c.removeEventListener("abort",f)}}}function q(t,e,r,n){if(!r)return;let o=re(t.headers.get("Server-Timing"));if(o)try{r(o,e)}catch(s){n&&y(` onServerTiming callback threw: ${s}`,!0)}}async function ge(t,e,r,n,o,s,l,i){let a=Math.round(performance.now()-s);if(!t.ok){let f=await t.text(),c=f;l&&(y(`\u274C Request [${r}] failed with HTTP ${t.status} in ${a}ms`,!0),y(` URL: ${e}`,!0),y(` Status: ${t.status} ${t.statusText}`,!0),c&&y(` Response body: ${c.substring(0,500)}${c.length>500?"...":""}`,!0));let g;try{let d=JSON.parse(c);typeof _optionalChain([d, 'optionalAccess', _11 => _11.code])=="string"&&(g=d.code)}catch (e3){}if(t.status===500)try{let d=JSON.parse(c);if(_optionalChain([d, 'optionalAccess', _12 => _12.values])&&(d.errors||d.warnings))return l&&(y(`\u26A0\uFE0F Request [${r}] completed with Grasshopper errors in ${a}ms`,!0),_optionalChain([d, 'access', _13 => _13.errors, 'optionalAccess', _14 => _14.length])>0&&y(` Errors: ${JSON.stringify(d.errors,null,2)}`,!0),_optionalChain([d, 'access', _15 => _15.warnings, 'optionalAccess', _16 => _16.length])>0&&y(` Warnings: ${JSON.stringify(d.warnings,null,2)}`,!0)),q(t,r,i,l),d;let E=typeof _optionalChain([d, 'optionalAccess', _17 => _17.message])=="string"&&d.message||typeof _optionalChain([d, 'optionalAccess', _18 => _18.Message])=="string"&&d.Message||"",T=typeof _optionalChain([d, 'optionalAccess', _19 => _19.ExceptionType])=="string"&&d.ExceptionType||"",S=_nullishCoalesce(_optionalChain([d, 'optionalAccess', _20 => _20.stackTrace]), () => (_optionalChain([d, 'optionalAccess', _21 => _21.StackTrace]))),b=Array.isArray(S)?S.join(`
|
|
2
|
-
`):S||"";E?c=`${T?`${T}: `:""}${E}${b?`
|
|
3
|
-
${b}`:""}`:_optionalChain([d, 'optionalAccess', _22 => _22.error])&&(c=typeof d.error=="string"?d.error:JSON.stringify(d.error,null,2))}catch(d){l&&y(` Failed to parse error body as JSON: ${d}`,!0)}ue(t,e,r,n,o,c,g,f)}y(`\u2705 Request [${r}] completed in ${a}ms`,l),q(t,r,i,l);try{return await t.json()}catch(f){let c=(_nullishCoalesce(t.headers.get("Content-Type"), () => (""))).toLowerCase();throw c!==""&&!c.includes("json")?new p(`Server returned a non-JSON response (Content-Type: ${c}) \u2014 check the server URL / proxy configuration`,u.INVALID_RESPONSE,{statusCode:t.status,context:{url:e,requestId:r,contentType:c},originalError:f instanceof Error?f:new Error(String(f))}):new p("Failed to parse JSON response",u.NETWORK_ERROR,{statusCode:t.status,context:{url:e,requestId:r},originalError:f instanceof Error?f:new Error(String(f))})}}async function he(t,e,r,n){let{signal:o,cleanup:s}=me(t.config.signal,t.config.timeoutMs),l=performance.now();try{let i=await fetch(t.fullUrl,{method:"POST",body:t.body,headers:t.headers,signal:o});if((P.has(i.status)||e.retryOn429&&i.status===429)&&r<n-1){let c=se(i.headers.get("Retry-After")),g=c!==null?Math.min(c,Math.max(e.maxDelayMs,ne)):C(r,e);return await i.text().catch(()=>{}),{ok:!1,retry:!0,delayMs:g,cause:new p(`HTTP ${i.status} ${i.statusText} (will retry)`,i.status===429?u.RATE_LIMIT:u.NETWORK_ERROR,{statusCode:i.status,context:{requestId:t.requestId}})}}return{ok:!0,value:await ge(i,t.fullUrl,t.requestId,t.requestSize,t.config.serverUrl,l,t.config.debug,t.config.onServerTiming)}}catch(i){if(i instanceof Error&&(i.name==="AbortError"||i.name==="TimeoutError")){if(_optionalChain([t, 'access', _23 => _23.config, 'access', _24 => _24.signal, 'optionalAccess', _25 => _25.aborted])===!0)return{ok:!1,retry:!1,cause:new p("Request aborted by caller",u.ABORTED,{context:{endpoint:t.endpoint,requestId:t.requestId,requestSize:t.requestSize},originalError:i})};let c=typeof t.config.timeoutMs=="number"&&t.config.timeoutMs>0?new p(`Request timed out after ${t.config.timeoutMs}ms`,u.TIMEOUT_ERROR,{context:{serverUrl:t.config.serverUrl,timeoutMs:t.config.timeoutMs,url:t.fullUrl,requestId:t.requestId,endpoint:t.endpoint,requestSize:t.requestSize},originalError:i}):new p(`Request aborted by the runtime (${i.name}): ${i.message}`,u.NETWORK_ERROR,{context:{serverUrl:t.config.serverUrl,url:t.fullUrl,requestId:t.requestId,endpoint:t.endpoint,requestSize:t.requestSize},originalError:i});return r<n-1?{ok:!1,retry:!0,delayMs:C(r,e),cause:c}:{ok:!1,retry:!1,cause:c}}if(i instanceof TypeError){let a=typeof window<"u"&&typeof window.document<"u",f={serverUrl:t.config.serverUrl,url:t.fullUrl,requestId:t.requestId,endpoint:t.endpoint,requestSize:t.requestSize},c=a?new p(`Request failed: ${i.message} \u2014 in a browser this usually means a CORS misconfiguration on the server (or a network failure; the browser does not distinguish them)`,u.CORS_ERROR,{context:f,originalError:i}):new p(`Network error: ${i.message}`,u.NETWORK_ERROR,{context:f,originalError:i});return r<n-1?{ok:!1,retry:!0,delayMs:C(r,e),cause:c}:{ok:!1,retry:!1,cause:c}}if(i instanceof p){let a=i.statusCode;return(i.code===u.NETWORK_ERROR&&a!==void 0&&a>=200&&a<300||a!==void 0&&(P.has(a)||e.retryOn429&&a===429))&&r<n-1?{ok:!1,retry:!0,delayMs:C(r,e),cause:i}:{ok:!1,retry:!1,cause:i}}return{ok:!1,retry:!1,cause:new p(i instanceof Error?i.message:String(i),u.UNKNOWN_ERROR,{context:{endpoint:t.endpoint,requestId:t.requestId},originalError:i instanceof Error?i:new Error(String(i))})}}finally{s()}}async function ye(t,e,r){let n=pe(),o=JSON.stringify(e),s=x(o),l=ce(t,r.serverUrl),i=fe(n,r),a=oe(r.retry),f=a.attempts+1;if(r.debug){let g=(s/1024).toFixed(2),d=s>1e5?"\u26A0\uFE0F":"\u{1F680}";y(`${d} Starting compute request [${n}]: ${t} (${g}KB)`,!0)}let c={endpoint:t,body:o,requestSize:s,fullUrl:l,requestId:n,headers:i,config:r};for(let g=0;;g++){let d=await he(c,a,g,f);if(d.ok)return d.value;if(!d.retry)throw d.cause;r.debug&&y(`\u{1F501} Request [${n}] retrying after ${d.delayMs}ms (attempt ${g+2}/${f}): ${d.cause.message}`,!0);try{await ie(d.delayMs,r.signal)}catch (e4){throw new p("Request aborted by caller",u.ABORTED,{context:{endpoint:t,requestId:n,requestSize:s},originalError:d.cause})}}}var Re="compute.rhino3d.com";function K(t){let e=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _26 => _26.trim, 'call', _27 => _27()]), () => (""));if(!e)throw new p("serverUrl is required",u.INVALID_CONFIG,{context:{receivedServerUrl:t}});if(!/^https?:\/\//i.test(e))throw new p(`Invalid serverUrl: "${e}". Must start with "http://" or "https://". For example: "http://localhost:5000" or "https://example.com"`,u.INVALID_CONFIG,{context:{receivedServerUrl:t}});let r;try{r=new URL(e)}catch(o){throw new p(`Invalid serverUrl: "${e}". Must be a valid URL. Received error: ${o instanceof Error?o.message:String(o)}`,u.INVALID_CONFIG,{context:{receivedServerUrl:t},originalError:o instanceof Error?o:void 0})}if(r.username!==""||r.password!=="")throw new p(`Invalid serverUrl: "${e}". Must not embed credentials (user:pass@host) \u2014 fetch rejects credentialed URLs at request time. Pass the API key separately.`,u.INVALID_CONFIG,{context:{receivedServerUrl:t}});if(e.includes("?")||e.includes("#"))throw new p(`Invalid serverUrl: "${e}". Must not contain a query string or fragment \u2014 endpoint paths are appended to this URL (e.g. "\${serverUrl}/version"), and a "?" or "#" suffix would corrupt every request path.`,u.INVALID_CONFIG,{context:{receivedServerUrl:t}});if(r.hostname.toLowerCase().replace(/\.+$/,"")===Re)throw new p("serverUrl must be set to your Compute server URL. The default public endpoint is not allowed.",u.INVALID_CONFIG,{context:{receivedServerUrl:t}});return e.replace(/\/+$/,"")}var R=class R{constructor(e,r){h(this,"serverUrl");h(this,"apiKey");h(this,"disposed",!1);h(this,"activeMonitors",new Set);h(this,"activeTimeouts",new Set);this.serverUrl=K(e),this.apiKey=r}buildHeaders(){let e={"Content-Type":"application/json"};return this.apiKey&&(e.RhinoComputeKey=this.apiKey),e}fetchWithTimeout(e,r={},n=R.DEFAULT_TIMEOUT_MS){let o=new Headers(this.buildHeaders());r.headers&&new Headers(r.headers).forEach((i,a)=>{o.set(a,i)});let s={};o.forEach((i,a)=>{s[a]=i});let l={...r,headers:s};return n>0&&!l.signal&&(l.signal=AbortSignal.timeout(n)),fetch(e,l)}async isServerOnline(e=5e3){this.ensureNotDisposed();let r=`${this.serverUrl}/`;try{return(await this.fetchWithTimeout(r,{method:"GET"},e)).ok}catch(n){return m().debug("[ComputeServerStats] Fetch error:",n),!1}}async getActiveChildren(e={}){this.ensureNotDisposed();let{initialize:r=!0}=e,n=r?`${this.serverUrl}/activechildren`:`${this.serverUrl}/activechildren?initialize=false`,o=r?R.LIFECYCLE_TIMEOUT_MS:R.DEFAULT_TIMEOUT_MS;try{let s=await this.fetchWithTimeout(n,{},o);if(!s.ok)return m().warn("[ComputeServerStats] Failed to fetch active children:",s.status),null;let l=(await s.text()).trim();return/^\d+$/.test(l)?parseInt(l,10):(m().warn("[ComputeServerStats] Invalid active children response:",l),null)}catch(s){return m().warn("[ComputeServerStats] Error fetching active children:",s),null}}async getVersion(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/version`);if(!e.ok)return m().warn("[ComputeServerStats] Failed to fetch version:",e.status),null;let r=await e.text();try{let n=JSON.parse(r);return{rhino:_nullishCoalesce(n.rhino, () => ("")),compute:_nullishCoalesce(n.compute, () => ("")),git_sha:_nullishCoalesce(n.git_sha, () => (null))}}catch (e5){return{rhino:r,compute:"",git_sha:null}}}catch(e){return m().warn("[ComputeServerStats] Error fetching version:",e),null}}async getInstalledPlugins(e="gh"){this.ensureNotDisposed();try{let r=await this.fetchWithTimeout(`${this.serverUrl}/plugins/${e}/installed`);if(!r.ok)return m().warn(`[ComputeServerStats] Failed to fetch ${e} plugins:`,r.status),null;let n=await r.text();try{let o=JSON.parse(n);return o&&typeof o=="object"?o:null}catch (e6){return null}}catch(r){return m().warn(`[ComputeServerStats] Error fetching ${e} plugins:`,r),null}}async getServerStats(){if(this.ensureNotDisposed(),!await this.isServerOnline())return{isOnline:!1};let[r,n]=await Promise.all([this.getVersion(),this.getActiveChildren({initialize:!1})]);return{isOnline:!0,...r&&{version:r},...n!==null&&{activeChildren:n}}}async purgeCache(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/cache/purge`,{method:"POST"});if(!e.ok)return m().warn("[ComputeServerStats] Failed to purge cache:",e.status),null;let r=await e.text();try{let n=JSON.parse(r);return typeof n.purged=="number"?n.purged:null}catch (e7){return null}}catch(e){return m().warn("[ComputeServerStats] Error purging cache:",e),null}}async purgeAllChildren(){this.ensureNotDisposed();let e=await this.getActiveChildren({initialize:!1});if(e===null)return m().warn("[ComputeServerStats] purgeAllChildren: could not read child count"),null;if(e===0)return{totalPurged:0,calls:0,children:0,confident:!0};let r=e*2,n=0;for(let o=0;o<r;o++){let s=await this.purgeCache();s!==null&&(n+=s)}return{totalPurged:n,calls:r,children:e,confident:e===1}}async getServerTime(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/servertime`);if(!e.ok)return m().warn("[ComputeServerStats] Failed to fetch server time:",e.status),null;let r=(await e.text()).trim().replace(/^"|"$/g,""),n=new Date(r);return isNaN(n.getTime())?null:n}catch(e){return m().warn("[ComputeServerStats] Error fetching server time:",e),null}}async getIdleSpan(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/idlespan`);if(!e.ok)return m().warn("[ComputeServerStats] Failed to fetch idle span:",e.status),null;let r=parseFloat((await e.text()).trim());return isNaN(r)?null:r}catch(e){return m().warn("[ComputeServerStats] Error fetching idle span:",e),null}}async launchChildren(){return this.postJson("/launch-children")}async launchChild(e){let r=e===void 0?"/launch-child":`/launch-child?port=${e}`;return this.postJson(r)}async shutdownChildren(e){let r=e===void 0?"/shutdown-children":`/shutdown-children?port=${e}`;return this.postJson(r)}async recycleChildren(e){let r=e===void 0?"/recycle-children":`/recycle-children?port=${e}`;return this.postJson(r)}async postJson(e){this.ensureNotDisposed();try{let r=await this.fetchWithTimeout(`${this.serverUrl}${e}`,{method:"POST"},R.LIFECYCLE_TIMEOUT_MS);if(!r.ok)return m().warn(`[ComputeServerStats] POST ${e} failed:`,r.status),null;let n=await r.text();try{return JSON.parse(n)}catch (e8){return null}}catch(r){return m().warn(`[ComputeServerStats] Error on POST ${e}:`,r),null}}monitor(e,r=5e3){if(this.ensureNotDisposed(),!Number.isFinite(r)||r<R.MIN_MONITOR_INTERVAL_MS)throw new RangeError(`monitor() intervalMs must be a finite number >= ${R.MIN_MONITOR_INTERVAL_MS}ms, got ${r}. Sub-${R.MIN_MONITOR_INTERVAL_MS}ms polling would hot-loop the server.`);let n=!0,o=null;m().info(`\u{1F504} Starting server stats monitoring every ${r}ms`);let s=async()=>{if(o!==null&&(this.activeTimeouts.delete(o),o=null),!(!n||this.disposed)){try{let i=await this.getServerStats();if(!n||this.disposed)return;try{e(i)}catch(a){m().error("[ComputeServerStats] Monitor callback threw:",a)}}catch(i){!n||this.disposed?m().debug("[ComputeServerStats] Monitor poll cancelled during shutdown:",i):m().error("[ComputeServerStats] Failed to fetch stats during monitor:",i)}n&&!this.disposed&&(o=setTimeout(()=>{s()},r),this.activeTimeouts.add(o))}},l=()=>{n=!1,o!==null&&(clearTimeout(o),this.activeTimeouts.delete(o),o=null),this.activeMonitors.delete(l)};return this.activeMonitors.add(l),s(),l}async dispose(){if(!this.disposed){this.disposed=!0;for(let e of this.activeMonitors)e();this.activeMonitors.clear();for(let e of this.activeTimeouts)clearTimeout(e);this.activeTimeouts.clear()}}ensureNotDisposed(){if(this.disposed)throw new p("ComputeServerStats has been disposed and cannot be used",u.INVALID_STATE,{context:{disposed:this.disposed}})}};h(R,"DEFAULT_TIMEOUT_MS",5e3),h(R,"LIFECYCLE_TIMEOUT_MS",6e4),h(R,"MIN_MONITOR_INTERVAL_MS",100);var N=R;function V(t,e={}){let{preserveSpaces:r=!1}=e,n=r?/[-_]+(.)?/g:/[\s\-_]+(.)?/g,o=t.trim().replace(n,(s,l)=>l?l.toUpperCase():"");return o=o.replace(/^[A-Z]+(?=[A-Z][a-z]|[^A-Za-z]|$)/,s=>s.toLowerCase()),o.charAt(0).toLowerCase()+o.slice(1)}function we(t){if(t===null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function L(t,e={}){if(!t||typeof t!="object")return t;if(Array.isArray(t))return e.deep?t.map(n=>L(n,e)):t;if(!we(t))return t;let r={};for(let n of Object.keys(t)){let o=V(n,{preserveSpaces:e.preserveSpaces});Object.prototype.hasOwnProperty.call(r,o)&&m().warn(`camelcaseKeys: key '${n}' collides with an earlier key on '${o}' \u2014 the earlier value is overwritten (last key wins).`);let s=t[n];r[o]=e.deep?L(s,e):s}return r}function w(t,e){if(!t||typeof t!="object")return;let r=t;if(z(r,e))return r[e];let n=H(r).get(e.toLowerCase());return n===void 0?void 0:r[n]}var z=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);function Ze(t,e){if(!t||typeof t!="object")return!1;let r=t;return z(r,e)?!0:H(r).has(e.toLowerCase())}var W=new WeakMap;function H(t){let e=Object.keys(t),r=W.get(t);if(r&&r.keyCount===e.length)return r.map;let n=new Map;for(let o of e){let s=o.toLowerCase();n.has(s)||n.set(s,o)}return W.set(t,{keyCount:e.length,map:n}),n}var Ee=async(t,e=null)=>{try{return await J(t,e)}catch(r){throw new p("Failed to extract files from compute response",u.INVALID_STATE,{context:{originalError:r instanceof Error?r.message:String(r)},originalError:r instanceof Error?r:void 0})}},be= exports.t =async(t,e,r=null)=>{if(typeof document>"u"||typeof Blob>"u")throw new p("File download functionality is only available in browser environments. This function requires the DOM API (document, Blob).",u.BROWSER_ONLY,{context:{environment:typeof window<"u"?"browser (SSR)":"Node.js",documentAvailable:typeof document<"u",blobAvailable:typeof Blob<"u"}});try{let n=await J(t,r);await Ie(n,e)}catch(n){throw n instanceof p?n:new p("Failed to download files from compute response",u.INVALID_STATE,{context:{originalError:n instanceof Error?n.message:String(n)},originalError:n instanceof Error?n:void 0})}},A=t=>t.replace(/\\/g,"/").split("/").map(e=>e.trim()).filter(e=>e!==""&&e!=="."&&e!==".."&&!/^[a-zA-Z]:$/.test(e)).join("/"),ve=t=>t===!0||typeof t=="string"&&t.trim().toLowerCase()==="true",Te=t=>{let e=[];return t.forEach(r=>{let n=_nullishCoalesce(w(r,"fileName"), () => ("")),o=_nullishCoalesce(w(r,"fileType"), () => ("")),s=A(`${n}${o}`);if(s===""){m().warn(`Skipping file with unusable name "${n}${o}": no safe archive path remains after sanitization.`);return}let l=w(r,"subFolder"),i=l?A(l):"",a=i!==""?`${i}/${s}`:s,f=w(r,"data");if(typeof f!="string"||f===""){m().warn(`Skipping file "${a}": item carries no usable data.`);return}if(ve(w(r,"isBase64Encoded")))try{e.push({fileName:s,content:k(f),path:a})}catch(c){m().warn(`Skipping file "${a}": base64 decode failed.`,c)}else e.push({fileName:s,content:f,path:a})}),e},Se=3e4,Oe=async t=>(await Promise.all(t.map(async r=>{try{let n=typeof AbortSignal<"u"&&typeof AbortSignal.timeout=="function"?AbortSignal.timeout(Se):void 0,o=await fetch(r.filePath,{signal:n});if(!o.ok)return m().warn(`Failed to fetch additional file from URL: ${r.filePath}`),null;let s=await o.arrayBuffer(),l=A(r.fileName);if(l==="")return m().warn(`Skipping fetched file with unusable name: ${r.fileName}`),null;let i=r.subFolder?A(r.subFolder):"";return{fileName:l,content:new Uint8Array(s),path:i!==""?`${i}/${l}`:l}}catch(n){return m().error(`Error fetching additional file from URL: ${r.filePath}`,n),null}}))).filter(r=>r!==null),J=async(t,e)=>{let r=Te(t);if(e){let o=Array.isArray(e)?e:[e];r.push(...await Oe(o))}let n=new Set;return r.map(o=>{let s=j(o.path,n);return n.add(s),s===o.path?o:(m().warn(`Duplicate archive path "${o.path}" \u2014 storing as "${s}".`),{...o,path:s,fileName:s.slice(s.lastIndexOf("/")+1)})})};async function Ie(t,e){let{zip:r,strToU8:n}=await Promise.resolve().then(() => _interopRequireWildcard(require("fflate"))),o={},s=new Set;t.forEach(a=>{let f=j(a.path,s);s.add(f),f!==a.path&&m().warn(`Duplicate archive path "${a.path}" \u2014 storing as "${f}".`),o[f]=typeof a.content=="string"?n(a.content):a.content});let l=await new Promise((a,f)=>{r(o,{level:6},(c,g)=>c?f(c):a(g))}),i=new Blob([l],{type:"application/zip"});Ce(i,`${e}.zip`)}function j(t,e){if(!e.has(t))return t;let r=t.lastIndexOf("/"),n=t.lastIndexOf("."),o=n>r?n:t.length,s=t.slice(0,o),l=t.slice(o);for(let i=2;;i++){let a=`${s}-${i}${l}`;if(!e.has(a))return a}}function Ce(t,e){if(typeof document>"u")throw new p("saveFile requires a browser environment with DOM API access.",u.BROWSER_ONLY,{context:{function:"saveFile",requiredAPI:"document"}});let r=URL.createObjectURL(t),n=document.createElement("a");n.href=r,n.download=e,document.body.appendChild(n),n.click(),n.remove(),setTimeout(()=>URL.revokeObjectURL(r),1e4)}exports.a = Ne; exports.b = h; exports.c = u; exports.d = p; exports.e = m; exports.f = F; exports.g = Q; exports.h = Me; exports.i = Fe; exports.j = k; exports.k = te; exports.l = ye; exports.m = K; exports.n = N; exports.o = V; exports.p = L; exports.q = w; exports.r = Ze; exports.s = Ee; exports.t = be;
|
|
4
|
-
//# sourceMappingURL=chunk-CUQQ3ZBV.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/selva-compute/selva-compute/dist/chunk-CUQQ3ZBV.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,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,CAAC,CAAC,CAAC,CAAC,CAAC,CCA3N,IAAMA,CAAAA,CAAa,CACzB,aAAA,CAAe,eAAA,CACf,UAAA,CAAY,YAAA,CACZ,gBAAA,CAAkB,kBAAA,CAClB,iBAAA,CAAmB,mBAAA,CACnB,aAAA,CAAe,eAAA,CACf,UAAA,CAAY,YAAA,CAEZ,SAAA,CAAW,WAAA,CAEX,UAAA,CAAY,YAAA,CAOZ,gBAAA,CAAkB,kBAAA,CAClB,aAAA,CAAe,eAAA,CACf,aAAA,CAAe,eAAA,CACf,aAAA,CAAe,eAAA,CACf,cAAA,CAAgB,gBAAA,CAChB,YAAA,CAAc,cAAA,CACd,iBAAA,CAAmB,mBAAA,CACnB,cAAA,CAAgB,gBAAA,CAEhB,iBAAA,CAAmB,mBAAA,CAEnB,UAAA,CAAY,YAAA,CAEZ,OAAA,CAAS,SAAA,CAOT,UAAA,CAAY,YAAA,CAMZ,aAAA,CAAe,eAAA,CAQf,qBAAA,CAAuB,uBACxB,CAAA,CASaC,CAAAA,aAAN,MAAMC,EAAAA,QAA0B,KAAM,CAM5C,WAAA,CACCC,CAAAA,CACAC,CAAAA,CAAkBJ,CAAAA,CAAW,aAAA,CAC7BK,CAAAA,CACC,CACD,KAAA,CAAMF,CAAO,CAAA,CAVdG,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;AC0VzC;AAsIT","file":"/home/runner/work/selva-compute/selva-compute/dist/chunk-CUQQ3ZBV.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';\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\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\treturn await response.json();\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"]}
|
package/dist/chunk-GFY3L653.cjs
DELETED
|
@@ -1,62 +0,0 @@
|
|
|
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 _chunkCUQQ3ZBVcjs = require('./chunk-CUQQ3ZBV.cjs');var Rt={};_chunkCUQQ3ZBVcjs.a.call(void 0, Rt,{CONCRETE_MATERIAL:()=>De,EMISSIVE_MATERIAL:()=>Le,GLASS_MATERIAL:()=>Pe,METAL_MATERIAL:()=>Ie,PLASTIC_MATERIAL:()=>Oe,RUBBER_MATERIAL:()=>Ve,SHARED_MATERIALS:()=>ge,WOOD_MATERIAL:()=>Be});var _three = require('three'); var O = _interopRequireWildcard(_three); var k = _interopRequireWildcard(_three); var z = _interopRequireWildcard(_three); var U = _interopRequireWildcard(_three); var W = _interopRequireWildcard(_three); var oe = _interopRequireWildcard(_three); var We = _interopRequireWildcard(_three); var D = _interopRequireWildcard(_three); var fe = _interopRequireWildcard(_three); var E = _interopRequireWildcard(_three); var $ = _interopRequireWildcard(_three); var P = _interopRequireWildcard(_three);var Le=new O.MeshPhysicalMaterial({color:0,emissive:new O.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:O.FrontSide,dithering:!0}),Ie=new O.MeshPhysicalMaterial({color:new O.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:O.FrontSide,dithering:!0}),De=new O.MeshPhysicalMaterial({color:new O.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:O.FrontSide,dithering:!0}),Oe=new O.MeshPhysicalMaterial({color:new O.Color(16777215),metalness:0,roughness:.3,envMapIntensity:.5,clearcoat:.5,clearcoatRoughness:.1,reflectivity:.5,ior:1.4,transmission:0,transparent:!1,depthWrite:!0,side:O.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Pe=new O.MeshPhysicalMaterial({color:new O.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:O.DoubleSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Ve=new O.MeshPhysicalMaterial({color:new O.Color(1710618),metalness:0,roughness:.9,envMapIntensity:.2,clearcoat:.1,clearcoatRoughness:.8,reflectivity:.2,ior:1.3,transmission:0,depthWrite:!0,side:O.FrontSide,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),Be=new O.MeshPhysicalMaterial({color:new O.Color(8934707),metalness:0,roughness:.7,envMapIntensity:.3,clearcoat:.3,clearcoatRoughness:.4,reflectivity:.3,ior:1.3,transmission:0,depthWrite:!0,side:O.FrontSide,dithering:!0,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}),ge=new Set([Le,Ie,De,Oe,Pe,Ve,Be]);var q={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 Dr(e,n,t,r,i){if(wt(e),n.length===0)return;n.forEach(d=>{e.add(d)});let o=ye(n),a=o.getCenter(new k.Vector3),s=o.getSize(new k.Vector3),l=Math.max(s.x,s.y,s.z);if(l/Math.min(s.x||1,s.y||1,s.z||1)>q.SCALE_RATIO_THRESHOLD||l>q.HUGE_THRESHOLD?(t.near=l*q.NEAR_PLANE_FACTOR.TINY,t.far=l*q.FAR_PLANE_FACTOR.HUGE):l>q.LARGE_THRESHOLD?(t.near=l*q.NEAR_PLANE_FACTOR.SMALL,t.far=l*q.FAR_PLANE_FACTOR.LARGE):(t.near=Math.max(.01,l*q.NEAR_PLANE_FACTOR.NORMAL),t.far=Math.max(2e3,l*q.FAR_PLANE_FACTOR.NORMAL)),t.updateProjectionMatrix(),!i){let d=l*q.INITIAL_DISTANCE_MULTIPLIER;t.position.set(a.x+d*.8,a.y+d,a.z+d*1.2),r.target.copy(a),r.update()}}function Fe(e){if(!e||typeof e!="string")return _chunkCUQQ3ZBVcjs.e.call(void 0, ).warn(`Invalid color input: ${e}, using white`),new k.Color(16777215);let n=e.trim();if(/^#?[0-9A-Fa-f]{6}$/.test(n))try{let r=n.startsWith("#")?n:`#${n}`;return new k.Color(r)}catch (e2){return _chunkCUQQ3ZBVcjs.e.call(void 0, ).warn(`Invalid hex color: ${e}, using white`),new k.Color(16777215)}if(n.includes(",")){let r=n.split(",").map(i=>parseInt(i.trim(),10));if(r.length===3&&r.every(i=>!isNaN(i)&&i>=0&&i<=255))return new k.Color(r[0]/255,r[1]/255,r[2]/255)}let t=n.toLowerCase();return t in k.Color.NAMES?new k.Color(k.Color.NAMES[t]):(_chunkCUQQ3ZBVcjs.e.call(void 0, ).warn(`Invalid color string: ${e}, using white`),new k.Color(16777215))}function ke(e,n,t="z"){e.forEach(r=>{r.position[t]-=n})}function ye(e){let n=new k.Box3;return e.length===0||e.forEach(t=>{t.updateMatrixWorld(!0);let r=new k.Box3().setFromObject(t);n.union(r)}),n}var vt=new Set(["grid","floor","label-layer","measure"]);function xt(e){let n=e;for(;n;){if(typeof n.userData.id=="string"&&vt.has(n.userData.id))return!0;n=n.parent}return!1}function re(e){e.updateMatrixWorld(!0);let n=new k.Box3;return e.traverse(t=>{let r=t;t.visible&&!xt(t)&&r.geometry&&n.expandByObject(t)}),n}var Ht=new Set(["floor","grid","label-layer"]);function wt(e){[...e.children].forEach(t=>{Ht.has(t.userData.id)||t.userData.source!=="user"&&(t.traverse(r=>{let i=r;if(!i.geometry&&!i.material)return;_optionalChain([i, 'access', _2 => _2.geometry, 'optionalAccess', _3 => _3.dispose, 'call', _4 => _4()]);let o=i.material;if(!o)return;(Array.isArray(o)?o:[o]).forEach(s=>{if(!ge.has(s)){for(let l of Object.values(s))l instanceof k.Texture&&l.dispose();s.dispose()}})}),t.removeFromParent())})}function Ct(e){let n=e.clone().normalize(),t=new z.Vector3(0,0,1),r=new z.Vector3(0,1,0),i=Math.abs(n.dot(t))>.9?r:t,o=new z.Vector3().crossVectors(n,i).normalize(),a=new z.Vector3().crossVectors(o,n).normalize();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 Ue(e){let{scene:n,perspective:t,controls:r,onActiveCameraChange:i}=e,o=(_nullishCoalesce(e.up, () => (t.up))).clone().normalize(),a=Ct(o),s=new z.OrthographicCamera(-1,1,1,-1,t.near,t.far);s.up.copy(o);let l="perspective",c=t.aspect,d=()=>l==="perspective"?t:s,m=null,u=()=>{_optionalChain([m, 'optionalAccess', _5 => _5.cancel, 'call', _6 => _6()]),m=null},f=()=>{let y=(l==="orthographic"?s:t).position.distanceTo(r.target)*Math.tan(t.fov*Math.PI/360),H=y*c;s.left=-H,s.right=H,s.top=y,s.bottom=-y,s.near=t.near,s.far=t.far,s.updateProjectionMatrix()},b=p=>{if(p!==l){if(u(),p==="orthographic")s.position.copy(t.position),s.up.copy(t.up),s.lookAt(r.target),s.zoom=1,f();else{let y=(s.top-s.bottom)/(2*s.zoom)/Math.tan(t.fov*Math.PI/360),H=s.position.clone().sub(r.target);H.lengthSq()<1e-12&&H.copy(o),H.normalize(),t.position.copy(r.target).add(H.multiplyScalar(y))}l=p,r.object=d(),r.update(),i(d())}},T=(p,v,y,H)=>{let A=t.fov*(Math.PI/180),V=v/(2*Math.tan(A/2))*1.5,G=Mt(y,o),F=p.clone().add(G.clone().multiplyScalar(V)),Y=d();l==="orthographic"&&(s.zoom=1),u(),H?m=St(Y,r,F,p,()=>{l==="orthographic"&&f()}):(Y.position.copy(F),r.target.copy(p),l==="orthographic"&&f(),r.update())},R=(p,v=!0)=>{let y=re(n),H=y.isEmpty()?r.target.clone():y.getCenter(new z.Vector3),A=y.isEmpty()?new z.Vector3(1,1,1):y.getSize(new z.Vector3),V=Math.max(A.x,A.y,A.z)||1;T(H,V,p,v)};return{getActiveCamera:d,getProjection:()=>l,setProjection:b,toggleProjection:()=>(b(l==="perspective"?"orthographic":"perspective"),l),setView:(p,v=!0)=>{R(a[p],v)},setViewDirection:R,frameBounds:(p,v=!0)=>{if(p.isEmpty())return;let y=p.getCenter(new z.Vector3),H=p.getSize(new z.Vector3),A=Math.max(H.x,H.y,H.z)||1,V=d().position.clone().sub(r.target);V.lengthSq()<1e-12&&V.copy(a.iso),T(y,A,V.normalize(),v)},setRotateEnabled:p=>{r.enableRotate=p},isRotateEnabled:()=>r.enableRotate,updateAspect:(p,v)=>{c=v===0?c:p/v,l==="orthographic"&&f()},dispose:u}}function Mt(e,n){let t=n.clone().normalize(),r=e.clone().normalize();if(Math.abs(r.dot(t))<.9999)return e;let i=Math.abs(t.dot(new z.Vector3(0,0,1)))>.9?new z.Vector3(0,1,0):new z.Vector3(0,0,1),o=new z.Vector3().crossVectors(t,i).normalize(),a=.5*Math.PI/180;return r.multiplyScalar(Math.cos(a)).add(o.multiplyScalar(Math.sin(a))).normalize()}var At=e=>1-Math.pow(1-e,3);function St(e,n,t,r,i,o=250){let a=e.position.clone(),s=n.target.clone(),l=performance.now(),c=null,d=()=>{c=null;let m=At(Math.min((performance.now()-l)/o,1));e.position.lerpVectors(a,t,m),n.target.lerpVectors(s,r,m),i(),n.update(),m<1&&(c=requestAnimationFrame(d))};return c=requestAnimationFrame(d),{cancel:()=>{c!==null&&(cancelAnimationFrame(c),c=null)}}}var Lt=`
|
|
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
|
-
`,It=`
|
|
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 ze(e={}){let{cellSize:n=1,majorEvery:t=10,cellColor:r=8947848,majorColor:i=4473924,fadeDistance:o=100,plane:a="y"}=e,s=a==="y"?new U.Vector2(0,2):a==="z"?new U.Vector2(0,1):new U.Vector2(1,2),l=o*2.5,c=new U.PlaneGeometry(l,l);a==="y"?c.rotateX(-Math.PI/2):a==="x"&&c.rotateY(Math.PI/2);let d=new U.ShaderMaterial({vertexShader:Lt,fragmentShader:It,transparent:!0,depthWrite:!1,side:U.DoubleSide,uniforms:{uAxes:{value:s},uCell:{value:n},uMajor:{value:t},uCellColor:{value:new U.Color(r)},uMajorColor:{value:new U.Color(i)},uCenter:{value:new U.Vector3},uFade:{value:o}}}),m=new U.Mesh(c,d);m.name="grid",m.userData.id="grid",m.renderOrder=-1;let u=new U.Vector3;return{object:m,update:f=>{a==="y"?(m.position.set(f.x,0,f.z),u.set(f.x,0,f.z)):a==="z"?(m.position.set(f.x,f.y,0),u.set(f.x,f.y,0)):(m.position.set(0,f.y,f.z),u.set(0,f.y,f.z)),d.uniforms.uCenter.value.copy(u)},setVisible:f=>{m.visible=f},dispose:()=>{m.removeFromParent(),c.dispose(),d.dispose()}}}var _ViewHelperjs = require('three/addons/helpers/ViewHelper.js');function _e(e){let{camera:n,domElement:t,controller:r}=e,i=new (0, _ViewHelperjs.ViewHelper)(n,t);i.setLabels("X","Y","Z");let o=!0,a=128,s=new W.Raycaster,l=new W.OrthographicCamera(-2,2,2,-2,0,4);l.position.set(0,0,2),l.updateMatrixWorld();let c={posX:new W.Vector3(1,0,0),negX:new W.Vector3(-1,0,0),posY:new W.Vector3(0,1,0),negY:new W.Vector3(0,-1,0),posZ:new W.Vector3(0,0,1),negZ:new W.Vector3(0,0,-1)},d=u=>{let f=t.getBoundingClientRect(),b=f.left+t.offsetWidth-a-i.location.right,T=f.top+t.offsetHeight-a-i.location.bottom,R=new W.Vector2((u.clientX-b)/a*2-1,-((u.clientY-T)/a)*2+1);if(Math.abs(R.x)>1||Math.abs(R.y)>1)return null;i.quaternion.copy(n.quaternion).invert(),i.updateMatrixWorld(),s.setFromCamera(R,l);let C=s.intersectObjects(i.children,!1);for(let h of C){let x=_optionalChain([h, 'access', _7 => _7.object, 'access', _8 => _8.userData, 'optionalAccess', _9 => _9.type]);if(typeof x=="string"&&x in c)return x}return null};return{render:u=>{if(!o)return;let f=u.autoClear;u.autoClear=!1,i.render(u),u.autoClear=f},update:()=>{},handleClick:u=>{if(!o)return!1;let f=d(u);return f?(r.getProjection()==="orthographic"&&r.setProjection("perspective"),r.setViewDirection(c[f],!1),!0):!1},isAnimating:!1,setVisible:u=>{o=u},isVisible:()=>o,dispose:()=>i.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');var ue="edge-overlay",Vt=2236962,Bt=1.5,Ft=30,be=new WeakMap;function Ge(e,n={}){let t=new oe.Color(_nullishCoalesce(n.color, () => (Vt))),r=_nullishCoalesce(n.width, () => (Bt)),i=_nullishCoalesce(n.thresholdAngle, () => (Ft)),o=[];return e.traverse(a=>{if(!(a instanceof oe.Mesh)||a.userData.id==="floor"||a.userData.id==="grid"||a.userData.kind===ue||a.children.some(l=>_optionalChain([l, 'access', _10 => _10.userData, 'optionalAccess', _11 => _11.kind])===ue)||!a.geometry)return;let s=zt(a.geometry,t,r,i);a.add(s),o.push(s)}),o}function kt(e,n){let t=be.get(e);t||(t=new Map,be.set(e,t));let r=t.get(n);if(!r){let i=new oe.EdgesGeometry(e,n),o=new _LineSegmentsGeometryjs.LineSegmentsGeometry;o.setPositions(i.attributes.position.array),i.dispose(),r={geometry:o,refCount:0},t.set(n,r)}return r.refCount+=1,r.geometry}function Ut(e){let n=e.userData,t=n.edgeSource&&be.get(n.edgeSource),r=n.edgeThresholdAngle!=null?_optionalChain([t, 'optionalAccess', _12 => _12.get, 'call', _13 => _13(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 zt(e,n,t,r){let i=kt(e,r),o=new (0, _LineMaterialjs.LineMaterial)({color:n});o.linewidth=t,o.polygonOffset=!0,o.polygonOffsetFactor=-1,o.polygonOffsetUnits=-4;let a=new (0, _LineSegments2js.LineSegments2)(i,o);return a.userData.kind=ue,a.userData.edgeSource=e,a.userData.edgeThresholdAngle=r,a.raycast=()=>{},a}function _t(e){return _optionalChain([e, 'access', _14 => _14.userData, 'optionalAccess', _15 => _15.kind])===ue}function jr(e){let n=[];e.traverse(t=>{t instanceof _LineSegments2js.LineSegments2&&_t(t)&&n.push(t)});for(let t of n)Ut(t),t.material.dispose(),t.removeFromParent();return n.length}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 Ne(e,n,t,r,i,o){let a=new (0, _EffectComposerjs.EffectComposer)(e),s=new (0, _RenderPassjs.RenderPass)(n,t);a.addPass(s);let l=new (0, _GTAOPassjs.GTAOPass)(n,t,r,i);l.blendIntensity=_nullishCoalesce(o.aoIntensity, () => (1)),l.updateGtaoMaterial({screenSpaceRadius:!0}),a.addPass(l);let c=new _SMAAPassjs.SMAAPass;a.addPass(c);let d=new _OutputPassjs.OutputPass;a.addPass(d),e.toneMapping=o.toneMapping,e.toneMappingExposure=o.toneMappingExposure;let m=_nullishCoalesce(o.aoPixelRatio, () => (1));return a.setSize(r,i),{render:u=>a.render(u),setSize:(u,f,b)=>{a.setPixelRatio(Math.min(b,m)),a.setSize(u,f)},setCamera:u=>{s.camera=u,l.camera=u;let f=u.isPerspectiveCamera?1:0;l.gtaoMaterial.defines.PERSPECTIVE_CAMERA!==f&&(l.gtaoMaterial.defines.PERSPECTIVE_CAMERA=f,l.gtaoMaterial.needsUpdate=!0)},dispose:()=>{a.dispose(),l.dispose(),c.dispose(),d.dispose()}}}var _CSS2DRendererjs = require('three/addons/renderers/CSS2DRenderer.js');function $e(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 i={width:e.clientWidth||1,height:e.clientHeight||1};t.setSize(i.width,i.height);let o=new We.Group;o.name="label-layer",o.userData.id="label-layer",n.add(o);let a=new Set;return{addLabel:(l,c,d)=>{let m=document.createElement("div");m.textContent=l,d?m.className=d:Object.assign(m.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"}),m.style.pointerEvents="none";let u=new (0, _CSS2DRendererjs.CSS2DObject)(m);return u.position.copy(c),o.add(u),a.add(u),{object:u,setPosition:f=>u.position.copy(f),setText:f=>{m.textContent=f},remove:()=>{u.removeFromParent(),m.remove(),a.delete(u)}}},render:(l,c)=>t.render(l,c),setSize:(l,c)=>t.setSize(l,c),dispose:()=>{a.forEach(l=>{l.removeFromParent(),l.element.remove()}),a.clear(),o.removeFromParent(),r.remove()}}}var _Line2js = require('three/addons/lines/Line2.js');var _LineGeometryjs = require('three/addons/lines/LineGeometry.js');var Jt=12,Qt=16763904,Ye=.015,Xe={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 en(e){let n=e&&Xe[e]||Xe.Meters;return t=>`${(t/n.metersPerUnit).toPrecision(3)} ${n.suffix}`}function tn(e,n){if(e.isOrthographicCamera){let r=e;return Math.abs(r.top-r.bottom)/(r.zoom||1)*Ye}return((n?e.position.distanceTo(n):e.position.length())||1)*Ye}function nn(e){let n=e.object;if(n instanceof D.Mesh)return e.face?[e.face.a,e.face.b,e.face.c]:null;if(n instanceof D.Points)return e.index!=null?[e.index]:null;if(n instanceof D.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 rn(e,n,t,r){let i=e.point.clone(),o=e.object,a=nn(e);if(!a||!o.geometry)return i;let s=o.geometry.attributes.position;if(!s)return i;let l=u=>{let f=u.clone().project(n);return new D.Vector2((f.x+1)/2*t.width,(1-f.y)/2*t.height)},c=l(i),d=i,m=r;for(let u of a){if(u>=s.count)continue;let b=new D.Vector3().fromBufferAttribute(s,u).applyMatrix4(o.matrixWorld),T=l(b).distanceTo(c);T<m&&(m=T,d=b)}return d}function qe(e){let{canvas:n,scene:t,getActiveCamera:r,getViewTarget:i,labelLayer:o,options:a={}}=e,s=_nullishCoalesce(a.snapPixels, () => (Jt)),l=new D.Color(_nullishCoalesce(a.color, () => (Qt))),c=en(a.displayUnit),d=(S,w)=>`${c(S)}
|
|
54
|
-
\u0394x ${c(w.x)} \u0394y ${c(w.y)} \u0394z ${c(w.z)}`,m=_nullishCoalesce(a.format, () => (d)),u=new D.Raycaster,f=new D.Vector2,b=!1,T=[],R=[],C=null,h=null,x=new D.PointsMaterial({color:l,size:8,sizeAttenuation:!1,depthTest:!1}),L=new D.PointsMaterial({color:l,size:11,sizeAttenuation:!1,depthTest:!1,transparent:!0,opacity:.5}),p=null,v=S=>{if(!S){p&&(p.visible=!1);return}if(!p){let w=new D.BufferGeometry;w.setAttribute("position",new D.Float32BufferAttribute([0,0,0],3)),p=new D.Points(w,L),p.renderOrder=1e3,p.userData.id="measure",p.raycast=()=>{},t.add(p)}p.position.copy(S),p.visible=!0},y=S=>{let w=new D.BufferGeometry;w.setAttribute("position",new D.Float32BufferAttribute([S.x,S.y,S.z],3));let j=new D.Points(w,x);return j.renderOrder=999,j.userData.id="measure",j.raycast=()=>{},t.add(j),j},H=()=>{T.length=0,R.forEach(S=>{S.geometry.dispose(),S.removeFromParent()}),R.length=0,C&&(C.geometry.dispose(),C.material.dispose(),C.removeFromParent(),C=null),_optionalChain([h, 'optionalAccess', _16 => _16.remove, 'call', _17 => _17()]),h=null},A=()=>{if(T.length!==2)return;let[S,w]=T,j=new _LineGeometryjs.LineGeometry;j.setPositions([S.x,S.y,S.z,w.x,w.y,w.z]);let K=new (0, _LineMaterialjs.LineMaterial)({color:l});K.linewidth=2,K.depthTest=!1,C=new (0, _Line2js.Line2)(j,K),C.renderOrder=998,C.userData.id="measure",C.raycast=()=>{},t.add(C);let Q=S.clone().add(w).multiplyScalar(.5),ee=new D.Vector3(Math.abs(w.x-S.x),Math.abs(w.y-S.y),Math.abs(w.z-S.z));h=o.addLabel(m(S.distanceTo(w),ee),Q,a.labelClassName)},V=S=>{let w=n.getBoundingClientRect();f.x=(S.clientX-w.left)/w.width*2-1,f.y=-((S.clientY-w.top)/w.height)*2+1;let j=r();u.setFromCamera(f,j);let K=tn(j,_optionalChain([i, 'optionalCall', _18 => _18()]));u.params.Line.threshold=K,u.params.Points.threshold=K;let Q=u.intersectObjects(t.children,!0).filter(ee=>ee.object.userData.id!=="measure"&&ee.object.userData.id!=="grid");return Q.length===0?null:rn(Q[0],j,{width:w.width,height:w.height},s)},G=null,F=0,Y=()=>{F&&(cancelAnimationFrame(F),F=0),G=null};return{setEnabled:S=>{b=S,S||(Y(),H(),v(null))},isEnabled:()=>b,handleClick:S=>{if(!b)return!1;T.length===2&&H();let w=V(S);return w===null||(T.push(w),R.push(y(w)),T.length===2&&A()),!0},handleMove:S=>{b&&(G=S,!F&&(F=requestAnimationFrame(()=>{F=0;let w=G;G=null,!(!b||!w)&&v(V(w))})))},clear:H,dispose:()=>{Y(),H(),p&&(p.geometry.dispose(),p.removeFromParent(),p=null),x.dispose(),L.dispose()}}}var on=64,an=256,X=new Map,ae=new Map,de=0,pe=class extends Error{constructor(n){super(`Texture load for ${n} resolved after clearTextureCache(); texture disposed.`),this.name="StaleTextureLoadError"}},me=1;function Ze(e){me=Math.max(1,e);for(let n of X.values())n.anisotropy!==me&&(n.anisotropy=me,n.needsUpdate=!0)}function Ke(e,n){let t=sn(n),r=X.get(t);if(r){X.delete(t),X.set(t,r),e.map=r,e.needsUpdate=!0;return}typeof document>"u"||un(n,t).then(i=>{e.map=i,e.needsUpdate=!0}).catch(i=>{i instanceof pe||_chunkCUQQ3ZBVcjs.e.call(void 0, ).warn(`Failed to load material texture ${n}:`,i)})}function ro(){de++;for(let e of X.values())e.dispose();X.clear(),ae.clear()}function sn(e){return e.length<=an?e:`data-uri:${ln(e).toString(16)}:${e.length}`}function ln(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 cn(e,n){for(X.set(e,n);X.size>on;){let t=X.keys().next().value,r=X.get(t);X.delete(t),r.dispose()}}function un(e,n){let t=ae.get(n);if(!t){let r=de;t=new Promise((i,o)=>{new fe.TextureLoader().load(e,a=>{if(r!==de){a.dispose(),o(new pe(e));return}a.colorSpace=fe.SRGBColorSpace,a.anisotropy=me,cn(n,a),ae.delete(n),i(a)},void 0,a=>{r===de&&ae.delete(n),o(a)})}),ae.set(n,t)}return t}var _OrbitControlsjs = require('three/addons/controls/OrbitControls.js');var _HDRLoaderjs = require('three/addons/loaders/HDRLoader.js');var ie=new E.Vector3(0,0,1),pn="technical",Te={studio:{toneMapping:E.ACESFilmicToneMapping,toneMappingExposure:1,envMapIntensity:1.3,environmentIntensity:1.2,hemisphereIntensity:1,ambientIntensity:.3,cullBackfaces:!1,ambientOcclusion:!1},technical:{toneMapping:E.NeutralToneMapping,toneMappingExposure:1,envMapIntensity:.5,environmentIntensity:1,hemisphereIntensity:0,ambientIntensity:1,cullBackfaces:!1,ambientOcclusion:!1},showcase:{toneMapping:E.ACESFilmicToneMapping,toneMappingExposure:1.05,envMapIntensity:1.6,environmentIntensity:1.35,hemisphereIntensity:1.2,ambientIntensity:.25,cullBackfaces:!1,ambientOcclusion:!1}};function fn(e){let n=Te[e];return{envMapIntensity:n.envMapIntensity,cullBackfaces:n.cullBackfaces}}function En(e){let n=Math.abs(e.x),t=Math.abs(e.y),r=Math.abs(e.z);return r>=n&&r>=t?"z":t>=n&&t>=r?"y":"x"}var yo=function(e,n){let t=hn(n||{}),r=_optionalChain([t, 'access', _19 => _19.environment, 'optionalAccess', _20 => _20.sceneUp])||ie,i=_nullishCoalesce(t.render.pixelRatio, () => (Math.min(window.devicePixelRatio,2))),o=yn(t),a=xn(t,e);a.up.copy(r);let s=Hn(e,t,i);Ze(s.capabilities.getMaxAnisotropy());let l=Cn(a,e,t),c=Ue({scene:o,perspective:a,controls:l,onActiveCameraChange:()=>{},up:r}),d=()=>c.getActiveCamera(),m=!1;Tn(o,t,()=>m);let u=Rn(o,t),f=u.sun,b=()=>{f&&gn(f,re(o))};_optionalChain([t, 'access', _21 => _21.floor, 'optionalAccess', _22 => _22.enabled])&&vn(o,t);let T=t.grid.enabled?ze({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;T&&o.add(T.object);let R=t.gizmo.enabled?_e({camera:a,domElement:e,controller:c}):null,C=_nullishCoalesce(e.parentElement, () => (e)),h=t.measure.enabled?$e(C,o):null,x=t.measure.enabled&&h?qe({canvas:e,scene:o,getActiveCamera:d,labelLayer:h,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?wn(e,o,c,t):{dispose:()=>{},fitToView:()=>{},clearSelection:()=>{}},p=5,v=0,y=0,H=g=>{v=g.clientX,y=g.clientY},A=g=>Math.hypot(g.clientX-v,g.clientY-y)>p,V=g=>{if(!A(g)){if(_optionalChain([x, 'optionalAccess', _23 => _23.handleClick, 'call', _24 => _24(g)])){g.stopImmediatePropagation();return}_optionalChain([R, 'optionalAccess', _25 => _25.handleClick, 'call', _26 => _26(g)])&&g.stopImmediatePropagation()}};(R||x)&&(e.addEventListener("mousedown",H,{capture:!0}),e.addEventListener("click",V,{capture:!0}));let G=g=>_optionalChain([x, 'optionalAccess', _27 => _27.handleMove, 'call', _28 => _28(g)]);x&&e.addEventListener("mousemove",G,{passive:!0});let F=g=>{Ge(g,{color:t.edges.color,width:t.edges.width,thresholdAngle:t.edges.thresholdAngle})},Y=e.parentElement,J=()=>Y?{width:Y.clientWidth,height:Y.clientHeight}:{width:window.innerWidth,height:window.innerHeight},B=null,S=()=>{let{width:g,height:I}=J(),N=Ne(s,o,d(),Math.max(1,g),Math.max(1,I),{toneMapping:_nullishCoalesce(t.render.toneMapping, () => (E.NeutralToneMapping)),toneMappingExposure:_nullishCoalesce(t.render.toneMappingExposure, () => (1)),aoIntensity:t.render.aoIntensity,aoPixelRatio:t.render.aoPixelRatio});return N.setSize(Math.max(1,g),Math.max(1,I),i),N},w=g=>{g&&!B?B=S():!g&&B&&(B.dispose(),B=null)};t.render.ambientOcclusion&&(B=S());let j=g=>{g.ambientIntensity!==void 0&&(u.ambient.intensity=g.ambientIntensity),g.hemisphereIntensity!==void 0&&!u.hemisphere&&g.hemisphereIntensity>0&&(u.hemisphere=new E.HemisphereLight(_nullishCoalesce(g.hemisphereSkyColor, () => (t.lighting.hemisphereSkyColor)),_nullishCoalesce(g.hemisphereGroundColor, () => (t.lighting.hemisphereGroundColor)),g.hemisphereIntensity),u.hemisphere.position.copy(_nullishCoalesce(t.environment.sceneUp, () => (ie))),o.add(u.hemisphere)),u.hemisphere&&(g.hemisphereIntensity!==void 0&&(u.hemisphere.intensity=g.hemisphereIntensity),g.hemisphereSkyColor!==void 0&&u.hemisphere.color.set(g.hemisphereSkyColor),g.hemisphereGroundColor!==void 0&&u.hemisphere.groundColor.set(g.hemisphereGroundColor))},K=g=>{t.environment.environmentIntensity=g,o.environmentIntensity=g},Q=g=>{t.render.toneMappingExposure=g,s.toneMappingExposure=g,B&&(w(!1),w(!0))},ee=g=>{t.render.aoIntensity=g,B&&(w(!1),w(!0))},mt=g=>{let I=Te[g];Ce=g,s.toneMapping=I.toneMapping,s.toneMappingExposure=I.toneMappingExposure,t.render.toneMapping=I.toneMapping,t.render.toneMappingExposure=I.toneMappingExposure,j({hemisphereIntensity:I.hemisphereIntensity,ambientIntensity:I.ambientIntensity}),K(I.environmentIntensity),B&&w(!1),w(I.ambientOcclusion),o.traverse(N=>{if(N.userData.source!=="compute")return;let ce=N,bt=Array.isArray(ce.material)?ce.material:ce.material?[ce.material]:[];for(let Ae of bt)"envMapIntensity"in Ae&&(Ae.envMapIntensity=I.envMapIntensity)})},Ce=t.look,pt=()=>fn(Ce),{animate:ft,dispose:Et}=bn(s,o,a,d,c,l,J,i,t.events.onFrame,T,R,()=>B,h);ft(),o.up.set(r.x,r.y,r.z),b();let Me=g=>{g.traverse(I=>{let N=I;!N.geometry&&!N.material||(_optionalChain([N, 'access', _29 => _29.geometry, 'optionalAccess', _30 => _30.dispose, 'call', _31 => _31()]),Array.isArray(N.material)?N.material.forEach(Ee):N.material&&Ee(N.material))})},ht=g=>{g.userData.source="user",o.add(g)},gt=g=>{g.removeFromParent(),Me(g)},yt=()=>{o.children.filter(I=>I.userData.source==="user").forEach(I=>{I.removeFromParent(),Me(I)})};return{scene:o,camera:a,controls:l,renderer:s,cameraController:c,grid:T,gizmo:R,measureTool:x,applyEdges:F,setAmbientOcclusion:w,setLook:mt,setFillLights:j,setEnvironmentIntensity:K,setToneMappingExposure:Q,setAoIntensity:ee,getMaterialAppearance:pt,updateShadowBounds:b,dispose:()=>{m||(m=!0,Et(),L.dispose(),(R||x)&&(e.removeEventListener("mousedown",H,{capture:!0}),e.removeEventListener("click",V,{capture:!0})),x&&e.removeEventListener("mousemove",G),_optionalChain([x, 'optionalAccess', _32 => _32.dispose, 'call', _33 => _33()]),_optionalChain([h, 'optionalAccess', _34 => _34.dispose, 'call', _35 => _35()]),_optionalChain([R, 'optionalAccess', _36 => _36.dispose, 'call', _37 => _37()]),_optionalChain([T, 'optionalAccess', _38 => _38.dispose, 'call', _39 => _39()]),_optionalChain([B, 'optionalAccess', _40 => _40.dispose, 'call', _41 => _41()]),c.dispose(),l.dispose(),s.dispose(),s.forceContextLoss(),o.traverse(g=>{let I=g;!I.geometry&&!I.material||(_optionalChain([I, 'access', _42 => _42.geometry, 'optionalAccess', _43 => _43.dispose, 'call', _44 => _44()]),Array.isArray(I.material)?I.material.forEach(Ee):I.material&&Ee(I.material))}),_optionalChain([o, 'access', _45 => _45.environment, 'optionalAccess', _46 => _46.dispose, 'call', _47 => _47()]),o.background instanceof E.Texture&&o.background.dispose())},fitToView:L.fitToView,clearSelection:L.clearSelection,addUserGeometry:ht,removeUserGeometry:gt,clearUserGeometry:yt}};function hn(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],i=_nullishCoalesce(e.look, () => (pn)),o=Te[i];return{sceneScale:n,look:i,camera:{position:_optionalChain([e, 'access', _48 => _48.camera, 'optionalAccess', _49 => _49.position])||new E.Vector3(-r.cameraDistance,-r.cameraDistance,r.cameraDistance),fov:_optionalChain([e, 'access', _50 => _50.camera, 'optionalAccess', _51 => _51.fov])||20,near:_optionalChain([e, 'access', _52 => _52.camera, 'optionalAccess', _53 => _53.near])||r.near,far:_optionalChain([e, 'access', _54 => _54.camera, 'optionalAccess', _55 => _55.far])||r.far,target:_optionalChain([e, 'access', _56 => _56.camera, 'optionalAccess', _57 => _57.target])||new E.Vector3(0,0,0)},lighting:{enableSunlight:_nullishCoalesce(_optionalChain([e, 'access', _58 => _58.lighting, 'optionalAccess', _59 => _59.enableSunlight]), () => (!0)),sunlightIntensity:_nullishCoalesce(_optionalChain([e, 'access', _60 => _60.lighting, 'optionalAccess', _61 => _61.sunlightIntensity]), () => (1)),sunlightPosition:_optionalChain([e, 'access', _62 => _62.lighting, 'optionalAccess', _63 => _63.sunlightPosition])||new E.Vector3(r.lightDistance,r.lightDistance,r.lightHeight),ambientLightColor:_optionalChain([e, 'access', _64 => _64.lighting, 'optionalAccess', _65 => _65.ambientLightColor])||new E.Color(4210752),ambientLightIntensity:_nullishCoalesce(_optionalChain([e, 'access', _66 => _66.lighting, 'optionalAccess', _67 => _67.ambientLightIntensity]), () => (o.ambientIntensity)),sunlightColor:_optionalChain([e, 'access', _68 => _68.lighting, 'optionalAccess', _69 => _69.sunlightColor])||16777215,enableHemisphereLight:_nullishCoalesce(_optionalChain([e, 'access', _70 => _70.lighting, 'optionalAccess', _71 => _71.enableHemisphereLight]), () => (o.hemisphereIntensity>0)),hemisphereSkyColor:_nullishCoalesce(_optionalChain([e, 'access', _72 => _72.lighting, 'optionalAccess', _73 => _73.hemisphereSkyColor]), () => (14673663)),hemisphereGroundColor:_nullishCoalesce(_optionalChain([e, 'access', _74 => _74.lighting, 'optionalAccess', _75 => _75.hemisphereGroundColor]), () => (7036754)),hemisphereIntensity:_nullishCoalesce(_optionalChain([e, 'access', _76 => _76.lighting, 'optionalAccess', _77 => _77.hemisphereIntensity]), () => (o.hemisphereIntensity))},environment:{hdrPath:_optionalChain([e, 'access', _78 => _78.environment, 'optionalAccess', _79 => _79.hdrPath])||"/baseHDR.hdr",backgroundColor:_optionalChain([e, 'access', _80 => _80.environment, 'optionalAccess', _81 => _81.backgroundColor])||new E.Color(15790320),enableEnvironmentLighting:_nullishCoalesce(_optionalChain([e, 'access', _82 => _82.environment, 'optionalAccess', _83 => _83.enableEnvironmentLighting]), () => (!0)),sceneUp:_optionalChain([e, 'access', _84 => _84.environment, 'optionalAccess', _85 => _85.sceneUp])||ie,showEnvironment:_nullishCoalesce(_optionalChain([e, 'access', _86 => _86.environment, 'optionalAccess', _87 => _87.showEnvironment]), () => (!1)),environmentIntensity:_nullishCoalesce(_optionalChain([e, 'access', _88 => _88.environment, 'optionalAccess', _89 => _89.environmentIntensity]), () => (o.environmentIntensity))},floor:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _90 => _90.floor, 'optionalAccess', _91 => _91.enabled]), () => (!1)),size:_optionalChain([e, 'access', _92 => _92.floor, 'optionalAccess', _93 => _93.size])||r.floorSize,color:_optionalChain([e, 'access', _94 => _94.floor, 'optionalAccess', _95 => _95.color])||new E.Color(8421504),roughness:_nullishCoalesce(_optionalChain([e, 'access', _96 => _96.floor, 'optionalAccess', _97 => _97.roughness]), () => (.7)),metalness:_nullishCoalesce(_optionalChain([e, 'access', _98 => _98.floor, 'optionalAccess', _99 => _99.metalness]), () => (0)),receiveShadow:_nullishCoalesce(_optionalChain([e, 'access', _100 => _100.floor, 'optionalAccess', _101 => _101.receiveShadow]), () => (!0))},render:{enableShadows:_nullishCoalesce(_optionalChain([e, 'access', _102 => _102.render, 'optionalAccess', _103 => _103.enableShadows]), () => (!0)),shadowMapSize:_optionalChain([e, 'access', _104 => _104.render, 'optionalAccess', _105 => _105.shadowMapSize])||2048,antialias:_nullishCoalesce(_optionalChain([e, 'access', _106 => _106.render, 'optionalAccess', _107 => _107.antialias]), () => (!0)),pixelRatio:_optionalChain([e, 'access', _108 => _108.render, 'optionalAccess', _109 => _109.pixelRatio])||Math.min(window.devicePixelRatio,2),toneMapping:_nullishCoalesce(_optionalChain([e, 'access', _110 => _110.render, 'optionalAccess', _111 => _111.toneMapping]), () => (o.toneMapping)),toneMappingExposure:_nullishCoalesce(_optionalChain([e, 'access', _112 => _112.render, 'optionalAccess', _113 => _113.toneMappingExposure]), () => (o.toneMappingExposure)),preserveDrawingBuffer:_nullishCoalesce(_optionalChain([e, 'access', _114 => _114.render, 'optionalAccess', _115 => _115.preserveDrawingBuffer]), () => (!1)),ambientOcclusion:_nullishCoalesce(_optionalChain([e, 'access', _116 => _116.render, 'optionalAccess', _117 => _117.ambientOcclusion]), () => (o.ambientOcclusion)),aoIntensity:_nullishCoalesce(_optionalChain([e, 'access', _118 => _118.render, 'optionalAccess', _119 => _119.aoIntensity]), () => (1)),aoPixelRatio:_nullishCoalesce(_optionalChain([e, 'access', _120 => _120.render, 'optionalAccess', _121 => _121.aoPixelRatio]), () => (1))},controls:{enableDamping:_nullishCoalesce(_optionalChain([e, 'access', _122 => _122.controls, 'optionalAccess', _123 => _123.enableDamping]), () => (!1)),dampingFactor:_optionalChain([e, 'access', _124 => _124.controls, 'optionalAccess', _125 => _125.dampingFactor])||.05,autoRotate:_nullishCoalesce(_optionalChain([e, 'access', _126 => _126.controls, 'optionalAccess', _127 => _127.autoRotate]), () => (!1)),autoRotateSpeed:_optionalChain([e, 'access', _128 => _128.controls, 'optionalAccess', _129 => _129.autoRotateSpeed])||.5,enableZoom:_nullishCoalesce(_optionalChain([e, 'access', _130 => _130.controls, 'optionalAccess', _131 => _131.enableZoom]), () => (!0)),enablePan:_nullishCoalesce(_optionalChain([e, 'access', _132 => _132.controls, 'optionalAccess', _133 => _133.enablePan]), () => (!0)),minDistance:_optionalChain([e, 'access', _134 => _134.controls, 'optionalAccess', _135 => _135.minDistance])||r.minDistance,maxDistance:_optionalChain([e, 'access', _136 => _136.controls, 'optionalAccess', _137 => _137.maxDistance])||1/0},grid:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _138 => _138.grid, 'optionalAccess', _139 => _139.enabled]), () => (!1)),cellSize:_nullishCoalesce(_optionalChain([e, 'access', _140 => _140.grid, 'optionalAccess', _141 => _141.cellSize]), () => (1)),majorEvery:_nullishCoalesce(_optionalChain([e, 'access', _142 => _142.grid, 'optionalAccess', _143 => _143.majorEvery]), () => (10)),cellColor:_nullishCoalesce(_optionalChain([e, 'access', _144 => _144.grid, 'optionalAccess', _145 => _145.cellColor]), () => (8947848)),majorColor:_nullishCoalesce(_optionalChain([e, 'access', _146 => _146.grid, 'optionalAccess', _147 => _147.majorColor]), () => (4473924)),fadeDistance:_nullishCoalesce(_optionalChain([e, 'access', _148 => _148.grid, 'optionalAccess', _149 => _149.fadeDistance]), () => (100)),plane:_nullishCoalesce(_optionalChain([e, 'access', _150 => _150.grid, 'optionalAccess', _151 => _151.plane]), () => (En(_nullishCoalesce(_optionalChain([e, 'access', _152 => _152.environment, 'optionalAccess', _153 => _153.sceneUp]), () => (ie)))))},gizmo:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _154 => _154.gizmo, 'optionalAccess', _155 => _155.enabled]), () => (!1))},edges:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _156 => _156.edges, 'optionalAccess', _157 => _157.enabled]), () => (!1)),color:_nullishCoalesce(_optionalChain([e, 'access', _158 => _158.edges, 'optionalAccess', _159 => _159.color]), () => (2236962)),width:_nullishCoalesce(_optionalChain([e, 'access', _160 => _160.edges, 'optionalAccess', _161 => _161.width]), () => (1.5)),thresholdAngle:_nullishCoalesce(_optionalChain([e, 'access', _162 => _162.edges, 'optionalAccess', _163 => _163.thresholdAngle]), () => (30))},measure:{enabled:_nullishCoalesce(_optionalChain([e, 'access', _164 => _164.measure, 'optionalAccess', _165 => _165.enabled]), () => (!1)),snapPixels:_optionalChain([e, 'access', _166 => _166.measure, 'optionalAccess', _167 => _167.snapPixels]),color:_optionalChain([e, 'access', _168 => _168.measure, 'optionalAccess', _169 => _169.color]),labelClassName:_optionalChain([e, 'access', _170 => _170.measure, 'optionalAccess', _171 => _171.labelClassName]),displayUnit:_optionalChain([e, 'access', _172 => _172.measure, 'optionalAccess', _173 => _173.displayUnit]),format:_optionalChain([e, 'access', _174 => _174.measure, 'optionalAccess', _175 => _175.format])},events:{onBackgroundClicked:_optionalChain([e, 'access', _176 => _176.events, 'optionalAccess', _177 => _177.onBackgroundClicked]),onObjectSelected:_optionalChain([e, 'access', _178 => _178.events, 'optionalAccess', _179 => _179.onObjectSelected]),onMeshMetadataClicked:_optionalChain([e, 'access', _180 => _180.events, 'optionalAccess', _181 => _181.onMeshMetadataClicked]),onMeshDoubleClicked:_optionalChain([e, 'access', _182 => _182.events, 'optionalAccess', _183 => _183.onMeshDoubleClicked]),selectionColor:_optionalChain([e, 'access', _184 => _184.events, 'optionalAccess', _185 => _185.selectionColor])||"#ff0000",enableEventHandlers:_nullishCoalesce(_optionalChain([e, 'access', _186 => _186.events, 'optionalAccess', _187 => _187.enableEventHandlers]), () => (!0)),enableKeyboardControls:_nullishCoalesce(_optionalChain([e, 'access', _188 => _188.events, 'optionalAccess', _189 => _189.enableKeyboardControls]), () => (!0)),enableClickToFocus:_nullishCoalesce(_optionalChain([e, 'access', _190 => _190.events, 'optionalAccess', _191 => _191.enableClickToFocus]), () => (!0)),enableDoubleClickZoom:_nullishCoalesce(_optionalChain([e, 'access', _192 => _192.events, 'optionalAccess', _193 => _193.enableDoubleClickZoom]), () => (!0)),onReady:_optionalChain([e, 'access', _194 => _194.events, 'optionalAccess', _195 => _195.onReady]),onFrame:_optionalChain([e, 'access', _196 => _196.events, 'optionalAccess', _197 => _197.onFrame])}}}function Ee(e){for(let n of Object.values(e))n instanceof E.Texture&&n.dispose();e.dispose()}function gn(e,n){if(n.isEmpty())return;let t=n.getCenter(new E.Vector3),r=n.getSize(new E.Vector3).length()*.5*1.2,i=e.shadow.camera;i.left=-r,i.right=r,i.top=r,i.bottom=-r,e.target.position.copy(t),e.target.updateMatrixWorld();let o=e.position.distanceTo(t);i.near=Math.max(r*.01,o-r),i.far=o+r,i.updateProjectionMatrix()}function yn(e){let n=new E.Scene,t=typeof e.environment.backgroundColor=="string"?new E.Color(e.environment.backgroundColor):e.environment.backgroundColor;return n.background=t||null,n}function bn(e,n,t,r,i,o,a,s,l,c,d,m,u){let f=null,b=performance.now(),T=()=>{let{width:h,height:x}=a();if(h===0||x===0)return;let L=Math.floor(h*s),p=Math.floor(x*s);(e.domElement.width!==L||e.domElement.height!==p)&&(e.setPixelRatio(s),e.setSize(h,x,!1),t.aspect=h/x,t.updateProjectionMatrix(),i.updateAspect(h,x),_optionalChain([m, 'optionalCall', _198 => _198(), 'optionalAccess', _199 => _199.setSize, 'call', _200 => _200(h,x,s)]),_optionalChain([u, 'optionalAccess', _201 => _201.setSize, 'call', _202 => _202(h,x)]))},R=function(){f=requestAnimationFrame(R);let h=performance.now(),x=(h-b)/1e3;b=h,T(),(o.enableDamping||o.autoRotate)&&o.update(),c&&c.update(r().position),d&&d.update(x),_optionalChain([l, 'optionalCall', _203 => _203(x)]);let L=r(),p=_optionalChain([m, 'optionalCall', _204 => _204()]);p?(p.setCamera(L),p.render(x)):e.render(n,L),u&&u.render(n,L),d&&d.render(e)};return{animate:R,dispose:()=>{f!==null&&(cancelAnimationFrame(f),f=null)}}}function Tn(e,n,t){n.environment.enableEnvironmentLighting?new (0, _HDRLoaderjs.HDRLoader)().load(n.environment.hdrPath||"/baseHDR.hdr",function(r){if(t()){r.dispose();return}if(!_optionalChain([r, 'optionalAccess', _205 => _205.image])){_chunkCUQQ3ZBVcjs.e.call(void 0, ).warn("HDR loaded without image data; skipping environment map."),_optionalChain([r, 'optionalAccess', _206 => _206.dispose, 'call', _207 => _207()]),_optionalChain([n, 'access', _208 => _208.events, 'access', _209 => _209.onReady, 'optionalCall', _210 => _210()]);return}r.mapping=E.EquirectangularReflectionMapping,e.environment=r,e.environmentIntensity=_nullishCoalesce(n.environment.environmentIntensity, () => (1)),n.environment.showEnvironment&&(e.background=r),_optionalChain([n, 'access', _211 => _211.events, 'access', _212 => _212.onReady, 'optionalCall', _213 => _213()])},void 0,function(r){t()||(_chunkCUQQ3ZBVcjs.e.call(void 0, ).warn("HDR texture could not be loaded, falling back to basic lighting:",r),_optionalChain([n, 'access', _214 => _214.events, 'access', _215 => _215.onReady, 'optionalCall', _216 => _216()]))}):_optionalChain([n, 'access', _217 => _217.events, 'access', _218 => _218.onReady, 'optionalCall', _219 => _219()])}function Rn(e,n){let t=new E.AmbientLight(n.lighting.ambientLightColor,n.lighting.ambientLightIntensity);e.add(t);let r=null;if(n.lighting.enableHemisphereLight){r=new E.HemisphereLight(n.lighting.hemisphereSkyColor,n.lighting.hemisphereGroundColor,n.lighting.hemisphereIntensity);let a=_nullishCoalesce(n.environment.sceneUp, () => (ie));r.position.copy(a),e.add(r)}if(!n.lighting.enableSunlight)return{ambient:t,hemisphere:r,sun:null};let i=new E.DirectionalLight(_nullishCoalesce(n.lighting.sunlightColor, () => (16777215)),n.lighting.sunlightIntensity),o=n.lighting.sunlightPosition;return o&&i.position.set(o.x,o.y,o.z),n.render.enableShadows?(i.castShadow=!0,i.shadow.mapSize.width=n.render.shadowMapSize||2048,i.shadow.mapSize.height=n.render.shadowMapSize||2048,i.shadow.bias=-1e-4,i.shadow.normalBias=.02,i.shadow.radius=4,e.add(i),e.add(i.target),{ambient:t,hemisphere:r,sun:i}):(e.add(i),{ambient:t,hemisphere:r,sun:null})}function vn(e,n){let t=n.floor.size,r=new E.PlaneGeometry(t,t),i=typeof n.floor.color=="string"?new E.Color(n.floor.color):n.floor.color,o=new E.MeshStandardMaterial({color:i,roughness:n.floor.roughness,metalness:n.floor.metalness,side:E.DoubleSide}),a=new E.Mesh(r,o);a.userData.id="floor",a.name="floor";let s=(_optionalChain([n, 'access', _220 => _220.environment, 'optionalAccess', _221 => _221.sceneUp])||ie).clone().normalize();a.quaternion.setFromUnitVectors(new E.Vector3(0,0,1),s),a.position.set(0,0,0),n.floor.receiveShadow&&n.render.enableShadows&&(a.receiveShadow=!0),e.add(a)}function xn(e,n){let t=n.parentElement,r=t?t.clientWidth:window.innerWidth,i=t?t.clientHeight:window.innerHeight,o=new E.PerspectiveCamera(e.camera.fov,r/i,e.camera.near,e.camera.far),a=e.camera.position;return a&&o.position.set(a.x,a.y,a.z),o}function Hn(e,n,t){let r=new E.WebGLRenderer({antialias:n.render.antialias,canvas:e,alpha:!0,powerPreference:"high-performance",preserveDrawingBuffer:n.render.preserveDrawingBuffer,logarithmicDepthBuffer:!1}),i=e.parentElement,o=i?i.clientWidth:window.innerWidth,a=i?i.clientHeight:window.innerHeight;return i&&(e.style.width="100%",e.style.height="100%",e.style.display="block"),r.setSize(o,a,!1),r.setPixelRatio(t),n.render.enableShadows&&(r.shadowMap.enabled=!0,r.shadowMap.type=E.VSMShadowMap),r.toneMapping=n.render.toneMapping,r.toneMappingExposure=_nullishCoalesce(n.render.toneMappingExposure, () => (1)),r.outputColorSpace=E.SRGBColorSpace,r.sortObjects=!0,r}function wn(e,n,t,r){let i=new Set,o=new Map,a=new E.Raycaster,s=new E.Vector2,l=new E.Vector2,c=()=>t.getActiveCamera(),d=p=>{let v=p;for(;v;){if(!v.visible)return!1;v=v.parent}return!0},m=()=>{let p=re(n);if(p.isEmpty()){_chunkCUQQ3ZBVcjs.e.call(void 0, ).warn("No objects to fit to view");return}t.frameBounds(p,!1)},u=typeof r.events.selectionColor=="string"?new E.Color(r.events.selectionColor):r.events.selectionColor instanceof E.Color?r.events.selectionColor:new E.Color("#ff0000"),f=()=>{i.forEach(p=>{let v=p;if(o.has(p)){let y=o.get(p),H=v.material;H instanceof E.Material?H.dispose():Array.isArray(H)&&H.forEach(V=>V.dispose()),v.material=y,o.delete(p);let A=p;for(;A.parent;)A=A.parent;A!==n&&(y instanceof E.Material?y.dispose():y.forEach(V=>V.dispose()))}}),i.clear()},b=p=>{let v=p;if(!(v.material instanceof E.Material))return!1;o.set(p,v.material);let y=v.material.clone();return p instanceof E.Mesh&&"emissive"in y?y.emissive=u.clone():"color"in y&&(y.color=u.clone()),v.material=y,!0},T=()=>{let p=re(n),v=p.isEmpty()?1:p.getSize(new E.Vector3).length();a.params.Points.threshold=v*.01},R=p=>{l.set(p.clientX,p.clientY)},C=p=>{let v=new E.Vector2(p.clientX,p.clientY);if(l.distanceTo(v)>5)return;let y=e.getBoundingClientRect();s.x=(p.clientX-y.left)/y.width*2-1,s.y=-((p.clientY-y.top)/y.height)*2+1,T(),a.setFromCamera(s,c());let H=a.intersectObjects(n.children,!0).filter(A=>d(A.object));if(H.length>0){let A=H[0].object;i.has(A)||(f(),i.add(A),b(A),_optionalChain([r, 'access', _222 => _222.events, 'optionalAccess', _223 => _223.onObjectSelected, 'optionalCall', _224 => _224(A)]),A instanceof E.Mesh&&Object.keys(A.userData).length>0&&_optionalChain([r, 'access', _225 => _225.events, 'optionalAccess', _226 => _226.onMeshMetadataClicked, 'optionalCall', _227 => _227(A.userData)]))}else f(),_optionalChain([r, 'access', _228 => _228.events, 'optionalAccess', _229 => _229.onBackgroundClicked, 'optionalCall', _230 => _230({x:s.x,y:s.y})])},h=p=>{let v=e.getBoundingClientRect();s.x=(p.clientX-v.left)/v.width*2-1,s.y=-((p.clientY-v.top)/v.height)*2+1,T(),a.setFromCamera(s,c());let y=a.intersectObjects(n.children,!0).filter(V=>d(V.object));if(y.length===0)return;let H=y[0].object;if(_optionalChain([r, 'access', _231 => _231.events, 'optionalAccess', _232 => _232.onMeshDoubleClicked, 'optionalCall', _233 => _233(H)]),!_optionalChain([r, 'access', _234 => _234.events, 'optionalAccess', _235 => _235.enableDoubleClickZoom]))return;let A=new E.Box3().setFromObject(H);A.isEmpty()||t.frameBounds(A,!0)},x=p=>{if(_optionalChain([r, 'access', _236 => _236.events, 'optionalAccess', _237 => _237.enableKeyboardControls]))switch(p.key.toLowerCase()){case"f":p.preventDefault(),m();break;case"escape":p.preventDefault(),f();break;case" ":p.preventDefault(),m();break}};return _optionalChain([r, 'access', _238 => _238.events, 'optionalAccess', _239 => _239.enableClickToFocus])&&(e.addEventListener("mousedown",R),e.addEventListener("click",C),e.addEventListener("dblclick",h)),_optionalChain([r, 'access', _240 => _240.events, 'optionalAccess', _241 => _241.enableKeyboardControls])&&(e.setAttribute("tabindex","0"),e.addEventListener("keydown",x)),{dispose:()=>{e.removeEventListener("mousedown",R),e.removeEventListener("click",C),e.removeEventListener("dblclick",h),e.removeEventListener("keydown",x),f()},fitToView:m,clearSelection:f}}function Cn(e,n,t){let r=new (0, _OrbitControlsjs.OrbitControls)(e,n),i=t.camera.target;return i&&r.target.set(i.x,i.y,i.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 To=["technical","studio","showcase"];function he(e,n,t,r=!0){return{x:e,y:n,z:t}}var Ln="#ffffff",Je=12,In=4e-4,Dn=12,On=.05;function Qe(e,n={}){if(!e||e.length===0)return[];let{rhino:t,applyTransforms:r=!0}=n,i=[];for(let o of e)switch(o.kind){case"curve":{let a=Vn(o,t,r);a&&i.push(a);break}case"point":{let a=Bn(o,r);a&&i.push(a);break}default:{let s=o;_chunkCUQQ3ZBVcjs.e.call(void 0, ).warn(`Skipping unknown display item kind: ${String(s.kind)}`);break}}return i}var Pn=2;function Vn(e,n,t){if(!n)return _chunkCUQQ3ZBVcjs.e.call(void 0, ).warn("No rhino3dm instance provided; skipping curve display item."),null;let r=Fn(e.json,n);if(!r)return null;let i;try{i=kn(r,t)}catch(m){return _chunkCUQQ3ZBVcjs.e.call(void 0, ).warn("Failed to tessellate curve display item; skipping.",m),null}finally{se(r)}if(i.length<2)return null;let o=[];for(let m of i)o.push(m.x,m.y,m.z);let a=new _LineGeometryjs.LineGeometry;a.setPositions(o);let s=et(e.color,e.opacity),l=new (0, _LineMaterialjs.LineMaterial)({color:s.color}),c=l;c.linewidth=_nullishCoalesce(e.width, () => (Pn)),c.transparent=s.transparent,c.opacity=s.opacity;let d=new (0, _Line2js.Line2)(a,l);return d.computeLineDistances(),d.name=e.name,d.userData={source:"compute",id:e.id,layer:e.layer,kind:"curve",metadata:e.metadata},d}function Bn(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 _chunkCUQQ3ZBVcjs.e.call(void 0, ).warn(`Skipping point display item with missing or non-finite position (id: ${String(e.id)}).`),null;let{x:r,y:i,z:o}=he(t.X,t.Y,t.Z,n),a=new $.BufferGeometry;a.setAttribute("position",new $.Float32BufferAttribute([r,i,o],3));let s=new $.PointsMaterial({...et(e.color,e.opacity),size:6,sizeAttenuation:!1}),l=new $.Points(a,s);return l.name=e.name,l.userData={source:"compute",id:e.id,layer:e.layer,kind:"point",metadata:e.metadata},l}function se(e){_optionalChain([e, 'optionalAccess', _242 => _242.delete, 'optionalCall', _243 => _243()])}function Fn(e,n){try{let t=JSON.parse(e),r=n.CommonObject.decode(t);return r&&typeof r.pointAt=="function"?r:(se(r),_chunkCUQQ3ZBVcjs.e.call(void 0, ).warn("Decoded display-item JSON is not a curve; skipping."),null)}catch(t){return _chunkCUQQ3ZBVcjs.e.call(void 0, ).warn("Failed to decode curve display item JSON:",t),null}}function kn(e,n){let t=Un(e,n);return t||zn(e,n)}function Un(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 i=[];for(let o=0;o<r.count;o++){let a=r.get(o),{x:s,y:l,z:c}=he(a[0],a[1],a[2],n);i.push(new $.Vector3(s,l,c))}return se(r),i}function zn(e,n){let t=e.domain,r=t[0],o=t[1]-r,a=m=>{let u=e.pointAt(m),{x:f,y:b,z:T}=he(u[0],u[1],u[2],n);return new $.Vector3(f,b,T)},s=_n(e),l=r,c=a(r),d=[c];for(let m=0;m<Je;m++){let u=r+o*(m+1)/Je,f=a(u);Re(l,c,u,f,a,s,Dn,d),d.push(f),l=u,c=f}return d}function Re(e,n,t,r,i,o,a,s){if(a<=0)return;let l=(e+t)/2,c=i(l),d=Gn(c,n,r),m=jn(n,c,r);d<=o&&m<=On||(Re(e,n,l,c,i,o,a-1,s),s.push(c),Re(l,c,t,r,i,o,a-1,s))}function _n(e){let n=e.getBoundingBox(),t=n.min,r=n.max;se(n);let i=Math.hypot(r[0]-t[0],r[1]-t[1],r[2]-t[2]);return Math.max(i*In,1e-6)}function jn(e,n,t){let r=n.x-e.x,i=n.y-e.y,o=n.z-e.z,a=t.x-n.x,s=t.y-n.y,l=t.z-n.z,c=Math.sqrt(r*r+i*i+o*o),d=Math.sqrt(a*a+s*s+l*l);if(c===0||d===0)return 0;let m=r*a+i*s+o*l,u=Math.max(-1,Math.min(1,m/(c*d)));return Math.acos(u)}function Gn(e,n,t){let r=t.x-n.x,i=t.y-n.y,o=t.z-n.z,a=r*r+i*i+o*o;if(a===0)return e.distanceTo(n);let s=e.x-n.x,l=e.y-n.y,c=e.z-n.z,d=Math.max(0,Math.min(1,(s*r+l*i+c*o)/a)),m=s-r*d,u=l-i*d,f=c-o*d;return Math.sqrt(m*m+u*u+f*f)}function et(e,n){let t=_nullishCoalesce(n, () => (1));return{color:new $.Color(_nullishCoalesce(e, () => (Ln))),transparent:t<1,opacity:t}}var _fflate = require('fflate');var tt=1096174675,Wn= exports.y =1515605075,nt= exports.z =3,rt= exports.A =1,xe= exports.B =1,$n= exports.C =2,Yn= exports.D =4,Xn= exports.E =8,qn= exports.F =16,Do= exports.G =0,Zn= exports.H =1,ot=12,it=56,Kn=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1;function He(e){if(!Kn)throw new (0, _chunkCUQQ3ZBVcjs.d)("SLVA parsing requires a little-endian host: the zero-copy geometry readers view the wire bytes in host byte order.",_chunkCUQQ3ZBVcjs.c.ENVIRONMENT_ERROR);let n=tr(er(e)),t=new DataView(n.buffer,n.byteOffset,n.byteLength);if(n.byteLength<ot)throw _("Blob too small to contain SLVA header.",{expectedBytes:ot,availableBytes:n.byteLength});let r=0,i=t.getUint32(r,!0);if(r+=4,i!==tt)throw _(`Invalid SLVA magic: 0x${i.toString(16)}`,{expectedMagic:`0x${tt.toString(16)}`,actualMagic:`0x${i.toString(16)}`});let o=t.getUint32(r,!0);if(r+=4,o<rt||o>nt)throw _(`Unsupported SLVA version: ${o}`,{minSupportedVersion:rt,maxSupportedVersion:nt,actualVersion:o});let a=t.getUint32(r,!0);if(r+=4,r+a>n.byteLength)throw _("Insufficient data to read metadata JSON.",{expectedBytes:a,availableBytes:n.byteLength-r,offset:r});let s=n.subarray(r,r+a);r+=a;let l;try{l=JSON.parse(nr(s))}catch(B){throw _(`Failed to parse metadata JSON: ${B instanceof Error?B.message:String(B)}`,{metadataLen:a})}if(r+it>n.byteLength)throw _("Insufficient data to read geometry header.",{expectedBytes:it,availableBytes:n.byteLength-r,offset:r});let c=t.getUint32(r,!0);r+=4;let d=t.getFloat64(r,!0);r+=8;let m=t.getFloat64(r,!0);r+=8;let u=t.getFloat64(r,!0);r+=8;let f=t.getFloat64(r,!0);r+=8;let b=t.getFloat64(r,!0);r+=8;let T=t.getFloat64(r,!0);r+=8;let R=t.getUint32(r,!0);r+=4;let C=(c&xe)!==0,h=(c&Yn)!==0,x=R*3,p=x*(C?4:2);if(r+p>n.byteLength)throw _("Insufficient data to read vertices.",{expectedBytes:p,availableBytes:n.byteLength-r,offset:r,useFloat32:C,vertexCount:R});let v=n.byteOffset+r,y;if(C?y=st(n.buffer,v,x):h?y=ar(ve(n.buffer,v,x)):y=rr(n.buffer,v,x),r+=p,r+4>n.byteLength)throw _("Insufficient data to read index count.",{expectedBytes:4,availableBytes:n.byteLength-r,offset:r});let H=t.getUint32(r,!0);r+=4;let A=(c&$n)!==0,G=H*(A?2:4);if(r+G>n.byteLength)throw _("Insufficient data to read indices.",{expectedBytes:G,availableBytes:n.byteLength-r,offset:r,indexCount:H,useUint16Indices:A});let F=A?ve(n.buffer,n.byteOffset+r,H):or(n.buffer,n.byteOffset+r,H);h&&(F=F instanceof Uint16Array?sr(F):lr(F)),ir(F,R),r+=G;let Y=null;if((c&Xn)!==0){let B=Jn(n,t,r,R,h);Y=B.uvs,r=B.offset}let J=null;return(c&qn)!==0&&(J=Qn(n,r,R,h)),{metadata:l,flags:c,vertices:y,indices:F,origin:[d,m,u],scale:[f,b,T],uvs:Y,colors:J}}var at=36;function Jn(e,n,t,r,i){if(t+at>e.byteLength)throw _("Insufficient data to read UV chunk header.",{expectedBytes:at,availableBytes:e.byteLength-t,offset:t});let o=n.getUint32(t,!0);t+=4;let a=n.getFloat64(t,!0);t+=8;let s=n.getFloat64(t,!0);t+=8;let l=n.getFloat64(t,!0);t+=8;let c=n.getFloat64(t,!0);t+=8;let d=r*2,m=o===Zn,u=d*(m?4:2);if(t+u>e.byteLength)throw _("Insufficient data to read UV chunk.",{expectedBytes:u,availableBytes:e.byteLength-t,offset:t,uvFormat:o,vertexCount:r});let f=e.byteOffset+t,b;if(m)b=st(e.buffer,f,d).slice();else{let T=ve(e.buffer,f,d);b=new Float32Array(d);let R=0,C=0;for(let h=0;h<d;h+=2)i?(R=R+Z(T[h])&65535,C=C+Z(T[h+1])&65535):(R=T[h],C=T[h+1]),b[h]=a+R*l,b[h+1]=s+C*c}return{uvs:b,offset:t+u}}function Qn(e,n,t,r){let i=t*3;if(n+i>e.byteLength)throw _("Insufficient data to read vertex-color chunk.",{expectedBytes:i,availableBytes:e.byteLength-n,offset:n,vertexCount:t});let o=e.subarray(n,n+i);if(!r)return o.slice();let a=new Uint8Array(i),s=0,l=0,c=0;for(let d=0;d<i;d+=3)s=s+Z(o[d])&255,l=l+Z(o[d+1])&255,c=c+Z(o[d+2])&255,a[d]=s,a[d+1]=l,a[d+2]=c;return a}function er(e){return typeof e=="string"?_chunkCUQQ3ZBVcjs.j.call(void 0, e):e instanceof Uint8Array?e:new Uint8Array(e)}function tr(e){if(e.byteLength<8)return e;let n=new DataView(e.buffer,e.byteOffset,e.byteLength);if(n.getUint32(0,!0)!==Wn)return e;let t=n.getUint32(4,!0),r=e.subarray(8),i=Math.max(r.byteLength*1032+1024,1<<20);if(t>i)throw _("SLVZ header declares an implausible uncompressed length",{uncompressedLen:t,deflatedBytes:r.byteLength,maxPlausibleLen:i});let o;try{o=_fflate.inflateSync.call(void 0, r,{out:new Uint8Array(t+1)})}catch(a){throw _(`Failed to inflate SLVZ blob: ${a instanceof Error?a.message:String(a)}`,{uncompressedLen:t,deflatedBytes:r.byteLength})}if(o.byteLength!==t)throw _("SLVZ payload inflated to a different size than the header declares.",{declaredLen:t,actualLen:o.byteLength,deflatedBytes:r.byteLength});return o}function nr(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, _chunkCUQQ3ZBVcjs.d)("No UTF-8 decoder available in this environment.",_chunkCUQQ3ZBVcjs.c.INVALID_STATE)}function rr(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 st(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 ve(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 or(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 ir(e,n){if(e.length!==0&&!(e instanceof Uint16Array&&n>65535)){for(let t=0;t<e.length;t++)if(e[t]>=n)throw _("Index out of range of vertexCount.",{indexPosition:t,indexValue:e[t],vertexCount:n})}}function Z(e){return e>>>1^-(e&1)}function ar(e){let n=new Int16Array(e.length),t=0,r=0,i=0;for(let o=0;o<e.length;o+=3)t=t+Z(e[o])<<16>>16,r=r+Z(e[o+1])<<16>>16,i=i+Z(e[o+2])<<16>>16,n[o]=t,n[o+1]=r,n[o+2]=i;return n}function sr(e){let n=new Uint16Array(e.length),t=0;for(let r=0;r<e.length;r++)t=t+Z(e[r])&65535,n[r]=t;return n}function lr(e){let n=new Uint32Array(e.length),t=0;for(let r=0;r<e.length;r++)t=t+Z(e[r])>>>0,n[r]=t;return n}function _(e,n){return new (0, _chunkCUQQ3ZBVcjs.d)(e,_chunkCUQQ3ZBVcjs.c.VALIDATION_ERROR,{context:n})}async function Uo(e,n){let{debug:t=!1}=_nullishCoalesce(n, () => ({})),r=t?performance.now():0,i,o=performance.now();try{i=JSON.parse(e)}catch(s){return _chunkCUQQ3ZBVcjs.e.call(void 0, ).error("Error parsing mesh batch envelope JSON:",s),[]}let a=performance.now()-o;return await we(i,n,{parseTime:a,perfStart:r})}async function we(e,n,t){let{mergeByMaterial:r=!0,applyTransforms:i=!0,debug:o=!1,material:a}=_nullishCoalesce(n, () => ({})),{parseTime:s=0,perfStart:l=o?performance.now():0}=_nullishCoalesce(t, () => ({}));if(!e.compressedData)return[];let c=performance.now(),d=He(e.compressedData),m=performance.now()-c,u=o?hr(e.compressedData):0;return lt(d,{mergeByMaterial:r,applyTransforms:i,debug:o,material:a,parseTime:s,decodeTime:m,perfStart:l,blobBytes:u,fallback:{materials:e.materials,groups:e.groups,sourceComponentId:e.sourceComponentId}})}async function zo(e,n){let{mergeByMaterial:t=!0,applyTransforms:r=!0,debug:i=!1,material:o}=_nullishCoalesce(n, () => ({})),a=i?performance.now():0,s=performance.now(),l=He(e),c=performance.now()-s,d=e.byteLength;return lt(l,{mergeByMaterial:t,applyTransforms:r,debug:i,material:o,parseTime:0,decodeTime:c,perfStart:a,blobBytes:d})}function lt(e,n){let{mergeByMaterial:t,applyTransforms:r,debug:i,material:o,parseTime:a,decodeTime:s,perfStart:l,blobBytes:c,fallback:d}=n,m=_nullishCoalesce(_nullishCoalesce(e.metadata.materials, () => (_optionalChain([d, 'optionalAccess', _244 => _244.materials]))), () => ([])),u=_nullishCoalesce(_nullishCoalesce(e.metadata.groups, () => (_optionalChain([d, 'optionalAccess', _245 => _245.groups]))), () => ([])),f=_nullishCoalesce(_optionalChain([d, 'optionalAccess', _246 => _246.sourceComponentId]), () => (e.metadata.sourceComponentId)),b=(e.flags&xe)!==0;cr(u,m.length,e.vertices.length/3,e.indices.length);let T=b?dr(e.vertices,r):ur(e.vertices,e.origin,e.scale,r);if(i){let L=e.vertices.byteLength+e.indices.byteLength;_chunkCUQQ3ZBVcjs.e.call(void 0, ).debug("Mesh Batch Stats:"),_chunkCUQQ3ZBVcjs.e.call(void 0, ).debug(` Materials: ${m.length} | Groups: ${u.length}`),_chunkCUQQ3ZBVcjs.e.call(void 0, ).debug(` Vertices: ${e.vertices.length/3} | Indices: ${e.indices.length}`),_chunkCUQQ3ZBVcjs.e.call(void 0, ).debug(` Format: ${b?"float32":"int16 quantized"}`),_chunkCUQQ3ZBVcjs.e.call(void 0, ).debug(` Blob: ${(c/1024/1024).toFixed(2)} MB | Geometry on wire: ${(L/1024/1024).toFixed(2)} MB`)}let R=performance.now(),C=m.map(L=>mr(L,{vertexColors:e.colors!=null,appearance:o})),h=[];for(let L of u)if(t&&L.meshes.length>1){let p=fr(L,T,e.indices,C,e.uvs,e.colors);p.userData.sourceComponentId=_nullishCoalesce(f, () => (null)),h.push(p)}else{let p=Er(L,T,e.indices,C,e.uvs,e.colors);for(let v of p)v.userData.sourceComponentId=_nullishCoalesce(f, () => (null));h.push(...p)}let x=performance.now()-R;if(i){let L=performance.now()-l;_chunkCUQQ3ZBVcjs.e.call(void 0, ).debug("Performance:"),a>0&&_chunkCUQQ3ZBVcjs.e.call(void 0, ).debug(` Parse JSON: ${a.toFixed(2)}ms`),_chunkCUQQ3ZBVcjs.e.call(void 0, ).debug(` Decode binary: ${s.toFixed(2)}ms`),_chunkCUQQ3ZBVcjs.e.call(void 0, ).debug(` Create Meshes: ${x.toFixed(2)}ms`),_chunkCUQQ3ZBVcjs.e.call(void 0, ).debug(` Total: ${L.toFixed(2)}ms`)}return Promise.resolve(h)}function le(e,n){return new (0, _chunkCUQQ3ZBVcjs.d)(e,_chunkCUQQ3ZBVcjs.c.VALIDATION_ERROR,{context:n})}function cr(e,n,t,r){for(let i of e){if(!Number.isInteger(i.materialId)||i.materialId<0||i.materialId>=n)throw le("Group materialId out of range of the materials array.",{materialId:i.materialId,materialCount:n});for(let o of i.meshes){let a={vertexStart:o.vertexStart,vertexCount:o.vertexCount,indexStart:o.indexStart,indexCount:o.indexCount};for(let[s,l]of Object.entries(a))if(!Number.isInteger(l)||l<0)throw le(`Mesh metadata field "${s}" must be a non-negative integer.`,{meshName:o.name,field:s,value:l});if(o.vertexStart+o.vertexCount>t)throw le("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 le("Mesh index window exceeds the batch index buffer.",{meshName:o.name,indexStart:o.indexStart,indexCount:o.indexCount,totalIndexCount:r})}}}function ct(e,n){if(e<n.vertexStart||e>=n.vertexStart+n.vertexCount)throw le("Index references a vertex outside its mesh's vertex window.",{meshName:n.name,indexValue:e,vertexStart:n.vertexStart,vertexCount:n.vertexCount})}function ur(e,n,t,r){let i=new Float32Array(e.length),o=n[0],a=n[1],s=n[2],l=t[0],c=t[1],d=t[2];for(let m=0;m<e.length;m+=3)i[m]=o+(e[m]+32767)*l,i[m+1]=a+(e[m+1]+32767)*c,i[m+2]=s+(e[m+2]+32767)*d;return i}function dr(e,n){return e}function mr(e,n){let t=Fe(e.color),r=_nullishCoalesce(_optionalChain([n, 'optionalAccess', _247 => _247.vertexColors]), () => (!1)),i=_optionalChain([n, 'optionalAccess', _248 => _248.appearance]),o=new P.MeshPhysicalMaterial({color:t,metalness:e.metalness,roughness:e.roughness,opacity:e.opacity,transparent:e.transparent,vertexColors:r,side:_optionalChain([i, 'optionalAccess', _249 => _249.cullBackfaces])?P.FrontSide:P.DoubleSide,polygonOffset:!0,polygonOffsetFactor:.5,polygonOffsetUnits:.5,depthWrite:!0,depthTest:!0});return _optionalChain([i, 'optionalAccess', _250 => _250.envMapIntensity])!=null&&(o.envMapIntensity=i.envMapIntensity),r&&pr(o),e.map&&Ke(o,e.map),o}function pr(e){e.onBeforeCompile=n=>{n.vertexShader=n.vertexShader.replace("#include <color_vertex>",`#include <color_vertex>
|
|
55
|
-
#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )
|
|
56
|
-
vColor.rgb = mix(
|
|
57
|
-
vColor.rgb / 12.92,
|
|
58
|
-
pow( ( vColor.rgb + 0.055 ) / 1.055, vec3( 2.4 ) ),
|
|
59
|
-
step( vec3( 0.04045 ), vColor.rgb )
|
|
60
|
-
);
|
|
61
|
-
#endif`)}}function fr(e,n,t,r,i=null,o=null){let a=0,s=0;for(let h of e.meshes)a+=h.vertexCount,s+=h.indexCount;let l=new Float32Array(a*3),c=new Uint32Array(s),d=i?new Float32Array(a*2):null,m=o?new Uint8Array(a*3):null,u=0,f=0;for(let h of e.meshes){let x=h.vertexStart*3,L=h.vertexCount*3;if(l.set(n.subarray(x,x+L),u*3),d&&i){let y=h.vertexStart*2;d.set(i.subarray(y,y+h.vertexCount*2),u*2)}m&&o&&m.set(o.subarray(x,x+L),u*3);let p=t.subarray(h.indexStart,h.indexStart+h.indexCount),v=u-h.vertexStart;for(let y=0;y<p.length;y++){let H=p[y];ct(H,h),c[f+y]=H+v}u+=h.vertexCount,f+=h.indexCount}let b=new P.BufferGeometry;b.setAttribute("position",new P.BufferAttribute(l,3)),b.setIndex(new P.BufferAttribute(c,1)),d&&b.setAttribute("uv",new P.BufferAttribute(d,2)),m&&b.setAttribute("color",new P.BufferAttribute(m,3,!0)),b.computeVertexNormals();let T=new P.Mesh(b,r[e.materialId]),R=e.meshes[0],C=e.meshes.map(h=>h.name).filter(h=>h&&h.length>0);return T.name=C.length>0?C[0]:`merged_material_${e.materialId}`,T.castShadow=!0,T.receiveShadow=!0,T.userData={source:"compute",name:T.name,layer:_nullishCoalesce(_optionalChain([R, 'optionalAccess', _251 => _251.layer]), () => ("")),originalIndex:_nullishCoalesce(_optionalChain([R, 'optionalAccess', _252 => _252.originalIndex]), () => (0)),metadata:_nullishCoalesce(_optionalChain([R, 'optionalAccess', _253 => _253.metadata]), () => ({})),mergedFrom:e.meshes.slice(1).map(h=>({name:h.name,layer:h.layer,originalIndex:h.originalIndex}))},T}function Er(e,n,t,r,i=null,o=null){let a=[];for(let s of e.meshes){let l=s.vertexStart*3,c=s.vertexCount*3,d=n.slice(l,l+c),m=t.subarray(s.indexStart,s.indexStart+s.indexCount),u=new Uint32Array(m.length),f=s.vertexStart;for(let R=0;R<m.length;R++){let C=m[R];ct(C,s),u[R]=C-f}let b=new P.BufferGeometry;if(b.setAttribute("position",new P.BufferAttribute(d,3)),b.setIndex(new P.BufferAttribute(u,1)),i){let R=s.vertexStart*2,C=i.slice(R,R+s.vertexCount*2);b.setAttribute("uv",new P.BufferAttribute(C,2))}if(o){let R=o.slice(l,l+c);b.setAttribute("color",new P.BufferAttribute(R,3,!0))}b.computeVertexNormals();let T=new P.Mesh(b,r[e.materialId]);T.name=s.name,T.userData={source:"compute",name:s.name,layer:_nullishCoalesce(s.layer, () => ("")),originalIndex:s.originalIndex,metadata:_nullishCoalesce(s.metadata, () => ({}))},T.castShadow=!0,T.receiveShadow=!0,a.push(T)}return a}function hr(e){return Math.floor(e.length*3/4)}var ut={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},gr="Display",yr="DisplayBatch";function br(e){let n=e.split(".");return n.includes(gr)||n.includes(yr)}var dt=new Set;async function $o(e,n){let t=performance.now(),r=[],{allowScaling:i=!0,allowAutoPosition:o=!0,rhino:a,debug:s=!1,parsing:l={}}=_nullishCoalesce(n, () => ({}));try{let c=i?Tr(e.modelunits):1;return await Rr(e,r,c,l,a,s),o&&wr(r),r}catch(c){throw Cr(c,r),c}finally{s&&Ar(t)}}function Tr(e){let n=ut[e];return n!==void 0?n:(dt.has(e)||(dt.add(e),_chunkCUQQ3ZBVcjs.e.call(void 0, ).warn(`Unknown Rhino model unit "${e}" \u2014 geometry will not be scaled (factor 1). Known units: ${Object.keys(ut).join(", ")}.`)),1)}async function Rr(e,n,t,r,i,o){for(let a of e.values){let s=a.InnerTree;for(let l in s){let c=s[l];c&&await vr(c,n,t,r,i,o)}}}async function vr(e,n,t,r,i,o){for(let a of e){if(!br(a.type))continue;let s={mergeByMaterial:!0,applyTransforms:!0,debug:!1,...r},l=xr(a.data);if(!l){_chunkCUQQ3ZBVcjs.e.call(void 0, ).error("Error parsing display batch envelope: invalid JSON");continue}let c=await we(l,s),d=Qe(l.items,{rhino:i,applyTransforms:s.applyTransforms}),m=[...c,...d];if(t!==1)for(let u of m)u.scale.set(t,t,t);n.push(...m),o&&_chunkCUQQ3ZBVcjs.e.call(void 0, ).debug(`Extracted ${c.length} meshes and ${d.length} items from batch`)}}function xr(e){return typeof e=="string"?Hr(e):e}function Hr(e){try{return JSON.parse(e)}catch (e3){return}}function wr(e){if(e.length===0)return;let n=ye(e);ke(e,n.min.z,"z")}function Cr(e,n){_chunkCUQQ3ZBVcjs.e.call(void 0, ).error("An unexpected error occurred:",e),Mr(n)}function Mr(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 Ar(e){let n=performance.now()-e;_chunkCUQQ3ZBVcjs.e.call(void 0, ).info("Time to process meshes:",`${n.toFixed(2)}ms`)}exports.a = Rt; exports.b = Dr; exports.c = Fe; exports.d = ke; exports.e = ye; exports.f = Ue; exports.g = ze; exports.h = _e; exports.i = ue; exports.j = Ge; exports.k = _t; exports.l = jr; exports.m = Ne; exports.n = $e; exports.o = rn; exports.p = qe; exports.q = on; exports.r = Ze; exports.s = ro; exports.t = fn; exports.u = yo; exports.v = To; exports.w = Qe; exports.x = tt; exports.y = Wn; exports.z = nt; exports.A = rt; exports.B = xe; exports.C = $n; exports.D = Yn; exports.E = Xn; exports.F = qn; exports.G = Do; exports.H = Zn; exports.I = He; exports.J = Uo; exports.K = we; exports.L = zo; exports.M = ut; exports.N = $o;
|
|
62
|
-
//# sourceMappingURL=chunk-GFY3L653.cjs.map
|