@selvajs/compute 5.0.0-beta.6 → 5.0.0-beta.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./core-DF0VYOve.cjs");var t=class t{serverUrl;headers;disposed=!1;activeMonitors=/* @__PURE__ */ 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(t,n){this.serverUrl=e.x(t),this.headers={...e.y(typeof n==`string`?{apiKey:n}:n??{}),"Content-Type":`application/json`}}fetchWithTimeout(e,n={},r=t.DEFAULT_TIMEOUT_MS){let i={...n,headers:this.headers,redirect:`manual`};return r>0&&!i.signal&&(i.signal=AbortSignal.timeout(r)),fetch(e,i)}async getText(n,r={},i=t.DEFAULT_TIMEOUT_MS){this.ensureNotDisposed();let a=`${r.method??`GET`} ${n}`;try{let o=await this.fetchWithTimeout(`${this.serverUrl}${n}`,r,i);if(!o.ok)return e.T().warn(`[ComputeServerStats] ${a} failed:`,o.status),await o.body?.cancel().catch(()=>{}),null;let{text:s,truncated:c}=await e.m(o,t.MAX_BODY_BYTES);return c?(e.T().warn(`[ComputeServerStats] ${a} answered with an oversized body`),null):s}catch(t){return e.T().warn(`[ComputeServerStats] ${a} errored:`,t),null}}async isServerOnline(e=t.DEFAULT_TIMEOUT_MS){return(await this.probeServer(e)).online}async probeServer(n=t.DEFAULT_TIMEOUT_MS){this.ensureNotDisposed();let r=`${this.serverUrl}/`;try{let t=await this.fetchWithTimeout(r,{method:`GET`},n);return await t.body?.cancel().catch(()=>{}),{online:t.ok||e.d(t),status:t.status}}catch(t){return e.T().debug(`[ComputeServerStats] Fetch error:`,t),{online:!1,error:t instanceof Error?`${t.name}: ${t.message}`:String(t)}}}async getActiveChildren(n={}){let{initialize:r=!0}=n,i=r?await this.getText(`/activechildren`,{},t.LIFECYCLE_TIMEOUT_MS):await this.getText(`/activechildren?initialize=false`);if(i===null)return null;let a=i.trim();return/^\d+$/.test(a)?parseInt(a,10):(e.T().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=n(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`),r=t===null?void 0:n(t);return r&&typeof r==`object`?r: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:n(e))?.purged;return typeof t==`number`?t:null}async purgeAllChildren(){this.ensureNotDisposed();let t=await this.getActiveChildren({initialize:!1});if(t===null)return e.T().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 r=await this.getText(e,{method:`POST`},t.LIFECYCLE_TIMEOUT_MS);return r===null?null:n(r)??null}monitor(n,r=5e3){if(this.ensureNotDisposed(),!Number.isFinite(r)||r<t.MIN_MONITOR_INTERVAL_MS)throw new e.D(`monitor() intervalMs must be a finite number >= ${t.MIN_MONITOR_INTERVAL_MS}ms, got ${r}. Sub-${t.MIN_MONITOR_INTERVAL_MS}ms polling would hot-loop the server.`,e.O.INVALID_CONFIG,{context:{intervalMs:r}});let i=!0,a=null;e.T().info(`🔄 Starting server stats monitoring every ${r}ms`);let o=async()=>{if(a=null,i&&!this.disposed){try{let t=await this.getServerStats();if(!i||this.disposed)return;try{n(t)}catch(t){e.T().error(`[ComputeServerStats] Monitor callback threw:`,t)}}catch(t){!i||this.disposed?e.T().debug(`[ComputeServerStats] Monitor poll cancelled during shutdown:`,t):e.T().error(`[ComputeServerStats] Failed to fetch stats during monitor:`,t)}i&&!this.disposed&&(a=setTimeout(()=>void o(),r))}},s=()=>{i=!1,a!==null&&(clearTimeout(a),a=null),this.activeMonitors.delete(s)};return this.activeMonitors.add(s),o(),s}async dispose(){if(!this.disposed){this.disposed=!0;for(let e of this.activeMonitors)e();this.activeMonitors.clear()}}ensureNotDisposed(){if(this.disposed)throw new e.D(`ComputeServerStats has been disposed and cannot be used`,e.O.INVALID_STATE)}};function n(e){try{return JSON.parse(e)}catch{return}}const r=/* @__PURE__ */ new Set;function i(){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 a(t,n){n||i()&&!r.has(t)&&(r.add(t),e.T().warn(`Warning: ${t} is running on the client side. For better performance and security, consider running this on the server side.`))}const o={definition_not_cached:e.O.DEFINITION_NOT_CACHED};function s(e){return{...e,serverErrorCodes:{...o,...e.serverErrorCodes}}}function c(t){return t instanceof e.D?t.code===e.O.DEFINITION_NOT_CACHED||t.message.includes(`Unable to load grasshopper definition`):!1}function l(t,n){if(!n)return;let r=e.C(t,`values`);if(!Array.isArray(r)||r.length===0)return;let i=[];for(let t of r){let n=e.C(t,`innerTree`);n&&Object.keys(n).length!==0||i.push(e.C(t,`paramName`)??`<unnamed>`)}if(i.length===0)return;let a=i.length===r.length?`all`:`${i.length}/${r.length}`;e.T().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 u(e,t,n){return a(`solveGrasshopperDefinition`,n.suppressBrowserWarning),(await f(e,t,n)).response}async function d(e,t,n,r){if(a(`solveWithServerCacheKey`,r.suppressBrowserWarning),t!==null)try{return{...await m({algo:null,pointer:t,values:e},r),missed:!1}}catch(e){if(!c(e))throw e}return{...await f(e,n,r),missed:!0}}async function f(e,t,n){return m(h(await p(t),e),n)}async function p(t){if(!e.s(t))return t;try{return await t.load()}catch(n){throw new e.D(`Failed to load definition bytes for ref '${t.key}'`,e.O.INVALID_INPUT,{context:{definitionKey:t.key},originalError:n})}}async function m(t,n){e.x(n.serverUrl),ee(t,n);let{maxResponseBytes:r}=n,i=await e.l(`grasshopper`,t,s({...n,maxResponseBytes:r!==void 0&&t.algo?r+t.algo.length:r})),{pointer:a,algo:o,...c}=i,u=c,d=e.f(i);if(d!==void 0){let t=typeof o==`string`?o.length:0;e.p(u,Math.max(0,d-t))}return l(u,n.debug),{response:u,cacheKey:typeof a==`string`?a:null}}function h(t,n){let r={algo:null,pointer:null,values:n};return t instanceof Uint8Array?r.algo=e.h(t):e.c(t)?r.pointer=t:r.algo=e._(t)??e.v(t),r}function ee(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 g(e,t,n){t===`__proto__`?Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0}):e[t]=n}const _=/^\{(-?\d+(?:;-?\d+)*)?\}$/;function v(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.entries(e);return t.length>0&&t.every(([e,t])=>_.test(e)&&Array.isArray(t))}function y(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 b=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},x=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},te=e=>typeof e==`string`?e.length>=2&&e.startsWith(`"`)&&e.endsWith(`"`)?e.slice(1,-1):e.startsWith(`"`)?e.slice(1):e:null,ne=e=>{if(typeof e==`string`){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)&&(t=t.slice(1,-1).trim()),t}return null};function S(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.T().warn(`Parsed value for input ${t} is not an object`),null)}catch(r){return e.T().warn(`Failed to parse object value "${n}" for input ${t}`,r),null}return null}}const re=/* @__PURE__ */ new Set([`System.Double`,`System.Single`,`System.Decimal`,`System.Int32`,`System.Int64`]),ie=/* @__PURE__ */ new Set([`System.Int32`,`System.Int64`]);function ae(t,n){return e.T().warn(n),{schema:{...t,default:null},warning:{code:e.O.MALFORMED_DEFAULT,message:n}}}function oe(t,n){if(typeof t.default!=`object`||t.default===null||Array.isArray(t.default)||v(t.default))return{schema:t};if(!e.S(t.default,`innerTree`))return ae(t,`Input "${n}" default had an unrecognized shape (no innerTree key); the default was dropped.`);let r=e.C(t.default,`innerTree`)??{};if(Object.keys(r).length===0)return{schema:{...t,default:void 0}};if(t.treeAccess||t.atMost&&t.atMost>1){let i={},a=[];for(let[o,s]of Object.entries(r)){if(!Array.isArray(s))return ae(t,`Input "${n}" default had a non-array innerTree branch ("${o}"); the default was dropped.`);let r=[];for(let t of s){let n=e.C(t,`data`),i=e.C(t,`type`);if(i&&re.has(i)){if(typeof n==`string`&&n.trim()===``)continue;let e=b(n);if(e===null){a.push(`"${String(n)}" (${i})`);continue}r.push(ie.has(i)?Math.round(e):e)}else if(i===`System.Boolean`){let e=x(n);if(e===null){a.push(`"${String(n)}" (${i})`);continue}r.push(e)}else if(typeof n==`string`&&i?.startsWith(`Rhino.Geometry`))try{r.push(JSON.parse(n))}catch{r.push(n)}else r.push(n)}g(i,o,r)}if(a.length>0){let r=`Input "${n}" default contained ${a.length} tree value(s) that could not be parsed and were dropped: ${a.join(`, `)}.`;return e.T().warn(r),{schema:{...t,default:i},warning:{code:e.O.MALFORMED_DEFAULT,message:r}}}return{schema:{...t,default:i}}}let i=[];for(let t of Object.values(r))if(Array.isArray(t))for(let n of t)n&&typeof n==`object`&&e.S(n,`data`)&&i.push(e.C(n,`data`));return{schema:{...t,default:i.length>1?i:i[0]}}}function se(e,t){let n=Number(e.toFixed(t));return Math.abs(e-n)<1e-8?n:e}function C(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 ce(e){if(!Number.isFinite(e)||e===0)return .1;let t=C(e);return t===0?Math.abs(e)>=1?1:.1:Number((10**-t).toFixed(t))}function w(e){return typeof e.stepSize==`number`&&Number.isFinite(e.stepSize)&&e.stepSize>0?e.stepSize:void 0}const T=(e,t)=>(e.atMost??1)>1?[t]:t,E=e=>w(e)??(e.paramType===`Integer`?1:.1),D=(e,t)=>Array.isArray(e)?e.map(e=>typeof e==`number`?t(e):e):typeof e==`number`?t(e):e;function le(t){if(v(t.default))return{default:t.default,stepSize:E(t)};if(typeof t.default==`string`&&t.default.trim()!==``&&b(t.default)===null)throw new e.D(`Invalid numeric default "${t.default}" for input "${t.name||`unknown`}"`,e.O.VALIDATION_ERROR,{context:{inputName:t.name,default:t.default}});let n=y(t.default,b,!0);if(t.paramType===`Integer`)return{default:D(n,Math.round),stepSize:E(t)};let r=Array.isArray(n)?n[0]:n,i=[r,t.minimum,t.maximum].find(e=>typeof e==`number`&&Number.isFinite(e)&&e!==0),a=w(t)??(i===void 0?.1:ce(i)),o=C(a);if(o===0&&typeof r==`number`&&r!==0&&Math.abs(r)<1){let e=Math.ceil(-Math.log10(Math.abs(r)));Number.isFinite(e)&&e>0&&(o=e)}return o=Math.min(Math.max(o,0),12),{default:D(n,e=>se(e,o)),stepSize:a}}const O={parse(e,t){let{default:n,stepSize:r}=le(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:E(e),default:T(e,n)}}},ue={parse(t,n){if(v(t.default))return{...n,paramType:`Boolean`,default:t.default};let r=y(t.default,x,!1);if(r!=null&&typeof r!=`boolean`&&!Array.isArray(r))throw new e.D(`Invalid boolean default "${String(r)}" for input "${t.name||`unknown`}"`,e.O.VALIDATION_ERROR,{context:{inputName:t.name,default:t.default}});return{...n,paramType:`Boolean`,default:r}},fallback(e,t){return{...t,paramType:`Boolean`,default:T(e,!1)}}},de={parse(e,t){let n=y(e.default,te,!1);return{...t,paramType:`Text`,default:n}}},fe={parse(t,n,r){if(!t.values||typeof t.values!=`object`||Object.keys(t.values).length===0){let n=t.nickname||`unnamed`;throw new e.D(`Input "${n}" has no values defined (expected ValueList)`,e.O.INVALID_INPUT,{context:{inputName:n,expectedType:`ValueList`}})}let i=t.default;if(t.default!==void 0&&t.default!==null){if(typeof t.default==`object`)throw new e.D(`ValueList input "${t.nickname||`unnamed`}" default is not a string-able value`,e.O.VALIDATION_ERROR,{context:{inputName:t.name,default:t.default}});let n=String(t.default).toLowerCase(),a=Object.keys(t.values).find(e=>e.toLowerCase()===n);if(a!==void 0)i=a;else{let n=`ValueList input "${t.nickname||`unnamed`}" default value "${t.default}" is not in available values`;e.T().warn(n),r?.({code:e.O.VALIDATION_ERROR,message:n})}}return{...n,paramType:`ValueList`,values:t.values,default:i}},fallback(e,t){return{...t,paramType:`ValueList`,values:e.values&&typeof e.values==`object`?e.values:{},default:void 0}}};function k(e,t){return{...t,paramType:`Geometry`,default:T(e,null)}}const A=/* @__PURE__ */ new Map([[`Number`,O],[`Integer`,O],[`Boolean`,ue],[`Text`,de],[`ValueList`,fe],[`Geometry`,{parse(e,t){let n=y(e.default,S(e.nickname||`unnamed`),!0);return{...t,paramType:`Geometry`,default:n}},fallback:k}],[`File`,{parse(e,t){let n=y(e.default,S(e.nickname||`unnamed`),!0);return{...t,paramType:`File`,acceptedFormats:e.acceptedFormats,default:n}}}],[`Color`,{parse(e,t){let n=y(e.default,ne,!1);return{...t,paramType:`Color`,default:n}}}]]),pe=k,me=new Map([...A.keys()].map(e=>[e.toLowerCase(),e]));function he(e){return me.get(e?.toLowerCase())??e}function ge(e){return j(e).input}function j(t){let n=t.name||`unknown`,r=[],i=({code:e,message:i})=>{r.push({inputName:n,paramType:t.paramType,message:i,code:e})},a={description:t.description,name:t.name,nickname:t.nickname,treeAccess:t.treeAccess,groupName:t.groupName??void 0,id:t.id},o=he(t.paramType),s={...t,paramType:o};try{let{schema:e,warning:t}=oe(s,n);s=e,t&&i(t)}catch(t){s={...s,default:null},i({code:e.O.MALFORMED_DEFAULT,message:`Input "${n}" default could not be normalized and was dropped: ${t instanceof Error?t.message:String(t)}`})}let c=A.get(o);try{if(!c)throw new e.D(`Unknown paramType: ${o}`,e.O.VALIDATION_ERROR,{context:{receivedParamType:o,paramName:t.name}});return{input:c.parse(s,a,i),errors:r}}catch(l){if(!(l instanceof e.D))throw new e.D(l instanceof Error?l.message:String(l),e.O.VALIDATION_ERROR,{context:{paramName:t.name,paramType:o},originalError:l});return e.T().error(`Validation error for input ${n}:`,l.message),i(l),{input:(c?.fallback??pe)(s,a),errors:r}}}function _e(e){let t=[],n=[];for(let r of e){let{input:e,errors:i}=j(r);t.push(e),n.push(...i)}return{inputs:t,parseErrors:n}}function ve(t){let n=e.C(t,`stepSize`);return{id:e.C(t,`id`)??``,name:e.C(t,`name`)??``,nickname:e.C(t,`nickname`)??null,description:e.C(t,`description`)??``,paramType:e.C(t,`paramType`)??``,treeAccess:e.C(t,`treeAccess`)??!1,minimum:e.C(t,`minimum`)??null,maximum:e.C(t,`maximum`)??null,atLeast:e.C(t,`atLeast`)??1,atMost:e.C(t,`atMost`)??1,stepSize:typeof n==`number`&&Number.isFinite(n)?n:void 0,default:e.C(t,`default`),values:e.C(t,`values`),acceptedFormats:e.C(t,`acceptedFormats`),groupName:e.C(t,`groupName`)??null}}function ye(t){return{name:e.C(t,`name`)??``,nickname:e.C(t,`nickname`)??null,paramType:e.C(t,`paramType`)??``,id:e.C(t,`id`)??``}}async function M(t,n){a(`fetchDefinitionIO`,n.suppressBrowserWarning),e.x(n.serverUrl);let{algo:r,pointer:i}=h(t,[]);if(!r&&!i)throw new e.D(`Definition must resolve to either a URL pointer or base64 algo`,e.O.INVALID_INPUT);let o=await e.l(`io`,r?{algo:r}:{pointer:i},s(n));if(!o||typeof o!=`object`)throw new e.D(`Invalid IO response structure`,e.O.INVALID_INPUT,{context:{response:o}});let c=N(e.C(o,`warnings`)),l=N(e.C(o,`errors`)),u=e.C(o,`inputs`),d=e.C(o,`outputs`);return{inputs:Array.isArray(u)?u.map(ve):[],outputs:Array.isArray(d)?d.map(ye):[],...c&&{loadWarnings:c},...l&&{loadErrors:l}}}function N(e){if(!Array.isArray(e))return;let t=e.map(be).filter(e=>e!==void 0);return t.length>0?t:void 0}function be(t){if(t==null)return;let n;if(typeof t==`string`)n=t;else if(typeof t==`object`){let r=e.C(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 P(e,t){let{inputs:n,outputs:r,loadWarnings:i,loadErrors:a}=await M(e,t),{inputs:o,parseErrors:s}=_e(n);return{inputs:o,outputs:r,...s.length>0&&{parseErrors:s},...i&&{loadWarnings:i},...a&&{loadErrors:a}}}const F=globalThis.process?.getBuiltinModule?.(`node:crypto`);function I(e){if(F){let t=F.createHash(`sha256`);return typeof e==`string`?t.update(e,`utf16le`):t.update(e),t.digest(`hex`)}return Se(e)}const xe=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 Se(e){let t=new Ce;return typeof e==`string`?t.updateString(e):t.update(e),t.digestHex()}var Ce=class{h=new Int32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);w=/* @__PURE__ */ new Int32Array(64);pending=/* @__PURE__ */ 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+xe[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 L(e){let t=/* @__PURE__ */ 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:${I(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 we(e,t){return R(z(e),t)}function R(e,t){return`${e}|t:${I(L(t))}`}function z(t){return e.s(t)?`r:${t.key}`:typeof t==`string`?`s:${I(t)}`:`u8:${I(t)}`}const B=/* @__PURE__ */ new WeakMap;function Te(e){if(!(e instanceof Uint8Array))return z(e);let t=B.get(e);return t===void 0&&(t=z(e),B.set(e,t)),t}var Ee=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??=R(this.definitionHash,this.dataTree)}},De=class{items=[];head=0;live=/* @__PURE__ */ 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 Oe(e){try{return JSON.stringify(e)?.length??0}catch{return 0}}var V=class{executor;baseConfig;mode;maxConcurrent;maxQueueDepth;queueWaitMs;timeoutMs;retry;cacheEnabled;cacheMaxBytes;cacheTtl;cacheErroredSolves;cache=/* @__PURE__ */ new Map;cacheBytes=0;cacheHits=0;cacheMisses=0;cacheEvictions=0;reuseServerDefinitionCache;serverCacheKeys=/* @__PURE__ */ new Map;lastStringDefinition=null;onStart;onSettle;onSuperseded;subscribers=/* @__PURE__ */ new Set;inFlight=/* @__PURE__ */ new Set;pendingForLatestWins=null;fifo=new De;_lastResult=null;_lastError=null;_lastDurationMs=null;solveSeq=0;lastStateSeq=0;disposed=!1;constructor(t,n,r={}){if(this.executor=t,this.baseConfig=n,this.mode=r.mode??`latest-wins`,this.mode!==`latest-wins`&&this.mode!==`queue`)throw new e.D(`Unknown scheduler mode '${String(this.mode)}'. For concurrent solves use { mode: 'queue', maxConcurrent: 4 }.`,e.O.INVALID_CONFIG,{context:{mode:this.mode}});this.maxConcurrent=Math.max(1,r.maxConcurrent??1),this.maxQueueDepth=r.maxQueueDepth!==void 0&&r.maxQueueDepth>0?Math.floor(r.maxQueueDepth):void 0,this.queueWaitMs=r.queueWaitMs!==void 0&&r.queueWaitMs>0?r.queueWaitMs:void 0,this.timeoutMs=r.timeoutMs,this.retry=r.retry;let i=r.cache,a=typeof i==`object`?i:null;this.cacheMaxBytes=Math.max(0,a?.maxBytes??0),this.cacheEnabled=this.cacheMaxBytes>0,this.cacheTtl=a?.ttlMs??0,this.cacheErroredSolves=a?.cacheErroredSolves??!0,this.reuseServerDefinitionCache=r.reuseServerDefinitionCache??!0,this.onStart=r.onStart,this.onSettle=r.onSettle,this.onSuperseded=r.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 t of this.subscribers)try{t()}catch(t){e.T().error(`[SolveScheduler] subscriber threw:`,t)}}solve(e,t,n){return this.solveDetailed(e,t,n).then(e=>e.response)}solveDetailed(t,n,r){if(this.disposed)return Promise.reject(new e.D(`SolveScheduler has been disposed and cannot be used`,e.O.INVALID_STATE));let i=new Ee(()=>this.hashDefinitionMemo(t),n),a=``;if(this.cacheEnabled||this.onStart||this.onSettle||this.onSuperseded)try{a=i.key}catch(t){return Promise.reject(new e.D(`Solve input could not be hashed`,e.O.INVALID_INPUT,{originalError:t}))}let o=++this.solveSeq,s={key:a,enqueuedAt:Date.now(),startedAt:null};if(r?.signal?.aborted)return Promise.reject(this.makeAbortError(s));let c=this.readCache(a);if(c){this.mode===`latest-wins`&&this.supersedeCurrent();let e={status:`success`,response:c,durationMs:0,fromCache:!0};return this.writeLastState(o,{result:c,durationMs:0}),this.runHook(this.onStart,s),this.runHook(this.onSettle,s,e),this.notify(),Promise.resolve({response:c,fromCache:!0,durationMs:0})}return new Promise((e,a)=>{let c={definition:t,dataTree:n,hashes:i,ctx:s,seq:o,resolve:e,reject:a,externalSignal:r?.signal,selvaevents:r?.selvaevents,onServerTiming:r?.onServerTiming};c.externalSignal&&(c.queuedAbortHandler=()=>this.abortQueuedItem(c),c.externalSignal.addEventListener(`abort`,c.queuedAbortHandler,{once:!0})),this.enqueue(c)})}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(t){let n=new e.D(`Solve queue is full; request rejected (backpressure)`,e.O.QUEUE_FULL,{statusCode:503,context:{queueDepth:this.fifo.size,maxQueueDepth:this.maxQueueDepth}});this.fail(t,n),this.notify()}armQueueWaitTimer(t){if(this.queueWaitMs===void 0)return;let n=this.queueWaitMs;t.queueWaitTimer=setTimeout(()=>{if(t.settled)return;this.dequeue(t);let r=new e.D(`Solve waited longer than ${n}ms in queue; rejected (backpressure)`,e.O.QUEUE_TIMEOUT,{statusCode:503,context:{waitedMs:Date.now()-t.ctx.enqueuedAt,queueWaitMs:n}});this.fail(t,r),this.notify()},n)}clearQueueWaitTimer(e){e.queueWaitTimer!==void 0&&(clearTimeout(e.queueWaitTimer),e.queueWaitTimer=void 0)}enqueue(e){switch(this.mode){case`latest-wins`:this.supersedeCurrent(),this.inFlight.size===0?this.execute(e):this.pendingForLatestWins=e;break;case`queue`: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(t,n){let{definition:r,dataTree:i}=t;if(!this.reuseServerDefinitionCache||e.c(r)){let{response:e}=await this.executor(r,i,null,n);return{response:e}}let a=t.hashes.definitionHash,o=this.serverCacheKeys.get(a)??null,s=await this.executor(r,i,o,n);return this.serverCacheKeys.delete(a),s.cacheKey&&(this.serverCacheKeys.set(a,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:z(e)}),this.lastStringDefinition.hash):Te(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)}}else for(;this.fifo.size>0&&this.inFlight.size<this.maxConcurrent;)this.execute(this.fifo.shift())}}supersede(t){let n=new e.D(`Superseded by newer solve`,e.O.SUPERSEDED,{context:{enqueuedAt:t.ctx.enqueuedAt}});this.settleError(t,n)&&this.runHook(this.onSuperseded,t.ctx)}makeAbortError(t){return new e.D(`Request aborted by caller`,e.O.ABORTED,{context:{enqueuedAt:t.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(t,n){return n.settled&&`error`in n.settled?n.settled.error:t instanceof e.D?t:t instanceof Error&&t.name===`AbortError`?this.makeAbortError(n.ctx):new e.D(t instanceof Error?t.message:String(t),e.O.UNKNOWN_ERROR,{originalError:t})}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.C(n,`errors`);if(!this.cacheErroredSolves&&Array.isArray(r)&&r.length>0)return;let i=e.f(n)??Oe(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(t,...n){if(t)try{t(...n)}catch(t){e.T().error(`[SolveScheduler] hook threw:`,t)}}};function H(t){return e.s(t)?`ref:${t.key}`:typeof t==`string`&&t.length<200?t:`...content...`}function U(t){return Array.isArray(t)?t.map(t=>{let n=0,r=0,i=e.C(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.C(t,`paramName`)??`<unnamed>`,items:n,bytes:r}}):[]}var ke=class n{config;serverStats;disposed=!1;static CREATE_PROBE_TIMEOUT_MS=2e3;constructor(n){this.config={...n,serverUrl:e.x(n.serverUrl),debug:n.debug??!1},this.serverStats=new t(this.config.serverUrl,this.config)}static async create(t,r={}){let i=new n(t),a=Math.max(1,(r.probe?.attempts??2)+1),o=r.probe?.baseDelayMs??250,s=r.probe?.maxDelayMs??1e3,c,l=null,u=0;for(let t=0;t<a;t++){if(u=t+1,c=await i.serverStats.probeServer(n.CREATE_PROBE_TIMEOUT_MS),c.online)return i;if(l=e.u(c),l&&!l.retryable)break;if(t<a-1){let e=Math.min(o*2**t,s);await new Promise(t=>setTimeout(t,e))}}await i.dispose();let d=c?.status,f=l?`Rhino Compute server is not available. ${l.summary}`:`Rhino Compute server is not online`;throw new e.D(f,e.O.NETWORK_ERROR,{...d!==void 0&&{statusCode:d},context:{serverUrl:i.config.serverUrl,attempts:u,maxAttempts:a,...l&&{probeVerdict:l.verdict,probeRetryable:l.retryable},...d!==void 0&&{lastProbeStatus:d},...c?.error!==void 0&&{lastProbeError:c.error}}})}getConfig(){return this.ensureNotDisposed(),{...this.config}}async getIO(e){return this.ensureNotDisposed(),P(e,this.config)}async getRawIO(e){return this.ensureNotDisposed(),M(e,this.config)}async solve(t,n,r){this.ensureNotDisposed();try{if(typeof t==`string`&&!t.trim())throw new e.D(`Definition URL/content is required`,e.O.INVALID_INPUT,{context:{receivedUrl:t}});if(t instanceof Uint8Array&&t.length===0)throw new e.D(`Definition content is empty`,e.O.INVALID_INPUT);if(e.s(t)&&!t.key.trim())throw new e.D(`DefinitionRef key is empty`,e.O.INVALID_INPUT);let i=await u(n,t,{...this.config,...r?.signal!==void 0&&{signal:r.signal},...r?.timeoutMs!==void 0&&{timeoutMs:r.timeoutMs},...r?.retry!==void 0&&{retry:r.retry},...r?.selvaevents!==void 0&&{selvaevents:r.selvaevents}}),a=e.C(i,`errors`);if(Array.isArray(a)&&a.length>0)throw new e.D(a.map(String).join(`; `)||`Computation failed`,e.O.COMPUTATION_ERROR,{context:{definition:H(t),inputSummary:U(n),errors:a,warnings:e.C(i,`warnings`),values:i.values}});return i}catch(r){throw this.config.debug&&e.T().error(`Compute failed:`,r),r instanceof e.D?r:new e.D(r instanceof Error?r.message:String(r),e.O.COMPUTATION_ERROR,{context:{definition:H(t),inputSummary:U(n)},originalError:r})}}createScheduler(e){return this.ensureNotDisposed(),new V((e,t,n,r)=>d(t,n,e,r),this.config,e)}async dispose(){this.disposed||(this.disposed=!0,await this.serverStats.dispose())}ensureNotDisposed(){if(this.disposed)throw new e.D(`GrasshopperClient has been disposed and cannot be used`,e.O.INVALID_STATE)}};function Ae(e){return typeof e==`object`&&!!e&&e.__decodeError===!0}function W(e,t){return{__decodeError:!0,type:e,raw:t}}function G(e){let t=/* @__PURE__ */ 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 K=/* @__PURE__ */ 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 je(e){if(K.has(e))return K.get(e);for(let[t,n]of K)if(e.startsWith(t))return n}function Me(e){return!!(e&&typeof e==`object`&&typeof e.data==`string`)}function Ne(t,n,r){let i=je(n),a=!1;if(i)try{let e=i(r,t);if(e!=null)return e}catch(t){e.T().warn(`Failed to decode Rhino type ${n}:`,t),a=!0}try{if(Me(t))return r.CommonObject.decode(t)}catch(r){return e.T().warn(`Failed to decode ${n} with CommonObject:`,r),W(n,t)}return a?W(n,t):t}const q={STRING:`System.String`,INT:`System.Int32`,DOUBLE:`System.Double`,BOOL:`System.Boolean`},J=`FileData`;function Y(e,t){return e.includes(`WebDisplay`)||t&&e!==q.STRING}function Pe(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 Fe(e,t,n){switch(t){case q.STRING:return typeof e==`string`?e.replace(/^"(.*)"$/,`$1`):e;case q.INT:return Number.parseInt(String(e),10);case q.DOUBLE:return Number.parseFloat(String(e));case q.BOOL:return String(e).toLowerCase()===`true`;default:return n&&t.startsWith(`Rhino.Geometry.`)?Ne(e,t,n):e}}function Ie(e,t,n,r){if(typeof e.data!=`string`)return e.data;let i=n?Pe(e.data):e.data;return n&&t.includes(J)?Le(i)??i:Fe(i,t,r)}function Le(t){if(!t||typeof t!=`object`)return null;let n=e.C(t,`fileName`),r=e.C(t,`fileType`),i=e.C(t,`subFolder`),a=e.C(t,`isBase64Encoded`);if(typeof n!=`string`||typeof r!=`string`||typeof i!=`string`||!e.S(t,`data`)||typeof a!=`boolean`&&typeof a!=`string`)return null;let o=e.C(t,`metadata`);return{fileName:n,fileType:r,data:e.C(t,`data`),isBase64Encoded:e.i(a),subFolder:i,...o?{metadata:o}:{}}}function X(t){let n=e.C(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 Re(t,n=!1,r={}){let{parseValues:i=!0,rhino:a,stringOnly:o=!1}=r,s={},c=/* @__PURE__ */ new Set;for(let r of X(t)){let t=e.C(r,`paramName`);Q(e.C(r,`innerTree`),e=>{let r=Z(e);if(Y(r,o))return;let l=n?e.id:t;if(!l)return;let u=Ie(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)):g(s,l,u)})}return{values:s,dispose:()=>G(s)}}function ze(t){let n=[];for(let r of X(t))Q(e.C(r,`innerTree`),e=>{if(!Z(e).includes(J))return;let t=Le(Pe(e.data));t&&n.push(t)});return n}function Be(t,n,r={}){let{parseValues:i=!0,rhino:a,stringOnly:o=!1}=r;for(let r of X(t)){let t=e.C(r,`innerTree`),s=!1;if(`byName`in n){if(e.C(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);Y(t,o)||c.push(Ie(e,t,i,a))}),s)return c.length===0?void 0:c.length===1?c[0]:c}}var Ve=class{response;constructor(e){this.response=e}getValues(e=!1,t={}){return Re(this.response,e,t)}getValue(e,t){return Be(this.response,e,t)}async getAndDownloadFiles(t,n){await e.t(ze(this.response),t,n)}};function He(t){return(Array.isArray(t)?t:[t]).map(t=>({schemas:e.C(t,`schemas`),error:e.C(t,`error`)}))}const Ue=/* @__PURE__ */ new Set([`options`,`defaultOptions`,`values`]),We=/* @__PURE__ */ new Set([`optionMedia`,`assets`]),Ge=e=>e>=`A`&&e<=`Z`;function Ke(e){if(e.length===0||!Ge(e[0]))return e;let t=0;for(;t<e.length&&Ge(e[t]);)t++;return t>1&&t<e.length&&t--,e.slice(0,t).toLowerCase()+e.slice(t)}function qe(e){return $(e)}function $(e){if(Array.isArray(e))return e.map($);if(typeof e!=`object`||!e)return e;let t={};for(let[n,r]of Object.entries(e)){let e=Ke(n);g(t,e,Ue.has(e)?r:We.has(e)?Je(r):$(r))}return t}function Je(e){if(typeof e!=`object`||!e||Array.isArray(e))return e;let t={};for(let[n,r]of Object.entries(e))g(t,n,$(r));return t}var Ye=class t{innerTree;paramName;constructor(e){this.paramName=e,this.innerTree={}}append(e,n){let r=this.innerTree[t.formatPathString(e)]??=[];for(let e of n)r.push({data:t.serializeValue(e)});return this}fromDataTreeDefault(e){this.innerTree={};for(let[n,r]of Object.entries(e)){if(!Array.isArray(r))continue;let e=t.parsePathString(n);this.append(e,r)}return this}appendFlat(e){let t=Array.isArray(e)?e:[e];return this.append([0],t)}flatten(){let e=[];for(let n of Object.values(this.innerTree))if(Array.isArray(n))for(let r of n)e.push(t.deserializeValue(r.data));return e}toComputeFormat(){return{ParamName:this.paramName,InnerTree:this.innerTree}}getParamName(){return this.paramName}static fromInputParams(e){return t.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(n){let r=[];for(let i of n){let n=new t(i.paramName),a=t.itemCoercer(i);for(let[r,o]of t.branchesOf(i.value)){let t=[];for(let n of o){if(n==null)continue;let r=a(n);r===null?e.T().warn(`${i.paramName}: dropped an item that is not a valid ${i.paramType}`):t.push(r)}t.length>0&&n.append(r,t)}Object.keys(n.innerTree).length>0&&r.push(n.toComputeFormat())}return r}static branchesOf(e){return t.hasValidValue(e)?v(e)?Object.entries(e).map(([e,n])=>[t.parsePathString(e),n]):[[[0],Array.isArray(e)?e:[e]]]:[]}static itemCoercer(e){let{paramName:n,minimum:r,maximum:i}=e,a=e.paramType.toLowerCase();return a===`number`||a===`integer`?e=>{let o=b(e);if(o===null)return null;let s=a===`integer`?Math.round(o):o;return t.clampValue(s,r,i,n)}:a===`boolean`?x:e=>e}static replaceTreeValue(e,n,r){let i=t.buildFromValue(n,r).toComputeFormat(),a=e.slice(),o=a.findIndex(e=>t.paramNameOf(e)===n);return o===-1?a.push(i):a[o]=i,a}static buildFromValue(e,n){let r=new t(e);return v(n)?r.fromDataTreeDefault(n):r.appendFlat(n),r}static getTree(n,r){let i=n.find(e=>t.paramNameOf(e)===r);if(!i)return null;let a=/* @__PURE__ */ new Map,o=e.C(i,`InnerTree`);if(!o||typeof o!=`object`)return a;for(let[e,n]of Object.entries(o))Array.isArray(n)&&a.set(e,n.map(e=>e?.data===void 0?null:t.deserializeValue(e.data)));return a}static getTreeValue(n,r){let i=t.getTree(n,r);if(!i||i.size===0)return null;if(i.size>1)throw new e.D(`"${r}" has ${i.size} branches; read it with TreeBuilder.getTree`,e.O.INVALID_INPUT,{context:{paramName:r,branchCount:i.size}});let[a]=i.values();return a.length===0?null:a.length===1?a[0]:a}static paramNameOf(t){return e.C(t,`ParamName`)}static parsePathString(t){let n=t.match(_);if(!n)throw new e.D(`Invalid Grasshopper tree path: "${t}". Expected "{}", "{0}", or "{0;1;2}" (negative indices allowed, no empty segments).`,e.O.INVALID_INPUT,{context:{pathStr:t}});return n[1]?n[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.T().warn(`${i}: ${t} below min ${n}, clamping`),a=n),r!=null&&a>r&&(e.T().warn(`${i}: ${t} above max ${r}, clamping`),a=r),a}};exports.ComputeServerStats=t,exports.GrasshopperClient=ke,exports.GrasshopperResponseProcessor=Ve,exports.SolveScheduler=V,exports.TreeBuilder=Ye,exports.disposeRhinoObjects=G,exports.fetchDefinitionIO=M,exports.fetchParsedDefinitionIO=P,exports.hashDefinition=z,exports.hashSolveInput=we,exports.isRhinoDecodeError=Ae,exports.normalizeUISchemaCasing=qe,exports.processInput=ge,exports.readSchemaResults=He,exports.solveGrasshopperDefinition=u,exports.stableStringify=L;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./core-DF0VYOve.cjs");var t=class t{serverUrl;headers;disposed=!1;activeMonitors=/* @__PURE__ */ 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(t,n){this.serverUrl=e.x(t),this.headers={...e.y(typeof n==`string`?{apiKey:n}:n??{}),"Content-Type":`application/json`}}fetchWithTimeout(e,n={},r=t.DEFAULT_TIMEOUT_MS){let i={...n,headers:this.headers,redirect:`manual`};return r>0&&!i.signal&&(i.signal=AbortSignal.timeout(r)),fetch(e,i)}async getText(n,r={},i=t.DEFAULT_TIMEOUT_MS){this.ensureNotDisposed();let a=`${r.method??`GET`} ${n}`;try{let o=await this.fetchWithTimeout(`${this.serverUrl}${n}`,r,i);if(!o.ok)return e.T().warn(`[ComputeServerStats] ${a} failed:`,o.status),await o.body?.cancel().catch(()=>{}),null;let{text:s,truncated:c}=await e.m(o,t.MAX_BODY_BYTES);return c?(e.T().warn(`[ComputeServerStats] ${a} answered with an oversized body`),null):s}catch(t){return e.T().warn(`[ComputeServerStats] ${a} errored:`,t),null}}async isServerOnline(e=t.DEFAULT_TIMEOUT_MS){return(await this.probeServer(e)).online}async probeServer(n=t.DEFAULT_TIMEOUT_MS){this.ensureNotDisposed();let r=`${this.serverUrl}/`;try{let t=await this.fetchWithTimeout(r,{method:`GET`},n);return await t.body?.cancel().catch(()=>{}),{online:t.ok||e.d(t),status:t.status}}catch(t){return e.T().debug(`[ComputeServerStats] Fetch error:`,t),{online:!1,error:t instanceof Error?`${t.name}: ${t.message}`:String(t)}}}async getActiveChildren(n={}){let{initialize:r=!0}=n,i=r?await this.getText(`/activechildren`,{},t.LIFECYCLE_TIMEOUT_MS):await this.getText(`/activechildren?initialize=false`);if(i===null)return null;let a=i.trim();return/^\d+$/.test(a)?parseInt(a,10):(e.T().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=n(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`),r=t===null?void 0:n(t);return r&&typeof r==`object`?r: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:n(e))?.purged;return typeof t==`number`?t:null}async purgeAllChildren(){this.ensureNotDisposed();let t=await this.getActiveChildren({initialize:!1});if(t===null)return e.T().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 r=await this.getText(e,{method:`POST`},t.LIFECYCLE_TIMEOUT_MS);return r===null?null:n(r)??null}monitor(n,r=5e3){if(this.ensureNotDisposed(),!Number.isFinite(r)||r<t.MIN_MONITOR_INTERVAL_MS)throw new e.D(`monitor() intervalMs must be a finite number >= ${t.MIN_MONITOR_INTERVAL_MS}ms, got ${r}. Sub-${t.MIN_MONITOR_INTERVAL_MS}ms polling would hot-loop the server.`,e.O.INVALID_CONFIG,{context:{intervalMs:r}});let i=!0,a=null;e.T().info(`🔄 Starting server stats monitoring every ${r}ms`);let o=async()=>{if(a=null,i&&!this.disposed){try{let t=await this.getServerStats();if(!i||this.disposed)return;try{n(t)}catch(t){e.T().error(`[ComputeServerStats] Monitor callback threw:`,t)}}catch(t){!i||this.disposed?e.T().debug(`[ComputeServerStats] Monitor poll cancelled during shutdown:`,t):e.T().error(`[ComputeServerStats] Failed to fetch stats during monitor:`,t)}i&&!this.disposed&&(a=setTimeout(()=>void o(),r))}},s=()=>{i=!1,a!==null&&(clearTimeout(a),a=null),this.activeMonitors.delete(s)};return this.activeMonitors.add(s),o(),s}async dispose(){if(!this.disposed){this.disposed=!0;for(let e of this.activeMonitors)e();this.activeMonitors.clear()}}ensureNotDisposed(){if(this.disposed)throw new e.D(`ComputeServerStats has been disposed and cannot be used`,e.O.INVALID_STATE)}};function n(e){try{return JSON.parse(e)}catch{return}}const r=/* @__PURE__ */ new Set;function i(){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 a(t,n){n||i()&&!r.has(t)&&(r.add(t),e.T().warn(`Warning: ${t} is running on the client side. For better performance and security, consider running this on the server side.`))}const o={definition_not_cached:e.O.DEFINITION_NOT_CACHED};function s(e){return{...e,serverErrorCodes:{...o,...e.serverErrorCodes}}}function c(t){return t instanceof e.D?t.code===e.O.DEFINITION_NOT_CACHED||t.message.includes(`Unable to load grasshopper definition`):!1}function l(t,n){if(!n)return;let r=e.C(t,`values`);if(!Array.isArray(r)||r.length===0)return;let i=[];for(let t of r){let n=e.C(t,`innerTree`);n&&Object.keys(n).length!==0||i.push(e.C(t,`paramName`)??`<unnamed>`)}if(i.length===0)return;let a=i.length===r.length?`all`:`${i.length}/${r.length}`;e.T().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 u(e,t,n){return a(`solveGrasshopperDefinition`,n.suppressBrowserWarning),(await f(e,t,n)).response}async function d(e,t,n,r){if(a(`solveWithServerCacheKey`,r.suppressBrowserWarning),t!==null)try{return{...await m({algo:null,pointer:t,values:e},r),missed:!1}}catch(e){if(!c(e))throw e}return{...await f(e,n,r),missed:!0}}async function f(e,t,n){return m(h(await p(t),e),n)}async function p(t){if(!e.s(t))return t;try{return await t.load()}catch(n){throw new e.D(`Failed to load definition bytes for ref '${t.key}'`,e.O.INVALID_INPUT,{context:{definitionKey:t.key},originalError:n})}}async function m(t,n){e.x(n.serverUrl),ee(t,n);let{maxResponseBytes:r}=n,i=await e.l(`grasshopper`,t,s({...n,maxResponseBytes:r!==void 0&&t.algo?r+t.algo.length:r})),{pointer:a,algo:o,...c}=i,u=c,d=e.f(i);if(d!==void 0){let t=typeof o==`string`?o.length:0;e.p(u,Math.max(0,d-t))}return l(u,n.debug),{response:u,cacheKey:typeof a==`string`?a:null}}function h(t,n){let r={algo:null,pointer:null,values:n};return t instanceof Uint8Array?r.algo=e.h(t):e.c(t)?r.pointer=t:r.algo=e._(t)??e.v(t),r}function ee(e,t){t.cachesolve!=null&&(e.cachesolve=t.cachesolve),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 g(e,t,n){t===`__proto__`?Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0}):e[t]=n}const _=/^\{(-?\d+(?:;-?\d+)*)?\}$/;function v(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.entries(e);return t.length>0&&t.every(([e,t])=>_.test(e)&&Array.isArray(t))}function y(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 b=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},x=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},te=e=>typeof e==`string`?e.length>=2&&e.startsWith(`"`)&&e.endsWith(`"`)?e.slice(1,-1):e.startsWith(`"`)?e.slice(1):e:null,ne=e=>{if(typeof e==`string`){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)&&(t=t.slice(1,-1).trim()),t}return null};function S(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.T().warn(`Parsed value for input ${t} is not an object`),null)}catch(r){return e.T().warn(`Failed to parse object value "${n}" for input ${t}`,r),null}return null}}const re=/* @__PURE__ */ new Set([`System.Double`,`System.Single`,`System.Decimal`,`System.Int32`,`System.Int64`]),ie=/* @__PURE__ */ new Set([`System.Int32`,`System.Int64`]);function ae(t,n){return e.T().warn(n),{schema:{...t,default:null},warning:{code:e.O.MALFORMED_DEFAULT,message:n}}}function oe(t,n){if(typeof t.default!=`object`||t.default===null||Array.isArray(t.default)||v(t.default))return{schema:t};if(!e.S(t.default,`innerTree`))return ae(t,`Input "${n}" default had an unrecognized shape (no innerTree key); the default was dropped.`);let r=e.C(t.default,`innerTree`)??{};if(Object.keys(r).length===0)return{schema:{...t,default:void 0}};if(t.treeAccess||t.atMost&&t.atMost>1){let i={},a=[];for(let[o,s]of Object.entries(r)){if(!Array.isArray(s))return ae(t,`Input "${n}" default had a non-array innerTree branch ("${o}"); the default was dropped.`);let r=[];for(let t of s){let n=e.C(t,`data`),i=e.C(t,`type`);if(i&&re.has(i)){if(typeof n==`string`&&n.trim()===``)continue;let e=b(n);if(e===null){a.push(`"${String(n)}" (${i})`);continue}r.push(ie.has(i)?Math.round(e):e)}else if(i===`System.Boolean`){let e=x(n);if(e===null){a.push(`"${String(n)}" (${i})`);continue}r.push(e)}else if(typeof n==`string`&&i?.startsWith(`Rhino.Geometry`))try{r.push(JSON.parse(n))}catch{r.push(n)}else r.push(n)}g(i,o,r)}if(a.length>0){let r=`Input "${n}" default contained ${a.length} tree value(s) that could not be parsed and were dropped: ${a.join(`, `)}.`;return e.T().warn(r),{schema:{...t,default:i},warning:{code:e.O.MALFORMED_DEFAULT,message:r}}}return{schema:{...t,default:i}}}let i=[];for(let t of Object.values(r))if(Array.isArray(t))for(let n of t)n&&typeof n==`object`&&e.S(n,`data`)&&i.push(e.C(n,`data`));return{schema:{...t,default:i.length>1?i:i[0]}}}function se(e,t){let n=Number(e.toFixed(t));return Math.abs(e-n)<1e-8?n:e}function C(e){if(!Number.isFinite(e))return 0;let t=Number(Math.abs(e).toPrecision(15)),[n,r=`0`]=String(t).split(`e`),i=(n.split(`.`)[1]?.length??0)-Number(r);return Math.min(Math.max(i,0),12)}function ce(e){if(!Number.isFinite(e)||e===0)return .1;let t=C(e);return t===0?Math.abs(e)>=1?1:.1:Number((10**-t).toFixed(t))}function w(e){return typeof e.stepSize==`number`&&Number.isFinite(e.stepSize)&&e.stepSize>0?e.stepSize:void 0}const T=(e,t)=>(e.atMost??1)>1?[t]:t,E=e=>w(e)??(e.paramType===`Integer`?1:.1),D=(e,t)=>Array.isArray(e)?e.map(e=>typeof e==`number`?t(e):e):typeof e==`number`?t(e):e;function le(t){if(v(t.default))return{default:t.default,stepSize:E(t)};if(typeof t.default==`string`&&t.default.trim()!==``&&b(t.default)===null)throw new e.D(`Invalid numeric default "${t.default}" for input "${t.name||`unknown`}"`,e.O.VALIDATION_ERROR,{context:{inputName:t.name,default:t.default}});let n=y(t.default,b,!0);if(t.paramType===`Integer`)return{default:D(n,Math.round),stepSize:E(t)};let r=Array.isArray(n)?n[0]:n,i=[r,t.minimum,t.maximum].find(e=>typeof e==`number`&&Number.isFinite(e)&&e!==0),a=w(t)??(i===void 0?.1:ce(i)),o=C(a);if(o===0&&typeof r==`number`&&r!==0&&Math.abs(r)<1){let e=Math.ceil(-Math.log10(Math.abs(r)));Number.isFinite(e)&&e>0&&(o=e)}return o=Math.min(Math.max(o,0),12),{default:D(n,e=>se(e,o)),stepSize:a}}const O={parse(e,t){let{default:n,stepSize:r}=le(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:E(e),default:T(e,n)}}},ue={parse(t,n){if(v(t.default))return{...n,paramType:`Boolean`,default:t.default};let r=y(t.default,x,!1);if(r!=null&&typeof r!=`boolean`&&!Array.isArray(r))throw new e.D(`Invalid boolean default "${String(r)}" for input "${t.name||`unknown`}"`,e.O.VALIDATION_ERROR,{context:{inputName:t.name,default:t.default}});return{...n,paramType:`Boolean`,default:r}},fallback(e,t){return{...t,paramType:`Boolean`,default:T(e,!1)}}},de={parse(e,t){let n=y(e.default,te,!1);return{...t,paramType:`Text`,default:n}}},fe={parse(t,n,r){if(!t.values||typeof t.values!=`object`||Object.keys(t.values).length===0){let n=t.nickname||`unnamed`;throw new e.D(`Input "${n}" has no values defined (expected ValueList)`,e.O.INVALID_INPUT,{context:{inputName:n,expectedType:`ValueList`}})}let i=t.default;if(t.default!==void 0&&t.default!==null){if(typeof t.default==`object`)throw new e.D(`ValueList input "${t.nickname||`unnamed`}" default is not a string-able value`,e.O.VALIDATION_ERROR,{context:{inputName:t.name,default:t.default}});let n=String(t.default).toLowerCase(),a=Object.keys(t.values).find(e=>e.toLowerCase()===n);if(a!==void 0)i=a;else{let n=`ValueList input "${t.nickname||`unnamed`}" default value "${t.default}" is not in available values`;e.T().warn(n),r?.({code:e.O.VALIDATION_ERROR,message:n})}}return{...n,paramType:`ValueList`,values:t.values,default:i}},fallback(e,t){return{...t,paramType:`ValueList`,values:e.values&&typeof e.values==`object`?e.values:{},default:void 0}}};function k(e,t){return{...t,paramType:`Geometry`,default:T(e,null)}}const A=/* @__PURE__ */ new Map([[`Number`,O],[`Integer`,O],[`Boolean`,ue],[`Text`,de],[`ValueList`,fe],[`Geometry`,{parse(e,t){let n=y(e.default,S(e.nickname||`unnamed`),!0);return{...t,paramType:`Geometry`,default:n}},fallback:k}],[`File`,{parse(e,t){let n=y(e.default,S(e.nickname||`unnamed`),!0);return{...t,paramType:`File`,acceptedFormats:e.acceptedFormats,default:n}}}],[`Color`,{parse(e,t){let n=y(e.default,ne,!1);return{...t,paramType:`Color`,default:n}}}]]),pe=k,me=new Map([...A.keys()].map(e=>[e.toLowerCase(),e]));function he(e){return me.get(e?.toLowerCase())??e}function ge(e){return j(e).input}function j(t){let n=t.name||`unknown`,r=[],i=({code:e,message:i})=>{r.push({inputName:n,paramType:t.paramType,message:i,code:e})},a={description:t.description,name:t.name,nickname:t.nickname,treeAccess:t.treeAccess,groupName:t.groupName??void 0,id:t.id},o=he(t.paramType),s={...t,paramType:o};try{let{schema:e,warning:t}=oe(s,n);s=e,t&&i(t)}catch(t){s={...s,default:null},i({code:e.O.MALFORMED_DEFAULT,message:`Input "${n}" default could not be normalized and was dropped: ${t instanceof Error?t.message:String(t)}`})}let c=A.get(o);try{if(!c)throw new e.D(`Unknown paramType: ${o}`,e.O.VALIDATION_ERROR,{context:{receivedParamType:o,paramName:t.name}});return{input:c.parse(s,a,i),errors:r}}catch(l){if(!(l instanceof e.D))throw new e.D(l instanceof Error?l.message:String(l),e.O.VALIDATION_ERROR,{context:{paramName:t.name,paramType:o},originalError:l});return e.T().error(`Validation error for input ${n}:`,l.message),i(l),{input:(c?.fallback??pe)(s,a),errors:r}}}function _e(e){let t=[],n=[];for(let r of e){let{input:e,errors:i}=j(r);t.push(e),n.push(...i)}return{inputs:t,parseErrors:n}}function ve(t){let n=e.C(t,`stepSize`);return{id:e.C(t,`id`)??``,name:e.C(t,`name`)??``,nickname:e.C(t,`nickname`)??null,description:e.C(t,`description`)??``,paramType:e.C(t,`paramType`)??``,treeAccess:e.C(t,`treeAccess`)??!1,minimum:e.C(t,`minimum`)??null,maximum:e.C(t,`maximum`)??null,atLeast:e.C(t,`atLeast`)??1,atMost:e.C(t,`atMost`)??1,stepSize:typeof n==`number`&&Number.isFinite(n)?n:void 0,default:e.C(t,`default`),values:e.C(t,`values`),acceptedFormats:e.C(t,`acceptedFormats`),groupName:e.C(t,`groupName`)??null}}function ye(t){return{name:e.C(t,`name`)??``,nickname:e.C(t,`nickname`)??null,paramType:e.C(t,`paramType`)??``,id:e.C(t,`id`)??``}}async function M(t,n){a(`fetchDefinitionIO`,n.suppressBrowserWarning),e.x(n.serverUrl);let{algo:r,pointer:i}=h(t,[]);if(!r&&!i)throw new e.D(`Definition must resolve to either a URL pointer or base64 algo`,e.O.INVALID_INPUT);let o=await e.l(`io`,r?{algo:r}:{pointer:i},s(n));if(!o||typeof o!=`object`)throw new e.D(`Invalid IO response structure`,e.O.INVALID_INPUT,{context:{response:o}});let c=N(e.C(o,`warnings`)),l=N(e.C(o,`errors`)),u=e.C(o,`inputs`),d=e.C(o,`outputs`);return{inputs:Array.isArray(u)?u.map(ve):[],outputs:Array.isArray(d)?d.map(ye):[],...c&&{loadWarnings:c},...l&&{loadErrors:l}}}function N(e){if(!Array.isArray(e))return;let t=e.map(be).filter(e=>e!==void 0);return t.length>0?t:void 0}function be(t){if(t==null)return;let n;if(typeof t==`string`)n=t;else if(typeof t==`object`){let r=e.C(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 P(e,t){let{inputs:n,outputs:r,loadWarnings:i,loadErrors:a}=await M(e,t),{inputs:o,parseErrors:s}=_e(n);return{inputs:o,outputs:r,...s.length>0&&{parseErrors:s},...i&&{loadWarnings:i},...a&&{loadErrors:a}}}const F=globalThis.process?.getBuiltinModule?.(`node:crypto`);function I(e){if(F){let t=F.createHash(`sha256`);return typeof e==`string`?t.update(e,`utf16le`):t.update(e),t.digest(`hex`)}return Se(e)}const xe=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 Se(e){let t=new Ce;return typeof e==`string`?t.updateString(e):t.update(e),t.digestHex()}var Ce=class{h=new Int32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);w=/* @__PURE__ */ new Int32Array(64);pending=/* @__PURE__ */ 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+xe[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 L(e){let t=/* @__PURE__ */ 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:${I(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 we(e,t){return R(z(e),t)}function R(e,t){return`${e}|t:${I(L(t))}`}function z(t){return e.s(t)?`r:${t.key}`:typeof t==`string`?`s:${I(t)}`:`u8:${I(t)}`}const B=/* @__PURE__ */ new WeakMap;function Te(e){if(!(e instanceof Uint8Array))return z(e);let t=B.get(e);return t===void 0&&(t=z(e),B.set(e,t)),t}var Ee=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??=R(this.definitionHash,this.dataTree)}},De=class{items=[];head=0;live=/* @__PURE__ */ 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 Oe(e){try{return JSON.stringify(e)?.length??0}catch{return 0}}var V=class{executor;baseConfig;mode;maxConcurrent;maxQueueDepth;queueWaitMs;timeoutMs;retry;cacheEnabled;cacheMaxBytes;cacheTtl;cacheErroredSolves;cache=/* @__PURE__ */ new Map;cacheBytes=0;cacheHits=0;cacheMisses=0;cacheEvictions=0;reuseServerDefinitionCache;serverCacheKeys=/* @__PURE__ */ new Map;lastStringDefinition=null;onStart;onSettle;onSuperseded;subscribers=/* @__PURE__ */ new Set;inFlight=/* @__PURE__ */ new Set;pendingForLatestWins=null;fifo=new De;_lastResult=null;_lastError=null;_lastDurationMs=null;solveSeq=0;lastStateSeq=0;disposed=!1;constructor(t,n,r={}){if(this.executor=t,this.baseConfig=n,this.mode=r.mode??`latest-wins`,this.mode!==`latest-wins`&&this.mode!==`queue`)throw new e.D(`Unknown scheduler mode '${String(this.mode)}'. For concurrent solves use { mode: 'queue', maxConcurrent: 4 }.`,e.O.INVALID_CONFIG,{context:{mode:this.mode}});this.maxConcurrent=Math.max(1,r.maxConcurrent??1),this.maxQueueDepth=r.maxQueueDepth!==void 0&&r.maxQueueDepth>0?Math.floor(r.maxQueueDepth):void 0,this.queueWaitMs=r.queueWaitMs!==void 0&&r.queueWaitMs>0?r.queueWaitMs:void 0,this.timeoutMs=r.timeoutMs,this.retry=r.retry;let i=r.cache,a=typeof i==`object`?i:null;this.cacheMaxBytes=Math.max(0,a?.maxBytes??0),this.cacheEnabled=this.cacheMaxBytes>0,this.cacheTtl=a?.ttlMs??0,this.cacheErroredSolves=a?.cacheErroredSolves??!0,this.reuseServerDefinitionCache=r.reuseServerDefinitionCache??!0,this.onStart=r.onStart,this.onSettle=r.onSettle,this.onSuperseded=r.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 t of this.subscribers)try{t()}catch(t){e.T().error(`[SolveScheduler] subscriber threw:`,t)}}solve(e,t,n){return this.solveDetailed(e,t,n).then(e=>e.response)}solveDetailed(t,n,r){if(this.disposed)return Promise.reject(new e.D(`SolveScheduler has been disposed and cannot be used`,e.O.INVALID_STATE));let i=new Ee(()=>this.hashDefinitionMemo(t),n),a=``;if(this.cacheEnabled||this.onStart||this.onSettle||this.onSuperseded)try{a=i.key}catch(t){return Promise.reject(new e.D(`Solve input could not be hashed`,e.O.INVALID_INPUT,{originalError:t}))}let o=++this.solveSeq,s={key:a,enqueuedAt:Date.now(),startedAt:null};if(r?.signal?.aborted)return Promise.reject(this.makeAbortError(s));let c=this.readCache(a);if(c){this.mode===`latest-wins`&&this.supersedeCurrent();let e={status:`success`,response:c,durationMs:0,fromCache:!0};return this.writeLastState(o,{result:c,durationMs:0}),this.runHook(this.onStart,s),this.runHook(this.onSettle,s,e),this.notify(),Promise.resolve({response:c,fromCache:!0,durationMs:0})}return new Promise((e,a)=>{let c={definition:t,dataTree:n,hashes:i,ctx:s,seq:o,resolve:e,reject:a,externalSignal:r?.signal,selvaevents:r?.selvaevents,onServerTiming:r?.onServerTiming};c.externalSignal&&(c.queuedAbortHandler=()=>this.abortQueuedItem(c),c.externalSignal.addEventListener(`abort`,c.queuedAbortHandler,{once:!0})),this.enqueue(c)})}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(t){let n=new e.D(`Solve queue is full; request rejected (backpressure)`,e.O.QUEUE_FULL,{statusCode:503,context:{queueDepth:this.fifo.size,maxQueueDepth:this.maxQueueDepth}});this.fail(t,n),this.notify()}armQueueWaitTimer(t){if(this.queueWaitMs===void 0)return;let n=this.queueWaitMs;t.queueWaitTimer=setTimeout(()=>{if(t.settled)return;this.dequeue(t);let r=new e.D(`Solve waited longer than ${n}ms in queue; rejected (backpressure)`,e.O.QUEUE_TIMEOUT,{statusCode:503,context:{waitedMs:Date.now()-t.ctx.enqueuedAt,queueWaitMs:n}});this.fail(t,r),this.notify()},n)}clearQueueWaitTimer(e){e.queueWaitTimer!==void 0&&(clearTimeout(e.queueWaitTimer),e.queueWaitTimer=void 0)}enqueue(e){switch(this.mode){case`latest-wins`:this.supersedeCurrent(),this.inFlight.size===0?this.execute(e):this.pendingForLatestWins=e;break;case`queue`: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(t,n){let{definition:r,dataTree:i}=t;if(!this.reuseServerDefinitionCache||e.c(r)){let{response:e}=await this.executor(r,i,null,n);return{response:e}}let a=t.hashes.definitionHash,o=this.serverCacheKeys.get(a)??null,s=await this.executor(r,i,o,n);return this.serverCacheKeys.delete(a),s.cacheKey&&(this.serverCacheKeys.set(a,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:z(e)}),this.lastStringDefinition.hash):Te(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)}}else for(;this.fifo.size>0&&this.inFlight.size<this.maxConcurrent;)this.execute(this.fifo.shift())}}supersede(t){let n=new e.D(`Superseded by newer solve`,e.O.SUPERSEDED,{context:{enqueuedAt:t.ctx.enqueuedAt}});this.settleError(t,n)&&this.runHook(this.onSuperseded,t.ctx)}makeAbortError(t){return new e.D(`Request aborted by caller`,e.O.ABORTED,{context:{enqueuedAt:t.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(t,n){return n.settled&&`error`in n.settled?n.settled.error:t instanceof e.D?t:t instanceof Error&&t.name===`AbortError`?this.makeAbortError(n.ctx):new e.D(t instanceof Error?t.message:String(t),e.O.UNKNOWN_ERROR,{originalError:t})}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.C(n,`errors`);if(!this.cacheErroredSolves&&Array.isArray(r)&&r.length>0)return;let i=e.C(e.C(n,`selva`),`outcome`);if(e.C(i,`aborted`)===!0)return;let a=e.f(n)??Oe(n);if(!(a>this.cacheMaxBytes))for(this.dropCacheEntry(t),this.cache.set(t,{response:n,insertedAt:Date.now(),sizeBytes:a}),this.cacheBytes+=a;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.T().error(`[SolveScheduler] hook threw:`,t)}}};function H(t){return e.s(t)?`ref:${t.key}`:typeof t==`string`&&t.length<200?t:`...content...`}function U(t){return Array.isArray(t)?t.map(t=>{let n=0,r=0,i=e.C(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.C(t,`paramName`)??`<unnamed>`,items:n,bytes:r}}):[]}var ke=class n{config;serverStats;disposed=!1;static CREATE_PROBE_TIMEOUT_MS=2e3;constructor(n){this.config={...n,serverUrl:e.x(n.serverUrl),debug:n.debug??!1},this.serverStats=new t(this.config.serverUrl,this.config)}static async create(t,r={}){let i=new n(t),a=Math.max(1,(r.probe?.attempts??2)+1),o=r.probe?.baseDelayMs??250,s=r.probe?.maxDelayMs??1e3,c,l=null,u=0;for(let t=0;t<a;t++){if(u=t+1,c=await i.serverStats.probeServer(n.CREATE_PROBE_TIMEOUT_MS),c.online)return i;if(l=e.u(c),l&&!l.retryable)break;if(t<a-1){let e=Math.min(o*2**t,s);await new Promise(t=>setTimeout(t,e))}}await i.dispose();let d=c?.status,f=l?`Rhino Compute server is not available. ${l.summary}`:`Rhino Compute server is not online`;throw new e.D(f,e.O.NETWORK_ERROR,{...d!==void 0&&{statusCode:d},context:{serverUrl:i.config.serverUrl,attempts:u,maxAttempts:a,...l&&{probeVerdict:l.verdict,probeRetryable:l.retryable},...d!==void 0&&{lastProbeStatus:d},...c?.error!==void 0&&{lastProbeError:c.error}}})}getConfig(){return this.ensureNotDisposed(),{...this.config}}async getIO(e){return this.ensureNotDisposed(),P(e,this.config)}async getRawIO(e){return this.ensureNotDisposed(),M(e,this.config)}async solve(t,n,r){this.ensureNotDisposed();try{if(typeof t==`string`&&!t.trim())throw new e.D(`Definition URL/content is required`,e.O.INVALID_INPUT,{context:{receivedUrl:t}});if(t instanceof Uint8Array&&t.length===0)throw new e.D(`Definition content is empty`,e.O.INVALID_INPUT);if(e.s(t)&&!t.key.trim())throw new e.D(`DefinitionRef key is empty`,e.O.INVALID_INPUT);let i=await u(n,t,{...this.config,...r?.signal!==void 0&&{signal:r.signal},...r?.timeoutMs!==void 0&&{timeoutMs:r.timeoutMs},...r?.retry!==void 0&&{retry:r.retry},...r?.selvaevents!==void 0&&{selvaevents:r.selvaevents}}),a=e.C(i,`errors`);if(Array.isArray(a)&&a.length>0)throw new e.D(a.map(String).join(`; `)||`Computation failed`,e.O.COMPUTATION_ERROR,{context:{definition:H(t),inputSummary:U(n),errors:a,warnings:e.C(i,`warnings`),values:i.values}});return i}catch(r){throw this.config.debug&&e.T().error(`Compute failed:`,r),r instanceof e.D?r:new e.D(r instanceof Error?r.message:String(r),e.O.COMPUTATION_ERROR,{context:{definition:H(t),inputSummary:U(n)},originalError:r})}}createScheduler(e){return this.ensureNotDisposed(),new V((e,t,n,r)=>d(t,n,e,r),this.config,e)}async dispose(){this.disposed||(this.disposed=!0,await this.serverStats.dispose())}ensureNotDisposed(){if(this.disposed)throw new e.D(`GrasshopperClient has been disposed and cannot be used`,e.O.INVALID_STATE)}};function Ae(e){return typeof e==`object`&&!!e&&e.__decodeError===!0}function W(e,t){return{__decodeError:!0,type:e,raw:t}}function G(e){let t=/* @__PURE__ */ 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 K=/* @__PURE__ */ 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 je(e){if(K.has(e))return K.get(e);for(let[t,n]of K)if(e.startsWith(t))return n}function Me(e){return!!(e&&typeof e==`object`&&typeof e.data==`string`)}function Ne(t,n,r){let i=je(n),a=!1;if(i)try{let e=i(r,t);if(e!=null)return e}catch(t){e.T().warn(`Failed to decode Rhino type ${n}:`,t),a=!0}try{if(Me(t))return r.CommonObject.decode(t)}catch(r){return e.T().warn(`Failed to decode ${n} with CommonObject:`,r),W(n,t)}return a?W(n,t):t}const q={STRING:`System.String`,INT:`System.Int32`,DOUBLE:`System.Double`,BOOL:`System.Boolean`},J=`FileData`;function Y(e,t){return e.includes(`WebDisplay`)||t&&e!==q.STRING}function Pe(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 Fe(e,t,n){switch(t){case q.STRING:return typeof e==`string`?e.replace(/^"(.*)"$/,`$1`):e;case q.INT:return Number.parseInt(String(e),10);case q.DOUBLE:return Number.parseFloat(String(e));case q.BOOL:return String(e).toLowerCase()===`true`;default:return n&&t.startsWith(`Rhino.Geometry.`)?Ne(e,t,n):e}}function Ie(e,t,n,r){if(typeof e.data!=`string`)return e.data;let i=n?Pe(e.data):e.data;return n&&t.includes(J)?Le(i)??i:Fe(i,t,r)}function Le(t){if(!t||typeof t!=`object`)return null;let n=e.C(t,`fileName`),r=e.C(t,`fileType`),i=e.C(t,`subFolder`),a=e.C(t,`isBase64Encoded`);if(typeof n!=`string`||typeof r!=`string`||typeof i!=`string`||!e.S(t,`data`)||typeof a!=`boolean`&&typeof a!=`string`)return null;let o=e.C(t,`metadata`);return{fileName:n,fileType:r,data:e.C(t,`data`),isBase64Encoded:e.i(a),subFolder:i,...o?{metadata:o}:{}}}function X(t){let n=e.C(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 Re(t,n=!1,r={}){let{parseValues:i=!0,rhino:a,stringOnly:o=!1}=r,s={},c=/* @__PURE__ */ new Set;for(let r of X(t)){let t=e.C(r,`paramName`);Q(e.C(r,`innerTree`),e=>{let r=Z(e);if(Y(r,o))return;let l=n?e.id:t;if(!l)return;let u=Ie(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)):g(s,l,u)})}return{values:s,dispose:()=>G(s)}}function ze(t){let n=[];for(let r of X(t))Q(e.C(r,`innerTree`),e=>{if(!Z(e).includes(J))return;let t=Le(Pe(e.data));t&&n.push(t)});return n}function Be(t,n,r={}){let{parseValues:i=!0,rhino:a,stringOnly:o=!1}=r;for(let r of X(t)){let t=e.C(r,`innerTree`),s=!1;if(`byName`in n){if(e.C(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);Y(t,o)||c.push(Ie(e,t,i,a))}),s)return c.length===0?void 0:c.length===1?c[0]:c}}var Ve=class{response;constructor(e){this.response=e}getValues(e=!1,t={}){return Re(this.response,e,t)}getValue(e,t){return Be(this.response,e,t)}async getAndDownloadFiles(t,n){await e.t(ze(this.response),t,n)}};function He(t){return(Array.isArray(t)?t:[t]).map(t=>({schemas:e.C(t,`schemas`),error:e.C(t,`error`)}))}const Ue=/* @__PURE__ */ new Set([`options`,`defaultOptions`,`values`]),We=/* @__PURE__ */ new Set([`optionMedia`,`assets`]),Ge=e=>e>=`A`&&e<=`Z`;function Ke(e){if(e.length===0||!Ge(e[0]))return e;let t=0;for(;t<e.length&&Ge(e[t]);)t++;return t>1&&t<e.length&&t--,e.slice(0,t).toLowerCase()+e.slice(t)}function qe(e){return $(e)}function $(e){if(Array.isArray(e))return e.map($);if(typeof e!=`object`||!e)return e;let t={};for(let[n,r]of Object.entries(e)){let e=Ke(n);g(t,e,Ue.has(e)?r:We.has(e)?Je(r):$(r))}return t}function Je(e){if(typeof e!=`object`||!e||Array.isArray(e))return e;let t={};for(let[n,r]of Object.entries(e))g(t,n,$(r));return t}var Ye=class t{innerTree;paramName;constructor(e){this.paramName=e,this.innerTree={}}append(e,n){let r=this.innerTree[t.formatPathString(e)]??=[];for(let e of n)r.push({data:t.serializeValue(e)});return this}fromDataTreeDefault(e){this.innerTree={};for(let[n,r]of Object.entries(e)){if(!Array.isArray(r))continue;let e=t.parsePathString(n);this.append(e,r)}return this}appendFlat(e){let t=Array.isArray(e)?e:[e];return this.append([0],t)}flatten(){let e=[];for(let n of Object.values(this.innerTree))if(Array.isArray(n))for(let r of n)e.push(t.deserializeValue(r.data));return e}toComputeFormat(){return{ParamName:this.paramName,InnerTree:this.innerTree}}getParamName(){return this.paramName}static fromInputParams(e){return t.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(n){let r=[];for(let i of n){let n=new t(i.paramName),a=t.itemCoercer(i);for(let[r,o]of t.branchesOf(i.value)){let t=[];for(let n of o){if(n==null)continue;let r=a(n);r===null?e.T().warn(`${i.paramName}: dropped an item that is not a valid ${i.paramType}`):t.push(r)}t.length>0&&n.append(r,t)}Object.keys(n.innerTree).length>0&&r.push(n.toComputeFormat())}return r}static branchesOf(e){return t.hasValidValue(e)?v(e)?Object.entries(e).map(([e,n])=>[t.parsePathString(e),n]):[[[0],Array.isArray(e)?e:[e]]]:[]}static itemCoercer(e){let{paramName:n,minimum:r,maximum:i}=e,a=e.paramType.toLowerCase();return a===`number`||a===`integer`?e=>{let o=b(e);if(o===null)return null;let s=a===`integer`?Math.round(o):o;return t.clampValue(s,r,i,n)}:a===`boolean`?x:e=>e}static replaceTreeValue(e,n,r){let i=t.buildFromValue(n,r).toComputeFormat(),a=e.slice(),o=a.findIndex(e=>t.paramNameOf(e)===n);return o===-1?a.push(i):a[o]=i,a}static buildFromValue(e,n){let r=new t(e);return v(n)?r.fromDataTreeDefault(n):r.appendFlat(n),r}static getTree(n,r){let i=n.find(e=>t.paramNameOf(e)===r);if(!i)return null;let a=/* @__PURE__ */ new Map,o=e.C(i,`InnerTree`);if(!o||typeof o!=`object`)return a;for(let[e,n]of Object.entries(o))Array.isArray(n)&&a.set(e,n.map(e=>e?.data===void 0?null:t.deserializeValue(e.data)));return a}static getTreeValue(n,r){let i=t.getTree(n,r);if(!i||i.size===0)return null;if(i.size>1)throw new e.D(`"${r}" has ${i.size} branches; read it with TreeBuilder.getTree`,e.O.INVALID_INPUT,{context:{paramName:r,branchCount:i.size}});let[a]=i.values();return a.length===0?null:a.length===1?a[0]:a}static paramNameOf(t){return e.C(t,`ParamName`)}static parsePathString(t){let n=t.match(_);if(!n)throw new e.D(`Invalid Grasshopper tree path: "${t}". Expected "{}", "{0}", or "{0;1;2}" (negative indices allowed, no empty segments).`,e.O.INVALID_INPUT,{context:{pathStr:t}});return n[1]?n[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.T().warn(`${i}: ${t} below min ${n}, clamping`),a=n),r!=null&&a>r&&(e.T().warn(`${i}: ${t} above max ${r}, clamping`),a=r),a}};exports.ComputeServerStats=t,exports.GrasshopperClient=ke,exports.GrasshopperResponseProcessor=Ve,exports.SolveScheduler=V,exports.TreeBuilder=Ye,exports.disposeRhinoObjects=G,exports.fetchDefinitionIO=M,exports.fetchParsedDefinitionIO=P,exports.hashDefinition=z,exports.hashSolveInput=we,exports.isRhinoDecodeError=Ae,exports.normalizeUISchemaCasing=qe,exports.processInput=ge,exports.readSchemaResults=He,exports.solveGrasshopperDefinition=u,exports.stableStringify=L;
2
2
  //# sourceMappingURL=grasshopper.cjs.map