@selvajs/compute 4.0.0-beta.1 → 4.0.0-beta.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -3
- package/dist/chunk-AYH5O3VG.js +4 -0
- package/dist/chunk-AYH5O3VG.js.map +1 -0
- package/dist/chunk-MLPWPV6F.cjs +4 -0
- package/dist/chunk-MLPWPV6F.cjs.map +1 -0
- package/dist/core.cjs +1 -1
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.cts +81 -56
- package/dist/core.d.ts +81 -56
- package/dist/core.js +1 -1
- package/dist/grasshopper.cjs +1 -1
- package/dist/grasshopper.cjs.map +1 -1
- package/dist/grasshopper.d.cts +371 -65
- package/dist/grasshopper.d.ts +371 -65
- package/dist/grasshopper.js +1 -1
- package/dist/grasshopper.js.map +1 -1
- package/dist/handle-files-DMK9bCOW.d.cts +231 -0
- package/dist/handle-files-DMK9bCOW.d.ts +231 -0
- package/dist/index.cjs +1 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -3
- package/dist/index.d.ts +2 -3
- package/dist/index.js +0 -1
- package/package.json +1 -1
- package/dist/chunk-BCVDB6AE.js +0 -2
- package/dist/chunk-BCVDB6AE.js.map +0 -1
- package/dist/chunk-BVMGO7IG.cjs +0 -2
- package/dist/chunk-BVMGO7IG.cjs.map +0 -1
- package/dist/chunk-LLUNR66G.cjs +0 -4
- package/dist/chunk-LLUNR66G.cjs.map +0 -1
- package/dist/chunk-XT3XWDDV.js +0 -4
- package/dist/chunk-XT3XWDDV.js.map +0 -1
- package/dist/handle-files-DcA24IkS.d.cts +0 -478
- package/dist/handle-files-DcA24IkS.d.ts +0 -478
package/dist/chunk-BVMGO7IG.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); 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 _chunkLLUNR66Gcjs = require('./chunk-LLUNR66G.cjs');var ie=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 I(t,e){e||Ve()&&!ie.has(t)&&(ie.add(t),_chunkLLUNR66Gcjs.h.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 Ge="Unable to load grasshopper definition";function We(t){return t instanceof _chunkLLUNR66Gcjs.c?t.code===_chunkLLUNR66Gcjs.b.DEFINITION_NOT_CACHED||t.message.includes(Ge):!1}function je(t,e){if(!e)return;let r=_chunkLLUNR66Gcjs.r.call(void 0, t,"values");if(!Array.isArray(r)||r.length===0)return;let n=[];for(let o of r){let i=_chunkLLUNR66Gcjs.r.call(void 0, o,"innerTree");(!i||Object.keys(i).length===0)&&n.push(_nullishCoalesce(_chunkLLUNR66Gcjs.r.call(void 0, o,"paramName"), () => ("<unnamed>")))}if(n.length===0)return;let s=n.length===r.length?"all":`${n.length}/${r.length}`;_chunkLLUNR66Gcjs.h.call(void 0, ).warn(`Solve returned empty output(s) (${s}): ${n.join(", ")}. These parameters produced no data \u2014 check the definition's inputs and the branch feeding each.`)}async function k(t,e,r){I("solveGrasshopperDefinition",_nullishCoalesce(r.suppressBrowserWarning, () => (r.suppressClientSideWarning)));let n=await j(e),{response:s}=await P(w(n,t),r);return s}async function ae(t,e,r){I("solveGrasshopperDefinitionWithCacheKey",_nullishCoalesce(r.suppressBrowserWarning, () => (r.suppressClientSideWarning)));let n=await j(e);return P(w(n,t),r)}async function ue(t,e,r,n){I("solveByCacheKey",_nullishCoalesce(n.suppressBrowserWarning, () => (n.suppressClientSideWarning)));let s={algo:null,pointer:e,values:t};try{return{...await P(s,n),missed:!1}}catch(o){if(!We(o))throw o;let i=await j(r);return{...await P(w(i,t),n),missed:!0}}}async function j(t){if(!T(t))return t;try{return await t.load()}catch(e){throw new (0, _chunkLLUNR66Gcjs.c)(`Failed to load definition bytes for ref '${t.key}'`,_chunkLLUNR66Gcjs.b.INVALID_INPUT,{context:{definitionKey:t.key},originalError:e instanceof Error?e:new Error(String(e))})}}async function P(t,e){Be(t,e);let r=await _chunkLLUNR66Gcjs.m.call(void 0, "grasshopper",t,e),{pointer:n,algo:s,...o}=r,i=o,a=_chunkLLUNR66Gcjs.l.call(void 0, r);if(a!==void 0){let u=typeof s=="string"?s.length:0;_chunkLLUNR66Gcjs.k.call(void 0, i,Math.max(0,a-u))}return je(i,e.debug),{response:i,cacheKey:typeof n=="string"?n:null}}function w(t,e){let r={algo:null,pointer:null,values:e};return t instanceof Uint8Array?r.algo=_chunkLLUNR66Gcjs.g.call(void 0, t):/^https?:\/\//i.test(t)?r.pointer=t:r.algo=_nullishCoalesce(_chunkLLUNR66Gcjs.e.call(void 0, t), () => (_chunkLLUNR66Gcjs.d.call(void 0, t))),r}function Be(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 le(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":"${fe(n)}"}`;if(Array.isArray(n)){if(e.has(n))return'"[Circular]"';e.add(n);let s=[];for(let o=0;o<n.length;o++)s.push(r(n[o]));return e.delete(n),`[${s.join(",")}]`}if(typeof n=="object"){if(e.has(n))return'"[Circular]"';e.add(n);let s;return typeof n.toJSON=="function"?s=r(n.toJSON()):n instanceof Map?s=`{"__map":[${[...n.entries()].map(([i,a])=>`[${r(i)},${r(a)}]`).sort().join(",")}]}`:n instanceof Set?s=`{"__set":[${[...n.values()].map(r).sort().join(",")}]}`:s=`{${Object.keys(n).sort().map(a=>`${JSON.stringify(a)}:${r(n[a])}`).join(",")}}`,e.delete(n),s}return"null"};return r(t)}function pe(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 ce(t){return pe(t.length,e=>t.charCodeAt(e))}function fe(t){return pe(t.length,e=>t[e])}function $e(t,e){return B(N(t),e)}function B(t,e){let r=le(e);return`${t}|t:${r.length}:${ce(r)}`}function N(t){return T(t)?`r:${t.key}`:typeof t=="string"?`s:${t.length}:${ce(t)}`:`u8:${t.length}:${fe(t)}`}var ze=100;function Ue(t){return typeof t!="string"?!0:!/^https?:\/\//i.test(t)}function _e(t){try{return _nullishCoalesce(_optionalChain([JSON, 'access', _6 => _6.stringify, 'call', _7 => _7(t), 'optionalAccess', _8 => _8.length]), () => (0))}catch (e2){return 0}}var E=class{constructor(e,r,n={},s){_chunkLLUNR66Gcjs.a.call(void 0, this,"executor");_chunkLLUNR66Gcjs.a.call(void 0, this,"baseConfig");_chunkLLUNR66Gcjs.a.call(void 0, this,"mode");_chunkLLUNR66Gcjs.a.call(void 0, this,"maxConcurrent");_chunkLLUNR66Gcjs.a.call(void 0, this,"maxQueueDepth");_chunkLLUNR66Gcjs.a.call(void 0, this,"queueWaitMs");_chunkLLUNR66Gcjs.a.call(void 0, this,"timeoutMs");_chunkLLUNR66Gcjs.a.call(void 0, this,"retry");_chunkLLUNR66Gcjs.a.call(void 0, this,"cacheEnabled");_chunkLLUNR66Gcjs.a.call(void 0, this,"cacheMaxBytes");_chunkLLUNR66Gcjs.a.call(void 0, this,"cacheTtl");_chunkLLUNR66Gcjs.a.call(void 0, this,"cacheErroredSolves");_chunkLLUNR66Gcjs.a.call(void 0, this,"cache",new Map);_chunkLLUNR66Gcjs.a.call(void 0, this,"cacheBytes",0);_chunkLLUNR66Gcjs.a.call(void 0, this,"cacheHits",0);_chunkLLUNR66Gcjs.a.call(void 0, this,"cacheMisses",0);_chunkLLUNR66Gcjs.a.call(void 0, this,"cacheEvictions",0);_chunkLLUNR66Gcjs.a.call(void 0, this,"cacheKeyExecutor");_chunkLLUNR66Gcjs.a.call(void 0, this,"reuseServerDefinitionCache");_chunkLLUNR66Gcjs.a.call(void 0, this,"serverCacheKeys",new Map);_chunkLLUNR66Gcjs.a.call(void 0, this,"onStart");_chunkLLUNR66Gcjs.a.call(void 0, this,"onSettle");_chunkLLUNR66Gcjs.a.call(void 0, this,"onSuperseded");_chunkLLUNR66Gcjs.a.call(void 0, this,"subscribers",new Set);_chunkLLUNR66Gcjs.a.call(void 0, this,"inFlight",new Set);_chunkLLUNR66Gcjs.a.call(void 0, this,"pendingForLatestWins",null);_chunkLLUNR66Gcjs.a.call(void 0, this,"fifoQueue",[]);_chunkLLUNR66Gcjs.a.call(void 0, this,"_lastResult",null);_chunkLLUNR66Gcjs.a.call(void 0, this,"_lastError",null);_chunkLLUNR66Gcjs.a.call(void 0, this,"_lastDurationMs",null);_chunkLLUNR66Gcjs.a.call(void 0, this,"solveSeq",0);_chunkLLUNR66Gcjs.a.call(void 0, this,"lastStateSeq",0);_chunkLLUNR66Gcjs.a.call(void 0, this,"disposed",!1);this.executor=e,this.cacheKeyExecutor=s,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 o=n.cache,i=typeof o=="object"?o:null;this.cacheMaxBytes=Math.max(0,_nullishCoalesce(_optionalChain([i, 'optionalAccess', _9 => _9.maxBytes]), () => (0))),this.cacheEnabled=this.cacheMaxBytes>0,this.cacheTtl=_nullishCoalesce(_optionalChain([i, 'optionalAccess', _10 => _10.ttlMs]), () => (0)),this.cacheErroredSolves=_nullishCoalesce(_optionalChain([i, 'optionalAccess', _11 => _11.cacheErroredSolves]), () => (!0)),this.reuseServerDefinitionCache=!!s&&(_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){_chunkLLUNR66Gcjs.h.call(void 0, ).error("[SolveScheduler] subscriber threw:",r)}}solve(e,r,n){if(this.disposed)return Promise.reject(new (0, _chunkLLUNR66Gcjs.c)("SolveScheduler has been disposed and cannot be used",_chunkLLUNR66Gcjs.b.INVALID_STATE));let s=N(e),o=B(s,r),i=++this.solveSeq,a={key:o,enqueuedAt:Date.now(),startedAt:null};if(_optionalChain([n, 'optionalAccess', _12 => _12.signal, 'optionalAccess', _13 => _13.aborted]))return Promise.reject(this.makeAbortError(a));if(this.cacheEnabled){let u=this.readCache(o);if(u){this.mode==="latest-wins"&&this.supersedeCurrent();let f={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,f),this.notify(),Promise.resolve(u)}}return new Promise((u,f)=>{let c={definition:e,dataTree:r,definitionHash:s,ctx:a,seq:i,resolve:u,reject:f,externalSignal:_optionalChain([n, 'optionalAccess', _14 => _14.signal])};c.externalSignal&&(c.queuedAbortHandler=()=>this.abortQueuedItem(c),c.externalSignal.addEventListener("abort",c.queuedAbortHandler,{once:!0})),this.enqueue(c)})}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, _chunkLLUNR66Gcjs.c)("Solve queue is full; request shed (backpressure)",_chunkLLUNR66Gcjs.b.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 s=new (0, _chunkLLUNR66Gcjs.c)(`Solve waited longer than ${r}ms in queue; shed (backpressure)`,_chunkLLUNR66Gcjs.b.QUEUE_TIMEOUT,{statusCode:503,context:{key:e.ctx.key,waitedMs:Date.now()-e.ctx.enqueuedAt,queueWaitMs:r}});this.settleError(e,s)&&this.runHook(this.onSettle,e.ctx,{status:"error",error:s,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 s=()=>r.abort();_optionalChain([e, 'access', _15 => _15.externalSignal, 'optionalAccess', _16 => _16.addEventListener, 'call', _17 => _17("abort",s,{once:!0})]),this.runHook(this.onStart,e.ctx),this.notify();let o=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),f=performance.now()-o;if(this.cacheEnabled&&this.writeCache(e.ctx.key,a),!this.settleSuccess(e,a))return;this.writeLastState(e.seq,{result:a,durationMs:f}),this.runHook(this.onSettle,e.ctx,{status:"success",response:a,durationMs:f,fromCache:!1,definitionReuploaded:u})}catch(i){let a=performance.now()-o,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', _18 => _18.externalSignal, 'optionalAccess', _19 => _19.removeEventListener, 'call', _20 => _20("abort",s)]),this.inFlight.delete(n),this.drainNext(),this.notify()}}async runExecutor(e,r,n,s){if(!this.cacheKeyExecutor||!this.reuseServerDefinitionCache||!Ue(e))return{response:await this.executor(e,r,s)};let o=n,i=_nullishCoalesce(this.serverCacheKeys.get(o), () => (null)),a=await this.cacheKeyExecutor(e,r,i,s);if(a.cacheKey)for(this.serverCacheKeys.delete(o),this.serverCacheKeys.set(o,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(o);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, _chunkLLUNR66Gcjs.c)("Superseded by newer solve",_chunkLLUNR66Gcjs.b.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, _chunkLLUNR66Gcjs.c)("Request aborted by caller",_chunkLLUNR66Gcjs.b.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 _chunkLLUNR66Gcjs.c?e:this.isAbortLikeError(e)?this.makeAbortError(r.ctx):new (0, _chunkLLUNR66Gcjs.c)(e instanceof Error?e.message:String(e),_chunkLLUNR66Gcjs.b.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),this.cacheMisses+=1,null):(this.cache.delete(e),this.cache.set(e,r),this.cacheHits+=1,r.response):(this.cacheMisses+=1,null)}writeCache(e,r){if(!this.cacheEnabled||!this.cacheErroredSolves&&r.errors&&r.errors.length>0)return;let n=_nullishCoalesce(_chunkLLUNR66Gcjs.l.call(void 0, r), () => (_e(r)));if(!(n>this.cacheMaxBytes))for(this.dropCacheEntry(e),this.cache.set(e,{response:r,insertedAt:Date.now(),sizeBytes:n}),this.cacheBytes+=n;this.cacheBytes>this.cacheMaxBytes&&this.cache.size>0;){let s=this.cache.keys().next().value;if(s===void 0)break;this.dropCacheEntry(s),this.cacheEvictions+=1}}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,hits:this.cacheHits,misses:this.cacheMisses,evictions:this.cacheEvictions}}dispose(){this.disposed||(this.disposed=!0,this.cancelAll(),this.subscribers.clear(),this.clearCache())}runHook(e,...r){if(e)try{e(...r)}catch(n){_chunkLLUNR66Gcjs.h.call(void 0, ).error("[SolveScheduler] hook threw:",n)}}};function de(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,s=_chunkLLUNR66Gcjs.r.call(void 0, e,"innerTree");if(s&&typeof s=="object"){for(let o of Object.values(s))if(Array.isArray(o)){r+=o.length;for(let i of o){let a=_optionalChain([i, 'optionalAccess', _21 => _21.data]);typeof a=="string"&&(n+=a.length)}}}return{param:_nullishCoalesce(_chunkLLUNR66Gcjs.r.call(void 0, e,"paramName"), () => ("<unnamed>")),items:r,bytes:n}}):[]}var O=class t{constructor(e){_chunkLLUNR66Gcjs.a.call(void 0, this,"config");_chunkLLUNR66Gcjs.a.call(void 0, this,"serverStats");_chunkLLUNR66Gcjs.a.call(void 0, this,"disposed",!1);this.config=this.normalizeComputeConfig(e),this.serverStats=new (0, _chunkLLUNR66Gcjs.o)(this.config.serverUrl,this.config.apiKey)}static async create(e){let r=new t(e),n=Math.max(1,(_nullishCoalesce(_optionalChain([e, 'access', _22 => _22.retry, 'optionalAccess', _23 => _23.attempts]), () => (2)))+1),s=_nullishCoalesce(_optionalChain([e, 'access', _24 => _24.retry, 'optionalAccess', _25 => _25.baseDelayMs]), () => (250)),o=_nullishCoalesce(_optionalChain([e, 'access', _26 => _26.retry, 'optionalAccess', _27 => _27.maxDelayMs]), () => (1e3));for(let i=0;i<n;i++){if(await r.serverStats.isServerOnline())return r;if(i<n-1){let a=Math.min(s*2**i,o);await new Promise(u=>setTimeout(u,a))}}throw await r.dispose(),new (0, _chunkLLUNR66Gcjs.c)("Rhino Compute server is not online",_chunkLLUNR66Gcjs.b.NETWORK_ERROR,{context:{serverUrl:r.config.serverUrl,attempts:n}})}getConfig(){return this.ensureNotDisposed(),{...this.config}}async getIO(e){return this.ensureNotDisposed(),$(e,this.config)}async getRawIO(e){return this.ensureNotDisposed(),F(e,this.config)}async solve(e,r,n){this.ensureNotDisposed();try{if(typeof e=="string"&&!_optionalChain([e, 'optionalAccess', _28 => _28.trim, 'call', _29 => _29()]))throw new (0, _chunkLLUNR66Gcjs.c)("Definition URL/content is required",_chunkLLUNR66Gcjs.b.INVALID_INPUT,{context:{receivedUrl:e}});if(e instanceof Uint8Array&&e.length===0)throw new (0, _chunkLLUNR66Gcjs.c)("Definition content is empty",_chunkLLUNR66Gcjs.b.INVALID_INPUT);if(T(e)&&!e.key.trim())throw new (0, _chunkLLUNR66Gcjs.c)("DefinitionRef key is empty",_chunkLLUNR66Gcjs.b.INVALID_INPUT);let s={...this.config,..._optionalChain([n, 'optionalAccess', _30 => _30.signal])!==void 0&&{signal:n.signal},..._optionalChain([n, 'optionalAccess', _31 => _31.timeoutMs])!==void 0&&{timeoutMs:n.timeoutMs},..._optionalChain([n, 'optionalAccess', _32 => _32.retry])!==void 0&&{retry:n.retry}},o=await k(r,e,s);if(_optionalChain([o, 'optionalAccess', _33 => _33.errors])&&o.errors.length>0)throw new (0, _chunkLLUNR66Gcjs.c)(o.errors.join("; ")||"Computation failed",_chunkLLUNR66Gcjs.b.COMPUTATION_ERROR,{context:{definition:de(e),inputSummary:me(r),errors:o.errors,warnings:o.warnings,values:o.values}});return o}catch(s){throw this.config.debug&&_chunkLLUNR66Gcjs.h.call(void 0, ).error("Compute failed:",s),s instanceof _chunkLLUNR66Gcjs.c?s:new (0, _chunkLLUNR66Gcjs.c)(s instanceof Error?s.message:String(s),_chunkLLUNR66Gcjs.b.COMPUTATION_ERROR,{context:{definition:de(e),inputSummary:me(r)},originalError:s instanceof Error?s:new Error(String(s))})}}createScheduler(e){this.ensureNotDisposed();let r=(s,o,i)=>k(o,s,i),n=(s,o,i,a)=>i===null?ae(o,s,a).then(u=>({...u,missed:!1})):ue(o,i,s,a);return new E(r,this.config,e,n)}async dispose(){this.disposed||(this.disposed=!0,await this.serverStats.dispose())}ensureNotDisposed(){if(this.disposed)throw new (0, _chunkLLUNR66Gcjs.c)("GrasshopperClient has been disposed and cannot be used",_chunkLLUNR66Gcjs.b.INVALID_STATE)}normalizeComputeConfig(e){return{...e,serverUrl:_chunkLLUNR66Gcjs.n.call(void 0, e.serverUrl),apiKey:e.apiKey,authToken:e.authToken,debug:_nullishCoalesce(e.debug, () => (!1)),suppressBrowserWarning:_nullishCoalesce(e.suppressBrowserWarning, () => (e.suppressClientSideWarning))}}};var M=new Map;function ye(t,e){M.set(t,e)}ye("Rhino.Geometry.Point3d",(t,e)=>{let r=e;return!r||typeof r.X!="number"?null:new t.Point([r.X,r.Y,r.Z])});ye("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 qe(t){if(M.has(t))return M.get(t);for(let[e,r]of M)if(t.startsWith(e))return r}function Ke(t){return!!(t&&typeof t=="object"&&typeof t.data=="string")}function he(t,e){return{__decodeError:!0,type:t,raw:e}}function ge(t,e,r){let n=qe(e),s=!1;if(n)try{let o=n(r,t);if(o!=null)return o}catch(o){_chunkLLUNR66Gcjs.h.call(void 0, ).warn(`Failed to decode Rhino type ${e}:`,o),s=!0}try{if(Ke(t))return r.CommonObject.decode(t)}catch(o){return _chunkLLUNR66Gcjs.h.call(void 0, ).warn(`Failed to decode ${e} with CommonObject:`,o),he(e,t)}return s?he(e,t):t}function be(t){let e=new WeakSet,r=n=>{if(!n||typeof n!="object"||e.has(n))return;e.add(n);let s=n.delete;if(typeof s=="function"){let i=n.isDeleted;(typeof i!="function"||!i.call(n))&&s.call(n);return}if(Array.isArray(n)){for(let i of n)r(i);return}let o=Object.getPrototypeOf(n);if(o===Object.prototype||o===null)for(let i of Object.values(n))r(i)};r(t)}var x={STRING:"System.String",INT:"System.Int32",DOUBLE:"System.Double",BOOL:"System.Boolean"},Qe="Rhino.Geometry.",He=["WebDisplay"],Je="FileData";function Te(t){return He.some(e=>t.includes(e))}function Ye(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 Xe(t,e,r){switch(e){case x.STRING:return typeof t!="string"?t:t.replace(/^"(.*)"$/,"$1");case x.INT:return Number.parseInt(t,10);case x.DOUBLE:return Number.parseFloat(t);case x.BOOL:return String(t).toLowerCase()==="true";default:return r&&e.startsWith(Qe)?ge(t,e,r):t}}var z=new WeakMap;function Se(t){if(z.has(t))return z.get(t);let e=Ye(t.data);return z.set(t,e),e}function De(t,e,r,n){if(typeof t.data!="string")return t.data;let s=r?Se(t):t.data;return Xe(s,e,n)}function Ze(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 U(t){let e=_chunkLLUNR66Gcjs.r.call(void 0, t,"values");return Array.isArray(e)?e:[]}function _(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 Ie(t,e=!1,r={}){let{parseValues:n=!0,rhino:s,stringOnly:o=!1}=r,i={},a=new Set;for(let u of U(t)){let f=_chunkLLUNR66Gcjs.r.call(void 0, u,"paramName");q(_chunkLLUNR66Gcjs.r.call(void 0, u,"innerTree"),c=>{let d=_(c);if(Te(d)||o&&d!==x.STRING)return;let g=e?c.id:f;if(!g)return;let b=De(c,d,n,s);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:()=>be(i)}}function xe(t){let e=[];for(let r of U(t))q(_chunkLLUNR66Gcjs.r.call(void 0, r,"innerTree"),n=>{if(!_(n).includes(Je))return;let s=Se(n);Ze(s)&&e.push(s)});return e}function Ce(t,e,r={}){let{parseValues:n=!0,rhino:s,stringOnly:o=!1}=r;for(let i of U(t)){let a=_chunkLLUNR66Gcjs.r.call(void 0, i,"innerTree"),u=!1;if("byName"in e){if(_chunkLLUNR66Gcjs.r.call(void 0, i,"paramName")!==e.byName)continue;u=!0}let f=[];if(q(a,c=>{if("byId"in e){if(c.id!==e.byId)return;u=!0}let d=_(c);Te(d)||o&&d!==x.STRING||f.push(De(c,d,n,s))}),u)return f.length===0?void 0:f.length===1?f[0]:f}}var L=class{constructor(e,r=!1){_chunkLLUNR66Gcjs.a.call(void 0, this,"response",e);_chunkLLUNR66Gcjs.a.call(void 0, this,"debug",r)}getValues(e=!1,r={}){return Ie(this.response,e,r)}getValue(e,r){return Ce(this.response,e,r)}getFileData(){return xe(this.response)}async getAndDownloadFiles(e,r){let n=this.getFileData();await _chunkLLUNR66Gcjs.u.call(void 0, n,e,r)}};var K=/^\{(-?\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])=>K.test(r)&&Array.isArray(n))}function Q(t,e,r){let n=Number(t.toFixed(e));return Math.abs(t-n)<r?n:t}function we(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),D=Math.pow(10,-b),Z=Number(D.toFixed(b));return Math.abs(Z-D)<e?Z:D}return 1}let n=String(t),s=n.toLowerCase().match(/e(-?\d+)/);if(s){let d=Number(s[1]);if(d<0||n.toLowerCase().includes("e-")){let g=Math.abs(d),b=Math.pow(10,-g),D=Number(b.toFixed(g));return Math.abs(D-b)<e?D:b}return .1}let o=12,a=r.toFixed(o).replace(/0+$/,""),u=Math.min((a.split(".")[1]||"").length,o);if(u===0)return .1;let f=Math.pow(10,-u),c=Number(f.toFixed(u));return Math.abs(c-f)<e?c:f}function H(t){return typeof t.stepSize=="number"&&Number.isFinite(t.stepSize)&&t.stepSize>0?t.stepSize:void 0}function S(t,e,r){if(t==null)return t;if(Array.isArray(t)){let s=t.map(e).filter(o=>o!==null);return s.length>0?s:void 0}let n=e(t);return n!==null?n:r?void 0:t}var v=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},V=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},Ee=t=>typeof t=="string"?t.length>=2&&t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t.startsWith('"')?t.slice(1):t:null,ve=t=>{if(typeof t=="string"){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')&&(e=e.slice(1,-1).trim()),e}return null};function J(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:(_chunkLLUNR66Gcjs.h.call(void 0, ).warn(`Parsed value for input ${t} is not an object`),null)}catch(r){return _chunkLLUNR66Gcjs.h.call(void 0, ).warn(`Failed to parse object value "${e}" for input ${t}`,r),null}return null}}function et(t,e=1e-8){let r=t.paramType==="Integer",n=H(t);if(C(t.default))return{default:t.default,stepSize:_nullishCoalesce(n, () => ((r?1:.1)))};if(typeof t.default=="string"&&t.default.trim()!==""&&v(t.default)===null)throw new (0, _chunkLLUNR66Gcjs.c)(`Invalid numeric default "${t.default}" for input "${t.name||"unknown"}"`,_chunkLLUNR66Gcjs.b.VALIDATION_ERROR,{context:{inputName:t.name,default:t.default}});let s=S(t.default,v,!0);if(r)return Array.isArray(s)?s=s.map(d=>typeof d=="number"?Math.round(d):d):typeof s=="number"&&(s=Math.round(s)),{default:s,stepSize:_nullishCoalesce(n, () => (1))};let o=Array.isArray(s)?s[0]:s,i;typeof o=="number"&&Number.isFinite(o)&&o!==0?i=o: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?we(i,e):.1))),u=0,f=String(a),c=f.toLowerCase().match(/e(-?\d+)/);if(c?u=Math.abs(Number(c[1])):u=_nullishCoalesce(_optionalChain([f, 'access', _34 => _34.split, 'call', _35 => _35("."), 'access', _36 => _36[1], 'optionalAccess', _37 => _37.length]), () => (0)),u===0&&typeof o=="number"&&o!==0&&Math.abs(o)<1){let d=Math.ceil(-Math.log10(Math.abs(o)));Number.isFinite(d)&&d>0&&(u=d)}return u=Math.min(Math.max(u,0),12),Array.isArray(s)?s=s.map(d=>typeof d=="number"?Q(d,u,e):d):typeof s=="number"&&(s=Q(s,u,e)),{default:s,stepSize:a}}var tt={types:["Number","Integer"],parse(t,e){let{default:r,stepSize:n}=et(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(H(t), () => ((t.paramType==="Integer"?1:.1))),default:r?[n]:n}}},rt={types:["Boolean"],parse(t,e){if(C(t.default))return{...e,paramType:"Boolean",default:t.default};let r=S(t.default,V,!1);if(r!=null&&typeof r!="boolean"&&!Array.isArray(r))throw new (0, _chunkLLUNR66Gcjs.c)(`Invalid boolean default "${String(r)}" for input "${t.name||"unknown"}"`,_chunkLLUNR66Gcjs.b.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}}},nt={types:["Text"],parse(t,e){let r=S(t.default,Ee,!1);return{...e,paramType:"Text",default:r}},fallback(t,e){let r=(_nullishCoalesce(t.atMost, () => (1)))>1;return{...e,paramType:"Text",default:r?[""]:""}}},st={types:["ValueList"],parse(t,e){if(!t.values||typeof t.values!="object"||Object.keys(t.values).length===0)throw _chunkLLUNR66Gcjs.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 (0, _chunkLLUNR66Gcjs.c)(`ValueList input "${t.nickname||"unnamed"}" default is not a string-able value`,_chunkLLUNR66Gcjs.b.VALIDATION_ERROR,{context:{inputName:t.name,default:t.default}});let n=String(t.default).toLowerCase(),s=Object.keys(t.values).find(o=>o.toLowerCase()===n);s!==void 0?r=s:_chunkLLUNR66Gcjs.h.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}}},Ae={types:["Geometry"],parse(t,e){let r=S(t.default,J(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}}},ot={types:["File"],parse(t,e){let r=S(t.default,J(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}}},it={types:["Color"],parse(t,e){let r=S(t.default,ve,!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"}}},at=[tt,rt,nt,st,Ae,ot,it],Y=new Map(at.flatMap(t=>t.types.map(e=>[e,t]))),Re=Ae;function Pe(t){return _chunkLLUNR66Gcjs.r.call(void 0, t,"data")}function ut(t){return _chunkLLUNR66Gcjs.r.call(void 0, t,"type")}var lt=new Set(["System.Double","System.Single","System.Decimal","System.Int32","System.Int64"]),pt=new Set(["System.Int32","System.Int64"]);function ke(t){if(typeof t.default!="object"||t.default===null)return{schema:t};if(Array.isArray(t.default))return{schema:t};if(!_chunkLLUNR66Gcjs.s.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 _chunkLLUNR66Gcjs.h.call(void 0, ).warn("Unexpected structure in input.default:",t.default),{schema:{...t,default:null},warning:{code:"MALFORMED_DEFAULT",message:n}}}let e=_nullishCoalesce(_chunkLLUNR66Gcjs.r.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={},s=[];for(let[i,a]of Object.entries(e)){if(!Array.isArray(a)){let f=`Input "${_nullishCoalesce(t.name, () => ("unknown"))}" default had a non-array innerTree branch ("${i}"); the default was dropped.`;return _chunkLLUNR66Gcjs.h.call(void 0, ).warn("Unexpected structure in input.default innerTree:",t.default),{schema:{...t,default:null},warning:{code:"MALFORMED_DEFAULT",message:f}}}let u=[];for(let f of a){let c=Pe(f),d=ut(f);if(d&<.has(d)){if(typeof c=="string"&&c.trim()==="")continue;let g=v(c);if(g===null){s.push(`"${String(c)}" (${d})`);continue}u.push(pt.has(d)?Math.round(g):g);continue}if(d==="System.Boolean"){let g=V(c);if(g===null){s.push(`"${String(c)}" (${d})`);continue}u.push(g);continue}if(typeof c=="string"&&_optionalChain([d, 'optionalAccess', _38 => _38.startsWith, 'call', _39 => _39("Rhino.Geometry")])){try{u.push(JSON.parse(c))}catch (e5){u.push(c)}continue}u.push(c)}n[i]=u}let o;if(s.length>0){let i=`Input "${_nullishCoalesce(t.name, () => ("unknown"))}" default contained ${s.length} tree value(s) that could not be parsed and were dropped: ${s.join(", ")}.`;_chunkLLUNR66Gcjs.h.call(void 0, ).warn(i),o={code:"MALFORMED_DEFAULT",message:i}}return{schema:{...t,default:n},...o&&{warning:o}}}let r=[];for(let n of Object.values(e))Array.isArray(n)&&n.forEach(s=>{s&&typeof s=="object"&&_chunkLLUNR66Gcjs.s.call(void 0, s,"data")&&r.push(Pe(s))});return r.length===0?{schema:{...t,default:void 0}}:r.length===1?{schema:{...t,default:r[0]}}:{schema:{...t,default:r}}}var ct=new Map([...Y.keys()].map(t=>[t.toLowerCase(),t]));function ft(t){return _nullishCoalesce(ct.get(_optionalChain([t, 'optionalAccess', _40 => _40.toLowerCase, 'call', _41 => _41()])), () => (t))}function dt(t){return Ne(t).input}function Ne(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=ft(t.paramType),n={...t,paramType:r},s;try{let{schema:i,warning:a}=ke(n);n=i,s=a&&{inputName:t.name||"unknown",paramType:t.paramType,message:a.message,code:a.code}}catch(i){n={...n,default:null},s={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 o=Y.get(r);try{if(!o)throw _chunkLLUNR66Gcjs.c.unknownParamType(r,t.name);return{input:o.parse(n,e),error:s,...s&&{errors:[s]}}}catch(i){if(i instanceof _chunkLLUNR66Gcjs.c){_chunkLLUNR66Gcjs.h.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(o, () => (Re))).fallback(n,e),error:a,errors:s?[s,a]:[a]}}throw new (0, _chunkLLUNR66Gcjs.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 Oe(t){let e=[],r=[];for(let n of t){let{input:s,errors:o}=Ne(n);e.push(s),o&&r.push(...o)}return{inputs:e,parseErrors:r}}function Fe(t){let e=_chunkLLUNR66Gcjs.r.call(void 0, t,"stepSize");return{id:_nullishCoalesce(_chunkLLUNR66Gcjs.r.call(void 0, t,"id"), () => ("")),name:_nullishCoalesce(_chunkLLUNR66Gcjs.r.call(void 0, t,"name"), () => ("")),nickname:_nullishCoalesce(_chunkLLUNR66Gcjs.r.call(void 0, t,"nickname"), () => (null)),description:_nullishCoalesce(_chunkLLUNR66Gcjs.r.call(void 0, t,"description"), () => ("")),paramType:_nullishCoalesce(_chunkLLUNR66Gcjs.r.call(void 0, t,"paramType"), () => ("")),treeAccess:_nullishCoalesce(_chunkLLUNR66Gcjs.r.call(void 0, t,"treeAccess"), () => (!1)),minimum:_nullishCoalesce(_chunkLLUNR66Gcjs.r.call(void 0, t,"minimum"), () => (null)),maximum:_nullishCoalesce(_chunkLLUNR66Gcjs.r.call(void 0, t,"maximum"), () => (null)),atLeast:_nullishCoalesce(_chunkLLUNR66Gcjs.r.call(void 0, t,"atLeast"), () => (1)),atMost:_nullishCoalesce(_chunkLLUNR66Gcjs.r.call(void 0, t,"atMost"), () => (1)),stepSize:typeof e=="number"&&Number.isFinite(e)?e:void 0,default:_chunkLLUNR66Gcjs.r.call(void 0, t,"default"),values:_chunkLLUNR66Gcjs.r.call(void 0, t,"values"),acceptedFormats:_chunkLLUNR66Gcjs.r.call(void 0, t,"acceptedFormats"),groupName:_nullishCoalesce(_chunkLLUNR66Gcjs.r.call(void 0, t,"groupName"), () => (null))}}function Me(t){return{name:_nullishCoalesce(_chunkLLUNR66Gcjs.r.call(void 0, t,"name"), () => ("")),nickname:_nullishCoalesce(_chunkLLUNR66Gcjs.r.call(void 0, t,"nickname"), () => (null)),paramType:_nullishCoalesce(_chunkLLUNR66Gcjs.r.call(void 0, t,"paramType"), () => ("")),id:_nullishCoalesce(_chunkLLUNR66Gcjs.r.call(void 0, t,"id"), () => (""))}}async function F(t,e){let r=w(t,[]),n={};if(r.algo&&(n.algo=r.algo),r.pointer&&(n.pointer=r.pointer),!n.algo&&!n.pointer)throw new (0, _chunkLLUNR66Gcjs.c)("Definition must resolve to either a URL pointer or base64 algo",_chunkLLUNR66Gcjs.b.INVALID_INPUT,{context:{definition:t}});let s=await _chunkLLUNR66Gcjs.m.call(void 0, "io",n,e);if(!s||typeof s!="object")throw new (0, _chunkLLUNR66Gcjs.c)("Invalid IO response structure",_chunkLLUNR66Gcjs.b.INVALID_INPUT,{context:{response:s,definition:t}});let o=Le(_chunkLLUNR66Gcjs.r.call(void 0, s,"warnings")),i=Le(_chunkLLUNR66Gcjs.r.call(void 0, s,"errors")),a=_chunkLLUNR66Gcjs.r.call(void 0, s,"inputs"),u=_chunkLLUNR66Gcjs.r.call(void 0, s,"outputs");return{inputs:Array.isArray(a)?a.map(Fe):[],outputs:Array.isArray(u)?u.map(Me):[],...o&&{loadWarnings:o},...i&&{loadErrors:i}}}function Le(t){if(!Array.isArray(t))return;let e=t.map(mt).filter(r=>r!==void 0);return e.length>0?e:void 0}function mt(t){if(t==null)return;let e;if(typeof t=="string")e=t;else if(typeof t=="object"){let r=_chunkLLUNR66Gcjs.r.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 $(t,e){I("fetchParsedDefinitionIO",_nullishCoalesce(e.suppressBrowserWarning, () => (e.suppressClientSideWarning)));let{inputs:r,outputs:n,loadWarnings:s,loadErrors:o}=await F(t,e),{inputs:i,parseErrors:a}=Oe(r);return{inputs:i,outputs:n,...a.length>0&&{parseErrors:a},...s&&{loadWarnings:s},...o&&{loadErrors:o}}}var X=class t{constructor(e){_chunkLLUNR66Gcjs.a.call(void 0, this,"innerTree");_chunkLLUNR66Gcjs.a.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 s=r.map(o=>({data:t.serializeValue(o)}));return this.innerTree[n].push(...s),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 s=t.parsePathString(r);this.append(s,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(s=>t.deserializeValue(s.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"),s=r.default;if(r.treeAccess&&C(s))n.fromDataTreeDefault(s),t.isNumericInput(r)&&n.applyNumericConstraints(r.minimum,r.maximum,r.nickname||"unnamed");else{let o=Array.isArray(s)?s:[s],i=t.processValues(o,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 s=e.length>0&&e[0]instanceof t,o=t.buildFromValue(r,n);if(s){let f=e.slice(),c=f.findIndex(d=>d.getParamName()===r);return c!==-1?f[c]=o:f.push(o),f}let i=e.slice(),a=o.toComputeFormat(),u=i.findIndex(f=>f.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 s=e.length>0&&e[0]instanceof t?t.readFromBuilders(e,r):t.readFromDataTrees(e,r);return s===null||s.length===0?null:s.length===1?s[0]:s}static readFromBuilders(e,r){let n=e.find(s=>s.getParamName()===r);return n?n.flatten():null}static readFromDataTrees(e,r){let n=e.find(i=>i.ParamName===r);if(!_optionalChain([n, 'optionalAccess', _42 => _42.InnerTree]))return null;let s=Object.keys(n.InnerTree)[0];if(!s)return null;let o=n.InnerTree[s];return Array.isArray(o)?o.map(i=>_optionalChain([i, 'optionalAccess', _43 => _43.data])!==void 0?t.deserializeValue(i.data):null):_optionalChain([o, 'optionalAccess', _44 => _44.data])!==void 0?[t.deserializeValue(o.data)]:o!==void 0?[o]:null}static parsePathString(e){let r=e.match(K);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 s of Object.values(this.innerTree))if(Array.isArray(s))for(let o of s){let i=t.deserializeValue(o.data);if(typeof i=="number"){let a=t.clampValue(i,e,r,n);o.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,s){let o=e;return r!=null&&o<r&&(_chunkLLUNR66Gcjs.h.call(void 0, ).warn(`${s}: ${e} below min ${r}, clamping`),o=r),n!=null&&o>n&&(_chunkLLUNR66Gcjs.h.call(void 0, ).warn(`${s}: ${e} above max ${n}, clamping`),o=n),o}};exports.a = T; exports.b = k; exports.c = le; exports.d = $e; exports.e = N; exports.f = E; exports.g = O; exports.h = L; exports.i = dt; exports.j = F; exports.k = $; exports.l = X;
|
|
2
|
-
//# sourceMappingURL=chunk-BVMGO7IG.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/selva/selva/packages/compute/dist/chunk-BVMGO7IG.cjs","../src/core/utils/warnings.ts","../src/grasshopper/definition-ref.ts","../src/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,yuBAA2I,ICGrIA,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-BVMGO7IG.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, which would consume the scheduler cache's\n * byte budget many times over. Stripping via shallow copy rather than `delete`\n * keeps any already-observed response object 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"]}
|
package/dist/chunk-LLUNR66G.cjs
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var ae=Object.defineProperty;var ue=(t,e,r)=>e in t?ae(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var y=(t,e,r)=>ue(t,typeof e!="symbol"?e+"":e,r);var l={NETWORK_ERROR:"NETWORK_ERROR",AUTH_ERROR:"AUTH_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",COMPUTATION_ERROR:"COMPUTATION_ERROR",TIMEOUT_ERROR:"TIMEOUT_ERROR",CORS_ERROR:"CORS_ERROR",NOT_FOUND:"NOT_FOUND",RATE_LIMIT:"RATE_LIMIT",INVALID_RESPONSE:"INVALID_RESPONSE",UNKNOWN_ERROR:"UNKNOWN_ERROR",INVALID_STATE:"INVALID_STATE",INVALID_INPUT:"INVALID_INPUT",INVALID_CONFIG:"INVALID_CONFIG",BROWSER_ONLY:"BROWSER_ONLY",ENVIRONMENT_ERROR:"ENVIRONMENT_ERROR",ENCODING_ERROR:"ENCODING_ERROR",MALFORMED_DEFAULT:"MALFORMED_DEFAULT",SUPERSEDED:"SUPERSEDED",ABORTED:"ABORTED",QUEUE_FULL:"QUEUE_FULL",QUEUE_TIMEOUT:"QUEUE_TIMEOUT",DEFINITION_NOT_CACHED:"DEFINITION_NOT_CACHED"},p= exports.c =class t extends Error{constructor(r,n=l.UNKNOWN_ERROR,o){super(r);y(this,"code");y(this,"statusCode");y(this,"context");y(this,"originalError");this.name="RhinoComputeError",this.code=n,this.statusCode=_optionalChain([o, 'optionalAccess', _2 => _2.statusCode]),this.context=_optionalChain([o, 'optionalAccess', _3 => _3.context]),this.originalError=_optionalChain([o, 'optionalAccess', _4 => _4.originalError]),_optionalChain([o, 'optionalAccess', _5 => _5.originalError])&&(this.cause=o.originalError)}static missingValues(r,n,o){return new t(`Input "${r}" has no values defined${n?` (expected ${n})`:""}`,l.INVALID_INPUT,{context:{inputName:r,expectedType:n,...o}})}static unknownParamType(r,n,o){return new t(`Unknown paramType: ${r}`,l.VALIDATION_ERROR,{context:{receivedParamType:r,paramName:n,...o}})}};function C(){let t=globalThis.Buffer;return typeof t=="function"?t:void 0}function De(t){let e=C();return e?e.from(t,"utf-8").toString("base64"):de(new TextEncoder().encode(t))}var le=64,ce="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function Me(t){if(!t)return null;let e=t.replace(/[\t\n\f\r ]/g,"");e.length%4===0&&(e=e.replace(/={1,2}$/,""));let r=e.length%4;if(r===1||e.length<le||!/^[A-Za-z0-9+/]*$/.test(e))return null;let n=ce.indexOf(e.charAt(e.length-1));return r===2&&(n&15)!==0||r===3&&(n&3)!==0?null:r===0?e:e+"==".slice(0,4-r)}function _(t){let e=t.replace(/[\t\n\f\r ]/g,"");if(e.length%4===0&&(e=e.replace(/={1,2}$/,"")),e.length%4===1||!/^[A-Za-z0-9+/]*$/.test(e))throw new p("Invalid base64 input.",l.ENCODING_ERROR,{context:{inputLength:t.length}});let r=C();if(r)return new Uint8Array(r.from(e,"base64"));if(typeof globalThis.atob=="function"){let n=globalThis.atob(e),o=new Uint8Array(n.length);for(let s=0;s<n.length;s++)o[s]=n.charCodeAt(s)&255;return o}throw new p("Base64 decoding not supported in this environment.",l.INVALID_STATE,{context:{environmentInfo:"atob or Buffer not available"}})}function P(t){let e=C();if(e)return e.byteLength(t,"utf-8");let r=0;for(let n=0;n<t.length;n++){let o=t.charCodeAt(n);o<128?r+=1:o<2048?r+=2:o>=55296&&o<=56319&&n+1<t.length&&(t.charCodeAt(n+1)&64512)===56320?(r+=4,n++):r+=3}return r}function de(t){let e=C();if(e)return e.from(t).toString("base64");if(typeof globalThis.btoa=="function"){let n=[];for(let o=0;o<t.length;o+=32766)n.push(globalThis.btoa(String.fromCharCode.apply(null,t.subarray(o,o+32766))));return n.join("")}throw new p("Base64 encoding not supported in this environment.",l.INVALID_STATE,{context:{environmentInfo:"btoa or Buffer not available"}})}var I=class{debug(){}info(){}warn(){}error(){}},U=class{debug(e,...r){console.debug(e,...r)}info(e,...r){console.info(e,...r)}warn(e,...r){console.warn(e,...r)}error(e,...r){console.error(e,...r)}},L=new I;function m(){return L}function B(t){if(t===null){L=new I;return}let e=["debug","info","warn","error"].filter(r=>typeof t[r]!="function");if(e.length>0)throw new p(`Logger is missing required method(s): ${e.join(", ")}. A logger must implement debug, info, warn and error.`,l.INVALID_CONFIG,{context:{missingMethods:e}});L=t}function fe(){B(new U)}function h(t,e){e&&m().debug(t)}function W(t,e){let r=e.replace(/\/+$/,""),n=t.replace(/^\/+/,"");return`${r}/${n}`}function pe(t){try{let e=new URL(t).hostname.toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}catch (e2){return/(localhost|127\.0\.0\.1|\[::1\])/i.test(t)}}var q=new Set;function z(t,e){let r={...e.headers,"X-Request-ID":t,"Content-Type":"application/json",...e.authToken&&{Authorization:e.authToken},...e.apiKey&&{RhinoComputeKey:e.apiKey}};return!e.apiKey&&!e.authToken&&!q.has(e.serverUrl)&&!pe(e.serverUrl)&&(q.add(e.serverUrl),m().warn(`\u26A0\uFE0F [Rhino Compute] Request [${t}] targets remote server (${e.serverUrl}) but no API key or auth token is configured. Requests may fail or be rate-limited. (warned once per server)`)),r}function K(){return`${Date.now()}-${Math.random().toString(36).substring(2,11)}`}function me(t){if(!t)return null;let e={raw:t},r=!1;for(let n of t.split(",")){let[o,...s]=n.trim().split(";"),c=s.find(d=>d.trim().toLowerCase().startsWith("dur"));if(!c)continue;let i=Number(c.split("=")[1]);if(!Number.isFinite(i))continue;let a=o.trim().toLowerCase();(a==="decode"||a==="solve"||a==="encode")&&(e[a]=i,r=!0)}return r?e:null}function x(t,e,r,n){if(!r)return;let o=me(t.headers.get("Server-Timing"));if(o)try{r(o,e)}catch(s){n&&h(` onServerTiming callback threw: ${s}`,!0)}}var V=new WeakMap;function N(t,e){typeof t!="object"||t===null||V.set(t,e)}function ge(t){if(!(typeof t!="object"||t===null))return V.get(t)}var D=4096;function he(t){return t.length<=D?t:`${t.slice(0,D)}\u2026 [truncated ${t.length-D} chars]`}function ye(t,e,r,n,o,s,c,i){let{status:a,statusText:d}=t,u={};t.headers.forEach((se,ie)=>{u[ie]=se});let g=s.trim(),f=g?` \u2014 ${g.slice(0,200)}${g.length>200?"\u2026":""}`:"",E=_nullishCoalesce(i, () => (s)),S={url:e,requestId:r,method:"POST",requestSize:n,serverUrl:o,responseBody:E?he(E):void 0,responseHeaders:u},b={401:{message:`HTTP ${a}: ${d}${f}`,code:l.AUTH_ERROR},403:{message:`HTTP ${a}: ${d}${f}`,code:l.AUTH_ERROR},404:{message:`Endpoint not found: ${e}`,code:l.NOT_FOUND},413:{message:`Request too large: ${(n/1024).toFixed(2)}KB`,code:l.VALIDATION_ERROR},429:{message:`Rate limit exceeded${f}`,code:l.RATE_LIMIT},500:{message:`Server error: ${d}${f}`,code:l.COMPUTATION_ERROR},502:{message:`Service unavailable: ${d}${f}`,code:l.NETWORK_ERROR},503:{message:`Service unavailable: ${d}${f}`,code:l.NETWORK_ERROR},504:{message:`Service unavailable: ${d}${f}`,code:l.NETWORK_ERROR}}[a]||{message:`HTTP ${a}: ${d}${f}`,code:l.UNKNOWN_ERROR},k=_nullishCoalesce(Re(c), () => (b.code));throw new p(b.message,k,{statusCode:a,context:S})}function Re(t){if(t==="definition_not_cached")return l.DEFINITION_NOT_CACHED}async function H(t,e,r,n,o,s,c,i){let a=Math.round(performance.now()-s);if(!t.ok){let d=await t.text(),u=d;c&&(h(`\u274C Request [${r}] failed with HTTP ${t.status} in ${a}ms`,!0),h(` URL: ${e}`,!0),h(` Status: ${t.status} ${t.statusText}`,!0),u&&h(` Response body: ${u.substring(0,500)}${u.length>500?"...":""}`,!0));let g;try{let f=JSON.parse(u);typeof _optionalChain([f, 'optionalAccess', _6 => _6.code])=="string"&&(g=f.code)}catch (e3){}if(t.status===500)try{let f=JSON.parse(u);if(_optionalChain([f, 'optionalAccess', _7 => _7.values])&&(f.errors||f.warnings))return N(f,u.length),c&&(h(`\u26A0\uFE0F Request [${r}] completed with Grasshopper errors in ${a}ms`,!0),_optionalChain([f, 'access', _8 => _8.errors, 'optionalAccess', _9 => _9.length])>0&&h(` Errors: ${JSON.stringify(f.errors,null,2)}`,!0),_optionalChain([f, 'access', _10 => _10.warnings, 'optionalAccess', _11 => _11.length])>0&&h(` Warnings: ${JSON.stringify(f.warnings,null,2)}`,!0)),x(t,r,i,c),f;let E=typeof _optionalChain([f, 'optionalAccess', _12 => _12.message])=="string"&&f.message||typeof _optionalChain([f, 'optionalAccess', _13 => _13.Message])=="string"&&f.Message||"",S=typeof _optionalChain([f, 'optionalAccess', _14 => _14.ExceptionType])=="string"&&f.ExceptionType||"",O=_nullishCoalesce(_optionalChain([f, 'optionalAccess', _15 => _15.stackTrace]), () => (_optionalChain([f, 'optionalAccess', _16 => _16.StackTrace]))),b=Array.isArray(O)?O.join(`
|
|
2
|
-
`):O||"";E?u=`${S?`${S}: `:""}${E}${b?`
|
|
3
|
-
${b}`:""}`:_optionalChain([f, 'optionalAccess', _17 => _17.error])&&(u=typeof f.error=="string"?f.error:JSON.stringify(f.error,null,2))}catch(f){c&&h(` Failed to parse error body as JSON: ${f}`,!0)}ye(t,e,r,n,o,u,g,d)}h(`\u2705 Request [${r}] completed in ${a}ms`,c),x(t,r,i,c);try{let d=await t.text(),u=JSON.parse(d);return N(u,d.length),u}catch(d){let u=(_nullishCoalesce(t.headers.get("Content-Type"), () => (""))).toLowerCase();throw u!==""&&!u.includes("json")?new p(`Server returned a non-JSON response (Content-Type: ${u}) \u2014 check the server URL / proxy configuration`,l.INVALID_RESPONSE,{statusCode:t.status,context:{url:e,requestId:r,contentType:u},originalError:d instanceof Error?d:new Error(String(d))}):new p("Failed to parse JSON response",l.NETWORK_ERROR,{statusCode:t.status,context:{url:e,requestId:r},originalError:d instanceof Error?d:new Error(String(d))})}}var T={attempts:0,baseDelayMs:500,maxDelayMs:3e4,retryOn429:!0},M=new Set([502,503,504]),J=6e4;function j(t){return t?{attempts:_nullishCoalesce(t.attempts, () => (T.attempts)),baseDelayMs:_nullishCoalesce(t.baseDelayMs, () => (T.baseDelayMs)),maxDelayMs:_nullishCoalesce(t.maxDelayMs, () => (T.maxDelayMs)),retryOn429:_nullishCoalesce(t.retryOn429, () => (T.retryOn429))}:T}function G(t){if(!t)return null;let e=Number(t);if(Number.isFinite(e)&&e>=0)return e*1e3;let r=Date.parse(t);if(Number.isFinite(r)){let n=r-Date.now();return n>0?n:0}return null}function v(t,e){let r=e.baseDelayMs*Math.pow(2,t),n=Math.random()*e.baseDelayMs;return Math.min(r+n,e.maxDelayMs)}function Y(t,e){return new Promise((r,n)=>{if(_optionalChain([e, 'optionalAccess', _18 => _18.aborted])){n(new DOMException("Aborted","AbortError"));return}let o=setTimeout(()=>{_optionalChain([e, 'optionalAccess', _19 => _19.removeEventListener, 'call', _20 => _20("abort",s)]),r()},t),s=()=>{clearTimeout(o),n(new DOMException("Aborted","AbortError"))};_optionalChain([e, 'optionalAccess', _21 => _21.addEventListener, 'call', _22 => _22("abort",s,{once:!0})])})}function Z(t,e){let r=()=>{},n=typeof e=="number"&&e>0;if(!t&&!n)return{signal:void 0,cleanup:r};if(t&&!n)return{signal:t,cleanup:r};let o=typeof AbortSignal<"u"&&typeof AbortSignal.timeout=="function";if(!t){if(o)return{signal:AbortSignal.timeout(e),cleanup:r};let u=new AbortController,g=setTimeout(()=>u.abort(),e);return{signal:u.signal,cleanup:()=>clearTimeout(g)}}let s=new AbortController,c,i;if(o)c=AbortSignal.timeout(e);else{let u=new AbortController;i=setTimeout(()=>u.abort(),e),c=u.signal}let a=[t,c],d=function(){s.abort(this.reason)};for(let u of a){if(u.aborted){s.abort(u.reason);break}u.addEventListener("abort",d,{once:!0})}return{signal:s.signal,cleanup:()=>{i!==void 0&&clearTimeout(i);for(let u of a)u.removeEventListener("abort",d)}}}async function we(t,e,r,n){let{signal:o,cleanup:s}=Z(t.config.signal,t.config.timeoutMs),c=performance.now();try{let i=await fetch(t.fullUrl,{method:"POST",body:t.body,headers:t.headers,signal:o});if((M.has(i.status)||e.retryOn429&&i.status===429)&&r<n-1){let u=G(i.headers.get("Retry-After")),g=u!==null?Math.min(u,Math.max(e.maxDelayMs,J)):v(r,e);return await i.text().catch(()=>{}),{ok:!1,retry:!0,delayMs:g,cause:new p(`HTTP ${i.status} ${i.statusText} (will retry)`,i.status===429?l.RATE_LIMIT:l.NETWORK_ERROR,{statusCode:i.status,context:{requestId:t.requestId}})}}return{ok:!0,value:await H(i,t.fullUrl,t.requestId,t.requestSize,t.config.serverUrl,c,t.config.debug,t.config.onServerTiming)}}catch(i){if(i instanceof Error&&(i.name==="AbortError"||i.name==="TimeoutError")){if(_optionalChain([t, 'access', _23 => _23.config, 'access', _24 => _24.signal, 'optionalAccess', _25 => _25.aborted])===!0)return{ok:!1,retry:!1,cause:new p("Request aborted by caller",l.ABORTED,{context:{endpoint:t.endpoint,requestId:t.requestId,requestSize:t.requestSize},originalError:i})};let u=typeof t.config.timeoutMs=="number"&&t.config.timeoutMs>0?new p(`Request timed out after ${t.config.timeoutMs}ms`,l.TIMEOUT_ERROR,{context:{serverUrl:t.config.serverUrl,timeoutMs:t.config.timeoutMs,url:t.fullUrl,requestId:t.requestId,endpoint:t.endpoint,requestSize:t.requestSize},originalError:i}):new p(`Request aborted by the runtime (${i.name}): ${i.message}`,l.NETWORK_ERROR,{context:{serverUrl:t.config.serverUrl,url:t.fullUrl,requestId:t.requestId,endpoint:t.endpoint,requestSize:t.requestSize},originalError:i});return r<n-1?{ok:!1,retry:!0,delayMs:v(r,e),cause:u}:{ok:!1,retry:!1,cause:u}}if(i instanceof TypeError){let a=typeof window<"u"&&typeof window.document<"u",d={serverUrl:t.config.serverUrl,url:t.fullUrl,requestId:t.requestId,endpoint:t.endpoint,requestSize:t.requestSize},u=a?new p(`Request failed: ${i.message} \u2014 in a browser this usually means a CORS misconfiguration on the server (or a network failure; the browser does not distinguish them)`,l.CORS_ERROR,{context:d,originalError:i}):new p(`Network error: ${i.message}`,l.NETWORK_ERROR,{context:d,originalError:i});return r<n-1?{ok:!1,retry:!0,delayMs:v(r,e),cause:u}:{ok:!1,retry:!1,cause:u}}if(i instanceof p){let a=i.statusCode;return(i.code===l.NETWORK_ERROR&&a!==void 0&&a>=200&&a<300||a!==void 0&&(M.has(a)||e.retryOn429&&a===429))&&r<n-1?{ok:!1,retry:!0,delayMs:v(r,e),cause:i}:{ok:!1,retry:!1,cause:i}}return{ok:!1,retry:!1,cause:new p(i instanceof Error?i.message:String(i),l.UNKNOWN_ERROR,{context:{endpoint:t.endpoint,requestId:t.requestId},originalError:i instanceof Error?i:new Error(String(i))})}}finally{s()}}async function Ee(t,e,r){let n=K(),o=JSON.stringify(e),s=P(o),c=W(t,r.serverUrl),i=z(n,r),a=j(r.retry),d=a.attempts+1;if(r.debug){let g=(s/1024).toFixed(2),f=s>1e5?"\u26A0\uFE0F":"\u{1F680}";h(`${f} Starting compute request [${n}]: ${t} (${g}KB)`,!0)}let u={endpoint:t,body:o,requestSize:s,fullUrl:c,requestId:n,headers:i,config:r};for(let g=0;;g++){let f=await we(u,a,g,d);if(f.ok)return f.value;if(!f.retry)throw f.cause;r.debug&&h(`\u{1F501} Request [${n}] retrying after ${f.delayMs}ms (attempt ${g+2}/${d}): ${f.cause.message}`,!0);try{await Y(f.delayMs,r.signal)}catch (e4){throw new p("Request aborted by caller",l.ABORTED,{context:{endpoint:t,requestId:n,requestSize:s},originalError:f.cause})}}}var be="compute.rhino3d.com";function Q(t){let e=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _26 => _26.trim, 'call', _27 => _27()]), () => (""));if(!e)throw new p("serverUrl is required",l.INVALID_CONFIG,{context:{receivedServerUrl:t}});if(!/^https?:\/\//i.test(e))throw new p(`Invalid serverUrl: "${e}". Must start with "http://" or "https://". For example: "http://localhost:5000" or "https://example.com"`,l.INVALID_CONFIG,{context:{receivedServerUrl:t}});let r;try{r=new URL(e)}catch(o){throw new p(`Invalid serverUrl: "${e}". Must be a valid URL. Received error: ${o instanceof Error?o.message:String(o)}`,l.INVALID_CONFIG,{context:{receivedServerUrl:t},originalError:o instanceof Error?o:void 0})}if(r.username!==""||r.password!=="")throw new p(`Invalid serverUrl: "${e}". Must not embed credentials (user:pass@host) \u2014 fetch rejects credentialed URLs at request time. Pass the API key separately.`,l.INVALID_CONFIG,{context:{receivedServerUrl:t}});if(e.includes("?")||e.includes("#"))throw new p(`Invalid serverUrl: "${e}". Must not contain a query string or fragment \u2014 endpoint paths are appended to this URL (e.g. "\${serverUrl}/version"), and a "?" or "#" suffix would corrupt every request path.`,l.INVALID_CONFIG,{context:{receivedServerUrl:t}});if(r.hostname.toLowerCase().replace(/\.+$/,"")===be)throw new p("serverUrl must be set to your Compute server URL. The default public endpoint is not allowed.",l.INVALID_CONFIG,{context:{receivedServerUrl:t}});return e.replace(/\/+$/,"")}var R=class R{constructor(e,r){y(this,"serverUrl");y(this,"apiKey");y(this,"disposed",!1);y(this,"activeMonitors",new Set);y(this,"activeTimeouts",new Set);this.serverUrl=Q(e),this.apiKey=r}buildHeaders(){let e={"Content-Type":"application/json"};return this.apiKey&&(e.RhinoComputeKey=this.apiKey),e}fetchWithTimeout(e,r={},n=R.DEFAULT_TIMEOUT_MS){let o=new Headers(this.buildHeaders());r.headers&&new Headers(r.headers).forEach((i,a)=>{o.set(a,i)});let s={};o.forEach((i,a)=>{s[a]=i});let c={...r,headers:s};return n>0&&!c.signal&&(c.signal=AbortSignal.timeout(n)),fetch(e,c)}async isServerOnline(e=5e3){this.ensureNotDisposed();let r=`${this.serverUrl}/`;try{return(await this.fetchWithTimeout(r,{method:"GET"},e)).ok}catch(n){return m().debug("[ComputeServerStats] Fetch error:",n),!1}}async getActiveChildren(e={}){this.ensureNotDisposed();let{initialize:r=!0}=e,n=r?`${this.serverUrl}/activechildren`:`${this.serverUrl}/activechildren?initialize=false`,o=r?R.LIFECYCLE_TIMEOUT_MS:R.DEFAULT_TIMEOUT_MS;try{let s=await this.fetchWithTimeout(n,{},o);if(!s.ok)return m().warn("[ComputeServerStats] Failed to fetch active children:",s.status),null;let c=(await s.text()).trim();return/^\d+$/.test(c)?parseInt(c,10):(m().warn("[ComputeServerStats] Invalid active children response:",c),null)}catch(s){return m().warn("[ComputeServerStats] Error fetching active children:",s),null}}async getVersion(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/version`);if(!e.ok)return m().warn("[ComputeServerStats] Failed to fetch version:",e.status),null;let r=await e.text();try{let n=JSON.parse(r);return{rhino:_nullishCoalesce(n.rhino, () => ("")),compute:_nullishCoalesce(n.compute, () => ("")),git_sha:_nullishCoalesce(n.git_sha, () => (null))}}catch (e5){return{rhino:r,compute:"",git_sha:null}}}catch(e){return m().warn("[ComputeServerStats] Error fetching version:",e),null}}async getInstalledPlugins(e="gh"){this.ensureNotDisposed();try{let r=await this.fetchWithTimeout(`${this.serverUrl}/plugins/${e}/installed`);if(!r.ok)return m().warn(`[ComputeServerStats] Failed to fetch ${e} plugins:`,r.status),null;let n=await r.text();try{let o=JSON.parse(n);return o&&typeof o=="object"?o:null}catch (e6){return null}}catch(r){return m().warn(`[ComputeServerStats] Error fetching ${e} plugins:`,r),null}}async getServerStats(){if(this.ensureNotDisposed(),!await this.isServerOnline())return{isOnline:!1};let[r,n]=await Promise.all([this.getVersion(),this.getActiveChildren({initialize:!1})]);return{isOnline:!0,...r&&{version:r},...n!==null&&{activeChildren:n}}}async purgeCache(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/cache/purge`,{method:"POST"});if(!e.ok)return m().warn("[ComputeServerStats] Failed to purge cache:",e.status),null;let r=await e.text();try{let n=JSON.parse(r);return typeof n.purged=="number"?n.purged:null}catch (e7){return null}}catch(e){return m().warn("[ComputeServerStats] Error purging cache:",e),null}}async purgeAllChildren(){this.ensureNotDisposed();let e=await this.getActiveChildren({initialize:!1});if(e===null)return m().warn("[ComputeServerStats] purgeAllChildren: could not read child count"),null;if(e===0)return{totalPurged:0,calls:0,children:0,confident:!0};let r=e*2,n=0;for(let o=0;o<r;o++){let s=await this.purgeCache();s!==null&&(n+=s)}return{totalPurged:n,calls:r,children:e,confident:e===1}}async getServerTime(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/servertime`);if(!e.ok)return m().warn("[ComputeServerStats] Failed to fetch server time:",e.status),null;let r=(await e.text()).trim().replace(/^"|"$/g,""),n=new Date(r);return isNaN(n.getTime())?null:n}catch(e){return m().warn("[ComputeServerStats] Error fetching server time:",e),null}}async getIdleSpan(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/idlespan`);if(!e.ok)return m().warn("[ComputeServerStats] Failed to fetch idle span:",e.status),null;let r=parseFloat((await e.text()).trim());return isNaN(r)?null:r}catch(e){return m().warn("[ComputeServerStats] Error fetching idle span:",e),null}}async launchChildren(){return this.postJson("/launch-children")}async launchChild(e){let r=e===void 0?"/launch-child":`/launch-child?port=${e}`;return this.postJson(r)}async shutdownChildren(e){let r=e===void 0?"/shutdown-children":`/shutdown-children?port=${e}`;return this.postJson(r)}async recycleChildren(e){let r=e===void 0?"/recycle-children":`/recycle-children?port=${e}`;return this.postJson(r)}async postJson(e){this.ensureNotDisposed();try{let r=await this.fetchWithTimeout(`${this.serverUrl}${e}`,{method:"POST"},R.LIFECYCLE_TIMEOUT_MS);if(!r.ok)return m().warn(`[ComputeServerStats] POST ${e} failed:`,r.status),null;let n=await r.text();try{return JSON.parse(n)}catch (e8){return null}}catch(r){return m().warn(`[ComputeServerStats] Error on POST ${e}:`,r),null}}monitor(e,r=5e3){if(this.ensureNotDisposed(),!Number.isFinite(r)||r<R.MIN_MONITOR_INTERVAL_MS)throw new RangeError(`monitor() intervalMs must be a finite number >= ${R.MIN_MONITOR_INTERVAL_MS}ms, got ${r}. Sub-${R.MIN_MONITOR_INTERVAL_MS}ms polling would hot-loop the server.`);let n=!0,o=null;m().info(`\u{1F504} Starting server stats monitoring every ${r}ms`);let s=async()=>{if(o!==null&&(this.activeTimeouts.delete(o),o=null),!(!n||this.disposed)){try{let i=await this.getServerStats();if(!n||this.disposed)return;try{e(i)}catch(a){m().error("[ComputeServerStats] Monitor callback threw:",a)}}catch(i){!n||this.disposed?m().debug("[ComputeServerStats] Monitor poll cancelled during shutdown:",i):m().error("[ComputeServerStats] Failed to fetch stats during monitor:",i)}n&&!this.disposed&&(o=setTimeout(()=>{s()},r),this.activeTimeouts.add(o))}},c=()=>{n=!1,o!==null&&(clearTimeout(o),this.activeTimeouts.delete(o),o=null),this.activeMonitors.delete(c)};return this.activeMonitors.add(c),s(),c}async dispose(){if(!this.disposed){this.disposed=!0;for(let e of this.activeMonitors)e();this.activeMonitors.clear();for(let e of this.activeTimeouts)clearTimeout(e);this.activeTimeouts.clear()}}ensureNotDisposed(){if(this.disposed)throw new p("ComputeServerStats has been disposed and cannot be used",l.INVALID_STATE,{context:{disposed:this.disposed}})}};y(R,"DEFAULT_TIMEOUT_MS",5e3),y(R,"LIFECYCLE_TIMEOUT_MS",6e4),y(R,"MIN_MONITOR_INTERVAL_MS",100);var A=R;function X(t,e={}){let{preserveSpaces:r=!1}=e,n=r?/[-_]+(.)?/g:/[\s\-_]+(.)?/g,o=t.trim().replace(n,(s,c)=>c?c.toUpperCase():"");return o=o.replace(/^[A-Z]+(?=[A-Z][a-z]|[^A-Za-z]|$)/,s=>s.toLowerCase()),o.charAt(0).toLowerCase()+o.slice(1)}function Te(t){if(t===null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function F(t,e={}){if(!t||typeof t!="object")return t;if(Array.isArray(t))return e.deep?t.map(n=>F(n,e)):t;if(!Te(t))return t;let r={};for(let n of Object.keys(t)){let o=X(n,{preserveSpaces:e.preserveSpaces});Object.prototype.hasOwnProperty.call(r,o)&&m().warn(`camelcaseKeys: key '${n}' collides with an earlier key on '${o}' \u2014 the earlier value is overwritten (last key wins).`);let s=t[n];r[o]=e.deep?F(s,e):s}return r}function w(t,e){if(!t||typeof t!="object")return;let r=t;if(te(r,e))return r[e];let n=re(r).get(e.toLowerCase());return n===void 0?void 0:r[n]}var te=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);function yt(t,e){if(!t||typeof t!="object")return!1;let r=t;return te(r,e)?!0:re(r).has(e.toLowerCase())}var ee=new WeakMap;function re(t){let e=Object.keys(t),r=ee.get(t);if(r&&r.keyCount===e.length)return r.map;let n=new Map;for(let o of e){let s=o.toLowerCase();n.has(s)||n.set(s,o)}return ee.set(t,{keyCount:e.length,map:n}),n}var ve=async(t,e=null)=>{try{return await ne(t,e)}catch(r){throw new p("Failed to extract files from compute response",l.INVALID_STATE,{context:{originalError:r instanceof Error?r.message:String(r)},originalError:r instanceof Error?r:void 0})}},Se= exports.u =async(t,e,r=null)=>{if(typeof document>"u"||typeof Blob>"u")throw new p("File download functionality is only available in browser environments. This function requires the DOM API (document, Blob).",l.BROWSER_ONLY,{context:{environment:typeof window<"u"?"browser (SSR)":"Node.js",documentAvailable:typeof document<"u",blobAvailable:typeof Blob<"u"}});try{let n=await ne(t,r);await Ae(n,e)}catch(n){throw n instanceof p?n:new p("Failed to download files from compute response",l.INVALID_STATE,{context:{originalError:n instanceof Error?n.message:String(n)},originalError:n instanceof Error?n:void 0})}},$=t=>t.replace(/\\/g,"/").split("/").map(e=>e.trim()).filter(e=>e!==""&&e!=="."&&e!==".."&&!/^[a-zA-Z]:$/.test(e)).join("/"),Oe=t=>t===!0||typeof t=="string"&&t.trim().toLowerCase()==="true",Ce=t=>{let e=[];return t.forEach(r=>{let n=_nullishCoalesce(w(r,"fileName"), () => ("")),o=_nullishCoalesce(w(r,"fileType"), () => ("")),s=$(`${n}${o}`);if(s===""){m().warn(`Skipping file with unusable name "${n}${o}": no safe archive path remains after sanitization.`);return}let c=w(r,"subFolder"),i=c?$(c):"",a=i!==""?`${i}/${s}`:s,d=w(r,"data");if(typeof d!="string"||d===""){m().warn(`Skipping file "${a}": item carries no usable data.`);return}if(Oe(w(r,"isBase64Encoded")))try{e.push({fileName:s,content:_(d),path:a})}catch(u){m().warn(`Skipping file "${a}": base64 decode failed.`,u)}else e.push({fileName:s,content:d,path:a})}),e},Ie=3e4,Ne=async t=>(await Promise.all(t.map(async r=>{try{let n=typeof AbortSignal<"u"&&typeof AbortSignal.timeout=="function"?AbortSignal.timeout(Ie):void 0,o=await fetch(r.filePath,{signal:n});if(!o.ok)return m().warn(`Failed to fetch additional file from URL: ${r.filePath}`),null;let s=await o.arrayBuffer(),c=$(r.fileName);if(c==="")return m().warn(`Skipping fetched file with unusable name: ${r.fileName}`),null;let i=r.subFolder?$(r.subFolder):"";return{fileName:c,content:new Uint8Array(s),path:i!==""?`${i}/${c}`:c}}catch(n){return m().error(`Error fetching additional file from URL: ${r.filePath}`,n),null}}))).filter(r=>r!==null),ne=async(t,e)=>{let r=Ce(t);if(e){let o=Array.isArray(e)?e:[e];r.push(...await Ne(o))}let n=new Set;return r.map(o=>{let s=oe(o.path,n);return n.add(s),s===o.path?o:(m().warn(`Duplicate archive path "${o.path}" \u2014 storing as "${s}".`),{...o,path:s,fileName:s.slice(s.lastIndexOf("/")+1)})})};async function Ae(t,e){let{zip:r,strToU8:n}=await Promise.resolve().then(() => _interopRequireWildcard(require("fflate"))),o={},s=new Set;t.forEach(a=>{let d=oe(a.path,s);s.add(d),d!==a.path&&m().warn(`Duplicate archive path "${a.path}" \u2014 storing as "${d}".`),o[d]=typeof a.content=="string"?n(a.content):a.content});let c=await new Promise((a,d)=>{r(o,{level:6},(u,g)=>u?d(u):a(g))}),i=new Blob([c],{type:"application/zip"});$e(i,`${e}.zip`)}function oe(t,e){if(!e.has(t))return t;let r=t.lastIndexOf("/"),n=t.lastIndexOf("."),o=n>r?n:t.length,s=t.slice(0,o),c=t.slice(o);for(let i=2;;i++){let a=`${s}-${i}${c}`;if(!e.has(a))return a}}function $e(t,e){if(typeof document>"u")throw new p("saveFile requires a browser environment with DOM API access.",l.BROWSER_ONLY,{context:{function:"saveFile",requiredAPI:"document"}});let r=URL.createObjectURL(t),n=document.createElement("a");n.href=r,n.download=e,document.body.appendChild(n),n.click(),n.remove(),setTimeout(()=>URL.revokeObjectURL(r),1e4)}exports.a = y; exports.b = l; exports.c = p; exports.d = De; exports.e = Me; exports.f = _; exports.g = de; exports.h = m; exports.i = B; exports.j = fe; exports.k = N; exports.l = ge; exports.m = Ee; exports.n = Q; exports.o = A; exports.p = X; exports.q = F; exports.r = w; exports.s = yt; exports.t = ve; exports.u = Se;
|
|
4
|
-
//# sourceMappingURL=chunk-LLUNR66G.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/selva/selva/packages/compute/dist/chunk-LLUNR66G.cjs","../src/core/errors.ts","../src/core/compute-fetch/response.ts","../src/core/compute-fetch/retry.ts"],"names":["ErrorCodes","RhinoComputeError","_RhinoComputeError","message","code","options","__publicField","inputName","expectedType","context"],"mappings":"AAAA,u8BAAI,EAAE,CAAC,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,EAAE,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CCAhK,IAAMA,CAAAA,CAAa,CACzB,aAAA,CAAe,eAAA,CACf,UAAA,CAAY,YAAA,CACZ,gBAAA,CAAkB,kBAAA,CAClB,iBAAA,CAAmB,mBAAA,CACnB,aAAA,CAAe,eAAA,CACf,UAAA,CAAY,YAAA,CAEZ,SAAA,CAAW,WAAA,CAEX,UAAA,CAAY,YAAA,CAOZ,gBAAA,CAAkB,kBAAA,CAClB,aAAA,CAAe,eAAA,CACf,aAAA,CAAe,eAAA,CACf,aAAA,CAAe,eAAA,CACf,cAAA,CAAgB,gBAAA,CAChB,YAAA,CAAc,cAAA,CACd,iBAAA,CAAmB,mBAAA,CACnB,cAAA,CAAgB,gBAAA,CAEhB,iBAAA,CAAmB,mBAAA,CAEnB,UAAA,CAAY,YAAA,CAEZ,OAAA,CAAS,SAAA,CAOT,UAAA,CAAY,YAAA,CAMZ,aAAA,CAAe,eAAA,CAQf,qBAAA,CAAuB,uBACxB,CAAA,CASaC,CAAAA,aAAN,MAAMC,EAAAA,QAA0B,KAAM,CAM5C,WAAA,CACCC,CAAAA,CACAC,CAAAA,CAAkBJ,CAAAA,CAAW,aAAA,CAC7BK,CAAAA,CACC,CACD,KAAA,CAAMF,CAAO,CAAA,CAVdG,CAAAA,CAAA,IAAA,CAAgB,MAAA,CAAA,CAChBA,CAAAA,CAAA,IAAA,CAAgB,YAAA,CAAA,CAChBA,CAAAA,CAAA,IAAA,CAAgB,SAAA,CAAA,CAChBA,CAAAA,CAAA,IAAA,CAAgB,eAAA,CAAA,CAQf,IAAA,CAAK,IAAA,CAAO,mBAAA,CACZ,IAAA,CAAK,IAAA,CAAOF,CAAAA,CACZ,IAAA,CAAK,UAAA,iBAAaC,CAAAA,6BAAS,YAAA,CAC3B,IAAA,CAAK,OAAA,iBAAUA,CAAAA,6BAAS,SAAA,CACxB,IAAA,CAAK,aAAA,iBAAgBA,CAAAA,6BAAS,eAAA,iBAC1BA,CAAAA,6BAAS,eAAA,EAAA,CACX,IAAA,CAA6B,KAAA,CAAQA,CAAAA,CAAQ,aAAA,CAEhD,CAKA,OAAO,aAAA,CACNE,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACC,CACD,OAAO,IAAIP,CAAAA,CACV,CAAA,OAAA,EAAUK,CAAS,CAAA,uBAAA,EAA0BC,CAAAA,CAAe,CAAA,WAAA,EAAcA,CAAY,CAAA,CAAA,CAAA,CAAM,EAAE,CAAA,CAAA;ACwGzC;ACvJjD","file":"/home/runner/work/selva/selva/packages/compute/dist/chunk-LLUNR66G.cjs","sourcesContent":[null,"export const ErrorCodes = {\n\tNETWORK_ERROR: 'NETWORK_ERROR',\n\tAUTH_ERROR: 'AUTH_ERROR',\n\tVALIDATION_ERROR: 'VALIDATION_ERROR',\n\tCOMPUTATION_ERROR: 'COMPUTATION_ERROR',\n\tTIMEOUT_ERROR: 'TIMEOUT_ERROR',\n\tCORS_ERROR: 'CORS_ERROR',\n\t/** HTTP 404 — the endpoint path does not exist on the server (usually a typo'd route or wrong server). Never retried. */\n\tNOT_FOUND: 'NOT_FOUND',\n\t/** HTTP 429 — the server is rate-limiting requests. Retried by default (honors `Retry-After`); see `RetryPolicy.retryOn429`. */\n\tRATE_LIMIT: 'RATE_LIMIT',\n\t/**\n\t * The server answered 2xx but the body is deterministically not JSON (the\n\t * response declared a non-JSON `Content-Type`, e.g. an HTML captive-portal or\n\t * proxy login page, or a misconfigured endpoint). Never retried — refetching\n\t * returns the same page.\n\t */\n\tINVALID_RESPONSE: 'INVALID_RESPONSE',\n\tUNKNOWN_ERROR: 'UNKNOWN_ERROR',\n\tINVALID_STATE: 'INVALID_STATE',\n\tINVALID_INPUT: 'INVALID_INPUT',\n\tINVALID_CONFIG: 'INVALID_CONFIG',\n\tBROWSER_ONLY: 'BROWSER_ONLY',\n\tENVIRONMENT_ERROR: 'ENVIRONMENT_ERROR',\n\tENCODING_ERROR: 'ENCODING_ERROR',\n\t/** An input's `default` had a shape the normalizer didn't recognize (no innerTree key). */\n\tMALFORMED_DEFAULT: 'MALFORMED_DEFAULT',\n\t/** Scheduler latest-wins: this call was replaced by a newer one. */\n\tSUPERSEDED: 'SUPERSEDED',\n\t/** Scheduler / caller-supplied AbortSignal: this call was aborted. */\n\tABORTED: 'ABORTED',\n\t/**\n\t * Scheduler backpressure: the queue was already at `maxQueueDepth` when this\n\t * call arrived, so it was shed immediately rather than queued. Retryable — the\n\t * caller (or an HTTP layer, as 503 + Retry-After) should back off and retry.\n\t * The error `context` carries `{ queueDepth, maxQueueDepth }`.\n\t */\n\tQUEUE_FULL: 'QUEUE_FULL',\n\t/**\n\t * Scheduler backpressure: this call sat queued longer than `queueWaitMs`\n\t * without starting, so it was shed before wasting compute on a stale request.\n\t * Retryable. The error `context` carries `{ waitedMs, queueWaitMs }`.\n\t */\n\tQUEUE_TIMEOUT: 'QUEUE_TIMEOUT',\n\t/**\n\t * A solve referenced a definition by `pointer` (server-side cache key), but the\n\t * server no longer holds that definition (evicted / GC'd / a different child in\n\t * the pool / server restarted). The caller should retry with the full\n\t * definition. Surfaced when the server tags its error body with\n\t * `code: \"definition_not_cached\"`, so it survives production message-scrubbing.\n\t */\n\tDEFINITION_NOT_CACHED: 'DEFINITION_NOT_CACHED'\n} as const;\n\nexport type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];\n\n/**\n * Simplified error for Rhino Compute operations\n *\n * @public Use this for error handling with error codes and context.\n */\nexport class RhinoComputeError extends Error {\n\tpublic readonly code: ErrorCode;\n\tpublic readonly statusCode?: number;\n\tpublic readonly context?: Record<string, unknown>;\n\tpublic readonly originalError?: Error;\n\n\tconstructor(\n\t\tmessage: string,\n\t\tcode: ErrorCode = ErrorCodes.UNKNOWN_ERROR,\n\t\toptions?: { statusCode?: number; context?: Record<string, unknown>; originalError?: Error }\n\t) {\n\t\tsuper(message);\n\t\tthis.name = 'RhinoComputeError';\n\t\tthis.code = code;\n\t\tthis.statusCode = options?.statusCode;\n\t\tthis.context = options?.context;\n\t\tthis.originalError = options?.originalError;\n\t\tif (options?.originalError) {\n\t\t\t(this as { cause?: unknown }).cause = options.originalError;\n\t\t}\n\t}\n\n\t/**\n\t * Create an error for missing/empty values\n\t */\n\tstatic missingValues(\n\t\tinputName: string,\n\t\texpectedType?: string,\n\t\tcontext?: Record<string, unknown>\n\t) {\n\t\treturn new RhinoComputeError(\n\t\t\t`Input \"${inputName}\" has no values defined${expectedType ? ` (expected ${expectedType})` : ''}`,\n\t\t\tErrorCodes.INVALID_INPUT,\n\t\t\t{ context: { inputName, expectedType, ...context } }\n\t\t);\n\t}\n\n\t/**\n\t * Create an error for unknown parameter type\n\t */\n\tstatic unknownParamType(\n\t\tparamType: string,\n\t\tparamName?: string,\n\t\tcontext?: Record<string, unknown>\n\t) {\n\t\treturn new RhinoComputeError(`Unknown paramType: ${paramType}`, ErrorCodes.VALIDATION_ERROR, {\n\t\t\tcontext: { receivedParamType: paramType, paramName, ...context }\n\t\t});\n\t}\n}\n","import { RhinoComputeError, ErrorCodes, type ErrorCode } from '../errors';\nimport { log } from './log';\nimport { fireServerTiming } from './server-timing';\nimport { setResponseWireSize } from './wire-size';\n\nimport type { ServerTiming } from '../types';\n\n/** Upper bound for the raw server body stored on error `context.responseBody`. */\nconst MAX_CONTEXT_BODY_CHARS = 4096;\n\n/** Truncate a server body for storage on error context — bounded, with an honest marker. */\nfunction truncateBody(body: string): string {\n\tif (body.length <= MAX_CONTEXT_BODY_CHARS) return body;\n\treturn `${body.slice(0, MAX_CONTEXT_BODY_CHARS)}… [truncated ${body.length - MAX_CONTEXT_BODY_CHARS} chars]`;\n}\n\nexport function throwHttpError(\n\tresponse: Response,\n\tfullUrl: string,\n\trequestId: string,\n\trequestSize: number,\n\tserverUrl: string,\n\terrorBody: string,\n\tserverCode?: string,\n\trawBody?: string\n): never {\n\tconst { status, statusText } = response;\n\n\tconst responseHeaders: Record<string, string> = {};\n\tresponse.headers.forEach((value, key) => {\n\t\tresponseHeaders[key] = value;\n\t});\n\n\tconst trimmed = errorBody.trim();\n\tconst bodyHint = trimmed ? ` — ${trimmed.slice(0, 200)}${trimmed.length > 200 ? '…' : ''}` : '';\n\n\t// context.responseBody holds the RAW server body (what actually came over the\n\t// wire), bounded to MAX_CONTEXT_BODY_CHARS so a huge body isn't pinned for the\n\t// error's lifetime. `errorBody` may have been rewritten into a synthesized\n\t// message (500 exception shape) — that goes in the message, not the context.\n\tconst storedBody = rawBody ?? errorBody;\n\tconst context = {\n\t\turl: fullUrl,\n\t\trequestId,\n\t\tmethod: 'POST',\n\t\trequestSize,\n\t\tserverUrl,\n\t\tresponseBody: storedBody ? truncateBody(storedBody) : undefined,\n\t\tresponseHeaders\n\t};\n\n\tconst errorMap: Record<number, { message: string; code: ErrorCode }> = {\n\t\t401: { message: `HTTP ${status}: ${statusText}${bodyHint}`, code: ErrorCodes.AUTH_ERROR },\n\t\t403: { message: `HTTP ${status}: ${statusText}${bodyHint}`, code: ErrorCodes.AUTH_ERROR },\n\t\t404: { message: `Endpoint not found: ${fullUrl}`, code: ErrorCodes.NOT_FOUND },\n\t\t413: {\n\t\t\tmessage: `Request too large: ${(requestSize / 1024).toFixed(2)}KB`,\n\t\t\tcode: ErrorCodes.VALIDATION_ERROR\n\t\t},\n\t\t429: { message: `Rate limit exceeded${bodyHint}`, code: ErrorCodes.RATE_LIMIT },\n\t\t500: { message: `Server error: ${statusText}${bodyHint}`, code: ErrorCodes.COMPUTATION_ERROR },\n\t\t502: {\n\t\t\tmessage: `Service unavailable: ${statusText}${bodyHint}`,\n\t\t\tcode: ErrorCodes.NETWORK_ERROR\n\t\t},\n\t\t503: {\n\t\t\tmessage: `Service unavailable: ${statusText}${bodyHint}`,\n\t\t\tcode: ErrorCodes.NETWORK_ERROR\n\t\t},\n\t\t504: {\n\t\t\tmessage: `Service unavailable: ${statusText}${bodyHint}`,\n\t\t\tcode: ErrorCodes.NETWORK_ERROR\n\t\t}\n\t};\n\n\tconst error = errorMap[status] || {\n\t\tmessage: `HTTP ${status}: ${statusText}${bodyHint}`,\n\t\tcode: ErrorCodes.UNKNOWN_ERROR\n\t};\n\n\t// A machine code in the server's error body (e.g. \"definition_not_cached\")\n\t// outranks the status-based mapping: it's stable across the server's\n\t// production message-scrubbing, where the human message is replaced with a\n\t// generic string. Keep the status-derived message for context.\n\tconst code = mapServerErrorCode(serverCode) ?? error.code;\n\n\tthrow new RhinoComputeError(error.message, code, { statusCode: status, context });\n}\n\n/**\n * Map a server-supplied error code (from the JSON error body's `code` field) to\n * one of our {@link ErrorCodes}. Returns `undefined` for an absent or unknown\n * code so the caller falls back to its status-based mapping.\n */\nexport function mapServerErrorCode(serverCode?: string): ErrorCode | undefined {\n\tswitch (serverCode) {\n\t\tcase 'definition_not_cached':\n\t\t\treturn ErrorCodes.DEFINITION_NOT_CACHED;\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\nexport async function handleResponse(\n\tresponse: Response,\n\tfullUrl: string,\n\trequestId: string,\n\trequestSize: number,\n\tserverUrl: string,\n\tstartTime: number,\n\tdebug?: boolean,\n\tonServerTiming?: (timing: ServerTiming, requestId: string) => void\n): Promise<any> {\n\tconst responseTime = Math.round(performance.now() - startTime);\n\n\tif (!response.ok) {\n\t\t// Read body once and reuse. `rawBody` stays what came over the wire (stored\n\t\t// on error context); `errorBody` may be rewritten into a friendlier message.\n\t\tconst rawBody = await response.text();\n\t\tlet errorBody = rawBody;\n\n\t\t// Enhanced logging for errors\n\t\tif (debug) {\n\t\t\tlog(\n\t\t\t\t`❌ Request [${requestId}] failed with HTTP ${response.status} in ${responseTime}ms`,\n\t\t\t\ttrue\n\t\t\t);\n\t\t\tlog(` URL: ${fullUrl}`, true);\n\t\t\tlog(` Status: ${response.status} ${response.statusText}`, true);\n\t\t\tif (errorBody) {\n\t\t\t\tlog(\n\t\t\t\t\t` Response body: ${errorBody.substring(0, 500)}${errorBody.length > 500 ? '...' : ''}`,\n\t\t\t\t\ttrue\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// A machine-readable code the server may tag onto its error body (e.g.\n\t\t// \"definition_not_cached\"). Unlike the human `message`, it isn't scrubbed in\n\t\t// the server's production (non-debug) mode, so it's the reliable signal for\n\t\t// classifying the error (see throwHttpError → mapServerErrorCode). It can\n\t\t// ride any error status, not just 500, so read it here.\n\t\tlet serverCode: string | undefined;\n\n\t\ttry {\n\t\t\tconst parsedForCode = JSON.parse(errorBody);\n\t\t\tif (typeof parsedForCode?.code === 'string') serverCode = parsedForCode.code;\n\t\t} catch {\n\t\t\t// Non-JSON body — nothing to extract.\n\t\t}\n\n\t\t// Check if it's a valid compute response with errors/warnings\n\t\tif (response.status === 500) {\n\t\t\ttry {\n\t\t\t\tconst parsed = JSON.parse(errorBody);\n\t\t\t\t// If it has values, it's a partial success with errors\n\t\t\t\tif (parsed?.values && (parsed.errors || parsed.warnings)) {\n\t\t\t\t\tsetResponseWireSize(parsed, errorBody.length);\n\t\t\t\t\tif (debug) {\n\t\t\t\t\t\tlog(\n\t\t\t\t\t\t\t`⚠️ Request [${requestId}] completed with Grasshopper errors in ${responseTime}ms`,\n\t\t\t\t\t\t\ttrue\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (parsed.errors?.length > 0) {\n\t\t\t\t\t\t\tlog(` Errors: ${JSON.stringify(parsed.errors, null, 2)}`, true);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (parsed.warnings?.length > 0) {\n\t\t\t\t\t\t\tlog(` Warnings: ${JSON.stringify(parsed.warnings, null, 2)}`, true);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfireServerTiming(response, requestId, onServerTiming, debug);\n\t\t\t\t\treturn parsed;\n\t\t\t\t}\n\n\t\t\t\t// Raw server-side exception. The Compute8 server's exception handler\n\t\t\t\t// (compute.geometry Startup.cs) emits:\n\t\t\t\t// { error: \"Internal Server Error\", message: \"<category>: <detail>\",\n\t\t\t\t// stackTrace?: string[] } // stackTrace only when Config.Debug\n\t\t\t\t// The actionable part is `message` — surface it, with the optional\n\t\t\t\t// stack appended for debugging. We prefer `message`/`error` (current\n\t\t\t\t// server) and keep `Message`/`ExceptionType`/`StackTrace` (old\n\t\t\t\t// PascalCase .NET shape) as a back-compat fallback so an older server\n\t\t\t\t// still produces a useful message.\n\t\t\t\tconst serverMessage =\n\t\t\t\t\t(typeof parsed?.message === 'string' && parsed.message) ||\n\t\t\t\t\t(typeof parsed?.Message === 'string' && parsed.Message) ||\n\t\t\t\t\t'';\n\t\t\t\tconst exceptionType =\n\t\t\t\t\t(typeof parsed?.ExceptionType === 'string' && parsed.ExceptionType) || '';\n\t\t\t\tconst stack = parsed?.stackTrace ?? parsed?.StackTrace;\n\t\t\t\tconst stackStr = Array.isArray(stack) ? stack.join('\\n') : stack || '';\n\n\t\t\t\tif (serverMessage) {\n\t\t\t\t\t// Don't repeat the generic \"Internal Server Error\" label when the\n\t\t\t\t\t// message already carries the real detail.\n\t\t\t\t\tconst prefix = exceptionType ? `${exceptionType}: ` : '';\n\t\t\t\t\terrorBody = `${prefix}${serverMessage}${stackStr ? `\\n${stackStr}` : ''}`;\n\t\t\t\t} else if (parsed?.error) {\n\t\t\t\t\terrorBody =\n\t\t\t\t\t\ttypeof parsed.error === 'string' ? parsed.error : JSON.stringify(parsed.error, null, 2);\n\t\t\t\t}\n\t\t\t} catch (e) {\n\t\t\t\tif (debug) {\n\t\t\t\t\tlog(` Failed to parse error body as JSON: ${e}`, true);\n\t\t\t\t}\n\t\t\t\t// Not valid JSON, proceed with HTTP error\n\t\t\t}\n\t\t}\n\n\t\tthrowHttpError(\n\t\t\tresponse,\n\t\t\tfullUrl,\n\t\t\trequestId,\n\t\t\trequestSize,\n\t\t\tserverUrl,\n\t\t\terrorBody,\n\t\t\tserverCode,\n\t\t\trawBody\n\t\t);\n\t}\n\n\tlog(`✅ Request [${requestId}] completed in ${responseTime}ms`, debug);\n\n\tfireServerTiming(response, requestId, onServerTiming, debug);\n\n\ttry {\n\t\t// text-then-parse (what `response.json()` does internally) so the body's\n\t\t// wire size rides along with the parsed object — downstream byte-budgeted\n\t\t// caches read it instead of re-serializing a potentially huge tree.\n\t\tconst rawBody = await response.text();\n\t\tconst parsed = JSON.parse(rawBody);\n\t\tsetResponseWireSize(parsed, rawBody.length);\n\t\treturn parsed;\n\t} catch (error) {\n\t\t// Classify by the declared Content-Type (issue 87). A 2xx that DECLARES a\n\t\t// non-JSON body (HTML from a captive portal, a reverse-proxy login page, a\n\t\t// misconfigured endpoint) is deterministic — refetching returns the same\n\t\t// page — so fail immediately with INVALID_RESPONSE (never retried). A body\n\t\t// that fails to parse under a JSON (or absent) Content-Type means the\n\t\t// stream was likely cut mid-body — as transient as any network error — and\n\t\t// keeps the retryable NETWORK_ERROR classification.\n\t\tconst contentType = (response.headers.get('Content-Type') ?? '').toLowerCase();\n\t\tconst declaredNonJson = contentType !== '' && !contentType.includes('json');\n\t\tif (declaredNonJson) {\n\t\t\tthrow new RhinoComputeError(\n\t\t\t\t`Server returned a non-JSON response (Content-Type: ${contentType}) — check the server URL / proxy configuration`,\n\t\t\t\tErrorCodes.INVALID_RESPONSE,\n\t\t\t\t{\n\t\t\t\t\tstatusCode: response.status,\n\t\t\t\t\tcontext: { url: fullUrl, requestId, contentType },\n\t\t\t\t\toriginalError: error instanceof Error ? error : new Error(String(error))\n\t\t\t\t}\n\t\t\t);\n\t\t}\n\t\tthrow new RhinoComputeError('Failed to parse JSON response', ErrorCodes.NETWORK_ERROR, {\n\t\t\tstatusCode: response.status,\n\t\t\tcontext: {\n\t\t\t\turl: fullUrl,\n\t\t\t\trequestId\n\t\t\t},\n\t\t\toriginalError: error instanceof Error ? error : new Error(String(error))\n\t\t});\n\t}\n}\n","import type { RetryPolicy } from '../types';\n\nconst DEFAULT_RETRY: Required<RetryPolicy> = {\n\tattempts: 0,\n\tbaseDelayMs: 500,\n\tmaxDelayMs: 30_000,\n\tretryOn429: true\n};\n\nexport const RETRYABLE_STATUS = new Set([502, 503, 504]);\n\n/**\n * Absolute ceiling for a server-supplied `Retry-After` wait. The server's\n * stated window wins over `retryPolicy.maxDelayMs` (retrying earlier all but\n * guarantees another 429), but a bad/hostile header must not park the client\n * for minutes — anything above this cap is clamped.\n */\nexport const RETRY_AFTER_CAP_MS = 60_000;\n\nexport function resolveRetryPolicy(policy: RetryPolicy | undefined): Required<RetryPolicy> {\n\tif (!policy) return DEFAULT_RETRY;\n\treturn {\n\t\tattempts: policy.attempts ?? DEFAULT_RETRY.attempts,\n\t\tbaseDelayMs: policy.baseDelayMs ?? DEFAULT_RETRY.baseDelayMs,\n\t\tmaxDelayMs: policy.maxDelayMs ?? DEFAULT_RETRY.maxDelayMs,\n\t\tretryOn429: policy.retryOn429 ?? DEFAULT_RETRY.retryOn429\n\t};\n}\n\n/**\n * Parse a Retry-After header value (seconds-int or HTTP-date) into ms.\n * Returns null if the header is missing or unparseable.\n */\nexport function parseRetryAfter(headerValue: string | null): number | null {\n\tif (!headerValue) return null;\n\tconst seconds = Number(headerValue);\n\tif (Number.isFinite(seconds) && seconds >= 0) return seconds * 1000;\n\tconst dateMs = Date.parse(headerValue);\n\tif (Number.isFinite(dateMs)) {\n\t\tconst delta = dateMs - Date.now();\n\t\treturn delta > 0 ? delta : 0;\n\t}\n\treturn null;\n}\n\nexport function backoffDelay(attempt: number, policy: Required<RetryPolicy>): number {\n\tconst exponential = policy.baseDelayMs * Math.pow(2, attempt);\n\tconst jitter = Math.random() * policy.baseDelayMs;\n\treturn Math.min(exponential + jitter, policy.maxDelayMs);\n}\n\nexport function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(new DOMException('Aborted', 'AbortError'));\n\t\t\treturn;\n\t\t}\n\t\tconst id = setTimeout(() => {\n\t\t\tsignal?.removeEventListener('abort', onAbort);\n\t\t\tresolve();\n\t\t}, ms);\n\t\tconst onAbort = () => {\n\t\t\tclearTimeout(id);\n\t\t\treject(new DOMException('Aborted', 'AbortError'));\n\t\t};\n\t\tsignal?.addEventListener('abort', onAbort, { once: true });\n\t});\n}\n"]}
|
package/dist/chunk-XT3XWDDV.js
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
var ae=Object.defineProperty;var ue=(t,e,r)=>e in t?ae(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var y=(t,e,r)=>ue(t,typeof e!="symbol"?e+"":e,r);var l={NETWORK_ERROR:"NETWORK_ERROR",AUTH_ERROR:"AUTH_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",COMPUTATION_ERROR:"COMPUTATION_ERROR",TIMEOUT_ERROR:"TIMEOUT_ERROR",CORS_ERROR:"CORS_ERROR",NOT_FOUND:"NOT_FOUND",RATE_LIMIT:"RATE_LIMIT",INVALID_RESPONSE:"INVALID_RESPONSE",UNKNOWN_ERROR:"UNKNOWN_ERROR",INVALID_STATE:"INVALID_STATE",INVALID_INPUT:"INVALID_INPUT",INVALID_CONFIG:"INVALID_CONFIG",BROWSER_ONLY:"BROWSER_ONLY",ENVIRONMENT_ERROR:"ENVIRONMENT_ERROR",ENCODING_ERROR:"ENCODING_ERROR",MALFORMED_DEFAULT:"MALFORMED_DEFAULT",SUPERSEDED:"SUPERSEDED",ABORTED:"ABORTED",QUEUE_FULL:"QUEUE_FULL",QUEUE_TIMEOUT:"QUEUE_TIMEOUT",DEFINITION_NOT_CACHED:"DEFINITION_NOT_CACHED"},p=class t extends Error{constructor(r,n=l.UNKNOWN_ERROR,o){super(r);y(this,"code");y(this,"statusCode");y(this,"context");y(this,"originalError");this.name="RhinoComputeError",this.code=n,this.statusCode=o?.statusCode,this.context=o?.context,this.originalError=o?.originalError,o?.originalError&&(this.cause=o.originalError)}static missingValues(r,n,o){return new t(`Input "${r}" has no values defined${n?` (expected ${n})`:""}`,l.INVALID_INPUT,{context:{inputName:r,expectedType:n,...o}})}static unknownParamType(r,n,o){return new t(`Unknown paramType: ${r}`,l.VALIDATION_ERROR,{context:{receivedParamType:r,paramName:n,...o}})}};function C(){let t=globalThis.Buffer;return typeof t=="function"?t:void 0}function De(t){let e=C();return e?e.from(t,"utf-8").toString("base64"):de(new TextEncoder().encode(t))}var le=64,ce="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function Me(t){if(!t)return null;let e=t.replace(/[\t\n\f\r ]/g,"");e.length%4===0&&(e=e.replace(/={1,2}$/,""));let r=e.length%4;if(r===1||e.length<le||!/^[A-Za-z0-9+/]*$/.test(e))return null;let n=ce.indexOf(e.charAt(e.length-1));return r===2&&(n&15)!==0||r===3&&(n&3)!==0?null:r===0?e:e+"==".slice(0,4-r)}function _(t){let e=t.replace(/[\t\n\f\r ]/g,"");if(e.length%4===0&&(e=e.replace(/={1,2}$/,"")),e.length%4===1||!/^[A-Za-z0-9+/]*$/.test(e))throw new p("Invalid base64 input.",l.ENCODING_ERROR,{context:{inputLength:t.length}});let r=C();if(r)return new Uint8Array(r.from(e,"base64"));if(typeof globalThis.atob=="function"){let n=globalThis.atob(e),o=new Uint8Array(n.length);for(let s=0;s<n.length;s++)o[s]=n.charCodeAt(s)&255;return o}throw new p("Base64 decoding not supported in this environment.",l.INVALID_STATE,{context:{environmentInfo:"atob or Buffer not available"}})}function P(t){let e=C();if(e)return e.byteLength(t,"utf-8");let r=0;for(let n=0;n<t.length;n++){let o=t.charCodeAt(n);o<128?r+=1:o<2048?r+=2:o>=55296&&o<=56319&&n+1<t.length&&(t.charCodeAt(n+1)&64512)===56320?(r+=4,n++):r+=3}return r}function de(t){let e=C();if(e)return e.from(t).toString("base64");if(typeof globalThis.btoa=="function"){let n=[];for(let o=0;o<t.length;o+=32766)n.push(globalThis.btoa(String.fromCharCode.apply(null,t.subarray(o,o+32766))));return n.join("")}throw new p("Base64 encoding not supported in this environment.",l.INVALID_STATE,{context:{environmentInfo:"btoa or Buffer not available"}})}var I=class{debug(){}info(){}warn(){}error(){}},U=class{debug(e,...r){console.debug(e,...r)}info(e,...r){console.info(e,...r)}warn(e,...r){console.warn(e,...r)}error(e,...r){console.error(e,...r)}},L=new I;function m(){return L}function B(t){if(t===null){L=new I;return}let e=["debug","info","warn","error"].filter(r=>typeof t[r]!="function");if(e.length>0)throw new p(`Logger is missing required method(s): ${e.join(", ")}. A logger must implement debug, info, warn and error.`,l.INVALID_CONFIG,{context:{missingMethods:e}});L=t}function fe(){B(new U)}function h(t,e){e&&m().debug(t)}function W(t,e){let r=e.replace(/\/+$/,""),n=t.replace(/^\/+/,"");return`${r}/${n}`}function pe(t){try{let e=new URL(t).hostname.toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}catch{return/(localhost|127\.0\.0\.1|\[::1\])/i.test(t)}}var q=new Set;function z(t,e){let r={...e.headers,"X-Request-ID":t,"Content-Type":"application/json",...e.authToken&&{Authorization:e.authToken},...e.apiKey&&{RhinoComputeKey:e.apiKey}};return!e.apiKey&&!e.authToken&&!q.has(e.serverUrl)&&!pe(e.serverUrl)&&(q.add(e.serverUrl),m().warn(`\u26A0\uFE0F [Rhino Compute] Request [${t}] targets remote server (${e.serverUrl}) but no API key or auth token is configured. Requests may fail or be rate-limited. (warned once per server)`)),r}function K(){return`${Date.now()}-${Math.random().toString(36).substring(2,11)}`}function me(t){if(!t)return null;let e={raw:t},r=!1;for(let n of t.split(",")){let[o,...s]=n.trim().split(";"),c=s.find(d=>d.trim().toLowerCase().startsWith("dur"));if(!c)continue;let i=Number(c.split("=")[1]);if(!Number.isFinite(i))continue;let a=o.trim().toLowerCase();(a==="decode"||a==="solve"||a==="encode")&&(e[a]=i,r=!0)}return r?e:null}function x(t,e,r,n){if(!r)return;let o=me(t.headers.get("Server-Timing"));if(o)try{r(o,e)}catch(s){n&&h(` onServerTiming callback threw: ${s}`,!0)}}var V=new WeakMap;function N(t,e){typeof t!="object"||t===null||V.set(t,e)}function ge(t){if(!(typeof t!="object"||t===null))return V.get(t)}var D=4096;function he(t){return t.length<=D?t:`${t.slice(0,D)}\u2026 [truncated ${t.length-D} chars]`}function ye(t,e,r,n,o,s,c,i){let{status:a,statusText:d}=t,u={};t.headers.forEach((se,ie)=>{u[ie]=se});let g=s.trim(),f=g?` \u2014 ${g.slice(0,200)}${g.length>200?"\u2026":""}`:"",E=i??s,S={url:e,requestId:r,method:"POST",requestSize:n,serverUrl:o,responseBody:E?he(E):void 0,responseHeaders:u},b={401:{message:`HTTP ${a}: ${d}${f}`,code:l.AUTH_ERROR},403:{message:`HTTP ${a}: ${d}${f}`,code:l.AUTH_ERROR},404:{message:`Endpoint not found: ${e}`,code:l.NOT_FOUND},413:{message:`Request too large: ${(n/1024).toFixed(2)}KB`,code:l.VALIDATION_ERROR},429:{message:`Rate limit exceeded${f}`,code:l.RATE_LIMIT},500:{message:`Server error: ${d}${f}`,code:l.COMPUTATION_ERROR},502:{message:`Service unavailable: ${d}${f}`,code:l.NETWORK_ERROR},503:{message:`Service unavailable: ${d}${f}`,code:l.NETWORK_ERROR},504:{message:`Service unavailable: ${d}${f}`,code:l.NETWORK_ERROR}}[a]||{message:`HTTP ${a}: ${d}${f}`,code:l.UNKNOWN_ERROR},k=Re(c)??b.code;throw new p(b.message,k,{statusCode:a,context:S})}function Re(t){if(t==="definition_not_cached")return l.DEFINITION_NOT_CACHED}async function H(t,e,r,n,o,s,c,i){let a=Math.round(performance.now()-s);if(!t.ok){let d=await t.text(),u=d;c&&(h(`\u274C Request [${r}] failed with HTTP ${t.status} in ${a}ms`,!0),h(` URL: ${e}`,!0),h(` Status: ${t.status} ${t.statusText}`,!0),u&&h(` Response body: ${u.substring(0,500)}${u.length>500?"...":""}`,!0));let g;try{let f=JSON.parse(u);typeof f?.code=="string"&&(g=f.code)}catch{}if(t.status===500)try{let f=JSON.parse(u);if(f?.values&&(f.errors||f.warnings))return N(f,u.length),c&&(h(`\u26A0\uFE0F Request [${r}] completed with Grasshopper errors in ${a}ms`,!0),f.errors?.length>0&&h(` Errors: ${JSON.stringify(f.errors,null,2)}`,!0),f.warnings?.length>0&&h(` Warnings: ${JSON.stringify(f.warnings,null,2)}`,!0)),x(t,r,i,c),f;let E=typeof f?.message=="string"&&f.message||typeof f?.Message=="string"&&f.Message||"",S=typeof f?.ExceptionType=="string"&&f.ExceptionType||"",O=f?.stackTrace??f?.StackTrace,b=Array.isArray(O)?O.join(`
|
|
2
|
-
`):O||"";E?u=`${S?`${S}: `:""}${E}${b?`
|
|
3
|
-
${b}`:""}`:f?.error&&(u=typeof f.error=="string"?f.error:JSON.stringify(f.error,null,2))}catch(f){c&&h(` Failed to parse error body as JSON: ${f}`,!0)}ye(t,e,r,n,o,u,g,d)}h(`\u2705 Request [${r}] completed in ${a}ms`,c),x(t,r,i,c);try{let d=await t.text(),u=JSON.parse(d);return N(u,d.length),u}catch(d){let u=(t.headers.get("Content-Type")??"").toLowerCase();throw u!==""&&!u.includes("json")?new p(`Server returned a non-JSON response (Content-Type: ${u}) \u2014 check the server URL / proxy configuration`,l.INVALID_RESPONSE,{statusCode:t.status,context:{url:e,requestId:r,contentType:u},originalError:d instanceof Error?d:new Error(String(d))}):new p("Failed to parse JSON response",l.NETWORK_ERROR,{statusCode:t.status,context:{url:e,requestId:r},originalError:d instanceof Error?d:new Error(String(d))})}}var T={attempts:0,baseDelayMs:500,maxDelayMs:3e4,retryOn429:!0},M=new Set([502,503,504]),J=6e4;function j(t){return t?{attempts:t.attempts??T.attempts,baseDelayMs:t.baseDelayMs??T.baseDelayMs,maxDelayMs:t.maxDelayMs??T.maxDelayMs,retryOn429:t.retryOn429??T.retryOn429}:T}function G(t){if(!t)return null;let e=Number(t);if(Number.isFinite(e)&&e>=0)return e*1e3;let r=Date.parse(t);if(Number.isFinite(r)){let n=r-Date.now();return n>0?n:0}return null}function v(t,e){let r=e.baseDelayMs*Math.pow(2,t),n=Math.random()*e.baseDelayMs;return Math.min(r+n,e.maxDelayMs)}function Y(t,e){return new Promise((r,n)=>{if(e?.aborted){n(new DOMException("Aborted","AbortError"));return}let o=setTimeout(()=>{e?.removeEventListener("abort",s),r()},t),s=()=>{clearTimeout(o),n(new DOMException("Aborted","AbortError"))};e?.addEventListener("abort",s,{once:!0})})}function Z(t,e){let r=()=>{},n=typeof e=="number"&&e>0;if(!t&&!n)return{signal:void 0,cleanup:r};if(t&&!n)return{signal:t,cleanup:r};let o=typeof AbortSignal<"u"&&typeof AbortSignal.timeout=="function";if(!t){if(o)return{signal:AbortSignal.timeout(e),cleanup:r};let u=new AbortController,g=setTimeout(()=>u.abort(),e);return{signal:u.signal,cleanup:()=>clearTimeout(g)}}let s=new AbortController,c,i;if(o)c=AbortSignal.timeout(e);else{let u=new AbortController;i=setTimeout(()=>u.abort(),e),c=u.signal}let a=[t,c],d=function(){s.abort(this.reason)};for(let u of a){if(u.aborted){s.abort(u.reason);break}u.addEventListener("abort",d,{once:!0})}return{signal:s.signal,cleanup:()=>{i!==void 0&&clearTimeout(i);for(let u of a)u.removeEventListener("abort",d)}}}async function we(t,e,r,n){let{signal:o,cleanup:s}=Z(t.config.signal,t.config.timeoutMs),c=performance.now();try{let i=await fetch(t.fullUrl,{method:"POST",body:t.body,headers:t.headers,signal:o});if((M.has(i.status)||e.retryOn429&&i.status===429)&&r<n-1){let u=G(i.headers.get("Retry-After")),g=u!==null?Math.min(u,Math.max(e.maxDelayMs,J)):v(r,e);return await i.text().catch(()=>{}),{ok:!1,retry:!0,delayMs:g,cause:new p(`HTTP ${i.status} ${i.statusText} (will retry)`,i.status===429?l.RATE_LIMIT:l.NETWORK_ERROR,{statusCode:i.status,context:{requestId:t.requestId}})}}return{ok:!0,value:await H(i,t.fullUrl,t.requestId,t.requestSize,t.config.serverUrl,c,t.config.debug,t.config.onServerTiming)}}catch(i){if(i instanceof Error&&(i.name==="AbortError"||i.name==="TimeoutError")){if(t.config.signal?.aborted===!0)return{ok:!1,retry:!1,cause:new p("Request aborted by caller",l.ABORTED,{context:{endpoint:t.endpoint,requestId:t.requestId,requestSize:t.requestSize},originalError:i})};let u=typeof t.config.timeoutMs=="number"&&t.config.timeoutMs>0?new p(`Request timed out after ${t.config.timeoutMs}ms`,l.TIMEOUT_ERROR,{context:{serverUrl:t.config.serverUrl,timeoutMs:t.config.timeoutMs,url:t.fullUrl,requestId:t.requestId,endpoint:t.endpoint,requestSize:t.requestSize},originalError:i}):new p(`Request aborted by the runtime (${i.name}): ${i.message}`,l.NETWORK_ERROR,{context:{serverUrl:t.config.serverUrl,url:t.fullUrl,requestId:t.requestId,endpoint:t.endpoint,requestSize:t.requestSize},originalError:i});return r<n-1?{ok:!1,retry:!0,delayMs:v(r,e),cause:u}:{ok:!1,retry:!1,cause:u}}if(i instanceof TypeError){let a=typeof window<"u"&&typeof window.document<"u",d={serverUrl:t.config.serverUrl,url:t.fullUrl,requestId:t.requestId,endpoint:t.endpoint,requestSize:t.requestSize},u=a?new p(`Request failed: ${i.message} \u2014 in a browser this usually means a CORS misconfiguration on the server (or a network failure; the browser does not distinguish them)`,l.CORS_ERROR,{context:d,originalError:i}):new p(`Network error: ${i.message}`,l.NETWORK_ERROR,{context:d,originalError:i});return r<n-1?{ok:!1,retry:!0,delayMs:v(r,e),cause:u}:{ok:!1,retry:!1,cause:u}}if(i instanceof p){let a=i.statusCode;return(i.code===l.NETWORK_ERROR&&a!==void 0&&a>=200&&a<300||a!==void 0&&(M.has(a)||e.retryOn429&&a===429))&&r<n-1?{ok:!1,retry:!0,delayMs:v(r,e),cause:i}:{ok:!1,retry:!1,cause:i}}return{ok:!1,retry:!1,cause:new p(i instanceof Error?i.message:String(i),l.UNKNOWN_ERROR,{context:{endpoint:t.endpoint,requestId:t.requestId},originalError:i instanceof Error?i:new Error(String(i))})}}finally{s()}}async function Ee(t,e,r){let n=K(),o=JSON.stringify(e),s=P(o),c=W(t,r.serverUrl),i=z(n,r),a=j(r.retry),d=a.attempts+1;if(r.debug){let g=(s/1024).toFixed(2),f=s>1e5?"\u26A0\uFE0F":"\u{1F680}";h(`${f} Starting compute request [${n}]: ${t} (${g}KB)`,!0)}let u={endpoint:t,body:o,requestSize:s,fullUrl:c,requestId:n,headers:i,config:r};for(let g=0;;g++){let f=await we(u,a,g,d);if(f.ok)return f.value;if(!f.retry)throw f.cause;r.debug&&h(`\u{1F501} Request [${n}] retrying after ${f.delayMs}ms (attempt ${g+2}/${d}): ${f.cause.message}`,!0);try{await Y(f.delayMs,r.signal)}catch{throw new p("Request aborted by caller",l.ABORTED,{context:{endpoint:t,requestId:n,requestSize:s},originalError:f.cause})}}}var be="compute.rhino3d.com";function Q(t){let e=t?.trim()??"";if(!e)throw new p("serverUrl is required",l.INVALID_CONFIG,{context:{receivedServerUrl:t}});if(!/^https?:\/\//i.test(e))throw new p(`Invalid serverUrl: "${e}". Must start with "http://" or "https://". For example: "http://localhost:5000" or "https://example.com"`,l.INVALID_CONFIG,{context:{receivedServerUrl:t}});let r;try{r=new URL(e)}catch(o){throw new p(`Invalid serverUrl: "${e}". Must be a valid URL. Received error: ${o instanceof Error?o.message:String(o)}`,l.INVALID_CONFIG,{context:{receivedServerUrl:t},originalError:o instanceof Error?o:void 0})}if(r.username!==""||r.password!=="")throw new p(`Invalid serverUrl: "${e}". Must not embed credentials (user:pass@host) \u2014 fetch rejects credentialed URLs at request time. Pass the API key separately.`,l.INVALID_CONFIG,{context:{receivedServerUrl:t}});if(e.includes("?")||e.includes("#"))throw new p(`Invalid serverUrl: "${e}". Must not contain a query string or fragment \u2014 endpoint paths are appended to this URL (e.g. "\${serverUrl}/version"), and a "?" or "#" suffix would corrupt every request path.`,l.INVALID_CONFIG,{context:{receivedServerUrl:t}});if(r.hostname.toLowerCase().replace(/\.+$/,"")===be)throw new p("serverUrl must be set to your Compute server URL. The default public endpoint is not allowed.",l.INVALID_CONFIG,{context:{receivedServerUrl:t}});return e.replace(/\/+$/,"")}var R=class R{constructor(e,r){y(this,"serverUrl");y(this,"apiKey");y(this,"disposed",!1);y(this,"activeMonitors",new Set);y(this,"activeTimeouts",new Set);this.serverUrl=Q(e),this.apiKey=r}buildHeaders(){let e={"Content-Type":"application/json"};return this.apiKey&&(e.RhinoComputeKey=this.apiKey),e}fetchWithTimeout(e,r={},n=R.DEFAULT_TIMEOUT_MS){let o=new Headers(this.buildHeaders());r.headers&&new Headers(r.headers).forEach((i,a)=>{o.set(a,i)});let s={};o.forEach((i,a)=>{s[a]=i});let c={...r,headers:s};return n>0&&!c.signal&&(c.signal=AbortSignal.timeout(n)),fetch(e,c)}async isServerOnline(e=5e3){this.ensureNotDisposed();let r=`${this.serverUrl}/`;try{return(await this.fetchWithTimeout(r,{method:"GET"},e)).ok}catch(n){return m().debug("[ComputeServerStats] Fetch error:",n),!1}}async getActiveChildren(e={}){this.ensureNotDisposed();let{initialize:r=!0}=e,n=r?`${this.serverUrl}/activechildren`:`${this.serverUrl}/activechildren?initialize=false`,o=r?R.LIFECYCLE_TIMEOUT_MS:R.DEFAULT_TIMEOUT_MS;try{let s=await this.fetchWithTimeout(n,{},o);if(!s.ok)return m().warn("[ComputeServerStats] Failed to fetch active children:",s.status),null;let c=(await s.text()).trim();return/^\d+$/.test(c)?parseInt(c,10):(m().warn("[ComputeServerStats] Invalid active children response:",c),null)}catch(s){return m().warn("[ComputeServerStats] Error fetching active children:",s),null}}async getVersion(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/version`);if(!e.ok)return m().warn("[ComputeServerStats] Failed to fetch version:",e.status),null;let r=await e.text();try{let n=JSON.parse(r);return{rhino:n.rhino??"",compute:n.compute??"",git_sha:n.git_sha??null}}catch{return{rhino:r,compute:"",git_sha:null}}}catch(e){return m().warn("[ComputeServerStats] Error fetching version:",e),null}}async getInstalledPlugins(e="gh"){this.ensureNotDisposed();try{let r=await this.fetchWithTimeout(`${this.serverUrl}/plugins/${e}/installed`);if(!r.ok)return m().warn(`[ComputeServerStats] Failed to fetch ${e} plugins:`,r.status),null;let n=await r.text();try{let o=JSON.parse(n);return o&&typeof o=="object"?o:null}catch{return null}}catch(r){return m().warn(`[ComputeServerStats] Error fetching ${e} plugins:`,r),null}}async getServerStats(){if(this.ensureNotDisposed(),!await this.isServerOnline())return{isOnline:!1};let[r,n]=await Promise.all([this.getVersion(),this.getActiveChildren({initialize:!1})]);return{isOnline:!0,...r&&{version:r},...n!==null&&{activeChildren:n}}}async purgeCache(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/cache/purge`,{method:"POST"});if(!e.ok)return m().warn("[ComputeServerStats] Failed to purge cache:",e.status),null;let r=await e.text();try{let n=JSON.parse(r);return typeof n.purged=="number"?n.purged:null}catch{return null}}catch(e){return m().warn("[ComputeServerStats] Error purging cache:",e),null}}async purgeAllChildren(){this.ensureNotDisposed();let e=await this.getActiveChildren({initialize:!1});if(e===null)return m().warn("[ComputeServerStats] purgeAllChildren: could not read child count"),null;if(e===0)return{totalPurged:0,calls:0,children:0,confident:!0};let r=e*2,n=0;for(let o=0;o<r;o++){let s=await this.purgeCache();s!==null&&(n+=s)}return{totalPurged:n,calls:r,children:e,confident:e===1}}async getServerTime(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/servertime`);if(!e.ok)return m().warn("[ComputeServerStats] Failed to fetch server time:",e.status),null;let r=(await e.text()).trim().replace(/^"|"$/g,""),n=new Date(r);return isNaN(n.getTime())?null:n}catch(e){return m().warn("[ComputeServerStats] Error fetching server time:",e),null}}async getIdleSpan(){this.ensureNotDisposed();try{let e=await this.fetchWithTimeout(`${this.serverUrl}/idlespan`);if(!e.ok)return m().warn("[ComputeServerStats] Failed to fetch idle span:",e.status),null;let r=parseFloat((await e.text()).trim());return isNaN(r)?null:r}catch(e){return m().warn("[ComputeServerStats] Error fetching idle span:",e),null}}async launchChildren(){return this.postJson("/launch-children")}async launchChild(e){let r=e===void 0?"/launch-child":`/launch-child?port=${e}`;return this.postJson(r)}async shutdownChildren(e){let r=e===void 0?"/shutdown-children":`/shutdown-children?port=${e}`;return this.postJson(r)}async recycleChildren(e){let r=e===void 0?"/recycle-children":`/recycle-children?port=${e}`;return this.postJson(r)}async postJson(e){this.ensureNotDisposed();try{let r=await this.fetchWithTimeout(`${this.serverUrl}${e}`,{method:"POST"},R.LIFECYCLE_TIMEOUT_MS);if(!r.ok)return m().warn(`[ComputeServerStats] POST ${e} failed:`,r.status),null;let n=await r.text();try{return JSON.parse(n)}catch{return null}}catch(r){return m().warn(`[ComputeServerStats] Error on POST ${e}:`,r),null}}monitor(e,r=5e3){if(this.ensureNotDisposed(),!Number.isFinite(r)||r<R.MIN_MONITOR_INTERVAL_MS)throw new RangeError(`monitor() intervalMs must be a finite number >= ${R.MIN_MONITOR_INTERVAL_MS}ms, got ${r}. Sub-${R.MIN_MONITOR_INTERVAL_MS}ms polling would hot-loop the server.`);let n=!0,o=null;m().info(`\u{1F504} Starting server stats monitoring every ${r}ms`);let s=async()=>{if(o!==null&&(this.activeTimeouts.delete(o),o=null),!(!n||this.disposed)){try{let i=await this.getServerStats();if(!n||this.disposed)return;try{e(i)}catch(a){m().error("[ComputeServerStats] Monitor callback threw:",a)}}catch(i){!n||this.disposed?m().debug("[ComputeServerStats] Monitor poll cancelled during shutdown:",i):m().error("[ComputeServerStats] Failed to fetch stats during monitor:",i)}n&&!this.disposed&&(o=setTimeout(()=>{s()},r),this.activeTimeouts.add(o))}},c=()=>{n=!1,o!==null&&(clearTimeout(o),this.activeTimeouts.delete(o),o=null),this.activeMonitors.delete(c)};return this.activeMonitors.add(c),s(),c}async dispose(){if(!this.disposed){this.disposed=!0;for(let e of this.activeMonitors)e();this.activeMonitors.clear();for(let e of this.activeTimeouts)clearTimeout(e);this.activeTimeouts.clear()}}ensureNotDisposed(){if(this.disposed)throw new p("ComputeServerStats has been disposed and cannot be used",l.INVALID_STATE,{context:{disposed:this.disposed}})}};y(R,"DEFAULT_TIMEOUT_MS",5e3),y(R,"LIFECYCLE_TIMEOUT_MS",6e4),y(R,"MIN_MONITOR_INTERVAL_MS",100);var A=R;function X(t,e={}){let{preserveSpaces:r=!1}=e,n=r?/[-_]+(.)?/g:/[\s\-_]+(.)?/g,o=t.trim().replace(n,(s,c)=>c?c.toUpperCase():"");return o=o.replace(/^[A-Z]+(?=[A-Z][a-z]|[^A-Za-z]|$)/,s=>s.toLowerCase()),o.charAt(0).toLowerCase()+o.slice(1)}function Te(t){if(t===null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function F(t,e={}){if(!t||typeof t!="object")return t;if(Array.isArray(t))return e.deep?t.map(n=>F(n,e)):t;if(!Te(t))return t;let r={};for(let n of Object.keys(t)){let o=X(n,{preserveSpaces:e.preserveSpaces});Object.prototype.hasOwnProperty.call(r,o)&&m().warn(`camelcaseKeys: key '${n}' collides with an earlier key on '${o}' \u2014 the earlier value is overwritten (last key wins).`);let s=t[n];r[o]=e.deep?F(s,e):s}return r}function w(t,e){if(!t||typeof t!="object")return;let r=t;if(te(r,e))return r[e];let n=re(r).get(e.toLowerCase());return n===void 0?void 0:r[n]}var te=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);function yt(t,e){if(!t||typeof t!="object")return!1;let r=t;return te(r,e)?!0:re(r).has(e.toLowerCase())}var ee=new WeakMap;function re(t){let e=Object.keys(t),r=ee.get(t);if(r&&r.keyCount===e.length)return r.map;let n=new Map;for(let o of e){let s=o.toLowerCase();n.has(s)||n.set(s,o)}return ee.set(t,{keyCount:e.length,map:n}),n}var ve=async(t,e=null)=>{try{return await ne(t,e)}catch(r){throw new p("Failed to extract files from compute response",l.INVALID_STATE,{context:{originalError:r instanceof Error?r.message:String(r)},originalError:r instanceof Error?r:void 0})}},Se=async(t,e,r=null)=>{if(typeof document>"u"||typeof Blob>"u")throw new p("File download functionality is only available in browser environments. This function requires the DOM API (document, Blob).",l.BROWSER_ONLY,{context:{environment:typeof window<"u"?"browser (SSR)":"Node.js",documentAvailable:typeof document<"u",blobAvailable:typeof Blob<"u"}});try{let n=await ne(t,r);await Ae(n,e)}catch(n){throw n instanceof p?n:new p("Failed to download files from compute response",l.INVALID_STATE,{context:{originalError:n instanceof Error?n.message:String(n)},originalError:n instanceof Error?n:void 0})}},$=t=>t.replace(/\\/g,"/").split("/").map(e=>e.trim()).filter(e=>e!==""&&e!=="."&&e!==".."&&!/^[a-zA-Z]:$/.test(e)).join("/"),Oe=t=>t===!0||typeof t=="string"&&t.trim().toLowerCase()==="true",Ce=t=>{let e=[];return t.forEach(r=>{let n=w(r,"fileName")??"",o=w(r,"fileType")??"",s=$(`${n}${o}`);if(s===""){m().warn(`Skipping file with unusable name "${n}${o}": no safe archive path remains after sanitization.`);return}let c=w(r,"subFolder"),i=c?$(c):"",a=i!==""?`${i}/${s}`:s,d=w(r,"data");if(typeof d!="string"||d===""){m().warn(`Skipping file "${a}": item carries no usable data.`);return}if(Oe(w(r,"isBase64Encoded")))try{e.push({fileName:s,content:_(d),path:a})}catch(u){m().warn(`Skipping file "${a}": base64 decode failed.`,u)}else e.push({fileName:s,content:d,path:a})}),e},Ie=3e4,Ne=async t=>(await Promise.all(t.map(async r=>{try{let n=typeof AbortSignal<"u"&&typeof AbortSignal.timeout=="function"?AbortSignal.timeout(Ie):void 0,o=await fetch(r.filePath,{signal:n});if(!o.ok)return m().warn(`Failed to fetch additional file from URL: ${r.filePath}`),null;let s=await o.arrayBuffer(),c=$(r.fileName);if(c==="")return m().warn(`Skipping fetched file with unusable name: ${r.fileName}`),null;let i=r.subFolder?$(r.subFolder):"";return{fileName:c,content:new Uint8Array(s),path:i!==""?`${i}/${c}`:c}}catch(n){return m().error(`Error fetching additional file from URL: ${r.filePath}`,n),null}}))).filter(r=>r!==null),ne=async(t,e)=>{let r=Ce(t);if(e){let o=Array.isArray(e)?e:[e];r.push(...await Ne(o))}let n=new Set;return r.map(o=>{let s=oe(o.path,n);return n.add(s),s===o.path?o:(m().warn(`Duplicate archive path "${o.path}" \u2014 storing as "${s}".`),{...o,path:s,fileName:s.slice(s.lastIndexOf("/")+1)})})};async function Ae(t,e){let{zip:r,strToU8:n}=await import("fflate"),o={},s=new Set;t.forEach(a=>{let d=oe(a.path,s);s.add(d),d!==a.path&&m().warn(`Duplicate archive path "${a.path}" \u2014 storing as "${d}".`),o[d]=typeof a.content=="string"?n(a.content):a.content});let c=await new Promise((a,d)=>{r(o,{level:6},(u,g)=>u?d(u):a(g))}),i=new Blob([c],{type:"application/zip"});$e(i,`${e}.zip`)}function oe(t,e){if(!e.has(t))return t;let r=t.lastIndexOf("/"),n=t.lastIndexOf("."),o=n>r?n:t.length,s=t.slice(0,o),c=t.slice(o);for(let i=2;;i++){let a=`${s}-${i}${c}`;if(!e.has(a))return a}}function $e(t,e){if(typeof document>"u")throw new p("saveFile requires a browser environment with DOM API access.",l.BROWSER_ONLY,{context:{function:"saveFile",requiredAPI:"document"}});let r=URL.createObjectURL(t),n=document.createElement("a");n.href=r,n.download=e,document.body.appendChild(n),n.click(),n.remove(),setTimeout(()=>URL.revokeObjectURL(r),1e4)}export{y as a,l as b,p as c,De as d,Me as e,_ as f,de as g,m as h,B as i,fe as j,N as k,ge as l,Ee as m,Q as n,A as o,X as p,F as q,w as r,yt as s,ve as t,Se as u};
|
|
4
|
-
//# sourceMappingURL=chunk-XT3XWDDV.js.map
|