@selvajs/compute 4.0.2 → 4.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/README.md +26 -56
- package/dist/core-PfYDuaFq.js +3 -0
- package/dist/core-PfYDuaFq.js.map +1 -0
- package/dist/core-wTiSQLB8.cjs +3 -0
- package/dist/core-wTiSQLB8.cjs.map +1 -0
- package/dist/core.cjs +1 -1
- package/dist/core.d.cts +2 -2
- package/dist/core.d.ts +2 -2
- package/dist/core.js +1 -1
- package/dist/grasshopper.cjs +1 -1
- package/dist/grasshopper.cjs.map +1 -1
- package/dist/grasshopper.d.cts +50 -10
- package/dist/grasshopper.d.ts +50 -10
- package/dist/grasshopper.js +1 -1
- package/dist/grasshopper.js.map +1 -1
- package/dist/{index-C7Olveh2.d.ts → index-zlzEAi12.d.cts} +56 -5
- package/dist/{index-C7Olveh2.d.cts → index-zlzEAi12.d.ts} +56 -5
- package/package.json +2 -2
- package/dist/core-BQtRL5GE.js +0 -3
- package/dist/core-BQtRL5GE.js.map +0 -1
- package/dist/core-DdSvCuFX.cjs +0 -3
- package/dist/core-DdSvCuFX.cjs.map +0 -1
package/dist/grasshopper.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { M as ComputeError, O as ComputeConfig, _ as isDefinitionRef, a as extractFilesFromComputeResponse, c as ProcessedFile, g as SolveDefinition, h as DefinitionRef, k as RetryPolicy, o as FileBaseInfo, r as downloadFileData, s as FileData } from "./index-zlzEAi12.cjs";
|
|
2
2
|
//#region src/grasshopper/server/compute-server-stats.d.ts
|
|
3
3
|
/**
|
|
4
4
|
* ComputeServerStats provides methods to query Rhino Compute server statistics.
|
|
@@ -61,6 +61,24 @@ declare class ComputeServerStats {
|
|
|
61
61
|
* stalling the caller indefinitely.
|
|
62
62
|
*/
|
|
63
63
|
isServerOnline(timeoutMs?: number): Promise<boolean>;
|
|
64
|
+
/**
|
|
65
|
+
* Detailed liveness probe backing {@link isServerOnline}.
|
|
66
|
+
*
|
|
67
|
+
* Reports what the probe actually saw so callers can distinguish "connection
|
|
68
|
+
* failed" (`error` set) from "server answered non-2xx" (`status` set) — e.g.
|
|
69
|
+
* a 401 from a proxy that requires an API key is a misconfiguration, not an
|
|
70
|
+
* offline server. Same single-sample caveat as {@link isServerOnline}.
|
|
71
|
+
*
|
|
72
|
+
* @param timeoutMs - Abort the probe after this many ms (default: 5000).
|
|
73
|
+
* Pass `0` to disable the timeout.
|
|
74
|
+
* @returns `online` plus either the HTTP `status` the server answered with,
|
|
75
|
+
* or the `error` the connection attempt failed with.
|
|
76
|
+
*/
|
|
77
|
+
probeServer(timeoutMs?: number): Promise<{
|
|
78
|
+
online: boolean;
|
|
79
|
+
status?: number;
|
|
80
|
+
error?: string;
|
|
81
|
+
}>;
|
|
64
82
|
/**
|
|
65
83
|
* Get the number of active child processes on the server.
|
|
66
84
|
*
|
|
@@ -280,7 +298,7 @@ declare class ComputeServerStats {
|
|
|
280
298
|
* @param intervalMs - Milliseconds between checks (default: 5000). Must be a
|
|
281
299
|
* finite number of at least 100 ms — lower values would hot-loop the server.
|
|
282
300
|
* @returns Function to stop monitoring
|
|
283
|
-
* @throws {
|
|
301
|
+
* @throws {ComputeError} `INVALID_CONFIG` if `intervalMs` is not a finite number >= 100.
|
|
284
302
|
*
|
|
285
303
|
* @example
|
|
286
304
|
* ```typescript
|
|
@@ -902,6 +920,12 @@ declare class SolveScheduler {
|
|
|
902
920
|
* Responses served from the cache (and via `lastResult`) are shared objects,
|
|
903
921
|
* not copies — treat them as immutable. Mutating one poisons every later
|
|
904
922
|
* cache hit for that key.
|
|
923
|
+
*
|
|
924
|
+
* Partial-success contract: unlike `GrasshopperClient.solve()`, which throws
|
|
925
|
+
* `COMPUTATION_ERROR` when the response carries solver errors, this RESOLVES
|
|
926
|
+
* with the response as-is — check `response.errors` yourself if a partial
|
|
927
|
+
* success must not be treated as a result (see `cacheErroredSolves` for the
|
|
928
|
+
* caching side of the same distinction).
|
|
905
929
|
*/
|
|
906
930
|
solve(definition: SolveDefinition, dataTree: DataTree[], options?: {
|
|
907
931
|
signal?: AbortSignal;
|
|
@@ -1039,19 +1063,34 @@ declare class GrasshopperClient {
|
|
|
1039
1063
|
private readonly config;
|
|
1040
1064
|
readonly serverStats: ComputeServerStats;
|
|
1041
1065
|
private disposed;
|
|
1066
|
+
/**
|
|
1067
|
+
* Per-probe timeout for the `create()` liveness gate. A healthy `GET /` on the
|
|
1068
|
+
* proxy answers in milliseconds; this bound only ever applies to a server that
|
|
1069
|
+
* is not answering, where every extra second is multiplied by the retry count
|
|
1070
|
+
* and paid by whoever is waiting on the solve.
|
|
1071
|
+
*/
|
|
1072
|
+
private static readonly CREATE_PROBE_TIMEOUT_MS;
|
|
1042
1073
|
private constructor();
|
|
1043
1074
|
/**
|
|
1044
1075
|
* Creates and initializes a GrasshopperClient with server validation.
|
|
1045
1076
|
*
|
|
1046
1077
|
* The pre-flight liveness probe (a GET on the proxy root `/`) is a
|
|
1047
1078
|
* single-sample boolean gate that reads a cold or briefly-busy-but-up server
|
|
1048
|
-
* as offline. To avoid failing
|
|
1049
|
-
*
|
|
1050
|
-
*
|
|
1051
|
-
*
|
|
1079
|
+
* as offline. To avoid failing construction on that transient class, the probe
|
|
1080
|
+
* is retried with a short exponential backoff before giving up.
|
|
1081
|
+
*
|
|
1082
|
+
* Retries stop early when {@link classifyProbeFailure} says waiting cannot
|
|
1083
|
+
* change the answer — connection refused, or a 401/403. This runs in front of
|
|
1084
|
+
* a user who clicked Solve, so the retry ladder must not spend its whole
|
|
1085
|
+
* budget confirming that a machine is switched off.
|
|
1086
|
+
*
|
|
1087
|
+
* Each probe is bounded by {@link CREATE_PROBE_TIMEOUT_MS} rather than the
|
|
1088
|
+
* stats default: a healthy `GET /` answers in milliseconds, so a longer
|
|
1089
|
+
* per-probe timeout only multiplies the wait when the server is unreachable.
|
|
1052
1090
|
*
|
|
1053
1091
|
* @throws {ComputeError} with code NETWORK_ERROR if the server stays
|
|
1054
|
-
* unreachable across all attempts
|
|
1092
|
+
* unreachable across all attempts. `context.probeVerdict` carries the
|
|
1093
|
+
* {@link ProbeVerdict} so callers can render a specific cause.
|
|
1055
1094
|
* @throws {ComputeError} with code INVALID_CONFIG if configuration is invalid
|
|
1056
1095
|
*/
|
|
1057
1096
|
static create(config: GrasshopperComputeConfig): Promise<GrasshopperClient>;
|
|
@@ -1676,9 +1715,10 @@ declare class TreeBuilder {
|
|
|
1676
1715
|
*
|
|
1677
1716
|
* @param pathStr - Path string
|
|
1678
1717
|
* @returns Array of path indices
|
|
1679
|
-
* @throws
|
|
1680
|
-
* Malformed keys must never silently collapse to a
|
|
1681
|
-
* two distinct unparseable keys would merge their items
|
|
1718
|
+
* @throws {ComputeError} `INVALID_INPUT` when the path string is not a valid
|
|
1719
|
+
* Grasshopper branch path. Malformed keys must never silently collapse to a
|
|
1720
|
+
* default branch — two distinct unparseable keys would merge their items
|
|
1721
|
+
* into one branch.
|
|
1682
1722
|
*/
|
|
1683
1723
|
static parsePathString(pathStr: string): number[];
|
|
1684
1724
|
/**
|
package/dist/grasshopper.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { M as ComputeError, O as ComputeConfig, _ as isDefinitionRef, a as extractFilesFromComputeResponse, c as ProcessedFile, g as SolveDefinition, h as DefinitionRef, k as RetryPolicy, o as FileBaseInfo, r as downloadFileData, s as FileData } from "./index-zlzEAi12.js";
|
|
2
2
|
//#region src/grasshopper/server/compute-server-stats.d.ts
|
|
3
3
|
/**
|
|
4
4
|
* ComputeServerStats provides methods to query Rhino Compute server statistics.
|
|
@@ -61,6 +61,24 @@ declare class ComputeServerStats {
|
|
|
61
61
|
* stalling the caller indefinitely.
|
|
62
62
|
*/
|
|
63
63
|
isServerOnline(timeoutMs?: number): Promise<boolean>;
|
|
64
|
+
/**
|
|
65
|
+
* Detailed liveness probe backing {@link isServerOnline}.
|
|
66
|
+
*
|
|
67
|
+
* Reports what the probe actually saw so callers can distinguish "connection
|
|
68
|
+
* failed" (`error` set) from "server answered non-2xx" (`status` set) — e.g.
|
|
69
|
+
* a 401 from a proxy that requires an API key is a misconfiguration, not an
|
|
70
|
+
* offline server. Same single-sample caveat as {@link isServerOnline}.
|
|
71
|
+
*
|
|
72
|
+
* @param timeoutMs - Abort the probe after this many ms (default: 5000).
|
|
73
|
+
* Pass `0` to disable the timeout.
|
|
74
|
+
* @returns `online` plus either the HTTP `status` the server answered with,
|
|
75
|
+
* or the `error` the connection attempt failed with.
|
|
76
|
+
*/
|
|
77
|
+
probeServer(timeoutMs?: number): Promise<{
|
|
78
|
+
online: boolean;
|
|
79
|
+
status?: number;
|
|
80
|
+
error?: string;
|
|
81
|
+
}>;
|
|
64
82
|
/**
|
|
65
83
|
* Get the number of active child processes on the server.
|
|
66
84
|
*
|
|
@@ -280,7 +298,7 @@ declare class ComputeServerStats {
|
|
|
280
298
|
* @param intervalMs - Milliseconds between checks (default: 5000). Must be a
|
|
281
299
|
* finite number of at least 100 ms — lower values would hot-loop the server.
|
|
282
300
|
* @returns Function to stop monitoring
|
|
283
|
-
* @throws {
|
|
301
|
+
* @throws {ComputeError} `INVALID_CONFIG` if `intervalMs` is not a finite number >= 100.
|
|
284
302
|
*
|
|
285
303
|
* @example
|
|
286
304
|
* ```typescript
|
|
@@ -902,6 +920,12 @@ declare class SolveScheduler {
|
|
|
902
920
|
* Responses served from the cache (and via `lastResult`) are shared objects,
|
|
903
921
|
* not copies — treat them as immutable. Mutating one poisons every later
|
|
904
922
|
* cache hit for that key.
|
|
923
|
+
*
|
|
924
|
+
* Partial-success contract: unlike `GrasshopperClient.solve()`, which throws
|
|
925
|
+
* `COMPUTATION_ERROR` when the response carries solver errors, this RESOLVES
|
|
926
|
+
* with the response as-is — check `response.errors` yourself if a partial
|
|
927
|
+
* success must not be treated as a result (see `cacheErroredSolves` for the
|
|
928
|
+
* caching side of the same distinction).
|
|
905
929
|
*/
|
|
906
930
|
solve(definition: SolveDefinition, dataTree: DataTree[], options?: {
|
|
907
931
|
signal?: AbortSignal;
|
|
@@ -1039,19 +1063,34 @@ declare class GrasshopperClient {
|
|
|
1039
1063
|
private readonly config;
|
|
1040
1064
|
readonly serverStats: ComputeServerStats;
|
|
1041
1065
|
private disposed;
|
|
1066
|
+
/**
|
|
1067
|
+
* Per-probe timeout for the `create()` liveness gate. A healthy `GET /` on the
|
|
1068
|
+
* proxy answers in milliseconds; this bound only ever applies to a server that
|
|
1069
|
+
* is not answering, where every extra second is multiplied by the retry count
|
|
1070
|
+
* and paid by whoever is waiting on the solve.
|
|
1071
|
+
*/
|
|
1072
|
+
private static readonly CREATE_PROBE_TIMEOUT_MS;
|
|
1042
1073
|
private constructor();
|
|
1043
1074
|
/**
|
|
1044
1075
|
* Creates and initializes a GrasshopperClient with server validation.
|
|
1045
1076
|
*
|
|
1046
1077
|
* The pre-flight liveness probe (a GET on the proxy root `/`) is a
|
|
1047
1078
|
* single-sample boolean gate that reads a cold or briefly-busy-but-up server
|
|
1048
|
-
* as offline. To avoid failing
|
|
1049
|
-
*
|
|
1050
|
-
*
|
|
1051
|
-
*
|
|
1079
|
+
* as offline. To avoid failing construction on that transient class, the probe
|
|
1080
|
+
* is retried with a short exponential backoff before giving up.
|
|
1081
|
+
*
|
|
1082
|
+
* Retries stop early when {@link classifyProbeFailure} says waiting cannot
|
|
1083
|
+
* change the answer — connection refused, or a 401/403. This runs in front of
|
|
1084
|
+
* a user who clicked Solve, so the retry ladder must not spend its whole
|
|
1085
|
+
* budget confirming that a machine is switched off.
|
|
1086
|
+
*
|
|
1087
|
+
* Each probe is bounded by {@link CREATE_PROBE_TIMEOUT_MS} rather than the
|
|
1088
|
+
* stats default: a healthy `GET /` answers in milliseconds, so a longer
|
|
1089
|
+
* per-probe timeout only multiplies the wait when the server is unreachable.
|
|
1052
1090
|
*
|
|
1053
1091
|
* @throws {ComputeError} with code NETWORK_ERROR if the server stays
|
|
1054
|
-
* unreachable across all attempts
|
|
1092
|
+
* unreachable across all attempts. `context.probeVerdict` carries the
|
|
1093
|
+
* {@link ProbeVerdict} so callers can render a specific cause.
|
|
1055
1094
|
* @throws {ComputeError} with code INVALID_CONFIG if configuration is invalid
|
|
1056
1095
|
*/
|
|
1057
1096
|
static create(config: GrasshopperComputeConfig): Promise<GrasshopperClient>;
|
|
@@ -1676,9 +1715,10 @@ declare class TreeBuilder {
|
|
|
1676
1715
|
*
|
|
1677
1716
|
* @param pathStr - Path string
|
|
1678
1717
|
* @returns Array of path indices
|
|
1679
|
-
* @throws
|
|
1680
|
-
* Malformed keys must never silently collapse to a
|
|
1681
|
-
* two distinct unparseable keys would merge their items
|
|
1718
|
+
* @throws {ComputeError} `INVALID_INPUT` when the path string is not a valid
|
|
1719
|
+
* Grasshopper branch path. Malformed keys must never silently collapse to a
|
|
1720
|
+
* default branch — two distinct unparseable keys would merge their items
|
|
1721
|
+
* into one branch.
|
|
1682
1722
|
*/
|
|
1683
1723
|
static parsePathString(pathStr: string): number[];
|
|
1684
1724
|
/**
|
package/dist/grasshopper.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{S as e,_ as t,c as n,f as r,g as i,h as a,l as o,o as s,p as c,r as l,s as u,t as d,u as ee,x as f,y as p}from"./core-BQtRL5GE.js";var m=class t{serverUrl;apiKey;disposed=!1;activeMonitors=new Set;activeTimeouts=new Set;static DEFAULT_TIMEOUT_MS=5e3;static LIFECYCLE_TIMEOUT_MS=6e4;static MIN_MONITOR_INTERVAL_MS=100;constructor(e,t){this.serverUrl=a(e),this.apiKey=t}buildHeaders(){let e={"Content-Type":`application/json`};return this.apiKey&&(e.RhinoComputeKey=this.apiKey),e}fetchWithTimeout(e,n={},r=t.DEFAULT_TIMEOUT_MS){let i=new Headers(this.buildHeaders());n.headers&&new Headers(n.headers).forEach((e,t)=>{i.set(t,e)});let a={};i.forEach((e,t)=>{a[t]=e});let o={...n,headers:a};return r>0&&!o.signal&&(o.signal=AbortSignal.timeout(r)),fetch(e,o)}async isServerOnline(e=5e3){this.ensureNotDisposed();let t=`${this.serverUrl}/`;try{return(await this.fetchWithTimeout(t,{method:`GET`},e)).ok}catch(e){return p().debug(`[ComputeServerStats] Fetch error:`,e),!1}}async getActiveChildren(e={}){this.ensureNotDisposed();let{initialize:n=!0}=e,r=n?`${this.serverUrl}/activechildren`:`${this.serverUrl}/activechildren?initialize=false`,i=n?t.LIFECYCLE_TIMEOUT_MS:t.DEFAULT_TIMEOUT_MS;try{let e=await this.fetchWithTimeout(r,{},i);if(!e.ok)return p().warn(`[ComputeServerStats] Failed to fetch active children:`,e.status),null;let t=(await e.text()).trim();return/^\d+$/.test(t)?parseInt(t,10):(p().warn(`[ComputeServerStats] Invalid active children response:`,t),null)}catch(e){return p().warn(`[ComputeServerStats] Error fetching active children:`,e),null}}async getVersion(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/version`);if(!e.ok)return p().warn(`[ComputeServerStats] Failed to fetch version:`,e.status),null;let t=await e.text();try{let e=JSON.parse(t);return{rhino:e.rhino??``,compute:e.compute??``,git_sha:e.git_sha??null}}catch{return{rhino:t,compute:``,git_sha:null}}}catch(e){return p().warn(`[ComputeServerStats] Error fetching version:`,e),null}}async getInstalledPlugins(e=`gh`){this.ensureNotDisposed();try{let t=await this.fetchWithTimeout(`${this.serverUrl}/plugins/${e}/installed`);if(!t.ok)return p().warn(`[ComputeServerStats] Failed to fetch ${e} plugins:`,t.status),null;let n=await t.text();try{let e=JSON.parse(n);return e&&typeof e==`object`?e:null}catch{return null}}catch(t){return p().warn(`[ComputeServerStats] Error fetching ${e} plugins:`,t),null}}async getServerStats(){if(this.ensureNotDisposed(),!await this.isServerOnline())return{isOnline:!1};let[e,t]=await Promise.all([this.getVersion(),this.getActiveChildren({initialize:!1})]);return{isOnline:!0,...e&&{version:e},...t!==null&&{activeChildren:t}}}async purgeCache(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/cache/purge`,{method:`POST`});if(!e.ok)return p().warn(`[ComputeServerStats] Failed to purge cache:`,e.status),null;let t=await e.text();try{let e=JSON.parse(t);return typeof e.purged==`number`?e.purged:null}catch{return null}}catch(e){return p().warn(`[ComputeServerStats] Error purging cache:`,e),null}}async purgeAllChildren(){this.ensureNotDisposed();let e=await this.getActiveChildren({initialize:!1});if(e===null)return p().warn(`[ComputeServerStats] purgeAllChildren: could not read child count`),null;if(e===0)return{totalPurged:0,calls:0,children:0,confident:!0};let t=e*2,n=0;for(let e=0;e<t;e++){let e=await this.purgeCache();e!==null&&(n+=e)}return{totalPurged:n,calls:t,children:e,confident:e===1}}async getServerTime(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/servertime`);if(!e.ok)return p().warn(`[ComputeServerStats] Failed to fetch server time:`,e.status),null;let t=(await e.text()).trim().replace(/^"|"$/g,``),n=new Date(t);return isNaN(n.getTime())?null:n}catch(e){return p().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 p().warn(`[ComputeServerStats] Failed to fetch idle span:`,e.status),null;let t=parseFloat((await e.text()).trim());return isNaN(t)?null:t}catch(e){return p().warn(`[ComputeServerStats] Error fetching idle span:`,e),null}}async launchChildren(){return this.postJson(`/launch-children`)}async launchChild(e){let t=e===void 0?`/launch-child`:`/launch-child?port=${e}`;return this.postJson(t)}async shutdownChildren(e){let t=e===void 0?`/shutdown-children`:`/shutdown-children?port=${e}`;return this.postJson(t)}async recycleChildren(e){let t=e===void 0?`/recycle-children`:`/recycle-children?port=${e}`;return this.postJson(t)}async postJson(e){this.ensureNotDisposed();try{let n=await this.fetchWithTimeout(`${this.serverUrl}${e}`,{method:`POST`},t.LIFECYCLE_TIMEOUT_MS);if(!n.ok)return p().warn(`[ComputeServerStats] POST ${e} failed:`,n.status),null;let r=await n.text();try{return JSON.parse(r)}catch{return null}}catch(t){return p().warn(`[ComputeServerStats] Error on POST ${e}:`,t),null}}monitor(e,n=5e3){if(this.ensureNotDisposed(),!Number.isFinite(n)||n<t.MIN_MONITOR_INTERVAL_MS)throw RangeError(`monitor() intervalMs must be a finite number >= ${t.MIN_MONITOR_INTERVAL_MS}ms, got ${n}. Sub-${t.MIN_MONITOR_INTERVAL_MS}ms polling would hot-loop the server.`);let r=!0,i=null;p().info(`🔄 Starting server stats monitoring every ${n}ms`);let a=async()=>{if(i!==null&&(this.activeTimeouts.delete(i),i=null),!(!r||this.disposed)){try{let t=await this.getServerStats();if(!r||this.disposed)return;try{e(t)}catch(e){p().error(`[ComputeServerStats] Monitor callback threw:`,e)}}catch(e){!r||this.disposed?p().debug(`[ComputeServerStats] Monitor poll cancelled during shutdown:`,e):p().error(`[ComputeServerStats] Failed to fetch stats during monitor:`,e)}r&&!this.disposed&&(i=setTimeout(()=>void a(),n),this.activeTimeouts.add(i))}},o=()=>{r=!1,i!==null&&(clearTimeout(i),this.activeTimeouts.delete(i),i=null),this.activeMonitors.delete(o)};return this.activeMonitors.add(o),a(),o}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 f(`ComputeServerStats has been disposed and cannot be used`,e.INVALID_STATE,{context:{disposed:this.disposed}})}};const h=new Set;function te(){if(typeof window>`u`||globalThis.process?.versions?.node!=null)return!1;let e=globalThis.navigator,t=typeof e?.userAgent==`string`?e.userAgent:``;return!/jsdom/i.test(t)}function g(e,t){t||te()&&!h.has(e)&&(h.add(e),p().warn(`Warning: ${e} is running on the client side. For better performance and security, consider running this on the server side.`))}const ne={definition_not_cached:e.DEFINITION_NOT_CACHED};function _(e){return{...e,serverErrorCodes:{...ne,...e.serverErrorCodes}}}function re(t){return t instanceof f?t.code===e.DEFINITION_NOT_CACHED||t.message.includes(`Unable to load grasshopper definition`):!1}function ie(e,n){if(!n)return;let r=t(e,`values`);if(!Array.isArray(r)||r.length===0)return;let i=[];for(let e of r){let n=t(e,`innerTree`);(!n||Object.keys(n).length===0)&&i.push(t(e,`paramName`)??`<unnamed>`)}if(i.length===0)return;let a=i.length===r.length?`all`:`${i.length}/${r.length}`;p().warn(`Solve returned empty output(s) (${a}): ${i.join(`, `)}. These parameters produced no data — check the definition's inputs and the branch feeding each.`)}async function v(e,t,n){g(`solveGrasshopperDefinition`,n.suppressBrowserWarning);let{response:r}=await b(x(await y(t),e),n);return r}async function ae(e,t,n){return g(`solveGrasshopperDefinitionWithCacheKey`,n.suppressBrowserWarning),b(x(await y(t),e),n)}async function oe(e,t,n,r){g(`solveByCacheKey`,r.suppressBrowserWarning);let i={algo:null,pointer:t,values:e};try{return{...await b(i,r),missed:!1}}catch(t){if(!re(t))throw t;return{...await b(x(await y(n),e),r),missed:!0}}}async function y(t){if(!s(t))return t;try{return await t.load()}catch(n){throw new f(`Failed to load definition bytes for ref '${t.key}'`,e.INVALID_INPUT,{context:{definitionKey:t.key},originalError:n instanceof Error?n:Error(String(n))})}}async function b(e,t){se(e,t);let r=await u(`grasshopper`,e,_(t)),{pointer:i,algo:a,...s}=r,c=s,l=n(r);if(l!==void 0){let e=typeof a==`string`?a.length:0;o(c,Math.max(0,l-e))}return ie(c,t.debug),{response:c,cacheKey:typeof i==`string`?i:null}}function x(e,t){let n={algo:null,pointer:null,values:t};return e instanceof Uint8Array?n.algo=ee(e):/^https?:\/\//i.test(e)?n.pointer=e:n.algo=r(e)??c(e),n}function se(e,t){t.cachesolve!=null&&(e.cachesolve=t.cachesolve),t.cacheerroredsolves!=null&&(e.cacheerroredsolves=t.cacheerroredsolves),t.modelunits!=null&&(e.modelunits=t.modelunits),t.angletolerance!=null&&(e.angletolerance=t.angletolerance),t.absolutetolerance!=null&&(e.absolutetolerance=t.absolutetolerance),t.dataversion!=null&&(e.dataversion=t.dataversion)}function S(e){let t=new WeakSet,n=e=>{if(e===void 0)return`undefined`;if(e===null)return`null`;if(typeof e==`number`)return Number.isFinite(e)?String(e):`null`;if(typeof e==`string`||typeof e==`boolean`)return JSON.stringify(e);if(typeof e==`bigint`)return`${e}n`;if(e instanceof Uint8Array)return`{"__u8":${e.length},"hash":"${C(e)}"}`;if(Array.isArray(e)){if(t.has(e))return`"[Circular]"`;t.add(e);let r=[];for(let t=0;t<e.length;t++)r.push(n(e[t]));return t.delete(e),`[${r.join(`,`)}]`}if(typeof e==`object`){if(t.has(e))return`"[Circular]"`;t.add(e);let r;return r=typeof e.toJSON==`function`?n(e.toJSON()):e instanceof Map?`{"__map":[${[...e.entries()].map(([e,t])=>`[${n(e)},${n(t)}]`).sort().join(`,`)}]}`:e instanceof Set?`{"__set":[${[...e.values()].map(n).sort().join(`,`)}]}`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${n(e[t])}`).join(`,`)}}`,t.delete(e),r}return`null`};return n(e)}function ce(e,t){let n=2166136261;for(let r=0;r<e;r++)n^=t(r),n=n+((n<<1)+(n<<4)+(n<<7)+(n<<8)+(n<<24))>>>0;return n.toString(16).padStart(8,`0`)}function le(e){return ce(e.length,t=>e.charCodeAt(t))}function C(e){return ce(e.length,t=>e[t])}function ue(e,t){return w(T(e),t)}function w(e,t){let n=S(t);return`${e}|t:${n.length}:${le(n)}`}function T(e){return s(e)?`r:${e.key}`:typeof e==`string`?`s:${e.length}:${le(e)}`:`u8:${e.length}:${C(e)}`}function de(e){return typeof e!=`string`||!/^https?:\/\//i.test(e)}function fe(e){try{return JSON.stringify(e)?.length??0}catch{return 0}}var E=class{executor;baseConfig;mode;maxConcurrent;maxQueueDepth;queueWaitMs;timeoutMs;retry;cacheEnabled;cacheMaxBytes;cacheTtl;cacheErroredSolves;cache=new Map;cacheBytes=0;cacheHits=0;cacheMisses=0;cacheEvictions=0;cacheKeyExecutor;reuseServerDefinitionCache;serverCacheKeys=new Map;onStart;onSettle;onSuperseded;subscribers=new Set;inFlight=new Set;pendingForLatestWins=null;fifoQueue=[];_lastResult=null;_lastError=null;_lastDurationMs=null;solveSeq=0;lastStateSeq=0;disposed=!1;constructor(e,t,n={},r){this.executor=e,this.cacheKeyExecutor=r,this.baseConfig=t,this.mode=n.mode??`latest-wins`,this.maxConcurrent=Math.max(1,n.maxConcurrent??(this.mode===`parallel`?4:1)),this.maxQueueDepth=n.maxQueueDepth!==void 0&&n.maxQueueDepth>0?Math.floor(n.maxQueueDepth):void 0,this.queueWaitMs=n.queueWaitMs!==void 0&&n.queueWaitMs>0?n.queueWaitMs:void 0,this.timeoutMs=n.timeoutMs,this.retry=n.retry;let i=n.cache,a=typeof i==`object`?i:null;this.cacheMaxBytes=Math.max(0,a?.maxBytes??0),this.cacheEnabled=this.cacheMaxBytes>0,this.cacheTtl=a?.ttlMs??0,this.cacheErroredSolves=a?.cacheErroredSolves??!0,this.reuseServerDefinitionCache=!!r&&(n.reuseServerDefinitionCache??!0),this.onStart=n.onStart,this.onSettle=n.onSettle,this.onSuperseded=n.onSuperseded}get isSolving(){return this.inFlight.size>0}get hasPending(){return this.pendingForLatestWins!==null||this.fifoQueue.length>0}get inFlightCount(){return this.inFlight.size}get queueDepth(){return this.fifoQueue.length+ +!!this.pendingForLatestWins}get lastResult(){return this._lastResult}get lastError(){return this._lastError}get lastDurationMs(){return this._lastDurationMs}setMaxConcurrent(e){let t=Math.max(1,Math.floor(e));if(t===this.maxConcurrent)return;let n=t>this.maxConcurrent;this.maxConcurrent=t,n&&this.drainNext()}getMaxConcurrent(){return this.maxConcurrent}subscribe(e){return this.subscribers.add(e),()=>this.subscribers.delete(e)}notify(){for(let e of this.subscribers)try{e()}catch(e){p().error(`[SolveScheduler] subscriber threw:`,e)}}solve(t,n,r){if(this.disposed)return Promise.reject(new f(`SolveScheduler has been disposed and cannot be used`,e.INVALID_STATE));let i=T(t),a=w(i,n),o=++this.solveSeq,s={key:a,enqueuedAt:Date.now(),startedAt:null};if(r?.signal?.aborted)return Promise.reject(this.makeAbortError(s));if(this.cacheEnabled){let e=this.readCache(a);if(e){this.mode===`latest-wins`&&this.supersedeCurrent();let t={status:`success`,response:e,durationMs:0,fromCache:!0};return this.writeLastState(o,{result:e,durationMs:0}),this.runHook(this.onStart,s),this.runHook(this.onSettle,s,t),this.notify(),Promise.resolve(e)}}return new Promise((e,a)=>{let c={definition:t,dataTree:n,definitionHash:i,ctx:s,seq:o,resolve:e,reject:a,externalSignal:r?.signal};c.externalSignal&&(c.queuedAbortHandler=()=>this.abortQueuedItem(c),c.externalSignal.addEventListener(`abort`,c.queuedAbortHandler,{once:!0})),this.enqueue(c)})}writeLastState(e,t){return e<this.lastStateSeq?!1:(this.lastStateSeq=e,`result`in t?(this._lastResult=t.result,this._lastError=null):this._lastError=t.error,this._lastDurationMs=t.durationMs,!0)}supersedeCurrent(){this.pendingForLatestWins&&=(this.supersede(this.pendingForLatestWins),null);for(let e of this.inFlight)this.supersede(e),e.controller.abort()}abortQueuedItem(e){this.pendingForLatestWins===e&&(this.pendingForLatestWins=null);let t=this.fifoQueue.indexOf(e);t>=0&&this.fifoQueue.splice(t,1),this.rejectAsAborted(e),this.notify()}shedAsQueueFull(t){let n=new f(`Solve queue is full; request rejected (backpressure)`,e.QUEUE_FULL,{statusCode:503,context:{key:t.ctx.key,queueDepth:this.fifoQueue.length,maxQueueDepth:this.maxQueueDepth}});this.settleError(t,n)&&this.runHook(this.onSettle,t.ctx,{status:`error`,error:n,durationMs:0}),this.notify()}armQueueWaitTimer(t){if(this.queueWaitMs===void 0)return;let n=this.queueWaitMs;t.queueWaitTimer=setTimeout(()=>{if(t.settled)return;let r=this.fifoQueue.indexOf(t);r>=0&&this.fifoQueue.splice(r,1);let i=new f(`Solve waited longer than ${n}ms in queue; rejected (backpressure)`,e.QUEUE_TIMEOUT,{statusCode:503,context:{key:t.ctx.key,waitedMs:Date.now()-t.ctx.enqueuedAt,queueWaitMs:n}});this.settleError(t,i)&&this.runHook(this.onSettle,t.ctx,{status:`error`,error:i,durationMs:0}),this.notify()},n)}clearQueueWaitTimer(e){e.queueWaitTimer!==void 0&&(clearTimeout(e.queueWaitTimer),e.queueWaitTimer=void 0)}enqueue(e){switch(this.mode){case`latest-wins`:this.supersedeCurrent(),this.inFlight.size===0?this.execute(e):this.pendingForLatestWins=e;break;case`queue`:case`parallel`:this.inFlight.size<this.maxConcurrent?this.execute(e):this.maxQueueDepth!==void 0&&this.fifoQueue.length>=this.maxQueueDepth?this.shedAsQueueFull(e):(this.armQueueWaitTimer(e),this.fifoQueue.push(e))}this.notify()}async execute(e){let t=new AbortController,n=e;n.controller=t,this.inFlight.add(n),e.ctx.startedAt=Date.now(),this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e);let r=()=>t.abort();e.externalSignal?.addEventListener(`abort`,r,{once:!0}),this.runHook(this.onStart,e.ctx),this.notify();let i=performance.now();try{let n={...this.baseConfig,signal:t.signal,...this.timeoutMs!==void 0&&{timeoutMs:this.timeoutMs},...this.retry!==void 0&&{retry:this.retry}},{response:r,definitionReuploaded:a}=await this.runExecutor(e.definition,e.dataTree,e.definitionHash,n),o=performance.now()-i;if(this.cacheEnabled&&this.writeCache(e.ctx.key,r),!this.settleSuccess(e,r))return;this.writeLastState(e.seq,{result:r,durationMs:o}),this.runHook(this.onSettle,e.ctx,{status:`success`,response:r,durationMs:o,fromCache:!1,definitionReuploaded:a})}catch(t){let r=performance.now()-i,a=this.normalizeExecutionError(t,n);this.writeLastState(e.seq,{error:a,durationMs:r}),this.settleError(e,a)&&this.runHook(this.onSettle,e.ctx,{status:`error`,error:a,durationMs:r})}finally{e.externalSignal?.removeEventListener(`abort`,r),this.inFlight.delete(n),this.drainNext(),this.notify()}}async runExecutor(e,t,n,r){if(!this.cacheKeyExecutor||!this.reuseServerDefinitionCache||!de(e))return{response:await this.executor(e,t,r)};let i=n,a=this.serverCacheKeys.get(i)??null,o=await this.cacheKeyExecutor(e,t,a,r);if(o.cacheKey)for(this.serverCacheKeys.delete(i),this.serverCacheKeys.set(i,o.cacheKey);this.serverCacheKeys.size>100;){let e=this.serverCacheKeys.keys().next().value;if(e===void 0)break;this.serverCacheKeys.delete(e)}else this.serverCacheKeys.delete(i);return{response:o.response,definitionReuploaded:o.missed}}drainNext(){if(!this.disposed){if(this.mode===`latest-wins`){if(this.pendingForLatestWins&&this.inFlight.size===0){let e=this.pendingForLatestWins;this.pendingForLatestWins=null,this.execute(e)}return}for(;this.fifoQueue.length>0&&this.inFlight.size<this.maxConcurrent;){let e=this.fifoQueue.shift();this.execute(e)}}}supersede(t){let n=new f(`Superseded by newer solve`,e.SUPERSEDED,{context:{key:t.ctx.key,enqueuedAt:t.ctx.enqueuedAt}});this.settleError(t,n)&&this.runHook(this.onSuperseded,t.ctx)}makeAbortError(t){return new f(`Request aborted by caller`,e.ABORTED,{context:{key:t.key,enqueuedAt:t.enqueuedAt}})}settleError(e,t){return!e.settled&&(e.settled={error:t},this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e),e.reject(t),!0)}settleSuccess(e,t){return!e.settled&&(e.settled={ok:!0},this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e),e.resolve(t),!0)}removeQueuedAbortHandler(e){e.queuedAbortHandler&&e.externalSignal&&e.externalSignal.removeEventListener(`abort`,e.queuedAbortHandler),e.queuedAbortHandler=void 0}isAbortLikeError(e){if(e instanceof Error){if(e.name===`AbortError`)return!0;if(typeof DOMException<`u`&&e instanceof DOMException)return e.name===`AbortError`}return!1}normalizeExecutionError(t,n){return n.settled&&`error`in n.settled?n.settled.error:t instanceof f?t:this.isAbortLikeError(t)?this.makeAbortError(n.ctx):new f(t instanceof Error?t.message:String(t),e.UNKNOWN_ERROR,{originalError:t instanceof Error?t:Error(String(t))})}cancelAll(){for(this.pendingForLatestWins&&=(this.rejectAsAborted(this.pendingForLatestWins),null);this.fifoQueue.length>0;){let e=this.fifoQueue.shift();this.rejectAsAborted(e)}for(let e of this.inFlight){let t=this.makeAbortError(e.ctx);this.settleError(e,t)&&this.runHook(this.onSettle,e.ctx,{status:`error`,error:t,durationMs:e.ctx.startedAt?Date.now()-e.ctx.startedAt:0}),e.controller.abort()}this.notify()}rejectAsAborted(e){let t=this.makeAbortError(e.ctx);this.settleError(e,t)&&this.runHook(this.onSettle,e.ctx,{status:`error`,error:t,durationMs:0})}readCache(e){if(!this.cacheEnabled)return null;let t=this.cache.get(e);return t?this.cacheTtl>0&&Date.now()-t.insertedAt>this.cacheTtl?(this.dropCacheEntry(e),this.cacheMisses+=1,null):(this.cache.delete(e),this.cache.set(e,t),this.cacheHits+=1,t.response):(this.cacheMisses+=1,null)}writeCache(e,t){if(!this.cacheEnabled||!this.cacheErroredSolves&&t.errors&&t.errors.length>0)return;let r=n(t)??fe(t);if(!(r>this.cacheMaxBytes))for(this.dropCacheEntry(e),this.cache.set(e,{response:t,insertedAt:Date.now(),sizeBytes:r}),this.cacheBytes+=r;this.cacheBytes>this.cacheMaxBytes&&this.cache.size>0;){let e=this.cache.keys().next().value;if(e===void 0)break;this.dropCacheEntry(e),this.cacheEvictions+=1}}dropCacheEntry(e){let t=this.cache.get(e);t&&(this.cache.delete(e),this.cacheBytes-=t.sizeBytes)}clearCache(){this.cache.clear(),this.cacheBytes=0}cacheStats(){return{entries:this.cache.size,bytes:this.cacheBytes,hits:this.cacheHits,misses:this.cacheMisses,evictions:this.cacheEvictions}}dispose(){this.disposed||(this.disposed=!0,this.cancelAll(),this.subscribers.clear(),this.clearCache())}runHook(e,...t){if(e)try{e(...t)}catch(e){p().error(`[SolveScheduler] hook threw:`,e)}}};function D(e){return s(e)?`ref:${e.key}`:typeof e==`string`&&e.length<200?e:`...content...`}function O(e){return Array.isArray(e)?e.map(e=>{let n=0,r=0,i=t(e,`innerTree`);if(i&&typeof i==`object`){for(let e of Object.values(i))if(Array.isArray(e)){n+=e.length;for(let t of e){let e=t?.data;typeof e==`string`&&(r+=e.length)}}}return{param:t(e,`paramName`)??`<unnamed>`,items:n,bytes:r}}):[]}var pe=class t{config;serverStats;disposed=!1;constructor(e){this.config=this.normalizeComputeConfig(e),this.serverStats=new m(this.config.serverUrl,this.config.apiKey)}static async create(n){let r=new t(n),i=Math.max(1,(n.retry?.attempts??2)+1),a=n.retry?.baseDelayMs??250,o=n.retry?.maxDelayMs??1e3;for(let e=0;e<i;e++){if(await r.serverStats.isServerOnline())return r;if(e<i-1){let t=Math.min(a*2**e,o);await new Promise(e=>setTimeout(e,t))}}throw await r.dispose(),new f(`Rhino Compute server is not online`,e.NETWORK_ERROR,{context:{serverUrl:r.config.serverUrl,attempts:i}})}getConfig(){return this.ensureNotDisposed(),{...this.config}}async getIO(e){return this.ensureNotDisposed(),qe(e,this.config)}async getRawIO(e){return this.ensureNotDisposed(),Q(e,this.config)}async solve(t,n,r){this.ensureNotDisposed();try{if(typeof t==`string`&&!t?.trim())throw new f(`Definition URL/content is required`,e.INVALID_INPUT,{context:{receivedUrl:t}});if(t instanceof Uint8Array&&t.length===0)throw new f(`Definition content is empty`,e.INVALID_INPUT);if(s(t)&&!t.key.trim())throw new f(`DefinitionRef key is empty`,e.INVALID_INPUT);let i=await v(n,t,{...this.config,...r?.signal!==void 0&&{signal:r.signal},...r?.timeoutMs!==void 0&&{timeoutMs:r.timeoutMs},...r?.retry!==void 0&&{retry:r.retry}});if(i?.errors&&i.errors.length>0)throw new f(i.errors.join(`; `)||`Computation failed`,e.COMPUTATION_ERROR,{context:{definition:D(t),inputSummary:O(n),errors:i.errors,warnings:i.warnings,values:i.values}});return i}catch(r){throw this.config.debug&&p().error(`Compute failed:`,r),r instanceof f?r:new f(r instanceof Error?r.message:String(r),e.COMPUTATION_ERROR,{context:{definition:D(t),inputSummary:O(n)},originalError:r instanceof Error?r:Error(String(r))})}}createScheduler(e){return this.ensureNotDisposed(),new E((e,t,n)=>v(t,e,n),this.config,e,(e,t,n,r)=>n===null?ae(t,e,r).then(e=>({...e,missed:!1})):oe(t,n,e,r))}async dispose(){this.disposed||(this.disposed=!0,await this.serverStats.dispose())}ensureNotDisposed(){if(this.disposed)throw new f(`GrasshopperClient has been disposed and cannot be used`,e.INVALID_STATE)}normalizeComputeConfig(e){return{...e,serverUrl:a(e.serverUrl),apiKey:e.apiKey,authToken:e.authToken,debug:e.debug??!1,suppressBrowserWarning:e.suppressBrowserWarning}}};const k=new Map;function A(e,t){k.set(e,t)}A(`Rhino.Geometry.Point3d`,(e,t)=>{let n=t;return!n||typeof n.X!=`number`?null:new e.Point([n.X,n.Y,n.Z])}),A(`Rhino.Geometry.Line`,(e,t)=>{let n=t;return!n||!n.From||!n.To?null:new e.Line([n.From.X,n.From.Y,n.From.Z],[n.To.X,n.To.Y,n.To.Z])});function me(e){if(k.has(e))return k.get(e);for(let[t,n]of k)if(e.startsWith(t))return n}function he(e){return!!(e&&typeof e==`object`&&typeof e.data==`string`)}function j(e,t){return{__decodeError:!0,type:e,raw:t}}function ge(e,t,n){let r=me(t),i=!1;if(r)try{let t=r(n,e);if(t!=null)return t}catch(e){p().warn(`Failed to decode Rhino type ${t}:`,e),i=!0}try{if(he(e))return n.CommonObject.decode(e)}catch(n){return p().warn(`Failed to decode ${t} with CommonObject:`,n),j(t,e)}return i?j(t,e):e}function _e(e){let t=new WeakSet,n=e=>{if(!e||typeof e!=`object`||t.has(e))return;t.add(e);let r=e.delete;if(typeof r==`function`){let t=e.isDeleted;(typeof t!=`function`||!t.call(e))&&r.call(e);return}if(Array.isArray(e)){for(let t of e)n(t);return}let i=Object.getPrototypeOf(e);if(i===Object.prototype||i===null)for(let t of Object.values(e))n(t)};n(e)}const M={STRING:`System.String`,INT:`System.Int32`,DOUBLE:`System.Double`,BOOL:`System.Boolean`},ve=[`WebDisplay`];function N(e){return ve.some(t=>e.includes(t))}function ye(e){if(typeof e!=`string`)return e;let t=e.trim();if(!(t.startsWith(`{`)||t.startsWith(`[`)||t.startsWith(`"`)))return e;try{let e=JSON.parse(t);if(typeof e==`string`)try{return JSON.parse(e)}catch{return e}return e}catch{return e}}function be(e,t,n){switch(t){case M.STRING:return typeof e==`string`?e.replace(/^"(.*)"$/,`$1`):e;case M.INT:return Number.parseInt(e,10);case M.DOUBLE:return Number.parseFloat(e);case M.BOOL:return String(e).toLowerCase()===`true`;default:return n&&t.startsWith(`Rhino.Geometry.`)?ge(e,t,n):e}}const P=new WeakMap;function F(e){if(P.has(e))return P.get(e);let t=ye(e.data);return P.set(e,t),t}function I(e,t,n,r){return typeof e.data==`string`?be(n?F(e):e.data,t,r):e.data}function xe(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.fileName==`string`&&typeof t.fileType==`string`&&`data`in t&&typeof t.isBase64Encoded==`boolean`&&typeof t.subFolder==`string`}function L(e){let n=t(e,`values`);return Array.isArray(n)?n:[]}function R(e){return typeof e.type==`string`?e.type:``}function z(e,t){if(!(!e||typeof e!=`object`)){for(let n of Object.values(e))if(Array.isArray(n))for(let e of n)e&&typeof e==`object`&&t(e)}}function Se(e,n=!1,r={}){let{parseValues:i=!0,rhino:a,stringOnly:o=!1}=r,s={},c=new Set;for(let r of L(e)){let e=t(r,`paramName`);z(t(r,`innerTree`),t=>{let r=R(t);if(N(r)||o&&r!==M.STRING)return;let l=n?t.id:e;if(!l)return;let u=I(t,r,i,a);l in s?c.has(l)?s[l].push(u):(s[l]=[s[l],u],c.add(l)):s[l]=u})}return{values:s,dispose:()=>_e(s)}}function Ce(e){let n=[];for(let r of L(e))z(t(r,`innerTree`),e=>{if(!R(e).includes(`FileData`))return;let t=F(e);xe(t)&&n.push(t)});return n}function we(e,n,r={}){let{parseValues:i=!0,rhino:a,stringOnly:o=!1}=r;for(let r of L(e)){let e=t(r,`innerTree`),s=!1;if(`byName`in n){if(t(r,`paramName`)!==n.byName)continue;s=!0}let c=[];if(z(e,e=>{if(`byId`in n){if(e.id!==n.byId)return;s=!0}let t=R(e);N(t)||o&&t!==M.STRING||c.push(I(e,t,i,a))}),s)return c.length===0?void 0:c.length===1?c[0]:c}}var Te=class{response;debug;constructor(e,t=!1){this.response=e,this.debug=t}getValues(e=!1,t={}){return Se(this.response,e,t)}getValue(e,t){return we(this.response,e,t)}getFileData(){return Ce(this.response)}async getAndDownloadFiles(e,t){let n=this.getFileData();await d(n,e,t)}};const B=/^\{(-?\d+(?:;-?\d+)*)?\}$/;function V(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.entries(e);return t.length>0&&t.every(([e,t])=>B.test(e)&&Array.isArray(t))}function H(e,t,n){let r=Number(e.toFixed(t));return Math.abs(e-r)<n?r:e}function Ee(e,t){if(!Number.isFinite(e)||e===0)return .1;let n=Math.abs(e);if(n>=1){let n=String(e).split(`.`)[1];if(n&&n.length>0){let e=Math.min(n.length,12),r=10**-e,i=Number(r.toFixed(e));return Math.abs(i-r)<t?i:r}return 1}let r=String(e),i=r.toLowerCase().match(/e(-?\d+)/);if(i){let e=Number(i[1]);if(e<0||r.toLowerCase().includes(`e-`)){let n=Math.abs(e),r=10**-n,i=Number(r.toFixed(n));return Math.abs(i-r)<t?i:r}return .1}let a=n.toFixed(12).replace(/0+$/,``),o=Math.min((a.split(`.`)[1]||``).length,12);if(o===0)return .1;let s=10**-o,c=Number(s.toFixed(o));return Math.abs(c-s)<t?c:s}function U(e){return typeof e.stepSize==`number`&&Number.isFinite(e.stepSize)&&e.stepSize>0?e.stepSize:void 0}function W(e,t,n){if(e==null)return e;if(Array.isArray(e)){let n=e.map(t).filter(e=>e!==null);return n.length>0?n:void 0}let r=t(e);return r===null?n?void 0:e:r}const G=e=>{if(typeof e==`number`)return Number.isFinite(e)?e:null;if(typeof e==`string`){let t=e.trim();if(t===``||/^[+-]?0[xbo]/i.test(t))return null;let n=Number(t);return Number.isFinite(n)?n:null}return null},K=e=>{if(typeof e==`boolean`)return e;if(typeof e==`string`){let t=e.trim().toLowerCase();if(t===`true`)return!0;if(t===`false`)return!1}return null},De=e=>typeof e==`string`?e.length>=2&&e.startsWith(`"`)&&e.endsWith(`"`)?e.slice(1,-1):e.startsWith(`"`)?e.slice(1):e:null,Oe=e=>{if(typeof e==`string`){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)&&(t=t.slice(1,-1).trim()),t}return null};function q(e){return t=>{if(typeof t==`object`&&t)return t;if(typeof t==`string`&&t.trim()!==``)try{let n=JSON.parse(t);return typeof n==`object`&&n?n:(p().warn(`Parsed value for input ${e} is not an object`),null)}catch(n){return p().warn(`Failed to parse object value "${t}" for input ${e}`,n),null}return null}}function ke(t,n=1e-8){let r=t.paramType===`Integer`,i=U(t);if(V(t.default))return{default:t.default,stepSize:i??(r?1:.1)};if(typeof t.default==`string`&&t.default.trim()!==``&&G(t.default)===null)throw new f(`Invalid numeric default "${t.default}" for input "${t.name||`unknown`}"`,e.VALIDATION_ERROR,{context:{inputName:t.name,default:t.default}});let a=W(t.default,G,!0);if(r)return Array.isArray(a)?a=a.map(e=>typeof e==`number`?Math.round(e):e):typeof a==`number`&&(a=Math.round(a)),{default:a,stepSize:i??1};let o=Array.isArray(a)?a[0]:a,s;typeof o==`number`&&Number.isFinite(o)&&o!==0?s=o:typeof t.minimum==`number`&&Number.isFinite(t.minimum)&&t.minimum!==0?s=t.minimum:typeof t.maximum==`number`&&Number.isFinite(t.maximum)&&t.maximum!==0&&(s=t.maximum);let c=i??(s===void 0?.1:Ee(s,n)),l=0,u=String(c),d=u.toLowerCase().match(/e(-?\d+)/);if(l=d?Math.abs(Number(d[1])):u.split(`.`)[1]?.length??0,l===0&&typeof o==`number`&&o!==0&&Math.abs(o)<1){let e=Math.ceil(-Math.log10(Math.abs(o)));Number.isFinite(e)&&e>0&&(l=e)}return l=Math.min(Math.max(l,0),12),Array.isArray(a)?a=a.map(e=>typeof e==`number`?H(e,l,n):e):typeof a==`number`&&(a=H(a,l,n)),{default:a,stepSize:c}}const Ae={types:[`Number`,`Integer`],parse(e,t){let{default:n,stepSize:r}=ke(e);return{...t,paramType:e.paramType,minimum:e.minimum,maximum:e.maximum,atLeast:e.atLeast,atMost:e.atMost,stepSize:r,default:n}},fallback(e,t){let n=(e.atMost??1)>1,r=typeof e.minimum==`number`&&Number.isFinite(e.minimum)&&e.minimum>0?e.minimum:0;return{...t,paramType:e.paramType,minimum:e.minimum,maximum:e.maximum,atLeast:e.atLeast,atMost:e.atMost,stepSize:U(e)??(e.paramType===`Integer`?1:.1),default:n?[r]:r}}},je={types:[`Boolean`],parse(t,n){if(V(t.default))return{...n,paramType:`Boolean`,default:t.default};let r=W(t.default,K,!1);if(r!=null&&typeof r!=`boolean`&&!Array.isArray(r))throw new f(`Invalid boolean default "${String(r)}" for input "${t.name||`unknown`}"`,e.VALIDATION_ERROR,{context:{inputName:t.name,default:t.default}});return{...n,paramType:`Boolean`,default:r}},fallback(e,t){let n=(e.atMost??1)>1;return{...t,paramType:`Boolean`,default:n?[!1]:!1}}},Me={types:[`Text`],parse(e,t){let n=W(e.default,De,!1);return{...t,paramType:`Text`,default:n}},fallback(e,t){let n=(e.atMost??1)>1;return{...t,paramType:`Text`,default:n?[``]:``}}},Ne={types:[`ValueList`],parse(t,n){if(!t.values||typeof t.values!=`object`||Object.keys(t.values).length===0)throw f.missingValues(t.nickname||`unnamed`,`ValueList`);let r=t.default;if(t.default!==void 0&&t.default!==null){if(typeof t.default==`object`)throw new f(`ValueList input "${t.nickname||`unnamed`}" default is not a string-able value`,e.VALIDATION_ERROR,{context:{inputName:t.name,default:t.default}});let n=String(t.default).toLowerCase(),i=Object.keys(t.values).find(e=>e.toLowerCase()===n);i===void 0?p().warn(`ValueList input "${t.nickname||`unnamed`}" default value "${t.default}" is not in available values`):r=i}return{...n,paramType:`ValueList`,values:t.values,default:r}},fallback(e,t){return{...t,paramType:`ValueList`,values:e.values&&typeof e.values==`object`?e.values:{},default:void 0}}},J={types:[`Geometry`],parse(e,t){let n=W(e.default,q(e.nickname||`unnamed`),!0);return{...t,paramType:`Geometry`,default:n}},fallback(e,t){let n=(e.atMost??1)>1;return{...t,paramType:`Geometry`,default:n?[null]:null}}},Y=new Map([Ae,je,Me,Ne,J,{types:[`File`],parse(e,t){let n=W(e.default,q(e.nickname||`unnamed`),!0);return{...t,paramType:`File`,acceptedFormats:e.acceptedFormats,default:n}},fallback(e,t){let n=(e.atMost??1)>1;return{...t,paramType:`File`,default:n?[null]:null}}},{types:[`Color`],parse(e,t){let n=W(e.default,Oe,!1);return{...t,paramType:`Color`,default:n}},fallback(e,t){let n=(e.atMost??1)>1;return{...t,paramType:`Color`,default:n?[`0, 0, 0`]:`0, 0, 0`}}}].flatMap(e=>e.types.map(t=>[t,e]))),Pe=J;function X(e){return t(e,`data`)}function Fe(e){return t(e,`type`)}const Ie=new Set([`System.Double`,`System.Single`,`System.Decimal`,`System.Int32`,`System.Int64`]),Le=new Set([`System.Int32`,`System.Int64`]);function Re(e){if(typeof e.default!=`object`||e.default===null||Array.isArray(e.default))return{schema:e};if(!i(e.default,`innerTree`)){let t=`Input "${e.name??`unknown`}" default had an unrecognized shape (no innerTree key); the default was dropped.`;return p().warn(`Unexpected structure in input.default:`,e.default),{schema:{...e,default:null},warning:{code:`MALFORMED_DEFAULT`,message:t}}}let n=t(e.default,`innerTree`)??{};if(Object.keys(n).length===0)return{schema:{...e,default:void 0}};if(e.treeAccess||e.atMost&&e.atMost>1){let t={},r=[];for(let[i,a]of Object.entries(n)){if(!Array.isArray(a)){let t=`Input "${e.name??`unknown`}" default had a non-array innerTree branch ("${i}"); the default was dropped.`;return p().warn(`Unexpected structure in input.default innerTree:`,e.default),{schema:{...e,default:null},warning:{code:`MALFORMED_DEFAULT`,message:t}}}let n=[];for(let e of a){let t=X(e),i=Fe(e);if(i&&Ie.has(i)){if(typeof t==`string`&&t.trim()===``)continue;let e=G(t);if(e===null){r.push(`"${String(t)}" (${i})`);continue}n.push(Le.has(i)?Math.round(e):e);continue}if(i===`System.Boolean`){let e=K(t);if(e===null){r.push(`"${String(t)}" (${i})`);continue}n.push(e);continue}if(typeof t==`string`&&i?.startsWith(`Rhino.Geometry`)){try{n.push(JSON.parse(t))}catch{n.push(t)}continue}n.push(t)}t[i]=n}let i;if(r.length>0){let t=`Input "${e.name??`unknown`}" default contained ${r.length} tree value(s) that could not be parsed and were dropped: ${r.join(`, `)}.`;p().warn(t),i={code:`MALFORMED_DEFAULT`,message:t}}return{schema:{...e,default:t},...i&&{warning:i}}}let r=[];for(let e of Object.values(n))Array.isArray(e)&&e.forEach(e=>{e&&typeof e==`object`&&i(e,`data`)&&r.push(X(e))});return r.length===0?{schema:{...e,default:void 0}}:r.length===1?{schema:{...e,default:r[0]}}:{schema:{...e,default:r}}}const ze=new Map([...Y.keys()].map(e=>[e.toLowerCase(),e]));function Be(e){return ze.get(e?.toLowerCase())??e}function Ve(e){return Z(e).input}function Z(e){let t={description:e.description,name:e.name,nickname:e.nickname,treeAccess:e.treeAccess,groupName:e.groupName??void 0,id:e.id},n=Be(e.paramType),r={...e,paramType:n},i;try{let{schema:t,warning:n}=Re(r);r=t,i=n&&{inputName:e.name||`unknown`,paramType:e.paramType,message:n.message,code:n.code}}catch(t){r={...r,default:null},i={inputName:e.name||`unknown`,paramType:e.paramType,message:`Input "${e.name??`unknown`}" default could not be normalized and was dropped: ${t instanceof Error?t.message:String(t)}`,code:`MALFORMED_DEFAULT`}}let a=Y.get(n);try{if(!a)throw f.unknownParamType(n,e.name);return{input:a.parse(r,t),error:i,...i&&{errors:[i]}}}catch(o){if(o instanceof f){p().error(`Validation error for input ${e.name||`unknown`}:`,o.message);let n={inputName:e.name||`unknown`,paramType:e.paramType,message:o.message,code:o.code};return{input:(a??Pe).fallback(r,t),error:n,errors:i?[i,n]:[n]}}throw new f(o instanceof Error?o.message:String(o),`VALIDATION_ERROR`,{context:{paramName:e.name,paramType:n},originalError:o instanceof Error?o:Error(String(o))})}}function He(e){let t=[],n=[];for(let r of e){let{input:e,errors:i}=Z(r);t.push(e),i&&n.push(...i)}return{inputs:t,parseErrors:n}}function Ue(e){let n=t(e,`stepSize`);return{id:t(e,`id`)??``,name:t(e,`name`)??``,nickname:t(e,`nickname`)??null,description:t(e,`description`)??``,paramType:t(e,`paramType`)??``,treeAccess:t(e,`treeAccess`)??!1,minimum:t(e,`minimum`)??null,maximum:t(e,`maximum`)??null,atLeast:t(e,`atLeast`)??1,atMost:t(e,`atMost`)??1,stepSize:typeof n==`number`&&Number.isFinite(n)?n:void 0,default:t(e,`default`),values:t(e,`values`),acceptedFormats:t(e,`acceptedFormats`),groupName:t(e,`groupName`)??null}}function We(e){return{name:t(e,`name`)??``,nickname:t(e,`nickname`)??null,paramType:t(e,`paramType`)??``,id:t(e,`id`)??``}}async function Q(n,r){let i=x(n,[]),a={};if(i.algo&&(a.algo=i.algo),i.pointer&&(a.pointer=i.pointer),!a.algo&&!a.pointer)throw new f(`Definition must resolve to either a URL pointer or base64 algo`,e.INVALID_INPUT,{context:{definition:n}});let o=await u(`io`,a,_(r));if(!o||typeof o!=`object`)throw new f(`Invalid IO response structure`,e.INVALID_INPUT,{context:{response:o,definition:n}});let s=Ge(t(o,`warnings`)),c=Ge(t(o,`errors`)),l=t(o,`inputs`),d=t(o,`outputs`);return{inputs:Array.isArray(l)?l.map(Ue):[],outputs:Array.isArray(d)?d.map(We):[],...s&&{loadWarnings:s},...c&&{loadErrors:c}}}function Ge(e){if(!Array.isArray(e))return;let t=e.map(Ke).filter(e=>e!==void 0);return t.length>0?t:void 0}function Ke(e){if(e==null)return;let n;if(typeof e==`string`)n=e;else if(typeof e==`object`){let r=t(e,`message`);if(typeof r==`string`&&r.trim().length>0)n=r;else try{n=JSON.stringify(e)??String(e)}catch{n=String(e)}}else n=String(e);return n.trim().length>0?n:void 0}async function qe(e,t){g(`fetchParsedDefinitionIO`,t.suppressBrowserWarning);let{inputs:n,outputs:r,loadWarnings:i,loadErrors:a}=await Q(e,t),{inputs:o,parseErrors:s}=He(n);return{inputs:o,outputs:r,...s.length>0&&{parseErrors:s},...i&&{loadWarnings:i},...a&&{loadErrors:a}}}function Je(e){return(Array.isArray(e)?e:[e]).map(e=>({schemas:t(e,`schemas`),error:t(e,`error`)}))}const Ye=new Set([`options`,`defaultOptions`,`values`]),Xe=e=>e>=`A`&&e<=`Z`;function Ze(e){if(e.length===0||!Xe(e[0]))return e;let t=0;for(;t<e.length&&Xe(e[t]);)t++;return t>1&&t<e.length&&t--,e.slice(0,t).toLowerCase()+e.slice(t)}function Qe(e){return $(e)}function $(e){if(Array.isArray(e))return e.map($);if(typeof e!=`object`||!e)return e;let t={};for(let[n,r]of Object.entries(e)){let e=Ze(n);t[e]=Ye.has(e)?r:$(r)}return t}var $e=class e{innerTree;paramName;constructor(e){this.paramName=e,this.innerTree={}}append(t,n){let r=e.formatPathString(t);this.innerTree[r]||(this.innerTree[r]=[]);let i=n.map(t=>({data:e.serializeValue(t)}));return this.innerTree[r].push(...i),this}appendSingle(e,t){return this.append(e,[t])}fromDataTreeDefault(t){this.innerTree={};for(let[n,r]of Object.entries(t)){if(!Array.isArray(r))continue;let t=e.parsePathString(n);this.append(t,r)}return this}appendFlat(e){let t=Array.isArray(e)?e:[e];return this.append([0],t)}flatten(){let t=[];for(let n of Object.values(this.innerTree))if(Array.isArray(n))for(let r of n)t.push(e.deserializeValue(r.data));return t}getPaths(){return Object.keys(this.innerTree)}getPath(t){let n=e.formatPathString(t),r=this.innerTree[n];if(r)return r.map(t=>e.deserializeValue(t.data))}toComputeFormat(){return{ParamName:this.paramName,InnerTree:this.innerTree}}getInnerTree(){return this.innerTree}getParamName(){return this.paramName}static fromInputParams(t){return t.filter(t=>e.hasValidValue(t.default)).map(t=>{let n=new e(t.nickname||`unnamed`),r=t.default;if(t.treeAccess&&V(r))n.fromDataTreeDefault(r),e.isNumericInput(t)&&n.applyNumericConstraints(t.minimum,t.maximum,t.nickname||`unnamed`);else{let i=Array.isArray(r)?r:[r],a=e.processValues(i,t);n.appendFlat(a)}return n.toComputeFormat()})}static fromInputParam(t){if(e.hasValidValue(t.default))return e.fromInputParams([t])[0]}static replaceTreeValue(t,n,r){let i=t.length>0&&t[0]instanceof e,a=e.buildFromValue(n,r);if(i){let e=t.slice(),r=e.findIndex(e=>e.getParamName()===n);return r===-1?e.push(a):e[r]=a,e}let o=t.slice(),s=a.toComputeFormat(),c=o.findIndex(e=>e.ParamName===n);return c===-1?o.push(s):o[c]=s,o}static buildFromValue(t,n){let r=new e(t);return V(n)?r.fromDataTreeDefault(n):r.appendFlat(n),r}static getTreeValue(t,n){let r=t.length>0&&t[0]instanceof e?e.readFromBuilders(t,n):e.readFromDataTrees(t,n);return r===null||r.length===0?null:r.length===1?r[0]:r}static readFromBuilders(e,t){let n=e.find(e=>e.getParamName()===t);return n?n.flatten():null}static readFromDataTrees(t,n){let r=t.find(e=>e.ParamName===n);if(!r?.InnerTree)return null;let i=Object.keys(r.InnerTree)[0];if(!i)return null;let a=r.InnerTree[i];return Array.isArray(a)?a.map(t=>t?.data===void 0?null:e.deserializeValue(t.data)):a?.data===void 0?a===void 0?null:[a]:[e.deserializeValue(a.data)]}static parsePathString(e){let t=e.match(B);if(!t)throw Error(`Invalid Grasshopper tree path: "${e}". Expected "{}", "{0}", or "{0;1;2}" (negative indices allowed, no empty segments).`);return t[1]?t[1].split(`;`).map(Number):[]}static formatPathString(e){return`{${e.join(`;`)}}`}applyNumericConstraints(t,n,r){for(let i of Object.values(this.innerTree))if(Array.isArray(i))for(let a of i){let i=e.deserializeValue(a.data);if(typeof i==`number`){let o=e.clampValue(i,t,n,r);a.data=e.serializeValue(o)}}}static serializeValue(e){return typeof e==`boolean`||typeof e==`number`||typeof e==`string`?e:typeof e==`object`&&e?JSON.stringify(e):String(e)}static deserializeValue(e){if(typeof e==`boolean`||typeof e==`number`||typeof e!=`string`)return e;if(e.startsWith(`{`)||e.startsWith(`[`))try{return JSON.parse(e)}catch{return e}let t=Number(e);return Number.isFinite(t)&&String(t)===e?t:e===`true`||e!==`false`&&e}static hasValidValue(e){return e==null?!1:typeof e==`string`||!(Array.isArray(e)&&e.length===0||typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0)}static isNumericInput(e){return e.paramType===`Number`||e.paramType===`Integer`}static processValues(t,n){return t.map(t=>e.isNumericInput(n)&&typeof t==`number`?e.clampValue(t,n.minimum,n.maximum,n.nickname||`unnamed`):t).filter(e=>e!=null)}static clampValue(e,t,n,r){let i=e;return t!=null&&i<t&&(p().warn(`${r}: ${e} below min ${t}, clamping`),i=t),n!=null&&i>n&&(p().warn(`${r}: ${e} above max ${n}, clamping`),i=n),i}};export{m as ComputeServerStats,pe as GrasshopperClient,Te as GrasshopperResponseProcessor,E as SolveScheduler,$e as TreeBuilder,d as downloadFileData,l as extractFilesFromComputeResponse,Q as fetchDefinitionIO,qe as fetchParsedDefinitionIO,T as hashDefinition,ue as hashSolveInput,s as isDefinitionRef,Qe as normalizeUISchemaCasing,Ve as processInput,Je as readSchemaResults,v as solveGrasshopperDefinition,S as stableStringify};
|
|
1
|
+
import{C as e,S as t,_ as n,b as r,c as i,f as a,g as o,l as s,m as c,o as l,p as u,r as d,s as f,t as p,u as ee,v as m}from"./core-PfYDuaFq.js";var h=class n{serverUrl;apiKey;disposed=!1;activeMonitors=new Set;activeTimeouts=new Set;static DEFAULT_TIMEOUT_MS=5e3;static LIFECYCLE_TIMEOUT_MS=6e4;static MIN_MONITOR_INTERVAL_MS=100;constructor(e,t){this.serverUrl=o(e),this.apiKey=t}buildHeaders(){let e={"Content-Type":`application/json`};return this.apiKey&&(e.RhinoComputeKey=this.apiKey),e}fetchWithTimeout(e,t={},r=n.DEFAULT_TIMEOUT_MS){let i=new Headers(this.buildHeaders());t.headers&&new Headers(t.headers).forEach((e,t)=>{i.set(t,e)});let a={};i.forEach((e,t)=>{a[t]=e});let o={...t,headers:a};return r>0&&!o.signal&&(o.signal=AbortSignal.timeout(r)),fetch(e,o)}async isServerOnline(e=5e3){return(await this.probeServer(e)).online}async probeServer(e=5e3){this.ensureNotDisposed();let t=`${this.serverUrl}/`;try{let n=await this.fetchWithTimeout(t,{method:`GET`},e);return{online:n.ok,status:n.status}}catch(e){return r().debug(`[ComputeServerStats] Fetch error:`,e),{online:!1,error:e instanceof Error?`${e.name}: ${e.message}`:String(e)}}}async getActiveChildren(e={}){this.ensureNotDisposed();let{initialize:t=!0}=e,i=t?`${this.serverUrl}/activechildren`:`${this.serverUrl}/activechildren?initialize=false`,a=t?n.LIFECYCLE_TIMEOUT_MS:n.DEFAULT_TIMEOUT_MS;try{let e=await this.fetchWithTimeout(i,{},a);if(!e.ok)return r().warn(`[ComputeServerStats] Failed to fetch active children:`,e.status),null;let t=(await e.text()).trim();return/^\d+$/.test(t)?parseInt(t,10):(r().warn(`[ComputeServerStats] Invalid active children response:`,t),null)}catch(e){return r().warn(`[ComputeServerStats] Error fetching active children:`,e),null}}async getVersion(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/version`);if(!e.ok)return r().warn(`[ComputeServerStats] Failed to fetch version:`,e.status),null;let t=await e.text();try{let e=JSON.parse(t);return{rhino:e.rhino??``,compute:e.compute??``,git_sha:e.git_sha??null}}catch{return{rhino:t,compute:``,git_sha:null}}}catch(e){return r().warn(`[ComputeServerStats] Error fetching version:`,e),null}}async getInstalledPlugins(e=`gh`){this.ensureNotDisposed();try{let t=await this.fetchWithTimeout(`${this.serverUrl}/plugins/${e}/installed`);if(!t.ok)return r().warn(`[ComputeServerStats] Failed to fetch ${e} plugins:`,t.status),null;let n=await t.text();try{let e=JSON.parse(n);return e&&typeof e==`object`?e:null}catch{return null}}catch(t){return r().warn(`[ComputeServerStats] Error fetching ${e} plugins:`,t),null}}async getServerStats(){if(this.ensureNotDisposed(),!await this.isServerOnline())return{isOnline:!1};let[e,t]=await Promise.all([this.getVersion(),this.getActiveChildren({initialize:!1})]);return{isOnline:!0,...e&&{version:e},...t!==null&&{activeChildren:t}}}async purgeCache(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/cache/purge`,{method:`POST`});if(!e.ok)return r().warn(`[ComputeServerStats] Failed to purge cache:`,e.status),null;let t=await e.text();try{let e=JSON.parse(t);return typeof e.purged==`number`?e.purged:null}catch{return null}}catch(e){return r().warn(`[ComputeServerStats] Error purging cache:`,e),null}}async purgeAllChildren(){this.ensureNotDisposed();let e=await this.getActiveChildren({initialize:!1});if(e===null)return r().warn(`[ComputeServerStats] purgeAllChildren: could not read child count`),null;if(e===0)return{totalPurged:0,calls:0,children:0,confident:!0};let t=e*2,n=0;for(let e=0;e<t;e++){let e=await this.purgeCache();e!==null&&(n+=e)}return{totalPurged:n,calls:t,children:e,confident:e===1}}async getServerTime(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/servertime`);if(!e.ok)return r().warn(`[ComputeServerStats] Failed to fetch server time:`,e.status),null;let t=(await e.text()).trim().replace(/^"|"$/g,``),n=new Date(t);return isNaN(n.getTime())?null:n}catch(e){return r().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 r().warn(`[ComputeServerStats] Failed to fetch idle span:`,e.status),null;let t=parseFloat((await e.text()).trim());return isNaN(t)?null:t}catch(e){return r().warn(`[ComputeServerStats] Error fetching idle span:`,e),null}}async launchChildren(){return this.postJson(`/launch-children`)}async launchChild(e){let t=e===void 0?`/launch-child`:`/launch-child?port=${e}`;return this.postJson(t)}async shutdownChildren(e){let t=e===void 0?`/shutdown-children`:`/shutdown-children?port=${e}`;return this.postJson(t)}async recycleChildren(e){let t=e===void 0?`/recycle-children`:`/recycle-children?port=${e}`;return this.postJson(t)}async postJson(e){this.ensureNotDisposed();try{let t=await this.fetchWithTimeout(`${this.serverUrl}${e}`,{method:`POST`},n.LIFECYCLE_TIMEOUT_MS);if(!t.ok)return r().warn(`[ComputeServerStats] POST ${e} failed:`,t.status),null;let i=await t.text();try{return JSON.parse(i)}catch{return null}}catch(t){return r().warn(`[ComputeServerStats] Error on POST ${e}:`,t),null}}monitor(i,a=5e3){if(this.ensureNotDisposed(),!Number.isFinite(a)||a<n.MIN_MONITOR_INTERVAL_MS)throw new t(`monitor() intervalMs must be a finite number >= ${n.MIN_MONITOR_INTERVAL_MS}ms, got ${a}. Sub-${n.MIN_MONITOR_INTERVAL_MS}ms polling would hot-loop the server.`,e.INVALID_CONFIG,{context:{intervalMs:a}});let o=!0,s=null;r().info(`🔄 Starting server stats monitoring every ${a}ms`);let c=async()=>{if(s!==null&&(this.activeTimeouts.delete(s),s=null),!(!o||this.disposed)){try{let e=await this.getServerStats();if(!o||this.disposed)return;try{i(e)}catch(e){r().error(`[ComputeServerStats] Monitor callback threw:`,e)}}catch(e){!o||this.disposed?r().debug(`[ComputeServerStats] Monitor poll cancelled during shutdown:`,e):r().error(`[ComputeServerStats] Failed to fetch stats during monitor:`,e)}o&&!this.disposed&&(s=setTimeout(()=>void c(),a),this.activeTimeouts.add(s))}},l=()=>{o=!1,s!==null&&(clearTimeout(s),this.activeTimeouts.delete(s),s=null),this.activeMonitors.delete(l)};return this.activeMonitors.add(l),c(),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 t(`ComputeServerStats has been disposed and cannot be used`,e.INVALID_STATE,{context:{disposed:this.disposed}})}};const g=new Set;function te(){if(typeof window>`u`||globalThis.process?.versions?.node!=null)return!1;let e=globalThis.navigator,t=typeof e?.userAgent==`string`?e.userAgent:``;return!/jsdom/i.test(t)}function _(e,t){t||te()&&!g.has(e)&&(g.add(e),r().warn(`Warning: ${e} is running on the client side. For better performance and security, consider running this on the server side.`))}const ne={definition_not_cached:e.DEFINITION_NOT_CACHED};function re(e){return{...e,serverErrorCodes:{...ne,...e.serverErrorCodes}}}function ie(n){return n instanceof t?n.code===e.DEFINITION_NOT_CACHED||n.message.includes(`Unable to load grasshopper definition`):!1}function ae(e,t){if(!t)return;let n=m(e,`values`);if(!Array.isArray(n)||n.length===0)return;let i=[];for(let e of n){let t=m(e,`innerTree`);(!t||Object.keys(t).length===0)&&i.push(m(e,`paramName`)??`<unnamed>`)}if(i.length===0)return;let a=i.length===n.length?`all`:`${i.length}/${n.length}`;r().warn(`Solve returned empty output(s) (${a}): ${i.join(`, `)}. These parameters produced no data — check the definition's inputs and the branch feeding each.`)}async function v(e,t,n){_(`solveGrasshopperDefinition`,n.suppressBrowserWarning);let{response:r}=await b(x(await y(t),e),n);return r}async function oe(e,t,n){return _(`solveGrasshopperDefinitionWithCacheKey`,n.suppressBrowserWarning),b(x(await y(t),e),n)}async function se(e,t,n,r){_(`solveByCacheKey`,r.suppressBrowserWarning);let i={algo:null,pointer:t,values:e};try{return{...await b(i,r),missed:!1}}catch(t){if(!ie(t))throw t;return{...await b(x(await y(n),e),r),missed:!0}}}async function y(n){if(!l(n))return n;try{return await n.load()}catch(r){throw new t(`Failed to load definition bytes for ref '${n.key}'`,e.INVALID_INPUT,{context:{definitionKey:n.key},originalError:r instanceof Error?r:Error(String(r))})}}async function b(e,t){ce(e,t);let n=await f(`grasshopper`,e,re(t)),{pointer:r,algo:a,...o}=n,c=o,l=i(n);if(l!==void 0){let e=typeof a==`string`?a.length:0;s(c,Math.max(0,l-e))}return ae(c,t.debug),{response:c,cacheKey:typeof r==`string`?r:null}}function x(e,t){let n={algo:null,pointer:null,values:t};return e instanceof Uint8Array?n.algo=ee(e):/^https?:\/\//i.test(e)?n.pointer=e:n.algo=a(e)??u(e),n}function ce(e,t){t.cachesolve!=null&&(e.cachesolve=t.cachesolve),t.cacheerroredsolves!=null&&(e.cacheerroredsolves=t.cacheerroredsolves),t.modelunits!=null&&(e.modelunits=t.modelunits),t.angletolerance!=null&&(e.angletolerance=t.angletolerance),t.absolutetolerance!=null&&(e.absolutetolerance=t.absolutetolerance),t.dataversion!=null&&(e.dataversion=t.dataversion)}function S(e){let t=new WeakSet,n=e=>{if(e===void 0)return`undefined`;if(e===null)return`null`;if(typeof e==`number`)return Number.isFinite(e)?String(e):`null`;if(typeof e==`string`||typeof e==`boolean`)return JSON.stringify(e);if(typeof e==`bigint`)return`${e}n`;if(e instanceof Uint8Array)return`{"__u8":${e.length},"hash":"${T(e)}"}`;if(Array.isArray(e)){if(t.has(e))return`"[Circular]"`;t.add(e);let r=[];for(let t=0;t<e.length;t++)r.push(n(e[t]));return t.delete(e),`[${r.join(`,`)}]`}if(typeof e==`object`){if(t.has(e))return`"[Circular]"`;t.add(e);let r;return r=typeof e.toJSON==`function`?n(e.toJSON()):e instanceof Map?`{"__map":[${[...e.entries()].map(([e,t])=>`[${n(e)},${n(t)}]`).sort().join(`,`)}]}`:e instanceof Set?`{"__set":[${[...e.values()].map(n).sort().join(`,`)}]}`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${n(e[t])}`).join(`,`)}}`,t.delete(e),r}return`null`};return n(e)}function C(e,t){let n=2166136261;for(let r=0;r<e;r++)n^=t(r),n=n+((n<<1)+(n<<4)+(n<<7)+(n<<8)+(n<<24))>>>0;return n.toString(16).padStart(8,`0`)}function w(e){return C(e.length,t=>e.charCodeAt(t))}function T(e){return C(e.length,t=>e[t])}function le(e,t){return E(D(e),t)}function E(e,t){let n=S(t);return`${e}|t:${n.length}:${w(n)}`}function D(e){return l(e)?`r:${e.key}`:typeof e==`string`?`s:${e.length}:${w(e)}`:`u8:${e.length}:${T(e)}`}function ue(e){return typeof e!=`string`||!/^https?:\/\//i.test(e)}function de(e){try{return JSON.stringify(e)?.length??0}catch{return 0}}var O=class{executor;baseConfig;mode;maxConcurrent;maxQueueDepth;queueWaitMs;timeoutMs;retry;cacheEnabled;cacheMaxBytes;cacheTtl;cacheErroredSolves;cache=new Map;cacheBytes=0;cacheHits=0;cacheMisses=0;cacheEvictions=0;cacheKeyExecutor;reuseServerDefinitionCache;serverCacheKeys=new Map;onStart;onSettle;onSuperseded;subscribers=new Set;inFlight=new Set;pendingForLatestWins=null;fifoQueue=[];_lastResult=null;_lastError=null;_lastDurationMs=null;solveSeq=0;lastStateSeq=0;disposed=!1;constructor(e,t,n={},r){this.executor=e,this.cacheKeyExecutor=r,this.baseConfig=t,this.mode=n.mode??`latest-wins`,this.maxConcurrent=Math.max(1,n.maxConcurrent??(this.mode===`parallel`?4:1)),this.maxQueueDepth=n.maxQueueDepth!==void 0&&n.maxQueueDepth>0?Math.floor(n.maxQueueDepth):void 0,this.queueWaitMs=n.queueWaitMs!==void 0&&n.queueWaitMs>0?n.queueWaitMs:void 0,this.timeoutMs=n.timeoutMs,this.retry=n.retry;let i=n.cache,a=typeof i==`object`?i:null;this.cacheMaxBytes=Math.max(0,a?.maxBytes??0),this.cacheEnabled=this.cacheMaxBytes>0,this.cacheTtl=a?.ttlMs??0,this.cacheErroredSolves=a?.cacheErroredSolves??!0,this.reuseServerDefinitionCache=!!r&&(n.reuseServerDefinitionCache??!0),this.onStart=n.onStart,this.onSettle=n.onSettle,this.onSuperseded=n.onSuperseded}get isSolving(){return this.inFlight.size>0}get hasPending(){return this.pendingForLatestWins!==null||this.fifoQueue.length>0}get inFlightCount(){return this.inFlight.size}get queueDepth(){return this.fifoQueue.length+ +!!this.pendingForLatestWins}get lastResult(){return this._lastResult}get lastError(){return this._lastError}get lastDurationMs(){return this._lastDurationMs}setMaxConcurrent(e){let t=Math.max(1,Math.floor(e));if(t===this.maxConcurrent)return;let n=t>this.maxConcurrent;this.maxConcurrent=t,n&&this.drainNext()}getMaxConcurrent(){return this.maxConcurrent}subscribe(e){return this.subscribers.add(e),()=>this.subscribers.delete(e)}notify(){for(let e of this.subscribers)try{e()}catch(e){r().error(`[SolveScheduler] subscriber threw:`,e)}}solve(n,r,i){if(this.disposed)return Promise.reject(new t(`SolveScheduler has been disposed and cannot be used`,e.INVALID_STATE));let a=D(n),o=E(a,r),s=++this.solveSeq,c={key:o,enqueuedAt:Date.now(),startedAt:null};if(i?.signal?.aborted)return Promise.reject(this.makeAbortError(c));if(this.cacheEnabled){let e=this.readCache(o);if(e){this.mode===`latest-wins`&&this.supersedeCurrent();let t={status:`success`,response:e,durationMs:0,fromCache:!0};return this.writeLastState(s,{result:e,durationMs:0}),this.runHook(this.onStart,c),this.runHook(this.onSettle,c,t),this.notify(),Promise.resolve(e)}}return new Promise((e,t)=>{let o={definition:n,dataTree:r,definitionHash:a,ctx:c,seq:s,resolve:e,reject:t,externalSignal:i?.signal};o.externalSignal&&(o.queuedAbortHandler=()=>this.abortQueuedItem(o),o.externalSignal.addEventListener(`abort`,o.queuedAbortHandler,{once:!0})),this.enqueue(o)})}writeLastState(e,t){return e<this.lastStateSeq?!1:(this.lastStateSeq=e,`result`in t?(this._lastResult=t.result,this._lastError=null):this._lastError=t.error,this._lastDurationMs=t.durationMs,!0)}supersedeCurrent(){this.pendingForLatestWins&&=(this.supersede(this.pendingForLatestWins),null);for(let e of this.inFlight)this.supersede(e),e.controller.abort()}abortQueuedItem(e){this.pendingForLatestWins===e&&(this.pendingForLatestWins=null);let t=this.fifoQueue.indexOf(e);t>=0&&this.fifoQueue.splice(t,1),this.rejectAsAborted(e),this.notify()}shedAsQueueFull(n){let r=new t(`Solve queue is full; request rejected (backpressure)`,e.QUEUE_FULL,{statusCode:503,context:{key:n.ctx.key,queueDepth:this.fifoQueue.length,maxQueueDepth:this.maxQueueDepth}});this.settleError(n,r)&&this.runHook(this.onSettle,n.ctx,{status:`error`,error:r,durationMs:0}),this.notify()}armQueueWaitTimer(n){if(this.queueWaitMs===void 0)return;let r=this.queueWaitMs;n.queueWaitTimer=setTimeout(()=>{if(n.settled)return;let i=this.fifoQueue.indexOf(n);i>=0&&this.fifoQueue.splice(i,1);let a=new t(`Solve waited longer than ${r}ms in queue; rejected (backpressure)`,e.QUEUE_TIMEOUT,{statusCode:503,context:{key:n.ctx.key,waitedMs:Date.now()-n.ctx.enqueuedAt,queueWaitMs:r}});this.settleError(n,a)&&this.runHook(this.onSettle,n.ctx,{status:`error`,error:a,durationMs:0}),this.notify()},r)}clearQueueWaitTimer(e){e.queueWaitTimer!==void 0&&(clearTimeout(e.queueWaitTimer),e.queueWaitTimer=void 0)}enqueue(e){switch(this.mode){case`latest-wins`:this.supersedeCurrent(),this.inFlight.size===0?this.execute(e):this.pendingForLatestWins=e;break;case`queue`:case`parallel`:this.inFlight.size<this.maxConcurrent?this.execute(e):this.maxQueueDepth!==void 0&&this.fifoQueue.length>=this.maxQueueDepth?this.shedAsQueueFull(e):(this.armQueueWaitTimer(e),this.fifoQueue.push(e))}this.notify()}async execute(e){let t=new AbortController,n=e;n.controller=t,this.inFlight.add(n),e.ctx.startedAt=Date.now(),this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e);let r=()=>t.abort();e.externalSignal?.addEventListener(`abort`,r,{once:!0}),this.runHook(this.onStart,e.ctx),this.notify();let i=performance.now();try{let n={...this.baseConfig,signal:t.signal,...this.timeoutMs!==void 0&&{timeoutMs:this.timeoutMs},...this.retry!==void 0&&{retry:this.retry}},{response:r,definitionReuploaded:a}=await this.runExecutor(e.definition,e.dataTree,e.definitionHash,n),o=performance.now()-i;if(this.cacheEnabled&&this.writeCache(e.ctx.key,r),!this.settleSuccess(e,r))return;this.writeLastState(e.seq,{result:r,durationMs:o}),this.runHook(this.onSettle,e.ctx,{status:`success`,response:r,durationMs:o,fromCache:!1,definitionReuploaded:a})}catch(t){let r=performance.now()-i,a=this.normalizeExecutionError(t,n);this.writeLastState(e.seq,{error:a,durationMs:r}),this.settleError(e,a)&&this.runHook(this.onSettle,e.ctx,{status:`error`,error:a,durationMs:r})}finally{e.externalSignal?.removeEventListener(`abort`,r),this.inFlight.delete(n),this.drainNext(),this.notify()}}async runExecutor(e,t,n,r){if(!this.cacheKeyExecutor||!this.reuseServerDefinitionCache||!ue(e))return{response:await this.executor(e,t,r)};let i=n,a=this.serverCacheKeys.get(i)??null,o=await this.cacheKeyExecutor(e,t,a,r);if(o.cacheKey)for(this.serverCacheKeys.delete(i),this.serverCacheKeys.set(i,o.cacheKey);this.serverCacheKeys.size>100;){let e=this.serverCacheKeys.keys().next().value;if(e===void 0)break;this.serverCacheKeys.delete(e)}else this.serverCacheKeys.delete(i);return{response:o.response,definitionReuploaded:o.missed}}drainNext(){if(!this.disposed){if(this.mode===`latest-wins`){if(this.pendingForLatestWins&&this.inFlight.size===0){let e=this.pendingForLatestWins;this.pendingForLatestWins=null,this.execute(e)}return}for(;this.fifoQueue.length>0&&this.inFlight.size<this.maxConcurrent;){let e=this.fifoQueue.shift();this.execute(e)}}}supersede(n){let r=new t(`Superseded by newer solve`,e.SUPERSEDED,{context:{key:n.ctx.key,enqueuedAt:n.ctx.enqueuedAt}});this.settleError(n,r)&&this.runHook(this.onSuperseded,n.ctx)}makeAbortError(n){return new t(`Request aborted by caller`,e.ABORTED,{context:{key:n.key,enqueuedAt:n.enqueuedAt}})}settleError(e,t){return!e.settled&&(e.settled={error:t},this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e),e.reject(t),!0)}settleSuccess(e,t){return!e.settled&&(e.settled={ok:!0},this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e),e.resolve(t),!0)}removeQueuedAbortHandler(e){e.queuedAbortHandler&&e.externalSignal&&e.externalSignal.removeEventListener(`abort`,e.queuedAbortHandler),e.queuedAbortHandler=void 0}isAbortLikeError(e){if(e instanceof Error){if(e.name===`AbortError`)return!0;if(typeof DOMException<`u`&&e instanceof DOMException)return e.name===`AbortError`}return!1}normalizeExecutionError(n,r){return r.settled&&`error`in r.settled?r.settled.error:n instanceof t?n:this.isAbortLikeError(n)?this.makeAbortError(r.ctx):new t(n instanceof Error?n.message:String(n),e.UNKNOWN_ERROR,{originalError:n instanceof Error?n:Error(String(n))})}cancelAll(){for(this.pendingForLatestWins&&=(this.rejectAsAborted(this.pendingForLatestWins),null);this.fifoQueue.length>0;){let e=this.fifoQueue.shift();this.rejectAsAborted(e)}for(let e of this.inFlight){let t=this.makeAbortError(e.ctx);this.settleError(e,t)&&this.runHook(this.onSettle,e.ctx,{status:`error`,error:t,durationMs:e.ctx.startedAt?Date.now()-e.ctx.startedAt:0}),e.controller.abort()}this.notify()}rejectAsAborted(e){let t=this.makeAbortError(e.ctx);this.settleError(e,t)&&this.runHook(this.onSettle,e.ctx,{status:`error`,error:t,durationMs:0})}readCache(e){if(!this.cacheEnabled)return null;let t=this.cache.get(e);return t?this.cacheTtl>0&&Date.now()-t.insertedAt>this.cacheTtl?(this.dropCacheEntry(e),this.cacheMisses+=1,null):(this.cache.delete(e),this.cache.set(e,t),this.cacheHits+=1,t.response):(this.cacheMisses+=1,null)}writeCache(e,t){if(!this.cacheEnabled)return;let n=m(t,`errors`);if(!this.cacheErroredSolves&&Array.isArray(n)&&n.length>0)return;let r=i(t)??de(t);if(!(r>this.cacheMaxBytes))for(this.dropCacheEntry(e),this.cache.set(e,{response:t,insertedAt:Date.now(),sizeBytes:r}),this.cacheBytes+=r;this.cacheBytes>this.cacheMaxBytes&&this.cache.size>0;){let e=this.cache.keys().next().value;if(e===void 0)break;this.dropCacheEntry(e),this.cacheEvictions+=1}}dropCacheEntry(e){let t=this.cache.get(e);t&&(this.cache.delete(e),this.cacheBytes-=t.sizeBytes)}clearCache(){this.cache.clear(),this.cacheBytes=0}cacheStats(){return{entries:this.cache.size,bytes:this.cacheBytes,hits:this.cacheHits,misses:this.cacheMisses,evictions:this.cacheEvictions}}dispose(){this.disposed||(this.disposed=!0,this.cancelAll(),this.subscribers.clear(),this.clearCache())}runHook(e,...t){if(e)try{e(...t)}catch(e){r().error(`[SolveScheduler] hook threw:`,e)}}};function k(e){return l(e)?`ref:${e.key}`:typeof e==`string`&&e.length<200?e:`...content...`}function fe(e){return Array.isArray(e)?e.map(e=>{let t=0,n=0,r=m(e,`innerTree`);if(r&&typeof r==`object`){for(let e of Object.values(r))if(Array.isArray(e)){t+=e.length;for(let t of e){let e=t?.data;typeof e==`string`&&(n+=e.length)}}}return{param:m(e,`paramName`)??`<unnamed>`,items:t,bytes:n}}):[]}var pe=class n{config;serverStats;disposed=!1;static CREATE_PROBE_TIMEOUT_MS=2e3;constructor(e){this.config=this.normalizeComputeConfig(e),this.serverStats=new h(this.config.serverUrl,this.config.apiKey)}static async create(r){let i=new n(r),a=Math.max(1,(r.retry?.attempts??2)+1),o=r.retry?.baseDelayMs??250,s=r.retry?.maxDelayMs??1e3,l,u=null,d=0;for(let e=0;e<a;e++){if(d=e+1,l=await i.serverStats.probeServer(n.CREATE_PROBE_TIMEOUT_MS),l.online)return i;if(u=c(l),u&&!u.retryable)break;if(e<a-1){let t=Math.min(o*2**e,s);await new Promise(e=>setTimeout(e,t))}}await i.dispose();let f=l?.status,p=u?`Rhino Compute server is not available. ${u.summary}`:`Rhino Compute server is not online`;throw new t(p,e.NETWORK_ERROR,{...f!==void 0&&{statusCode:f},context:{serverUrl:i.config.serverUrl,attempts:d,maxAttempts:a,...u&&{probeVerdict:u.verdict,probeRetryable:u.retryable},...f!==void 0&&{lastProbeStatus:f},...l?.error!==void 0&&{lastProbeError:l.error}}})}getConfig(){return this.ensureNotDisposed(),{...this.config}}async getIO(e){return this.ensureNotDisposed(),Je(e,this.config)}async getRawIO(e){return this.ensureNotDisposed(),Q(e,this.config)}async solve(n,i,a){this.ensureNotDisposed();try{if(typeof n==`string`&&!n?.trim())throw new t(`Definition URL/content is required`,e.INVALID_INPUT,{context:{receivedUrl:n}});if(n instanceof Uint8Array&&n.length===0)throw new t(`Definition content is empty`,e.INVALID_INPUT);if(l(n)&&!n.key.trim())throw new t(`DefinitionRef key is empty`,e.INVALID_INPUT);let r=await v(i,n,{...this.config,...a?.signal!==void 0&&{signal:a.signal},...a?.timeoutMs!==void 0&&{timeoutMs:a.timeoutMs},...a?.retry!==void 0&&{retry:a.retry}}),o=m(r,`errors`);if(Array.isArray(o)&&o.length>0)throw new t(o.map(String).join(`; `)||`Computation failed`,e.COMPUTATION_ERROR,{context:{definition:k(n),inputSummary:fe(i),errors:o,warnings:m(r,`warnings`),values:r.values}});return r}catch(a){throw this.config.debug&&r().error(`Compute failed:`,a),a instanceof t?a:new t(a instanceof Error?a.message:String(a),e.COMPUTATION_ERROR,{context:{definition:k(n),inputSummary:fe(i)},originalError:a instanceof Error?a:Error(String(a))})}}createScheduler(e){return this.ensureNotDisposed(),new O((e,t,n)=>v(t,e,n),this.config,e,(e,t,n,r)=>n===null?oe(t,e,r).then(e=>({...e,missed:!1})):se(t,n,e,r))}async dispose(){this.disposed||(this.disposed=!0,await this.serverStats.dispose())}ensureNotDisposed(){if(this.disposed)throw new t(`GrasshopperClient has been disposed and cannot be used`,e.INVALID_STATE)}normalizeComputeConfig(e){return{...e,serverUrl:o(e.serverUrl),apiKey:e.apiKey,authToken:e.authToken,debug:e.debug??!1,suppressBrowserWarning:e.suppressBrowserWarning}}};const A=new Map;function me(e,t){A.set(e,t)}me(`Rhino.Geometry.Point3d`,(e,t)=>{let n=t;return!n||typeof n.X!=`number`?null:new e.Point([n.X,n.Y,n.Z])}),me(`Rhino.Geometry.Line`,(e,t)=>{let n=t;return!n||!n.From||!n.To?null:new e.Line([n.From.X,n.From.Y,n.From.Z],[n.To.X,n.To.Y,n.To.Z])});function he(e){if(A.has(e))return A.get(e);for(let[t,n]of A)if(e.startsWith(t))return n}function ge(e){return!!(e&&typeof e==`object`&&typeof e.data==`string`)}function j(e,t){return{__decodeError:!0,type:e,raw:t}}function _e(e,t,n){let i=he(t),a=!1;if(i)try{let t=i(n,e);if(t!=null)return t}catch(e){r().warn(`Failed to decode Rhino type ${t}:`,e),a=!0}try{if(ge(e))return n.CommonObject.decode(e)}catch(n){return r().warn(`Failed to decode ${t} with CommonObject:`,n),j(t,e)}return a?j(t,e):e}function ve(e){let t=new WeakSet,n=e=>{if(!e||typeof e!=`object`||t.has(e))return;t.add(e);let r=e.delete;if(typeof r==`function`){let t=e.isDeleted;(typeof t!=`function`||!t.call(e))&&r.call(e);return}if(Array.isArray(e)){for(let t of e)n(t);return}let i=Object.getPrototypeOf(e);if(i===Object.prototype||i===null)for(let t of Object.values(e))n(t)};n(e)}const M={STRING:`System.String`,INT:`System.Int32`,DOUBLE:`System.Double`,BOOL:`System.Boolean`},ye=[`WebDisplay`];function N(e){return ye.some(t=>e.includes(t))}function be(e){if(typeof e!=`string`)return e;let t=e.trim();if(!(t.startsWith(`{`)||t.startsWith(`[`)||t.startsWith(`"`)))return e;try{let e=JSON.parse(t);if(typeof e==`string`)try{return JSON.parse(e)}catch{return e}return e}catch{return e}}function xe(e,t,n){switch(t){case M.STRING:return typeof e==`string`?e.replace(/^"(.*)"$/,`$1`):e;case M.INT:return Number.parseInt(e,10);case M.DOUBLE:return Number.parseFloat(e);case M.BOOL:return String(e).toLowerCase()===`true`;default:return n&&t.startsWith(`Rhino.Geometry.`)?_e(e,t,n):e}}const P=new WeakMap;function F(e){if(P.has(e))return P.get(e);let t=be(e.data);return P.set(e,t),t}function I(e,t,n,r){return typeof e.data==`string`?xe(n?F(e):e.data,t,r):e.data}function Se(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.fileName==`string`&&typeof t.fileType==`string`&&`data`in t&&typeof t.isBase64Encoded==`boolean`&&typeof t.subFolder==`string`}function L(e){let t=m(e,`values`);return Array.isArray(t)?t:[]}function R(e){return typeof e.type==`string`?e.type:``}function z(e,t){if(!(!e||typeof e!=`object`)){for(let n of Object.values(e))if(Array.isArray(n))for(let e of n)e&&typeof e==`object`&&t(e)}}function Ce(e,t=!1,n={}){let{parseValues:r=!0,rhino:i,stringOnly:a=!1}=n,o={},s=new Set;for(let n of L(e)){let e=m(n,`paramName`);z(m(n,`innerTree`),n=>{let c=R(n);if(N(c)||a&&c!==M.STRING)return;let l=t?n.id:e;if(!l)return;let u=I(n,c,r,i);l in o?s.has(l)?o[l].push(u):(o[l]=[o[l],u],s.add(l)):o[l]=u})}return{values:o,dispose:()=>ve(o)}}function we(e){let t=[];for(let n of L(e))z(m(n,`innerTree`),e=>{if(!R(e).includes(`FileData`))return;let n=F(e);Se(n)&&t.push(n)});return t}function Te(e,t,n={}){let{parseValues:r=!0,rhino:i,stringOnly:a=!1}=n;for(let n of L(e)){let e=m(n,`innerTree`),o=!1;if(`byName`in t){if(m(n,`paramName`)!==t.byName)continue;o=!0}let s=[];if(z(e,e=>{if(`byId`in t){if(e.id!==t.byId)return;o=!0}let n=R(e);N(n)||a&&n!==M.STRING||s.push(I(e,n,r,i))}),o)return s.length===0?void 0:s.length===1?s[0]:s}}var Ee=class{response;debug;constructor(e,t=!1){this.response=e,this.debug=t}getValues(e=!1,t={}){return Ce(this.response,e,t)}getValue(e,t){return Te(this.response,e,t)}getFileData(){return we(this.response)}async getAndDownloadFiles(e,t){let n=this.getFileData();await p(n,e,t)}};const B=/^\{(-?\d+(?:;-?\d+)*)?\}$/;function V(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.entries(e);return t.length>0&&t.every(([e,t])=>B.test(e)&&Array.isArray(t))}function H(e,t,n){let r=Number(e.toFixed(t));return Math.abs(e-r)<n?r:e}function De(e,t){if(!Number.isFinite(e)||e===0)return .1;let n=Math.abs(e);if(n>=1){let n=String(e).split(`.`)[1];if(n&&n.length>0){let e=Math.min(n.length,12),r=10**-e,i=Number(r.toFixed(e));return Math.abs(i-r)<t?i:r}return 1}let r=String(e),i=r.toLowerCase().match(/e(-?\d+)/);if(i){let e=Number(i[1]);if(e<0||r.toLowerCase().includes(`e-`)){let n=Math.abs(e),r=10**-n,i=Number(r.toFixed(n));return Math.abs(i-r)<t?i:r}return .1}let a=n.toFixed(12).replace(/0+$/,``),o=Math.min((a.split(`.`)[1]||``).length,12);if(o===0)return .1;let s=10**-o,c=Number(s.toFixed(o));return Math.abs(c-s)<t?c:s}function U(e){return typeof e.stepSize==`number`&&Number.isFinite(e.stepSize)&&e.stepSize>0?e.stepSize:void 0}function W(e,t,n){if(e==null)return e;if(Array.isArray(e)){let n=e.map(t).filter(e=>e!==null);return n.length>0?n:void 0}let r=t(e);return r===null?n?void 0:e:r}const G=e=>{if(typeof e==`number`)return Number.isFinite(e)?e:null;if(typeof e==`string`){let t=e.trim();if(t===``||/^[+-]?0[xbo]/i.test(t))return null;let n=Number(t);return Number.isFinite(n)?n:null}return null},K=e=>{if(typeof e==`boolean`)return e;if(typeof e==`string`){let t=e.trim().toLowerCase();if(t===`true`)return!0;if(t===`false`)return!1}return null},Oe=e=>typeof e==`string`?e.length>=2&&e.startsWith(`"`)&&e.endsWith(`"`)?e.slice(1,-1):e.startsWith(`"`)?e.slice(1):e:null,ke=e=>{if(typeof e==`string`){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)&&(t=t.slice(1,-1).trim()),t}return null};function q(e){return t=>{if(typeof t==`object`&&t)return t;if(typeof t==`string`&&t.trim()!==``)try{let n=JSON.parse(t);return typeof n==`object`&&n?n:(r().warn(`Parsed value for input ${e} is not an object`),null)}catch(n){return r().warn(`Failed to parse object value "${t}" for input ${e}`,n),null}return null}}function Ae(n,r=1e-8){let i=n.paramType===`Integer`,a=U(n);if(V(n.default))return{default:n.default,stepSize:a??(i?1:.1)};if(typeof n.default==`string`&&n.default.trim()!==``&&G(n.default)===null)throw new t(`Invalid numeric default "${n.default}" for input "${n.name||`unknown`}"`,e.VALIDATION_ERROR,{context:{inputName:n.name,default:n.default}});let o=W(n.default,G,!0);if(i)return Array.isArray(o)?o=o.map(e=>typeof e==`number`?Math.round(e):e):typeof o==`number`&&(o=Math.round(o)),{default:o,stepSize:a??1};let s=Array.isArray(o)?o[0]:o,c;typeof s==`number`&&Number.isFinite(s)&&s!==0?c=s:typeof n.minimum==`number`&&Number.isFinite(n.minimum)&&n.minimum!==0?c=n.minimum:typeof n.maximum==`number`&&Number.isFinite(n.maximum)&&n.maximum!==0&&(c=n.maximum);let l=a??(c===void 0?.1:De(c,r)),u=0,d=String(l),f=d.toLowerCase().match(/e(-?\d+)/);if(u=f?Math.abs(Number(f[1])):d.split(`.`)[1]?.length??0,u===0&&typeof s==`number`&&s!==0&&Math.abs(s)<1){let e=Math.ceil(-Math.log10(Math.abs(s)));Number.isFinite(e)&&e>0&&(u=e)}return u=Math.min(Math.max(u,0),12),Array.isArray(o)?o=o.map(e=>typeof e==`number`?H(e,u,r):e):typeof o==`number`&&(o=H(o,u,r)),{default:o,stepSize:l}}const je={types:[`Number`,`Integer`],parse(e,t){let{default:n,stepSize:r}=Ae(e);return{...t,paramType:e.paramType,minimum:e.minimum,maximum:e.maximum,atLeast:e.atLeast,atMost:e.atMost,stepSize:r,default:n}},fallback(e,t){let n=(e.atMost??1)>1,r=typeof e.minimum==`number`&&Number.isFinite(e.minimum)&&e.minimum>0?e.minimum:0;return{...t,paramType:e.paramType,minimum:e.minimum,maximum:e.maximum,atLeast:e.atLeast,atMost:e.atMost,stepSize:U(e)??(e.paramType===`Integer`?1:.1),default:n?[r]:r}}},Me={types:[`Boolean`],parse(n,r){if(V(n.default))return{...r,paramType:`Boolean`,default:n.default};let i=W(n.default,K,!1);if(i!=null&&typeof i!=`boolean`&&!Array.isArray(i))throw new t(`Invalid boolean default "${String(i)}" for input "${n.name||`unknown`}"`,e.VALIDATION_ERROR,{context:{inputName:n.name,default:n.default}});return{...r,paramType:`Boolean`,default:i}},fallback(e,t){let n=(e.atMost??1)>1;return{...t,paramType:`Boolean`,default:n?[!1]:!1}}},Ne={types:[`Text`],parse(e,t){let n=W(e.default,Oe,!1);return{...t,paramType:`Text`,default:n}},fallback(e,t){let n=(e.atMost??1)>1;return{...t,paramType:`Text`,default:n?[``]:``}}},Pe={types:[`ValueList`],parse(n,i,a){if(!n.values||typeof n.values!=`object`||Object.keys(n.values).length===0)throw t.missingValues(n.nickname||`unnamed`,`ValueList`);let o=n.default;if(n.default!==void 0&&n.default!==null){if(typeof n.default==`object`)throw new t(`ValueList input "${n.nickname||`unnamed`}" default is not a string-able value`,e.VALIDATION_ERROR,{context:{inputName:n.name,default:n.default}});let i=String(n.default).toLowerCase(),s=Object.keys(n.values).find(e=>e.toLowerCase()===i);if(s!==void 0)o=s;else{let t=`ValueList input "${n.nickname||`unnamed`}" default value "${n.default}" is not in available values`;r().warn(t),a?.({code:e.VALIDATION_ERROR,message:t})}}return{...i,paramType:`ValueList`,values:n.values,default:o}},fallback(e,t){return{...t,paramType:`ValueList`,values:e.values&&typeof e.values==`object`?e.values:{},default:void 0}}},J={types:[`Geometry`],parse(e,t){let n=W(e.default,q(e.nickname||`unnamed`),!0);return{...t,paramType:`Geometry`,default:n}},fallback(e,t){let n=(e.atMost??1)>1;return{...t,paramType:`Geometry`,default:n?[null]:null}}},Y=new Map([je,Me,Ne,Pe,J,{types:[`File`],parse(e,t){let n=W(e.default,q(e.nickname||`unnamed`),!0);return{...t,paramType:`File`,acceptedFormats:e.acceptedFormats,default:n}},fallback(e,t){let n=(e.atMost??1)>1;return{...t,paramType:`File`,default:n?[null]:null}}},{types:[`Color`],parse(e,t){let n=W(e.default,ke,!1);return{...t,paramType:`Color`,default:n}},fallback(e,t){let n=(e.atMost??1)>1;return{...t,paramType:`Color`,default:n?[`0, 0, 0`]:`0, 0, 0`}}}].flatMap(e=>e.types.map(t=>[t,e]))),Fe=J;function X(e){return m(e,`data`)}function Ie(e){return m(e,`type`)}const Le=new Set([`System.Double`,`System.Single`,`System.Decimal`,`System.Int32`,`System.Int64`]),Re=new Set([`System.Int32`,`System.Int64`]);function ze(e){if(typeof e.default!=`object`||e.default===null||Array.isArray(e.default))return{schema:e};if(!n(e.default,`innerTree`)){let t=`Input "${e.name??`unknown`}" default had an unrecognized shape (no innerTree key); the default was dropped.`;return r().warn(`Unexpected structure in input.default:`,e.default),{schema:{...e,default:null},warning:{code:`MALFORMED_DEFAULT`,message:t}}}let t=m(e.default,`innerTree`)??{};if(Object.keys(t).length===0)return{schema:{...e,default:void 0}};if(e.treeAccess||e.atMost&&e.atMost>1){let n={},i=[];for(let[a,o]of Object.entries(t)){if(!Array.isArray(o)){let t=`Input "${e.name??`unknown`}" default had a non-array innerTree branch ("${a}"); the default was dropped.`;return r().warn(`Unexpected structure in input.default innerTree:`,e.default),{schema:{...e,default:null},warning:{code:`MALFORMED_DEFAULT`,message:t}}}let t=[];for(let e of o){let n=X(e),r=Ie(e);if(r&&Le.has(r)){if(typeof n==`string`&&n.trim()===``)continue;let e=G(n);if(e===null){i.push(`"${String(n)}" (${r})`);continue}t.push(Re.has(r)?Math.round(e):e);continue}if(r===`System.Boolean`){let e=K(n);if(e===null){i.push(`"${String(n)}" (${r})`);continue}t.push(e);continue}if(typeof n==`string`&&r?.startsWith(`Rhino.Geometry`)){try{t.push(JSON.parse(n))}catch{t.push(n)}continue}t.push(n)}n[a]=t}let a;if(i.length>0){let t=`Input "${e.name??`unknown`}" default contained ${i.length} tree value(s) that could not be parsed and were dropped: ${i.join(`, `)}.`;r().warn(t),a={code:`MALFORMED_DEFAULT`,message:t}}return{schema:{...e,default:n},...a&&{warning:a}}}let i=[];for(let e of Object.values(t))Array.isArray(e)&&e.forEach(e=>{e&&typeof e==`object`&&n(e,`data`)&&i.push(X(e))});return i.length===0?{schema:{...e,default:void 0}}:i.length===1?{schema:{...e,default:i[0]}}:{schema:{...e,default:i}}}const Be=new Map([...Y.keys()].map(e=>[e.toLowerCase(),e]));function Ve(e){return Be.get(e?.toLowerCase())??e}function He(e){return Z(e).input}function Z(e){let n={description:e.description,name:e.name,nickname:e.nickname,treeAccess:e.treeAccess,groupName:e.groupName??void 0,id:e.id},i=Ve(e.paramType),a={...e,paramType:i},o;try{let{schema:t,warning:n}=ze(a);a=t,o=n&&{inputName:e.name||`unknown`,paramType:e.paramType,message:n.message,code:n.code}}catch(t){a={...a,default:null},o={inputName:e.name||`unknown`,paramType:e.paramType,message:`Input "${e.name??`unknown`}" default could not be normalized and was dropped: ${t instanceof Error?t.message:String(t)}`,code:`MALFORMED_DEFAULT`}}let s=Y.get(i),c=[],l=t=>c.push({inputName:e.name||`unknown`,paramType:e.paramType,message:t.message,code:t.code});try{if(!s)throw t.unknownParamType(i,e.name);let r=s.parse(a,n,l),u=o?[o,...c]:c;return{input:r,error:o,...u.length>0&&{errors:u}}}catch(l){if(l instanceof t){r().error(`Validation error for input ${e.name||`unknown`}:`,l.message);let t={inputName:e.name||`unknown`,paramType:e.paramType,message:l.message,code:l.code};return{input:(s??Fe).fallback(a,n),error:t,errors:[...o?[o]:[],...c,t]}}throw new t(l instanceof Error?l.message:String(l),`VALIDATION_ERROR`,{context:{paramName:e.name,paramType:i},originalError:l instanceof Error?l:Error(String(l))})}}function Ue(e){let t=[],n=[];for(let r of e){let{input:e,errors:i}=Z(r);t.push(e),i&&n.push(...i)}return{inputs:t,parseErrors:n}}function We(e){let t=m(e,`stepSize`);return{id:m(e,`id`)??``,name:m(e,`name`)??``,nickname:m(e,`nickname`)??null,description:m(e,`description`)??``,paramType:m(e,`paramType`)??``,treeAccess:m(e,`treeAccess`)??!1,minimum:m(e,`minimum`)??null,maximum:m(e,`maximum`)??null,atLeast:m(e,`atLeast`)??1,atMost:m(e,`atMost`)??1,stepSize:typeof t==`number`&&Number.isFinite(t)?t:void 0,default:m(e,`default`),values:m(e,`values`),acceptedFormats:m(e,`acceptedFormats`),groupName:m(e,`groupName`)??null}}function Ge(e){return{name:m(e,`name`)??``,nickname:m(e,`nickname`)??null,paramType:m(e,`paramType`)??``,id:m(e,`id`)??``}}async function Q(n,r){let i=x(n,[]),a={};if(i.algo&&(a.algo=i.algo),i.pointer&&(a.pointer=i.pointer),!a.algo&&!a.pointer)throw new t(`Definition must resolve to either a URL pointer or base64 algo`,e.INVALID_INPUT,{context:{definition:n}});let o=await f(`io`,a,re(r));if(!o||typeof o!=`object`)throw new t(`Invalid IO response structure`,e.INVALID_INPUT,{context:{response:o,definition:n}});let s=Ke(m(o,`warnings`)),c=Ke(m(o,`errors`)),l=m(o,`inputs`),u=m(o,`outputs`);return{inputs:Array.isArray(l)?l.map(We):[],outputs:Array.isArray(u)?u.map(Ge):[],...s&&{loadWarnings:s},...c&&{loadErrors:c}}}function Ke(e){if(!Array.isArray(e))return;let t=e.map(qe).filter(e=>e!==void 0);return t.length>0?t:void 0}function qe(e){if(e==null)return;let t;if(typeof e==`string`)t=e;else if(typeof e==`object`){let n=m(e,`message`);if(typeof n==`string`&&n.trim().length>0)t=n;else try{t=JSON.stringify(e)??String(e)}catch{t=String(e)}}else t=String(e);return t.trim().length>0?t:void 0}async function Je(e,t){_(`fetchParsedDefinitionIO`,t.suppressBrowserWarning);let{inputs:n,outputs:r,loadWarnings:i,loadErrors:a}=await Q(e,t),{inputs:o,parseErrors:s}=Ue(n);return{inputs:o,outputs:r,...s.length>0&&{parseErrors:s},...i&&{loadWarnings:i},...a&&{loadErrors:a}}}function Ye(e){return(Array.isArray(e)?e:[e]).map(e=>({schemas:m(e,`schemas`),error:m(e,`error`)}))}const Xe=new Set([`options`,`defaultOptions`,`values`]),Ze=e=>e>=`A`&&e<=`Z`;function Qe(e){if(e.length===0||!Ze(e[0]))return e;let t=0;for(;t<e.length&&Ze(e[t]);)t++;return t>1&&t<e.length&&t--,e.slice(0,t).toLowerCase()+e.slice(t)}function $e(e){return $(e)}function $(e){if(Array.isArray(e))return e.map($);if(typeof e!=`object`||!e)return e;let t={};for(let[n,r]of Object.entries(e)){let e=Qe(n);t[e]=Xe.has(e)?r:$(r)}return t}var et=class n{innerTree;paramName;constructor(e){this.paramName=e,this.innerTree={}}append(e,t){let r=n.formatPathString(e);this.innerTree[r]||(this.innerTree[r]=[]);let i=t.map(e=>({data:n.serializeValue(e)}));return this.innerTree[r].push(...i),this}appendSingle(e,t){return this.append(e,[t])}fromDataTreeDefault(e){this.innerTree={};for(let[t,r]of Object.entries(e)){if(!Array.isArray(r))continue;let e=n.parsePathString(t);this.append(e,r)}return this}appendFlat(e){let t=Array.isArray(e)?e:[e];return this.append([0],t)}flatten(){let e=[];for(let t of Object.values(this.innerTree))if(Array.isArray(t))for(let r of t)e.push(n.deserializeValue(r.data));return e}getPaths(){return Object.keys(this.innerTree)}getPath(e){let t=n.formatPathString(e),r=this.innerTree[t];if(r)return r.map(e=>n.deserializeValue(e.data))}toComputeFormat(){return{ParamName:this.paramName,InnerTree:this.innerTree}}getInnerTree(){return this.innerTree}getParamName(){return this.paramName}static fromInputParams(e){return e.filter(e=>n.hasValidValue(e.default)).map(e=>{let t=new n(e.nickname||`unnamed`),r=e.default;if(e.treeAccess&&V(r))t.fromDataTreeDefault(r),n.isNumericInput(e)&&t.applyNumericConstraints(e.minimum,e.maximum,e.nickname||`unnamed`);else{let i=Array.isArray(r)?r:[r],a=n.processValues(i,e);t.appendFlat(a)}return t.toComputeFormat()})}static fromInputParam(e){if(n.hasValidValue(e.default))return n.fromInputParams([e])[0]}static replaceTreeValue(e,t,r){let i=e.length>0&&e[0]instanceof n,a=n.buildFromValue(t,r);if(i){let n=e.slice(),r=n.findIndex(e=>e.getParamName()===t);return r===-1?n.push(a):n[r]=a,n}let o=e.slice(),s=a.toComputeFormat(),c=o.findIndex(e=>e.ParamName===t);return c===-1?o.push(s):o[c]=s,o}static buildFromValue(e,t){let r=new n(e);return V(t)?r.fromDataTreeDefault(t):r.appendFlat(t),r}static getTreeValue(e,t){let r=e.length>0&&e[0]instanceof n?n.readFromBuilders(e,t):n.readFromDataTrees(e,t);return r===null||r.length===0?null:r.length===1?r[0]:r}static readFromBuilders(e,t){let n=e.find(e=>e.getParamName()===t);return n?n.flatten():null}static readFromDataTrees(e,t){let r=e.find(e=>e.ParamName===t);if(!r?.InnerTree)return null;let i=Object.keys(r.InnerTree)[0];if(!i)return null;let a=r.InnerTree[i];return Array.isArray(a)?a.map(e=>e?.data===void 0?null:n.deserializeValue(e.data)):a?.data===void 0?a===void 0?null:[a]:[n.deserializeValue(a.data)]}static parsePathString(n){let r=n.match(B);if(!r)throw new t(`Invalid Grasshopper tree path: "${n}". Expected "{}", "{0}", or "{0;1;2}" (negative indices allowed, no empty segments).`,e.INVALID_INPUT,{context:{pathStr:n}});return r[1]?r[1].split(`;`).map(Number):[]}static formatPathString(e){return`{${e.join(`;`)}}`}applyNumericConstraints(e,t,r){for(let i of Object.values(this.innerTree))if(Array.isArray(i))for(let a of i){let i=n.deserializeValue(a.data);if(typeof i==`number`){let o=n.clampValue(i,e,t,r);a.data=n.serializeValue(o)}}}static serializeValue(e){return typeof e==`boolean`||typeof e==`number`||typeof e==`string`?e:typeof e==`object`&&e?JSON.stringify(e):String(e)}static deserializeValue(e){if(typeof e==`boolean`||typeof e==`number`||typeof e!=`string`)return e;if(e.startsWith(`{`)||e.startsWith(`[`))try{return JSON.parse(e)}catch{return e}let t=Number(e);return Number.isFinite(t)&&String(t)===e?t:e===`true`||e!==`false`&&e}static hasValidValue(e){return e==null?!1:typeof e==`string`||!(Array.isArray(e)&&e.length===0||typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0)}static isNumericInput(e){return e.paramType===`Number`||e.paramType===`Integer`}static processValues(e,t){return e.map(e=>n.isNumericInput(t)&&typeof e==`number`?n.clampValue(e,t.minimum,t.maximum,t.nickname||`unnamed`):e).filter(e=>e!=null)}static clampValue(e,t,n,i){let a=e;return t!=null&&a<t&&(r().warn(`${i}: ${e} below min ${t}, clamping`),a=t),n!=null&&a>n&&(r().warn(`${i}: ${e} above max ${n}, clamping`),a=n),a}};export{h as ComputeServerStats,pe as GrasshopperClient,Ee as GrasshopperResponseProcessor,O as SolveScheduler,et as TreeBuilder,p as downloadFileData,d as extractFilesFromComputeResponse,Q as fetchDefinitionIO,Je as fetchParsedDefinitionIO,D as hashDefinition,le as hashSolveInput,l as isDefinitionRef,$e as normalizeUISchemaCasing,He as processInput,Ye as readSchemaResults,v as solveGrasshopperDefinition,S as stableStringify};
|
|
2
2
|
//# sourceMappingURL=grasshopper.js.map
|