@selvajs/compute 3.1.0-beta.13 → 3.1.0-beta.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-6R4EL3ZJ.cjs → chunk-25TNL6LY.cjs} +2 -2
- package/dist/chunk-25TNL6LY.cjs.map +1 -0
- package/dist/chunk-3QSC23Y2.cjs +120 -0
- package/dist/chunk-3QSC23Y2.cjs.map +1 -0
- package/dist/chunk-H3FZW6OX.cjs.map +1 -1
- package/dist/{chunk-6TMSTNHN.js → chunk-J4NKIVF3.js} +2 -2
- package/dist/chunk-KJVV3L5H.js +120 -0
- package/dist/chunk-KJVV3L5H.js.map +1 -0
- package/dist/core.cjs.map +1 -1
- package/dist/grasshopper.cjs +1 -1
- package/dist/grasshopper.cjs.map +1 -1
- package/dist/grasshopper.d.cts +2 -2
- package/dist/grasshopper.d.ts +2 -2
- package/dist/grasshopper.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/{types-Dtok-mVq.d.ts → types-4FMvnx2j.d.ts} +14 -1
- package/dist/{types-C8XWc4Ab.d.cts → types-BpOl6U02.d.cts} +14 -1
- package/dist/visualization-2TKA3LVK.cjs +2 -0
- package/dist/visualization-2TKA3LVK.cjs.map +1 -0
- package/dist/visualization-XWX3PR4N.js +2 -0
- package/dist/visualization.cjs +1 -1
- package/dist/visualization.cjs.map +1 -1
- package/dist/visualization.d.cts +100 -9
- package/dist/visualization.d.ts +100 -9
- package/dist/visualization.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-6R4EL3ZJ.cjs.map +0 -1
- package/dist/chunk-GLOTP5TC.cjs +0 -120
- package/dist/chunk-GLOTP5TC.cjs.map +0 -1
- package/dist/chunk-NVMSD4CC.js +0 -120
- package/dist/chunk-NVMSD4CC.js.map +0 -1
- package/dist/visualization-BIHTM2KJ.js +0 -2
- package/dist/visualization-FLDYIZ3F.cjs +0 -2
- package/dist/visualization-FLDYIZ3F.cjs.map +0 -1
- /package/dist/{chunk-6TMSTNHN.js.map → chunk-J4NKIVF3.js.map} +0 -0
- /package/dist/{visualization-BIHTM2KJ.js.map → visualization-XWX3PR4N.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["d:\\Coding\\selva\\packages\\compute\\dist\\chunk-3QSC23Y2.cjs"],"names":[],"mappings":"AAAA,2/BAAgF,IAAK,EAAE,CAAC,CAAC,CAAC,CAAC,iCAAE,EAAG,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,iBAAiB,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,cAAc,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,cAAc,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,gBAAgB,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,eAAe,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,gBAAgB,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,aAAa,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,2oBAAuB,IAAK,EAAE,CAAC,IAAI,CAAC,CAAC,oBAAoB,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,EAAE,CAAC,SAAS,CAAC,EAAE,CAAC,kBAAkB,CAAC,EAAE,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC,IAAI,CAAC,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ACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAA;AACA,QAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAA","file":"D:\\Coding\\selva\\packages\\compute\\dist\\chunk-3QSC23Y2.cjs","sourcesContent":[null]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/selva/selva/packages/compute/dist/chunk-H3FZW6OX.cjs","../src/core/errors.ts","../src/core/compute-fetch/compute-fetch.ts"],"names":["ErrorCodes","RhinoComputeError","_RhinoComputeError","message","code","options","__publicField","inputName","expectedType","context"],"mappings":"AAAA,u8BAAI,CAAC,CAAC,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC,CAAC,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,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,C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,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;AC4VzC;AA2IU","file":"/home/runner/work/selva/selva/packages/compute/dist/chunk-H3FZW6OX.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 { getLogger } from '../utils/logger';\nimport { utf8ByteLength } from '../utils/encoding';\nimport { setResponseWireSize } from './wire-size';\n\nimport type { ComputeConfig, RetryPolicy, ServerTiming } from '../types';\n\n/**\n * Parse a `Server-Timing` header value into typed durations (ms).\n *\n * Header grammar (RFC 9110 §10.1.10), as emitted by the solve endpoint:\n * `decode;dur=3, solve;dur=120, encode;dur=8`\n *\n * Returns null when the header is absent or carries no recognizable metric, so\n * the caller can skip the callback entirely.\n *\n * @internal exported for tests\n */\nexport function parseServerTiming(headerValue: string | null): ServerTiming | null {\n\tif (!headerValue) return null;\n\tconst timing: ServerTiming = { raw: headerValue };\n\tlet sawMetric = false;\n\tfor (const part of headerValue.split(',')) {\n\t\tconst [name, ...params] = part.trim().split(';');\n\t\tconst durParam = params.find((p) => p.trim().toLowerCase().startsWith('dur'));\n\t\tif (!durParam) continue;\n\t\tconst dur = Number(durParam.split('=')[1]);\n\t\tif (!Number.isFinite(dur)) continue;\n\t\tconst key = name.trim().toLowerCase();\n\t\tif (key === 'decode' || key === 'solve' || key === 'encode') {\n\t\t\ttiming[key] = dur;\n\t\t\tsawMetric = true;\n\t\t}\n\t}\n\treturn sawMetric ? timing : null;\n}\n\nconst DEFAULT_RETRY: Required<RetryPolicy> = {\n\tattempts: 0,\n\tbaseDelayMs: 500,\n\tmaxDelayMs: 30_000,\n\tretryOn429: true\n};\n\nconst 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 */\nconst RETRY_AFTER_CAP_MS = 60_000;\n\n/** Upper bound for the raw server body stored on error `context.responseBody`. */\nconst MAX_CONTEXT_BODY_CHARS = 4096;\n\nfunction 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 */\nfunction 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\nfunction 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\nfunction 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\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\nfunction 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 */\nfunction 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\nfunction buildUrl(endpoint: string, serverUrl: string): string {\n\tconst base = serverUrl.replace(/\\/+$/, '');\n\tconst path = endpoint.replace(/^\\/+/, '');\n\treturn `${base}/${path}`;\n}\n\nfunction isLocalhost(serverUrl: string): boolean {\n\ttry {\n\t\t// `hostname` (not `host`) strips the port; IPv6 hostnames keep their\n\t\t// brackets, so `http://[::1]:6500` yields `[::1]`.\n\t\tconst hostname = new URL(serverUrl).hostname.toLowerCase();\n\t\treturn hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '[::1]';\n\t} catch {\n\t\treturn /(localhost|127\\.0\\.0\\.1|\\[::1\\])/i.test(serverUrl);\n\t}\n}\n\n/** Server URLs already warned about missing auth — warn once per server, not per request. */\nconst warnedNoAuth = new Set<string>();\n\nfunction buildHeaders(requestId: string, config: ComputeConfig): HeadersInit {\n\tconst headers: HeadersInit = {\n\t\t// Caller headers first so the transport's own headers below OVERWRITE them —\n\t\t// a caller can never clobber the request id, content type, or auth.\n\t\t...config.headers,\n\t\t'X-Request-ID': requestId,\n\t\t'Content-Type': 'application/json',\n\t\t...(config.authToken && { Authorization: config.authToken }),\n\t\t...(config.apiKey && { RhinoComputeKey: config.apiKey })\n\t};\n\n\tif (\n\t\t!config.apiKey &&\n\t\t!config.authToken &&\n\t\t!warnedNoAuth.has(config.serverUrl) &&\n\t\t!isLocalhost(config.serverUrl)\n\t) {\n\t\twarnedNoAuth.add(config.serverUrl);\n\t\tgetLogger().warn(\n\t\t\t`⚠️ [Rhino Compute] Request [${requestId}] targets remote server (${config.serverUrl}) but no API key or auth token is configured. Requests may fail or be rate-limited. (warned once per server)`\n\t\t);\n\t}\n\n\treturn headers;\n}\n\nfunction generateRequestId(): string {\n\treturn `${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;\n}\n\nfunction log(message: string, debug?: boolean): void {\n\tif (debug) getLogger().debug(message);\n}\n\n/**\n * Compose a caller-supplied AbortSignal with an optional timeout. Returns a\n * combined signal, or `undefined` if neither was given.\n *\n * Uses `AbortSignal.timeout` (not setTimeout) so the timer is not throttled\n * when the tab is hidden. Falls back to a manual timer for older runtimes.\n *\n * @internal exported for tests\n */\nexport function composeSignal(\n\tcallerSignal: AbortSignal | undefined,\n\ttimeoutMs: number | undefined\n): { signal: AbortSignal | undefined; cleanup: () => void } {\n\tconst noCleanup = () => {};\n\tconst wantsTimeout = typeof timeoutMs === 'number' && timeoutMs > 0;\n\n\tif (!callerSignal && !wantsTimeout) return { signal: undefined, cleanup: noCleanup };\n\tif (callerSignal && !wantsTimeout) return { signal: callerSignal, cleanup: noCleanup };\n\n\tconst supportsTimeout =\n\t\ttypeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function';\n\n\t// Timeout only: nothing is registered on a caller signal, so there is nothing to clean up on\n\t// the modern path (the pending timer is small and self-expires at timeoutMs).\n\tif (!callerSignal) {\n\t\tif (supportsTimeout) return { signal: AbortSignal.timeout(timeoutMs!), cleanup: noCleanup };\n\t\tconst ctrl = new AbortController();\n\t\tconst id = setTimeout(() => ctrl.abort(), timeoutMs);\n\t\treturn { signal: ctrl.signal, cleanup: () => clearTimeout(id) };\n\t}\n\n\t// Caller signal + timeout: composed manually rather than with AbortSignal.any — `any` offers no\n\t// way to unregister its dependent link on the caller's signal, so an app reusing one long-lived\n\t// signal across many solves accumulates a registration per attempt for the full timeoutMs after\n\t// each response (and forever on Node versions with the known AbortSignal.any leak).\n\tconst ctrl = new AbortController();\n\n\tlet timeoutSignal: AbortSignal;\n\tlet timerId: ReturnType<typeof setTimeout> | undefined;\n\tif (supportsTimeout) {\n\t\ttimeoutSignal = AbortSignal.timeout(timeoutMs!);\n\t} else {\n\t\tconst timeoutCtrl = new AbortController();\n\t\ttimerId = setTimeout(() => timeoutCtrl.abort(), timeoutMs);\n\t\ttimeoutSignal = timeoutCtrl.signal;\n\t}\n\n\tconst sources = [callerSignal, timeoutSignal];\n\t// Forward the source's reason so fetch rejects with the right error name\n\t// ('TimeoutError' vs 'AbortError'), matching AbortSignal.any semantics.\n\tconst onAbort = function (this: AbortSignal) {\n\t\tctrl.abort(this.reason);\n\t};\n\n\tfor (const s of sources) {\n\t\tif (s.aborted) {\n\t\t\tctrl.abort(s.reason);\n\t\t\tbreak;\n\t\t}\n\t\ts.addEventListener('abort', onAbort, { once: true });\n\t}\n\n\treturn {\n\t\tsignal: ctrl.signal,\n\t\tcleanup: () => {\n\t\t\tif (timerId !== undefined) clearTimeout(timerId);\n\t\t\tfor (const s of sources) s.removeEventListener('abort', onAbort);\n\t\t}\n\t};\n}\n\n/**\n * Surface the server's per-request timing breakdown (if it sent one and a\n * caller is listening). Best-effort: a throwing callback must not fail the\n * request. Called on the success path AND the 500-with-values partial-success\n * path — solves that completed with Grasshopper errors carry real timings too.\n */\nfunction fireServerTiming(\n\tresponse: Response,\n\trequestId: string,\n\tonServerTiming: ((timing: ServerTiming, requestId: string) => void) | undefined,\n\tdebug?: boolean\n): void {\n\tif (!onServerTiming) return;\n\tconst timing = parseServerTiming(response.headers.get('Server-Timing'));\n\tif (!timing) return;\n\ttry {\n\t\tonServerTiming(timing, requestId);\n\t} catch (err) {\n\t\tif (debug) log(` onServerTiming callback threw: ${err}`, true);\n\t}\n}\n\nasync 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\ninterface AttemptContext {\n\tendpoint: string;\n\tbody: string;\n\trequestSize: number;\n\tfullUrl: string;\n\trequestId: string;\n\theaders: HeadersInit;\n\tconfig: ComputeConfig;\n}\n\ninterface AttemptResult {\n\tok: true;\n\tvalue: any;\n}\n\ninterface AttemptRetry {\n\tok: false;\n\tretry: true;\n\tdelayMs: number;\n\tcause: RhinoComputeError;\n}\n\ninterface AttemptFatal {\n\tok: false;\n\tretry: false;\n\tcause: RhinoComputeError;\n}\n\nasync function attemptFetch(\n\tctx: AttemptContext,\n\tretryPolicy: Required<RetryPolicy>,\n\tattempt: number,\n\ttotalAttempts: number\n): Promise<AttemptResult | AttemptRetry | AttemptFatal> {\n\tconst { signal, cleanup } = composeSignal(ctx.config.signal, ctx.config.timeoutMs);\n\tconst startTime = performance.now();\n\n\ttry {\n\t\tconst response = await fetch(ctx.fullUrl, {\n\t\t\tmethod: 'POST',\n\t\t\tbody: ctx.body,\n\t\t\theaders: ctx.headers,\n\t\t\tsignal\n\t\t});\n\n\t\t// 429 with Retry-After or retryable 5xx → maybe retry\n\t\tconst isRetryableStatus =\n\t\t\tRETRYABLE_STATUS.has(response.status) || (retryPolicy.retryOn429 && response.status === 429);\n\n\t\tif (isRetryableStatus && attempt < totalAttempts - 1) {\n\t\t\tconst retryAfterMs = parseRetryAfter(response.headers.get('Retry-After'));\n\t\t\t// The server's stated Retry-After window wins over maxDelayMs — retrying\n\t\t\t// before it all but guarantees another 429 and burns an attempt. It is\n\t\t\t// only clamped by the absolute RETRY_AFTER_CAP_MS safety cap (or by a\n\t\t\t// caller-configured maxDelayMs that is even larger), so a bad header\n\t\t\t// can't force a pathological sleep. backoffDelay already clamps itself.\n\t\t\tconst delayMs =\n\t\t\t\tretryAfterMs !== null\n\t\t\t\t\t? Math.min(retryAfterMs, Math.max(retryPolicy.maxDelayMs, RETRY_AFTER_CAP_MS))\n\t\t\t\t\t: backoffDelay(attempt, retryPolicy);\n\t\t\t// Drain the body so the connection can be reused on the next attempt.\n\t\t\t// On the *final* attempt we deliberately fall through — handleResponse\n\t\t\t// reads the body itself to surface the error context.\n\t\t\tawait response.text().catch(() => {});\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tretry: true,\n\t\t\t\tdelayMs,\n\t\t\t\tcause: new RhinoComputeError(\n\t\t\t\t\t`HTTP ${response.status} ${response.statusText} (will retry)`,\n\t\t\t\t\tresponse.status === 429 ? ErrorCodes.RATE_LIMIT : ErrorCodes.NETWORK_ERROR,\n\t\t\t\t\t{ statusCode: response.status, context: { requestId: ctx.requestId } }\n\t\t\t\t)\n\t\t\t};\n\t\t}\n\n\t\tconst value = await handleResponse(\n\t\t\tresponse,\n\t\t\tctx.fullUrl,\n\t\t\tctx.requestId,\n\t\t\tctx.requestSize,\n\t\t\tctx.config.serverUrl,\n\t\t\tstartTime,\n\t\t\tctx.config.debug,\n\t\t\tctx.config.onServerTiming\n\t\t);\n\t\treturn { ok: true, value };\n\t} catch (error) {\n\t\t// Caller-aborted vs timeout-aborted distinction\n\t\tif (error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError')) {\n\t\t\tconst callerAborted = ctx.config.signal?.aborted === true;\n\n\t\t\tif (callerAborted) {\n\t\t\t\t// Caller cancellation is never retried — propagate immediately\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tretry: false,\n\t\t\t\t\tcause: new RhinoComputeError('Request aborted by caller', ErrorCodes.ABORTED, {\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\tendpoint: ctx.endpoint,\n\t\t\t\t\t\t\trequestId: ctx.requestId,\n\t\t\t\t\t\t\trequestSize: ctx.requestSize\n\t\t\t\t\t\t},\n\t\t\t\t\t\toriginalError: error\n\t\t\t\t\t})\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Only claim a timeout when we actually armed one (issue 88). Without a\n\t\t\t// configured timeoutMs, a non-caller abort came from the runtime itself\n\t\t\t// (e.g. an undici socket teardown) — as transient as any network drop, so\n\t\t\t// it stays retryable, but it is NOT a timeout: report it truthfully\n\t\t\t// instead of \"timed out after undefinedms\" / TIMEOUT_ERROR.\n\t\t\tconst timeoutArmed = typeof ctx.config.timeoutMs === 'number' && ctx.config.timeoutMs > 0;\n\t\t\tconst fatal = timeoutArmed\n\t\t\t\t? new RhinoComputeError(\n\t\t\t\t\t\t`Request timed out after ${ctx.config.timeoutMs}ms`,\n\t\t\t\t\t\tErrorCodes.TIMEOUT_ERROR,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\t\tserverUrl: ctx.config.serverUrl,\n\t\t\t\t\t\t\t\ttimeoutMs: ctx.config.timeoutMs,\n\t\t\t\t\t\t\t\turl: ctx.fullUrl,\n\t\t\t\t\t\t\t\trequestId: ctx.requestId,\n\t\t\t\t\t\t\t\tendpoint: ctx.endpoint,\n\t\t\t\t\t\t\t\trequestSize: ctx.requestSize\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\toriginalError: error\n\t\t\t\t\t\t}\n\t\t\t\t\t)\n\t\t\t\t: new RhinoComputeError(\n\t\t\t\t\t\t`Request aborted by the runtime (${error.name}): ${error.message}`,\n\t\t\t\t\t\tErrorCodes.NETWORK_ERROR,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\t\tserverUrl: ctx.config.serverUrl,\n\t\t\t\t\t\t\t\turl: ctx.fullUrl,\n\t\t\t\t\t\t\t\trequestId: ctx.requestId,\n\t\t\t\t\t\t\t\tendpoint: ctx.endpoint,\n\t\t\t\t\t\t\t\trequestSize: ctx.requestSize\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\toriginalError: error\n\t\t\t\t\t\t}\n\t\t\t\t\t);\n\t\t\tif (attempt < totalAttempts - 1) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tretry: true,\n\t\t\t\t\tdelayMs: backoffDelay(attempt, retryPolicy),\n\t\t\t\t\tcause: fatal\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: false, retry: false, cause: fatal };\n\t\t}\n\n\t\t// Network error (TypeError) — retryable (issue 90).\n\t\t//\n\t\t// Duplicate-POST caveat: a connection reset can strike after the body was\n\t\t// sent, in which case the server may already have executed this POST and a\n\t\t// retry runs it again. Compute solves are deterministic, so a duplicate is\n\t\t// wasted work rather than corruption; RetryPolicy documents the risk and\n\t\t// defaults to attempts: 0.\n\t\t//\n\t\t// In a real browser, a fetch TypeError with no response is most often a\n\t\t// CORS misconfiguration (the browser hides the details by design), so it is\n\t\t// classified CORS_ERROR there to stop callers chasing phantom network\n\t\t// failures. Retries are kept in both environments: the same TypeError is\n\t\t// also what a flaky/offline network produces, and there is no way to tell\n\t\t// them apart.\n\t\tif (error instanceof TypeError) {\n\t\t\tconst inBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';\n\t\t\tconst errorContext = {\n\t\t\t\tserverUrl: ctx.config.serverUrl,\n\t\t\t\turl: ctx.fullUrl,\n\t\t\t\trequestId: ctx.requestId,\n\t\t\t\tendpoint: ctx.endpoint,\n\t\t\t\trequestSize: ctx.requestSize\n\t\t\t};\n\t\t\tconst fatal = inBrowser\n\t\t\t\t? new RhinoComputeError(\n\t\t\t\t\t\t`Request failed: ${error.message} — in a browser this usually means a CORS misconfiguration on the server (or a network failure; the browser does not distinguish them)`,\n\t\t\t\t\t\tErrorCodes.CORS_ERROR,\n\t\t\t\t\t\t{ context: errorContext, originalError: error }\n\t\t\t\t\t)\n\t\t\t\t: new RhinoComputeError(`Network error: ${error.message}`, ErrorCodes.NETWORK_ERROR, {\n\t\t\t\t\t\tcontext: errorContext,\n\t\t\t\t\t\toriginalError: error\n\t\t\t\t\t});\n\t\t\tif (attempt < totalAttempts - 1) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tretry: true,\n\t\t\t\t\tdelayMs: backoffDelay(attempt, retryPolicy),\n\t\t\t\t\tcause: fatal\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: false, retry: false, cause: fatal };\n\t\t}\n\t\t// RhinoComputeError thrown from handleResponse — already has full context.\n\t\t// Retryable only if it carries a retryable status code.\n\t\tif (error instanceof RhinoComputeError) {\n\t\t\tconst status = error.statusCode;\n\t\t\t// A 2xx whose body failed to parse UNDER A JSON CONTENT-TYPE\n\t\t\t// (NETWORK_ERROR from handleResponse) means the stream was cut mid-body —\n\t\t\t// as transient as any network error. A 2xx that declared a non-JSON body\n\t\t\t// arrives here as INVALID_RESPONSE (deterministic — captive portal /\n\t\t\t// login page) and deliberately does NOT match: it is never retried.\n\t\t\tconst isTruncatedSuccess =\n\t\t\t\terror.code === ErrorCodes.NETWORK_ERROR &&\n\t\t\t\tstatus !== undefined &&\n\t\t\t\tstatus >= 200 &&\n\t\t\t\tstatus < 300;\n\t\t\tconst retryable =\n\t\t\t\tisTruncatedSuccess ||\n\t\t\t\t(status !== undefined &&\n\t\t\t\t\t(RETRYABLE_STATUS.has(status) || (retryPolicy.retryOn429 && status === 429)));\n\t\t\tif (retryable && attempt < totalAttempts - 1) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\tretry: true,\n\t\t\t\t\tdelayMs: backoffDelay(attempt, retryPolicy),\n\t\t\t\t\tcause: error\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: false, retry: false, cause: error };\n\t\t}\n\n\t\t// Unknown — wrap and don't retry\n\t\treturn {\n\t\t\tok: false,\n\t\t\tretry: false,\n\t\t\tcause: new RhinoComputeError(\n\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t\tErrorCodes.UNKNOWN_ERROR,\n\t\t\t\t{\n\t\t\t\t\tcontext: { endpoint: ctx.endpoint, requestId: ctx.requestId },\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} finally {\n\t\tcleanup();\n\t}\n}\n\n/**\n * Generic Rhino Compute fetch function.\n * Sends a POST request to any Compute endpoint with pre-prepared arguments.\n *\n * Use this for advanced, low-level control over compute requests. For most use cases, prefer higher-level APIs.\n *\n * The transport is response-type-agnostic: it does not know which response a\n * given endpoint returns. Callers supply the response type via `R` (defaulting\n * to `unknown`, which forces an explicit narrowing before use).\n *\n * Timeout semantics: `config.timeoutMs` is a PER-ATTEMPT timeout, re-armed for\n * every retry. With `retry: { attempts: N }` the worst-case wall clock is\n * `(N + 1) × timeoutMs` plus backoff sleeps (and a server `Retry-After` can\n * stretch a single sleep up to 60s). For a hard overall deadline, pass\n * `config.signal` (e.g. `AbortSignal.timeout(totalMs)`) — a caller abort wins\n * immediately, including during backoff.\n *\n * Retry caveats: requests are POSTs, so a retry after a mid-flight connection\n * loss may re-execute a request the server already ran (see {@link RetryPolicy}).\n * A 2xx response that declares a non-JSON `Content-Type` (captive portal,\n * proxy login page) fails immediately with `INVALID_RESPONSE` and is never\n * retried; a body that fails to parse under a JSON content-type is treated as\n * a truncated stream and is retried.\n *\n * @typeParam R - The expected response shape. The caller names it at the call site.\n * @param endpoint - The Compute API endpoint (e.g., 'grasshopper', 'io', 'mesh').\n * @param args - Pre-prepared arguments for the request body.\n * @param config - Compute configuration (server URL, API key, timeout, debug, retry, signal).\n * @returns The parsed JSON response from the server, typed as `R`.\n *\n * @example\n * // Basic usage for the Grasshopper endpoint:\n * const response = await fetchRhinoCompute(\n * 'grasshopper',\n * { ... },\n * {\n * serverUrl: 'https://my-server.com',\n * debug: true,\n * timeoutMs: 30_000,\n * retry: { attempts: 2 },\n * signal: controller.signal,\n * }\n * );\n */\nexport async function fetchRhinoCompute<R = unknown>(\n\tendpoint: string,\n\targs: Record<string, any>,\n\tconfig: ComputeConfig\n): Promise<R> {\n\tconst requestId = generateRequestId();\n\tconst body = JSON.stringify(args);\n\t// Wire size in UTF-8 bytes — `body.length` counts UTF-16 code units and\n\t// undercounts non-ASCII payloads (matters for the 413 message and size logs).\n\tconst requestSize = utf8ByteLength(body);\n\tconst fullUrl = buildUrl(endpoint, config.serverUrl);\n\tconst headers = buildHeaders(requestId, config);\n\tconst retryPolicy = resolveRetryPolicy(config.retry);\n\tconst totalAttempts = retryPolicy.attempts + 1;\n\n\tif (config.debug) {\n\t\tconst sizeKb = (requestSize / 1024).toFixed(2);\n\t\tconst emoji = requestSize > 100000 ? '⚠️' : '🚀';\n\t\tlog(`${emoji} Starting compute request [${requestId}]: ${endpoint} (${sizeKb}KB)`, true);\n\t}\n\n\tconst ctx: AttemptContext = {\n\t\tendpoint,\n\t\tbody,\n\t\trequestSize,\n\t\tfullUrl,\n\t\trequestId,\n\t\theaders,\n\t\tconfig\n\t};\n\n\t// Every iteration ends in `return` or `throw` (issue 105): attemptFetch never\n\t// asks to retry on the final attempt (all its retry branches are gated on\n\t// `attempt < totalAttempts - 1`), so the exhausted-retries error is the final\n\t// attempt's own `result.cause` — there is no post-loop fallback to reach.\n\tfor (let attempt = 0; ; attempt++) {\n\t\tconst result = await attemptFetch(ctx, retryPolicy, attempt, totalAttempts);\n\n\t\tif (result.ok) return result.value as R;\n\n\t\tif (!result.retry) throw result.cause;\n\n\t\tif (config.debug) {\n\t\t\tlog(\n\t\t\t\t`🔁 Request [${requestId}] retrying after ${result.delayMs}ms (attempt ${attempt + 2}/${totalAttempts}): ${result.cause.message}`,\n\t\t\t\ttrue\n\t\t\t);\n\t\t}\n\n\t\ttry {\n\t\t\tawait sleep(result.delayMs, config.signal);\n\t\t} catch {\n\t\t\t// Caller cancelled during backoff\n\t\t\tthrow new RhinoComputeError('Request aborted by caller', ErrorCodes.ABORTED, {\n\t\t\t\tcontext: { endpoint, requestId, requestSize },\n\t\t\t\toriginalError: result.cause\n\t\t\t});\n\t\t}\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["d:\\Coding\\selva\\packages\\compute\\dist\\chunk-H3FZW6OX.cjs"],"names":[],"mappings":"AAAA,u8BAAI,CAAC,CAAC,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC,CAAC,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,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,EAAE,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,aAAa,CAAC,eAAe,CAAC,UAAU,CAAC,YAAY,CAAC,gBAAgB,CAAC,kBAAkB,CAAC,iBAAiB,CAAC,mBAAmB,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AAC,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAA;AACA;AACA","file":"D:\\Coding\\selva\\packages\\compute\\dist\\chunk-H3FZW6OX.cjs","sourcesContent":[null]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{b as l,c as h,d as c,e as y,h as Z,i as ee,k as te,l as re,m as O,n as M,o as ne,p as oe,s as p,t as j,v as F}from"./chunk-Y3M7P3BW.js";var se=new Set;function Ve(){if(typeof window>"u"||globalThis.process?.versions?.node!=null)return!1;let e=globalThis.navigator,r=typeof e?.userAgent=="string"?e.userAgent:"";return!/jsdom/i.test(r)}function D(t,e){e||Ve()&&!se.has(t)&&(se.add(t),y().warn(`Warning: ${t} is running on the client side. For better performance and security, consider running this on the server side.`))}function T(t){return typeof t=="object"&&!(t instanceof Uint8Array)&&typeof t.key=="string"&&typeof t.load=="function"}var Le="Unable to load grasshopper definition";function We(t){return t instanceof c?t.code===h.DEFINITION_NOT_CACHED||t.message.includes(Le):!1}function Be(t,e){if(!e)return;let r=p(t,"values");if(!Array.isArray(r)||r.length===0)return;let n=[];for(let s of r){let i=p(s,"innerTree");(!i||Object.keys(i).length===0)&&n.push(p(s,"paramName")??"<unnamed>")}if(n.length===0)return;let o=n.length===r.length?"all":`${n.length}/${r.length}`;y().warn(`Solve returned empty output(s) (${o}): ${n.join(", ")}. These parameters produced no data \u2014 check the definition's inputs and the branch feeding each.`)}async function E(t,e,r){D("solveGrasshopperDefinition",r.suppressBrowserWarning??r.suppressClientSideWarning);let n=await z(e),{response:o}=await N(v(n,t),r);return o}async function ie(t,e,r){D("solveGrasshopperDefinitionWithCacheKey",r.suppressBrowserWarning??r.suppressClientSideWarning);let n=await z(e);return N(v(n,t),r)}async function ae(t,e,r,n){D("solveByCacheKey",n.suppressBrowserWarning??n.suppressClientSideWarning);let o={algo:null,pointer:e,values:t};try{return{...await N(o,n),missed:!1}}catch(s){if(!We(s))throw s;let i=await z(r);return{...await N(v(i,t),n),missed:!0}}}async function z(t){if(!T(t))return t;try{return await t.load()}catch(e){throw new c(`Failed to load definition bytes for ref '${t.key}'`,h.INVALID_INPUT,{context:{definitionKey:t.key},originalError:e instanceof Error?e:new Error(String(e))})}}async function N(t,e){je(t,e);let r=await M("grasshopper",t,e),{pointer:n,algo:o,...s}=r,i=s,a=O(r);if(a!==void 0){let u=typeof o=="string"?o.length:0;re(i,Math.max(0,a-u))}return Be(i,e.debug),{response:i,cacheKey:typeof n=="string"?n:null}}function v(t,e){let r={algo:null,pointer:null,values:e};return t instanceof Uint8Array?r.algo=te(t):/^https?:\/\//i.test(t)?r.pointer=t:r.algo=ee(t)??Z(t),r}function je(t,e){e.cachesolve!=null&&(t.cachesolve=e.cachesolve),e.cacheerroredsolves!=null&&(t.cacheerroredsolves=e.cacheerroredsolves),e.modelunits!=null&&(t.modelunits=e.modelunits),e.angletolerance!=null&&(t.angletolerance=e.angletolerance),e.absolutetolerance!=null&&(t.absolutetolerance=e.absolutetolerance),e.dataversion!=null&&(t.dataversion=e.dataversion)}function $(t){let e=new WeakSet,r=n=>{if(n===void 0)return"undefined";if(n===null)return"null";if(typeof n=="number")return Number.isFinite(n)?String(n):"null";if(typeof n=="string"||typeof n=="boolean")return JSON.stringify(n);if(typeof n=="bigint")return`${n}n`;if(n instanceof Uint8Array)return`{"__u8":${n.length},"hash":"${le(n)}"}`;if(Array.isArray(n)){if(e.has(n))return'"[Circular]"';e.add(n);let o=[];for(let s=0;s<n.length;s++)o.push(r(n[s]));return e.delete(n),`[${o.join(",")}]`}if(typeof n=="object"){if(e.has(n))return'"[Circular]"';e.add(n);let o;return typeof n.toJSON=="function"?o=r(n.toJSON()):n instanceof Map?o=`{"__map":[${[...n.entries()].map(([i,a])=>`[${r(i)},${r(a)}]`).sort().join(",")}]}`:n instanceof Set?o=`{"__set":[${[...n.values()].map(r).sort().join(",")}]}`:o=`{${Object.keys(n).sort().map(a=>`${JSON.stringify(a)}:${r(n[a])}`).join(",")}}`,e.delete(n),o}return"null"};return r(t)}function ue(t,e){let r=2166136261;for(let n=0;n<t;n++)r^=e(n),r=r+((r<<1)+(r<<4)+(r<<7)+(r<<8)+(r<<24))>>>0;return r.toString(16).padStart(8,"0")}function pe(t){return ue(t.length,e=>t.charCodeAt(e))}function le(t){return ue(t.length,e=>t[e])}function ce(t,e){return q(R(t),e)}function q(t,e){let r=$(e);return`${t}|t:${r.length}:${pe(r)}`}function R(t){return T(t)?`r:${t.key}`:typeof t=="string"?`s:${t.length}:${pe(t)}`:`u8:${t.length}:${le(t)}`}var ze=100;function $e(t){return typeof t!="string"?!0:!/^https?:\/\//i.test(t)}function qe(t){try{return JSON.stringify(t)?.length??0}catch{return 0}}var x=class{constructor(e,r,n={},o){l(this,"executor");l(this,"baseConfig");l(this,"mode");l(this,"maxConcurrent");l(this,"maxQueueDepth");l(this,"queueWaitMs");l(this,"timeoutMs");l(this,"retry");l(this,"cacheEnabled");l(this,"cacheMax");l(this,"cacheMaxBytes");l(this,"cacheTtl");l(this,"cacheErroredSolves");l(this,"cache",new Map);l(this,"cacheBytes",0);l(this,"cacheKeyExecutor");l(this,"reuseServerDefinitionCache");l(this,"serverCacheKeys",new Map);l(this,"onStart");l(this,"onSettle");l(this,"onSuperseded");l(this,"subscribers",new Set);l(this,"inFlight",new Set);l(this,"pendingForLatestWins",null);l(this,"fifoQueue",[]);l(this,"_lastResult",null);l(this,"_lastError",null);l(this,"_lastDurationMs",null);l(this,"solveSeq",0);l(this,"lastStateSeq",0);l(this,"disposed",!1);this.executor=e,this.cacheKeyExecutor=o,this.baseConfig=r,this.mode=n.mode??"latest-wins",this.maxConcurrent=Math.max(1,n.maxConcurrent??(this.mode==="parallel"?4:1)),this.maxQueueDepth=n.maxQueueDepth!==void 0&&n.maxQueueDepth>0?Math.floor(n.maxQueueDepth):void 0,this.queueWaitMs=n.queueWaitMs!==void 0&&n.queueWaitMs>0?n.queueWaitMs:void 0,this.timeoutMs=n.timeoutMs,this.retry=n.retry;let s=n.cache;this.cacheEnabled=s!==void 0&&s!==!1;let i=typeof s=="object"?s:{};this.cacheMax=i.maxEntries??50,this.cacheMaxBytes=Math.max(0,i.maxBytes??0),this.cacheTtl=i.ttlMs??0,this.cacheErroredSolves=i.cacheErroredSolves??!0,this.reuseServerDefinitionCache=!!o&&(n.reuseServerDefinitionCache??!0),this.onStart=n.onStart,this.onSettle=n.onSettle,this.onSuperseded=n.onSuperseded}get isSolving(){return this.inFlight.size>0}get hasPending(){return this.pendingForLatestWins!==null||this.fifoQueue.length>0}get inFlightCount(){return this.inFlight.size}get queueDepth(){return this.fifoQueue.length+(this.pendingForLatestWins?1:0)}get lastResult(){return this._lastResult}get lastError(){return this._lastError}get lastDurationMs(){return this._lastDurationMs}subscribe(e){return this.subscribers.add(e),()=>this.subscribers.delete(e)}notify(){for(let e of this.subscribers)try{e()}catch(r){y().error("[SolveScheduler] subscriber threw:",r)}}solve(e,r,n){if(this.disposed)return Promise.reject(new c("SolveScheduler has been disposed and cannot be used",h.INVALID_STATE));let o=R(e),s=q(o,r),i=++this.solveSeq,a={key:s,enqueuedAt:Date.now(),startedAt:null};if(n?.signal?.aborted)return Promise.reject(this.makeAbortError(a));if(this.cacheEnabled){let u=this.readCache(s);if(u){this.mode==="latest-wins"&&this.supersedeCurrent();let m={status:"success",response:u,durationMs:0,fromCache:!0};return this.writeLastState(i,{result:u,durationMs:0}),this.runHook(this.onStart,a),this.runHook(this.onSettle,a,m),this.notify(),Promise.resolve(u)}}return new Promise((u,m)=>{let f={definition:e,dataTree:r,definitionHash:o,ctx:a,seq:i,resolve:u,reject:m,externalSignal:n?.signal};f.externalSignal&&(f.queuedAbortHandler=()=>this.abortQueuedItem(f),f.externalSignal.addEventListener("abort",f.queuedAbortHandler,{once:!0})),this.enqueue(f)})}writeLastState(e,r){return e<this.lastStateSeq?!1:(this.lastStateSeq=e,"result"in r?(this._lastResult=r.result,this._lastError=null):this._lastError=r.error,this._lastDurationMs=r.durationMs,!0)}supersedeCurrent(){this.pendingForLatestWins&&(this.supersede(this.pendingForLatestWins),this.pendingForLatestWins=null);for(let e of this.inFlight)this.supersede(e),e.controller.abort()}abortQueuedItem(e){this.pendingForLatestWins===e&&(this.pendingForLatestWins=null);let r=this.fifoQueue.indexOf(e);r>=0&&this.fifoQueue.splice(r,1),this.rejectAsAborted(e),this.notify()}shedAsQueueFull(e){let r=new c("Solve queue is full; request shed (backpressure)",h.QUEUE_FULL,{statusCode:503,context:{key:e.ctx.key,queueDepth:this.fifoQueue.length,maxQueueDepth:this.maxQueueDepth}});this.settleError(e,r)&&this.runHook(this.onSettle,e.ctx,{status:"error",error:r,durationMs:0}),this.notify()}armQueueWaitTimer(e){if(this.queueWaitMs===void 0)return;let r=this.queueWaitMs;e.queueWaitTimer=setTimeout(()=>{if(e.settled)return;let n=this.fifoQueue.indexOf(e);n>=0&&this.fifoQueue.splice(n,1);let o=new c(`Solve waited longer than ${r}ms in queue; shed (backpressure)`,h.QUEUE_TIMEOUT,{statusCode:503,context:{key:e.ctx.key,waitedMs:Date.now()-e.ctx.enqueuedAt,queueWaitMs:r}});this.settleError(e,o)&&this.runHook(this.onSettle,e.ctx,{status:"error",error:o,durationMs:0}),this.notify()},r)}clearQueueWaitTimer(e){e.queueWaitTimer!==void 0&&(clearTimeout(e.queueWaitTimer),e.queueWaitTimer=void 0)}enqueue(e){switch(this.mode){case"latest-wins":{this.supersedeCurrent(),this.inFlight.size===0?this.execute(e):this.pendingForLatestWins=e;break}case"queue":case"parallel":{this.inFlight.size<this.maxConcurrent?this.execute(e):this.maxQueueDepth!==void 0&&this.fifoQueue.length>=this.maxQueueDepth?this.shedAsQueueFull(e):(this.armQueueWaitTimer(e),this.fifoQueue.push(e));break}}this.notify()}async execute(e){let r=new AbortController,n=e;n.controller=r,this.inFlight.add(n),e.ctx.startedAt=Date.now(),this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e);let o=()=>r.abort();e.externalSignal?.addEventListener("abort",o,{once:!0}),this.runHook(this.onStart,e.ctx),this.notify();let s=performance.now();try{let i={...this.baseConfig,signal:r.signal,...this.timeoutMs!==void 0&&{timeoutMs:this.timeoutMs},...this.retry!==void 0&&{retry:this.retry}},{response:a,definitionReuploaded:u}=await this.runExecutor(e.definition,e.dataTree,e.definitionHash,i),m=performance.now()-s;if(this.cacheEnabled&&this.writeCache(e.ctx.key,a),!this.settleSuccess(e,a))return;this.writeLastState(e.seq,{result:a,durationMs:m}),this.runHook(this.onSettle,e.ctx,{status:"success",response:a,durationMs:m,fromCache:!1,definitionReuploaded:u})}catch(i){let a=performance.now()-s,u=this.normalizeExecutionError(i,n);this.writeLastState(e.seq,{error:u,durationMs:a}),this.settleError(e,u)&&this.runHook(this.onSettle,e.ctx,{status:"error",error:u,durationMs:a})}finally{e.externalSignal?.removeEventListener("abort",o),this.inFlight.delete(n),this.drainNext(),this.notify()}}async runExecutor(e,r,n,o){if(!this.cacheKeyExecutor||!this.reuseServerDefinitionCache||!$e(e))return{response:await this.executor(e,r,o)};let s=n,i=this.serverCacheKeys.get(s)??null,a=await this.cacheKeyExecutor(e,r,i,o);if(a.cacheKey)for(this.serverCacheKeys.delete(s),this.serverCacheKeys.set(s,a.cacheKey);this.serverCacheKeys.size>ze;){let u=this.serverCacheKeys.keys().next().value;if(u===void 0)break;this.serverCacheKeys.delete(u)}else this.serverCacheKeys.delete(s);return{response:a.response,definitionReuploaded:a.missed}}drainNext(){if(!this.disposed){if(this.mode==="latest-wins"){if(this.pendingForLatestWins&&this.inFlight.size===0){let e=this.pendingForLatestWins;this.pendingForLatestWins=null,this.execute(e)}return}for(;this.fifoQueue.length>0&&this.inFlight.size<this.maxConcurrent;){let e=this.fifoQueue.shift();this.execute(e)}}}supersede(e){let r=new c("Superseded by newer solve",h.SUPERSEDED,{context:{key:e.ctx.key,enqueuedAt:e.ctx.enqueuedAt}});this.settleError(e,r)&&this.runHook(this.onSuperseded,e.ctx)}makeAbortError(e){return new c("Request aborted by caller",h.ABORTED,{context:{key:e.key,enqueuedAt:e.enqueuedAt}})}settleError(e,r){return e.settled?!1:(e.settled={error:r},this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e),e.reject(r),!0)}settleSuccess(e,r){return e.settled?!1:(e.settled={ok:!0},this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e),e.resolve(r),!0)}removeQueuedAbortHandler(e){e.queuedAbortHandler&&e.externalSignal&&e.externalSignal.removeEventListener("abort",e.queuedAbortHandler),e.queuedAbortHandler=void 0}isAbortLikeError(e){if(e instanceof Error){if(e.name==="AbortError")return!0;if(typeof DOMException<"u"&&e instanceof DOMException)return e.name==="AbortError"}return!1}normalizeExecutionError(e,r){return r.settled&&"error"in r.settled?r.settled.error:e instanceof c?e:this.isAbortLikeError(e)?this.makeAbortError(r.ctx):new c(e instanceof Error?e.message:String(e),h.UNKNOWN_ERROR,{originalError:e instanceof Error?e:new Error(String(e))})}cancelAll(){for(this.pendingForLatestWins&&(this.rejectAsAborted(this.pendingForLatestWins),this.pendingForLatestWins=null);this.fifoQueue.length>0;){let e=this.fifoQueue.shift();this.rejectAsAborted(e)}for(let e of this.inFlight){let r=this.makeAbortError(e.ctx);this.settleError(e,r)&&this.runHook(this.onSettle,e.ctx,{status:"error",error:r,durationMs:e.ctx.startedAt?Date.now()-e.ctx.startedAt:0}),e.controller.abort()}this.notify()}rejectAsAborted(e){let r=this.makeAbortError(e.ctx);this.settleError(e,r)&&this.runHook(this.onSettle,e.ctx,{status:"error",error:r,durationMs:0})}readCache(e){if(!this.cacheEnabled)return null;let r=this.cache.get(e);return r?this.cacheTtl>0&&Date.now()-r.insertedAt>this.cacheTtl?(this.dropCacheEntry(e),null):(this.cache.delete(e),this.cache.set(e,r),r.response):null}writeCache(e,r){if(!this.cacheEnabled||!this.cacheErroredSolves&&r.errors&&r.errors.length>0)return;let n=O(r)??qe(r);if(!(this.cacheMaxBytes>0&&n>this.cacheMaxBytes))for(this.dropCacheEntry(e),this.cache.set(e,{response:r,insertedAt:Date.now(),sizeBytes:n}),this.cacheBytes+=n;(this.cache.size>this.cacheMax||this.cacheMaxBytes>0&&this.cacheBytes>this.cacheMaxBytes)&&this.cache.size>0;){let o=this.cache.keys().next().value;if(o===void 0)break;this.dropCacheEntry(o)}}dropCacheEntry(e){let r=this.cache.get(e);r&&(this.cache.delete(e),this.cacheBytes-=r.sizeBytes)}clearCache(){this.cache.clear(),this.cacheBytes=0}cacheStats(){return{entries:this.cache.size,bytes:this.cacheBytes}}dispose(){this.disposed||(this.disposed=!0,this.cancelAll(),this.subscribers.clear(),this.clearCache())}runHook(e,...r){if(e)try{e(...r)}catch(n){y().error("[SolveScheduler] hook threw:",n)}}};function fe(t){return T(t)?`ref:${t.key}`:typeof t=="string"&&t.length<200?t:"...content..."}function me(t){return Array.isArray(t)?t.map(e=>{let r=0,n=0,o=p(e,"innerTree");if(o&&typeof o=="object"){for(let s of Object.values(o))if(Array.isArray(s)){r+=s.length;for(let i of s){let a=i?.data;typeof a=="string"&&(n+=a.length)}}}return{param:p(e,"paramName")??"<unnamed>",items:r,bytes:n}}):[]}var A=class t{constructor(e){l(this,"config");l(this,"serverStats");l(this,"disposed",!1);this.config=this.normalizeComputeConfig(e),this.serverStats=new oe(this.config.serverUrl,this.config.apiKey)}static async create(e){let r=new t(e),n=Math.max(1,(e.retry?.attempts??2)+1),o=e.retry?.baseDelayMs??250,s=e.retry?.maxDelayMs??1e3;for(let i=0;i<n;i++){if(await r.serverStats.isServerOnline())return r;if(i<n-1){let a=Math.min(o*2**i,s);await new Promise(u=>setTimeout(u,a))}}throw await r.dispose(),new c("Rhino Compute server is not online",h.NETWORK_ERROR,{context:{serverUrl:r.config.serverUrl,attempts:n}})}getConfig(){return this.ensureNotDisposed(),{...this.config}}async getIO(e){return this.ensureNotDisposed(),G(e,this.config)}async getRawIO(e){return this.ensureNotDisposed(),P(e,this.config)}async solve(e,r,n){this.ensureNotDisposed();try{if(typeof e=="string"&&!e?.trim())throw new c("Definition URL/content is required",h.INVALID_INPUT,{context:{receivedUrl:e}});if(e instanceof Uint8Array&&e.length===0)throw new c("Definition content is empty",h.INVALID_INPUT);if(T(e)&&!e.key.trim())throw new c("DefinitionRef key is empty",h.INVALID_INPUT);let o={...this.config,...n?.signal!==void 0&&{signal:n.signal},...n?.timeoutMs!==void 0&&{timeoutMs:n.timeoutMs},...n?.retry!==void 0&&{retry:n.retry}},s=await E(r,e,o);if(s?.errors&&s.errors.length>0)throw new c(s.errors.join("; ")||"Computation failed",h.COMPUTATION_ERROR,{context:{definition:fe(e),inputSummary:me(r),errors:s.errors,warnings:s.warnings,values:s.values}});return s}catch(o){throw this.config.debug&&y().error("Compute failed:",o),o instanceof c?o:new c(o instanceof Error?o.message:String(o),h.COMPUTATION_ERROR,{context:{definition:fe(e),inputSummary:me(r)},originalError:o instanceof Error?o:new Error(String(o))})}}createScheduler(e){this.ensureNotDisposed();let r=(o,s,i)=>E(s,o,i),n=(o,s,i,a)=>i===null?ie(s,o,a).then(u=>({...u,missed:!1})):ae(s,i,o,a);return new x(r,this.config,e,n)}async dispose(){this.disposed||(this.disposed=!0,await this.serverStats.dispose())}ensureNotDisposed(){if(this.disposed)throw new c("GrasshopperClient has been disposed and cannot be used",h.INVALID_STATE)}normalizeComputeConfig(e){return{...e,serverUrl:ne(e.serverUrl),apiKey:e.apiKey,authToken:e.authToken,debug:e.debug??!1,suppressBrowserWarning:e.suppressBrowserWarning??e.suppressClientSideWarning}}};var V=new Map;function he(t,e){V.set(t,e)}he("Rhino.Geometry.Point3d",(t,e)=>{let r=e;return!r||typeof r.X!="number"?null:new t.Point([r.X,r.Y,r.Z])});he("Rhino.Geometry.Line",(t,e)=>{let r=e;return!r||!r.From||!r.To?null:new t.Line([r.From.X,r.From.Y,r.From.Z],[r.To.X,r.To.Y,r.To.Z])});function Ue(t){if(V.has(t))return V.get(t);for(let[e,r]of V)if(t.startsWith(e))return r}function _e(t){return!!(t&&typeof t=="object"&&typeof t.data=="string")}function de(t,e){return{__decodeError:!0,type:t,raw:e}}function ye(t,e,r){let n=Ue(e),o=!1;if(n)try{let s=n(r,t);if(s!=null)return s}catch(s){y().warn(`Failed to decode Rhino type ${e}:`,s),o=!0}try{if(_e(t))return r.CommonObject.decode(t)}catch(s){return y().warn(`Failed to decode ${e} with CommonObject:`,s),de(e,t)}return o?de(e,t):t}function ge(t){let e=new WeakSet,r=n=>{if(!n||typeof n!="object"||e.has(n))return;e.add(n);let o=n.delete;if(typeof o=="function"){let i=n.isDeleted;(typeof i!="function"||!i.call(n))&&o.call(n);return}if(Array.isArray(n)){for(let i of n)r(i);return}let s=Object.getPrototypeOf(n);if(s===Object.prototype||s===null)for(let i of Object.values(n))r(i)};r(t)}var I={STRING:"System.String",INT:"System.Int32",DOUBLE:"System.Double",BOOL:"System.Boolean"},Ke="Rhino.Geometry.",Qe=["WebDisplay"],He="FileData";function be(t){return Qe.some(e=>t.includes(e))}function Je(t){if(typeof t!="string")return t;let e=t.trim();if(!(e.startsWith("{")||e.startsWith("[")||e.startsWith('"')))return t;try{let n=JSON.parse(e);if(typeof n=="string")try{return JSON.parse(n)}catch{return n}return n}catch{return t}}function Ye(t,e,r){switch(e){case I.STRING:return typeof t!="string"?t:t.replace(/^"(.*)"$/,"$1");case I.INT:return Number.parseInt(t,10);case I.DOUBLE:return Number.parseFloat(t);case I.BOOL:return String(t).toLowerCase()==="true";default:return r&&e.startsWith(Ke)?ye(t,e,r):t}}var U=new WeakMap;function Te(t){if(U.has(t))return U.get(t);let e=Je(t.data);return U.set(t,e),e}function Se(t,e,r,n){if(typeof t.data!="string")return t.data;let o=r?Te(t):t.data;return Ye(o,e,n)}function Xe(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.fileName=="string"&&typeof e.fileType=="string"&&"data"in e&&typeof e.isBase64Encoded=="boolean"&&typeof e.subFolder=="string"}function _(t){let e=p(t,"values");return Array.isArray(e)?e:[]}function K(t){return typeof t.type=="string"?t.type:""}function Q(t,e){if(!(!t||typeof t!="object")){for(let r of Object.values(t))if(Array.isArray(r))for(let n of r)n&&typeof n=="object"&&e(n)}}function De(t,e=!1,r={}){let{parseValues:n=!0,rhino:o,stringOnly:s=!1}=r,i={},a=new Set;for(let u of _(t)){let m=p(u,"paramName");Q(p(u,"innerTree"),f=>{let d=K(f);if(be(d)||s&&d!==I.STRING)return;let g=e?f.id:m;if(!g)return;let b=Se(f,d,n,o);g in i?a.has(g)?i[g].push(b):(i[g]=[i[g],b],a.add(g)):i[g]=b})}return{values:i,dispose:()=>ge(i)}}function xe(t){let e=[];for(let r of _(t))Q(p(r,"innerTree"),n=>{if(!K(n).includes(He))return;let o=Te(n);Xe(o)&&e.push(o)});return e}function Ie(t,e,r={}){let{parseValues:n=!0,rhino:o,stringOnly:s=!1}=r;for(let i of _(t)){let a=p(i,"innerTree"),u=!1;if("byName"in e){if(p(i,"paramName")!==e.byName)continue;u=!0}let m=[];if(Q(a,f=>{if("byId"in e){if(f.id!==e.byId)return;u=!0}let d=K(f);be(d)||s&&d!==I.STRING||m.push(Se(f,d,n,o))}),u)return m.length===0?void 0:m.length===1?m[0]:m}}var k=class{constructor(e,r=!1){l(this,"response",e);l(this,"debug",r)}getValues(e=!1,r={}){return De(this.response,e,r)}getValue(e,r){return Ie(this.response,e,r)}async extractMeshesFromResponse(e){let r={debug:this.debug,...e},n;try{({getThreeMeshesFromComputeResponse:n}=await import("./visualization-BIHTM2KJ.js"))}catch(o){throw new c("Failed to load three.js visualization module. Ensure three.js is installed as a peer dependency.",h.INVALID_STATE,{context:{originalError:o instanceof Error?o.message:String(o)}})}return n(this.response,r)}getFileData(){return xe(this.response)}async getAndDownloadFiles(e,r){let n=this.getFileData();await F(n,e,r)}};var H=/^\{(-?\d+(?:;-?\d+)*)?\}$/;function C(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=Object.entries(t);return e.length>0&&e.every(([r,n])=>H.test(r)&&Array.isArray(n))}function w(t,e,r){if(t==null)return t;if(Array.isArray(t)){let o=t.map(e).filter(s=>s!==null);return o.length>0?o:void 0}let n=e(t);return n!==null?n:r?void 0:t}var L=t=>{if(typeof t=="number")return Number.isFinite(t)?t:null;if(typeof t=="string"){let e=t.trim();if(e===""||/^[+-]?0[xbo]/i.test(e))return null;let r=Number(e);return Number.isFinite(r)?r:null}return null},J=t=>{if(typeof t=="boolean")return t;if(typeof t=="string"){let e=t.trim().toLowerCase();if(e==="true")return!0;if(e==="false")return!1}return null},Ze=t=>typeof t=="string"?t.length>=2&&t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t.startsWith('"')?t.slice(1):t:null,et=t=>{if(typeof t=="string"){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')&&(e=e.slice(1,-1).trim()),e}return null};function we(t){return e=>{if(typeof e=="object"&&e!==null)return e;if(typeof e=="string"&&e.trim()!=="")try{let r=JSON.parse(e);return typeof r=="object"&&r!==null?r:(y().warn(`Parsed value for input ${t} is not an object`),null)}catch(r){return y().warn(`Failed to parse object value "${e}" for input ${t}`,r),null}return null}}function Ce(t,e,r){let n=Number(t.toFixed(e));return Math.abs(t-n)<r?n:t}function tt(t,e){if(!Number.isFinite(t)||t===0)return .1;let r=Math.abs(t);if(r>=1){let g=String(t).split(".")[1];if(g&&g.length>0){let b=Math.min(g.length,12),S=Math.pow(10,-b),X=Number(S.toFixed(b));return Math.abs(X-S)<e?X:S}return 1}let n=String(t),o=n.toLowerCase().match(/e(-?\d+)/);if(o){let d=Number(o[1]);if(d<0||n.toLowerCase().includes("e-")){let g=Math.abs(d),b=Math.pow(10,-g),S=Number(b.toFixed(g));return Math.abs(S-b)<e?S:b}return .1}let s=12,a=r.toFixed(s).replace(/0+$/,""),u=Math.min((a.split(".")[1]||"").length,s);if(u===0)return .1;let m=Math.pow(10,-u),f=Number(m.toFixed(u));return Math.abs(f-m)<e?f:m}function Ee(t){return typeof t.stepSize=="number"&&Number.isFinite(t.stepSize)&&t.stepSize>0?t.stepSize:void 0}function rt(t,e=1e-8){let r=t.paramType==="Integer",n=Ee(t);if(C(t.default))return{default:t.default,stepSize:n??(r?1:.1)};if(typeof t.default=="string"&&t.default.trim()!==""&&L(t.default)===null)throw new c(`Invalid numeric default "${t.default}" for input "${t.name||"unknown"}"`,h.VALIDATION_ERROR,{context:{inputName:t.name,default:t.default}});let o=w(t.default,L,!0);if(r)return Array.isArray(o)?o=o.map(d=>typeof d=="number"?Math.round(d):d):typeof o=="number"&&(o=Math.round(o)),{default:o,stepSize:n??1};let s=Array.isArray(o)?o[0]:o,i;typeof s=="number"&&Number.isFinite(s)&&s!==0?i=s:typeof t.minimum=="number"&&Number.isFinite(t.minimum)&&t.minimum!==0?i=t.minimum:typeof t.maximum=="number"&&Number.isFinite(t.maximum)&&t.maximum!==0&&(i=t.maximum);let a=n??(i!==void 0?tt(i,e):.1),u=0,m=String(a),f=m.toLowerCase().match(/e(-?\d+)/);if(f?u=Math.abs(Number(f[1])):u=m.split(".")[1]?.length??0,u===0&&typeof s=="number"&&s!==0&&Math.abs(s)<1){let d=Math.ceil(-Math.log10(Math.abs(s)));Number.isFinite(d)&&d>0&&(u=d)}return u=Math.min(Math.max(u,0),12),Array.isArray(o)?o=o.map(d=>typeof d=="number"?Ce(d,u,e):d):typeof o=="number"&&(o=Ce(o,u,e)),{default:o,stepSize:a}}var nt={types:["Number","Integer"],parse(t,e){let{default:r,stepSize:n}=rt(t);return{...e,paramType:t.paramType,minimum:t.minimum,maximum:t.maximum,atLeast:t.atLeast,atMost:t.atMost,stepSize:n,default:r}},fallback(t,e){let r=(t.atMost??1)>1,n=typeof t.minimum=="number"&&Number.isFinite(t.minimum)&&t.minimum>0?t.minimum:0;return{...e,paramType:t.paramType,minimum:t.minimum,maximum:t.maximum,atLeast:t.atLeast,atMost:t.atMost,stepSize:Ee(t)??(t.paramType==="Integer"?1:.1),default:r?[n]:n}}},ot={types:["Boolean"],parse(t,e){if(C(t.default))return{...e,paramType:"Boolean",default:t.default};let r=w(t.default,J,!1);if(r!=null&&typeof r!="boolean"&&!Array.isArray(r))throw new c(`Invalid boolean default "${String(r)}" for input "${t.name||"unknown"}"`,h.VALIDATION_ERROR,{context:{inputName:t.name,default:t.default}});return{...e,paramType:"Boolean",default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"Boolean",default:r?[!1]:!1}}},st={types:["Text"],parse(t,e){let r=w(t.default,Ze,!1);return{...e,paramType:"Text",default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"Text",default:r?[""]:""}}},it={types:["ValueList"],parse(t,e){if(!t.values||typeof t.values!="object"||Object.keys(t.values).length===0)throw c.missingValues(t.nickname||"unnamed","ValueList");let r=t.default;if(t.default!==void 0&&t.default!==null){if(typeof t.default=="object")throw new c(`ValueList input "${t.nickname||"unnamed"}" default is not a string-able value`,h.VALIDATION_ERROR,{context:{inputName:t.name,default:t.default}});let n=String(t.default).toLowerCase(),o=Object.keys(t.values).find(s=>s.toLowerCase()===n);o!==void 0?r=o:y().warn(`ValueList input "${t.nickname||"unnamed"}" default value "${t.default}" is not in available values`)}return{...e,paramType:"ValueList",values:t.values,default:r}},fallback(t,e){return{...e,paramType:"ValueList",values:t.values&&typeof t.values=="object"?t.values:{},default:void 0}}},ve={types:["Geometry"],parse(t,e){let r=w(t.default,we(t.nickname||"unnamed"),!0);return{...e,paramType:"Geometry",default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"Geometry",default:r?[null]:null}}},at={types:["File"],parse(t,e){let r=w(t.default,we(t.nickname||"unnamed"),!0);return{...e,paramType:"File",acceptedFormats:t.acceptedFormats,default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"File",default:r?[null]:null}}},ut={types:["Color"],parse(t,e){let r=w(t.default,et,!1);return{...e,paramType:"Color",default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"Color",default:r?["0, 0, 0"]:"0, 0, 0"}}},pt=[nt,ot,st,it,ve,at,ut],Y=new Map(pt.flatMap(t=>t.types.map(e=>[e,t]))),Re=ve;function Ae(t){return p(t,"data")}function lt(t){return p(t,"type")}var ct=new Set(["System.Double","System.Single","System.Decimal","System.Int32","System.Int64"]),ft=new Set(["System.Int32","System.Int64"]);function Pe(t){if(typeof t.default!="object"||t.default===null)return{schema:t};if(Array.isArray(t.default))return{schema:t};if(!j(t.default,"innerTree")){let n=`Input "${t.name??"unknown"}" default had an unrecognized shape (no innerTree key); the default was dropped.`;return y().warn("Unexpected structure in input.default:",t.default),{schema:{...t,default:null},warning:{code:"MALFORMED_DEFAULT",message:n}}}let e=p(t.default,"innerTree")??{};if(Object.keys(e).length===0)return{schema:{...t,default:void 0}};if(t.treeAccess||t.atMost&&t.atMost>1){let n={},o=[];for(let[i,a]of Object.entries(e)){if(!Array.isArray(a)){let m=`Input "${t.name??"unknown"}" default had a non-array innerTree branch ("${i}"); the default was dropped.`;return y().warn("Unexpected structure in input.default innerTree:",t.default),{schema:{...t,default:null},warning:{code:"MALFORMED_DEFAULT",message:m}}}let u=[];for(let m of a){let f=Ae(m),d=lt(m);if(d&&ct.has(d)){if(typeof f=="string"&&f.trim()==="")continue;let g=L(f);if(g===null){o.push(`"${String(f)}" (${d})`);continue}u.push(ft.has(d)?Math.round(g):g);continue}if(d==="System.Boolean"){let g=J(f);if(g===null){o.push(`"${String(f)}" (${d})`);continue}u.push(g);continue}if(typeof f=="string"&&d?.startsWith("Rhino.Geometry")){try{u.push(JSON.parse(f))}catch{u.push(f)}continue}u.push(f)}n[i]=u}let s;if(o.length>0){let i=`Input "${t.name??"unknown"}" default contained ${o.length} tree value(s) that could not be parsed and were dropped: ${o.join(", ")}.`;y().warn(i),s={code:"MALFORMED_DEFAULT",message:i}}return{schema:{...t,default:n},...s&&{warning:s}}}let r=[];for(let n of Object.values(e))Array.isArray(n)&&n.forEach(o=>{o&&typeof o=="object"&&j(o,"data")&&r.push(Ae(o))});return r.length===0?{schema:{...t,default:void 0}}:r.length===1?{schema:{...t,default:r[0]}}:{schema:{...t,default:r}}}var mt=new Map([...Y.keys()].map(t=>[t.toLowerCase(),t]));function dt(t){return mt.get(t?.toLowerCase())??t}function ke(t){return Oe(t).input}function Oe(t){let e={description:t.description,name:t.name,nickname:t.nickname,treeAccess:t.treeAccess,groupName:t.groupName??void 0,id:t.id},r=dt(t.paramType),n={...t,paramType:r},o;try{let{schema:i,warning:a}=Pe(n);n=i,o=a&&{inputName:t.name||"unknown",paramType:t.paramType,message:a.message,code:a.code}}catch(i){n={...n,default:null},o={inputName:t.name||"unknown",paramType:t.paramType,message:`Input "${t.name??"unknown"}" default could not be normalized and was dropped: ${i instanceof Error?i.message:String(i)}`,code:"MALFORMED_DEFAULT"}}let s=Y.get(r);try{if(!s)throw c.unknownParamType(r,t.name);return{input:s.parse(n,e),error:o,...o&&{errors:[o]}}}catch(i){if(i instanceof c){y().error(`Validation error for input ${t.name||"unknown"}:`,i.message);let a={inputName:t.name||"unknown",paramType:t.paramType,message:i.message,code:i.code};return{input:(s??Re).fallback(n,e),error:a,errors:o?[o,a]:[a]}}throw new c(i instanceof Error?i.message:String(i),"VALIDATION_ERROR",{context:{paramName:t.name,paramType:r},originalError:i instanceof Error?i:new Error(String(i))})}}function Me(t){return W(t).inputs}function W(t){let e=[],r=[];for(let n of t){let{input:o,errors:s}=Oe(n);e.push(o),s&&r.push(...s)}return{inputs:e,parseErrors:r}}function Fe(t){let e=p(t,"stepSize");return{id:p(t,"id")??"",name:p(t,"name")??"",nickname:p(t,"nickname")??null,description:p(t,"description")??"",paramType:p(t,"paramType")??"",treeAccess:p(t,"treeAccess")??!1,minimum:p(t,"minimum")??null,maximum:p(t,"maximum")??null,atLeast:p(t,"atLeast")??1,atMost:p(t,"atMost")??1,stepSize:typeof e=="number"&&Number.isFinite(e)?e:void 0,default:p(t,"default"),values:p(t,"values"),acceptedFormats:p(t,"acceptedFormats"),groupName:p(t,"groupName")??null}}function Ne(t){return{name:p(t,"name")??"",nickname:p(t,"nickname")??null,paramType:p(t,"paramType")??"",id:p(t,"id")??""}}async function P(t,e){let r=v(t,[]),n={};if(r.algo&&(n.algo=r.algo),r.pointer&&(n.pointer=r.pointer),!n.algo&&!n.pointer)throw new c("Definition must resolve to either a URL pointer or base64 algo",h.INVALID_INPUT,{context:{definition:t}});let o=await M("io",n,e);if(!o||typeof o!="object")throw new c("Invalid IO response structure",h.INVALID_INPUT,{context:{response:o,definition:t}});let s=Ge(p(o,"warnings")),i=Ge(p(o,"errors")),a=p(o,"inputs"),u=p(o,"outputs");return{inputs:Array.isArray(a)?a.map(Fe):[],outputs:Array.isArray(u)?u.map(Ne):[],...s&&{loadWarnings:s},...i&&{loadErrors:i}}}function Ge(t){if(!Array.isArray(t))return;let e=t.map(ht).filter(r=>r!==void 0);return e.length>0?e:void 0}function ht(t){if(t==null)return;let e;if(typeof t=="string")e=t;else if(typeof t=="object"){let r=p(t,"message");if(typeof r=="string"&&r.trim().length>0)e=r;else try{e=JSON.stringify(t)??String(t)}catch{e=String(t)}}else e=String(t);return e.trim().length>0?e:void 0}async function G(t,e){D("fetchParsedDefinitionIO",e.suppressBrowserWarning??e.suppressClientSideWarning);let{inputs:r,outputs:n,loadWarnings:o,loadErrors:s}=await P(t,e),{inputs:i,parseErrors:a}=W(r);return{inputs:i,outputs:n,...a.length>0&&{parseErrors:a},...o&&{loadWarnings:o},...s&&{loadErrors:s}}}var B=class t{constructor(e){l(this,"innerTree");l(this,"paramName");this.paramName=e,this.innerTree={}}append(e,r){let n=t.formatPathString(e);this.innerTree[n]||(this.innerTree[n]=[]);let o=r.map(s=>({data:t.serializeValue(s)}));return this.innerTree[n].push(...o),this}appendSingle(e,r){return this.append(e,[r])}fromDataTreeDefault(e){this.innerTree={};for(let[r,n]of Object.entries(e)){if(!Array.isArray(n))continue;let o=t.parsePathString(r);this.append(o,n)}return this}appendFlat(e){let r=Array.isArray(e)?e:[e];return this.append([0],r)}flatten(){let e=[];for(let r of Object.values(this.innerTree))if(Array.isArray(r))for(let n of r)e.push(t.deserializeValue(n.data));return e}getPaths(){return Object.keys(this.innerTree)}getPath(e){let r=t.formatPathString(e),n=this.innerTree[r];if(n)return n.map(o=>t.deserializeValue(o.data))}toComputeFormat(){return{ParamName:this.paramName,InnerTree:this.innerTree}}getInnerTree(){return this.innerTree}getParamName(){return this.paramName}static fromInputParams(e){return e.filter(r=>t.hasValidValue(r.default)).map(r=>{let n=new t(r.nickname||"unnamed"),o=r.default;if(r.treeAccess&&C(o))n.fromDataTreeDefault(o),t.isNumericInput(r)&&n.applyNumericConstraints(r.minimum,r.maximum,r.nickname||"unnamed");else{let s=Array.isArray(o)?o:[o],i=t.processValues(s,r);n.appendFlat(i)}return n.toComputeFormat()})}static fromInputParam(e){return t.hasValidValue(e.default)?t.fromInputParams([e])[0]:void 0}static replaceTreeValue(e,r,n){let o=e.length>0&&e[0]instanceof t,s=t.buildFromValue(r,n);if(o){let m=e.slice(),f=m.findIndex(d=>d.getParamName()===r);return f!==-1?m[f]=s:m.push(s),m}let i=e.slice(),a=s.toComputeFormat(),u=i.findIndex(m=>m.ParamName===r);return u!==-1?i[u]=a:i.push(a),i}static buildFromValue(e,r){let n=new t(e);return C(r)?n.fromDataTreeDefault(r):n.appendFlat(r),n}static getTreeValue(e,r){let o=e.length>0&&e[0]instanceof t?t.readFromBuilders(e,r):t.readFromDataTrees(e,r);return o===null||o.length===0?null:o.length===1?o[0]:o}static readFromBuilders(e,r){let n=e.find(o=>o.getParamName()===r);return n?n.flatten():null}static readFromDataTrees(e,r){let n=e.find(i=>i.ParamName===r);if(!n?.InnerTree)return null;let o=Object.keys(n.InnerTree)[0];if(!o)return null;let s=n.InnerTree[o];return Array.isArray(s)?s.map(i=>i?.data!==void 0?t.deserializeValue(i.data):null):s?.data!==void 0?[t.deserializeValue(s.data)]:s!==void 0?[s]:null}static parsePathString(e){let r=e.match(H);if(!r)throw new Error(`Invalid Grasshopper tree path: "${e}". Expected "{}", "{0}", or "{0;1;2}" (negative indices allowed, no empty segments).`);return r[1]?r[1].split(";").map(Number):[]}static formatPathString(e){return`{${e.join(";")}}`}applyNumericConstraints(e,r,n){for(let o of Object.values(this.innerTree))if(Array.isArray(o))for(let s of o){let i=t.deserializeValue(s.data);if(typeof i=="number"){let a=t.clampValue(i,e,r,n);s.data=t.serializeValue(a)}}}static serializeValue(e){return typeof e=="boolean"||typeof e=="number"||typeof e=="string"?e:typeof e=="object"&&e!==null?JSON.stringify(e):String(e)}static deserializeValue(e){if(typeof e=="boolean"||typeof e=="number"||typeof e!="string")return e;if(e.startsWith("{")||e.startsWith("["))try{return JSON.parse(e)}catch{return e}let r=Number(e);return Number.isFinite(r)&&String(r)===e?r:e==="true"?!0:e==="false"?!1:e}static hasValidValue(e){return e==null?!1:typeof e=="string"?!0:!(Array.isArray(e)&&e.length===0||typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0)}static isNumericInput(e){return e.paramType==="Number"||e.paramType==="Integer"}static processValues(e,r){return e.map(n=>t.isNumericInput(r)&&typeof n=="number"?t.clampValue(n,r.minimum,r.maximum,r.nickname||"unnamed"):n).filter(n=>n!=null)}static clampValue(e,r,n,o){let s=e;return r!=null&&s<r&&(y().warn(`${o}: ${e} below min ${r}, clamping`),s=r),n!=null&&s>n&&(y().warn(`${o}: ${e} above max ${n}, clamping`),s=n),s}};export{T as a,E as b,$ as c,ce as d,R as e,x as f,A as g,k as h,ke as i,Me as j,P as k,G as l,B as m};
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{b as l,c as h,d as c,e as y,h as Z,i as ee,k as te,l as re,m as O,n as M,o as ne,p as oe,s as p,t as j,v as F}from"./chunk-Y3M7P3BW.js";var se=new Set;function Ve(){if(typeof window>"u"||globalThis.process?.versions?.node!=null)return!1;let e=globalThis.navigator,r=typeof e?.userAgent=="string"?e.userAgent:"";return!/jsdom/i.test(r)}function D(t,e){e||Ve()&&!se.has(t)&&(se.add(t),y().warn(`Warning: ${t} is running on the client side. For better performance and security, consider running this on the server side.`))}function T(t){return typeof t=="object"&&!(t instanceof Uint8Array)&&typeof t.key=="string"&&typeof t.load=="function"}var Le="Unable to load grasshopper definition";function We(t){return t instanceof c?t.code===h.DEFINITION_NOT_CACHED||t.message.includes(Le):!1}function Be(t,e){if(!e)return;let r=p(t,"values");if(!Array.isArray(r)||r.length===0)return;let n=[];for(let s of r){let i=p(s,"innerTree");(!i||Object.keys(i).length===0)&&n.push(p(s,"paramName")??"<unnamed>")}if(n.length===0)return;let o=n.length===r.length?"all":`${n.length}/${r.length}`;y().warn(`Solve returned empty output(s) (${o}): ${n.join(", ")}. These parameters produced no data \u2014 check the definition's inputs and the branch feeding each.`)}async function E(t,e,r){D("solveGrasshopperDefinition",r.suppressBrowserWarning??r.suppressClientSideWarning);let n=await z(e),{response:o}=await N(v(n,t),r);return o}async function ie(t,e,r){D("solveGrasshopperDefinitionWithCacheKey",r.suppressBrowserWarning??r.suppressClientSideWarning);let n=await z(e);return N(v(n,t),r)}async function ae(t,e,r,n){D("solveByCacheKey",n.suppressBrowserWarning??n.suppressClientSideWarning);let o={algo:null,pointer:e,values:t};try{return{...await N(o,n),missed:!1}}catch(s){if(!We(s))throw s;let i=await z(r);return{...await N(v(i,t),n),missed:!0}}}async function z(t){if(!T(t))return t;try{return await t.load()}catch(e){throw new c(`Failed to load definition bytes for ref '${t.key}'`,h.INVALID_INPUT,{context:{definitionKey:t.key},originalError:e instanceof Error?e:new Error(String(e))})}}async function N(t,e){je(t,e);let r=await M("grasshopper",t,e),{pointer:n,algo:o,...s}=r,i=s,a=O(r);if(a!==void 0){let u=typeof o=="string"?o.length:0;re(i,Math.max(0,a-u))}return Be(i,e.debug),{response:i,cacheKey:typeof n=="string"?n:null}}function v(t,e){let r={algo:null,pointer:null,values:e};return t instanceof Uint8Array?r.algo=te(t):/^https?:\/\//i.test(t)?r.pointer=t:r.algo=ee(t)??Z(t),r}function je(t,e){e.cachesolve!=null&&(t.cachesolve=e.cachesolve),e.cacheerroredsolves!=null&&(t.cacheerroredsolves=e.cacheerroredsolves),e.modelunits!=null&&(t.modelunits=e.modelunits),e.angletolerance!=null&&(t.angletolerance=e.angletolerance),e.absolutetolerance!=null&&(t.absolutetolerance=e.absolutetolerance),e.dataversion!=null&&(t.dataversion=e.dataversion)}function $(t){let e=new WeakSet,r=n=>{if(n===void 0)return"undefined";if(n===null)return"null";if(typeof n=="number")return Number.isFinite(n)?String(n):"null";if(typeof n=="string"||typeof n=="boolean")return JSON.stringify(n);if(typeof n=="bigint")return`${n}n`;if(n instanceof Uint8Array)return`{"__u8":${n.length},"hash":"${le(n)}"}`;if(Array.isArray(n)){if(e.has(n))return'"[Circular]"';e.add(n);let o=[];for(let s=0;s<n.length;s++)o.push(r(n[s]));return e.delete(n),`[${o.join(",")}]`}if(typeof n=="object"){if(e.has(n))return'"[Circular]"';e.add(n);let o;return typeof n.toJSON=="function"?o=r(n.toJSON()):n instanceof Map?o=`{"__map":[${[...n.entries()].map(([i,a])=>`[${r(i)},${r(a)}]`).sort().join(",")}]}`:n instanceof Set?o=`{"__set":[${[...n.values()].map(r).sort().join(",")}]}`:o=`{${Object.keys(n).sort().map(a=>`${JSON.stringify(a)}:${r(n[a])}`).join(",")}}`,e.delete(n),o}return"null"};return r(t)}function ue(t,e){let r=2166136261;for(let n=0;n<t;n++)r^=e(n),r=r+((r<<1)+(r<<4)+(r<<7)+(r<<8)+(r<<24))>>>0;return r.toString(16).padStart(8,"0")}function pe(t){return ue(t.length,e=>t.charCodeAt(e))}function le(t){return ue(t.length,e=>t[e])}function ce(t,e){return q(R(t),e)}function q(t,e){let r=$(e);return`${t}|t:${r.length}:${pe(r)}`}function R(t){return T(t)?`r:${t.key}`:typeof t=="string"?`s:${t.length}:${pe(t)}`:`u8:${t.length}:${le(t)}`}var ze=100;function $e(t){return typeof t!="string"?!0:!/^https?:\/\//i.test(t)}function qe(t){try{return JSON.stringify(t)?.length??0}catch{return 0}}var x=class{constructor(e,r,n={},o){l(this,"executor");l(this,"baseConfig");l(this,"mode");l(this,"maxConcurrent");l(this,"maxQueueDepth");l(this,"queueWaitMs");l(this,"timeoutMs");l(this,"retry");l(this,"cacheEnabled");l(this,"cacheMax");l(this,"cacheMaxBytes");l(this,"cacheTtl");l(this,"cacheErroredSolves");l(this,"cache",new Map);l(this,"cacheBytes",0);l(this,"cacheKeyExecutor");l(this,"reuseServerDefinitionCache");l(this,"serverCacheKeys",new Map);l(this,"onStart");l(this,"onSettle");l(this,"onSuperseded");l(this,"subscribers",new Set);l(this,"inFlight",new Set);l(this,"pendingForLatestWins",null);l(this,"fifoQueue",[]);l(this,"_lastResult",null);l(this,"_lastError",null);l(this,"_lastDurationMs",null);l(this,"solveSeq",0);l(this,"lastStateSeq",0);l(this,"disposed",!1);this.executor=e,this.cacheKeyExecutor=o,this.baseConfig=r,this.mode=n.mode??"latest-wins",this.maxConcurrent=Math.max(1,n.maxConcurrent??(this.mode==="parallel"?4:1)),this.maxQueueDepth=n.maxQueueDepth!==void 0&&n.maxQueueDepth>0?Math.floor(n.maxQueueDepth):void 0,this.queueWaitMs=n.queueWaitMs!==void 0&&n.queueWaitMs>0?n.queueWaitMs:void 0,this.timeoutMs=n.timeoutMs,this.retry=n.retry;let s=n.cache;this.cacheEnabled=s!==void 0&&s!==!1;let i=typeof s=="object"?s:{};this.cacheMax=i.maxEntries??50,this.cacheMaxBytes=Math.max(0,i.maxBytes??0),this.cacheTtl=i.ttlMs??0,this.cacheErroredSolves=i.cacheErroredSolves??!0,this.reuseServerDefinitionCache=!!o&&(n.reuseServerDefinitionCache??!0),this.onStart=n.onStart,this.onSettle=n.onSettle,this.onSuperseded=n.onSuperseded}get isSolving(){return this.inFlight.size>0}get hasPending(){return this.pendingForLatestWins!==null||this.fifoQueue.length>0}get inFlightCount(){return this.inFlight.size}get queueDepth(){return this.fifoQueue.length+(this.pendingForLatestWins?1:0)}get lastResult(){return this._lastResult}get lastError(){return this._lastError}get lastDurationMs(){return this._lastDurationMs}subscribe(e){return this.subscribers.add(e),()=>this.subscribers.delete(e)}notify(){for(let e of this.subscribers)try{e()}catch(r){y().error("[SolveScheduler] subscriber threw:",r)}}solve(e,r,n){if(this.disposed)return Promise.reject(new c("SolveScheduler has been disposed and cannot be used",h.INVALID_STATE));let o=R(e),s=q(o,r),i=++this.solveSeq,a={key:s,enqueuedAt:Date.now(),startedAt:null};if(n?.signal?.aborted)return Promise.reject(this.makeAbortError(a));if(this.cacheEnabled){let u=this.readCache(s);if(u){this.mode==="latest-wins"&&this.supersedeCurrent();let m={status:"success",response:u,durationMs:0,fromCache:!0};return this.writeLastState(i,{result:u,durationMs:0}),this.runHook(this.onStart,a),this.runHook(this.onSettle,a,m),this.notify(),Promise.resolve(u)}}return new Promise((u,m)=>{let f={definition:e,dataTree:r,definitionHash:o,ctx:a,seq:i,resolve:u,reject:m,externalSignal:n?.signal};f.externalSignal&&(f.queuedAbortHandler=()=>this.abortQueuedItem(f),f.externalSignal.addEventListener("abort",f.queuedAbortHandler,{once:!0})),this.enqueue(f)})}writeLastState(e,r){return e<this.lastStateSeq?!1:(this.lastStateSeq=e,"result"in r?(this._lastResult=r.result,this._lastError=null):this._lastError=r.error,this._lastDurationMs=r.durationMs,!0)}supersedeCurrent(){this.pendingForLatestWins&&(this.supersede(this.pendingForLatestWins),this.pendingForLatestWins=null);for(let e of this.inFlight)this.supersede(e),e.controller.abort()}abortQueuedItem(e){this.pendingForLatestWins===e&&(this.pendingForLatestWins=null);let r=this.fifoQueue.indexOf(e);r>=0&&this.fifoQueue.splice(r,1),this.rejectAsAborted(e),this.notify()}shedAsQueueFull(e){let r=new c("Solve queue is full; request shed (backpressure)",h.QUEUE_FULL,{statusCode:503,context:{key:e.ctx.key,queueDepth:this.fifoQueue.length,maxQueueDepth:this.maxQueueDepth}});this.settleError(e,r)&&this.runHook(this.onSettle,e.ctx,{status:"error",error:r,durationMs:0}),this.notify()}armQueueWaitTimer(e){if(this.queueWaitMs===void 0)return;let r=this.queueWaitMs;e.queueWaitTimer=setTimeout(()=>{if(e.settled)return;let n=this.fifoQueue.indexOf(e);n>=0&&this.fifoQueue.splice(n,1);let o=new c(`Solve waited longer than ${r}ms in queue; shed (backpressure)`,h.QUEUE_TIMEOUT,{statusCode:503,context:{key:e.ctx.key,waitedMs:Date.now()-e.ctx.enqueuedAt,queueWaitMs:r}});this.settleError(e,o)&&this.runHook(this.onSettle,e.ctx,{status:"error",error:o,durationMs:0}),this.notify()},r)}clearQueueWaitTimer(e){e.queueWaitTimer!==void 0&&(clearTimeout(e.queueWaitTimer),e.queueWaitTimer=void 0)}enqueue(e){switch(this.mode){case"latest-wins":{this.supersedeCurrent(),this.inFlight.size===0?this.execute(e):this.pendingForLatestWins=e;break}case"queue":case"parallel":{this.inFlight.size<this.maxConcurrent?this.execute(e):this.maxQueueDepth!==void 0&&this.fifoQueue.length>=this.maxQueueDepth?this.shedAsQueueFull(e):(this.armQueueWaitTimer(e),this.fifoQueue.push(e));break}}this.notify()}async execute(e){let r=new AbortController,n=e;n.controller=r,this.inFlight.add(n),e.ctx.startedAt=Date.now(),this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e);let o=()=>r.abort();e.externalSignal?.addEventListener("abort",o,{once:!0}),this.runHook(this.onStart,e.ctx),this.notify();let s=performance.now();try{let i={...this.baseConfig,signal:r.signal,...this.timeoutMs!==void 0&&{timeoutMs:this.timeoutMs},...this.retry!==void 0&&{retry:this.retry}},{response:a,definitionReuploaded:u}=await this.runExecutor(e.definition,e.dataTree,e.definitionHash,i),m=performance.now()-s;if(this.cacheEnabled&&this.writeCache(e.ctx.key,a),!this.settleSuccess(e,a))return;this.writeLastState(e.seq,{result:a,durationMs:m}),this.runHook(this.onSettle,e.ctx,{status:"success",response:a,durationMs:m,fromCache:!1,definitionReuploaded:u})}catch(i){let a=performance.now()-s,u=this.normalizeExecutionError(i,n);this.writeLastState(e.seq,{error:u,durationMs:a}),this.settleError(e,u)&&this.runHook(this.onSettle,e.ctx,{status:"error",error:u,durationMs:a})}finally{e.externalSignal?.removeEventListener("abort",o),this.inFlight.delete(n),this.drainNext(),this.notify()}}async runExecutor(e,r,n,o){if(!this.cacheKeyExecutor||!this.reuseServerDefinitionCache||!$e(e))return{response:await this.executor(e,r,o)};let s=n,i=this.serverCacheKeys.get(s)??null,a=await this.cacheKeyExecutor(e,r,i,o);if(a.cacheKey)for(this.serverCacheKeys.delete(s),this.serverCacheKeys.set(s,a.cacheKey);this.serverCacheKeys.size>ze;){let u=this.serverCacheKeys.keys().next().value;if(u===void 0)break;this.serverCacheKeys.delete(u)}else this.serverCacheKeys.delete(s);return{response:a.response,definitionReuploaded:a.missed}}drainNext(){if(!this.disposed){if(this.mode==="latest-wins"){if(this.pendingForLatestWins&&this.inFlight.size===0){let e=this.pendingForLatestWins;this.pendingForLatestWins=null,this.execute(e)}return}for(;this.fifoQueue.length>0&&this.inFlight.size<this.maxConcurrent;){let e=this.fifoQueue.shift();this.execute(e)}}}supersede(e){let r=new c("Superseded by newer solve",h.SUPERSEDED,{context:{key:e.ctx.key,enqueuedAt:e.ctx.enqueuedAt}});this.settleError(e,r)&&this.runHook(this.onSuperseded,e.ctx)}makeAbortError(e){return new c("Request aborted by caller",h.ABORTED,{context:{key:e.key,enqueuedAt:e.enqueuedAt}})}settleError(e,r){return e.settled?!1:(e.settled={error:r},this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e),e.reject(r),!0)}settleSuccess(e,r){return e.settled?!1:(e.settled={ok:!0},this.clearQueueWaitTimer(e),this.removeQueuedAbortHandler(e),e.resolve(r),!0)}removeQueuedAbortHandler(e){e.queuedAbortHandler&&e.externalSignal&&e.externalSignal.removeEventListener("abort",e.queuedAbortHandler),e.queuedAbortHandler=void 0}isAbortLikeError(e){if(e instanceof Error){if(e.name==="AbortError")return!0;if(typeof DOMException<"u"&&e instanceof DOMException)return e.name==="AbortError"}return!1}normalizeExecutionError(e,r){return r.settled&&"error"in r.settled?r.settled.error:e instanceof c?e:this.isAbortLikeError(e)?this.makeAbortError(r.ctx):new c(e instanceof Error?e.message:String(e),h.UNKNOWN_ERROR,{originalError:e instanceof Error?e:new Error(String(e))})}cancelAll(){for(this.pendingForLatestWins&&(this.rejectAsAborted(this.pendingForLatestWins),this.pendingForLatestWins=null);this.fifoQueue.length>0;){let e=this.fifoQueue.shift();this.rejectAsAborted(e)}for(let e of this.inFlight){let r=this.makeAbortError(e.ctx);this.settleError(e,r)&&this.runHook(this.onSettle,e.ctx,{status:"error",error:r,durationMs:e.ctx.startedAt?Date.now()-e.ctx.startedAt:0}),e.controller.abort()}this.notify()}rejectAsAborted(e){let r=this.makeAbortError(e.ctx);this.settleError(e,r)&&this.runHook(this.onSettle,e.ctx,{status:"error",error:r,durationMs:0})}readCache(e){if(!this.cacheEnabled)return null;let r=this.cache.get(e);return r?this.cacheTtl>0&&Date.now()-r.insertedAt>this.cacheTtl?(this.dropCacheEntry(e),null):(this.cache.delete(e),this.cache.set(e,r),r.response):null}writeCache(e,r){if(!this.cacheEnabled||!this.cacheErroredSolves&&r.errors&&r.errors.length>0)return;let n=O(r)??qe(r);if(!(this.cacheMaxBytes>0&&n>this.cacheMaxBytes))for(this.dropCacheEntry(e),this.cache.set(e,{response:r,insertedAt:Date.now(),sizeBytes:n}),this.cacheBytes+=n;(this.cache.size>this.cacheMax||this.cacheMaxBytes>0&&this.cacheBytes>this.cacheMaxBytes)&&this.cache.size>0;){let o=this.cache.keys().next().value;if(o===void 0)break;this.dropCacheEntry(o)}}dropCacheEntry(e){let r=this.cache.get(e);r&&(this.cache.delete(e),this.cacheBytes-=r.sizeBytes)}clearCache(){this.cache.clear(),this.cacheBytes=0}cacheStats(){return{entries:this.cache.size,bytes:this.cacheBytes}}dispose(){this.disposed||(this.disposed=!0,this.cancelAll(),this.subscribers.clear(),this.clearCache())}runHook(e,...r){if(e)try{e(...r)}catch(n){y().error("[SolveScheduler] hook threw:",n)}}};function fe(t){return T(t)?`ref:${t.key}`:typeof t=="string"&&t.length<200?t:"...content..."}function me(t){return Array.isArray(t)?t.map(e=>{let r=0,n=0,o=p(e,"innerTree");if(o&&typeof o=="object"){for(let s of Object.values(o))if(Array.isArray(s)){r+=s.length;for(let i of s){let a=i?.data;typeof a=="string"&&(n+=a.length)}}}return{param:p(e,"paramName")??"<unnamed>",items:r,bytes:n}}):[]}var A=class t{constructor(e){l(this,"config");l(this,"serverStats");l(this,"disposed",!1);this.config=this.normalizeComputeConfig(e),this.serverStats=new oe(this.config.serverUrl,this.config.apiKey)}static async create(e){let r=new t(e),n=Math.max(1,(e.retry?.attempts??2)+1),o=e.retry?.baseDelayMs??250,s=e.retry?.maxDelayMs??1e3;for(let i=0;i<n;i++){if(await r.serverStats.isServerOnline())return r;if(i<n-1){let a=Math.min(o*2**i,s);await new Promise(u=>setTimeout(u,a))}}throw await r.dispose(),new c("Rhino Compute server is not online",h.NETWORK_ERROR,{context:{serverUrl:r.config.serverUrl,attempts:n}})}getConfig(){return this.ensureNotDisposed(),{...this.config}}async getIO(e){return this.ensureNotDisposed(),G(e,this.config)}async getRawIO(e){return this.ensureNotDisposed(),P(e,this.config)}async solve(e,r,n){this.ensureNotDisposed();try{if(typeof e=="string"&&!e?.trim())throw new c("Definition URL/content is required",h.INVALID_INPUT,{context:{receivedUrl:e}});if(e instanceof Uint8Array&&e.length===0)throw new c("Definition content is empty",h.INVALID_INPUT);if(T(e)&&!e.key.trim())throw new c("DefinitionRef key is empty",h.INVALID_INPUT);let o={...this.config,...n?.signal!==void 0&&{signal:n.signal},...n?.timeoutMs!==void 0&&{timeoutMs:n.timeoutMs},...n?.retry!==void 0&&{retry:n.retry}},s=await E(r,e,o);if(s?.errors&&s.errors.length>0)throw new c(s.errors.join("; ")||"Computation failed",h.COMPUTATION_ERROR,{context:{definition:fe(e),inputSummary:me(r),errors:s.errors,warnings:s.warnings,values:s.values}});return s}catch(o){throw this.config.debug&&y().error("Compute failed:",o),o instanceof c?o:new c(o instanceof Error?o.message:String(o),h.COMPUTATION_ERROR,{context:{definition:fe(e),inputSummary:me(r)},originalError:o instanceof Error?o:new Error(String(o))})}}createScheduler(e){this.ensureNotDisposed();let r=(o,s,i)=>E(s,o,i),n=(o,s,i,a)=>i===null?ie(s,o,a).then(u=>({...u,missed:!1})):ae(s,i,o,a);return new x(r,this.config,e,n)}async dispose(){this.disposed||(this.disposed=!0,await this.serverStats.dispose())}ensureNotDisposed(){if(this.disposed)throw new c("GrasshopperClient has been disposed and cannot be used",h.INVALID_STATE)}normalizeComputeConfig(e){return{...e,serverUrl:ne(e.serverUrl),apiKey:e.apiKey,authToken:e.authToken,debug:e.debug??!1,suppressBrowserWarning:e.suppressBrowserWarning??e.suppressClientSideWarning}}};var V=new Map;function he(t,e){V.set(t,e)}he("Rhino.Geometry.Point3d",(t,e)=>{let r=e;return!r||typeof r.X!="number"?null:new t.Point([r.X,r.Y,r.Z])});he("Rhino.Geometry.Line",(t,e)=>{let r=e;return!r||!r.From||!r.To?null:new t.Line([r.From.X,r.From.Y,r.From.Z],[r.To.X,r.To.Y,r.To.Z])});function Ue(t){if(V.has(t))return V.get(t);for(let[e,r]of V)if(t.startsWith(e))return r}function _e(t){return!!(t&&typeof t=="object"&&typeof t.data=="string")}function de(t,e){return{__decodeError:!0,type:t,raw:e}}function ye(t,e,r){let n=Ue(e),o=!1;if(n)try{let s=n(r,t);if(s!=null)return s}catch(s){y().warn(`Failed to decode Rhino type ${e}:`,s),o=!0}try{if(_e(t))return r.CommonObject.decode(t)}catch(s){return y().warn(`Failed to decode ${e} with CommonObject:`,s),de(e,t)}return o?de(e,t):t}function ge(t){let e=new WeakSet,r=n=>{if(!n||typeof n!="object"||e.has(n))return;e.add(n);let o=n.delete;if(typeof o=="function"){let i=n.isDeleted;(typeof i!="function"||!i.call(n))&&o.call(n);return}if(Array.isArray(n)){for(let i of n)r(i);return}let s=Object.getPrototypeOf(n);if(s===Object.prototype||s===null)for(let i of Object.values(n))r(i)};r(t)}var I={STRING:"System.String",INT:"System.Int32",DOUBLE:"System.Double",BOOL:"System.Boolean"},Ke="Rhino.Geometry.",Qe=["WebDisplay"],He="FileData";function be(t){return Qe.some(e=>t.includes(e))}function Je(t){if(typeof t!="string")return t;let e=t.trim();if(!(e.startsWith("{")||e.startsWith("[")||e.startsWith('"')))return t;try{let n=JSON.parse(e);if(typeof n=="string")try{return JSON.parse(n)}catch{return n}return n}catch{return t}}function Ye(t,e,r){switch(e){case I.STRING:return typeof t!="string"?t:t.replace(/^"(.*)"$/,"$1");case I.INT:return Number.parseInt(t,10);case I.DOUBLE:return Number.parseFloat(t);case I.BOOL:return String(t).toLowerCase()==="true";default:return r&&e.startsWith(Ke)?ye(t,e,r):t}}var U=new WeakMap;function Te(t){if(U.has(t))return U.get(t);let e=Je(t.data);return U.set(t,e),e}function Se(t,e,r,n){if(typeof t.data!="string")return t.data;let o=r?Te(t):t.data;return Ye(o,e,n)}function Xe(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.fileName=="string"&&typeof e.fileType=="string"&&"data"in e&&typeof e.isBase64Encoded=="boolean"&&typeof e.subFolder=="string"}function _(t){let e=p(t,"values");return Array.isArray(e)?e:[]}function K(t){return typeof t.type=="string"?t.type:""}function Q(t,e){if(!(!t||typeof t!="object")){for(let r of Object.values(t))if(Array.isArray(r))for(let n of r)n&&typeof n=="object"&&e(n)}}function De(t,e=!1,r={}){let{parseValues:n=!0,rhino:o,stringOnly:s=!1}=r,i={},a=new Set;for(let u of _(t)){let m=p(u,"paramName");Q(p(u,"innerTree"),f=>{let d=K(f);if(be(d)||s&&d!==I.STRING)return;let g=e?f.id:m;if(!g)return;let b=Se(f,d,n,o);g in i?a.has(g)?i[g].push(b):(i[g]=[i[g],b],a.add(g)):i[g]=b})}return{values:i,dispose:()=>ge(i)}}function xe(t){let e=[];for(let r of _(t))Q(p(r,"innerTree"),n=>{if(!K(n).includes(He))return;let o=Te(n);Xe(o)&&e.push(o)});return e}function Ie(t,e,r={}){let{parseValues:n=!0,rhino:o,stringOnly:s=!1}=r;for(let i of _(t)){let a=p(i,"innerTree"),u=!1;if("byName"in e){if(p(i,"paramName")!==e.byName)continue;u=!0}let m=[];if(Q(a,f=>{if("byId"in e){if(f.id!==e.byId)return;u=!0}let d=K(f);be(d)||s&&d!==I.STRING||m.push(Se(f,d,n,o))}),u)return m.length===0?void 0:m.length===1?m[0]:m}}var k=class{constructor(e,r=!1){l(this,"response",e);l(this,"debug",r)}getValues(e=!1,r={}){return De(this.response,e,r)}getValue(e,r){return Ie(this.response,e,r)}async extractMeshesFromResponse(e){let r={debug:this.debug,...e},n;try{({getThreeMeshesFromComputeResponse:n}=await import("./visualization-XWX3PR4N.js"))}catch(o){throw new c("Failed to load three.js visualization module. Ensure three.js is installed as a peer dependency.",h.INVALID_STATE,{context:{originalError:o instanceof Error?o.message:String(o)}})}return n(this.response,r)}getFileData(){return xe(this.response)}async getAndDownloadFiles(e,r){let n=this.getFileData();await F(n,e,r)}};var H=/^\{(-?\d+(?:;-?\d+)*)?\}$/;function C(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=Object.entries(t);return e.length>0&&e.every(([r,n])=>H.test(r)&&Array.isArray(n))}function w(t,e,r){if(t==null)return t;if(Array.isArray(t)){let o=t.map(e).filter(s=>s!==null);return o.length>0?o:void 0}let n=e(t);return n!==null?n:r?void 0:t}var L=t=>{if(typeof t=="number")return Number.isFinite(t)?t:null;if(typeof t=="string"){let e=t.trim();if(e===""||/^[+-]?0[xbo]/i.test(e))return null;let r=Number(e);return Number.isFinite(r)?r:null}return null},J=t=>{if(typeof t=="boolean")return t;if(typeof t=="string"){let e=t.trim().toLowerCase();if(e==="true")return!0;if(e==="false")return!1}return null},Ze=t=>typeof t=="string"?t.length>=2&&t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t.startsWith('"')?t.slice(1):t:null,et=t=>{if(typeof t=="string"){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')&&(e=e.slice(1,-1).trim()),e}return null};function we(t){return e=>{if(typeof e=="object"&&e!==null)return e;if(typeof e=="string"&&e.trim()!=="")try{let r=JSON.parse(e);return typeof r=="object"&&r!==null?r:(y().warn(`Parsed value for input ${t} is not an object`),null)}catch(r){return y().warn(`Failed to parse object value "${e}" for input ${t}`,r),null}return null}}function Ce(t,e,r){let n=Number(t.toFixed(e));return Math.abs(t-n)<r?n:t}function tt(t,e){if(!Number.isFinite(t)||t===0)return .1;let r=Math.abs(t);if(r>=1){let g=String(t).split(".")[1];if(g&&g.length>0){let b=Math.min(g.length,12),S=Math.pow(10,-b),X=Number(S.toFixed(b));return Math.abs(X-S)<e?X:S}return 1}let n=String(t),o=n.toLowerCase().match(/e(-?\d+)/);if(o){let d=Number(o[1]);if(d<0||n.toLowerCase().includes("e-")){let g=Math.abs(d),b=Math.pow(10,-g),S=Number(b.toFixed(g));return Math.abs(S-b)<e?S:b}return .1}let s=12,a=r.toFixed(s).replace(/0+$/,""),u=Math.min((a.split(".")[1]||"").length,s);if(u===0)return .1;let m=Math.pow(10,-u),f=Number(m.toFixed(u));return Math.abs(f-m)<e?f:m}function Ee(t){return typeof t.stepSize=="number"&&Number.isFinite(t.stepSize)&&t.stepSize>0?t.stepSize:void 0}function rt(t,e=1e-8){let r=t.paramType==="Integer",n=Ee(t);if(C(t.default))return{default:t.default,stepSize:n??(r?1:.1)};if(typeof t.default=="string"&&t.default.trim()!==""&&L(t.default)===null)throw new c(`Invalid numeric default "${t.default}" for input "${t.name||"unknown"}"`,h.VALIDATION_ERROR,{context:{inputName:t.name,default:t.default}});let o=w(t.default,L,!0);if(r)return Array.isArray(o)?o=o.map(d=>typeof d=="number"?Math.round(d):d):typeof o=="number"&&(o=Math.round(o)),{default:o,stepSize:n??1};let s=Array.isArray(o)?o[0]:o,i;typeof s=="number"&&Number.isFinite(s)&&s!==0?i=s:typeof t.minimum=="number"&&Number.isFinite(t.minimum)&&t.minimum!==0?i=t.minimum:typeof t.maximum=="number"&&Number.isFinite(t.maximum)&&t.maximum!==0&&(i=t.maximum);let a=n??(i!==void 0?tt(i,e):.1),u=0,m=String(a),f=m.toLowerCase().match(/e(-?\d+)/);if(f?u=Math.abs(Number(f[1])):u=m.split(".")[1]?.length??0,u===0&&typeof s=="number"&&s!==0&&Math.abs(s)<1){let d=Math.ceil(-Math.log10(Math.abs(s)));Number.isFinite(d)&&d>0&&(u=d)}return u=Math.min(Math.max(u,0),12),Array.isArray(o)?o=o.map(d=>typeof d=="number"?Ce(d,u,e):d):typeof o=="number"&&(o=Ce(o,u,e)),{default:o,stepSize:a}}var nt={types:["Number","Integer"],parse(t,e){let{default:r,stepSize:n}=rt(t);return{...e,paramType:t.paramType,minimum:t.minimum,maximum:t.maximum,atLeast:t.atLeast,atMost:t.atMost,stepSize:n,default:r}},fallback(t,e){let r=(t.atMost??1)>1,n=typeof t.minimum=="number"&&Number.isFinite(t.minimum)&&t.minimum>0?t.minimum:0;return{...e,paramType:t.paramType,minimum:t.minimum,maximum:t.maximum,atLeast:t.atLeast,atMost:t.atMost,stepSize:Ee(t)??(t.paramType==="Integer"?1:.1),default:r?[n]:n}}},ot={types:["Boolean"],parse(t,e){if(C(t.default))return{...e,paramType:"Boolean",default:t.default};let r=w(t.default,J,!1);if(r!=null&&typeof r!="boolean"&&!Array.isArray(r))throw new c(`Invalid boolean default "${String(r)}" for input "${t.name||"unknown"}"`,h.VALIDATION_ERROR,{context:{inputName:t.name,default:t.default}});return{...e,paramType:"Boolean",default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"Boolean",default:r?[!1]:!1}}},st={types:["Text"],parse(t,e){let r=w(t.default,Ze,!1);return{...e,paramType:"Text",default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"Text",default:r?[""]:""}}},it={types:["ValueList"],parse(t,e){if(!t.values||typeof t.values!="object"||Object.keys(t.values).length===0)throw c.missingValues(t.nickname||"unnamed","ValueList");let r=t.default;if(t.default!==void 0&&t.default!==null){if(typeof t.default=="object")throw new c(`ValueList input "${t.nickname||"unnamed"}" default is not a string-able value`,h.VALIDATION_ERROR,{context:{inputName:t.name,default:t.default}});let n=String(t.default).toLowerCase(),o=Object.keys(t.values).find(s=>s.toLowerCase()===n);o!==void 0?r=o:y().warn(`ValueList input "${t.nickname||"unnamed"}" default value "${t.default}" is not in available values`)}return{...e,paramType:"ValueList",values:t.values,default:r}},fallback(t,e){return{...e,paramType:"ValueList",values:t.values&&typeof t.values=="object"?t.values:{},default:void 0}}},ve={types:["Geometry"],parse(t,e){let r=w(t.default,we(t.nickname||"unnamed"),!0);return{...e,paramType:"Geometry",default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"Geometry",default:r?[null]:null}}},at={types:["File"],parse(t,e){let r=w(t.default,we(t.nickname||"unnamed"),!0);return{...e,paramType:"File",acceptedFormats:t.acceptedFormats,default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"File",default:r?[null]:null}}},ut={types:["Color"],parse(t,e){let r=w(t.default,et,!1);return{...e,paramType:"Color",default:r}},fallback(t,e){let r=(t.atMost??1)>1;return{...e,paramType:"Color",default:r?["0, 0, 0"]:"0, 0, 0"}}},pt=[nt,ot,st,it,ve,at,ut],Y=new Map(pt.flatMap(t=>t.types.map(e=>[e,t]))),Re=ve;function Ae(t){return p(t,"data")}function lt(t){return p(t,"type")}var ct=new Set(["System.Double","System.Single","System.Decimal","System.Int32","System.Int64"]),ft=new Set(["System.Int32","System.Int64"]);function Pe(t){if(typeof t.default!="object"||t.default===null)return{schema:t};if(Array.isArray(t.default))return{schema:t};if(!j(t.default,"innerTree")){let n=`Input "${t.name??"unknown"}" default had an unrecognized shape (no innerTree key); the default was dropped.`;return y().warn("Unexpected structure in input.default:",t.default),{schema:{...t,default:null},warning:{code:"MALFORMED_DEFAULT",message:n}}}let e=p(t.default,"innerTree")??{};if(Object.keys(e).length===0)return{schema:{...t,default:void 0}};if(t.treeAccess||t.atMost&&t.atMost>1){let n={},o=[];for(let[i,a]of Object.entries(e)){if(!Array.isArray(a)){let m=`Input "${t.name??"unknown"}" default had a non-array innerTree branch ("${i}"); the default was dropped.`;return y().warn("Unexpected structure in input.default innerTree:",t.default),{schema:{...t,default:null},warning:{code:"MALFORMED_DEFAULT",message:m}}}let u=[];for(let m of a){let f=Ae(m),d=lt(m);if(d&&ct.has(d)){if(typeof f=="string"&&f.trim()==="")continue;let g=L(f);if(g===null){o.push(`"${String(f)}" (${d})`);continue}u.push(ft.has(d)?Math.round(g):g);continue}if(d==="System.Boolean"){let g=J(f);if(g===null){o.push(`"${String(f)}" (${d})`);continue}u.push(g);continue}if(typeof f=="string"&&d?.startsWith("Rhino.Geometry")){try{u.push(JSON.parse(f))}catch{u.push(f)}continue}u.push(f)}n[i]=u}let s;if(o.length>0){let i=`Input "${t.name??"unknown"}" default contained ${o.length} tree value(s) that could not be parsed and were dropped: ${o.join(", ")}.`;y().warn(i),s={code:"MALFORMED_DEFAULT",message:i}}return{schema:{...t,default:n},...s&&{warning:s}}}let r=[];for(let n of Object.values(e))Array.isArray(n)&&n.forEach(o=>{o&&typeof o=="object"&&j(o,"data")&&r.push(Ae(o))});return r.length===0?{schema:{...t,default:void 0}}:r.length===1?{schema:{...t,default:r[0]}}:{schema:{...t,default:r}}}var mt=new Map([...Y.keys()].map(t=>[t.toLowerCase(),t]));function dt(t){return mt.get(t?.toLowerCase())??t}function ke(t){return Oe(t).input}function Oe(t){let e={description:t.description,name:t.name,nickname:t.nickname,treeAccess:t.treeAccess,groupName:t.groupName??void 0,id:t.id},r=dt(t.paramType),n={...t,paramType:r},o;try{let{schema:i,warning:a}=Pe(n);n=i,o=a&&{inputName:t.name||"unknown",paramType:t.paramType,message:a.message,code:a.code}}catch(i){n={...n,default:null},o={inputName:t.name||"unknown",paramType:t.paramType,message:`Input "${t.name??"unknown"}" default could not be normalized and was dropped: ${i instanceof Error?i.message:String(i)}`,code:"MALFORMED_DEFAULT"}}let s=Y.get(r);try{if(!s)throw c.unknownParamType(r,t.name);return{input:s.parse(n,e),error:o,...o&&{errors:[o]}}}catch(i){if(i instanceof c){y().error(`Validation error for input ${t.name||"unknown"}:`,i.message);let a={inputName:t.name||"unknown",paramType:t.paramType,message:i.message,code:i.code};return{input:(s??Re).fallback(n,e),error:a,errors:o?[o,a]:[a]}}throw new c(i instanceof Error?i.message:String(i),"VALIDATION_ERROR",{context:{paramName:t.name,paramType:r},originalError:i instanceof Error?i:new Error(String(i))})}}function Me(t){return W(t).inputs}function W(t){let e=[],r=[];for(let n of t){let{input:o,errors:s}=Oe(n);e.push(o),s&&r.push(...s)}return{inputs:e,parseErrors:r}}function Fe(t){let e=p(t,"stepSize");return{id:p(t,"id")??"",name:p(t,"name")??"",nickname:p(t,"nickname")??null,description:p(t,"description")??"",paramType:p(t,"paramType")??"",treeAccess:p(t,"treeAccess")??!1,minimum:p(t,"minimum")??null,maximum:p(t,"maximum")??null,atLeast:p(t,"atLeast")??1,atMost:p(t,"atMost")??1,stepSize:typeof e=="number"&&Number.isFinite(e)?e:void 0,default:p(t,"default"),values:p(t,"values"),acceptedFormats:p(t,"acceptedFormats"),groupName:p(t,"groupName")??null}}function Ne(t){return{name:p(t,"name")??"",nickname:p(t,"nickname")??null,paramType:p(t,"paramType")??"",id:p(t,"id")??""}}async function P(t,e){let r=v(t,[]),n={};if(r.algo&&(n.algo=r.algo),r.pointer&&(n.pointer=r.pointer),!n.algo&&!n.pointer)throw new c("Definition must resolve to either a URL pointer or base64 algo",h.INVALID_INPUT,{context:{definition:t}});let o=await M("io",n,e);if(!o||typeof o!="object")throw new c("Invalid IO response structure",h.INVALID_INPUT,{context:{response:o,definition:t}});let s=Ge(p(o,"warnings")),i=Ge(p(o,"errors")),a=p(o,"inputs"),u=p(o,"outputs");return{inputs:Array.isArray(a)?a.map(Fe):[],outputs:Array.isArray(u)?u.map(Ne):[],...s&&{loadWarnings:s},...i&&{loadErrors:i}}}function Ge(t){if(!Array.isArray(t))return;let e=t.map(ht).filter(r=>r!==void 0);return e.length>0?e:void 0}function ht(t){if(t==null)return;let e;if(typeof t=="string")e=t;else if(typeof t=="object"){let r=p(t,"message");if(typeof r=="string"&&r.trim().length>0)e=r;else try{e=JSON.stringify(t)??String(t)}catch{e=String(t)}}else e=String(t);return e.trim().length>0?e:void 0}async function G(t,e){D("fetchParsedDefinitionIO",e.suppressBrowserWarning??e.suppressClientSideWarning);let{inputs:r,outputs:n,loadWarnings:o,loadErrors:s}=await P(t,e),{inputs:i,parseErrors:a}=W(r);return{inputs:i,outputs:n,...a.length>0&&{parseErrors:a},...o&&{loadWarnings:o},...s&&{loadErrors:s}}}var B=class t{constructor(e){l(this,"innerTree");l(this,"paramName");this.paramName=e,this.innerTree={}}append(e,r){let n=t.formatPathString(e);this.innerTree[n]||(this.innerTree[n]=[]);let o=r.map(s=>({data:t.serializeValue(s)}));return this.innerTree[n].push(...o),this}appendSingle(e,r){return this.append(e,[r])}fromDataTreeDefault(e){this.innerTree={};for(let[r,n]of Object.entries(e)){if(!Array.isArray(n))continue;let o=t.parsePathString(r);this.append(o,n)}return this}appendFlat(e){let r=Array.isArray(e)?e:[e];return this.append([0],r)}flatten(){let e=[];for(let r of Object.values(this.innerTree))if(Array.isArray(r))for(let n of r)e.push(t.deserializeValue(n.data));return e}getPaths(){return Object.keys(this.innerTree)}getPath(e){let r=t.formatPathString(e),n=this.innerTree[r];if(n)return n.map(o=>t.deserializeValue(o.data))}toComputeFormat(){return{ParamName:this.paramName,InnerTree:this.innerTree}}getInnerTree(){return this.innerTree}getParamName(){return this.paramName}static fromInputParams(e){return e.filter(r=>t.hasValidValue(r.default)).map(r=>{let n=new t(r.nickname||"unnamed"),o=r.default;if(r.treeAccess&&C(o))n.fromDataTreeDefault(o),t.isNumericInput(r)&&n.applyNumericConstraints(r.minimum,r.maximum,r.nickname||"unnamed");else{let s=Array.isArray(o)?o:[o],i=t.processValues(s,r);n.appendFlat(i)}return n.toComputeFormat()})}static fromInputParam(e){return t.hasValidValue(e.default)?t.fromInputParams([e])[0]:void 0}static replaceTreeValue(e,r,n){let o=e.length>0&&e[0]instanceof t,s=t.buildFromValue(r,n);if(o){let m=e.slice(),f=m.findIndex(d=>d.getParamName()===r);return f!==-1?m[f]=s:m.push(s),m}let i=e.slice(),a=s.toComputeFormat(),u=i.findIndex(m=>m.ParamName===r);return u!==-1?i[u]=a:i.push(a),i}static buildFromValue(e,r){let n=new t(e);return C(r)?n.fromDataTreeDefault(r):n.appendFlat(r),n}static getTreeValue(e,r){let o=e.length>0&&e[0]instanceof t?t.readFromBuilders(e,r):t.readFromDataTrees(e,r);return o===null||o.length===0?null:o.length===1?o[0]:o}static readFromBuilders(e,r){let n=e.find(o=>o.getParamName()===r);return n?n.flatten():null}static readFromDataTrees(e,r){let n=e.find(i=>i.ParamName===r);if(!n?.InnerTree)return null;let o=Object.keys(n.InnerTree)[0];if(!o)return null;let s=n.InnerTree[o];return Array.isArray(s)?s.map(i=>i?.data!==void 0?t.deserializeValue(i.data):null):s?.data!==void 0?[t.deserializeValue(s.data)]:s!==void 0?[s]:null}static parsePathString(e){let r=e.match(H);if(!r)throw new Error(`Invalid Grasshopper tree path: "${e}". Expected "{}", "{0}", or "{0;1;2}" (negative indices allowed, no empty segments).`);return r[1]?r[1].split(";").map(Number):[]}static formatPathString(e){return`{${e.join(";")}}`}applyNumericConstraints(e,r,n){for(let o of Object.values(this.innerTree))if(Array.isArray(o))for(let s of o){let i=t.deserializeValue(s.data);if(typeof i=="number"){let a=t.clampValue(i,e,r,n);s.data=t.serializeValue(a)}}}static serializeValue(e){return typeof e=="boolean"||typeof e=="number"||typeof e=="string"?e:typeof e=="object"&&e!==null?JSON.stringify(e):String(e)}static deserializeValue(e){if(typeof e=="boolean"||typeof e=="number"||typeof e!="string")return e;if(e.startsWith("{")||e.startsWith("["))try{return JSON.parse(e)}catch{return e}let r=Number(e);return Number.isFinite(r)&&String(r)===e?r:e==="true"?!0:e==="false"?!1:e}static hasValidValue(e){return e==null?!1:typeof e=="string"?!0:!(Array.isArray(e)&&e.length===0||typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0)}static isNumericInput(e){return e.paramType==="Number"||e.paramType==="Integer"}static processValues(e,r){return e.map(n=>t.isNumericInput(r)&&typeof n=="number"?t.clampValue(n,r.minimum,r.maximum,r.nickname||"unnamed"):n).filter(n=>n!=null)}static clampValue(e,r,n,o){let s=e;return r!=null&&s<r&&(y().warn(`${o}: ${e} below min ${r}, clamping`),s=r),n!=null&&s>n&&(y().warn(`${o}: ${e} above max ${n}, clamping`),s=n),s}};export{T as a,E as b,$ as c,ce as d,R as e,x as f,A as g,k as h,ke as i,Me as j,P as k,G as l,B as m};
|
|
2
|
+
//# sourceMappingURL=chunk-J4NKIVF3.js.map
|