@selvajs/compute 5.0.0-beta.2 → 5.0.0-beta.4
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/dist/core-CFlbOj2M.js +3 -0
- package/dist/core-CFlbOj2M.js.map +1 -0
- package/dist/core-UUSszGkB.cjs +3 -0
- package/dist/core-UUSszGkB.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 +16 -4
- package/dist/grasshopper.d.ts +16 -4
- package/dist/grasshopper.js +1 -1
- package/dist/grasshopper.js.map +1 -1
- package/dist/{index-C5T6o4Fr.d.ts → index-cMvSohkf.d.cts} +28 -5
- package/dist/{index-C5T6o4Fr.d.cts → index-cMvSohkf.d.ts} +28 -5
- package/package.json +1 -1
- package/dist/core-DcBw277f.js +0 -3
- package/dist/core-DcBw277f.js.map +0 -1
- package/dist/core-XZk7EVP3.cjs +0 -3
- package/dist/core-XZk7EVP3.cjs.map +0 -1
package/dist/grasshopper.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { D as ComputeAuth, M as ComputeError, O as ComputeConfig, _ as SolveDefinition, j as ServerTiming, k as RetryPolicy, s as FileBaseInfo } from "./index-cMvSohkf.cjs";
|
|
2
2
|
//#region src/grasshopper/server/compute-server-stats.d.ts
|
|
3
3
|
interface ServerVersion {
|
|
4
4
|
rhino: string;
|
|
@@ -42,13 +42,18 @@ declare class ComputeServerStats {
|
|
|
42
42
|
private static readonly LIFECYCLE_TIMEOUT_MS;
|
|
43
43
|
/** Floor for `monitor()`'s `intervalMs` — anything lower hot-loops the server. */
|
|
44
44
|
private static readonly MIN_MONITOR_INTERVAL_MS;
|
|
45
|
+
/** Every control-plane answer is a count, a version or a short map. */
|
|
46
|
+
private static readonly MAX_BODY_BYTES;
|
|
45
47
|
/**
|
|
46
48
|
* @param serverUrl - Base URL of the Rhino Compute server with http:// or https:// scheme (e.g., 'http://localhost:6500')
|
|
47
49
|
* @param auth - An API key, or the same auth fields a solve's `ComputeConfig` carries
|
|
48
50
|
* (`apiKey`, `apiKeyHeader`, `authToken`, `headers`).
|
|
49
51
|
*/
|
|
50
52
|
constructor(serverUrl: string, auth?: string | ComputeAuth);
|
|
51
|
-
/**
|
|
53
|
+
/**
|
|
54
|
+
* Aborts after `timeoutMs` so a hung connection can't stall a probe or `monitor()`; `0` disables
|
|
55
|
+
* it. Redirects are not followed: fetch would carry the API key header to the target.
|
|
56
|
+
*/
|
|
52
57
|
private fetchWithTimeout;
|
|
53
58
|
/**
|
|
54
59
|
* The response body of `path`, or `null` (logged) on a non-2xx or a network
|
|
@@ -619,6 +624,8 @@ interface CacheOptions {
|
|
|
619
624
|
* fetch boundary — no re-serialization); a response without that hint
|
|
620
625
|
* (custom executor) is sized by a one-off `JSON.stringify`. A single
|
|
621
626
|
* response larger than the whole budget is served but never retained.
|
|
627
|
+
* Parsed, a response of many small items holds more heap than its wire size,
|
|
628
|
+
* so leave headroom.
|
|
622
629
|
*
|
|
623
630
|
* Required and must be > 0 — to disable caching, pass `cache: false`.
|
|
624
631
|
*/
|
|
@@ -789,13 +796,15 @@ export declare class SolveScheduler {
|
|
|
789
796
|
private readonly reuseServerDefinitionCache;
|
|
790
797
|
/** Definition hash → the server's cache key (`pointer`) for it. */
|
|
791
798
|
private readonly serverCacheKeys;
|
|
799
|
+
/** A string definition re-sent unchanged is compared with this, far cheaper than hashing it. */
|
|
800
|
+
private lastStringDefinition;
|
|
792
801
|
private readonly onStart?;
|
|
793
802
|
private readonly onSettle?;
|
|
794
803
|
private readonly onSuperseded?;
|
|
795
804
|
private readonly subscribers;
|
|
796
805
|
private readonly inFlight;
|
|
797
806
|
private pendingForLatestWins;
|
|
798
|
-
private readonly
|
|
807
|
+
private readonly fifo;
|
|
799
808
|
private _lastResult;
|
|
800
809
|
private _lastError;
|
|
801
810
|
private _lastDurationMs;
|
|
@@ -865,6 +874,7 @@ export declare class SolveScheduler {
|
|
|
865
874
|
private enqueue;
|
|
866
875
|
private execute;
|
|
867
876
|
private runExecutor;
|
|
877
|
+
private hashDefinitionMemo;
|
|
868
878
|
private drainNext;
|
|
869
879
|
private supersede;
|
|
870
880
|
private makeAbortError;
|
|
@@ -1140,13 +1150,15 @@ declare class GrasshopperResponseProcessor {
|
|
|
1140
1150
|
* The output is a cache key, so the invariant that matters is: two payloads
|
|
1141
1151
|
* that serialize differently on the wire must stringify differently here
|
|
1142
1152
|
* (false misses are harmless; false hits serve the wrong cached solve).
|
|
1153
|
+
* Non-JSON values get unquoted markers (`{u8:…}`, `[Circular]`) that no JSON
|
|
1154
|
+
* value stringifies to, so a plain object can't pose as one.
|
|
1143
1155
|
*/
|
|
1144
1156
|
export declare function stableStringify(value: unknown): string;
|
|
1145
1157
|
/** The scheduler's solve-cache key for a definition and its input tree. */
|
|
1146
1158
|
export declare function hashSolveInput(definition: SolveDefinition, dataTree: unknown): string;
|
|
1147
1159
|
/**
|
|
1148
1160
|
* A definition's identity, without its inputs. Strings and bytes are hashed over their full
|
|
1149
|
-
* content
|
|
1161
|
+
* content; a `DefinitionRef` uses its `key`.
|
|
1150
1162
|
*/
|
|
1151
1163
|
export declare function hashDefinition(definition: SolveDefinition): string;
|
|
1152
1164
|
//#endregion
|
package/dist/grasshopper.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { D as ComputeAuth, M as ComputeError, O as ComputeConfig, _ as SolveDefinition, j as ServerTiming, k as RetryPolicy, s as FileBaseInfo } from "./index-cMvSohkf.js";
|
|
2
2
|
//#region src/grasshopper/server/compute-server-stats.d.ts
|
|
3
3
|
interface ServerVersion {
|
|
4
4
|
rhino: string;
|
|
@@ -42,13 +42,18 @@ declare class ComputeServerStats {
|
|
|
42
42
|
private static readonly LIFECYCLE_TIMEOUT_MS;
|
|
43
43
|
/** Floor for `monitor()`'s `intervalMs` — anything lower hot-loops the server. */
|
|
44
44
|
private static readonly MIN_MONITOR_INTERVAL_MS;
|
|
45
|
+
/** Every control-plane answer is a count, a version or a short map. */
|
|
46
|
+
private static readonly MAX_BODY_BYTES;
|
|
45
47
|
/**
|
|
46
48
|
* @param serverUrl - Base URL of the Rhino Compute server with http:// or https:// scheme (e.g., 'http://localhost:6500')
|
|
47
49
|
* @param auth - An API key, or the same auth fields a solve's `ComputeConfig` carries
|
|
48
50
|
* (`apiKey`, `apiKeyHeader`, `authToken`, `headers`).
|
|
49
51
|
*/
|
|
50
52
|
constructor(serverUrl: string, auth?: string | ComputeAuth);
|
|
51
|
-
/**
|
|
53
|
+
/**
|
|
54
|
+
* Aborts after `timeoutMs` so a hung connection can't stall a probe or `monitor()`; `0` disables
|
|
55
|
+
* it. Redirects are not followed: fetch would carry the API key header to the target.
|
|
56
|
+
*/
|
|
52
57
|
private fetchWithTimeout;
|
|
53
58
|
/**
|
|
54
59
|
* The response body of `path`, or `null` (logged) on a non-2xx or a network
|
|
@@ -619,6 +624,8 @@ interface CacheOptions {
|
|
|
619
624
|
* fetch boundary — no re-serialization); a response without that hint
|
|
620
625
|
* (custom executor) is sized by a one-off `JSON.stringify`. A single
|
|
621
626
|
* response larger than the whole budget is served but never retained.
|
|
627
|
+
* Parsed, a response of many small items holds more heap than its wire size,
|
|
628
|
+
* so leave headroom.
|
|
622
629
|
*
|
|
623
630
|
* Required and must be > 0 — to disable caching, pass `cache: false`.
|
|
624
631
|
*/
|
|
@@ -789,13 +796,15 @@ export declare class SolveScheduler {
|
|
|
789
796
|
private readonly reuseServerDefinitionCache;
|
|
790
797
|
/** Definition hash → the server's cache key (`pointer`) for it. */
|
|
791
798
|
private readonly serverCacheKeys;
|
|
799
|
+
/** A string definition re-sent unchanged is compared with this, far cheaper than hashing it. */
|
|
800
|
+
private lastStringDefinition;
|
|
792
801
|
private readonly onStart?;
|
|
793
802
|
private readonly onSettle?;
|
|
794
803
|
private readonly onSuperseded?;
|
|
795
804
|
private readonly subscribers;
|
|
796
805
|
private readonly inFlight;
|
|
797
806
|
private pendingForLatestWins;
|
|
798
|
-
private readonly
|
|
807
|
+
private readonly fifo;
|
|
799
808
|
private _lastResult;
|
|
800
809
|
private _lastError;
|
|
801
810
|
private _lastDurationMs;
|
|
@@ -865,6 +874,7 @@ export declare class SolveScheduler {
|
|
|
865
874
|
private enqueue;
|
|
866
875
|
private execute;
|
|
867
876
|
private runExecutor;
|
|
877
|
+
private hashDefinitionMemo;
|
|
868
878
|
private drainNext;
|
|
869
879
|
private supersede;
|
|
870
880
|
private makeAbortError;
|
|
@@ -1140,13 +1150,15 @@ declare class GrasshopperResponseProcessor {
|
|
|
1140
1150
|
* The output is a cache key, so the invariant that matters is: two payloads
|
|
1141
1151
|
* that serialize differently on the wire must stringify differently here
|
|
1142
1152
|
* (false misses are harmless; false hits serve the wrong cached solve).
|
|
1153
|
+
* Non-JSON values get unquoted markers (`{u8:…}`, `[Circular]`) that no JSON
|
|
1154
|
+
* value stringifies to, so a plain object can't pose as one.
|
|
1143
1155
|
*/
|
|
1144
1156
|
export declare function stableStringify(value: unknown): string;
|
|
1145
1157
|
/** The scheduler's solve-cache key for a definition and its input tree. */
|
|
1146
1158
|
export declare function hashSolveInput(definition: SolveDefinition, dataTree: unknown): string;
|
|
1147
1159
|
/**
|
|
1148
1160
|
* A definition's identity, without its inputs. Strings and bytes are hashed over their full
|
|
1149
|
-
* content
|
|
1161
|
+
* content; a `DefinitionRef` uses its `key`.
|
|
1150
1162
|
*/
|
|
1151
1163
|
export declare function hashDefinition(definition: SolveDefinition): string;
|
|
1152
1164
|
//#endregion
|
package/dist/grasshopper.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{C as e,E as t,T as n,_ as r,b as i,c as a,d as o,f as s,g as c,h as l,i as u,l as d,m as f,s as p,t as m,u as h,x as g,y as _}from"./core-DcBw277f.js";var v=class i{serverUrl;headers;disposed=!1;activeMonitors=new Set;static DEFAULT_TIMEOUT_MS=5e3;static LIFECYCLE_TIMEOUT_MS=6e4;static MIN_MONITOR_INTERVAL_MS=100;constructor(e,t){this.serverUrl=_(e),this.headers={...r(typeof t==`string`?{apiKey:t}:t??{}),"Content-Type":`application/json`}}fetchWithTimeout(e,t={},n=i.DEFAULT_TIMEOUT_MS){let r={...t,headers:this.headers};return n>0&&!r.signal&&(r.signal=AbortSignal.timeout(n)),fetch(e,r)}async getText(t,n={},r=i.DEFAULT_TIMEOUT_MS){this.ensureNotDisposed();let a=`${n.method??`GET`} ${t}`;try{let i=await this.fetchWithTimeout(`${this.serverUrl}${t}`,n,r);return i.ok?await i.text():(e().warn(`[ComputeServerStats] ${a} failed:`,i.status),null)}catch(t){return e().warn(`[ComputeServerStats] ${a} errored:`,t),null}}async isServerOnline(e=i.DEFAULT_TIMEOUT_MS){return(await this.probeServer(e)).online}async probeServer(t=i.DEFAULT_TIMEOUT_MS){this.ensureNotDisposed();let n=`${this.serverUrl}/`;try{let e=await this.fetchWithTimeout(n,{method:`GET`,redirect:`manual`},t),r=e.type===`opaqueredirect`||e.status>=300&&e.status<400;return{online:e.ok||r,status:e.status}}catch(t){return e().debug(`[ComputeServerStats] Fetch error:`,t),{online:!1,error:t instanceof Error?`${t.name}: ${t.message}`:String(t)}}}async getActiveChildren(t={}){let{initialize:n=!0}=t,r=n?await this.getText(`/activechildren`,{},i.LIFECYCLE_TIMEOUT_MS):await this.getText(`/activechildren?initialize=false`);if(r===null)return null;let a=r.trim();return/^\d+$/.test(a)?parseInt(a,10):(e().warn(`[ComputeServerStats] /activechildren answered with a non-numeric body`),null)}async getVersion(){let e=await this.getText(`/version`);if(e===null)return null;let t=y(e);return t==null?{rhino:e,compute:``,git_sha:null}:{rhino:t.rhino??``,compute:t.compute??``,git_sha:t.git_sha??null}}async getInstalledPlugins(e=`gh`){let t=await this.getText(`/plugins/${e}/installed`),n=t===null?void 0:y(t);return n&&typeof n==`object`?n: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(){let e=await this.getText(`/cache/purge`,{method:`POST`}),t=(e===null?void 0:y(e))?.purged;return typeof t==`number`?t:null}async purgeAllChildren(){this.ensureNotDisposed();let t=await this.getActiveChildren({initialize:!1});if(t===null)return e().warn(`[ComputeServerStats] purgeAllChildren: could not read child count`),null;if(t===0)return{totalPurged:0,calls:0,children:0,confident:!0};let n=t*2,r=0;for(let e=0;e<n;e++){let e=await this.purgeCache();e!==null&&(r+=e)}return{totalPurged:r,calls:n,children:t,confident:t===1}}async getServerTime(){let e=await this.getText(`/servertime`);if(e===null)return null;let t=new Date(e.trim().replace(/^"|"$/g,``));return isNaN(t.getTime())?null:t}async getIdleSpan(){let e=await this.getText(`/idlespan`);if(e===null)return null;let t=parseFloat(e.trim());return isNaN(t)?null:t}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){let t=await this.getText(e,{method:`POST`},i.LIFECYCLE_TIMEOUT_MS);return t===null?null:y(t)??null}monitor(r,a=5e3){if(this.ensureNotDisposed(),!Number.isFinite(a)||a<i.MIN_MONITOR_INTERVAL_MS)throw new n(`monitor() intervalMs must be a finite number >= ${i.MIN_MONITOR_INTERVAL_MS}ms, got ${a}. Sub-${i.MIN_MONITOR_INTERVAL_MS}ms polling would hot-loop the server.`,t.INVALID_CONFIG,{context:{intervalMs:a}});let o=!0,s=null;e().info(`🔄 Starting server stats monitoring every ${a}ms`);let c=async()=>{if(s=null,o&&!this.disposed){try{let t=await this.getServerStats();if(!o||this.disposed)return;try{r(t)}catch(t){e().error(`[ComputeServerStats] Monitor callback threw:`,t)}}catch(t){!o||this.disposed?e().debug(`[ComputeServerStats] Monitor poll cancelled during shutdown:`,t):e().error(`[ComputeServerStats] Failed to fetch stats during monitor:`,t)}o&&!this.disposed&&(s=setTimeout(()=>void c(),a))}},l=()=>{o=!1,s!==null&&(clearTimeout(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()}}ensureNotDisposed(){if(this.disposed)throw new n(`ComputeServerStats has been disposed and cannot be used`,t.INVALID_STATE)}};function y(e){try{return JSON.parse(e)}catch{return}}const b=new Set;function ee(){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 x(t,n){n||ee()&&!b.has(t)&&(b.add(t),e().warn(`Warning: ${t} is running on the client side. For better performance and security, consider running this on the server side.`))}const te={definition_not_cached:t.DEFINITION_NOT_CACHED};function ne(e){return{...e,serverErrorCodes:{...te,...e.serverErrorCodes}}}function re(e){return e instanceof n?e.code===t.DEFINITION_NOT_CACHED||e.message.includes(`Unable to load grasshopper definition`):!1}function ie(t,n){if(!n)return;let r=g(t,`values`);if(!Array.isArray(r)||r.length===0)return;let i=[];for(let e of r){let t=g(e,`innerTree`);(!t||Object.keys(t).length===0)&&i.push(g(e,`paramName`)??`<unnamed>`)}if(i.length===0)return;let a=i.length===r.length?`all`:`${i.length}/${r.length}`;e().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 ae(e,t,n){return x(`solveGrasshopperDefinition`,n.suppressBrowserWarning),(await se(e,t,n)).response}async function oe(e,t,n,r){if(x(`solveWithServerCacheKey`,r.suppressBrowserWarning),t!==null)try{return{...await S({algo:null,pointer:t,values:e},r),missed:!1}}catch(e){if(!re(e))throw e}return{...await se(e,n,r),missed:!0}}async function se(e,t,n){return S(le(await ce(t),e),n)}async function ce(e){if(!p(e))return e;try{return await e.load()}catch(r){throw new n(`Failed to load definition bytes for ref '${e.key}'`,t.INVALID_INPUT,{context:{definitionKey:e.key},originalError:r})}}async function S(e,t){ue(e,t);let n=await d(`grasshopper`,e,ne(t)),{pointer:r,algo:i,...a}=n,s=a,c=h(n);if(c!==void 0){let e=typeof i==`string`?i.length:0;o(s,Math.max(0,c-e))}return ie(s,t.debug),{response:s,cacheKey:typeof r==`string`?r:null}}function le(e,t){let n={algo:null,pointer:null,values:t};return e instanceof Uint8Array?n.algo=s(e):a(e)?n.pointer=e:n.algo=f(e)??l(e),n}function ue(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),t.selvaevents!=null&&(e.selvaevents=t.selvaevents)}const C=/^\{(-?\d+(?:;-?\d+)*)?\}$/;function w(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.entries(e);return t.length>0&&t.every(([e,t])=>C.test(e)&&Array.isArray(t))}function T(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 E=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},D=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,fe=e=>{if(typeof e==`string`){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)&&(t=t.slice(1,-1).trim()),t}return null};function O(t){return n=>{if(typeof n==`object`&&n)return n;if(typeof n==`string`&&n.trim()!==``)try{let r=JSON.parse(n);return typeof r==`object`&&r?r:(e().warn(`Parsed value for input ${t} is not an object`),null)}catch(r){return e().warn(`Failed to parse object value "${n}" for input ${t}`,r),null}return null}}const pe=new Set([`System.Double`,`System.Single`,`System.Decimal`,`System.Int32`,`System.Int64`]),me=new Set([`System.Int32`,`System.Int64`]);function k(n,r){return e().warn(r),{schema:{...n,default:null},warning:{code:t.MALFORMED_DEFAULT,message:r}}}function he(n,r){if(typeof n.default!=`object`||n.default===null||Array.isArray(n.default)||w(n.default))return{schema:n};if(!i(n.default,`innerTree`))return k(n,`Input "${r}" default had an unrecognized shape (no innerTree key); the default was dropped.`);let a=g(n.default,`innerTree`)??{};if(Object.keys(a).length===0)return{schema:{...n,default:void 0}};if(n.treeAccess||n.atMost&&n.atMost>1){let i={},o=[];for(let[e,t]of Object.entries(a)){if(!Array.isArray(t))return k(n,`Input "${r}" default had a non-array innerTree branch ("${e}"); the default was dropped.`);let a=[];for(let e of t){let t=g(e,`data`),n=g(e,`type`);if(n&&pe.has(n)){if(typeof t==`string`&&t.trim()===``)continue;let e=E(t);if(e===null){o.push(`"${String(t)}" (${n})`);continue}a.push(me.has(n)?Math.round(e):e);continue}if(n===`System.Boolean`){let e=D(t);if(e===null){o.push(`"${String(t)}" (${n})`);continue}a.push(e);continue}if(typeof t==`string`&&n?.startsWith(`Rhino.Geometry`)){try{a.push(JSON.parse(t))}catch{a.push(t)}continue}a.push(t)}i[e]=a}if(o.length>0){let a=`Input "${r}" default contained ${o.length} tree value(s) that could not be parsed and were dropped: ${o.join(`, `)}.`;return e().warn(a),{schema:{...n,default:i},warning:{code:t.MALFORMED_DEFAULT,message:a}}}return{schema:{...n,default:i}}}let o=[];for(let e of Object.values(a))if(Array.isArray(e))for(let t of e)t&&typeof t==`object`&&i(t,`data`)&&o.push(g(t,`data`));return{schema:{...n,default:o.length>1?o:o[0]}}}function ge(e,t){let n=Number(e.toFixed(t));return Math.abs(e-n)<1e-8?n:e}function A(e){if(!Number.isFinite(e))return 0;let[t,n]=String(Math.abs(e)).split(`e`),r=n===void 0?Math.abs(e).toFixed(12).replace(/0+$/,``).split(`.`)[1]?.length??0:(t.split(`.`)[1]?.length??0)-Number(n);return Math.min(Math.max(r,0),12)}function _e(e){if(!Number.isFinite(e)||e===0)return .1;let t=A(e);return t===0?Math.abs(e)>=1?1:.1:Number((10**-t).toFixed(t))}function j(e){return typeof e.stepSize==`number`&&Number.isFinite(e.stepSize)&&e.stepSize>0?e.stepSize:void 0}const M=(e,t)=>(e.atMost??1)>1?[t]:t,N=e=>j(e)??(e.paramType===`Integer`?1:.1),P=(e,t)=>Array.isArray(e)?e.map(e=>typeof e==`number`?t(e):e):typeof e==`number`?t(e):e;function ve(e){if(w(e.default))return{default:e.default,stepSize:N(e)};if(typeof e.default==`string`&&e.default.trim()!==``&&E(e.default)===null)throw new n(`Invalid numeric default "${e.default}" for input "${e.name||`unknown`}"`,t.VALIDATION_ERROR,{context:{inputName:e.name,default:e.default}});let r=T(e.default,E,!0);if(e.paramType===`Integer`)return{default:P(r,Math.round),stepSize:N(e)};let i=Array.isArray(r)?r[0]:r,a=[i,e.minimum,e.maximum].find(e=>typeof e==`number`&&Number.isFinite(e)&&e!==0),o=j(e)??(a===void 0?.1:_e(a)),s=A(o);if(s===0&&typeof i==`number`&&i!==0&&Math.abs(i)<1){let e=Math.ceil(-Math.log10(Math.abs(i)));Number.isFinite(e)&&e>0&&(s=e)}return s=Math.min(Math.max(s,0),12),{default:P(r,e=>ge(e,s)),stepSize:o}}const F={parse(e,t){let{default:n,stepSize:r}=ve(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=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:N(e),default:M(e,n)}}},ye={parse(e,r){if(w(e.default))return{...r,paramType:`Boolean`,default:e.default};let i=T(e.default,D,!1);if(i!=null&&typeof i!=`boolean`&&!Array.isArray(i))throw new n(`Invalid boolean default "${String(i)}" for input "${e.name||`unknown`}"`,t.VALIDATION_ERROR,{context:{inputName:e.name,default:e.default}});return{...r,paramType:`Boolean`,default:i}},fallback(e,t){return{...t,paramType:`Boolean`,default:M(e,!1)}}},be={parse(e,t){let n=T(e.default,de,!1);return{...t,paramType:`Text`,default:n}}},xe={parse(r,i,a){if(!r.values||typeof r.values!=`object`||Object.keys(r.values).length===0){let e=r.nickname||`unnamed`;throw new n(`Input "${e}" has no values defined (expected ValueList)`,t.INVALID_INPUT,{context:{inputName:e,expectedType:`ValueList`}})}let o=r.default;if(r.default!==void 0&&r.default!==null){if(typeof r.default==`object`)throw new n(`ValueList input "${r.nickname||`unnamed`}" default is not a string-able value`,t.VALIDATION_ERROR,{context:{inputName:r.name,default:r.default}});let i=String(r.default).toLowerCase(),s=Object.keys(r.values).find(e=>e.toLowerCase()===i);if(s!==void 0)o=s;else{let n=`ValueList input "${r.nickname||`unnamed`}" default value "${r.default}" is not in available values`;e().warn(n),a?.({code:t.VALIDATION_ERROR,message:n})}}return{...i,paramType:`ValueList`,values:r.values,default:o}},fallback(e,t){return{...t,paramType:`ValueList`,values:e.values&&typeof e.values==`object`?e.values:{},default:void 0}}};function I(e,t){return{...t,paramType:`Geometry`,default:M(e,null)}}const L=new Map([[`Number`,F],[`Integer`,F],[`Boolean`,ye],[`Text`,be],[`ValueList`,xe],[`Geometry`,{parse(e,t){let n=T(e.default,O(e.nickname||`unnamed`),!0);return{...t,paramType:`Geometry`,default:n}},fallback:I}],[`File`,{parse(e,t){let n=T(e.default,O(e.nickname||`unnamed`),!0);return{...t,paramType:`File`,acceptedFormats:e.acceptedFormats,default:n}}}],[`Color`,{parse(e,t){let n=T(e.default,fe,!1);return{...t,paramType:`Color`,default:n}}}]]),Se=I,Ce=new Map([...L.keys()].map(e=>[e.toLowerCase(),e]));function we(e){return Ce.get(e?.toLowerCase())??e}function Te(e){return R(e).input}function R(r){let i=r.name||`unknown`,a=[],o=({code:e,message:t})=>{a.push({inputName:i,paramType:r.paramType,message:t,code:e})},s={description:r.description,name:r.name,nickname:r.nickname,treeAccess:r.treeAccess,groupName:r.groupName??void 0,id:r.id},c=we(r.paramType),l={...r,paramType:c};try{let{schema:e,warning:t}=he(l,i);l=e,t&&o(t)}catch(e){l={...l,default:null},o({code:t.MALFORMED_DEFAULT,message:`Input "${i}" default could not be normalized and was dropped: ${e instanceof Error?e.message:String(e)}`})}let u=L.get(c);try{if(!u)throw new n(`Unknown paramType: ${c}`,t.VALIDATION_ERROR,{context:{receivedParamType:c,paramName:r.name}});return{input:u.parse(l,s,o),errors:a}}catch(d){if(!(d instanceof n))throw new n(d instanceof Error?d.message:String(d),t.VALIDATION_ERROR,{context:{paramName:r.name,paramType:c},originalError:d});return e().error(`Validation error for input ${i}:`,d.message),o(d),{input:(u?.fallback??Se)(l,s),errors:a}}}function Ee(e){let t=[],n=[];for(let r of e){let{input:e,errors:i}=R(r);t.push(e),n.push(...i)}return{inputs:t,parseErrors:n}}function De(e){let t=g(e,`stepSize`);return{id:g(e,`id`)??``,name:g(e,`name`)??``,nickname:g(e,`nickname`)??null,description:g(e,`description`)??``,paramType:g(e,`paramType`)??``,treeAccess:g(e,`treeAccess`)??!1,minimum:g(e,`minimum`)??null,maximum:g(e,`maximum`)??null,atLeast:g(e,`atLeast`)??1,atMost:g(e,`atMost`)??1,stepSize:typeof t==`number`&&Number.isFinite(t)?t:void 0,default:g(e,`default`),values:g(e,`values`),acceptedFormats:g(e,`acceptedFormats`),groupName:g(e,`groupName`)??null}}function Oe(e){return{name:g(e,`name`)??``,nickname:g(e,`nickname`)??null,paramType:g(e,`paramType`)??``,id:g(e,`id`)??``}}async function z(e,r){x(`fetchDefinitionIO`,r.suppressBrowserWarning);let{algo:i,pointer:a}=le(e,[]);if(!i&&!a)throw new n(`Definition must resolve to either a URL pointer or base64 algo`,t.INVALID_INPUT);let o=await d(`io`,i?{algo:i}:{pointer:a},ne(r));if(!o||typeof o!=`object`)throw new n(`Invalid IO response structure`,t.INVALID_INPUT,{context:{response:o}});let s=B(g(o,`warnings`)),c=B(g(o,`errors`)),l=g(o,`inputs`),u=g(o,`outputs`);return{inputs:Array.isArray(l)?l.map(De):[],outputs:Array.isArray(u)?u.map(Oe):[],...s&&{loadWarnings:s},...c&&{loadErrors:c}}}function B(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 t;if(typeof e==`string`)t=e;else if(typeof e==`object`){let n=g(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 V(e,t){let{inputs:n,outputs:r,loadWarnings:i,loadErrors:a}=await z(e,t),{inputs:o,parseErrors:s}=Ee(n);return{inputs:o,outputs:r,...s.length>0&&{parseErrors:s},...i&&{loadWarnings:i},...a&&{loadErrors:a}}}function H(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":"${G(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 U(e,t){let n=2166136261;for(let r=0;r<e;r++)n^=t(r),n=Math.imul(n,16777619)>>>0;return n.toString(16).padStart(8,`0`)}function W(e){return U(e.length,t=>e.charCodeAt(t))}function G(e){return U(e.length,t=>e[t])}function Ae(e,t){return je(K(e),t)}function je(e,t){let n=H(t);return`${e}|t:${n.length}:${W(n)}`}function K(e){return p(e)?`r:${e.key}`:typeof e==`string`?`s:${e.length}:${W(e)}`:`u8:${e.length}:${G(e)}`}const Me=new WeakMap;function Ne(e){if(!(e instanceof Uint8Array))return K(e);let t=Me.get(e);return t===void 0&&(t=K(e),Me.set(e,t)),t}function Pe(e){try{return JSON.stringify(e)?.length??0}catch{return 0}}var Fe=class{executor;baseConfig;mode;maxConcurrent;maxQueueDepth;queueWaitMs;timeoutMs;retry;cacheEnabled;cacheMaxBytes;cacheTtl;cacheErroredSolves;cache=new Map;cacheBytes=0;cacheHits=0;cacheMisses=0;cacheEvictions=0;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,r,i={}){if(this.executor=e,this.baseConfig=r,this.mode=i.mode??`latest-wins`,this.mode!==`latest-wins`&&this.mode!==`queue`)throw new n(`Unknown scheduler mode '${String(this.mode)}'. For concurrent solves use { mode: 'queue', maxConcurrent: 4 }.`,t.INVALID_CONFIG,{context:{mode:this.mode}});this.maxConcurrent=Math.max(1,i.maxConcurrent??1),this.maxQueueDepth=i.maxQueueDepth!==void 0&&i.maxQueueDepth>0?Math.floor(i.maxQueueDepth):void 0,this.queueWaitMs=i.queueWaitMs!==void 0&&i.queueWaitMs>0?i.queueWaitMs:void 0,this.timeoutMs=i.timeoutMs,this.retry=i.retry;let a=i.cache,o=typeof a==`object`?a:null;this.cacheMaxBytes=Math.max(0,o?.maxBytes??0),this.cacheEnabled=this.cacheMaxBytes>0,this.cacheTtl=o?.ttlMs??0,this.cacheErroredSolves=o?.cacheErroredSolves??!0,this.reuseServerDefinitionCache=i.reuseServerDefinitionCache??!0,this.onStart=i.onStart,this.onSettle=i.onSettle,this.onSuperseded=i.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 t of this.subscribers)try{t()}catch(t){e().error(`[SolveScheduler] subscriber threw:`,t)}}solve(e,t,n){return this.solveDetailed(e,t,n).then(e=>e.response)}solveDetailed(e,r,i){if(this.disposed)return Promise.reject(new n(`SolveScheduler has been disposed and cannot be used`,t.INVALID_STATE));let a=Ne(e),o=je(a,r),s=++this.solveSeq,c={key:o,enqueuedAt:Date.now(),startedAt:null};if(i?.signal?.aborted)return Promise.reject(this.makeAbortError(c));let l=this.readCache(o);if(l){this.mode===`latest-wins`&&this.supersedeCurrent();let e={status:`success`,response:l,durationMs:0,fromCache:!0};return this.writeLastState(s,{result:l,durationMs:0}),this.runHook(this.onStart,c),this.runHook(this.onSettle,c,e),this.notify(),Promise.resolve({response:l,fromCache:!0,durationMs:0})}return new Promise((t,n)=>{let o={definition:e,dataTree:r,definitionHash:a,ctx:c,seq:s,resolve:t,reject:n,externalSignal:i?.signal,selvaevents:i?.selvaevents,onServerTiming:i?.onServerTiming};o.externalSignal&&(o.queuedAbortHandler=()=>this.abortQueuedItem(o),o.externalSignal.addEventListener(`abort`,o.queuedAbortHandler,{once:!0})),this.enqueue(o)})}writeLastState(e,t){e<this.lastStateSeq||(this.lastStateSeq=e,`result`in t?(this._lastResult=t.result,this._lastError=null):this._lastError=t.error,this._lastDurationMs=t.durationMs)}supersedeCurrent(){this.pendingForLatestWins&&=(this.supersede(this.pendingForLatestWins),null);for(let e of this.inFlight)this.supersede(e),e.controller.abort()}dequeue(e){this.pendingForLatestWins===e&&(this.pendingForLatestWins=null);let t=this.fifoQueue.indexOf(e);t>=0&&this.fifoQueue.splice(t,1)}abortQueuedItem(e){this.dequeue(e),this.fail(e,this.makeAbortError(e.ctx)),this.notify()}shedAsQueueFull(e){let r=new n(`Solve queue is full; request rejected (backpressure)`,t.QUEUE_FULL,{statusCode:503,context:{key:e.ctx.key,queueDepth:this.fifoQueue.length,maxQueueDepth:this.maxQueueDepth}});this.fail(e,r),this.notify()}armQueueWaitTimer(e){if(this.queueWaitMs===void 0)return;let r=this.queueWaitMs;e.queueWaitTimer=setTimeout(()=>{if(e.settled)return;this.dequeue(e);let i=new n(`Solve waited longer than ${r}ms in queue; rejected (backpressure)`,t.QUEUE_TIMEOUT,{statusCode:503,context:{key:e.ctx.key,waitedMs:Date.now()-e.ctx.enqueuedAt,queueWaitMs:r}});this.fail(e,i),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`: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},...e.selvaevents!==void 0&&{selvaevents:e.selvaevents}},r=e.onServerTiming;if(r){let e=this.baseConfig.onServerTiming;n.onServerTiming=(t,n)=>{try{e?.(t,n)}finally{r(t,n)}}}let{response:a,definitionReuploaded:o}=await this.runExecutor(e.definition,e.dataTree,e.definitionHash,n),s=performance.now()-i;if(this.writeCache(e.ctx.key,a),!this.settleSuccess(e,{response:a,fromCache:!1,definitionReuploaded:o,durationMs:s}))return;this.writeLastState(e.seq,{result:a,durationMs:s}),this.runHook(this.onSettle,e.ctx,{status:`success`,response:a,durationMs:s,fromCache:!1,definitionReuploaded:o})}catch(t){let r=performance.now()-i,a=this.normalizeExecutionError(t,n);this.writeLastState(e.seq,{error:a,durationMs:r}),this.fail(e,a,r)}finally{e.externalSignal?.removeEventListener(`abort`,r),this.inFlight.delete(n),this.drainNext(),this.notify()}}async runExecutor(e,t,n,r){if(!this.reuseServerDefinitionCache||a(e)){let{response:n}=await this.executor(e,t,null,r);return{response:n}}let i=this.serverCacheKeys.get(n)??null,o=await this.executor(e,t,i,r);return this.serverCacheKeys.delete(n),o.cacheKey&&(this.serverCacheKeys.set(n,o.cacheKey),this.serverCacheKeys.size>100&&this.serverCacheKeys.delete(this.serverCacheKeys.keys().next().value)),{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(e){let r=new n(`Superseded by newer solve`,t.SUPERSEDED,{context:{key:e.ctx.key,enqueuedAt:e.ctx.enqueuedAt}});this.settleError(e,r)&&this.runHook(this.onSuperseded,e.ctx)}makeAbortError(e){return new n(`Request aborted by caller`,t.ABORTED,{context:{key:e.key,enqueuedAt:e.enqueuedAt}})}settleError(e,t){return!e.settled&&(e.settled={error:t},this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e),e.reject(t),!0)}fail(e,t,n=0){this.settleError(e,t)&&this.runHook(this.onSettle,e.ctx,{status:`error`,error:t,durationMs:n})}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}normalizeExecutionError(e,r){return r.settled&&`error`in r.settled?r.settled.error:e instanceof n?e:e instanceof Error&&e.name===`AbortError`?this.makeAbortError(r.ctx):new n(e instanceof Error?e.message:String(e),t.UNKNOWN_ERROR,{originalError:e})}cancelAll(){for(this.pendingForLatestWins&&=(this.fail(this.pendingForLatestWins,this.makeAbortError(this.pendingForLatestWins.ctx)),null);this.fifoQueue.length>0;){let e=this.fifoQueue.shift();this.fail(e,this.makeAbortError(e.ctx))}for(let e of this.inFlight){let t=e.ctx.startedAt?Date.now()-e.ctx.startedAt:0;this.fail(e,this.makeAbortError(e.ctx),t),e.controller.abort()}this.notify()}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=g(t,`errors`);if(!this.cacheErroredSolves&&Array.isArray(n)&&n.length>0)return;let r=h(t)??Pe(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(t,...n){if(t)try{t(...n)}catch(t){e().error(`[SolveScheduler] hook threw:`,t)}}};function Ie(e){return p(e)?`ref:${e.key}`:typeof e==`string`&&e.length<200?e:`...content...`}function Le(e){return Array.isArray(e)?e.map(e=>{let t=0,n=0,r=g(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:g(e,`paramName`)??`<unnamed>`,items:t,bytes:n}}):[]}var Re=class r{config;serverStats;disposed=!1;static CREATE_PROBE_TIMEOUT_MS=2e3;constructor(e){this.config={...e,serverUrl:_(e.serverUrl),debug:e.debug??!1},this.serverStats=new v(this.config.serverUrl,this.config)}static async create(e,i={}){let a=new r(e),o=Math.max(1,(i.probe?.attempts??2)+1),s=i.probe?.baseDelayMs??250,l=i.probe?.maxDelayMs??1e3,u,d=null,f=0;for(let e=0;e<o;e++){if(f=e+1,u=await a.serverStats.probeServer(r.CREATE_PROBE_TIMEOUT_MS),u.online)return a;if(d=c(u),d&&!d.retryable)break;if(e<o-1){let t=Math.min(s*2**e,l);await new Promise(e=>setTimeout(e,t))}}await a.dispose();let p=u?.status,m=d?`Rhino Compute server is not available. ${d.summary}`:`Rhino Compute server is not online`;throw new n(m,t.NETWORK_ERROR,{...p!==void 0&&{statusCode:p},context:{serverUrl:a.config.serverUrl,attempts:f,maxAttempts:o,...d&&{probeVerdict:d.verdict,probeRetryable:d.retryable},...p!==void 0&&{lastProbeStatus:p},...u?.error!==void 0&&{lastProbeError:u.error}}})}getConfig(){return this.ensureNotDisposed(),{...this.config}}async getIO(e){return this.ensureNotDisposed(),V(e,this.config)}async getRawIO(e){return this.ensureNotDisposed(),z(e,this.config)}async solve(r,i,a){this.ensureNotDisposed();try{if(typeof r==`string`&&!r.trim())throw new n(`Definition URL/content is required`,t.INVALID_INPUT,{context:{receivedUrl:r}});if(r instanceof Uint8Array&&r.length===0)throw new n(`Definition content is empty`,t.INVALID_INPUT);if(p(r)&&!r.key.trim())throw new n(`DefinitionRef key is empty`,t.INVALID_INPUT);let e=await ae(i,r,{...this.config,...a?.signal!==void 0&&{signal:a.signal},...a?.timeoutMs!==void 0&&{timeoutMs:a.timeoutMs},...a?.retry!==void 0&&{retry:a.retry},...a?.selvaevents!==void 0&&{selvaevents:a.selvaevents}}),o=g(e,`errors`);if(Array.isArray(o)&&o.length>0)throw new n(o.map(String).join(`; `)||`Computation failed`,t.COMPUTATION_ERROR,{context:{definition:Ie(r),inputSummary:Le(i),errors:o,warnings:g(e,`warnings`),values:e.values}});return e}catch(a){throw this.config.debug&&e().error(`Compute failed:`,a),a instanceof n?a:new n(a instanceof Error?a.message:String(a),t.COMPUTATION_ERROR,{context:{definition:Ie(r),inputSummary:Le(i)},originalError:a})}}createScheduler(e){return this.ensureNotDisposed(),new Fe((e,t,n,r)=>oe(t,n,e,r),this.config,e)}async dispose(){this.disposed||(this.disposed=!0,await this.serverStats.dispose())}ensureNotDisposed(){if(this.disposed)throw new n(`GrasshopperClient has been disposed and cannot be used`,t.INVALID_STATE)}};function ze(e){return typeof e==`object`&&!!e&&e.__decodeError===!0}function Be(e,t){return{__decodeError:!0,type:e,raw:t}}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 q=new Map([[`Rhino.Geometry.Point3d`,(e,t)=>{let n=t;return!n||typeof n.X!=`number`?null:new e.Point([n.X,n.Y,n.Z])}],[`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(q.has(e))return q.get(e);for(let[t,n]of q)if(e.startsWith(t))return n}function Ue(e){return!!(e&&typeof e==`object`&&typeof e.data==`string`)}function We(t,n,r){let i=He(n),a=!1;if(i)try{let e=i(r,t);if(e!=null)return e}catch(t){e().warn(`Failed to decode Rhino type ${n}:`,t),a=!0}try{if(Ue(t))return r.CommonObject.decode(t)}catch(r){return e().warn(`Failed to decode ${n} with CommonObject:`,r),Be(n,t)}return a?Be(n,t):t}const J={STRING:`System.String`,INT:`System.Int32`,DOUBLE:`System.Double`,BOOL:`System.Boolean`},Ge=`FileData`;function Ke(e,t){return e.includes(`WebDisplay`)||t&&e!==J.STRING}function qe(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 Je(e,t,n){switch(t){case J.STRING:return typeof e==`string`?e.replace(/^"(.*)"$/,`$1`):e;case J.INT:return Number.parseInt(String(e),10);case J.DOUBLE:return Number.parseFloat(String(e));case J.BOOL:return String(e).toLowerCase()===`true`;default:return n&&t.startsWith(`Rhino.Geometry.`)?We(e,t,n):e}}function Y(e,t,n,r){if(typeof e.data!=`string`)return e.data;let i=n?qe(e.data):e.data;return n&&t.includes(Ge)?Ye(i)??i:Je(i,t,r)}function Ye(e){if(!e||typeof e!=`object`)return null;let t=g(e,`fileName`),n=g(e,`fileType`),r=g(e,`subFolder`),a=g(e,`isBase64Encoded`);if(typeof t!=`string`||typeof n!=`string`||typeof r!=`string`||!i(e,`data`)||typeof a!=`boolean`&&typeof a!=`string`)return null;let o=g(e,`metadata`);return{fileName:t,fileType:n,data:g(e,`data`),isBase64Encoded:u(a),subFolder:r,...o?{metadata:o}:{}}}function X(e){let t=g(e,`values`);return Array.isArray(t)?t:[]}function Z(e){return typeof e.type==`string`?e.type:``}function Q(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 Xe(e,t=!1,n={}){let{parseValues:r=!0,rhino:i,stringOnly:a=!1}=n,o={},s=new Set;for(let n of X(e)){let e=g(n,`paramName`);Q(g(n,`innerTree`),n=>{let c=Z(n);if(Ke(c,a))return;let l=t?n.id:e;if(!l)return;let u=Y(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 Ze(e){let t=[];for(let n of X(e))Q(g(n,`innerTree`),e=>{if(!Z(e).includes(Ge))return;let n=Ye(qe(e.data));n&&t.push(n)});return t}function Qe(e,t,n={}){let{parseValues:r=!0,rhino:i,stringOnly:a=!1}=n;for(let n of X(e)){let e=g(n,`innerTree`),o=!1;if(`byName`in t){if(g(n,`paramName`)!==t.byName)continue;o=!0}let s=[];if(Q(e,e=>{if(`byId`in t){if(e.id!==t.byId)return;o=!0}let n=Z(e);Ke(n,a)||s.push(Y(e,n,r,i))}),o)return s.length===0?void 0:s.length===1?s[0]:s}}var $e=class{response;constructor(e){this.response=e}getValues(e=!1,t={}){return Xe(this.response,e,t)}getValue(e,t){return Qe(this.response,e,t)}async getAndDownloadFiles(e,t){await m(Ze(this.response),e,t)}};function et(e){return(Array.isArray(e)?e:[e]).map(e=>({schemas:g(e,`schemas`),error:g(e,`error`)}))}const tt=new Set([`options`,`defaultOptions`,`values`]),nt=e=>e>=`A`&&e<=`Z`;function rt(e){if(e.length===0||!nt(e[0]))return e;let t=0;for(;t<e.length&&nt(e[t]);)t++;return t>1&&t<e.length&&t--,e.slice(0,t).toLowerCase()+e.slice(t)}function it(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=rt(n);t[e]=tt.has(e)?r:$(r)}return t}var at=class r{innerTree;paramName;constructor(e){this.paramName=e,this.innerTree={}}append(e,t){let n=r.formatPathString(e);this.innerTree[n]||(this.innerTree[n]=[]);let i=t.map(e=>({data:r.serializeValue(e)}));return this.innerTree[n].push(...i),this}fromDataTreeDefault(e){this.innerTree={};for(let[t,n]of Object.entries(e)){if(!Array.isArray(n))continue;let e=r.parsePathString(t);this.append(e,n)}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 n of t)e.push(r.deserializeValue(n.data));return e}toComputeFormat(){return{ParamName:this.paramName,InnerTree:this.innerTree}}getParamName(){return this.paramName}static fromInputParams(e){return r.fromValues(e.map(e=>({paramName:e.nickname||`unnamed`,paramType:e.paramType,value:e.default,...`minimum`in e&&{minimum:e.minimum,maximum:e.maximum}})))}static fromValues(t){let n=[];for(let i of t){let t=new r(i.paramName),a=r.itemCoercer(i);for(let[n,o]of r.branchesOf(i.value)){let r=[];for(let t of o){if(t==null)continue;let n=a(t);n===null?e().warn(`${i.paramName}: dropped an item that is not a valid ${i.paramType}`):r.push(n)}r.length>0&&t.append(n,r)}Object.keys(t.innerTree).length>0&&n.push(t.toComputeFormat())}return n}static branchesOf(e){return r.hasValidValue(e)?w(e)?Object.entries(e).map(([e,t])=>[r.parsePathString(e),t]):[[[0],Array.isArray(e)?e:[e]]]:[]}static itemCoercer(e){let{paramName:t,minimum:n,maximum:i}=e,a=e.paramType.toLowerCase();return a===`number`||a===`integer`?e=>{let o=E(e);if(o===null)return null;let s=a===`integer`?Math.round(o):o;return r.clampValue(s,n,i,t)}:a===`boolean`?D:e=>e}static replaceTreeValue(e,t,n){let i=r.buildFromValue(t,n).toComputeFormat(),a=e.slice(),o=a.findIndex(e=>r.paramNameOf(e)===t);return o===-1?a.push(i):a[o]=i,a}static buildFromValue(e,t){let n=new r(e);return w(t)?n.fromDataTreeDefault(t):n.appendFlat(t),n}static getTree(e,t){let n=e.find(e=>r.paramNameOf(e)===t);if(!n)return null;let i=new Map,a=g(n,`InnerTree`);if(!a||typeof a!=`object`)return i;for(let[e,t]of Object.entries(a))Array.isArray(t)&&i.set(e,t.map(e=>e?.data===void 0?null:r.deserializeValue(e.data)));return i}static getTreeValue(e,i){let a=r.getTree(e,i);if(!a||a.size===0)return null;if(a.size>1)throw new n(`"${i}" has ${a.size} branches; read it with TreeBuilder.getTree`,t.INVALID_INPUT,{context:{paramName:i,branchCount:a.size}});let[o]=a.values();return o.length===0?null:o.length===1?o[0]:o}static paramNameOf(e){return g(e,`ParamName`)}static parsePathString(e){let r=e.match(C);if(!r)throw new n(`Invalid Grasshopper tree path: "${e}". Expected "{}", "{0}", or "{0;1;2}" (negative indices allowed, no empty segments).`,t.INVALID_INPUT,{context:{pathStr:e}});return r[1]?r[1].split(`;`).map(Number):[]}static formatPathString(e){return`{${e.join(`;`)}}`}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!=`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 clampValue(t,n,r,i){let a=t;return n!=null&&a<n&&(e().warn(`${i}: ${t} below min ${n}, clamping`),a=n),r!=null&&a>r&&(e().warn(`${i}: ${t} above max ${r}, clamping`),a=r),a}};export{v as ComputeServerStats,Re as GrasshopperClient,$e as GrasshopperResponseProcessor,Fe as SolveScheduler,at as TreeBuilder,Ve as disposeRhinoObjects,z as fetchDefinitionIO,V as fetchParsedDefinitionIO,K as hashDefinition,Ae as hashSolveInput,ze as isRhinoDecodeError,it as normalizeUISchemaCasing,Te as processInput,et as readSchemaResults,ae as solveGrasshopperDefinition,H as stableStringify};
|
|
1
|
+
import{C as e,D as t,O as n,S as r,T as i,_ as a,c as o,d as s,f as c,h as l,i as u,l as d,m as f,p,s as m,t as ee,u as te,v as ne,x as h,y as re}from"./core-CFlbOj2M.js";var g=class e{serverUrl;headers;disposed=!1;activeMonitors=new Set;static DEFAULT_TIMEOUT_MS=5e3;static LIFECYCLE_TIMEOUT_MS=6e4;static MIN_MONITOR_INTERVAL_MS=100;static MAX_BODY_BYTES=1<<20;constructor(e,t){this.serverUrl=h(e),this.headers={...re(typeof t==`string`?{apiKey:t}:t??{}),"Content-Type":`application/json`}}fetchWithTimeout(t,n={},r=e.DEFAULT_TIMEOUT_MS){let i={...n,headers:this.headers,redirect:`manual`};return r>0&&!i.signal&&(i.signal=AbortSignal.timeout(r)),fetch(t,i)}async getText(t,n={},r=e.DEFAULT_TIMEOUT_MS){this.ensureNotDisposed();let a=`${n.method??`GET`} ${t}`;try{let o=await this.fetchWithTimeout(`${this.serverUrl}${t}`,n,r);if(!o.ok)return i().warn(`[ComputeServerStats] ${a} failed:`,o.status),await o.body?.cancel().catch(()=>{}),null;let{text:s,truncated:c}=await f(o,e.MAX_BODY_BYTES);return c?(i().warn(`[ComputeServerStats] ${a} answered with an oversized body`),null):s}catch(e){return i().warn(`[ComputeServerStats] ${a} errored:`,e),null}}async isServerOnline(t=e.DEFAULT_TIMEOUT_MS){return(await this.probeServer(t)).online}async probeServer(t=e.DEFAULT_TIMEOUT_MS){this.ensureNotDisposed();let n=`${this.serverUrl}/`;try{let e=await this.fetchWithTimeout(n,{method:`GET`},t);return await e.body?.cancel().catch(()=>{}),{online:e.ok||s(e),status:e.status}}catch(e){return i().debug(`[ComputeServerStats] Fetch error:`,e),{online:!1,error:e instanceof Error?`${e.name}: ${e.message}`:String(e)}}}async getActiveChildren(t={}){let{initialize:n=!0}=t,r=n?await this.getText(`/activechildren`,{},e.LIFECYCLE_TIMEOUT_MS):await this.getText(`/activechildren?initialize=false`);if(r===null)return null;let a=r.trim();return/^\d+$/.test(a)?parseInt(a,10):(i().warn(`[ComputeServerStats] /activechildren answered with a non-numeric body`),null)}async getVersion(){let e=await this.getText(`/version`);if(e===null)return null;let t=_(e);return t==null?{rhino:e,compute:``,git_sha:null}:{rhino:t.rhino??``,compute:t.compute??``,git_sha:t.git_sha??null}}async getInstalledPlugins(e=`gh`){let t=await this.getText(`/plugins/${e}/installed`),n=t===null?void 0:_(t);return n&&typeof n==`object`?n: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(){let e=await this.getText(`/cache/purge`,{method:`POST`}),t=(e===null?void 0:_(e))?.purged;return typeof t==`number`?t:null}async purgeAllChildren(){this.ensureNotDisposed();let e=await this.getActiveChildren({initialize:!1});if(e===null)return i().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(){let e=await this.getText(`/servertime`);if(e===null)return null;let t=new Date(e.trim().replace(/^"|"$/g,``));return isNaN(t.getTime())?null:t}async getIdleSpan(){let e=await this.getText(`/idlespan`);if(e===null)return null;let t=parseFloat(e.trim());return isNaN(t)?null:t}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(t){let n=await this.getText(t,{method:`POST`},e.LIFECYCLE_TIMEOUT_MS);return n===null?null:_(n)??null}monitor(r,a=5e3){if(this.ensureNotDisposed(),!Number.isFinite(a)||a<e.MIN_MONITOR_INTERVAL_MS)throw new t(`monitor() intervalMs must be a finite number >= ${e.MIN_MONITOR_INTERVAL_MS}ms, got ${a}. Sub-${e.MIN_MONITOR_INTERVAL_MS}ms polling would hot-loop the server.`,n.INVALID_CONFIG,{context:{intervalMs:a}});let o=!0,s=null;i().info(`🔄 Starting server stats monitoring every ${a}ms`);let c=async()=>{if(s=null,o&&!this.disposed){try{let e=await this.getServerStats();if(!o||this.disposed)return;try{r(e)}catch(e){i().error(`[ComputeServerStats] Monitor callback threw:`,e)}}catch(e){!o||this.disposed?i().debug(`[ComputeServerStats] Monitor poll cancelled during shutdown:`,e):i().error(`[ComputeServerStats] Failed to fetch stats during monitor:`,e)}o&&!this.disposed&&(s=setTimeout(()=>void c(),a))}},l=()=>{o=!1,s!==null&&(clearTimeout(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()}}ensureNotDisposed(){if(this.disposed)throw new t(`ComputeServerStats has been disposed and cannot be used`,n.INVALID_STATE)}};function _(e){try{return JSON.parse(e)}catch{return}}const v=new Set;function ie(){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 y(e,t){t||ie()&&!v.has(e)&&(v.add(e),i().warn(`Warning: ${e} is running on the client side. For better performance and security, consider running this on the server side.`))}const ae={definition_not_cached:n.DEFINITION_NOT_CACHED};function oe(e){return{...e,serverErrorCodes:{...ae,...e.serverErrorCodes}}}function se(e){return e instanceof t?e.code===n.DEFINITION_NOT_CACHED||e.message.includes(`Unable to load grasshopper definition`):!1}function ce(t,n){if(!n)return;let r=e(t,`values`);if(!Array.isArray(r)||r.length===0)return;let a=[];for(let t of r){let n=e(t,`innerTree`);(!n||Object.keys(n).length===0)&&a.push(e(t,`paramName`)??`<unnamed>`)}if(a.length===0)return;let o=a.length===r.length?`all`:`${a.length}/${r.length}`;i().warn(`Solve returned empty output(s) (${o}): ${a.join(`, `)}. These parameters produced no data — check the definition's inputs and the branch feeding each.`)}async function le(e,t,n){return y(`solveGrasshopperDefinition`,n.suppressBrowserWarning),(await de(e,t,n)).response}async function ue(e,t,n,r){if(y(`solveWithServerCacheKey`,r.suppressBrowserWarning),t!==null)try{return{...await pe({algo:null,pointer:t,values:e},r),missed:!1}}catch(e){if(!se(e))throw e}return{...await de(e,n,r),missed:!0}}async function de(e,t,n){return pe(b(await fe(t),e),n)}async function fe(e){if(!m(e))return e;try{return await e.load()}catch(r){throw new t(`Failed to load definition bytes for ref '${e.key}'`,n.INVALID_INPUT,{context:{definitionKey:e.key},originalError:r})}}async function pe(e,t){h(t.serverUrl),me(e,t);let{maxResponseBytes:n}=t,r=await d(`grasshopper`,e,oe({...t,maxResponseBytes:n!==void 0&&e.algo?n+e.algo.length:n})),{pointer:i,algo:a,...o}=r,s=o,l=c(r);if(l!==void 0){let e=typeof a==`string`?a.length:0;p(s,Math.max(0,l-e))}return ce(s,t.debug),{response:s,cacheKey:typeof i==`string`?i:null}}function b(e,t){let n={algo:null,pointer:null,values:t};return e instanceof Uint8Array?n.algo=l(e):o(e)?n.pointer=e:n.algo=a(e)??ne(e),n}function me(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),t.selvaevents!=null&&(e.selvaevents=t.selvaevents)}function x(e,t,n){t===`__proto__`?Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0}):e[t]=n}const S=/^\{(-?\d+(?:;-?\d+)*)?\}$/;function C(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.entries(e);return t.length>0&&t.every(([e,t])=>S.test(e)&&Array.isArray(t))}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 T=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},E=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},he=e=>typeof e==`string`?e.length>=2&&e.startsWith(`"`)&&e.endsWith(`"`)?e.slice(1,-1):e.startsWith(`"`)?e.slice(1):e:null,ge=e=>{if(typeof e==`string`){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)&&(t=t.slice(1,-1).trim()),t}return null};function D(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:(i().warn(`Parsed value for input ${e} is not an object`),null)}catch(n){return i().warn(`Failed to parse object value "${t}" for input ${e}`,n),null}return null}}const _e=new Set([`System.Double`,`System.Single`,`System.Decimal`,`System.Int32`,`System.Int64`]),ve=new Set([`System.Int32`,`System.Int64`]);function O(e,t){return i().warn(t),{schema:{...e,default:null},warning:{code:n.MALFORMED_DEFAULT,message:t}}}function ye(t,a){if(typeof t.default!=`object`||t.default===null||Array.isArray(t.default)||C(t.default))return{schema:t};if(!r(t.default,`innerTree`))return O(t,`Input "${a}" default had an unrecognized shape (no innerTree key); the default was dropped.`);let o=e(t.default,`innerTree`)??{};if(Object.keys(o).length===0)return{schema:{...t,default:void 0}};if(t.treeAccess||t.atMost&&t.atMost>1){let r={},s=[];for(let[n,i]of Object.entries(o)){if(!Array.isArray(i))return O(t,`Input "${a}" default had a non-array innerTree branch ("${n}"); the default was dropped.`);let o=[];for(let t of i){let n=e(t,`data`),r=e(t,`type`);if(r&&_e.has(r)){if(typeof n==`string`&&n.trim()===``)continue;let e=T(n);if(e===null){s.push(`"${String(n)}" (${r})`);continue}o.push(ve.has(r)?Math.round(e):e);continue}if(r===`System.Boolean`){let e=E(n);if(e===null){s.push(`"${String(n)}" (${r})`);continue}o.push(e);continue}if(typeof n==`string`&&r?.startsWith(`Rhino.Geometry`)){try{o.push(JSON.parse(n))}catch{o.push(n)}continue}o.push(n)}x(r,n,o)}if(s.length>0){let e=`Input "${a}" default contained ${s.length} tree value(s) that could not be parsed and were dropped: ${s.join(`, `)}.`;return i().warn(e),{schema:{...t,default:r},warning:{code:n.MALFORMED_DEFAULT,message:e}}}return{schema:{...t,default:r}}}let s=[];for(let t of Object.values(o))if(Array.isArray(t))for(let n of t)n&&typeof n==`object`&&r(n,`data`)&&s.push(e(n,`data`));return{schema:{...t,default:s.length>1?s:s[0]}}}function be(e,t){let n=Number(e.toFixed(t));return Math.abs(e-n)<1e-8?n:e}function k(e){if(!Number.isFinite(e))return 0;let[t,n]=String(Math.abs(e)).split(`e`),r=n===void 0?Math.abs(e).toFixed(12).replace(/0+$/,``).split(`.`)[1]?.length??0:(t.split(`.`)[1]?.length??0)-Number(n);return Math.min(Math.max(r,0),12)}function xe(e){if(!Number.isFinite(e)||e===0)return .1;let t=k(e);return t===0?Math.abs(e)>=1?1:.1:Number((10**-t).toFixed(t))}function A(e){return typeof e.stepSize==`number`&&Number.isFinite(e.stepSize)&&e.stepSize>0?e.stepSize:void 0}const j=(e,t)=>(e.atMost??1)>1?[t]:t,M=e=>A(e)??(e.paramType===`Integer`?1:.1),N=(e,t)=>Array.isArray(e)?e.map(e=>typeof e==`number`?t(e):e):typeof e==`number`?t(e):e;function Se(e){if(C(e.default))return{default:e.default,stepSize:M(e)};if(typeof e.default==`string`&&e.default.trim()!==``&&T(e.default)===null)throw new t(`Invalid numeric default "${e.default}" for input "${e.name||`unknown`}"`,n.VALIDATION_ERROR,{context:{inputName:e.name,default:e.default}});let r=w(e.default,T,!0);if(e.paramType===`Integer`)return{default:N(r,Math.round),stepSize:M(e)};let i=Array.isArray(r)?r[0]:r,a=[i,e.minimum,e.maximum].find(e=>typeof e==`number`&&Number.isFinite(e)&&e!==0),o=A(e)??(a===void 0?.1:xe(a)),s=k(o);if(s===0&&typeof i==`number`&&i!==0&&Math.abs(i)<1){let e=Math.ceil(-Math.log10(Math.abs(i)));Number.isFinite(e)&&e>0&&(s=e)}return s=Math.min(Math.max(s,0),12),{default:N(r,e=>be(e,s)),stepSize:o}}const P={parse(e,t){let{default:n,stepSize:r}=Se(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=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:M(e),default:j(e,n)}}},Ce={parse(e,r){if(C(e.default))return{...r,paramType:`Boolean`,default:e.default};let i=w(e.default,E,!1);if(i!=null&&typeof i!=`boolean`&&!Array.isArray(i))throw new t(`Invalid boolean default "${String(i)}" for input "${e.name||`unknown`}"`,n.VALIDATION_ERROR,{context:{inputName:e.name,default:e.default}});return{...r,paramType:`Boolean`,default:i}},fallback(e,t){return{...t,paramType:`Boolean`,default:j(e,!1)}}},we={parse(e,t){let n=w(e.default,he,!1);return{...t,paramType:`Text`,default:n}}},Te={parse(e,r,a){if(!e.values||typeof e.values!=`object`||Object.keys(e.values).length===0){let r=e.nickname||`unnamed`;throw new t(`Input "${r}" has no values defined (expected ValueList)`,n.INVALID_INPUT,{context:{inputName:r,expectedType:`ValueList`}})}let o=e.default;if(e.default!==void 0&&e.default!==null){if(typeof e.default==`object`)throw new t(`ValueList input "${e.nickname||`unnamed`}" default is not a string-able value`,n.VALIDATION_ERROR,{context:{inputName:e.name,default:e.default}});let r=String(e.default).toLowerCase(),s=Object.keys(e.values).find(e=>e.toLowerCase()===r);if(s!==void 0)o=s;else{let t=`ValueList input "${e.nickname||`unnamed`}" default value "${e.default}" is not in available values`;i().warn(t),a?.({code:n.VALIDATION_ERROR,message:t})}}return{...r,paramType:`ValueList`,values:e.values,default:o}},fallback(e,t){return{...t,paramType:`ValueList`,values:e.values&&typeof e.values==`object`?e.values:{},default:void 0}}};function F(e,t){return{...t,paramType:`Geometry`,default:j(e,null)}}const I=new Map([[`Number`,P],[`Integer`,P],[`Boolean`,Ce],[`Text`,we],[`ValueList`,Te],[`Geometry`,{parse(e,t){let n=w(e.default,D(e.nickname||`unnamed`),!0);return{...t,paramType:`Geometry`,default:n}},fallback:F}],[`File`,{parse(e,t){let n=w(e.default,D(e.nickname||`unnamed`),!0);return{...t,paramType:`File`,acceptedFormats:e.acceptedFormats,default:n}}}],[`Color`,{parse(e,t){let n=w(e.default,ge,!1);return{...t,paramType:`Color`,default:n}}}]]),Ee=F,De=new Map([...I.keys()].map(e=>[e.toLowerCase(),e]));function Oe(e){return De.get(e?.toLowerCase())??e}function ke(e){return L(e).input}function L(e){let r=e.name||`unknown`,a=[],o=({code:t,message:n})=>{a.push({inputName:r,paramType:e.paramType,message:n,code:t})},s={description:e.description,name:e.name,nickname:e.nickname,treeAccess:e.treeAccess,groupName:e.groupName??void 0,id:e.id},c=Oe(e.paramType),l={...e,paramType:c};try{let{schema:e,warning:t}=ye(l,r);l=e,t&&o(t)}catch(e){l={...l,default:null},o({code:n.MALFORMED_DEFAULT,message:`Input "${r}" default could not be normalized and was dropped: ${e instanceof Error?e.message:String(e)}`})}let u=I.get(c);try{if(!u)throw new t(`Unknown paramType: ${c}`,n.VALIDATION_ERROR,{context:{receivedParamType:c,paramName:e.name}});return{input:u.parse(l,s,o),errors:a}}catch(d){if(!(d instanceof t))throw new t(d instanceof Error?d.message:String(d),n.VALIDATION_ERROR,{context:{paramName:e.name,paramType:c},originalError:d});return i().error(`Validation error for input ${r}:`,d.message),o(d),{input:(u?.fallback??Ee)(l,s),errors:a}}}function Ae(e){let t=[],n=[];for(let r of e){let{input:e,errors:i}=L(r);t.push(e),n.push(...i)}return{inputs:t,parseErrors:n}}function je(t){let n=e(t,`stepSize`);return{id:e(t,`id`)??``,name:e(t,`name`)??``,nickname:e(t,`nickname`)??null,description:e(t,`description`)??``,paramType:e(t,`paramType`)??``,treeAccess:e(t,`treeAccess`)??!1,minimum:e(t,`minimum`)??null,maximum:e(t,`maximum`)??null,atLeast:e(t,`atLeast`)??1,atMost:e(t,`atMost`)??1,stepSize:typeof n==`number`&&Number.isFinite(n)?n:void 0,default:e(t,`default`),values:e(t,`values`),acceptedFormats:e(t,`acceptedFormats`),groupName:e(t,`groupName`)??null}}function Me(t){return{name:e(t,`name`)??``,nickname:e(t,`nickname`)??null,paramType:e(t,`paramType`)??``,id:e(t,`id`)??``}}async function R(r,i){y(`fetchDefinitionIO`,i.suppressBrowserWarning),h(i.serverUrl);let{algo:a,pointer:o}=b(r,[]);if(!a&&!o)throw new t(`Definition must resolve to either a URL pointer or base64 algo`,n.INVALID_INPUT);let s=await d(`io`,a?{algo:a}:{pointer:o},oe(i));if(!s||typeof s!=`object`)throw new t(`Invalid IO response structure`,n.INVALID_INPUT,{context:{response:s}});let c=z(e(s,`warnings`)),l=z(e(s,`errors`)),u=e(s,`inputs`),f=e(s,`outputs`);return{inputs:Array.isArray(u)?u.map(je):[],outputs:Array.isArray(f)?f.map(Me):[],...c&&{loadWarnings:c},...l&&{loadErrors:l}}}function z(e){if(!Array.isArray(e))return;let t=e.map(Ne).filter(e=>e!==void 0);return t.length>0?t:void 0}function Ne(t){if(t==null)return;let n;if(typeof t==`string`)n=t;else if(typeof t==`object`){let r=e(t,`message`);if(typeof r==`string`&&r.trim().length>0)n=r;else try{n=JSON.stringify(t)??String(t)}catch{n=String(t)}}else n=String(t);return n.trim().length>0?n:void 0}async function B(e,t){let{inputs:n,outputs:r,loadWarnings:i,loadErrors:a}=await R(e,t),{inputs:o,parseErrors:s}=Ae(n);return{inputs:o,outputs:r,...s.length>0&&{parseErrors:s},...i&&{loadWarnings:i},...a&&{loadErrors:a}}}const V=globalThis.process?.getBuiltinModule?.(`node:crypto`);function H(e){if(V){let t=V.createHash(`sha256`);return typeof e==`string`?t.update(e,`utf16le`):t.update(e),t.digest(`hex`)}return Fe(e)}const Pe=new Int32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function Fe(e){let t=new Ie;return typeof e==`string`?t.updateString(e):t.update(e),t.digestHex()}var Ie=class{h=new Int32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);w=new Int32Array(64);pending=new Uint8Array(64);pendingLength=0;totalBytes=0;update(e){this.totalBytes+=e.length;let t=0;if(this.pendingLength>0){let n=Math.min(64-this.pendingLength,e.length);if(this.pending.set(e.subarray(0,n),this.pendingLength),this.pendingLength+=n,t=n,this.pendingLength<64)return;this.compressBytes(this.pending,0),this.pendingLength=0}for(;t+64<=e.length;t+=64)this.compressBytes(e,t);this.pending.set(e.subarray(t),0),this.pendingLength=e.length-t}updateString(e){let t=this.w,n=e.length-e.length%32;for(let r=0;r<n;r+=32){for(let n=0;n<16;n++){let i=e.charCodeAt(r+2*n),a=e.charCodeAt(r+2*n+1);t[n]=(i&255)<<24|i>>>8<<16|(a&255)<<8|a>>>8}this.compress()}this.totalBytes+=n*2;let r=new Uint8Array((e.length-n)*2);for(let t=n,i=0;t<e.length;t++){let n=e.charCodeAt(t);r[i++]=n&255,r[i++]=n>>>8}this.update(r)}digestHex(){let e=this.totalBytes*8,t=new Uint8Array(this.pendingLength<56?64:128);t.set(this.pending.subarray(0,this.pendingLength)),t[this.pendingLength]=128;let n=new DataView(t.buffer);n.setUint32(t.length-8,Math.floor(e/4294967296)),n.setUint32(t.length-4,e>>>0);for(let e=0;e<t.length;e+=64)this.compressBytes(t,e);let r=``;for(let e of this.h)r+=(e>>>0).toString(16).padStart(8,`0`);return r}compressBytes(e,t){let n=this.w;for(let r=0;r<16;r++){let i=t+r*4;n[r]=e[i]<<24|e[i+1]<<16|e[i+2]<<8|e[i+3]}this.compress()}compress(){let e=this.w;for(let t=16;t<64;t++){let n=e[t-15],r=e[t-2],i=(n>>>7|n<<25)^(n>>>18|n<<14)^n>>>3,a=(r>>>17|r<<15)^(r>>>19|r<<13)^r>>>10;e[t]=e[t-16]+i+e[t-7]+a|0}let t=this.h,n=t[0],r=t[1],i=t[2],a=t[3],o=t[4],s=t[5],c=t[6],l=t[7];for(let t=0;t<64;t++){let u=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),d=o&s^~o&c,f=l+u+d+Pe[t]+e[t]|0,p=((n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10))+(n&r^n&i^r&i)|0;l=c,c=s,s=o,o=a+f|0,a=i,i=r,r=n,n=f+p|0}t[0]=t[0]+n|0,t[1]=t[1]+r|0,t[2]=t[2]+i|0,t[3]=t[3]+a|0,t[4]=t[4]+o|0,t[5]=t[5]+s|0,t[6]=t[6]+c|0,t[7]=t[7]+l|0}};function U(e){let t=new WeakSet,n=e=>{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(typeof e!=`object`)return`undefined`;if(e instanceof Uint8Array)return`{u8:${H(e)}}`;if(t.has(e))return`[Circular]`;t.add(e);let r;if(Array.isArray(e)){let t=[];for(let r=0;r<e.length;r++)t.push(n(e[r]));r=`[${t.join(`,`)}]`}else 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(`,`)}}`;return t.delete(e),r};return n(e)}function Le(e,t){return W(G(e),t)}function W(e,t){return`${e}|t:${H(U(t))}`}function G(e){return m(e)?`r:${e.key}`:typeof e==`string`?`s:${H(e)}`:`u8:${H(e)}`}const K=new WeakMap;function Re(e){if(!(e instanceof Uint8Array))return G(e);let t=K.get(e);return t===void 0&&(t=G(e),K.set(e,t)),t}var ze=class{hashDefinition;dataTree;definitionMemo;keyMemo;constructor(e,t){this.hashDefinition=e,this.dataTree=t}get definitionHash(){return this.definitionMemo??=this.hashDefinition()}get key(){return this.keyMemo??=W(this.definitionHash,this.dataTree)}},Be=class{items=[];head=0;live=new Set;get size(){return this.live.size}push(e){this.items.push(e),this.live.add(e)}remove(e){this.live.delete(e)&&this.compact()}shift(){for(;this.head<this.items.length;){let e=this.items[this.head];if(this.items[this.head++]=void 0,e&&this.live.delete(e))return this.compact(),e}}compact(){if(this.live.size===0){this.items=[],this.head=0;return}let e=this.items.length-this.live.size;e<=64||e<=this.live.size||(this.items=this.items.filter(e=>e!==void 0&&this.live.has(e)),this.head=0)}};function Ve(e){try{return JSON.stringify(e)?.length??0}catch{return 0}}var He=class{executor;baseConfig;mode;maxConcurrent;maxQueueDepth;queueWaitMs;timeoutMs;retry;cacheEnabled;cacheMaxBytes;cacheTtl;cacheErroredSolves;cache=new Map;cacheBytes=0;cacheHits=0;cacheMisses=0;cacheEvictions=0;reuseServerDefinitionCache;serverCacheKeys=new Map;lastStringDefinition=null;onStart;onSettle;onSuperseded;subscribers=new Set;inFlight=new Set;pendingForLatestWins=null;fifo=new Be;_lastResult=null;_lastError=null;_lastDurationMs=null;solveSeq=0;lastStateSeq=0;disposed=!1;constructor(e,r,i={}){if(this.executor=e,this.baseConfig=r,this.mode=i.mode??`latest-wins`,this.mode!==`latest-wins`&&this.mode!==`queue`)throw new t(`Unknown scheduler mode '${String(this.mode)}'. For concurrent solves use { mode: 'queue', maxConcurrent: 4 }.`,n.INVALID_CONFIG,{context:{mode:this.mode}});this.maxConcurrent=Math.max(1,i.maxConcurrent??1),this.maxQueueDepth=i.maxQueueDepth!==void 0&&i.maxQueueDepth>0?Math.floor(i.maxQueueDepth):void 0,this.queueWaitMs=i.queueWaitMs!==void 0&&i.queueWaitMs>0?i.queueWaitMs:void 0,this.timeoutMs=i.timeoutMs,this.retry=i.retry;let a=i.cache,o=typeof a==`object`?a:null;this.cacheMaxBytes=Math.max(0,o?.maxBytes??0),this.cacheEnabled=this.cacheMaxBytes>0,this.cacheTtl=o?.ttlMs??0,this.cacheErroredSolves=o?.cacheErroredSolves??!0,this.reuseServerDefinitionCache=i.reuseServerDefinitionCache??!0,this.onStart=i.onStart,this.onSettle=i.onSettle,this.onSuperseded=i.onSuperseded}get isSolving(){return this.inFlight.size>0}get hasPending(){return this.pendingForLatestWins!==null||this.fifo.size>0}get inFlightCount(){return this.inFlight.size}get queueDepth(){return this.fifo.size+ +!!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){i().error(`[SolveScheduler] subscriber threw:`,e)}}solve(e,t,n){return this.solveDetailed(e,t,n).then(e=>e.response)}solveDetailed(e,r,i){if(this.disposed)return Promise.reject(new t(`SolveScheduler has been disposed and cannot be used`,n.INVALID_STATE));let a=new ze(()=>this.hashDefinitionMemo(e),r),o=``;if(this.cacheEnabled||this.onStart||this.onSettle||this.onSuperseded)try{o=a.key}catch(e){return Promise.reject(new t(`Solve input could not be hashed`,n.INVALID_INPUT,{originalError:e}))}let s=++this.solveSeq,c={key:o,enqueuedAt:Date.now(),startedAt:null};if(i?.signal?.aborted)return Promise.reject(this.makeAbortError(c));let l=this.readCache(o);if(l){this.mode===`latest-wins`&&this.supersedeCurrent();let e={status:`success`,response:l,durationMs:0,fromCache:!0};return this.writeLastState(s,{result:l,durationMs:0}),this.runHook(this.onStart,c),this.runHook(this.onSettle,c,e),this.notify(),Promise.resolve({response:l,fromCache:!0,durationMs:0})}return new Promise((t,n)=>{let o={definition:e,dataTree:r,hashes:a,ctx:c,seq:s,resolve:t,reject:n,externalSignal:i?.signal,selvaevents:i?.selvaevents,onServerTiming:i?.onServerTiming};o.externalSignal&&(o.queuedAbortHandler=()=>this.abortQueuedItem(o),o.externalSignal.addEventListener(`abort`,o.queuedAbortHandler,{once:!0})),this.enqueue(o)})}writeLastState(e,t){e<this.lastStateSeq||(this.lastStateSeq=e,`result`in t?(this._lastResult=t.result,this._lastError=null):this._lastError=t.error,this._lastDurationMs=t.durationMs)}supersedeCurrent(){this.pendingForLatestWins&&=(this.supersede(this.pendingForLatestWins),null);for(let e of this.inFlight)this.supersede(e),e.controller.abort()}dequeue(e){this.pendingForLatestWins===e&&(this.pendingForLatestWins=null),this.fifo.remove(e)}abortQueuedItem(e){this.dequeue(e),this.fail(e,this.makeAbortError(e.ctx)),this.notify()}shedAsQueueFull(e){let r=new t(`Solve queue is full; request rejected (backpressure)`,n.QUEUE_FULL,{statusCode:503,context:{queueDepth:this.fifo.size,maxQueueDepth:this.maxQueueDepth}});this.fail(e,r),this.notify()}armQueueWaitTimer(e){if(this.queueWaitMs===void 0)return;let r=this.queueWaitMs;e.queueWaitTimer=setTimeout(()=>{if(e.settled)return;this.dequeue(e);let i=new t(`Solve waited longer than ${r}ms in queue; rejected (backpressure)`,n.QUEUE_TIMEOUT,{statusCode:503,context:{waitedMs:Date.now()-e.ctx.enqueuedAt,queueWaitMs:r}});this.fail(e,i),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`:this.inFlight.size<this.maxConcurrent?this.execute(e):this.maxQueueDepth!==void 0&&this.fifo.size>=this.maxQueueDepth?this.shedAsQueueFull(e):(this.armQueueWaitTimer(e),this.fifo.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},...e.selvaevents!==void 0&&{selvaevents:e.selvaevents}},r=e.onServerTiming;if(r){let e=this.baseConfig.onServerTiming;n.onServerTiming=(t,n)=>{try{e?.(t,n)}finally{r(t,n)}}}let{response:a,definitionReuploaded:o}=await this.runExecutor(e,n),s=performance.now()-i;if(this.writeCache(e.ctx.key,a),!this.settleSuccess(e,{response:a,fromCache:!1,definitionReuploaded:o,durationMs:s}))return;this.writeLastState(e.seq,{result:a,durationMs:s}),this.runHook(this.onSettle,e.ctx,{status:`success`,response:a,durationMs:s,fromCache:!1,definitionReuploaded:o})}catch(t){let r=performance.now()-i,a=this.normalizeExecutionError(t,n);this.writeLastState(e.seq,{error:a,durationMs:r}),this.fail(e,a,r)}finally{e.externalSignal?.removeEventListener(`abort`,r),this.inFlight.delete(n),this.drainNext(),this.notify()}}async runExecutor(e,t){let{definition:n,dataTree:r}=e;if(!this.reuseServerDefinitionCache||o(n)){let{response:e}=await this.executor(n,r,null,t);return{response:e}}let i=e.hashes.definitionHash,a=this.serverCacheKeys.get(i)??null,s=await this.executor(n,r,a,t);return this.serverCacheKeys.delete(i),s.cacheKey&&(this.serverCacheKeys.set(i,s.cacheKey),this.serverCacheKeys.size>100&&this.serverCacheKeys.delete(this.serverCacheKeys.keys().next().value)),{response:s.response,definitionReuploaded:s.missed}}hashDefinitionMemo(e){return typeof e==`string`?(this.lastStringDefinition?.value!==e&&(this.lastStringDefinition={value:e,hash:G(e)}),this.lastStringDefinition.hash):Re(e)}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.fifo.size>0&&this.inFlight.size<this.maxConcurrent;)this.execute(this.fifo.shift())}}supersede(e){let r=new t(`Superseded by newer solve`,n.SUPERSEDED,{context:{enqueuedAt:e.ctx.enqueuedAt}});this.settleError(e,r)&&this.runHook(this.onSuperseded,e.ctx)}makeAbortError(e){return new t(`Request aborted by caller`,n.ABORTED,{context:{enqueuedAt:e.enqueuedAt}})}settleError(e,t){return!e.settled&&(e.settled={error:t},this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e),e.reject(t),!0)}fail(e,t,n=0){this.settleError(e,t)&&this.runHook(this.onSettle,e.ctx,{status:`error`,error:t,durationMs:n})}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}normalizeExecutionError(e,r){return r.settled&&`error`in r.settled?r.settled.error:e instanceof t?e:e instanceof Error&&e.name===`AbortError`?this.makeAbortError(r.ctx):new t(e instanceof Error?e.message:String(e),n.UNKNOWN_ERROR,{originalError:e})}cancelAll(){this.pendingForLatestWins&&=(this.fail(this.pendingForLatestWins,this.makeAbortError(this.pendingForLatestWins.ctx)),null);for(let e=this.fifo.shift();e;e=this.fifo.shift())this.fail(e,this.makeAbortError(e.ctx));for(let e of this.inFlight){let t=e.ctx.startedAt?Date.now()-e.ctx.startedAt:0;this.fail(e,this.makeAbortError(e.ctx),t),e.controller.abort()}this.notify()}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(t,n){if(!this.cacheEnabled)return;let r=e(n,`errors`);if(!this.cacheErroredSolves&&Array.isArray(r)&&r.length>0)return;let i=c(n)??Ve(n);if(!(i>this.cacheMaxBytes))for(this.dropCacheEntry(t),this.cache.set(t,{response:n,insertedAt:Date.now(),sizeBytes:i}),this.cacheBytes+=i;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){i().error(`[SolveScheduler] hook threw:`,e)}}};function Ue(e){return m(e)?`ref:${e.key}`:typeof e==`string`&&e.length<200?e:`...content...`}function We(t){return Array.isArray(t)?t.map(t=>{let n=0,r=0,i=e(t,`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:e(t,`paramName`)??`<unnamed>`,items:n,bytes:r}}):[]}var Ge=class r{config;serverStats;disposed=!1;static CREATE_PROBE_TIMEOUT_MS=2e3;constructor(e){this.config={...e,serverUrl:h(e.serverUrl),debug:e.debug??!1},this.serverStats=new g(this.config.serverUrl,this.config)}static async create(e,i={}){let a=new r(e),o=Math.max(1,(i.probe?.attempts??2)+1),s=i.probe?.baseDelayMs??250,c=i.probe?.maxDelayMs??1e3,l,u=null,d=0;for(let e=0;e<o;e++){if(d=e+1,l=await a.serverStats.probeServer(r.CREATE_PROBE_TIMEOUT_MS),l.online)return a;if(u=te(l),u&&!u.retryable)break;if(e<o-1){let t=Math.min(s*2**e,c);await new Promise(e=>setTimeout(e,t))}}await a.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,n.NETWORK_ERROR,{...f!==void 0&&{statusCode:f},context:{serverUrl:a.config.serverUrl,attempts:d,maxAttempts:o,...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(),B(e,this.config)}async getRawIO(e){return this.ensureNotDisposed(),R(e,this.config)}async solve(r,a,o){this.ensureNotDisposed();try{if(typeof r==`string`&&!r.trim())throw new t(`Definition URL/content is required`,n.INVALID_INPUT,{context:{receivedUrl:r}});if(r instanceof Uint8Array&&r.length===0)throw new t(`Definition content is empty`,n.INVALID_INPUT);if(m(r)&&!r.key.trim())throw new t(`DefinitionRef key is empty`,n.INVALID_INPUT);let i=await le(a,r,{...this.config,...o?.signal!==void 0&&{signal:o.signal},...o?.timeoutMs!==void 0&&{timeoutMs:o.timeoutMs},...o?.retry!==void 0&&{retry:o.retry},...o?.selvaevents!==void 0&&{selvaevents:o.selvaevents}}),s=e(i,`errors`);if(Array.isArray(s)&&s.length>0)throw new t(s.map(String).join(`; `)||`Computation failed`,n.COMPUTATION_ERROR,{context:{definition:Ue(r),inputSummary:We(a),errors:s,warnings:e(i,`warnings`),values:i.values}});return i}catch(e){throw this.config.debug&&i().error(`Compute failed:`,e),e instanceof t?e:new t(e instanceof Error?e.message:String(e),n.COMPUTATION_ERROR,{context:{definition:Ue(r),inputSummary:We(a)},originalError:e})}}createScheduler(e){return this.ensureNotDisposed(),new He((e,t,n,r)=>ue(t,n,e,r),this.config,e)}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`,n.INVALID_STATE)}};function Ke(e){return typeof e==`object`&&!!e&&e.__decodeError===!0}function qe(e,t){return{__decodeError:!0,type:e,raw:t}}function Je(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 q=new Map([[`Rhino.Geometry.Point3d`,(e,t)=>{let n=t;return!n||typeof n.X!=`number`?null:new e.Point([n.X,n.Y,n.Z])}],[`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 Ye(e){if(q.has(e))return q.get(e);for(let[t,n]of q)if(e.startsWith(t))return n}function Xe(e){return!!(e&&typeof e==`object`&&typeof e.data==`string`)}function Ze(e,t,n){let r=Ye(t),a=!1;if(r)try{let t=r(n,e);if(t!=null)return t}catch(e){i().warn(`Failed to decode Rhino type ${t}:`,e),a=!0}try{if(Xe(e))return n.CommonObject.decode(e)}catch(n){return i().warn(`Failed to decode ${t} with CommonObject:`,n),qe(t,e)}return a?qe(t,e):e}const J={STRING:`System.String`,INT:`System.Int32`,DOUBLE:`System.Double`,BOOL:`System.Boolean`},Qe=`FileData`;function $e(e,t){return e.includes(`WebDisplay`)||t&&e!==J.STRING}function et(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 tt(e,t,n){switch(t){case J.STRING:return typeof e==`string`?e.replace(/^"(.*)"$/,`$1`):e;case J.INT:return Number.parseInt(String(e),10);case J.DOUBLE:return Number.parseFloat(String(e));case J.BOOL:return String(e).toLowerCase()===`true`;default:return n&&t.startsWith(`Rhino.Geometry.`)?Ze(e,t,n):e}}function Y(e,t,n,r){if(typeof e.data!=`string`)return e.data;let i=n?et(e.data):e.data;return n&&t.includes(Qe)?nt(i)??i:tt(i,t,r)}function nt(t){if(!t||typeof t!=`object`)return null;let n=e(t,`fileName`),i=e(t,`fileType`),a=e(t,`subFolder`),o=e(t,`isBase64Encoded`);if(typeof n!=`string`||typeof i!=`string`||typeof a!=`string`||!r(t,`data`)||typeof o!=`boolean`&&typeof o!=`string`)return null;let s=e(t,`metadata`);return{fileName:n,fileType:i,data:e(t,`data`),isBase64Encoded:u(o),subFolder:a,...s?{metadata:s}:{}}}function X(t){let n=e(t,`values`);return Array.isArray(n)?n:[]}function Z(e){return typeof e.type==`string`?e.type:``}function Q(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 rt(t,n=!1,r={}){let{parseValues:i=!0,rhino:a,stringOnly:o=!1}=r,s={},c=new Set;for(let r of X(t)){let t=e(r,`paramName`);Q(e(r,`innerTree`),e=>{let r=Z(e);if($e(r,o))return;let l=n?e.id:t;if(!l)return;let u=Y(e,r,i,a);Object.prototype.hasOwnProperty.call(s,l)?c.has(l)?s[l].push(u):(s[l]=[s[l],u],c.add(l)):x(s,l,u)})}return{values:s,dispose:()=>Je(s)}}function it(t){let n=[];for(let r of X(t))Q(e(r,`innerTree`),e=>{if(!Z(e).includes(Qe))return;let t=nt(et(e.data));t&&n.push(t)});return n}function at(t,n,r={}){let{parseValues:i=!0,rhino:a,stringOnly:o=!1}=r;for(let r of X(t)){let t=e(r,`innerTree`),s=!1;if(`byName`in n){if(e(r,`paramName`)!==n.byName)continue;s=!0}let c=[];if(Q(t,e=>{if(`byId`in n){if(e.id!==n.byId)return;s=!0}let t=Z(e);$e(t,o)||c.push(Y(e,t,i,a))}),s)return c.length===0?void 0:c.length===1?c[0]:c}}var ot=class{response;constructor(e){this.response=e}getValues(e=!1,t={}){return rt(this.response,e,t)}getValue(e,t){return at(this.response,e,t)}async getAndDownloadFiles(e,t){await ee(it(this.response),e,t)}};function st(t){return(Array.isArray(t)?t:[t]).map(t=>({schemas:e(t,`schemas`),error:e(t,`error`)}))}const ct=new Set([`options`,`defaultOptions`,`values`]),lt=new Set([`optionMedia`,`assets`]),ut=e=>e>=`A`&&e<=`Z`;function dt(e){if(e.length===0||!ut(e[0]))return e;let t=0;for(;t<e.length&&ut(e[t]);)t++;return t>1&&t<e.length&&t--,e.slice(0,t).toLowerCase()+e.slice(t)}function ft(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=dt(n);x(t,e,ct.has(e)?r:lt.has(e)?pt(r):$(r))}return t}function pt(e){if(typeof e!=`object`||!e||Array.isArray(e))return e;let t={};for(let[n,r]of Object.entries(e))x(t,n,$(r));return t}var mt=class r{innerTree;paramName;constructor(e){this.paramName=e,this.innerTree={}}append(e,t){let n=this.innerTree[r.formatPathString(e)]??=[];for(let e of t)n.push({data:r.serializeValue(e)});return this}fromDataTreeDefault(e){this.innerTree={};for(let[t,n]of Object.entries(e)){if(!Array.isArray(n))continue;let e=r.parsePathString(t);this.append(e,n)}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 n of t)e.push(r.deserializeValue(n.data));return e}toComputeFormat(){return{ParamName:this.paramName,InnerTree:this.innerTree}}getParamName(){return this.paramName}static fromInputParams(e){return r.fromValues(e.map(e=>({paramName:e.nickname||`unnamed`,paramType:e.paramType,value:e.default,...`minimum`in e&&{minimum:e.minimum,maximum:e.maximum}})))}static fromValues(e){let t=[];for(let n of e){let e=new r(n.paramName),a=r.itemCoercer(n);for(let[t,o]of r.branchesOf(n.value)){let r=[];for(let e of o){if(e==null)continue;let t=a(e);t===null?i().warn(`${n.paramName}: dropped an item that is not a valid ${n.paramType}`):r.push(t)}r.length>0&&e.append(t,r)}Object.keys(e.innerTree).length>0&&t.push(e.toComputeFormat())}return t}static branchesOf(e){return r.hasValidValue(e)?C(e)?Object.entries(e).map(([e,t])=>[r.parsePathString(e),t]):[[[0],Array.isArray(e)?e:[e]]]:[]}static itemCoercer(e){let{paramName:t,minimum:n,maximum:i}=e,a=e.paramType.toLowerCase();return a===`number`||a===`integer`?e=>{let o=T(e);if(o===null)return null;let s=a===`integer`?Math.round(o):o;return r.clampValue(s,n,i,t)}:a===`boolean`?E:e=>e}static replaceTreeValue(e,t,n){let i=r.buildFromValue(t,n).toComputeFormat(),a=e.slice(),o=a.findIndex(e=>r.paramNameOf(e)===t);return o===-1?a.push(i):a[o]=i,a}static buildFromValue(e,t){let n=new r(e);return C(t)?n.fromDataTreeDefault(t):n.appendFlat(t),n}static getTree(t,n){let i=t.find(e=>r.paramNameOf(e)===n);if(!i)return null;let a=new Map,o=e(i,`InnerTree`);if(!o||typeof o!=`object`)return a;for(let[e,t]of Object.entries(o))Array.isArray(t)&&a.set(e,t.map(e=>e?.data===void 0?null:r.deserializeValue(e.data)));return a}static getTreeValue(e,i){let a=r.getTree(e,i);if(!a||a.size===0)return null;if(a.size>1)throw new t(`"${i}" has ${a.size} branches; read it with TreeBuilder.getTree`,n.INVALID_INPUT,{context:{paramName:i,branchCount:a.size}});let[o]=a.values();return o.length===0?null:o.length===1?o[0]:o}static paramNameOf(t){return e(t,`ParamName`)}static parsePathString(e){let r=e.match(S);if(!r)throw new t(`Invalid Grasshopper tree path: "${e}". Expected "{}", "{0}", or "{0;1;2}" (negative indices allowed, no empty segments).`,n.INVALID_INPUT,{context:{pathStr:e}});return r[1]?r[1].split(`;`).map(Number):[]}static formatPathString(e){return`{${e.join(`;`)}}`}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!=`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 clampValue(e,t,n,r){let a=e;return t!=null&&a<t&&(i().warn(`${r}: ${e} below min ${t}, clamping`),a=t),n!=null&&a>n&&(i().warn(`${r}: ${e} above max ${n}, clamping`),a=n),a}};export{g as ComputeServerStats,Ge as GrasshopperClient,ot as GrasshopperResponseProcessor,He as SolveScheduler,mt as TreeBuilder,Je as disposeRhinoObjects,R as fetchDefinitionIO,B as fetchParsedDefinitionIO,G as hashDefinition,Le as hashSolveInput,Ke as isRhinoDecodeError,ft as normalizeUISchemaCasing,ke as processInput,st as readSchemaResults,le as solveGrasshopperDefinition,U as stableStringify};
|
|
2
2
|
//# sourceMappingURL=grasshopper.js.map
|