@selvajs/compute 3.1.0-beta.11 → 3.1.0-beta.13

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.
Files changed (51) hide show
  1. package/dist/chunk-6R4EL3ZJ.cjs +2 -0
  2. package/dist/chunk-6R4EL3ZJ.cjs.map +1 -0
  3. package/dist/chunk-6TMSTNHN.js +2 -0
  4. package/dist/chunk-6TMSTNHN.js.map +1 -0
  5. package/dist/chunk-GLOTP5TC.cjs +120 -0
  6. package/dist/chunk-GLOTP5TC.cjs.map +1 -0
  7. package/dist/chunk-H3FZW6OX.cjs +4 -0
  8. package/dist/chunk-H3FZW6OX.cjs.map +1 -0
  9. package/dist/chunk-NVMSD4CC.js +120 -0
  10. package/dist/chunk-NVMSD4CC.js.map +1 -0
  11. package/dist/chunk-Y3M7P3BW.js +4 -0
  12. package/dist/chunk-Y3M7P3BW.js.map +1 -0
  13. package/dist/core.cjs +1 -1
  14. package/dist/core.cjs.map +1 -1
  15. package/dist/core.d.cts +22 -1
  16. package/dist/core.d.ts +22 -1
  17. package/dist/core.js +1 -1
  18. package/dist/grasshopper.cjs +1 -1
  19. package/dist/grasshopper.d.cts +20 -0
  20. package/dist/grasshopper.d.ts +20 -0
  21. package/dist/grasshopper.js +1 -1
  22. package/dist/index.cjs +1 -1
  23. package/dist/index.cjs.map +1 -1
  24. package/dist/index.d.cts +1 -1
  25. package/dist/index.d.ts +1 -1
  26. package/dist/index.js +1 -1
  27. package/dist/visualization-BIHTM2KJ.js +2 -0
  28. package/dist/visualization-FLDYIZ3F.cjs +2 -0
  29. package/dist/visualization-FLDYIZ3F.cjs.map +1 -0
  30. package/dist/visualization.cjs +1 -1
  31. package/dist/visualization.cjs.map +1 -1
  32. package/dist/visualization.d.cts +193 -21
  33. package/dist/visualization.d.ts +193 -21
  34. package/dist/visualization.js +1 -1
  35. package/package.json +55 -34
  36. package/dist/chunk-7XMD5YXP.cjs +0 -62
  37. package/dist/chunk-7XMD5YXP.cjs.map +0 -1
  38. package/dist/chunk-C7P43VZF.js +0 -2
  39. package/dist/chunk-C7P43VZF.js.map +0 -1
  40. package/dist/chunk-CUQQ3ZBV.cjs +0 -4
  41. package/dist/chunk-CUQQ3ZBV.cjs.map +0 -1
  42. package/dist/chunk-PX2YTSHJ.js +0 -62
  43. package/dist/chunk-PX2YTSHJ.js.map +0 -1
  44. package/dist/chunk-QZECCPT3.cjs +0 -2
  45. package/dist/chunk-QZECCPT3.cjs.map +0 -1
  46. package/dist/chunk-WPB2LKCD.js +0 -4
  47. package/dist/chunk-WPB2LKCD.js.map +0 -1
  48. package/dist/visualization-4RSUYQG2.cjs +0 -2
  49. package/dist/visualization-4RSUYQG2.cjs.map +0 -1
  50. package/dist/visualization-MOYO6MDN.js +0 -2
  51. /package/dist/{visualization-MOYO6MDN.js.map → visualization-BIHTM2KJ.js.map} +0 -0
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkH3FZW6OXcjs = require('./chunk-H3FZW6OX.cjs');var se=new Set;function Ve(){if(typeof window>"u"||_optionalChain([globalThis, 'access', _2 => _2.process, 'optionalAccess', _3 => _3.versions, 'optionalAccess', _4 => _4.node])!=null)return!1;let e=globalThis.navigator,r=typeof _optionalChain([e, 'optionalAccess', _5 => _5.userAgent])=="string"?e.userAgent:"";return!/jsdom/i.test(r)}function D(t,e){e||Ve()&&!se.has(t)&&(se.add(t),_chunkH3FZW6OXcjs.e.call(void 0, ).warn(`Warning: ${t} is running on the client side. For better performance and security, consider running this on the server side.`))}function T(t){return typeof t=="object"&&!(t instanceof Uint8Array)&&typeof t.key=="string"&&typeof t.load=="function"}var Le="Unable to load grasshopper definition";function We(t){return t instanceof _chunkH3FZW6OXcjs.d?t.code===_chunkH3FZW6OXcjs.c.DEFINITION_NOT_CACHED||t.message.includes(Le):!1}function Be(t,e){if(!e)return;let r=_chunkH3FZW6OXcjs.s.call(void 0, t,"values");if(!Array.isArray(r)||r.length===0)return;let n=[];for(let s of r){let i=_chunkH3FZW6OXcjs.s.call(void 0, s,"innerTree");(!i||Object.keys(i).length===0)&&n.push(_nullishCoalesce(_chunkH3FZW6OXcjs.s.call(void 0, s,"paramName"), () => ("<unnamed>")))}if(n.length===0)return;let o=n.length===r.length?"all":`${n.length}/${r.length}`;_chunkH3FZW6OXcjs.e.call(void 0, ).warn(`Solve returned empty output(s) (${o}): ${n.join(", ")}. These parameters produced no data \u2014 check the definition's inputs and the branch feeding each.`)}async function E(t,e,r){D("solveGrasshopperDefinition",_nullishCoalesce(r.suppressBrowserWarning, () => (r.suppressClientSideWarning)));let n=await z(e),{response:o}=await N(v(n,t),r);return o}async function ie(t,e,r){D("solveGrasshopperDefinitionWithCacheKey",_nullishCoalesce(r.suppressBrowserWarning, () => (r.suppressClientSideWarning)));let n=await z(e);return N(v(n,t),r)}async function ae(t,e,r,n){D("solveByCacheKey",_nullishCoalesce(n.suppressBrowserWarning, () => (n.suppressClientSideWarning)));let o={algo:null,pointer:e,values:t};try{return{...await N(o,n),missed:!1}}catch(s){if(!We(s))throw s;let i=await z(r);return{...await N(v(i,t),n),missed:!0}}}async function z(t){if(!T(t))return t;try{return await t.load()}catch(e){throw new (0, _chunkH3FZW6OXcjs.d)(`Failed to load definition bytes for ref '${t.key}'`,_chunkH3FZW6OXcjs.c.INVALID_INPUT,{context:{definitionKey:t.key},originalError:e instanceof Error?e:new Error(String(e))})}}async function N(t,e){je(t,e);let r=await _chunkH3FZW6OXcjs.n.call(void 0, "grasshopper",t,e),{pointer:n,algo:o,...s}=r,i=s,a=_chunkH3FZW6OXcjs.m.call(void 0, r);if(a!==void 0){let u=typeof o=="string"?o.length:0;_chunkH3FZW6OXcjs.l.call(void 0, i,Math.max(0,a-u))}return Be(i,e.debug),{response:i,cacheKey:typeof n=="string"?n:null}}function v(t,e){let r={algo:null,pointer:null,values:e};return t instanceof Uint8Array?r.algo=_chunkH3FZW6OXcjs.k.call(void 0, t):/^https?:\/\//i.test(t)?r.pointer=t:r.algo=_nullishCoalesce(_chunkH3FZW6OXcjs.i.call(void 0, t), () => (_chunkH3FZW6OXcjs.h.call(void 0, t))),r}function je(t,e){e.cachesolve!=null&&(t.cachesolve=e.cachesolve),e.cacheerroredsolves!=null&&(t.cacheerroredsolves=e.cacheerroredsolves),e.modelunits!=null&&(t.modelunits=e.modelunits),e.angletolerance!=null&&(t.angletolerance=e.angletolerance),e.absolutetolerance!=null&&(t.absolutetolerance=e.absolutetolerance),e.dataversion!=null&&(t.dataversion=e.dataversion)}function $(t){let e=new WeakSet,r=n=>{if(n===void 0)return"undefined";if(n===null)return"null";if(typeof n=="number")return Number.isFinite(n)?String(n):"null";if(typeof n=="string"||typeof n=="boolean")return JSON.stringify(n);if(typeof n=="bigint")return`${n}n`;if(n instanceof Uint8Array)return`{"__u8":${n.length},"hash":"${le(n)}"}`;if(Array.isArray(n)){if(e.has(n))return'"[Circular]"';e.add(n);let o=[];for(let s=0;s<n.length;s++)o.push(r(n[s]));return e.delete(n),`[${o.join(",")}]`}if(typeof n=="object"){if(e.has(n))return'"[Circular]"';e.add(n);let o;return typeof n.toJSON=="function"?o=r(n.toJSON()):n instanceof Map?o=`{"__map":[${[...n.entries()].map(([i,a])=>`[${r(i)},${r(a)}]`).sort().join(",")}]}`:n instanceof Set?o=`{"__set":[${[...n.values()].map(r).sort().join(",")}]}`:o=`{${Object.keys(n).sort().map(a=>`${JSON.stringify(a)}:${r(n[a])}`).join(",")}}`,e.delete(n),o}return"null"};return r(t)}function ue(t,e){let r=2166136261;for(let n=0;n<t;n++)r^=e(n),r=r+((r<<1)+(r<<4)+(r<<7)+(r<<8)+(r<<24))>>>0;return r.toString(16).padStart(8,"0")}function pe(t){return ue(t.length,e=>t.charCodeAt(e))}function le(t){return ue(t.length,e=>t[e])}function ce(t,e){return q(R(t),e)}function q(t,e){let r=$(e);return`${t}|t:${r.length}:${pe(r)}`}function R(t){return T(t)?`r:${t.key}`:typeof t=="string"?`s:${t.length}:${pe(t)}`:`u8:${t.length}:${le(t)}`}var ze=100;function $e(t){return typeof t!="string"?!0:!/^https?:\/\//i.test(t)}function qe(t){try{return _nullishCoalesce(_optionalChain([JSON, 'access', _6 => _6.stringify, 'call', _7 => _7(t), 'optionalAccess', _8 => _8.length]), () => (0))}catch (e2){return 0}}var x=class{constructor(e,r,n={},o){_chunkH3FZW6OXcjs.b.call(void 0, this,"executor");_chunkH3FZW6OXcjs.b.call(void 0, this,"baseConfig");_chunkH3FZW6OXcjs.b.call(void 0, this,"mode");_chunkH3FZW6OXcjs.b.call(void 0, this,"maxConcurrent");_chunkH3FZW6OXcjs.b.call(void 0, this,"maxQueueDepth");_chunkH3FZW6OXcjs.b.call(void 0, this,"queueWaitMs");_chunkH3FZW6OXcjs.b.call(void 0, this,"timeoutMs");_chunkH3FZW6OXcjs.b.call(void 0, this,"retry");_chunkH3FZW6OXcjs.b.call(void 0, this,"cacheEnabled");_chunkH3FZW6OXcjs.b.call(void 0, this,"cacheMax");_chunkH3FZW6OXcjs.b.call(void 0, this,"cacheMaxBytes");_chunkH3FZW6OXcjs.b.call(void 0, this,"cacheTtl");_chunkH3FZW6OXcjs.b.call(void 0, this,"cacheErroredSolves");_chunkH3FZW6OXcjs.b.call(void 0, this,"cache",new Map);_chunkH3FZW6OXcjs.b.call(void 0, this,"cacheBytes",0);_chunkH3FZW6OXcjs.b.call(void 0, this,"cacheKeyExecutor");_chunkH3FZW6OXcjs.b.call(void 0, this,"reuseServerDefinitionCache");_chunkH3FZW6OXcjs.b.call(void 0, this,"serverCacheKeys",new Map);_chunkH3FZW6OXcjs.b.call(void 0, this,"onStart");_chunkH3FZW6OXcjs.b.call(void 0, this,"onSettle");_chunkH3FZW6OXcjs.b.call(void 0, this,"onSuperseded");_chunkH3FZW6OXcjs.b.call(void 0, this,"subscribers",new Set);_chunkH3FZW6OXcjs.b.call(void 0, this,"inFlight",new Set);_chunkH3FZW6OXcjs.b.call(void 0, this,"pendingForLatestWins",null);_chunkH3FZW6OXcjs.b.call(void 0, this,"fifoQueue",[]);_chunkH3FZW6OXcjs.b.call(void 0, this,"_lastResult",null);_chunkH3FZW6OXcjs.b.call(void 0, this,"_lastError",null);_chunkH3FZW6OXcjs.b.call(void 0, this,"_lastDurationMs",null);_chunkH3FZW6OXcjs.b.call(void 0, this,"solveSeq",0);_chunkH3FZW6OXcjs.b.call(void 0, this,"lastStateSeq",0);_chunkH3FZW6OXcjs.b.call(void 0, this,"disposed",!1);this.executor=e,this.cacheKeyExecutor=o,this.baseConfig=r,this.mode=_nullishCoalesce(n.mode, () => ("latest-wins")),this.maxConcurrent=Math.max(1,_nullishCoalesce(n.maxConcurrent, () => ((this.mode==="parallel"?4:1)))),this.maxQueueDepth=n.maxQueueDepth!==void 0&&n.maxQueueDepth>0?Math.floor(n.maxQueueDepth):void 0,this.queueWaitMs=n.queueWaitMs!==void 0&&n.queueWaitMs>0?n.queueWaitMs:void 0,this.timeoutMs=n.timeoutMs,this.retry=n.retry;let s=n.cache;this.cacheEnabled=s!==void 0&&s!==!1;let i=typeof s=="object"?s:{};this.cacheMax=_nullishCoalesce(i.maxEntries, () => (50)),this.cacheMaxBytes=Math.max(0,_nullishCoalesce(i.maxBytes, () => (0))),this.cacheTtl=_nullishCoalesce(i.ttlMs, () => (0)),this.cacheErroredSolves=_nullishCoalesce(i.cacheErroredSolves, () => (!0)),this.reuseServerDefinitionCache=!!o&&(_nullishCoalesce(n.reuseServerDefinitionCache, () => (!0))),this.onStart=n.onStart,this.onSettle=n.onSettle,this.onSuperseded=n.onSuperseded}get isSolving(){return this.inFlight.size>0}get hasPending(){return this.pendingForLatestWins!==null||this.fifoQueue.length>0}get inFlightCount(){return this.inFlight.size}get queueDepth(){return this.fifoQueue.length+(this.pendingForLatestWins?1:0)}get lastResult(){return this._lastResult}get lastError(){return this._lastError}get lastDurationMs(){return this._lastDurationMs}subscribe(e){return this.subscribers.add(e),()=>this.subscribers.delete(e)}notify(){for(let e of this.subscribers)try{e()}catch(r){_chunkH3FZW6OXcjs.e.call(void 0, ).error("[SolveScheduler] subscriber threw:",r)}}solve(e,r,n){if(this.disposed)return Promise.reject(new (0, _chunkH3FZW6OXcjs.d)("SolveScheduler has been disposed and cannot be used",_chunkH3FZW6OXcjs.c.INVALID_STATE));let o=R(e),s=q(o,r),i=++this.solveSeq,a={key:s,enqueuedAt:Date.now(),startedAt:null};if(_optionalChain([n, 'optionalAccess', _9 => _9.signal, 'optionalAccess', _10 => _10.aborted]))return Promise.reject(this.makeAbortError(a));if(this.cacheEnabled){let u=this.readCache(s);if(u){this.mode==="latest-wins"&&this.supersedeCurrent();let m={status:"success",response:u,durationMs:0,fromCache:!0};return this.writeLastState(i,{result:u,durationMs:0}),this.runHook(this.onStart,a),this.runHook(this.onSettle,a,m),this.notify(),Promise.resolve(u)}}return new Promise((u,m)=>{let f={definition:e,dataTree:r,definitionHash:o,ctx:a,seq:i,resolve:u,reject:m,externalSignal:_optionalChain([n, 'optionalAccess', _11 => _11.signal])};f.externalSignal&&(f.queuedAbortHandler=()=>this.abortQueuedItem(f),f.externalSignal.addEventListener("abort",f.queuedAbortHandler,{once:!0})),this.enqueue(f)})}writeLastState(e,r){return e<this.lastStateSeq?!1:(this.lastStateSeq=e,"result"in r?(this._lastResult=r.result,this._lastError=null):this._lastError=r.error,this._lastDurationMs=r.durationMs,!0)}supersedeCurrent(){this.pendingForLatestWins&&(this.supersede(this.pendingForLatestWins),this.pendingForLatestWins=null);for(let e of this.inFlight)this.supersede(e),e.controller.abort()}abortQueuedItem(e){this.pendingForLatestWins===e&&(this.pendingForLatestWins=null);let r=this.fifoQueue.indexOf(e);r>=0&&this.fifoQueue.splice(r,1),this.rejectAsAborted(e),this.notify()}shedAsQueueFull(e){let r=new (0, _chunkH3FZW6OXcjs.d)("Solve queue is full; request shed (backpressure)",_chunkH3FZW6OXcjs.c.QUEUE_FULL,{statusCode:503,context:{key:e.ctx.key,queueDepth:this.fifoQueue.length,maxQueueDepth:this.maxQueueDepth}});this.settleError(e,r)&&this.runHook(this.onSettle,e.ctx,{status:"error",error:r,durationMs:0}),this.notify()}armQueueWaitTimer(e){if(this.queueWaitMs===void 0)return;let r=this.queueWaitMs;e.queueWaitTimer=setTimeout(()=>{if(e.settled)return;let n=this.fifoQueue.indexOf(e);n>=0&&this.fifoQueue.splice(n,1);let o=new (0, _chunkH3FZW6OXcjs.d)(`Solve waited longer than ${r}ms in queue; shed (backpressure)`,_chunkH3FZW6OXcjs.c.QUEUE_TIMEOUT,{statusCode:503,context:{key:e.ctx.key,waitedMs:Date.now()-e.ctx.enqueuedAt,queueWaitMs:r}});this.settleError(e,o)&&this.runHook(this.onSettle,e.ctx,{status:"error",error:o,durationMs:0}),this.notify()},r)}clearQueueWaitTimer(e){e.queueWaitTimer!==void 0&&(clearTimeout(e.queueWaitTimer),e.queueWaitTimer=void 0)}enqueue(e){switch(this.mode){case"latest-wins":{this.supersedeCurrent(),this.inFlight.size===0?this.execute(e):this.pendingForLatestWins=e;break}case"queue":case"parallel":{this.inFlight.size<this.maxConcurrent?this.execute(e):this.maxQueueDepth!==void 0&&this.fifoQueue.length>=this.maxQueueDepth?this.shedAsQueueFull(e):(this.armQueueWaitTimer(e),this.fifoQueue.push(e));break}}this.notify()}async execute(e){let r=new AbortController,n=e;n.controller=r,this.inFlight.add(n),e.ctx.startedAt=Date.now(),this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e);let o=()=>r.abort();_optionalChain([e, 'access', _12 => _12.externalSignal, 'optionalAccess', _13 => _13.addEventListener, 'call', _14 => _14("abort",o,{once:!0})]),this.runHook(this.onStart,e.ctx),this.notify();let s=performance.now();try{let i={...this.baseConfig,signal:r.signal,...this.timeoutMs!==void 0&&{timeoutMs:this.timeoutMs},...this.retry!==void 0&&{retry:this.retry}},{response:a,definitionReuploaded:u}=await this.runExecutor(e.definition,e.dataTree,e.definitionHash,i),m=performance.now()-s;if(this.cacheEnabled&&this.writeCache(e.ctx.key,a),!this.settleSuccess(e,a))return;this.writeLastState(e.seq,{result:a,durationMs:m}),this.runHook(this.onSettle,e.ctx,{status:"success",response:a,durationMs:m,fromCache:!1,definitionReuploaded:u})}catch(i){let a=performance.now()-s,u=this.normalizeExecutionError(i,n);this.writeLastState(e.seq,{error:u,durationMs:a}),this.settleError(e,u)&&this.runHook(this.onSettle,e.ctx,{status:"error",error:u,durationMs:a})}finally{_optionalChain([e, 'access', _15 => _15.externalSignal, 'optionalAccess', _16 => _16.removeEventListener, 'call', _17 => _17("abort",o)]),this.inFlight.delete(n),this.drainNext(),this.notify()}}async runExecutor(e,r,n,o){if(!this.cacheKeyExecutor||!this.reuseServerDefinitionCache||!$e(e))return{response:await this.executor(e,r,o)};let s=n,i=_nullishCoalesce(this.serverCacheKeys.get(s), () => (null)),a=await this.cacheKeyExecutor(e,r,i,o);if(a.cacheKey)for(this.serverCacheKeys.delete(s),this.serverCacheKeys.set(s,a.cacheKey);this.serverCacheKeys.size>ze;){let u=this.serverCacheKeys.keys().next().value;if(u===void 0)break;this.serverCacheKeys.delete(u)}else this.serverCacheKeys.delete(s);return{response:a.response,definitionReuploaded:a.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 (0, _chunkH3FZW6OXcjs.d)("Superseded by newer solve",_chunkH3FZW6OXcjs.c.SUPERSEDED,{context:{key:e.ctx.key,enqueuedAt:e.ctx.enqueuedAt}});this.settleError(e,r)&&this.runHook(this.onSuperseded,e.ctx)}makeAbortError(e){return new (0, _chunkH3FZW6OXcjs.d)("Request aborted by caller",_chunkH3FZW6OXcjs.c.ABORTED,{context:{key:e.key,enqueuedAt:e.enqueuedAt}})}settleError(e,r){return e.settled?!1:(e.settled={error:r},this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e),e.reject(r),!0)}settleSuccess(e,r){return e.settled?!1:(e.settled={ok:!0},this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e),e.resolve(r),!0)}removeQueuedAbortHandler(e){e.queuedAbortHandler&&e.externalSignal&&e.externalSignal.removeEventListener("abort",e.queuedAbortHandler),e.queuedAbortHandler=void 0}isAbortLikeError(e){if(e instanceof Error){if(e.name==="AbortError")return!0;if(typeof DOMException<"u"&&e instanceof DOMException)return e.name==="AbortError"}return!1}normalizeExecutionError(e,r){return r.settled&&"error"in r.settled?r.settled.error:e instanceof _chunkH3FZW6OXcjs.d?e:this.isAbortLikeError(e)?this.makeAbortError(r.ctx):new (0, _chunkH3FZW6OXcjs.d)(e instanceof Error?e.message:String(e),_chunkH3FZW6OXcjs.c.UNKNOWN_ERROR,{originalError:e instanceof Error?e:new Error(String(e))})}cancelAll(){for(this.pendingForLatestWins&&(this.rejectAsAborted(this.pendingForLatestWins),this.pendingForLatestWins=null);this.fifoQueue.length>0;){let e=this.fifoQueue.shift();this.rejectAsAborted(e)}for(let e of this.inFlight){let r=this.makeAbortError(e.ctx);this.settleError(e,r)&&this.runHook(this.onSettle,e.ctx,{status:"error",error:r,durationMs:e.ctx.startedAt?Date.now()-e.ctx.startedAt:0}),e.controller.abort()}this.notify()}rejectAsAborted(e){let r=this.makeAbortError(e.ctx);this.settleError(e,r)&&this.runHook(this.onSettle,e.ctx,{status:"error",error:r,durationMs:0})}readCache(e){if(!this.cacheEnabled)return null;let r=this.cache.get(e);return r?this.cacheTtl>0&&Date.now()-r.insertedAt>this.cacheTtl?(this.dropCacheEntry(e),null):(this.cache.delete(e),this.cache.set(e,r),r.response):null}writeCache(e,r){if(!this.cacheEnabled||!this.cacheErroredSolves&&r.errors&&r.errors.length>0)return;let n=_nullishCoalesce(_chunkH3FZW6OXcjs.m.call(void 0, r), () => (qe(r)));if(!(this.cacheMaxBytes>0&&n>this.cacheMaxBytes))for(this.dropCacheEntry(e),this.cache.set(e,{response:r,insertedAt:Date.now(),sizeBytes:n}),this.cacheBytes+=n;(this.cache.size>this.cacheMax||this.cacheMaxBytes>0&&this.cacheBytes>this.cacheMaxBytes)&&this.cache.size>0;){let o=this.cache.keys().next().value;if(o===void 0)break;this.dropCacheEntry(o)}}dropCacheEntry(e){let r=this.cache.get(e);r&&(this.cache.delete(e),this.cacheBytes-=r.sizeBytes)}clearCache(){this.cache.clear(),this.cacheBytes=0}cacheStats(){return{entries:this.cache.size,bytes:this.cacheBytes}}dispose(){this.disposed||(this.disposed=!0,this.cancelAll(),this.subscribers.clear(),this.clearCache())}runHook(e,...r){if(e)try{e(...r)}catch(n){_chunkH3FZW6OXcjs.e.call(void 0, ).error("[SolveScheduler] hook threw:",n)}}};function fe(t){return T(t)?`ref:${t.key}`:typeof t=="string"&&t.length<200?t:"...content..."}function me(t){return Array.isArray(t)?t.map(e=>{let r=0,n=0,o=_chunkH3FZW6OXcjs.s.call(void 0, e,"innerTree");if(o&&typeof o=="object"){for(let s of Object.values(o))if(Array.isArray(s)){r+=s.length;for(let i of s){let a=_optionalChain([i, 'optionalAccess', _18 => _18.data]);typeof a=="string"&&(n+=a.length)}}}return{param:_nullishCoalesce(_chunkH3FZW6OXcjs.s.call(void 0, e,"paramName"), () => ("<unnamed>")),items:r,bytes:n}}):[]}var A=class t{constructor(e){_chunkH3FZW6OXcjs.b.call(void 0, this,"config");_chunkH3FZW6OXcjs.b.call(void 0, this,"serverStats");_chunkH3FZW6OXcjs.b.call(void 0, this,"disposed",!1);this.config=this.normalizeComputeConfig(e),this.serverStats=new (0, _chunkH3FZW6OXcjs.p)(this.config.serverUrl,this.config.apiKey)}static async create(e){let r=new t(e),n=Math.max(1,(_nullishCoalesce(_optionalChain([e, 'access', _19 => _19.retry, 'optionalAccess', _20 => _20.attempts]), () => (2)))+1),o=_nullishCoalesce(_optionalChain([e, 'access', _21 => _21.retry, 'optionalAccess', _22 => _22.baseDelayMs]), () => (250)),s=_nullishCoalesce(_optionalChain([e, 'access', _23 => _23.retry, 'optionalAccess', _24 => _24.maxDelayMs]), () => (1e3));for(let i=0;i<n;i++){if(await r.serverStats.isServerOnline())return r;if(i<n-1){let a=Math.min(o*2**i,s);await new Promise(u=>setTimeout(u,a))}}throw await r.dispose(),new (0, _chunkH3FZW6OXcjs.d)("Rhino Compute server is not online",_chunkH3FZW6OXcjs.c.NETWORK_ERROR,{context:{serverUrl:r.config.serverUrl,attempts:n}})}getConfig(){return this.ensureNotDisposed(),{...this.config}}async getIO(e){return this.ensureNotDisposed(),G(e,this.config)}async getRawIO(e){return this.ensureNotDisposed(),P(e,this.config)}async solve(e,r,n){this.ensureNotDisposed();try{if(typeof e=="string"&&!_optionalChain([e, 'optionalAccess', _25 => _25.trim, 'call', _26 => _26()]))throw new (0, _chunkH3FZW6OXcjs.d)("Definition URL/content is required",_chunkH3FZW6OXcjs.c.INVALID_INPUT,{context:{receivedUrl:e}});if(e instanceof Uint8Array&&e.length===0)throw new (0, _chunkH3FZW6OXcjs.d)("Definition content is empty",_chunkH3FZW6OXcjs.c.INVALID_INPUT);if(T(e)&&!e.key.trim())throw new (0, _chunkH3FZW6OXcjs.d)("DefinitionRef key is empty",_chunkH3FZW6OXcjs.c.INVALID_INPUT);let o={...this.config,..._optionalChain([n, 'optionalAccess', _27 => _27.signal])!==void 0&&{signal:n.signal},..._optionalChain([n, 'optionalAccess', _28 => _28.timeoutMs])!==void 0&&{timeoutMs:n.timeoutMs},..._optionalChain([n, 'optionalAccess', _29 => _29.retry])!==void 0&&{retry:n.retry}},s=await E(r,e,o);if(_optionalChain([s, 'optionalAccess', _30 => _30.errors])&&s.errors.length>0)throw new (0, _chunkH3FZW6OXcjs.d)(s.errors.join("; ")||"Computation failed",_chunkH3FZW6OXcjs.c.COMPUTATION_ERROR,{context:{definition:fe(e),inputSummary:me(r),errors:s.errors,warnings:s.warnings,values:s.values}});return s}catch(o){throw this.config.debug&&_chunkH3FZW6OXcjs.e.call(void 0, ).error("Compute failed:",o),o instanceof _chunkH3FZW6OXcjs.d?o:new (0, _chunkH3FZW6OXcjs.d)(o instanceof Error?o.message:String(o),_chunkH3FZW6OXcjs.c.COMPUTATION_ERROR,{context:{definition:fe(e),inputSummary:me(r)},originalError:o instanceof Error?o:new Error(String(o))})}}createScheduler(e){this.ensureNotDisposed();let r=(o,s,i)=>E(s,o,i),n=(o,s,i,a)=>i===null?ie(s,o,a).then(u=>({...u,missed:!1})):ae(s,i,o,a);return new x(r,this.config,e,n)}async dispose(){this.disposed||(this.disposed=!0,await this.serverStats.dispose())}ensureNotDisposed(){if(this.disposed)throw new (0, _chunkH3FZW6OXcjs.d)("GrasshopperClient has been disposed and cannot be used",_chunkH3FZW6OXcjs.c.INVALID_STATE)}normalizeComputeConfig(e){return{...e,serverUrl:_chunkH3FZW6OXcjs.o.call(void 0, e.serverUrl),apiKey:e.apiKey,authToken:e.authToken,debug:_nullishCoalesce(e.debug, () => (!1)),suppressBrowserWarning:_nullishCoalesce(e.suppressBrowserWarning, () => (e.suppressClientSideWarning))}}};var V=new Map;function he(t,e){V.set(t,e)}he("Rhino.Geometry.Point3d",(t,e)=>{let r=e;return!r||typeof r.X!="number"?null:new t.Point([r.X,r.Y,r.Z])});he("Rhino.Geometry.Line",(t,e)=>{let r=e;return!r||!r.From||!r.To?null:new t.Line([r.From.X,r.From.Y,r.From.Z],[r.To.X,r.To.Y,r.To.Z])});function Ue(t){if(V.has(t))return V.get(t);for(let[e,r]of V)if(t.startsWith(e))return r}function _e(t){return!!(t&&typeof t=="object"&&typeof t.data=="string")}function de(t,e){return{__decodeError:!0,type:t,raw:e}}function ye(t,e,r){let n=Ue(e),o=!1;if(n)try{let s=n(r,t);if(s!=null)return s}catch(s){_chunkH3FZW6OXcjs.e.call(void 0, ).warn(`Failed to decode Rhino type ${e}:`,s),o=!0}try{if(_e(t))return r.CommonObject.decode(t)}catch(s){return _chunkH3FZW6OXcjs.e.call(void 0, ).warn(`Failed to decode ${e} with CommonObject:`,s),de(e,t)}return o?de(e,t):t}function ge(t){let e=new WeakSet,r=n=>{if(!n||typeof n!="object"||e.has(n))return;e.add(n);let o=n.delete;if(typeof o=="function"){let i=n.isDeleted;(typeof i!="function"||!i.call(n))&&o.call(n);return}if(Array.isArray(n)){for(let i of n)r(i);return}let s=Object.getPrototypeOf(n);if(s===Object.prototype||s===null)for(let i of Object.values(n))r(i)};r(t)}var I={STRING:"System.String",INT:"System.Int32",DOUBLE:"System.Double",BOOL:"System.Boolean"},Ke="Rhino.Geometry.",Qe=["WebDisplay"],He="FileData";function be(t){return Qe.some(e=>t.includes(e))}function Je(t){if(typeof t!="string")return t;let e=t.trim();if(!(e.startsWith("{")||e.startsWith("[")||e.startsWith('"')))return t;try{let n=JSON.parse(e);if(typeof n=="string")try{return JSON.parse(n)}catch (e3){return n}return n}catch (e4){return t}}function Ye(t,e,r){switch(e){case I.STRING:return typeof t!="string"?t:t.replace(/^"(.*)"$/,"$1");case I.INT:return Number.parseInt(t,10);case I.DOUBLE:return Number.parseFloat(t);case I.BOOL:return String(t).toLowerCase()==="true";default:return r&&e.startsWith(Ke)?ye(t,e,r):t}}var U=new WeakMap;function Te(t){if(U.has(t))return U.get(t);let e=Je(t.data);return U.set(t,e),e}function Se(t,e,r,n){if(typeof t.data!="string")return t.data;let o=r?Te(t):t.data;return Ye(o,e,n)}function Xe(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.fileName=="string"&&typeof e.fileType=="string"&&"data"in e&&typeof e.isBase64Encoded=="boolean"&&typeof e.subFolder=="string"}function _(t){let e=_chunkH3FZW6OXcjs.s.call(void 0, t,"values");return Array.isArray(e)?e:[]}function K(t){return typeof t.type=="string"?t.type:""}function Q(t,e){if(!(!t||typeof t!="object")){for(let r of Object.values(t))if(Array.isArray(r))for(let n of r)n&&typeof n=="object"&&e(n)}}function De(t,e=!1,r={}){let{parseValues:n=!0,rhino:o,stringOnly:s=!1}=r,i={},a=new Set;for(let u of _(t)){let m=_chunkH3FZW6OXcjs.s.call(void 0, u,"paramName");Q(_chunkH3FZW6OXcjs.s.call(void 0, u,"innerTree"),f=>{let d=K(f);if(be(d)||s&&d!==I.STRING)return;let g=e?f.id:m;if(!g)return;let b=Se(f,d,n,o);g in i?a.has(g)?i[g].push(b):(i[g]=[i[g],b],a.add(g)):i[g]=b})}return{values:i,dispose:()=>ge(i)}}function xe(t){let e=[];for(let r of _(t))Q(_chunkH3FZW6OXcjs.s.call(void 0, r,"innerTree"),n=>{if(!K(n).includes(He))return;let o=Te(n);Xe(o)&&e.push(o)});return e}function Ie(t,e,r={}){let{parseValues:n=!0,rhino:o,stringOnly:s=!1}=r;for(let i of _(t)){let a=_chunkH3FZW6OXcjs.s.call(void 0, i,"innerTree"),u=!1;if("byName"in e){if(_chunkH3FZW6OXcjs.s.call(void 0, i,"paramName")!==e.byName)continue;u=!0}let m=[];if(Q(a,f=>{if("byId"in e){if(f.id!==e.byId)return;u=!0}let d=K(f);be(d)||s&&d!==I.STRING||m.push(Se(f,d,n,o))}),u)return m.length===0?void 0:m.length===1?m[0]:m}}var k=class{constructor(e,r=!1){_chunkH3FZW6OXcjs.b.call(void 0, this,"response",e);_chunkH3FZW6OXcjs.b.call(void 0, this,"debug",r)}getValues(e=!1,r={}){return De(this.response,e,r)}getValue(e,r){return Ie(this.response,e,r)}async extractMeshesFromResponse(e){let r={debug:this.debug,...e},n;try{({getThreeMeshesFromComputeResponse:n}=await Promise.resolve().then(() => _interopRequireWildcard(require("./visualization-FLDYIZ3F.cjs"))))}catch(o){throw new (0, _chunkH3FZW6OXcjs.d)("Failed to load three.js visualization module. Ensure three.js is installed as a peer dependency.",_chunkH3FZW6OXcjs.c.INVALID_STATE,{context:{originalError:o instanceof Error?o.message:String(o)}})}return n(this.response,r)}getFileData(){return xe(this.response)}async getAndDownloadFiles(e,r){let n=this.getFileData();await _chunkH3FZW6OXcjs.v.call(void 0, n,e,r)}};var H=/^\{(-?\d+(?:;-?\d+)*)?\}$/;function C(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=Object.entries(t);return e.length>0&&e.every(([r,n])=>H.test(r)&&Array.isArray(n))}function w(t,e,r){if(t==null)return t;if(Array.isArray(t)){let o=t.map(e).filter(s=>s!==null);return o.length>0?o:void 0}let n=e(t);return n!==null?n:r?void 0:t}var L=t=>{if(typeof t=="number")return Number.isFinite(t)?t:null;if(typeof t=="string"){let e=t.trim();if(e===""||/^[+-]?0[xbo]/i.test(e))return null;let r=Number(e);return Number.isFinite(r)?r:null}return null},J=t=>{if(typeof t=="boolean")return t;if(typeof t=="string"){let e=t.trim().toLowerCase();if(e==="true")return!0;if(e==="false")return!1}return null},Ze=t=>typeof t=="string"?t.length>=2&&t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t.startsWith('"')?t.slice(1):t:null,et=t=>{if(typeof t=="string"){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')&&(e=e.slice(1,-1).trim()),e}return null};function we(t){return e=>{if(typeof e=="object"&&e!==null)return e;if(typeof e=="string"&&e.trim()!=="")try{let r=JSON.parse(e);return typeof r=="object"&&r!==null?r:(_chunkH3FZW6OXcjs.e.call(void 0, ).warn(`Parsed value for input ${t} is not an object`),null)}catch(r){return _chunkH3FZW6OXcjs.e.call(void 0, ).warn(`Failed to parse object value "${e}" for input ${t}`,r),null}return null}}function Ce(t,e,r){let n=Number(t.toFixed(e));return Math.abs(t-n)<r?n:t}function tt(t,e){if(!Number.isFinite(t)||t===0)return .1;let r=Math.abs(t);if(r>=1){let g=String(t).split(".")[1];if(g&&g.length>0){let b=Math.min(g.length,12),S=Math.pow(10,-b),X=Number(S.toFixed(b));return Math.abs(X-S)<e?X:S}return 1}let n=String(t),o=n.toLowerCase().match(/e(-?\d+)/);if(o){let d=Number(o[1]);if(d<0||n.toLowerCase().includes("e-")){let g=Math.abs(d),b=Math.pow(10,-g),S=Number(b.toFixed(g));return Math.abs(S-b)<e?S:b}return .1}let s=12,a=r.toFixed(s).replace(/0+$/,""),u=Math.min((a.split(".")[1]||"").length,s);if(u===0)return .1;let m=Math.pow(10,-u),f=Number(m.toFixed(u));return Math.abs(f-m)<e?f:m}function Ee(t){return typeof t.stepSize=="number"&&Number.isFinite(t.stepSize)&&t.stepSize>0?t.stepSize:void 0}function rt(t,e=1e-8){let r=t.paramType==="Integer",n=Ee(t);if(C(t.default))return{default:t.default,stepSize:_nullishCoalesce(n, () => ((r?1:.1)))};if(typeof t.default=="string"&&t.default.trim()!==""&&L(t.default)===null)throw new (0, _chunkH3FZW6OXcjs.d)(`Invalid numeric default "${t.default}" for input "${t.name||"unknown"}"`,_chunkH3FZW6OXcjs.c.VALIDATION_ERROR,{context:{inputName:t.name,default:t.default}});let o=w(t.default,L,!0);if(r)return Array.isArray(o)?o=o.map(d=>typeof d=="number"?Math.round(d):d):typeof o=="number"&&(o=Math.round(o)),{default:o,stepSize:_nullishCoalesce(n, () => (1))};let s=Array.isArray(o)?o[0]:o,i;typeof s=="number"&&Number.isFinite(s)&&s!==0?i=s:typeof t.minimum=="number"&&Number.isFinite(t.minimum)&&t.minimum!==0?i=t.minimum:typeof t.maximum=="number"&&Number.isFinite(t.maximum)&&t.maximum!==0&&(i=t.maximum);let a=_nullishCoalesce(n, () => ((i!==void 0?tt(i,e):.1))),u=0,m=String(a),f=m.toLowerCase().match(/e(-?\d+)/);if(f?u=Math.abs(Number(f[1])):u=_nullishCoalesce(_optionalChain([m, 'access', _31 => _31.split, 'call', _32 => _32("."), 'access', _33 => _33[1], 'optionalAccess', _34 => _34.length]), () => (0)),u===0&&typeof s=="number"&&s!==0&&Math.abs(s)<1){let d=Math.ceil(-Math.log10(Math.abs(s)));Number.isFinite(d)&&d>0&&(u=d)}return u=Math.min(Math.max(u,0),12),Array.isArray(o)?o=o.map(d=>typeof d=="number"?Ce(d,u,e):d):typeof o=="number"&&(o=Ce(o,u,e)),{default:o,stepSize:a}}var nt={types:["Number","Integer"],parse(t,e){let{default:r,stepSize:n}=rt(t);return{...e,paramType:t.paramType,minimum:t.minimum,maximum:t.maximum,atLeast:t.atLeast,atMost:t.atMost,stepSize:n,default:r}},fallback(t,e){let r=(_nullishCoalesce(t.atMost, () => (1)))>1,n=typeof t.minimum=="number"&&Number.isFinite(t.minimum)&&t.minimum>0?t.minimum:0;return{...e,paramType:t.paramType,minimum:t.minimum,maximum:t.maximum,atLeast:t.atLeast,atMost:t.atMost,stepSize:_nullishCoalesce(Ee(t), () => ((t.paramType==="Integer"?1:.1))),default:r?[n]:n}}},ot={types:["Boolean"],parse(t,e){if(C(t.default))return{...e,paramType:"Boolean",default:t.default};let r=w(t.default,J,!1);if(r!=null&&typeof r!="boolean"&&!Array.isArray(r))throw new (0, _chunkH3FZW6OXcjs.d)(`Invalid boolean default "${String(r)}" for input "${t.name||"unknown"}"`,_chunkH3FZW6OXcjs.c.VALIDATION_ERROR,{context:{inputName:t.name,default:t.default}});return{...e,paramType:"Boolean",default:r}},fallback(t,e){let r=(_nullishCoalesce(t.atMost, () => (1)))>1;return{...e,paramType:"Boolean",default:r?[!1]:!1}}},st={types:["Text"],parse(t,e){let r=w(t.default,Ze,!1);return{...e,paramType:"Text",default:r}},fallback(t,e){let r=(_nullishCoalesce(t.atMost, () => (1)))>1;return{...e,paramType:"Text",default:r?[""]:""}}},it={types:["ValueList"],parse(t,e){if(!t.values||typeof t.values!="object"||Object.keys(t.values).length===0)throw _chunkH3FZW6OXcjs.d.missingValues(t.nickname||"unnamed","ValueList");let r=t.default;if(t.default!==void 0&&t.default!==null){if(typeof t.default=="object")throw new (0, _chunkH3FZW6OXcjs.d)(`ValueList input "${t.nickname||"unnamed"}" default is not a string-able value`,_chunkH3FZW6OXcjs.c.VALIDATION_ERROR,{context:{inputName:t.name,default:t.default}});let n=String(t.default).toLowerCase(),o=Object.keys(t.values).find(s=>s.toLowerCase()===n);o!==void 0?r=o:_chunkH3FZW6OXcjs.e.call(void 0, ).warn(`ValueList input "${t.nickname||"unnamed"}" default value "${t.default}" is not in available values`)}return{...e,paramType:"ValueList",values:t.values,default:r}},fallback(t,e){return{...e,paramType:"ValueList",values:t.values&&typeof t.values=="object"?t.values:{},default:void 0}}},ve={types:["Geometry"],parse(t,e){let r=w(t.default,we(t.nickname||"unnamed"),!0);return{...e,paramType:"Geometry",default:r}},fallback(t,e){let r=(_nullishCoalesce(t.atMost, () => (1)))>1;return{...e,paramType:"Geometry",default:r?[null]:null}}},at={types:["File"],parse(t,e){let r=w(t.default,we(t.nickname||"unnamed"),!0);return{...e,paramType:"File",acceptedFormats:t.acceptedFormats,default:r}},fallback(t,e){let r=(_nullishCoalesce(t.atMost, () => (1)))>1;return{...e,paramType:"File",default:r?[null]:null}}},ut={types:["Color"],parse(t,e){let r=w(t.default,et,!1);return{...e,paramType:"Color",default:r}},fallback(t,e){let r=(_nullishCoalesce(t.atMost, () => (1)))>1;return{...e,paramType:"Color",default:r?["0, 0, 0"]:"0, 0, 0"}}},pt=[nt,ot,st,it,ve,at,ut],Y=new Map(pt.flatMap(t=>t.types.map(e=>[e,t]))),Re=ve;function Ae(t){return _chunkH3FZW6OXcjs.s.call(void 0, t,"data")}function lt(t){return _chunkH3FZW6OXcjs.s.call(void 0, t,"type")}var ct=new Set(["System.Double","System.Single","System.Decimal","System.Int32","System.Int64"]),ft=new Set(["System.Int32","System.Int64"]);function Pe(t){if(typeof t.default!="object"||t.default===null)return{schema:t};if(Array.isArray(t.default))return{schema:t};if(!_chunkH3FZW6OXcjs.t.call(void 0, t.default,"innerTree")){let n=`Input "${_nullishCoalesce(t.name, () => ("unknown"))}" default had an unrecognized shape (no innerTree key); the default was dropped.`;return _chunkH3FZW6OXcjs.e.call(void 0, ).warn("Unexpected structure in input.default:",t.default),{schema:{...t,default:null},warning:{code:"MALFORMED_DEFAULT",message:n}}}let e=_nullishCoalesce(_chunkH3FZW6OXcjs.s.call(void 0, t.default,"innerTree"), () => ({}));if(Object.keys(e).length===0)return{schema:{...t,default:void 0}};if(t.treeAccess||t.atMost&&t.atMost>1){let n={},o=[];for(let[i,a]of Object.entries(e)){if(!Array.isArray(a)){let m=`Input "${_nullishCoalesce(t.name, () => ("unknown"))}" default had a non-array innerTree branch ("${i}"); the default was dropped.`;return _chunkH3FZW6OXcjs.e.call(void 0, ).warn("Unexpected structure in input.default innerTree:",t.default),{schema:{...t,default:null},warning:{code:"MALFORMED_DEFAULT",message:m}}}let u=[];for(let m of a){let f=Ae(m),d=lt(m);if(d&&ct.has(d)){if(typeof f=="string"&&f.trim()==="")continue;let g=L(f);if(g===null){o.push(`"${String(f)}" (${d})`);continue}u.push(ft.has(d)?Math.round(g):g);continue}if(d==="System.Boolean"){let g=J(f);if(g===null){o.push(`"${String(f)}" (${d})`);continue}u.push(g);continue}if(typeof f=="string"&&_optionalChain([d, 'optionalAccess', _35 => _35.startsWith, 'call', _36 => _36("Rhino.Geometry")])){try{u.push(JSON.parse(f))}catch (e5){u.push(f)}continue}u.push(f)}n[i]=u}let s;if(o.length>0){let i=`Input "${_nullishCoalesce(t.name, () => ("unknown"))}" default contained ${o.length} tree value(s) that could not be parsed and were dropped: ${o.join(", ")}.`;_chunkH3FZW6OXcjs.e.call(void 0, ).warn(i),s={code:"MALFORMED_DEFAULT",message:i}}return{schema:{...t,default:n},...s&&{warning:s}}}let r=[];for(let n of Object.values(e))Array.isArray(n)&&n.forEach(o=>{o&&typeof o=="object"&&_chunkH3FZW6OXcjs.t.call(void 0, o,"data")&&r.push(Ae(o))});return r.length===0?{schema:{...t,default:void 0}}:r.length===1?{schema:{...t,default:r[0]}}:{schema:{...t,default:r}}}var mt=new Map([...Y.keys()].map(t=>[t.toLowerCase(),t]));function dt(t){return _nullishCoalesce(mt.get(_optionalChain([t, 'optionalAccess', _37 => _37.toLowerCase, 'call', _38 => _38()])), () => (t))}function ke(t){return Oe(t).input}function Oe(t){let e={description:t.description,name:t.name,nickname:t.nickname,treeAccess:t.treeAccess,groupName:_nullishCoalesce(t.groupName, () => (void 0)),id:t.id},r=dt(t.paramType),n={...t,paramType:r},o;try{let{schema:i,warning:a}=Pe(n);n=i,o=a&&{inputName:t.name||"unknown",paramType:t.paramType,message:a.message,code:a.code}}catch(i){n={...n,default:null},o={inputName:t.name||"unknown",paramType:t.paramType,message:`Input "${_nullishCoalesce(t.name, () => ("unknown"))}" default could not be normalized and was dropped: ${i instanceof Error?i.message:String(i)}`,code:"MALFORMED_DEFAULT"}}let s=Y.get(r);try{if(!s)throw _chunkH3FZW6OXcjs.d.unknownParamType(r,t.name);return{input:s.parse(n,e),error:o,...o&&{errors:[o]}}}catch(i){if(i instanceof _chunkH3FZW6OXcjs.d){_chunkH3FZW6OXcjs.e.call(void 0, ).error(`Validation error for input ${t.name||"unknown"}:`,i.message);let a={inputName:t.name||"unknown",paramType:t.paramType,message:i.message,code:i.code};return{input:(_nullishCoalesce(s, () => (Re))).fallback(n,e),error:a,errors:o?[o,a]:[a]}}throw new (0, _chunkH3FZW6OXcjs.d)(i instanceof Error?i.message:String(i),"VALIDATION_ERROR",{context:{paramName:t.name,paramType:r},originalError:i instanceof Error?i:new Error(String(i))})}}function Me(t){return W(t).inputs}function W(t){let e=[],r=[];for(let n of t){let{input:o,errors:s}=Oe(n);e.push(o),s&&r.push(...s)}return{inputs:e,parseErrors:r}}function Fe(t){let e=_chunkH3FZW6OXcjs.s.call(void 0, t,"stepSize");return{id:_nullishCoalesce(_chunkH3FZW6OXcjs.s.call(void 0, t,"id"), () => ("")),name:_nullishCoalesce(_chunkH3FZW6OXcjs.s.call(void 0, t,"name"), () => ("")),nickname:_nullishCoalesce(_chunkH3FZW6OXcjs.s.call(void 0, t,"nickname"), () => (null)),description:_nullishCoalesce(_chunkH3FZW6OXcjs.s.call(void 0, t,"description"), () => ("")),paramType:_nullishCoalesce(_chunkH3FZW6OXcjs.s.call(void 0, t,"paramType"), () => ("")),treeAccess:_nullishCoalesce(_chunkH3FZW6OXcjs.s.call(void 0, t,"treeAccess"), () => (!1)),minimum:_nullishCoalesce(_chunkH3FZW6OXcjs.s.call(void 0, t,"minimum"), () => (null)),maximum:_nullishCoalesce(_chunkH3FZW6OXcjs.s.call(void 0, t,"maximum"), () => (null)),atLeast:_nullishCoalesce(_chunkH3FZW6OXcjs.s.call(void 0, t,"atLeast"), () => (1)),atMost:_nullishCoalesce(_chunkH3FZW6OXcjs.s.call(void 0, t,"atMost"), () => (1)),stepSize:typeof e=="number"&&Number.isFinite(e)?e:void 0,default:_chunkH3FZW6OXcjs.s.call(void 0, t,"default"),values:_chunkH3FZW6OXcjs.s.call(void 0, t,"values"),acceptedFormats:_chunkH3FZW6OXcjs.s.call(void 0, t,"acceptedFormats"),groupName:_nullishCoalesce(_chunkH3FZW6OXcjs.s.call(void 0, t,"groupName"), () => (null))}}function Ne(t){return{name:_nullishCoalesce(_chunkH3FZW6OXcjs.s.call(void 0, t,"name"), () => ("")),nickname:_nullishCoalesce(_chunkH3FZW6OXcjs.s.call(void 0, t,"nickname"), () => (null)),paramType:_nullishCoalesce(_chunkH3FZW6OXcjs.s.call(void 0, t,"paramType"), () => ("")),id:_nullishCoalesce(_chunkH3FZW6OXcjs.s.call(void 0, t,"id"), () => (""))}}async function P(t,e){let r=v(t,[]),n={};if(r.algo&&(n.algo=r.algo),r.pointer&&(n.pointer=r.pointer),!n.algo&&!n.pointer)throw new (0, _chunkH3FZW6OXcjs.d)("Definition must resolve to either a URL pointer or base64 algo",_chunkH3FZW6OXcjs.c.INVALID_INPUT,{context:{definition:t}});let o=await _chunkH3FZW6OXcjs.n.call(void 0, "io",n,e);if(!o||typeof o!="object")throw new (0, _chunkH3FZW6OXcjs.d)("Invalid IO response structure",_chunkH3FZW6OXcjs.c.INVALID_INPUT,{context:{response:o,definition:t}});let s=Ge(_chunkH3FZW6OXcjs.s.call(void 0, o,"warnings")),i=Ge(_chunkH3FZW6OXcjs.s.call(void 0, o,"errors")),a=_chunkH3FZW6OXcjs.s.call(void 0, o,"inputs"),u=_chunkH3FZW6OXcjs.s.call(void 0, o,"outputs");return{inputs:Array.isArray(a)?a.map(Fe):[],outputs:Array.isArray(u)?u.map(Ne):[],...s&&{loadWarnings:s},...i&&{loadErrors:i}}}function Ge(t){if(!Array.isArray(t))return;let e=t.map(ht).filter(r=>r!==void 0);return e.length>0?e:void 0}function ht(t){if(t==null)return;let e;if(typeof t=="string")e=t;else if(typeof t=="object"){let r=_chunkH3FZW6OXcjs.s.call(void 0, t,"message");if(typeof r=="string"&&r.trim().length>0)e=r;else try{e=_nullishCoalesce(JSON.stringify(t), () => (String(t)))}catch (e6){e=String(t)}}else e=String(t);return e.trim().length>0?e:void 0}async function G(t,e){D("fetchParsedDefinitionIO",_nullishCoalesce(e.suppressBrowserWarning, () => (e.suppressClientSideWarning)));let{inputs:r,outputs:n,loadWarnings:o,loadErrors:s}=await P(t,e),{inputs:i,parseErrors:a}=W(r);return{inputs:i,outputs:n,...a.length>0&&{parseErrors:a},...o&&{loadWarnings:o},...s&&{loadErrors:s}}}var B=class t{constructor(e){_chunkH3FZW6OXcjs.b.call(void 0, this,"innerTree");_chunkH3FZW6OXcjs.b.call(void 0, this,"paramName");this.paramName=e,this.innerTree={}}append(e,r){let n=t.formatPathString(e);this.innerTree[n]||(this.innerTree[n]=[]);let o=r.map(s=>({data:t.serializeValue(s)}));return this.innerTree[n].push(...o),this}appendSingle(e,r){return this.append(e,[r])}fromDataTreeDefault(e){this.innerTree={};for(let[r,n]of Object.entries(e)){if(!Array.isArray(n))continue;let o=t.parsePathString(r);this.append(o,n)}return this}appendFlat(e){let r=Array.isArray(e)?e:[e];return this.append([0],r)}flatten(){let e=[];for(let r of Object.values(this.innerTree))if(Array.isArray(r))for(let n of r)e.push(t.deserializeValue(n.data));return e}getPaths(){return Object.keys(this.innerTree)}getPath(e){let r=t.formatPathString(e),n=this.innerTree[r];if(n)return n.map(o=>t.deserializeValue(o.data))}toComputeFormat(){return{ParamName:this.paramName,InnerTree:this.innerTree}}getInnerTree(){return this.innerTree}getParamName(){return this.paramName}static fromInputParams(e){return e.filter(r=>t.hasValidValue(r.default)).map(r=>{let n=new t(r.nickname||"unnamed"),o=r.default;if(r.treeAccess&&C(o))n.fromDataTreeDefault(o),t.isNumericInput(r)&&n.applyNumericConstraints(r.minimum,r.maximum,r.nickname||"unnamed");else{let s=Array.isArray(o)?o:[o],i=t.processValues(s,r);n.appendFlat(i)}return n.toComputeFormat()})}static fromInputParam(e){return t.hasValidValue(e.default)?t.fromInputParams([e])[0]:void 0}static replaceTreeValue(e,r,n){let o=e.length>0&&e[0]instanceof t,s=t.buildFromValue(r,n);if(o){let m=e.slice(),f=m.findIndex(d=>d.getParamName()===r);return f!==-1?m[f]=s:m.push(s),m}let i=e.slice(),a=s.toComputeFormat(),u=i.findIndex(m=>m.ParamName===r);return u!==-1?i[u]=a:i.push(a),i}static buildFromValue(e,r){let n=new t(e);return C(r)?n.fromDataTreeDefault(r):n.appendFlat(r),n}static getTreeValue(e,r){let o=e.length>0&&e[0]instanceof t?t.readFromBuilders(e,r):t.readFromDataTrees(e,r);return o===null||o.length===0?null:o.length===1?o[0]:o}static readFromBuilders(e,r){let n=e.find(o=>o.getParamName()===r);return n?n.flatten():null}static readFromDataTrees(e,r){let n=e.find(i=>i.ParamName===r);if(!_optionalChain([n, 'optionalAccess', _39 => _39.InnerTree]))return null;let o=Object.keys(n.InnerTree)[0];if(!o)return null;let s=n.InnerTree[o];return Array.isArray(s)?s.map(i=>_optionalChain([i, 'optionalAccess', _40 => _40.data])!==void 0?t.deserializeValue(i.data):null):_optionalChain([s, 'optionalAccess', _41 => _41.data])!==void 0?[t.deserializeValue(s.data)]:s!==void 0?[s]:null}static parsePathString(e){let r=e.match(H);if(!r)throw new Error(`Invalid Grasshopper tree path: "${e}". Expected "{}", "{0}", or "{0;1;2}" (negative indices allowed, no empty segments).`);return r[1]?r[1].split(";").map(Number):[]}static formatPathString(e){return`{${e.join(";")}}`}applyNumericConstraints(e,r,n){for(let o of Object.values(this.innerTree))if(Array.isArray(o))for(let s of o){let i=t.deserializeValue(s.data);if(typeof i=="number"){let a=t.clampValue(i,e,r,n);s.data=t.serializeValue(a)}}}static serializeValue(e){return typeof e=="boolean"||typeof e=="number"||typeof e=="string"?e:typeof e=="object"&&e!==null?JSON.stringify(e):String(e)}static deserializeValue(e){if(typeof e=="boolean"||typeof e=="number"||typeof e!="string")return e;if(e.startsWith("{")||e.startsWith("["))try{return JSON.parse(e)}catch (e7){return e}let r=Number(e);return Number.isFinite(r)&&String(r)===e?r:e==="true"?!0:e==="false"?!1:e}static hasValidValue(e){return e==null?!1:typeof e=="string"?!0:!(Array.isArray(e)&&e.length===0||typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0)}static isNumericInput(e){return e.paramType==="Number"||e.paramType==="Integer"}static processValues(e,r){return e.map(n=>t.isNumericInput(r)&&typeof n=="number"?t.clampValue(n,r.minimum,r.maximum,r.nickname||"unnamed"):n).filter(n=>n!=null)}static clampValue(e,r,n,o){let s=e;return r!=null&&s<r&&(_chunkH3FZW6OXcjs.e.call(void 0, ).warn(`${o}: ${e} below min ${r}, clamping`),s=r),n!=null&&s>n&&(_chunkH3FZW6OXcjs.e.call(void 0, ).warn(`${o}: ${e} above max ${n}, clamping`),s=n),s}};exports.a = T; exports.b = E; exports.c = $; exports.d = ce; exports.e = R; exports.f = x; exports.g = A; exports.h = k; exports.i = ke; exports.j = Me; exports.k = P; exports.l = G; exports.m = B;
2
+ //# sourceMappingURL=chunk-6R4EL3ZJ.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/selva/selva/packages/compute/dist/chunk-6R4EL3ZJ.cjs","../src/core/utils/warnings.ts","../src/features/grasshopper/definition-ref.ts","../src/features/grasshopper/solve.ts"],"names":["warnedFunctions","isRealBrowser","nav","userAgent","warnIfClientSide","functionName","suppress","getLogger","isDefinitionRef","definition","DEFINITION_LOAD_FAILED","isDefinitionLoadMiss","error","RhinoComputeError","ErrorCodes","warnOnEmptyInnerTrees","response","debug","values","readField","empty","param","innerTree","scope"],"mappings":"AAAA,2/BAA+I,ICGzIA,EAAAA,CAAkB,IAAI,GAAA,CAa5B,SAASC,EAAAA,CAAAA,CAAyB,CAIjC,EAAA,CAHI,OAAO,MAAA,CAAW,GAAA,kBAER,UAAA,qBAA+D,OAAA,6BACnE,QAAA,6BAAU,MAAA,EAAQ,IAAA,CAAM,MAAO,CAAA,CAAA,CAEzC,IAAMC,CAAAA,CAAO,UAAA,CAAuD,SAAA,CAC9DC,CAAAA,CAAY,uBAAOD,CAAAA,6BAAK,WAAA,EAAc,QAAA,CAAWA,CAAAA,CAAI,SAAA,CAAY,EAAA,CACvE,MAAI,CAAA,QAAA,CAAS,IAAA,CAAKC,CAAS,CAG5B,CAEO,SAASC,CAAAA,CAAiBC,CAAAA,CAAsBC,CAAAA,CAA0B,CAC5EA,CAAAA,EAIAL,EAAAA,CAAc,CAAA,EAAK,CAACD,EAAAA,CAAgB,GAAA,CAAIK,CAAY,CAAA,EAAA,CACvDL,EAAAA,CAAgB,GAAA,CAAIK,CAAY,CAAA,CAChCE,iCAAAA,CAAU,CAAE,IAAA,CACX,CAAA,SAAA,EAAYF,CAAY,CAAA,8GAAA,CACzB,CAAA,CAEF,CCKO,SAASG,CAAAA,CAAgBC,CAAAA,CAA0D,CACzF,OACC,OAAOA,CAAAA,EAAe,QAAA,EACtB,CAAA,CAAEA,EAAAA,WAAsB,UAAA,CAAA,EACxB,OAAOA,CAAAA,CAAW,GAAA,EAAQ,QAAA,EAC1B,OAAOA,CAAAA,CAAW,IAAA,EAAS,UAE7B,CCvBA,IAAMC,EAAAA,CAAyB,uCAAA,CAG/B,SAASC,EAAAA,CAAqBC,CAAAA,CAAyB,CACtD,OAAMA,EAAAA,WAAiBC,mBAAAA,CAEtBD,CAAAA,CAAM,IAAA,GAASE,mBAAAA,CAAW,qBAAA,EAC1BF,CAAAA,CAAM,OAAA,CAAQ,QAAA,CAASF,EAAsB,CAAA,CAHI,CAAA,CAKnD,CAeO,SAASK,EAAAA,CAAsBC,CAAAA,CAAsCC,CAAAA,CAAuB,CAClG,EAAA,CAAI,CAACA,CAAAA,CAAO,MAAA,CAEZ,IAAMC,CAAAA,CAASC,iCAAAA,CAAqBH,CAAU,QAAQ,CAAA,CACtD,EAAA,CAAI,CAAC,KAAA,CAAM,OAAA,CAAQE,CAAM,CAAA,EAAKA,CAAAA,CAAO,MAAA,GAAW,CAAA,CAAG,MAAA,CAEnD,IAAME,CAAAA,CAAkB,CAAC,CAAA,CACzB,GAAA,CAAA,IAAWC,EAAAA,GAASH,CAAAA,CAAQ,CAC3B,IAAMI,CAAAA,CAAYH,iCAAAA,CAAmCE,CAAO,WAAW,CAAA,CAAA,CAEnE,CAACC,CAAAA,EAAa,MAAA,CAAO,IAAA,CAAKA,CAAS,CAAA,CAAE,MAAA,GAAW,CAAA,CAAA,EACnDF,CAAAA,CAAM,IAAA,kBAAKD,iCAAAA,CAAkBE,CAAO,WAAW,CAAA,SAAK,aAAW,CAEjE,CAEA,EAAA,CAAID,CAAAA,CAAM,MAAA,GAAW,CAAA,CAAG,MAAA,CAExB,IAAMG,CAAAA,CAAQH,CAAAA,CAAM,MAAA,GAAWF,CAAAA,CAAO,MAAA,CAAS,KAAA,CAAQ,CAAA,EAAA","file":"/home/runner/work/selva/selva/packages/compute/dist/chunk-6R4EL3ZJ.cjs","sourcesContent":[null,"import { getLogger } from './logger';\n\n/** Functions that already warned — the exposure risk doesn't change per call, so once is enough. */\nconst warnedFunctions = new Set<string>();\n\n/**\n * True only in a GENUINE browser/worker context — the case where an API key in\n * the config is actually exposed to end users. `typeof window !== 'undefined'`\n * alone is not enough: jsdom test environments define `window` too, and every\n * unsuppressed vitest/jest run would warn noisily (issue 110).\n *\n * Detection: `window` must exist, AND we must not be in Node (jsdom runs in\n * Node, so `process.versions.node` is defined there but never in a real\n * browser), AND the user agent must not carry jsdom's marker (belt-and-braces\n * for exotic setups that hide `process`). Genuine browsers pass all three.\n */\nfunction isRealBrowser(): boolean {\n\tif (typeof window === 'undefined') return false;\n\n\tconst proc = (globalThis as { process?: { versions?: { node?: unknown } } }).process;\n\tif (proc?.versions?.node != null) return false;\n\n\tconst nav = (globalThis as { navigator?: { userAgent?: unknown } }).navigator;\n\tconst userAgent = typeof nav?.userAgent === 'string' ? nav.userAgent : '';\n\tif (/jsdom/i.test(userAgent)) return false;\n\n\treturn true;\n}\n\nexport function warnIfClientSide(functionName: string, suppress?: boolean): void {\n\tif (suppress) {\n\t\treturn;\n\t}\n\n\tif (isRealBrowser() && !warnedFunctions.has(functionName)) {\n\t\twarnedFunctions.add(functionName);\n\t\tgetLogger().warn(\n\t\t\t`Warning: ${functionName} is running on the client side. For better performance and security, consider running this on the server side.`\n\t\t);\n\t}\n}\n\n/** @internal Reset the once-per-function dedupe — for tests only. */\nexport function resetClientSideWarnings(): void {\n\twarnedFunctions.clear();\n}\n","/**\n * By-reference definition form for solves.\n *\n * Lets a caller that already knows a definition's identity (e.g. a stored\n * version's UUID) schedule solves without materializing the multi-MB bytes:\n * cache keys and the server-pointer map are derived from `key` alone, and\n * `load()` is only called when an upload is genuinely unavoidable (first solve\n * of a definition, or a server-side pointer miss).\n */\n\n/**\n * A definition identified by a stable key, with bytes materialized on demand.\n *\n * **Immutability contract — read this before constructing one.** `key` must\n * identify IMMUTABLE bytes: every `load()` for a given `key` must return the\n * same content, forever. All caching (the scheduler's result cache, the\n * server-pointer map, and any durable cache built on these keys) trusts the\n * key as the definition's identity WITHOUT looking at the bytes. If two\n * different byte contents ever share a key, cached solves from one are served\n * for the other — silent cache poisoning with no diagnostic. Use an identity\n * that can never be reused for different content (e.g. a version UUID), never\n * a mutable name or path.\n */\nexport interface DefinitionRef {\n\t/**\n\t * Identity of immutable bytes (e.g. a version UUID). Two different byte\n\t * contents must never share a key — cache poisoning otherwise.\n\t */\n\tkey: string;\n\t/**\n\t * Materialize the bytes. Called ONLY when an upload is unavoidable — inside\n\t * the solve execution, so it counts toward the solve's abort semantics.\n\t */\n\tload: () => Promise<Uint8Array>;\n}\n\n/**\n * Every definition form accepted by the solve entry points:\n * - a URL, base64 string, or plain string (content-hashed for caching)\n * - raw `.gh` bytes (content-hashed)\n * - a {@link DefinitionRef} (identity-keyed; bytes loaded lazily)\n */\nexport type SolveDefinition = string | Uint8Array | DefinitionRef;\n\n/** Narrow a {@link SolveDefinition} to the by-reference form. */\nexport function isDefinitionRef(definition: SolveDefinition): definition is DefinitionRef {\n\treturn (\n\t\ttypeof definition === 'object' &&\n\t\t!(definition instanceof Uint8Array) &&\n\t\ttypeof definition.key === 'string' &&\n\t\ttypeof definition.load === 'function'\n\t);\n}\n","import { fetchRhinoCompute, RhinoComputeError, ErrorCodes } from '@/core';\nimport { getResponseWireSize, setResponseWireSize } from '@/core/compute-fetch/wire-size';\nimport { base64ByteArray, detectBase64Payload, encodeStringToBase64 } from '@/core/utils/encoding';\nimport { getLogger } from '@/core/utils/logger';\nimport { readField } from '@/core/utils/read-field';\nimport { warnIfClientSide } from '@/core/utils/warnings';\n\nimport {\n\tGrasshopperRequestSchema,\n\tGrasshopperComputeConfig,\n\tGrasshopperComputeResponse,\n\tDataTree\n} from './types';\nimport { isDefinitionRef, type SolveDefinition } from './definition-ref';\n\n/**\n * The exact message the server throws when it can neither resolve a `pointer`\n * nor a base64 `algo` to a definition (ResthopperEndpoints.cs). This is the\n * signal that a cache-key pointer missed the server's definition cache (GC'd, or\n * a different child in the pool), so the caller should retry with the full\n * definition. Matched as a substring because the server wraps it with a category\n * prefix in its exception handler.\n *\n * NOTE: the server only includes this message when running in debug mode; its\n * production exception handler scrubs the message to a generic string. The\n * reliable signal is therefore {@link ErrorCodes.DEFINITION_NOT_CACHED}, derived\n * from the server's machine `code` (which isn't scrubbed). The string match is\n * kept as a fallback for debug-mode servers and forks that don't yet emit a code.\n */\nconst DEFINITION_LOAD_FAILED = 'Unable to load grasshopper definition';\n\n/** Does this error look like a server-side definition-load miss? */\nfunction isDefinitionLoadMiss(error: unknown): boolean {\n\tif (!(error instanceof RhinoComputeError)) return false;\n\treturn (\n\t\terror.code === ErrorCodes.DEFINITION_NOT_CACHED ||\n\t\terror.message.includes(DEFINITION_LOAD_FAILED)\n\t);\n}\n\n/**\n * Debug aid: a solve can return successfully yet hand back outputs whose\n * `InnerTree` is empty (`{}`), meaning that parameter produced nothing — often a\n * sign the definition didn't actually compute (wrong/missing inputs, a guarded\n * branch). The names tell you exactly which output was empty so you can trace it\n * back to the responsible branch.\n *\n * Only logs when `debug` is set: an empty output can be legitimate, so this is a\n * diagnostic, never a hard failure. Reads `ParamName` / `InnerTree`\n * case-insensitively to stay robust across server-branch casing.\n *\n * @internal Exported for testing.\n */\nexport function warnOnEmptyInnerTrees(response: GrasshopperComputeResponse, debug?: boolean): void {\n\tif (!debug) return;\n\n\tconst values = readField<unknown[]>(response, 'values');\n\tif (!Array.isArray(values) || values.length === 0) return;\n\n\tconst empty: string[] = [];\n\tfor (const param of values) {\n\t\tconst innerTree = readField<Record<string, unknown>>(param, 'innerTree');\n\t\t// Treat a missing or empty innerTree as \"produced nothing\".\n\t\tif (!innerTree || Object.keys(innerTree).length === 0) {\n\t\t\tempty.push(readField<string>(param, 'paramName') ?? '<unnamed>');\n\t\t}\n\t}\n\n\tif (empty.length === 0) return;\n\n\tconst scope = empty.length === values.length ? 'all' : `${empty.length}/${values.length}`;\n\tgetLogger().warn(\n\t\t`Solve returned empty output(s) (${scope}): ${empty.join(', ')}. ` +\n\t\t\t`These parameters produced no data — check the definition's inputs and the branch feeding each.`\n\t);\n}\n\n/**\n * Result of a solve that also reports the definition's server-side cache key.\n *\n * `cacheKey` is the `md5_…` identifier the server assigned to the (base64)\n * definition — stable for identical content. A caller that holds it can solve\n * the same definition again by reference (`pointer: cacheKey`) instead of\n * re-uploading the full base64, which matters a lot for large (multi-MB)\n * definitions on a live UI. For a URL-pointer solve the server echoes the\n * request schema back, so `cacheKey` is the definition URL itself (already a\n * reference — nothing gained by re-pointing at it). `null` only when the\n * server's response carried no `pointer` at all — do NOT use `null` to detect\n * URL-pointer solves.\n */\nexport interface SolveWithCacheKey {\n\tresponse: GrasshopperComputeResponse;\n\tcacheKey: string | null;\n}\n\n/**\n * Runs a Rhino Compute job using the provided tree prototypes and Grasshopper definition.\n *\n * @public Use this for direct compute control. For high-level API, use `GrasshopperClient.solve()`.\n *\n * @param dataTree - An array of `DataTree` objects representing the input data for the compute job.\n * @param definition - The Grasshopper definition, which can be:\n * - A URL string (e.g., 'https://example.com/definition.gh')\n * - A base64-encoded string of the .gh file\n * - A plain string (will be base64-encoded)\n * - A Uint8Array of the .gh file (will be base64-encoded)\n * - A `DefinitionRef` (bytes are loaded via `ref.load()` for the upload)\n * @param config - Compute configuration (server URL, API key, etc. along with optional timeout, units, etc.)\n * @returns An object containing the compute result and extracted file data.\n *\n * @example\n * // Using a URL\n * await solveGrasshopperDefinition(trees, 'https://example.com/definition.gh', config);\n *\n * // Using a base64 string\n * await solveGrasshopperDefinition(trees, 'UEsDBBQAAAAIAL...', config);\n *\n * // Using binary data\n * const fileData = new Uint8Array([...]);\n * await solveGrasshopperDefinition(trees, fileData, config);\n */\nexport async function solveGrasshopperDefinition(\n\tdataTree: DataTree[],\n\tdefinition: SolveDefinition,\n\tconfig: GrasshopperComputeConfig\n): Promise<GrasshopperComputeResponse> {\n\t// Not gated on `debug`: exposing an API key in the browser is a security\n\t// concern in every configuration. `suppressBrowserWarning` is the opt-out.\n\twarnIfClientSide(\n\t\t'solveGrasshopperDefinition',\n\t\tconfig.suppressBrowserWarning ?? config.suppressClientSideWarning\n\t);\n\n\tconst bytes = await materializeDefinition(definition);\n\tconst { response } = await runSolve(prepareGrasshopperArgs(bytes, dataTree), config);\n\treturn response;\n}\n\n/**\n * Solve while reporting the server's definition cache key.\n *\n * Behaves like {@link solveGrasshopperDefinition} but returns the `cacheKey` the\n * server assigned, so a caller (e.g. the scheduler) can later solve the same\n * definition by reference instead of re-uploading it. The cache key is only\n * meaningful for base64/binary definitions; a URL-pointer solve returns the URL.\n *\n * @internal\n */\nexport async function solveGrasshopperDefinitionWithCacheKey(\n\tdataTree: DataTree[],\n\tdefinition: SolveDefinition,\n\tconfig: GrasshopperComputeConfig\n): Promise<SolveWithCacheKey> {\n\twarnIfClientSide(\n\t\t'solveGrasshopperDefinitionWithCacheKey',\n\t\tconfig.suppressBrowserWarning ?? config.suppressClientSideWarning\n\t);\n\n\tconst bytes = await materializeDefinition(definition);\n\treturn runSolve(prepareGrasshopperArgs(bytes, dataTree), config);\n}\n\n/**\n * Solve a definition by its server-side cache key (`pointer: cacheKey`),\n * skipping the (potentially multi-MB) base64 upload. If the key has been evicted\n * from the server's definition cache — `DEFINITION_LOAD_FAILED` — transparently\n * retry once with the full `definition` and report the fresh cache key so the\n * caller can update its mapping. A `DefinitionRef` definition is only\n * materialized (`ref.load()`) inside that miss branch — a pointer hit never\n * touches the bytes.\n *\n * @returns The solve result plus the (possibly refreshed) cache key, and whether\n * the fast path missed (so callers can record the new key / track hit rate).\n * @internal\n */\nexport async function solveByCacheKey(\n\tdataTree: DataTree[],\n\tcacheKey: string,\n\tdefinition: SolveDefinition,\n\tconfig: GrasshopperComputeConfig\n): Promise<SolveWithCacheKey & { missed: boolean }> {\n\twarnIfClientSide(\n\t\t'solveByCacheKey',\n\t\tconfig.suppressBrowserWarning ?? config.suppressClientSideWarning\n\t);\n\n\tconst pointerArgs: GrasshopperRequestSchema = { algo: null, pointer: cacheKey, values: dataTree };\n\n\ttry {\n\t\tconst fast = await runSolve(pointerArgs, config);\n\t\treturn { ...fast, missed: false };\n\t} catch (error) {\n\t\tif (!isDefinitionLoadMiss(error)) throw error;\n\t\t// Cache miss — fall back to the full upload and capture the fresh key.\n\t\tconst bytes = await materializeDefinition(definition);\n\t\tconst full = await runSolve(prepareGrasshopperArgs(bytes, dataTree), config);\n\t\treturn { ...full, missed: true };\n\t}\n}\n\n/**\n * Resolve a definition to uploadable form: a `DefinitionRef` is materialized\n * via `load()` (failures are wrapped so callers get a `RhinoComputeError`\n * naming the ref, not an opaque loader exception); other forms pass through.\n */\nasync function materializeDefinition(definition: SolveDefinition): Promise<string | Uint8Array> {\n\tif (!isDefinitionRef(definition)) return definition;\n\ttry {\n\t\treturn await definition.load();\n\t} catch (error) {\n\t\tthrow new RhinoComputeError(\n\t\t\t`Failed to load definition bytes for ref '${definition.key}'`,\n\t\t\tErrorCodes.INVALID_INPUT,\n\t\t\t{\n\t\t\t\tcontext: { definitionKey: definition.key },\n\t\t\t\toriginalError: error instanceof Error ? error : new Error(String(error))\n\t\t\t}\n\t\t);\n\t}\n}\n\n/**\n * Shared solve body: apply optional settings, POST, and split the server's\n * `pointer` (its cache key) off the response. `algo` — the request's full\n * base64 definition echoed back on every solve — is stripped too: keeping it\n * pins a multi-MB copy per response, multiplied by every cache holding\n * responses (the scheduler's LRU alone up to `maxEntries` times). Stripping via\n * shallow copy rather than `delete` keeps any already-observed response object\n * unmutated.\n */\nasync function runSolve(\n\targs: GrasshopperRequestSchema,\n\tconfig: GrasshopperComputeConfig\n): Promise<SolveWithCacheKey> {\n\tapplyOptionalComputeSettings(args, config);\n\n\tconst result = await fetchRhinoCompute<GrasshopperComputeResponse>('grasshopper', args, config);\n\n\tconst {\n\t\tpointer,\n\t\talgo: _algo,\n\t\t...rest\n\t} = result as GrasshopperComputeResponse & { pointer?: unknown; algo?: unknown };\n\tconst response = rest as GrasshopperComputeResponse;\n\t// The wire-size hint follows object identity, so the stripped copy must\n\t// re-register it — minus the echoed `algo`, which is no longer retained (it\n\t// can dwarf the actual outputs for a large definition).\n\tconst wireSize = getResponseWireSize(result);\n\tif (wireSize !== undefined) {\n\t\tconst algoLength = typeof _algo === 'string' ? _algo.length : 0;\n\t\tsetResponseWireSize(response, Math.max(0, wireSize - algoLength));\n\t}\n\twarnOnEmptyInnerTrees(response, config.debug);\n\treturn {\n\t\tresponse,\n\t\tcacheKey: typeof pointer === 'string' ? pointer : null\n\t};\n}\n\n// ============================================================================\n// Grasshopper Arguments\n// ============================================================================\n\n/**\n * Prepares Grasshopper arguments from a definition and data tree.\n * Automatically detects the definition format and converts it appropriately.\n *\n * @param definition - Can be a URL, base64 string, plain string, or Uint8Array\n * @param dataTree - Array of DataTree objects for compute inputs\n * @internal\n */\nexport function prepareGrasshopperArgs(\n\tdefinition: string | Uint8Array,\n\tdataTree: DataTree[]\n): GrasshopperRequestSchema {\n\tconst args: GrasshopperRequestSchema = {\n\t\talgo: null,\n\t\tpointer: null,\n\t\tvalues: dataTree\n\t};\n\n\tif (definition instanceof Uint8Array) {\n\t\t// Binary data → convert to base64\n\t\targs.algo = base64ByteArray(definition);\n\t} else if (/^https?:\\/\\//i.test(definition)) {\n\t\t// URL → use as pointer reference\n\t\targs.pointer = definition;\n\t} else {\n\t\t// Base64 detection is a heuristic (see detectBase64Payload): only long\n\t\t// (≥64 data chars), canonical base64 is passed through — normalized, so\n\t\t// newline-wrapped/unpadded definitions reach the server decodable instead\n\t\t// of double-encoded. Everything else (incl. short base64-shaped strings\n\t\t// like \"test\") is treated as a plain string and encoded. Pass a\n\t\t// Uint8Array to bypass sniffing entirely.\n\t\targs.algo = detectBase64Payload(definition) ?? encodeStringToBase64(definition);\n\t}\n\n\treturn args;\n}\n\n/**\n * @internal\n */\nexport function applyOptionalComputeSettings(\n\targlist: GrasshopperRequestSchema,\n\toptions: GrasshopperComputeConfig\n): void {\n\tif (options.cachesolve != null) arglist.cachesolve = options.cachesolve;\n\tif (options.cacheerroredsolves != null) arglist.cacheerroredsolves = options.cacheerroredsolves;\n\tif (options.modelunits != null) arglist.modelunits = options.modelunits;\n\tif (options.angletolerance != null) arglist.angletolerance = options.angletolerance;\n\tif (options.absolutetolerance != null) arglist.absolutetolerance = options.absolutetolerance;\n\tif (options.dataversion != null) arglist.dataversion = options.dataversion;\n}\n"]}
@@ -0,0 +1,2 @@
1
+ import{b as l,c as h,d as c,e as y,h as Z,i as ee,k as te,l as re,m as O,n as M,o as ne,p as oe,s as p,t as j,v as F}from"./chunk-Y3M7P3BW.js";var se=new Set;function Ve(){if(typeof window>"u"||globalThis.process?.versions?.node!=null)return!1;let e=globalThis.navigator,r=typeof e?.userAgent=="string"?e.userAgent:"";return!/jsdom/i.test(r)}function D(t,e){e||Ve()&&!se.has(t)&&(se.add(t),y().warn(`Warning: ${t} is running on the client side. For better performance and security, consider running this on the server side.`))}function T(t){return typeof t=="object"&&!(t instanceof Uint8Array)&&typeof t.key=="string"&&typeof t.load=="function"}var Le="Unable to load grasshopper definition";function We(t){return t instanceof c?t.code===h.DEFINITION_NOT_CACHED||t.message.includes(Le):!1}function Be(t,e){if(!e)return;let r=p(t,"values");if(!Array.isArray(r)||r.length===0)return;let n=[];for(let s of r){let i=p(s,"innerTree");(!i||Object.keys(i).length===0)&&n.push(p(s,"paramName")??"<unnamed>")}if(n.length===0)return;let o=n.length===r.length?"all":`${n.length}/${r.length}`;y().warn(`Solve returned empty output(s) (${o}): ${n.join(", ")}. These parameters produced no data \u2014 check the definition's inputs and the branch feeding each.`)}async function E(t,e,r){D("solveGrasshopperDefinition",r.suppressBrowserWarning??r.suppressClientSideWarning);let n=await z(e),{response:o}=await N(v(n,t),r);return o}async function ie(t,e,r){D("solveGrasshopperDefinitionWithCacheKey",r.suppressBrowserWarning??r.suppressClientSideWarning);let n=await z(e);return N(v(n,t),r)}async function ae(t,e,r,n){D("solveByCacheKey",n.suppressBrowserWarning??n.suppressClientSideWarning);let o={algo:null,pointer:e,values:t};try{return{...await N(o,n),missed:!1}}catch(s){if(!We(s))throw s;let i=await z(r);return{...await N(v(i,t),n),missed:!0}}}async function z(t){if(!T(t))return t;try{return await t.load()}catch(e){throw new c(`Failed to load definition bytes for ref '${t.key}'`,h.INVALID_INPUT,{context:{definitionKey:t.key},originalError:e instanceof Error?e:new Error(String(e))})}}async function N(t,e){je(t,e);let r=await M("grasshopper",t,e),{pointer:n,algo:o,...s}=r,i=s,a=O(r);if(a!==void 0){let u=typeof o=="string"?o.length:0;re(i,Math.max(0,a-u))}return Be(i,e.debug),{response:i,cacheKey:typeof n=="string"?n:null}}function v(t,e){let r={algo:null,pointer:null,values:e};return t instanceof Uint8Array?r.algo=te(t):/^https?:\/\//i.test(t)?r.pointer=t:r.algo=ee(t)??Z(t),r}function je(t,e){e.cachesolve!=null&&(t.cachesolve=e.cachesolve),e.cacheerroredsolves!=null&&(t.cacheerroredsolves=e.cacheerroredsolves),e.modelunits!=null&&(t.modelunits=e.modelunits),e.angletolerance!=null&&(t.angletolerance=e.angletolerance),e.absolutetolerance!=null&&(t.absolutetolerance=e.absolutetolerance),e.dataversion!=null&&(t.dataversion=e.dataversion)}function $(t){let e=new WeakSet,r=n=>{if(n===void 0)return"undefined";if(n===null)return"null";if(typeof n=="number")return Number.isFinite(n)?String(n):"null";if(typeof n=="string"||typeof n=="boolean")return JSON.stringify(n);if(typeof n=="bigint")return`${n}n`;if(n instanceof Uint8Array)return`{"__u8":${n.length},"hash":"${le(n)}"}`;if(Array.isArray(n)){if(e.has(n))return'"[Circular]"';e.add(n);let o=[];for(let s=0;s<n.length;s++)o.push(r(n[s]));return e.delete(n),`[${o.join(",")}]`}if(typeof n=="object"){if(e.has(n))return'"[Circular]"';e.add(n);let o;return typeof n.toJSON=="function"?o=r(n.toJSON()):n instanceof Map?o=`{"__map":[${[...n.entries()].map(([i,a])=>`[${r(i)},${r(a)}]`).sort().join(",")}]}`:n instanceof Set?o=`{"__set":[${[...n.values()].map(r).sort().join(",")}]}`:o=`{${Object.keys(n).sort().map(a=>`${JSON.stringify(a)}:${r(n[a])}`).join(",")}}`,e.delete(n),o}return"null"};return r(t)}function ue(t,e){let r=2166136261;for(let n=0;n<t;n++)r^=e(n),r=r+((r<<1)+(r<<4)+(r<<7)+(r<<8)+(r<<24))>>>0;return r.toString(16).padStart(8,"0")}function pe(t){return ue(t.length,e=>t.charCodeAt(e))}function le(t){return ue(t.length,e=>t[e])}function ce(t,e){return q(R(t),e)}function q(t,e){let r=$(e);return`${t}|t:${r.length}:${pe(r)}`}function R(t){return T(t)?`r:${t.key}`:typeof t=="string"?`s:${t.length}:${pe(t)}`:`u8:${t.length}:${le(t)}`}var ze=100;function $e(t){return typeof t!="string"?!0:!/^https?:\/\//i.test(t)}function qe(t){try{return JSON.stringify(t)?.length??0}catch{return 0}}var x=class{constructor(e,r,n={},o){l(this,"executor");l(this,"baseConfig");l(this,"mode");l(this,"maxConcurrent");l(this,"maxQueueDepth");l(this,"queueWaitMs");l(this,"timeoutMs");l(this,"retry");l(this,"cacheEnabled");l(this,"cacheMax");l(this,"cacheMaxBytes");l(this,"cacheTtl");l(this,"cacheErroredSolves");l(this,"cache",new Map);l(this,"cacheBytes",0);l(this,"cacheKeyExecutor");l(this,"reuseServerDefinitionCache");l(this,"serverCacheKeys",new Map);l(this,"onStart");l(this,"onSettle");l(this,"onSuperseded");l(this,"subscribers",new Set);l(this,"inFlight",new Set);l(this,"pendingForLatestWins",null);l(this,"fifoQueue",[]);l(this,"_lastResult",null);l(this,"_lastError",null);l(this,"_lastDurationMs",null);l(this,"solveSeq",0);l(this,"lastStateSeq",0);l(this,"disposed",!1);this.executor=e,this.cacheKeyExecutor=o,this.baseConfig=r,this.mode=n.mode??"latest-wins",this.maxConcurrent=Math.max(1,n.maxConcurrent??(this.mode==="parallel"?4:1)),this.maxQueueDepth=n.maxQueueDepth!==void 0&&n.maxQueueDepth>0?Math.floor(n.maxQueueDepth):void 0,this.queueWaitMs=n.queueWaitMs!==void 0&&n.queueWaitMs>0?n.queueWaitMs:void 0,this.timeoutMs=n.timeoutMs,this.retry=n.retry;let s=n.cache;this.cacheEnabled=s!==void 0&&s!==!1;let i=typeof s=="object"?s:{};this.cacheMax=i.maxEntries??50,this.cacheMaxBytes=Math.max(0,i.maxBytes??0),this.cacheTtl=i.ttlMs??0,this.cacheErroredSolves=i.cacheErroredSolves??!0,this.reuseServerDefinitionCache=!!o&&(n.reuseServerDefinitionCache??!0),this.onStart=n.onStart,this.onSettle=n.onSettle,this.onSuperseded=n.onSuperseded}get isSolving(){return this.inFlight.size>0}get hasPending(){return this.pendingForLatestWins!==null||this.fifoQueue.length>0}get inFlightCount(){return this.inFlight.size}get queueDepth(){return this.fifoQueue.length+(this.pendingForLatestWins?1:0)}get lastResult(){return this._lastResult}get lastError(){return this._lastError}get lastDurationMs(){return this._lastDurationMs}subscribe(e){return this.subscribers.add(e),()=>this.subscribers.delete(e)}notify(){for(let e of this.subscribers)try{e()}catch(r){y().error("[SolveScheduler] subscriber threw:",r)}}solve(e,r,n){if(this.disposed)return Promise.reject(new c("SolveScheduler has been disposed and cannot be used",h.INVALID_STATE));let o=R(e),s=q(o,r),i=++this.solveSeq,a={key:s,enqueuedAt:Date.now(),startedAt:null};if(n?.signal?.aborted)return Promise.reject(this.makeAbortError(a));if(this.cacheEnabled){let u=this.readCache(s);if(u){this.mode==="latest-wins"&&this.supersedeCurrent();let m={status:"success",response:u,durationMs:0,fromCache:!0};return this.writeLastState(i,{result:u,durationMs:0}),this.runHook(this.onStart,a),this.runHook(this.onSettle,a,m),this.notify(),Promise.resolve(u)}}return new Promise((u,m)=>{let f={definition:e,dataTree:r,definitionHash:o,ctx:a,seq:i,resolve:u,reject:m,externalSignal:n?.signal};f.externalSignal&&(f.queuedAbortHandler=()=>this.abortQueuedItem(f),f.externalSignal.addEventListener("abort",f.queuedAbortHandler,{once:!0})),this.enqueue(f)})}writeLastState(e,r){return e<this.lastStateSeq?!1:(this.lastStateSeq=e,"result"in r?(this._lastResult=r.result,this._lastError=null):this._lastError=r.error,this._lastDurationMs=r.durationMs,!0)}supersedeCurrent(){this.pendingForLatestWins&&(this.supersede(this.pendingForLatestWins),this.pendingForLatestWins=null);for(let e of this.inFlight)this.supersede(e),e.controller.abort()}abortQueuedItem(e){this.pendingForLatestWins===e&&(this.pendingForLatestWins=null);let r=this.fifoQueue.indexOf(e);r>=0&&this.fifoQueue.splice(r,1),this.rejectAsAborted(e),this.notify()}shedAsQueueFull(e){let r=new c("Solve queue is full; request shed (backpressure)",h.QUEUE_FULL,{statusCode:503,context:{key:e.ctx.key,queueDepth:this.fifoQueue.length,maxQueueDepth:this.maxQueueDepth}});this.settleError(e,r)&&this.runHook(this.onSettle,e.ctx,{status:"error",error:r,durationMs:0}),this.notify()}armQueueWaitTimer(e){if(this.queueWaitMs===void 0)return;let r=this.queueWaitMs;e.queueWaitTimer=setTimeout(()=>{if(e.settled)return;let n=this.fifoQueue.indexOf(e);n>=0&&this.fifoQueue.splice(n,1);let o=new c(`Solve waited longer than ${r}ms in queue; shed (backpressure)`,h.QUEUE_TIMEOUT,{statusCode:503,context:{key:e.ctx.key,waitedMs:Date.now()-e.ctx.enqueuedAt,queueWaitMs:r}});this.settleError(e,o)&&this.runHook(this.onSettle,e.ctx,{status:"error",error:o,durationMs:0}),this.notify()},r)}clearQueueWaitTimer(e){e.queueWaitTimer!==void 0&&(clearTimeout(e.queueWaitTimer),e.queueWaitTimer=void 0)}enqueue(e){switch(this.mode){case"latest-wins":{this.supersedeCurrent(),this.inFlight.size===0?this.execute(e):this.pendingForLatestWins=e;break}case"queue":case"parallel":{this.inFlight.size<this.maxConcurrent?this.execute(e):this.maxQueueDepth!==void 0&&this.fifoQueue.length>=this.maxQueueDepth?this.shedAsQueueFull(e):(this.armQueueWaitTimer(e),this.fifoQueue.push(e));break}}this.notify()}async execute(e){let r=new AbortController,n=e;n.controller=r,this.inFlight.add(n),e.ctx.startedAt=Date.now(),this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e);let o=()=>r.abort();e.externalSignal?.addEventListener("abort",o,{once:!0}),this.runHook(this.onStart,e.ctx),this.notify();let s=performance.now();try{let i={...this.baseConfig,signal:r.signal,...this.timeoutMs!==void 0&&{timeoutMs:this.timeoutMs},...this.retry!==void 0&&{retry:this.retry}},{response:a,definitionReuploaded:u}=await this.runExecutor(e.definition,e.dataTree,e.definitionHash,i),m=performance.now()-s;if(this.cacheEnabled&&this.writeCache(e.ctx.key,a),!this.settleSuccess(e,a))return;this.writeLastState(e.seq,{result:a,durationMs:m}),this.runHook(this.onSettle,e.ctx,{status:"success",response:a,durationMs:m,fromCache:!1,definitionReuploaded:u})}catch(i){let a=performance.now()-s,u=this.normalizeExecutionError(i,n);this.writeLastState(e.seq,{error:u,durationMs:a}),this.settleError(e,u)&&this.runHook(this.onSettle,e.ctx,{status:"error",error:u,durationMs:a})}finally{e.externalSignal?.removeEventListener("abort",o),this.inFlight.delete(n),this.drainNext(),this.notify()}}async runExecutor(e,r,n,o){if(!this.cacheKeyExecutor||!this.reuseServerDefinitionCache||!$e(e))return{response:await this.executor(e,r,o)};let s=n,i=this.serverCacheKeys.get(s)??null,a=await this.cacheKeyExecutor(e,r,i,o);if(a.cacheKey)for(this.serverCacheKeys.delete(s),this.serverCacheKeys.set(s,a.cacheKey);this.serverCacheKeys.size>ze;){let u=this.serverCacheKeys.keys().next().value;if(u===void 0)break;this.serverCacheKeys.delete(u)}else this.serverCacheKeys.delete(s);return{response:a.response,definitionReuploaded:a.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 c("Superseded by newer solve",h.SUPERSEDED,{context:{key:e.ctx.key,enqueuedAt:e.ctx.enqueuedAt}});this.settleError(e,r)&&this.runHook(this.onSuperseded,e.ctx)}makeAbortError(e){return new c("Request aborted by caller",h.ABORTED,{context:{key:e.key,enqueuedAt:e.enqueuedAt}})}settleError(e,r){return e.settled?!1:(e.settled={error:r},this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e),e.reject(r),!0)}settleSuccess(e,r){return e.settled?!1:(e.settled={ok:!0},this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e),e.resolve(r),!0)}removeQueuedAbortHandler(e){e.queuedAbortHandler&&e.externalSignal&&e.externalSignal.removeEventListener("abort",e.queuedAbortHandler),e.queuedAbortHandler=void 0}isAbortLikeError(e){if(e instanceof Error){if(e.name==="AbortError")return!0;if(typeof DOMException<"u"&&e instanceof DOMException)return e.name==="AbortError"}return!1}normalizeExecutionError(e,r){return r.settled&&"error"in r.settled?r.settled.error:e instanceof c?e:this.isAbortLikeError(e)?this.makeAbortError(r.ctx):new c(e instanceof Error?e.message:String(e),h.UNKNOWN_ERROR,{originalError:e instanceof Error?e:new Error(String(e))})}cancelAll(){for(this.pendingForLatestWins&&(this.rejectAsAborted(this.pendingForLatestWins),this.pendingForLatestWins=null);this.fifoQueue.length>0;){let e=this.fifoQueue.shift();this.rejectAsAborted(e)}for(let e of this.inFlight){let r=this.makeAbortError(e.ctx);this.settleError(e,r)&&this.runHook(this.onSettle,e.ctx,{status:"error",error:r,durationMs:e.ctx.startedAt?Date.now()-e.ctx.startedAt:0}),e.controller.abort()}this.notify()}rejectAsAborted(e){let r=this.makeAbortError(e.ctx);this.settleError(e,r)&&this.runHook(this.onSettle,e.ctx,{status:"error",error:r,durationMs:0})}readCache(e){if(!this.cacheEnabled)return null;let r=this.cache.get(e);return r?this.cacheTtl>0&&Date.now()-r.insertedAt>this.cacheTtl?(this.dropCacheEntry(e),null):(this.cache.delete(e),this.cache.set(e,r),r.response):null}writeCache(e,r){if(!this.cacheEnabled||!this.cacheErroredSolves&&r.errors&&r.errors.length>0)return;let n=O(r)??qe(r);if(!(this.cacheMaxBytes>0&&n>this.cacheMaxBytes))for(this.dropCacheEntry(e),this.cache.set(e,{response:r,insertedAt:Date.now(),sizeBytes:n}),this.cacheBytes+=n;(this.cache.size>this.cacheMax||this.cacheMaxBytes>0&&this.cacheBytes>this.cacheMaxBytes)&&this.cache.size>0;){let o=this.cache.keys().next().value;if(o===void 0)break;this.dropCacheEntry(o)}}dropCacheEntry(e){let r=this.cache.get(e);r&&(this.cache.delete(e),this.cacheBytes-=r.sizeBytes)}clearCache(){this.cache.clear(),this.cacheBytes=0}cacheStats(){return{entries:this.cache.size,bytes:this.cacheBytes}}dispose(){this.disposed||(this.disposed=!0,this.cancelAll(),this.subscribers.clear(),this.clearCache())}runHook(e,...r){if(e)try{e(...r)}catch(n){y().error("[SolveScheduler] hook threw:",n)}}};function fe(t){return T(t)?`ref:${t.key}`:typeof t=="string"&&t.length<200?t:"...content..."}function me(t){return Array.isArray(t)?t.map(e=>{let r=0,n=0,o=p(e,"innerTree");if(o&&typeof o=="object"){for(let s of Object.values(o))if(Array.isArray(s)){r+=s.length;for(let i of s){let a=i?.data;typeof a=="string"&&(n+=a.length)}}}return{param:p(e,"paramName")??"<unnamed>",items:r,bytes:n}}):[]}var A=class t{constructor(e){l(this,"config");l(this,"serverStats");l(this,"disposed",!1);this.config=this.normalizeComputeConfig(e),this.serverStats=new oe(this.config.serverUrl,this.config.apiKey)}static async create(e){let r=new t(e),n=Math.max(1,(e.retry?.attempts??2)+1),o=e.retry?.baseDelayMs??250,s=e.retry?.maxDelayMs??1e3;for(let i=0;i<n;i++){if(await r.serverStats.isServerOnline())return r;if(i<n-1){let a=Math.min(o*2**i,s);await new Promise(u=>setTimeout(u,a))}}throw await r.dispose(),new c("Rhino Compute server is not online",h.NETWORK_ERROR,{context:{serverUrl:r.config.serverUrl,attempts:n}})}getConfig(){return this.ensureNotDisposed(),{...this.config}}async getIO(e){return this.ensureNotDisposed(),G(e,this.config)}async getRawIO(e){return this.ensureNotDisposed(),P(e,this.config)}async solve(e,r,n){this.ensureNotDisposed();try{if(typeof e=="string"&&!e?.trim())throw new c("Definition URL/content is required",h.INVALID_INPUT,{context:{receivedUrl:e}});if(e instanceof Uint8Array&&e.length===0)throw new c("Definition content is empty",h.INVALID_INPUT);if(T(e)&&!e.key.trim())throw new c("DefinitionRef key is empty",h.INVALID_INPUT);let o={...this.config,...n?.signal!==void 0&&{signal:n.signal},...n?.timeoutMs!==void 0&&{timeoutMs:n.timeoutMs},...n?.retry!==void 0&&{retry:n.retry}},s=await E(r,e,o);if(s?.errors&&s.errors.length>0)throw new c(s.errors.join("; ")||"Computation failed",h.COMPUTATION_ERROR,{context:{definition:fe(e),inputSummary:me(r),errors:s.errors,warnings:s.warnings,values:s.values}});return s}catch(o){throw this.config.debug&&y().error("Compute failed:",o),o instanceof c?o:new c(o instanceof Error?o.message:String(o),h.COMPUTATION_ERROR,{context:{definition:fe(e),inputSummary:me(r)},originalError:o instanceof Error?o:new Error(String(o))})}}createScheduler(e){this.ensureNotDisposed();let r=(o,s,i)=>E(s,o,i),n=(o,s,i,a)=>i===null?ie(s,o,a).then(u=>({...u,missed:!1})):ae(s,i,o,a);return new x(r,this.config,e,n)}async dispose(){this.disposed||(this.disposed=!0,await this.serverStats.dispose())}ensureNotDisposed(){if(this.disposed)throw new c("GrasshopperClient has been disposed and cannot be used",h.INVALID_STATE)}normalizeComputeConfig(e){return{...e,serverUrl:ne(e.serverUrl),apiKey:e.apiKey,authToken:e.authToken,debug:e.debug??!1,suppressBrowserWarning:e.suppressBrowserWarning??e.suppressClientSideWarning}}};var V=new Map;function he(t,e){V.set(t,e)}he("Rhino.Geometry.Point3d",(t,e)=>{let r=e;return!r||typeof r.X!="number"?null:new t.Point([r.X,r.Y,r.Z])});he("Rhino.Geometry.Line",(t,e)=>{let r=e;return!r||!r.From||!r.To?null:new t.Line([r.From.X,r.From.Y,r.From.Z],[r.To.X,r.To.Y,r.To.Z])});function Ue(t){if(V.has(t))return V.get(t);for(let[e,r]of V)if(t.startsWith(e))return r}function _e(t){return!!(t&&typeof t=="object"&&typeof t.data=="string")}function de(t,e){return{__decodeError:!0,type:t,raw:e}}function ye(t,e,r){let n=Ue(e),o=!1;if(n)try{let s=n(r,t);if(s!=null)return s}catch(s){y().warn(`Failed to decode Rhino type ${e}:`,s),o=!0}try{if(_e(t))return r.CommonObject.decode(t)}catch(s){return y().warn(`Failed to decode ${e} with CommonObject:`,s),de(e,t)}return o?de(e,t):t}function ge(t){let e=new WeakSet,r=n=>{if(!n||typeof n!="object"||e.has(n))return;e.add(n);let o=n.delete;if(typeof o=="function"){let i=n.isDeleted;(typeof i!="function"||!i.call(n))&&o.call(n);return}if(Array.isArray(n)){for(let i of n)r(i);return}let s=Object.getPrototypeOf(n);if(s===Object.prototype||s===null)for(let i of Object.values(n))r(i)};r(t)}var I={STRING:"System.String",INT:"System.Int32",DOUBLE:"System.Double",BOOL:"System.Boolean"},Ke="Rhino.Geometry.",Qe=["WebDisplay"],He="FileData";function be(t){return Qe.some(e=>t.includes(e))}function Je(t){if(typeof t!="string")return t;let e=t.trim();if(!(e.startsWith("{")||e.startsWith("[")||e.startsWith('"')))return t;try{let n=JSON.parse(e);if(typeof n=="string")try{return JSON.parse(n)}catch{return n}return n}catch{return t}}function Ye(t,e,r){switch(e){case I.STRING:return typeof t!="string"?t:t.replace(/^"(.*)"$/,"$1");case I.INT:return Number.parseInt(t,10);case I.DOUBLE:return Number.parseFloat(t);case I.BOOL:return String(t).toLowerCase()==="true";default:return r&&e.startsWith(Ke)?ye(t,e,r):t}}var U=new WeakMap;function Te(t){if(U.has(t))return U.get(t);let e=Je(t.data);return U.set(t,e),e}function Se(t,e,r,n){if(typeof t.data!="string")return t.data;let o=r?Te(t):t.data;return Ye(o,e,n)}function Xe(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.fileName=="string"&&typeof e.fileType=="string"&&"data"in e&&typeof e.isBase64Encoded=="boolean"&&typeof e.subFolder=="string"}function _(t){let e=p(t,"values");return Array.isArray(e)?e:[]}function K(t){return typeof t.type=="string"?t.type:""}function Q(t,e){if(!(!t||typeof t!="object")){for(let r of Object.values(t))if(Array.isArray(r))for(let n of r)n&&typeof n=="object"&&e(n)}}function De(t,e=!1,r={}){let{parseValues:n=!0,rhino:o,stringOnly:s=!1}=r,i={},a=new Set;for(let u of _(t)){let m=p(u,"paramName");Q(p(u,"innerTree"),f=>{let d=K(f);if(be(d)||s&&d!==I.STRING)return;let g=e?f.id:m;if(!g)return;let b=Se(f,d,n,o);g in i?a.has(g)?i[g].push(b):(i[g]=[i[g],b],a.add(g)):i[g]=b})}return{values:i,dispose:()=>ge(i)}}function xe(t){let e=[];for(let r of _(t))Q(p(r,"innerTree"),n=>{if(!K(n).includes(He))return;let o=Te(n);Xe(o)&&e.push(o)});return e}function Ie(t,e,r={}){let{parseValues:n=!0,rhino:o,stringOnly:s=!1}=r;for(let i of _(t)){let a=p(i,"innerTree"),u=!1;if("byName"in e){if(p(i,"paramName")!==e.byName)continue;u=!0}let m=[];if(Q(a,f=>{if("byId"in e){if(f.id!==e.byId)return;u=!0}let d=K(f);be(d)||s&&d!==I.STRING||m.push(Se(f,d,n,o))}),u)return m.length===0?void 0:m.length===1?m[0]:m}}var k=class{constructor(e,r=!1){l(this,"response",e);l(this,"debug",r)}getValues(e=!1,r={}){return De(this.response,e,r)}getValue(e,r){return Ie(this.response,e,r)}async extractMeshesFromResponse(e){let r={debug:this.debug,...e},n;try{({getThreeMeshesFromComputeResponse:n}=await import("./visualization-BIHTM2KJ.js"))}catch(o){throw new c("Failed to load three.js visualization module. Ensure three.js is installed as a peer dependency.",h.INVALID_STATE,{context:{originalError:o instanceof Error?o.message:String(o)}})}return n(this.response,r)}getFileData(){return xe(this.response)}async getAndDownloadFiles(e,r){let n=this.getFileData();await F(n,e,r)}};var H=/^\{(-?\d+(?:;-?\d+)*)?\}$/;function C(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=Object.entries(t);return e.length>0&&e.every(([r,n])=>H.test(r)&&Array.isArray(n))}function w(t,e,r){if(t==null)return t;if(Array.isArray(t)){let o=t.map(e).filter(s=>s!==null);return o.length>0?o:void 0}let n=e(t);return n!==null?n:r?void 0:t}var L=t=>{if(typeof t=="number")return Number.isFinite(t)?t:null;if(typeof t=="string"){let e=t.trim();if(e===""||/^[+-]?0[xbo]/i.test(e))return null;let r=Number(e);return Number.isFinite(r)?r:null}return null},J=t=>{if(typeof t=="boolean")return t;if(typeof t=="string"){let e=t.trim().toLowerCase();if(e==="true")return!0;if(e==="false")return!1}return null},Ze=t=>typeof t=="string"?t.length>=2&&t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t.startsWith('"')?t.slice(1):t:null,et=t=>{if(typeof t=="string"){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')&&(e=e.slice(1,-1).trim()),e}return null};function we(t){return e=>{if(typeof e=="object"&&e!==null)return e;if(typeof e=="string"&&e.trim()!=="")try{let r=JSON.parse(e);return typeof r=="object"&&r!==null?r:(y().warn(`Parsed value for input ${t} is not an object`),null)}catch(r){return y().warn(`Failed to parse object value "${e}" for input ${t}`,r),null}return null}}function Ce(t,e,r){let n=Number(t.toFixed(e));return Math.abs(t-n)<r?n:t}function tt(t,e){if(!Number.isFinite(t)||t===0)return .1;let r=Math.abs(t);if(r>=1){let g=String(t).split(".")[1];if(g&&g.length>0){let b=Math.min(g.length,12),S=Math.pow(10,-b),X=Number(S.toFixed(b));return Math.abs(X-S)<e?X:S}return 1}let n=String(t),o=n.toLowerCase().match(/e(-?\d+)/);if(o){let d=Number(o[1]);if(d<0||n.toLowerCase().includes("e-")){let g=Math.abs(d),b=Math.pow(10,-g),S=Number(b.toFixed(g));return Math.abs(S-b)<e?S:b}return .1}let s=12,a=r.toFixed(s).replace(/0+$/,""),u=Math.min((a.split(".")[1]||"").length,s);if(u===0)return .1;let m=Math.pow(10,-u),f=Number(m.toFixed(u));return Math.abs(f-m)<e?f:m}function Ee(t){return typeof t.stepSize=="number"&&Number.isFinite(t.stepSize)&&t.stepSize>0?t.stepSize:void 0}function rt(t,e=1e-8){let r=t.paramType==="Integer",n=Ee(t);if(C(t.default))return{default:t.default,stepSize:n??(r?1:.1)};if(typeof t.default=="string"&&t.default.trim()!==""&&L(t.default)===null)throw new c(`Invalid numeric default "${t.default}" for input "${t.name||"unknown"}"`,h.VALIDATION_ERROR,{context:{inputName:t.name,default:t.default}});let o=w(t.default,L,!0);if(r)return Array.isArray(o)?o=o.map(d=>typeof d=="number"?Math.round(d):d):typeof o=="number"&&(o=Math.round(o)),{default:o,stepSize:n??1};let s=Array.isArray(o)?o[0]:o,i;typeof s=="number"&&Number.isFinite(s)&&s!==0?i=s:typeof t.minimum=="number"&&Number.isFinite(t.minimum)&&t.minimum!==0?i=t.minimum:typeof t.maximum=="number"&&Number.isFinite(t.maximum)&&t.maximum!==0&&(i=t.maximum);let a=n??(i!==void 0?tt(i,e):.1),u=0,m=String(a),f=m.toLowerCase().match(/e(-?\d+)/);if(f?u=Math.abs(Number(f[1])):u=m.split(".")[1]?.length??0,u===0&&typeof s=="number"&&s!==0&&Math.abs(s)<1){let d=Math.ceil(-Math.log10(Math.abs(s)));Number.isFinite(d)&&d>0&&(u=d)}return u=Math.min(Math.max(u,0),12),Array.isArray(o)?o=o.map(d=>typeof d=="number"?Ce(d,u,e):d):typeof o=="number"&&(o=Ce(o,u,e)),{default:o,stepSize:a}}var nt={types:["Number","Integer"],parse(t,e){let{default:r,stepSize:n}=rt(t);return{...e,paramType:t.paramType,minimum:t.minimum,maximum:t.maximum,atLeast:t.atLeast,atMost:t.atMost,stepSize:n,default:r}},fallback(t,e){let r=(t.atMost??1)>1,n=typeof t.minimum=="number"&&Number.isFinite(t.minimum)&&t.minimum>0?t.minimum:0;return{...e,paramType:t.paramType,minimum:t.minimum,maximum:t.maximum,atLeast:t.atLeast,atMost:t.atMost,stepSize:Ee(t)??(t.paramType==="Integer"?1:.1),default:r?[n]:n}}},ot={types:["Boolean"],parse(t,e){if(C(t.default))return{...e,paramType:"Boolean",default:t.default};let r=w(t.default,J,!1);if(r!=null&&typeof r!="boolean"&&!Array.isArray(r))throw new c(`Invalid boolean default "${String(r)}" for input "${t.name||"unknown"}"`,h.VALIDATION_ERROR,{context:{inputName:t.name,default:t.default}});return{...e,paramType:"Boolean",default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"Boolean",default:r?[!1]:!1}}},st={types:["Text"],parse(t,e){let r=w(t.default,Ze,!1);return{...e,paramType:"Text",default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"Text",default:r?[""]:""}}},it={types:["ValueList"],parse(t,e){if(!t.values||typeof t.values!="object"||Object.keys(t.values).length===0)throw c.missingValues(t.nickname||"unnamed","ValueList");let r=t.default;if(t.default!==void 0&&t.default!==null){if(typeof t.default=="object")throw new c(`ValueList input "${t.nickname||"unnamed"}" default is not a string-able value`,h.VALIDATION_ERROR,{context:{inputName:t.name,default:t.default}});let n=String(t.default).toLowerCase(),o=Object.keys(t.values).find(s=>s.toLowerCase()===n);o!==void 0?r=o:y().warn(`ValueList input "${t.nickname||"unnamed"}" default value "${t.default}" is not in available values`)}return{...e,paramType:"ValueList",values:t.values,default:r}},fallback(t,e){return{...e,paramType:"ValueList",values:t.values&&typeof t.values=="object"?t.values:{},default:void 0}}},ve={types:["Geometry"],parse(t,e){let r=w(t.default,we(t.nickname||"unnamed"),!0);return{...e,paramType:"Geometry",default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"Geometry",default:r?[null]:null}}},at={types:["File"],parse(t,e){let r=w(t.default,we(t.nickname||"unnamed"),!0);return{...e,paramType:"File",acceptedFormats:t.acceptedFormats,default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"File",default:r?[null]:null}}},ut={types:["Color"],parse(t,e){let r=w(t.default,et,!1);return{...e,paramType:"Color",default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"Color",default:r?["0, 0, 0"]:"0, 0, 0"}}},pt=[nt,ot,st,it,ve,at,ut],Y=new Map(pt.flatMap(t=>t.types.map(e=>[e,t]))),Re=ve;function Ae(t){return p(t,"data")}function lt(t){return p(t,"type")}var ct=new Set(["System.Double","System.Single","System.Decimal","System.Int32","System.Int64"]),ft=new Set(["System.Int32","System.Int64"]);function Pe(t){if(typeof t.default!="object"||t.default===null)return{schema:t};if(Array.isArray(t.default))return{schema:t};if(!j(t.default,"innerTree")){let n=`Input "${t.name??"unknown"}" default had an unrecognized shape (no innerTree key); the default was dropped.`;return y().warn("Unexpected structure in input.default:",t.default),{schema:{...t,default:null},warning:{code:"MALFORMED_DEFAULT",message:n}}}let e=p(t.default,"innerTree")??{};if(Object.keys(e).length===0)return{schema:{...t,default:void 0}};if(t.treeAccess||t.atMost&&t.atMost>1){let n={},o=[];for(let[i,a]of Object.entries(e)){if(!Array.isArray(a)){let m=`Input "${t.name??"unknown"}" default had a non-array innerTree branch ("${i}"); the default was dropped.`;return y().warn("Unexpected structure in input.default innerTree:",t.default),{schema:{...t,default:null},warning:{code:"MALFORMED_DEFAULT",message:m}}}let u=[];for(let m of a){let f=Ae(m),d=lt(m);if(d&&ct.has(d)){if(typeof f=="string"&&f.trim()==="")continue;let g=L(f);if(g===null){o.push(`"${String(f)}" (${d})`);continue}u.push(ft.has(d)?Math.round(g):g);continue}if(d==="System.Boolean"){let g=J(f);if(g===null){o.push(`"${String(f)}" (${d})`);continue}u.push(g);continue}if(typeof f=="string"&&d?.startsWith("Rhino.Geometry")){try{u.push(JSON.parse(f))}catch{u.push(f)}continue}u.push(f)}n[i]=u}let s;if(o.length>0){let i=`Input "${t.name??"unknown"}" default contained ${o.length} tree value(s) that could not be parsed and were dropped: ${o.join(", ")}.`;y().warn(i),s={code:"MALFORMED_DEFAULT",message:i}}return{schema:{...t,default:n},...s&&{warning:s}}}let r=[];for(let n of Object.values(e))Array.isArray(n)&&n.forEach(o=>{o&&typeof o=="object"&&j(o,"data")&&r.push(Ae(o))});return r.length===0?{schema:{...t,default:void 0}}:r.length===1?{schema:{...t,default:r[0]}}:{schema:{...t,default:r}}}var mt=new Map([...Y.keys()].map(t=>[t.toLowerCase(),t]));function dt(t){return mt.get(t?.toLowerCase())??t}function ke(t){return Oe(t).input}function Oe(t){let e={description:t.description,name:t.name,nickname:t.nickname,treeAccess:t.treeAccess,groupName:t.groupName??void 0,id:t.id},r=dt(t.paramType),n={...t,paramType:r},o;try{let{schema:i,warning:a}=Pe(n);n=i,o=a&&{inputName:t.name||"unknown",paramType:t.paramType,message:a.message,code:a.code}}catch(i){n={...n,default:null},o={inputName:t.name||"unknown",paramType:t.paramType,message:`Input "${t.name??"unknown"}" default could not be normalized and was dropped: ${i instanceof Error?i.message:String(i)}`,code:"MALFORMED_DEFAULT"}}let s=Y.get(r);try{if(!s)throw c.unknownParamType(r,t.name);return{input:s.parse(n,e),error:o,...o&&{errors:[o]}}}catch(i){if(i instanceof c){y().error(`Validation error for input ${t.name||"unknown"}:`,i.message);let a={inputName:t.name||"unknown",paramType:t.paramType,message:i.message,code:i.code};return{input:(s??Re).fallback(n,e),error:a,errors:o?[o,a]:[a]}}throw new c(i instanceof Error?i.message:String(i),"VALIDATION_ERROR",{context:{paramName:t.name,paramType:r},originalError:i instanceof Error?i:new Error(String(i))})}}function Me(t){return W(t).inputs}function W(t){let e=[],r=[];for(let n of t){let{input:o,errors:s}=Oe(n);e.push(o),s&&r.push(...s)}return{inputs:e,parseErrors:r}}function Fe(t){let e=p(t,"stepSize");return{id:p(t,"id")??"",name:p(t,"name")??"",nickname:p(t,"nickname")??null,description:p(t,"description")??"",paramType:p(t,"paramType")??"",treeAccess:p(t,"treeAccess")??!1,minimum:p(t,"minimum")??null,maximum:p(t,"maximum")??null,atLeast:p(t,"atLeast")??1,atMost:p(t,"atMost")??1,stepSize:typeof e=="number"&&Number.isFinite(e)?e:void 0,default:p(t,"default"),values:p(t,"values"),acceptedFormats:p(t,"acceptedFormats"),groupName:p(t,"groupName")??null}}function Ne(t){return{name:p(t,"name")??"",nickname:p(t,"nickname")??null,paramType:p(t,"paramType")??"",id:p(t,"id")??""}}async function P(t,e){let r=v(t,[]),n={};if(r.algo&&(n.algo=r.algo),r.pointer&&(n.pointer=r.pointer),!n.algo&&!n.pointer)throw new c("Definition must resolve to either a URL pointer or base64 algo",h.INVALID_INPUT,{context:{definition:t}});let o=await M("io",n,e);if(!o||typeof o!="object")throw new c("Invalid IO response structure",h.INVALID_INPUT,{context:{response:o,definition:t}});let s=Ge(p(o,"warnings")),i=Ge(p(o,"errors")),a=p(o,"inputs"),u=p(o,"outputs");return{inputs:Array.isArray(a)?a.map(Fe):[],outputs:Array.isArray(u)?u.map(Ne):[],...s&&{loadWarnings:s},...i&&{loadErrors:i}}}function Ge(t){if(!Array.isArray(t))return;let e=t.map(ht).filter(r=>r!==void 0);return e.length>0?e:void 0}function ht(t){if(t==null)return;let e;if(typeof t=="string")e=t;else if(typeof t=="object"){let r=p(t,"message");if(typeof r=="string"&&r.trim().length>0)e=r;else try{e=JSON.stringify(t)??String(t)}catch{e=String(t)}}else e=String(t);return e.trim().length>0?e:void 0}async function G(t,e){D("fetchParsedDefinitionIO",e.suppressBrowserWarning??e.suppressClientSideWarning);let{inputs:r,outputs:n,loadWarnings:o,loadErrors:s}=await P(t,e),{inputs:i,parseErrors:a}=W(r);return{inputs:i,outputs:n,...a.length>0&&{parseErrors:a},...o&&{loadWarnings:o},...s&&{loadErrors:s}}}var B=class t{constructor(e){l(this,"innerTree");l(this,"paramName");this.paramName=e,this.innerTree={}}append(e,r){let n=t.formatPathString(e);this.innerTree[n]||(this.innerTree[n]=[]);let o=r.map(s=>({data:t.serializeValue(s)}));return this.innerTree[n].push(...o),this}appendSingle(e,r){return this.append(e,[r])}fromDataTreeDefault(e){this.innerTree={};for(let[r,n]of Object.entries(e)){if(!Array.isArray(n))continue;let o=t.parsePathString(r);this.append(o,n)}return this}appendFlat(e){let r=Array.isArray(e)?e:[e];return this.append([0],r)}flatten(){let e=[];for(let r of Object.values(this.innerTree))if(Array.isArray(r))for(let n of r)e.push(t.deserializeValue(n.data));return e}getPaths(){return Object.keys(this.innerTree)}getPath(e){let r=t.formatPathString(e),n=this.innerTree[r];if(n)return n.map(o=>t.deserializeValue(o.data))}toComputeFormat(){return{ParamName:this.paramName,InnerTree:this.innerTree}}getInnerTree(){return this.innerTree}getParamName(){return this.paramName}static fromInputParams(e){return e.filter(r=>t.hasValidValue(r.default)).map(r=>{let n=new t(r.nickname||"unnamed"),o=r.default;if(r.treeAccess&&C(o))n.fromDataTreeDefault(o),t.isNumericInput(r)&&n.applyNumericConstraints(r.minimum,r.maximum,r.nickname||"unnamed");else{let s=Array.isArray(o)?o:[o],i=t.processValues(s,r);n.appendFlat(i)}return n.toComputeFormat()})}static fromInputParam(e){return t.hasValidValue(e.default)?t.fromInputParams([e])[0]:void 0}static replaceTreeValue(e,r,n){let o=e.length>0&&e[0]instanceof t,s=t.buildFromValue(r,n);if(o){let m=e.slice(),f=m.findIndex(d=>d.getParamName()===r);return f!==-1?m[f]=s:m.push(s),m}let i=e.slice(),a=s.toComputeFormat(),u=i.findIndex(m=>m.ParamName===r);return u!==-1?i[u]=a:i.push(a),i}static buildFromValue(e,r){let n=new t(e);return C(r)?n.fromDataTreeDefault(r):n.appendFlat(r),n}static getTreeValue(e,r){let o=e.length>0&&e[0]instanceof t?t.readFromBuilders(e,r):t.readFromDataTrees(e,r);return o===null||o.length===0?null:o.length===1?o[0]:o}static readFromBuilders(e,r){let n=e.find(o=>o.getParamName()===r);return n?n.flatten():null}static readFromDataTrees(e,r){let n=e.find(i=>i.ParamName===r);if(!n?.InnerTree)return null;let o=Object.keys(n.InnerTree)[0];if(!o)return null;let s=n.InnerTree[o];return Array.isArray(s)?s.map(i=>i?.data!==void 0?t.deserializeValue(i.data):null):s?.data!==void 0?[t.deserializeValue(s.data)]:s!==void 0?[s]:null}static parsePathString(e){let r=e.match(H);if(!r)throw new Error(`Invalid Grasshopper tree path: "${e}". Expected "{}", "{0}", or "{0;1;2}" (negative indices allowed, no empty segments).`);return r[1]?r[1].split(";").map(Number):[]}static formatPathString(e){return`{${e.join(";")}}`}applyNumericConstraints(e,r,n){for(let o of Object.values(this.innerTree))if(Array.isArray(o))for(let s of o){let i=t.deserializeValue(s.data);if(typeof i=="number"){let a=t.clampValue(i,e,r,n);s.data=t.serializeValue(a)}}}static serializeValue(e){return typeof e=="boolean"||typeof e=="number"||typeof e=="string"?e:typeof e=="object"&&e!==null?JSON.stringify(e):String(e)}static deserializeValue(e){if(typeof e=="boolean"||typeof e=="number"||typeof e!="string")return e;if(e.startsWith("{")||e.startsWith("["))try{return JSON.parse(e)}catch{return e}let r=Number(e);return Number.isFinite(r)&&String(r)===e?r:e==="true"?!0:e==="false"?!1:e}static hasValidValue(e){return e==null?!1:typeof e=="string"?!0:!(Array.isArray(e)&&e.length===0||typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0)}static isNumericInput(e){return e.paramType==="Number"||e.paramType==="Integer"}static processValues(e,r){return e.map(n=>t.isNumericInput(r)&&typeof n=="number"?t.clampValue(n,r.minimum,r.maximum,r.nickname||"unnamed"):n).filter(n=>n!=null)}static clampValue(e,r,n,o){let s=e;return r!=null&&s<r&&(y().warn(`${o}: ${e} below min ${r}, clamping`),s=r),n!=null&&s>n&&(y().warn(`${o}: ${e} above max ${n}, clamping`),s=n),s}};export{T as a,E as b,$ as c,ce as d,R as e,x as f,A as g,k as h,ke as i,Me as j,P as k,G as l,B as m};
2
+ //# sourceMappingURL=chunk-6TMSTNHN.js.map