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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/chunk-3SEQKFGD.js +2 -0
  2. package/dist/chunk-3SEQKFGD.js.map +1 -0
  3. package/dist/chunk-44HGB4C4.cjs +2 -0
  4. package/dist/chunk-44HGB4C4.cjs.map +1 -0
  5. package/dist/chunk-H3FZW6OX.cjs +4 -0
  6. package/dist/chunk-H3FZW6OX.cjs.map +1 -0
  7. package/dist/chunk-INP5HVA2.js +62 -0
  8. package/dist/chunk-INP5HVA2.js.map +1 -0
  9. package/dist/chunk-KTKY5M5S.cjs +62 -0
  10. package/dist/chunk-KTKY5M5S.cjs.map +1 -0
  11. package/dist/chunk-Y3M7P3BW.js +4 -0
  12. package/dist/chunk-Y3M7P3BW.js.map +1 -0
  13. package/dist/core.cjs +1 -1
  14. package/dist/core.cjs.map +1 -1
  15. package/dist/core.d.cts +22 -1
  16. package/dist/core.d.ts +22 -1
  17. package/dist/core.js +1 -1
  18. package/dist/grasshopper.cjs +1 -1
  19. package/dist/grasshopper.d.cts +20 -0
  20. package/dist/grasshopper.d.ts +20 -0
  21. package/dist/grasshopper.js +1 -1
  22. package/dist/index.cjs +1 -1
  23. package/dist/index.cjs.map +1 -1
  24. package/dist/index.d.cts +1 -1
  25. package/dist/index.d.ts +1 -1
  26. package/dist/index.js +1 -1
  27. package/dist/{visualization-MOYO6MDN.js → visualization-5RH6RSLV.js} +2 -2
  28. package/dist/visualization-KRP5OPYW.cjs +2 -0
  29. package/dist/{visualization-4RSUYQG2.cjs.map → visualization-KRP5OPYW.cjs.map} +1 -1
  30. package/dist/visualization.cjs +1 -1
  31. package/dist/visualization.d.cts +35 -4
  32. package/dist/visualization.d.ts +35 -4
  33. package/dist/visualization.js +1 -1
  34. package/package.json +51 -30
  35. package/dist/chunk-7XMD5YXP.cjs +0 -62
  36. package/dist/chunk-7XMD5YXP.cjs.map +0 -1
  37. package/dist/chunk-C7P43VZF.js +0 -2
  38. package/dist/chunk-C7P43VZF.js.map +0 -1
  39. package/dist/chunk-CUQQ3ZBV.cjs +0 -4
  40. package/dist/chunk-CUQQ3ZBV.cjs.map +0 -1
  41. package/dist/chunk-PX2YTSHJ.js +0 -62
  42. package/dist/chunk-PX2YTSHJ.js.map +0 -1
  43. package/dist/chunk-QZECCPT3.cjs +0 -2
  44. package/dist/chunk-QZECCPT3.cjs.map +0 -1
  45. package/dist/chunk-WPB2LKCD.js +0 -4
  46. package/dist/chunk-WPB2LKCD.js.map +0 -1
  47. package/dist/visualization-4RSUYQG2.cjs +0 -2
  48. /package/dist/{visualization-MOYO6MDN.js.map → visualization-5RH6RSLV.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/errors.ts","../src/core/utils/logger.ts","../src/core/utils/encoding.ts","../src/core/compute-fetch/wire-size.ts","../src/core/compute-fetch/compute-fetch.ts","../src/core/server/validate-server-url.ts","../src/core/server/compute-server-stats.ts","../src/core/utils/camel-case.ts","../src/core/utils/read-field.ts","../src/core/files/handle-files.ts"],"sourcesContent":["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 } from '../errors';\n\n/**\n * Logger interface for structured logging\n *\n * @public Implement this interface to provide custom logging behavior.\n */\nexport interface Logger {\n\tdebug(message: string, ...args: unknown[]): void;\n\tinfo(message: string, ...args: unknown[]): void;\n\twarn(message: string, ...args: unknown[]): void;\n\terror(message: string, ...args: unknown[]): void;\n}\n\n/**\n * No-op logger implementation (default)\n * @internal\n */\nclass NoOpLogger implements Logger {\n\tdebug(): void {}\n\tinfo(): void {}\n\twarn(): void {}\n\terror(): void {}\n}\n\n/**\n * Console logger implementation\n * @internal\n */\nclass ConsoleLogger implements Logger {\n\tdebug(message: string, ...args: unknown[]): void {\n\t\tconsole.debug(message, ...args);\n\t}\n\n\tinfo(message: string, ...args: unknown[]): void {\n\t\tconsole.info(message, ...args);\n\t}\n\n\twarn(message: string, ...args: unknown[]): void {\n\t\tconsole.warn(message, ...args);\n\t}\n\n\terror(message: string, ...args: unknown[]): void {\n\t\tconsole.error(message, ...args);\n\t}\n}\n\n/**\n * Internal logger instance\n * @internal\n */\nlet internalLogger: Logger = new NoOpLogger();\n\n/**\n * Get the current logger instance\n *\n * @returns The current logger instance\n */\nexport function getLogger(): Logger {\n\treturn internalLogger;\n}\n\n/**\n * Set a custom logger instance\n *\n * @public Use this to configure custom logging behavior.\n *\n * @param logger - Custom logger implementation or null to disable logging\n * @throws {RhinoComputeError} `INVALID_CONFIG` if the logger is missing any of\n * the four required methods — failing here beats a confusing\n * \"getLogger().debug is not a function\" at some later, unrelated call site.\n *\n * @example\n * ```typescript\n * import { setLogger } from '@selvajs/compute';\n *\n * // Enable console logging\n * setLogger(console);\n *\n * // Use a custom logger\n * setLogger({\n * debug: (msg, ...args) => myLogger.debug(msg, ...args),\n * info: (msg, ...args) => myLogger.info(msg, ...args),\n * warn: (msg, ...args) => myLogger.warn(msg, ...args),\n * error: (msg, ...args) => myLogger.error(msg, ...args)\n * });\n *\n * // Disable logging\n * setLogger(null);\n * ```\n */\nexport function setLogger(logger: Logger | Console | null): void {\n\tif (logger === null) {\n\t\tinternalLogger = new NoOpLogger();\n\t\treturn;\n\t}\n\n\tconst missing = (['debug', 'info', 'warn', 'error'] as const).filter(\n\t\t(method) => typeof (logger as unknown as Record<string, unknown>)[method] !== 'function'\n\t);\n\tif (missing.length > 0) {\n\t\tthrow new RhinoComputeError(\n\t\t\t`Logger is missing required method(s): ${missing.join(', ')}. A logger must implement debug, info, warn and error.`,\n\t\t\tErrorCodes.INVALID_CONFIG,\n\t\t\t{ context: { missingMethods: missing } }\n\t\t);\n\t}\n\n\tinternalLogger = logger as Logger;\n}\n\n/**\n * Enable debug logging to console\n *\n * @public Convenience method to enable console logging.\n *\n * @example\n * ```typescript\n * import { enableDebugLogging } from '@selvajs/compute';\n *\n * enableDebugLogging();\n * ```\n */\nexport function enableDebugLogging(): void {\n\tsetLogger(new ConsoleLogger());\n}\n","import { RhinoComputeError, ErrorCodes } from '../errors';\n\n/** Node's `Buffer` when present (faster path), else `undefined` in browsers/workers. */\nfunction getNodeBuffer(): typeof Buffer | undefined {\n\tconst buf = (globalThis as { Buffer?: typeof Buffer }).Buffer;\n\treturn typeof buf === 'function' ? buf : undefined;\n}\n\n/**\n * Encodes a string to base64 (Node 20+ safe)\n *\n * @internal\n * @param str - String to encode\n * @returns Base64 encoded string\n */\nexport function encodeStringToBase64(str: string): string {\n\tconst Buffer = getNodeBuffer();\n\tif (Buffer) {\n\t\treturn Buffer.from(str, 'utf-8').toString('base64');\n\t}\n\t// Browser/worker fallback: UTF-8 encode, then reuse the byte-array encoder.\n\treturn base64ByteArray(new TextEncoder().encode(str));\n}\n\n/**\n * Checks if a string is syntactically valid base64 (strict form: length a multiple of 4).\n * Note: this is validity checking, not detection — `\"test\"` is valid base64 here.\n * To detect whether an untyped string should be treated as base64 content, use {@link detectBase64Payload}.\n *\n * @internal\n * @param str - String to check\n * @returns True if the string is valid base64\n */\nexport function isBase64(str: string): boolean {\n\tif (!str || str.length < 2) return false;\n\t// Length must be a multiple of 4, only alphabet chars + at most 2 trailing '='\n\tif (str.length % 4 !== 0) return false;\n\treturn /^[A-Za-z0-9+/]+={0,2}$/.test(str);\n}\n\n/**\n * Minimum base64 length to treat bare strings as base64 content (excludes padding).\n * 64 chars ≈ 48 decoded bytes — high enough to avoid false positives on human strings.\n *\n * @internal\n */\nexport const BASE64_DETECT_MIN_LENGTH = 64;\n\n/** Lookup for a base64 character's 6-bit value; -1 when not in the alphabet. */\nconst B64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\n/**\n * Detects whether an untyped string is base64-encoded content.\n * Uses normalization, length checks, and canonical round-trip validation.\n * Perfect detection is impossible — pass `Uint8Array` instead if exact detection is required.\n *\n * @internal\n * @param str - String to inspect\n * @returns Canonical base64 form when confident, else `null` (treat as plain text)\n */\nexport function detectBase64Payload(str: string): string | null {\n\tif (!str) return null;\n\t// Forgiving-base64 normalization, mirroring decodeBase64ToBinary: strip\n\t// ASCII whitespace, then drop legal trailing padding.\n\tlet data = str.replace(/[\\t\\n\\f\\r ]/g, '');\n\tif (data.length % 4 === 0) data = data.replace(/={1,2}$/, '');\n\n\tconst rem = data.length % 4;\n\tif (rem === 1) return null; // no base64 encoding produces this length\n\tif (data.length < BASE64_DETECT_MIN_LENGTH) return null;\n\tif (!/^[A-Za-z0-9+/]*$/.test(data)) return null;\n\n\t// Canonical round-trip check without decoding: the final character's\n\t// unused low bits must be zero, otherwise re-encoding the decoded bytes\n\t// would not reproduce the input (i.e. it wasn't produced by an encoder).\n\tconst lastValue = B64_ALPHABET.indexOf(data.charAt(data.length - 1));\n\tif (rem === 2 && (lastValue & 0x0f) !== 0) return null;\n\tif (rem === 3 && (lastValue & 0x03) !== 0) return null;\n\n\treturn rem === 0 ? data : data + '=='.slice(0, 4 - rem);\n}\n\n/**\n * Decodes a base64 string to binary data (Uint8Array).\n * Normalizes and validates input per WHATWG forgiving-base64 so both runtimes fail consistently.\n *\n * @internal\n * @param base64File - Base64 encoded string\n * @returns Decoded binary data as Uint8Array\n * @throws {RhinoComputeError} `ENCODING_ERROR` if invalid, or `INVALID_STATE` if decoder unavailable\n */\nexport function decodeBase64ToBinary(base64File: string): Uint8Array {\n\t// Forgiving-base64 normalization: strip ASCII whitespace (wrapped /\n\t// pretty-printed payloads), then drop trailing padding only where the spec\n\t// allows it (total length a multiple of 4).\n\tlet data = base64File.replace(/[\\t\\n\\f\\r ]/g, '');\n\tif (data.length % 4 === 0) data = data.replace(/={1,2}$/, '');\n\tif (data.length % 4 === 1 || !/^[A-Za-z0-9+/]*$/.test(data)) {\n\t\tthrow new RhinoComputeError('Invalid base64 input.', ErrorCodes.ENCODING_ERROR, {\n\t\t\tcontext: { inputLength: base64File.length }\n\t\t});\n\t}\n\n\t// Prefer Buffer in Node — it's faster and avoids the latin-1 string detour\n\t// that atob + charCodeAt requires.\n\tconst Buffer = getNodeBuffer();\n\tif (Buffer) {\n\t\t// Copy the bytes out of the Buffer: small Buffer.from results are views\n\t\t// over Node's shared 8 KiB pool slab, so returning a view would retain\n\t\t// the whole slab and expose unrelated pooled bytes to any consumer that\n\t\t// touches `.buffer` (re-wrapping, structuredClone, postMessage transfer).\n\t\t// `new Uint8Array(typedArray)` copies into a fresh, exactly-sized buffer.\n\t\treturn new Uint8Array(Buffer.from(data, 'base64'));\n\t}\n\tif (typeof globalThis.atob === 'function') {\n\t\tconst binary = globalThis.atob(data);\n\t\tconst bytes = new Uint8Array(binary.length);\n\t\tfor (let i = 0; i < binary.length; i++) {\n\t\t\tbytes[i] = binary.charCodeAt(i) & 0xff;\n\t\t}\n\t\treturn bytes;\n\t}\n\n\tthrow new RhinoComputeError(\n\t\t'Base64 decoding not supported in this environment.',\n\t\tErrorCodes.INVALID_STATE,\n\t\t{ context: { environmentInfo: 'atob or Buffer not available' } }\n\t);\n}\n\n/**\n * UTF-8 byte length of a string without allocating an encoded copy.\n * Avoids doubling memory on large strings that `TextEncoder.encode` would require.\n *\n * @internal\n */\nexport function utf8ByteLength(str: string): number {\n\tconst Buffer = getNodeBuffer();\n\tif (Buffer) {\n\t\treturn Buffer.byteLength(str, 'utf-8');\n\t}\n\tlet bytes = 0;\n\tfor (let i = 0; i < str.length; i++) {\n\t\tconst code = str.charCodeAt(i);\n\t\tif (code < 0x80) {\n\t\t\tbytes += 1;\n\t\t} else if (code < 0x800) {\n\t\t\tbytes += 2;\n\t\t} else if (\n\t\t\tcode >= 0xd800 &&\n\t\t\tcode <= 0xdbff &&\n\t\t\ti + 1 < str.length &&\n\t\t\t(str.charCodeAt(i + 1) & 0xfc00) === 0xdc00\n\t\t) {\n\t\t\t// Surrogate pair → one 4-byte code point; lone surrogates fall through\n\t\t\t// to 3 bytes (the replacement-character encoding TextEncoder emits).\n\t\t\tbytes += 4;\n\t\t\ti++;\n\t\t} else {\n\t\t\tbytes += 3;\n\t\t}\n\t}\n\treturn bytes;\n}\n\n/**\n * Encodes binary data (Uint8Array) to base64 string.\n * Uses Node's `Buffer` when available, falls back to `btoa` in browsers/workers.\n *\n * @internal\n */\nexport function base64ByteArray(bytes: Uint8Array): string {\n\tconst Buffer = getNodeBuffer();\n\tif (Buffer) {\n\t\treturn Buffer.from(bytes).toString('base64');\n\t}\n\tif (typeof globalThis.btoa === 'function') {\n\t\t// Encode chunk-by-chunk and join the base64 pieces, instead of building\n\t\t// one full-input latin-1 string and btoa-ing it (which peaked at ~3×\n\t\t// input memory). The chunk size MUST be a multiple of 3 bytes so every\n\t\t// non-final chunk encodes to whole base64 quanta with no padding —\n\t\t// concatenating the pieces is then byte-for-byte identical to encoding\n\t\t// the whole input at once. 32766 = 3 × 10922, and stays well under the\n\t\t// fromCharCode.apply argument-count limit.\n\t\tconst CHUNK = 32766;\n\t\tconst parts: string[] = [];\n\t\tfor (let i = 0; i < bytes.length; i += CHUNK) {\n\t\t\t// A Uint8Array subarray is array-like, so pass it straight to\n\t\t\t// fromCharCode.apply — no need to copy it into a plain Array first.\n\t\t\tparts.push(\n\t\t\t\tglobalThis.btoa(\n\t\t\t\t\tString.fromCharCode.apply(null, bytes.subarray(i, i + CHUNK) as unknown as number[])\n\t\t\t\t)\n\t\t\t);\n\t\t}\n\t\treturn parts.join('');\n\t}\n\tthrow new RhinoComputeError(\n\t\t'Base64 encoding not supported in this environment.',\n\t\tErrorCodes.INVALID_STATE,\n\t\t{ context: { environmentInfo: 'btoa or Buffer not available' } }\n\t);\n}\n","/**\n * Side-channel carrying a response's wire size (its JSON text length) alongside\n * the parsed object, so downstream caches can budget by bytes without\n * re-serializing (audit C2/C3 — the response tree can be hundreds of MB, and\n * every extra `JSON.stringify` pass over it is a real cost).\n *\n * A `WeakMap` rather than a property on the response: the response type is the\n * server's schema, and an extra enumerable field would leak into every\n * `JSON.stringify(response)` on the way back out to clients. Derived copies\n * (e.g. the `algo`-stripped shallow copy in `runSolve`) must re-register — the\n * hint follows object identity, not content.\n *\n * The size is `text.length` (UTF-16 code units), not strict UTF-8 bytes —\n * compute responses are ASCII-dominated JSON (base64 + numerals), so the two\n * are interchangeable for budgeting purposes and `.length` is free.\n */\n\nconst wireSizes = new WeakMap<object, number>();\n\n/** Record `response`'s wire size. No-op for non-object/null values. */\nexport function setResponseWireSize(response: unknown, size: number): void {\n\tif (typeof response !== 'object' || response === null) return;\n\twireSizes.set(response, size);\n}\n\n/** The wire size recorded for `response`, or undefined when never registered. */\nexport function getResponseWireSize(response: unknown): number | undefined {\n\tif (typeof response !== 'object' || response === null) return undefined;\n\treturn wireSizes.get(response);\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","import { RhinoComputeError, ErrorCodes } from '@/core/errors';\n\n/**\n * The public McNeel endpoint's host — disallowed as a `serverUrl`; users must point at\n * their own server. Compared against the parsed hostname lowercased and with any\n * trailing dot stripped, so the FQDN form (`compute.rhino3d.com.`) can't bypass it.\n * Known limitation: the endpoint's raw IP is not blocked — it sits behind a load\n * balancer with no single stable, verifiable address to pin.\n */\nconst DEFAULT_PUBLIC_HOST = 'compute.rhino3d.com';\n\n/**\n * Validate and normalize a Rhino Compute `serverUrl`.\n *\n * This is the single source of truth for \"is this a usable server URL?\" — both\n * `GrasshopperClient` (via `normalizeComputeConfig`) and the standalone-exported\n * `ComputeServerStats` constructor delegate here, so a given URL is accepted or\n * rejected identically no matter which entry point a caller uses.\n *\n * Rules (all enforced, on the *trimmed* input — the trimmed form is what's\n * returned, so no stray whitespace survives into later `fetch` calls):\n * - non-empty (after trim)\n * - `http://` or `https://` scheme (case-insensitive, per RFC 3986)\n * - parseable by `new URL()`\n * - no embedded credentials (`http://user:pass@host`) — `fetch`/`new Request`\n * reject credentialed URLs at runtime, so they must fail here instead\n * - no query string or fragment — endpoint paths are appended to this URL\n * (`${serverUrl}/version`), which a `?…` or `#…` suffix would corrupt\n * - not the public McNeel endpoint — compared by parsed hostname (lowercased,\n * trailing dot stripped), so scheme, casing, port, path, trailing-slash, or\n * FQDN-dot variants can't slip past the block\n *\n * @param raw - The candidate server URL.\n * @returns The trimmed, normalized URL with any trailing slashes removed.\n * @throws {RhinoComputeError} `INVALID_CONFIG` if any rule fails.\n */\nexport function validateServerUrl(raw: string): string {\n\tconst trimmed = raw?.trim() ?? '';\n\tif (!trimmed) {\n\t\tthrow new RhinoComputeError('serverUrl is required', ErrorCodes.INVALID_CONFIG, {\n\t\t\tcontext: { receivedServerUrl: raw }\n\t\t});\n\t}\n\n\tif (!/^https?:\\/\\//i.test(trimmed)) {\n\t\tthrow new RhinoComputeError(\n\t\t\t`Invalid serverUrl: \"${trimmed}\". Must start with \"http://\" or \"https://\". ` +\n\t\t\t\t`For example: \"http://localhost:5000\" or \"https://example.com\"`,\n\t\t\tErrorCodes.INVALID_CONFIG,\n\t\t\t{ context: { receivedServerUrl: raw } }\n\t\t);\n\t}\n\n\tlet parsed: URL;\n\ttry {\n\t\tparsed = new URL(trimmed);\n\t} catch (err) {\n\t\tthrow new RhinoComputeError(\n\t\t\t`Invalid serverUrl: \"${trimmed}\". Must be a valid URL. ` +\n\t\t\t\t`Received error: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\tErrorCodes.INVALID_CONFIG,\n\t\t\t{\n\t\t\t\tcontext: { receivedServerUrl: raw },\n\t\t\t\toriginalError: err instanceof Error ? err : undefined\n\t\t\t}\n\t\t);\n\t}\n\n\tif (parsed.username !== '' || parsed.password !== '') {\n\t\tthrow new RhinoComputeError(\n\t\t\t`Invalid serverUrl: \"${trimmed}\". Must not embed credentials (user:pass@host) — ` +\n\t\t\t\t`fetch rejects credentialed URLs at request time. Pass the API key separately.`,\n\t\t\tErrorCodes.INVALID_CONFIG,\n\t\t\t{ context: { receivedServerUrl: raw } }\n\t\t);\n\t}\n\n\t// String check rather than parsed.search/hash: a bare trailing \"?\" or \"#\"\n\t// parses to an empty search/hash but still corrupts endpoint concatenation.\n\tif (trimmed.includes('?') || trimmed.includes('#')) {\n\t\tthrow new RhinoComputeError(\n\t\t\t`Invalid serverUrl: \"${trimmed}\". Must not contain a query string or fragment — ` +\n\t\t\t\t`endpoint paths are appended to this URL (e.g. \"\\${serverUrl}/version\"), ` +\n\t\t\t\t`and a \"?\" or \"#\" suffix would corrupt every request path.`,\n\t\t\tErrorCodes.INVALID_CONFIG,\n\t\t\t{ context: { receivedServerUrl: raw } }\n\t\t);\n\t}\n\n\t// Lowercase + strip any trailing dot so the FQDN form can't bypass the block.\n\tconst hostname = parsed.hostname.toLowerCase().replace(/\\.+$/, '');\n\tif (hostname === DEFAULT_PUBLIC_HOST) {\n\t\tthrow new RhinoComputeError(\n\t\t\t'serverUrl must be set to your Compute server URL. The default public endpoint is not allowed.',\n\t\t\tErrorCodes.INVALID_CONFIG,\n\t\t\t{ context: { receivedServerUrl: raw } }\n\t\t);\n\t}\n\n\treturn trimmed.replace(/\\/+$/, '');\n}\n","import { RhinoComputeError, ErrorCodes } from '../errors';\nimport { getLogger } from '../utils/logger';\nimport { validateServerUrl } from './validate-server-url';\n\n/**\n * ComputeServerStats provides methods to query Rhino Compute server statistics.\n *\n * @public Use this for server health monitoring and statistics.\n *\n * @example\n * ```typescript\n * const stats = new ComputeServerStats('http://localhost:6500', 'your-api-key');\n *\n * try {\n * const isOnline = await stats.isServerOnline();\n * const children = await stats.getActiveChildren();\n * const version = await stats.getVersion();\n *\n * // Or get everything at once\n * const allStats = await stats.getServerStats();\n * } finally {\n * await stats.dispose(); // Clean up resources\n * }\n * ```\n */\nexport default class ComputeServerStats {\n\tprivate readonly serverUrl: string;\n\tprivate readonly apiKey?: string;\n\tprivate disposed = false;\n\tprivate activeMonitors: Set<() => void> = new Set();\n\tprivate activeTimeouts: Set<ReturnType<typeof setTimeout>> = new Set();\n\n\t/** Timeout (ms) for the fast read/monitoring endpoints. */\n\tprivate static readonly DEFAULT_TIMEOUT_MS = 5000;\n\n\t/** Timeout (ms) for child-lifecycle POSTs — a cold Windows child can take ~30s to spawn. */\n\tprivate static readonly LIFECYCLE_TIMEOUT_MS = 60_000;\n\n\t/** Floor for `monitor()`'s `intervalMs` — anything lower hot-loops the server. */\n\tprivate static readonly MIN_MONITOR_INTERVAL_MS = 100;\n\n\t/**\n\t * @param serverUrl - Base URL of the Rhino Compute server with http:// or https:// scheme (e.g., 'http://localhost:6500')\n\t * @param apiKey - Optional API key for authentication\n\t */\n\tconstructor(serverUrl: string, apiKey?: string) {\n\t\tthis.serverUrl = validateServerUrl(serverUrl);\n\t\tthis.apiKey = apiKey;\n\t}\n\n\t/**\n\t * Build request headers with optional API key.\n\t */\n\tprivate buildHeaders(): Record<string, string> {\n\t\tconst headers: Record<string, string> = {\n\t\t\t'Content-Type': 'application/json'\n\t\t};\n\n\t\tif (this.apiKey) {\n\t\t\theaders['RhinoComputeKey'] = this.apiKey;\n\t\t}\n\n\t\treturn headers;\n\t}\n\n\t/**\n\t * `fetch` wrapper that aborts after `timeoutMs` so a hung connection can't stall\n\t * a probe (or the `monitor()` loop) forever. Pass `0` to disable the timeout.\n\t */\n\tprivate fetchWithTimeout(\n\t\turl: string,\n\t\tinit: RequestInit = {},\n\t\ttimeoutMs: number = ComputeServerStats.DEFAULT_TIMEOUT_MS\n\t): Promise<Response> {\n\t\t// Merge caller headers OVER the defaults instead of `{ headers: …, ...init }`,\n\t\t// where any `init.headers` would silently replace the whole set (dropping\n\t\t// the API key). BOTH sides go through `new Headers()` so every key is\n\t\t// normalized (lowercased) identically — a caller's `Content-Type` replaces\n\t\t// the default instead of coexisting as a differently-cased duplicate that\n\t\t// the runtime would combine into \"application/json, text/plain\".\n\t\tconst merged = new Headers(this.buildHeaders());\n\t\tif (init.headers) {\n\t\t\tnew Headers(init.headers).forEach((value, key) => {\n\t\t\t\tmerged.set(key, value);\n\t\t\t});\n\t\t}\n\t\tconst headers: Record<string, string> = {};\n\t\tmerged.forEach((value, key) => {\n\t\t\theaders[key] = value;\n\t\t});\n\t\tconst requestInit: RequestInit = { ...init, headers };\n\t\tif (timeoutMs > 0 && !requestInit.signal) {\n\t\t\trequestInit.signal = AbortSignal.timeout(timeoutMs);\n\t\t}\n\t\treturn fetch(url, requestInit);\n\t}\n\n\t/**\n\t * Check if the server is online.\n\t *\n\t * This is a single-sample probe: it returns `true` only on a 2xx from the\n\t * proxy liveness root `/`, and `false` for every other outcome (non-2xx,\n\t * network error, or timeout). A cold or briefly-busy-but-up server can therefore\n\t * read as offline — callers that gate on this (e.g. client construction)\n\t * should retry rather than treat a single `false` as authoritative.\n\t *\n\t * @param timeoutMs - Abort the probe after this many ms (default: 5000).\n\t * Pass `0` to disable the timeout. Prevents a hung connection from\n\t * stalling the caller indefinitely.\n\t */\n\tpublic async isServerOnline(timeoutMs: number = 5000): Promise<boolean> {\n\t\tthis.ensureNotDisposed();\n\n\t\t// The rhino.compute proxy has no `/healthcheck` route; its real liveness\n\t\t// signal is `GET /`, which returns \"compute.rhino3d running\". Probing an\n\t\t// unknown path would instead be forwarded to a child and only tells us the\n\t\t// proxy can reach one.\n\t\tconst url = `${this.serverUrl}/`;\n\n\t\ttry {\n\t\t\tconst response = await this.fetchWithTimeout(url, { method: 'GET' }, timeoutMs);\n\n\t\t\treturn response.ok;\n\t\t} catch (err) {\n\t\t\tgetLogger().debug('[ComputeServerStats] Fetch error:', err);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Get the number of active child processes on the server.\n\t *\n\t * By default the proxy's `/activechildren` endpoint will *spawn* children up\n\t * to the configured count if none are running, then report the count — which\n\t * wakes (and bills) an idle server. Pass `{ initialize: false }` for a passive\n\t * read that reports the current count without spawning; use this for\n\t * monitoring or before a purge/probe where you must not wake the server.\n\t *\n\t * @param options.initialize - When `false`, append `?initialize=false` so the\n\t * server reports without spawning. Defaults to `true` (the server's default).\n\t * @returns Number of active children, or null if unavailable\n\t */\n\tpublic async getActiveChildren(options: { initialize?: boolean } = {}): Promise<number | null> {\n\t\tthis.ensureNotDisposed();\n\n\t\tconst { initialize = true } = options;\n\t\tconst url = initialize\n\t\t\t? `${this.serverUrl}/activechildren`\n\t\t\t: `${this.serverUrl}/activechildren?initialize=false`;\n\n\t\t// `initialize` mode may spawn children before answering — give it the\n\t\t// lifecycle budget; the passive read stays on the short default.\n\t\tconst timeoutMs = initialize\n\t\t\t? ComputeServerStats.LIFECYCLE_TIMEOUT_MS\n\t\t\t: ComputeServerStats.DEFAULT_TIMEOUT_MS;\n\n\t\ttry {\n\t\t\tconst response = await this.fetchWithTimeout(url, {}, timeoutMs);\n\t\t\tif (!response.ok) {\n\t\t\t\tgetLogger().warn('[ComputeServerStats] Failed to fetch active children:', response.status);\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\t// Strict integer parse: `parseInt` would accept garbage-prefixed bodies\n\t\t\t// (e.g. an HTML error page starting \"302 Found\" → 302 children).\n\t\t\tconst text = (await response.text()).trim();\n\t\t\tif (!/^\\d+$/.test(text)) {\n\t\t\t\tgetLogger().warn('[ComputeServerStats] Invalid active children response:', text);\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\treturn parseInt(text, 10);\n\t\t} catch (err) {\n\t\t\tgetLogger().warn('[ComputeServerStats] Error fetching active children:', err);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Get the server version information.\n\t *\n\t * @returns Version object with rhino, compute, and git_sha, or null if unavailable\n\t */\n\tpublic async getVersion(): Promise<{\n\t\trhino: string;\n\t\tcompute: string;\n\t\tgit_sha: string | null;\n\t} | null> {\n\t\tthis.ensureNotDisposed();\n\n\t\ttry {\n\t\t\tconst response = await this.fetchWithTimeout(`${this.serverUrl}/version`);\n\n\t\t\tif (!response.ok) {\n\t\t\t\tgetLogger().warn('[ComputeServerStats] Failed to fetch version:', response.status);\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\t// Read body as text first, then try JSON.parse — avoids the\n\t\t\t// \"Body has already been read\" error if response.json() fails.\n\t\t\tconst text = await response.text();\n\t\t\ttry {\n\t\t\t\tconst json = JSON.parse(text);\n\t\t\t\treturn {\n\t\t\t\t\trhino: json.rhino ?? '',\n\t\t\t\t\tcompute: json.compute ?? '',\n\t\t\t\t\tgit_sha: json.git_sha ?? null\n\t\t\t\t};\n\t\t\t} catch {\n\t\t\t\treturn { rhino: text, compute: '', git_sha: null };\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tgetLogger().warn('[ComputeServerStats] Error fetching version:', err);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Get the plugins installed on the server.\n\t *\n\t * Returns a `name → version` map of non-core plugins the server has loaded,\n\t * or `null` if the request failed. Pass `kind` to choose which inventory:\n\t * `'gh'` (default) lists Grasshopper add-on assemblies via\n\t * `/plugins/gh/installed`; `'rhino'` lists Rhino plugins via\n\t * `/plugins/rhino/installed`. Plugins that ship with Rhino / are core\n\t * libraries are excluded by the server.\n\t *\n\t * @param kind - `'gh'` for Grasshopper add-ons (default) or `'rhino'` for Rhino plugins.\n\t * @returns Map of plugin name to version, or `null` on failure.\n\t *\n\t * @example\n\t * ```ts\n\t * const gh = await stats.getInstalledPlugins(); // Grasshopper add-ons\n\t * const selvaVersion = gh?.['Selva'] ?? null;\n\t * ```\n\t */\n\tpublic async getInstalledPlugins(\n\t\tkind: 'gh' | 'rhino' = 'gh'\n\t): Promise<Record<string, string> | null> {\n\t\tthis.ensureNotDisposed();\n\n\t\ttry {\n\t\t\tconst response = await this.fetchWithTimeout(`${this.serverUrl}/plugins/${kind}/installed`);\n\n\t\t\tif (!response.ok) {\n\t\t\t\tgetLogger().warn(`[ComputeServerStats] Failed to fetch ${kind} plugins:`, response.status);\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\t// Text-first so a non-JSON body can't throw \"body already read\".\n\t\t\tconst text = await response.text();\n\t\t\ttry {\n\t\t\t\tconst json = JSON.parse(text);\n\t\t\t\treturn json && typeof json === 'object' ? (json as Record<string, string>) : null;\n\t\t\t} catch {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tgetLogger().warn(`[ComputeServerStats] Error fetching ${kind} plugins:`, err);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Get comprehensive server statistics.\n\t * Fetches all available server information in parallel.\n\t *\n\t * @returns Object containing server status and available stats\n\t */\n\tpublic async getServerStats(): Promise<{\n\t\tisOnline: boolean;\n\t\tversion?: { rhino: string; compute: string; git_sha: string | null };\n\t\tactiveChildren?: number;\n\t}> {\n\t\tthis.ensureNotDisposed();\n\n\t\tconst isOnline = await this.isServerOnline();\n\n\t\tif (!isOnline) {\n\t\t\treturn { isOnline: false };\n\t\t}\n\n\t\t// Passive child count — never spawn from a stats read, or merely viewing\n\t\t// server health would wake (and bill) an idle server.\n\t\tconst [version, activeChildren] = await Promise.all([\n\t\t\tthis.getVersion(),\n\t\t\tthis.getActiveChildren({ initialize: false })\n\t\t]);\n\n\t\treturn {\n\t\t\tisOnline: true,\n\t\t\t...(version && { version }),\n\t\t\t...(activeChildren !== null && { activeChildren })\n\t\t};\n\t}\n\n\t/**\n\t * Purge the server's solve-results / URL-data cache.\n\t *\n\t * POSTs to `cache/purge` and returns the number of entries removed, or `null`\n\t * if the request failed. This clears cached solve responses and fetched\n\t * definition-URL data; it does NOT evict the definition cache (active\n\t * `pointer` references stay valid).\n\t *\n\t * **Caveat:** `cache/purge` is forwarded by the rhino.compute proxy to a\n\t * single round-robin-selected child, so in a multi-child deployment one call\n\t * purges one child's cache. Call repeatedly (or size the pool to 1) if you\n\t * need a fleet-wide purge.\n\t *\n\t * @returns Number of entries removed, or `null` on failure.\n\t *\n\t * @example\n\t * ```ts\n\t * const removed = await stats.purgeCache();\n\t * if (removed !== null) console.log(`Purged ${removed} cached solves`);\n\t * ```\n\t */\n\tpublic async purgeCache(): Promise<number | null> {\n\t\tthis.ensureNotDisposed();\n\n\t\ttry {\n\t\t\tconst response = await this.fetchWithTimeout(`${this.serverUrl}/cache/purge`, {\n\t\t\t\tmethod: 'POST'\n\t\t\t});\n\n\t\t\tif (!response.ok) {\n\t\t\t\tgetLogger().warn('[ComputeServerStats] Failed to purge cache:', response.status);\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\t// Read text-first so a non-JSON body can't throw \"body already read\".\n\t\t\tconst text = await response.text();\n\t\t\ttry {\n\t\t\t\tconst json = JSON.parse(text);\n\t\t\t\treturn typeof json.purged === 'number' ? json.purged : null;\n\t\t\t} catch {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tgetLogger().warn('[ComputeServerStats] Error purging cache:', err);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Best-effort fleet-wide cache purge across a multi-child deployment.\n\t *\n\t * A single {@link purgeCache} POST is forwarded by the rhino.compute proxy to\n\t * just ONE round-robin-selected child, so the other children keep serving\n\t * stale cached solves. There is no proxy endpoint that addresses children\n\t * individually, so this method reads the active child count (passively, never\n\t * spawning) and fires `2 × count` sequential purges, relying on the proxy's\n\t * round-robin to spread the hits across the pool.\n\t *\n\t * **This is best-effort, not a guarantee.** Round-robin can revisit one child\n\t * and skip another; under concurrent traffic the rotation drifts. The result's\n\t * `confident` flag is `true` only when the server reports a single child (where\n\t * one purge is exact) — surface it so callers don't over-promise. For a hard\n\t * fleet-wide guarantee, run the deployment at `--childcount 1` or add a\n\t * server-side fan-out endpoint.\n\t *\n\t * @returns `{ totalPurged, calls, children, confident }`, or `null` if the\n\t * child count couldn't be read (server unreachable). `totalPurged` sums the\n\t * per-call counts; `calls` is how many purges were issued; `children` is the\n\t * reported pool size; `confident` is `true` only at a single-child pool.\n\t *\n\t * @example\n\t * ```ts\n\t * const r = await stats.purgeAllChildren();\n\t * if (r && !r.confident) {\n\t * console.warn(`Purged ~${r.totalPurged} across ${r.children} children (best-effort)`);\n\t * }\n\t * ```\n\t */\n\tpublic async purgeAllChildren(): Promise<{\n\t\ttotalPurged: number;\n\t\tcalls: number;\n\t\tchildren: number;\n\t\tconfident: boolean;\n\t} | null> {\n\t\tthis.ensureNotDisposed();\n\n\t\t// Passive read — must not spawn children just to purge them.\n\t\tconst children = await this.getActiveChildren({ initialize: false });\n\t\tif (children === null) {\n\t\t\tgetLogger().warn('[ComputeServerStats] purgeAllChildren: could not read child count');\n\t\t\treturn null;\n\t\t}\n\n\t\tif (children === 0) {\n\t\t\t// No live children means nothing is cached on the compute side.\n\t\t\treturn { totalPurged: 0, calls: 0, children: 0, confident: true };\n\t\t}\n\n\t\t// 2× the pool size gives round-robin a strong chance of reaching every\n\t\t// child at least once. Sequential (not parallel) so the proxy advances its\n\t\t// round-robin cursor one child per call rather than racing them onto one.\n\t\tconst calls = children * 2;\n\t\tlet totalPurged = 0;\n\t\tfor (let i = 0; i < calls; i++) {\n\t\t\tconst purged = await this.purgeCache();\n\t\t\tif (purged !== null) totalPurged += purged;\n\t\t}\n\n\t\treturn { totalPurged, calls, children, confident: children === 1 };\n\t}\n\n\t/**\n\t * Get the server's current UTC clock.\n\t *\n\t * GETs `/servertime`, which the server emits as a JSON-encoded ISO-8601\n\t * timestamp (e.g. `\"2026-06-18T08:30:00Z\"`). Useful for detecting clock skew\n\t * between caller and server. Returns `null` if the request failed or the body\n\t * isn't a parseable date.\n\t *\n\t * @returns A `Date` for the server's UTC time, or `null` on failure.\n\t */\n\tpublic async getServerTime(): Promise<Date | null> {\n\t\tthis.ensureNotDisposed();\n\n\t\ttry {\n\t\t\tconst response = await this.fetchWithTimeout(`${this.serverUrl}/servertime`);\n\t\t\tif (!response.ok) {\n\t\t\t\tgetLogger().warn('[ComputeServerStats] Failed to fetch server time:', response.status);\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\t// Body is a JSON string (\"2026-…Z\"); strip surrounding quotes if present.\n\t\t\tconst text = (await response.text()).trim().replace(/^\"|\"$/g, '');\n\t\t\tconst date = new Date(text);\n\t\t\treturn isNaN(date.getTime()) ? null : date;\n\t\t} catch (err) {\n\t\t\tgetLogger().warn('[ComputeServerStats] Error fetching server time:', err);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Get how long the rhino.compute proxy has been idle.\n\t *\n\t * GETs `/idlespan` on the proxy, which returns the seconds elapsed since the\n\t * last request was forwarded to a compute child. This is a proxy-level metric\n\t * (not proxied to a child) used by autoscalers to decide when a node can be\n\t * drained. Returns `null` if unavailable.\n\t *\n\t * @returns Idle time in seconds, or `null` on failure.\n\t */\n\tpublic async getIdleSpan(): Promise<number | null> {\n\t\tthis.ensureNotDisposed();\n\n\t\ttry {\n\t\t\tconst response = await this.fetchWithTimeout(`${this.serverUrl}/idlespan`);\n\t\t\tif (!response.ok) {\n\t\t\t\tgetLogger().warn('[ComputeServerStats] Failed to fetch idle span:', response.status);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst seconds = parseFloat((await response.text()).trim());\n\t\t\treturn isNaN(seconds) ? null : seconds;\n\t\t} catch (err) {\n\t\t\tgetLogger().warn('[ComputeServerStats] Error fetching idle span:', err);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Fill the compute child pool up to the server's configured baseline.\n\t *\n\t * POSTs `/launch-children`. No-op when the pool is already at or above the\n\t * configured `--childcount`. Returns `{ spawned, active }` — how many children\n\t * were started and the resulting child count — or `null` on failure.\n\t *\n\t * To raise capacity above the baseline use {@link launchChild}; the baseline\n\t * itself can only be changed by restarting rhino.compute.\n\t *\n\t * @returns `{ spawned, active }`, or `null` on failure.\n\t */\n\tpublic async launchChildren(): Promise<{ spawned: number[]; active: number } | null> {\n\t\treturn this.postJson('/launch-children');\n\t}\n\n\t/**\n\t * Add a single compute child to the pool, optionally on a specific port.\n\t *\n\t * POSTs `/launch-child` (with `?port=N` when `port` is given). Unlike\n\t * {@link launchChildren}, this can push the pool above the baseline, up to the\n\t * server's `MaxChildren` cap. Returns `{ spawned: [port] }` on success, or\n\t * `null` on failure (server replies 400 for a bad port, 409 if the port is in\n\t * use, 503 at the max-children cap).\n\t *\n\t * @param port - Optional specific port to launch on; otherwise the next free one.\n\t * @returns `{ spawned }` listing the launched port, or `null` on failure.\n\t */\n\tpublic async launchChild(port?: number): Promise<{ spawned: number[] } | null> {\n\t\tconst path = port === undefined ? '/launch-child' : `/launch-child?port=${port}`;\n\t\treturn this.postJson(path);\n\t}\n\n\t/**\n\t * Gracefully shut down compute children without respawning them.\n\t *\n\t * POSTs `/shutdown-children`. With no `port` it shuts down every child; with\n\t * `port` it targets just that one. Children do not respawn, but the next\n\t * `/grasshopper` request auto-spawns the pool back to the baseline. Returns\n\t * `{ shutdown, active }` — how many were stopped and the remaining count — or\n\t * `null` on failure.\n\t *\n\t * @param port - Optional port to target; omit to shut down all children.\n\t * @returns `{ shutdown, active }`, or `null` on failure.\n\t */\n\tpublic async shutdownChildren(\n\t\tport?: number\n\t): Promise<{ shutdown: number; active: number } | null> {\n\t\tconst path = port === undefined ? '/shutdown-children' : `/shutdown-children?port=${port}`;\n\t\treturn this.postJson(path);\n\t}\n\n\t/**\n\t * Shut down compute children and respawn replacements (rolling restart).\n\t *\n\t * POSTs `/recycle-children`. With no `port` it recycles every child; with\n\t * `port` it recycles just that one. The server recycles sequentially (each\n\t * replacement is serving before the next child is stopped) so the pool never\n\t * drops to zero mid-recycle. Returns `{ shutdown, spawned, active }`, or\n\t * `null` on failure.\n\t *\n\t * @param port - Optional port to target; omit to recycle all children.\n\t * @returns `{ shutdown, spawned, active }`, or `null` on failure.\n\t */\n\tpublic async recycleChildren(\n\t\tport?: number\n\t): Promise<{ shutdown: number; spawned: number[]; active: number } | null> {\n\t\tconst path = port === undefined ? '/recycle-children' : `/recycle-children?port=${port}`;\n\t\treturn this.postJson(path);\n\t}\n\n\t/**\n\t * POST a control endpoint that replies with a JSON object and return it,\n\t * degrading to `null` on any non-2xx, non-JSON, or network failure. Shared by\n\t * the child-lifecycle methods so their failure semantics stay identical. Uses\n\t * the longer lifecycle timeout since a spawn/recycle can take ~30s.\n\t */\n\tprivate async postJson<T>(path: string): Promise<T | null> {\n\t\tthis.ensureNotDisposed();\n\n\t\ttry {\n\t\t\tconst response = await this.fetchWithTimeout(\n\t\t\t\t`${this.serverUrl}${path}`,\n\t\t\t\t{ method: 'POST' },\n\t\t\t\tComputeServerStats.LIFECYCLE_TIMEOUT_MS\n\t\t\t);\n\t\t\tif (!response.ok) {\n\t\t\t\tgetLogger().warn(`[ComputeServerStats] POST ${path} failed:`, response.status);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\t// Text-first so a non-JSON body can't throw \"body already read\".\n\t\t\tconst text = await response.text();\n\t\t\ttry {\n\t\t\t\treturn JSON.parse(text) as T;\n\t\t\t} catch {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tgetLogger().warn(`[ComputeServerStats] Error on POST ${path}:`, err);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Continuously monitor server stats at specified interval.\n\t *\n\t * @param callback - Function called with stats on each interval\n\t * @param intervalMs - Milliseconds between checks (default: 5000). Must be a\n\t * finite number of at least 100 ms — lower values would hot-loop the server.\n\t * @returns Function to stop monitoring\n\t * @throws {RangeError} If `intervalMs` is not a finite number >= 100.\n\t *\n\t * @example\n\t * ```typescript\n\t * const stopMonitoring = stats.monitor((data) => {\n\t * console.log('Server stats:', data);\n\t * }, 3000);\n\t *\n\t * // Later...\n\t * stopMonitoring();\n\t * ```\n\t */\n\tpublic monitor(\n\t\tcallback: (stats: Awaited<ReturnType<typeof this.getServerStats>>) => void,\n\t\tintervalMs: number = 5000\n\t): () => void {\n\t\tthis.ensureNotDisposed();\n\n\t\tif (!Number.isFinite(intervalMs) || intervalMs < ComputeServerStats.MIN_MONITOR_INTERVAL_MS) {\n\t\t\tthrow new RangeError(\n\t\t\t\t`monitor() intervalMs must be a finite number >= ${ComputeServerStats.MIN_MONITOR_INTERVAL_MS}ms, ` +\n\t\t\t\t\t`got ${intervalMs}. Sub-${ComputeServerStats.MIN_MONITOR_INTERVAL_MS}ms polling would hot-loop the server.`\n\t\t\t);\n\t\t}\n\n\t\tlet active = true;\n\t\tlet currentTimeoutId: ReturnType<typeof setTimeout> | null = null;\n\n\t\tgetLogger().info(`🔄 Starting server stats monitoring every ${intervalMs}ms`);\n\n\t\tconst check = async () => {\n\t\t\t// Clear current timeout from tracking since it has fired\n\t\t\tif (currentTimeoutId !== null) {\n\t\t\t\tthis.activeTimeouts.delete(currentTimeoutId);\n\t\t\t\tcurrentTimeoutId = null;\n\t\t\t}\n\n\t\t\tif (!active || this.disposed) return;\n\n\t\t\ttry {\n\t\t\t\tconst _stats = await this.getServerStats();\n\n\t\t\t\t// Check again after async operation to prevent race condition\n\t\t\t\tif (!active || this.disposed) return;\n\n\t\t\t\ttry {\n\t\t\t\t\tcallback(_stats);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tgetLogger().error('[ComputeServerStats] Monitor callback threw:', err);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tif (!active || this.disposed) {\n\t\t\t\t\t// dispose()/stop racing an in-flight poll is normal shutdown, not an\n\t\t\t\t\t// error — the nested ensureNotDisposed() throw is expected here.\n\t\t\t\t\tgetLogger().debug('[ComputeServerStats] Monitor poll cancelled during shutdown:', err);\n\t\t\t\t} else {\n\t\t\t\t\tgetLogger().error('[ComputeServerStats] Failed to fetch stats during monitor:', err);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (active && !this.disposed) {\n\t\t\t\tcurrentTimeoutId = setTimeout(() => void check(), intervalMs);\n\t\t\t\tthis.activeTimeouts.add(currentTimeoutId);\n\t\t\t}\n\t\t};\n\n\t\tconst stopMonitoring = () => {\n\t\t\tactive = false;\n\n\t\t\t// Clear any pending timeout\n\t\t\tif (currentTimeoutId !== null) {\n\t\t\t\tclearTimeout(currentTimeoutId);\n\t\t\t\tthis.activeTimeouts.delete(currentTimeoutId);\n\t\t\t\tcurrentTimeoutId = null;\n\t\t\t}\n\n\t\t\tthis.activeMonitors.delete(stopMonitoring);\n\t\t};\n\n\t\tthis.activeMonitors.add(stopMonitoring);\n\n\t\t// Explicitly mark as fire-and-forget since we don't need to await the initial call\n\t\tvoid check();\n\n\t\treturn stopMonitoring;\n\t}\n\n\t/**\n\t * Disposes of all resources and stops all active monitors.\n\t * Call this when you're done using the stats instance.\n\t */\n\tpublic async dispose(): Promise<void> {\n\t\tif (this.disposed) return;\n\n\t\tthis.disposed = true;\n\n\t\t// Stop all active monitors (this will also clear their timeouts)\n\t\tfor (const stopMonitor of this.activeMonitors) {\n\t\t\tstopMonitor();\n\t\t}\n\t\tthis.activeMonitors.clear();\n\n\t\t// Clear any remaining timeouts (defensive cleanup)\n\t\tfor (const timeoutId of this.activeTimeouts) {\n\t\t\tclearTimeout(timeoutId);\n\t\t}\n\t\tthis.activeTimeouts.clear();\n\t}\n\n\t/**\n\t * Ensures the instance hasn't been disposed.\n\t */\n\tprivate ensureNotDisposed(): void {\n\t\tif (this.disposed) {\n\t\t\tthrow new RhinoComputeError(\n\t\t\t\t'ComputeServerStats has been disposed and cannot be used',\n\t\t\t\tErrorCodes.INVALID_STATE,\n\t\t\t\t{ context: { disposed: this.disposed } }\n\t\t\t);\n\t\t}\n\t}\n}\n","import { getLogger } from './logger';\n\n/**\n * Converts a string to camelCase.\n *\n * Handling of the awkward shapes (fixed 2026-07-12 — issue 109; behavior\n * change from the earlier version, which only lowercased the first character\n * and kept leading separators):\n *\n * - Leading/trailing separators are stripped: `'_foo'` → `'foo'`,\n * `'__proto__'` → `'proto'` (the output can never contain `-`/`_`, so a\n * camelCased key can never be `'__proto__'` — proto pollution via\n * {@link camelcaseKeys} stays impossible).\n * - Leading acronym runs are lowercased as a unit: `'URLPath'` → `'urlPath'`,\n * `'IDNumber'` → `'idNumber'`, `'URL'` → `'url'` (previously `'uRLPath'`,\n * `'iDNumber'`, `'uRL'`).\n *\n * @param str - The string to convert\n * @param options - Options object\n * - preserveSpaces: If true, spaces are preserved (default: false)\n */\nexport function toCamelCase(str: string, options: { preserveSpaces?: boolean } = {}): string {\n\tconst { preserveSpaces = false } = options;\n\tconst sep = preserveSpaces ? /[-_]+(.)?/g : /[\\s\\-_]+(.)?/g;\n\tlet out = str.trim().replace(sep, (_, c: string | undefined) => (c ? c.toUpperCase() : ''));\n\t// Lowercase a leading acronym run in full — all uppercase letters up to\n\t// (but not including) one that starts a normal Word, or to the end.\n\tout = out.replace(/^[A-Z]+(?=[A-Z][a-z]|[^A-Za-z]|$)/, (m) => m.toLowerCase());\n\treturn out.charAt(0).toLowerCase() + out.slice(1);\n}\n\n/** Plain object = prototype is `Object.prototype` or `null` (JSON-shaped data). */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n\tif (value === null || typeof value !== 'object') return false;\n\tconst proto = Object.getPrototypeOf(value);\n\treturn proto === Object.prototype || proto === null;\n}\n\n/**\n * Recursively converts all object keys to camelCase.\n *\n * Only PLAIN objects (prototype `Object.prototype`/`null`) and arrays are\n * traversed; any other object — `Date`, `Map`, `Set`, `Uint8Array`/typed\n * arrays, class instances, … — is passed through untouched (previously deep\n * mode reduced a `Date` to `{}` and a `Uint8Array` to `{0: …, 1: …}`).\n *\n * When two keys camelCase to the same name (`inner_tree` + `innerTree`), the\n * LAST one in key order wins (matching plain object-spread semantics) and a\n * warning is logged naming both keys — the earlier value is silently\n * unreachable otherwise.\n *\n * @warning Do not use `deep: true` on Rhino Compute wire payloads: it\n * corrupts user-authored keys (value-list labels, item `data` JSON). Read the\n * specific fields you need case-insensitively with `readField`/`hasField` from\n * `core/utils/read-field` instead. Shallow (non-deep) use on wrapper keys is fine.\n *\n * @param obj - The object to process\n * @param options - Options object\n * - deep: If true, process deeply\n * - preserveSpaces: If true, spaces are preserved in keys\n * @returns The new object with camelCased keys\n * @internal\n */\nexport function camelcaseKeys(\n\tobj: unknown,\n\toptions: { deep?: boolean; preserveSpaces?: boolean } = {}\n): unknown {\n\tif (!obj || typeof obj !== 'object') {\n\t\treturn obj;\n\t}\n\n\tif (Array.isArray(obj)) {\n\t\treturn options.deep ? obj.map((item) => camelcaseKeys(item, options)) : obj;\n\t}\n\n\t// Non-plain objects (Date, Map, TypedArray, class instances, …) carry\n\t// behavior/internal slots that key-mapping would destroy — pass through.\n\tif (!isPlainObject(obj)) {\n\t\treturn obj;\n\t}\n\n\tconst result: Record<string, unknown> = {};\n\tfor (const key of Object.keys(obj)) {\n\t\tconst camelKey = toCamelCase(key, { preserveSpaces: options.preserveSpaces });\n\t\tif (Object.prototype.hasOwnProperty.call(result, camelKey)) {\n\t\t\tgetLogger().warn(\n\t\t\t\t`camelcaseKeys: key '${key}' collides with an earlier key on '${camelKey}' — the earlier value is overwritten (last key wins).`\n\t\t\t);\n\t\t}\n\t\tconst value = obj[key];\n\t\tresult[camelKey] = options.deep ? camelcaseKeys(value, options) : value;\n\t}\n\treturn result;\n}\n","/**\n * Case-insensitive single-key reader for wire payloads.\n *\n * The Rhino Compute family serializes the same logical field with different\n * casing depending on the server branch:\n *\n * - mcneel 8.x / 9.x: the IO schema is PascalCase (`ParamType`, `Default`,\n * `InnerTree`, …) because those C# classes carry no `[JsonProperty]`.\n * - VektorNode Compute8: the IO schema is camelCase (`paramType`, `default`,\n * …) because the fork added `[JsonProperty(\"camelCase\")]`, BUT the nested\n * `default` DataTree wrapper stays PascalCase (`ParamName` / `InnerTree`)\n * since `Resthopper.IO.DataTree` is an external type the fork can't attribute.\n *\n * So a single response can mix casings, and which casing a given field uses\n * depends on the server branch. Rather than deep-camelCasing the whole payload\n * (the old `camelcaseKeys` approach — which corrupted user-authored value-list\n * label keys and item `data` JSON), read the specific fields we care about\n * case-insensitively and leave everything else verbatim.\n *\n * Prefers an exact-case match when present, then falls back to the first\n * case-insensitive match. Returns `undefined` when no key matches.\n *\n * @param obj - The source object (any non-object input yields `undefined`).\n * @param name - The logical field name, in any casing.\n */\nexport function readField<T = unknown>(obj: unknown, name: string): T | undefined {\n\tif (!obj || typeof obj !== 'object') return undefined;\n\n\tconst record = obj as Record<string, unknown>;\n\t// Own-property check to avoid prototype chain lookups (see lowerKeyMap for full explanation).\n\tif (hasOwn(record, name)) return record[name] as T;\n\n\tconst key = lowerKeyMap(record).get(name.toLowerCase());\n\treturn key === undefined ? undefined : (record[key] as T);\n}\n\nconst hasOwn = (record: object, key: string): boolean =>\n\tObject.prototype.hasOwnProperty.call(record, key);\n\n/**\n * True when `obj` has a key matching `name` (case-insensitively). Distinguishes\n * \"field present but value is null/undefined\" from \"field absent\" — needed where\n * presence itself carries meaning (e.g. an `innerTree` that exists but is empty).\n */\nexport function hasField(obj: unknown, name: string): boolean {\n\tif (!obj || typeof obj !== 'object') return false;\n\tconst record = obj as Record<string, unknown>;\n\t// Own-property check only.\n\tif (hasOwn(record, name)) return true;\n\treturn lowerKeyMap(record).has(name.toLowerCase());\n}\n\n/**\n * Per-object cache of lowercased key → actual key. Invalidated by key-count changes.\n * Known limitation: key replacement without count change goes undetected (acceptable\n * since this mutation pattern doesn't occur in this codebase).\n */\nconst lowerKeyCache = new WeakMap<object, { keyCount: number; map: Map<string, string> }>();\n\nfunction lowerKeyMap(record: Record<string, unknown>): Map<string, string> {\n\tconst keys = Object.keys(record);\n\tconst cached = lowerKeyCache.get(record);\n\tif (cached && cached.keyCount === keys.length) return cached.map;\n\n\tconst map = new Map<string, string>();\n\tfor (const key of keys) {\n\t\tconst lower = key.toLowerCase();\n\t\tif (!map.has(lower)) map.set(lower, key);\n\t}\n\tlowerKeyCache.set(record, { keyCount: keys.length, map });\n\treturn map;\n}\n","import { RhinoComputeError, ErrorCodes } from '@/core/errors';\nimport { getLogger } from '@/core/utils/logger';\nimport { decodeBase64ToBinary } from '@/core/utils/encoding';\nimport { readField } from '@/core/utils/read-field';\n\nimport { FileBaseInfo, FileData, ProcessedFile } from './types';\n\n/** Extracts and processes files from compute response data without downloading them. */\nexport const extractFilesFromComputeResponse = async (\n\tdownloadableFiles: FileData[],\n\tadditionalFiles: FileBaseInfo[] | FileBaseInfo | null = null\n): Promise<ProcessedFile[]> => {\n\ttry {\n\t\treturn await processFiles(downloadableFiles, additionalFiles);\n\t} catch (err) {\n\t\tthrow new RhinoComputeError(\n\t\t\t'Failed to extract files from compute response',\n\t\t\tErrorCodes.INVALID_STATE,\n\t\t\t{\n\t\t\t\tcontext: { originalError: err instanceof Error ? err.message : String(err) },\n\t\t\t\toriginalError: err instanceof Error ? err : undefined\n\t\t\t}\n\t\t);\n\t}\n};\n\n/** Downloads files from a compute response as a ZIP archive. */\nexport const downloadFileData = async (\n\tdownloadableFiles: FileData[],\n\tfileFoldername: string,\n\tadditionalFiles: FileBaseInfo[] | FileBaseInfo | null = null\n): Promise<void> => {\n\t// Check if we're in a browser environment\n\tif (typeof document === 'undefined' || typeof Blob === 'undefined') {\n\t\tthrow new RhinoComputeError(\n\t\t\t'File download functionality is only available in browser environments. This function requires the DOM API (document, Blob).',\n\t\t\tErrorCodes.BROWSER_ONLY,\n\t\t\t{\n\t\t\t\tcontext: {\n\t\t\t\t\tenvironment: typeof window !== 'undefined' ? 'browser (SSR)' : 'Node.js',\n\t\t\t\t\tdocumentAvailable: typeof document !== 'undefined',\n\t\t\t\t\tblobAvailable: typeof Blob !== 'undefined'\n\t\t\t\t}\n\t\t\t}\n\t\t);\n\t}\n\n\ttry {\n\t\tconst processedFiles = await processFiles(downloadableFiles, additionalFiles);\n\t\tawait createAndDownloadZip(processedFiles, fileFoldername);\n\t} catch (err) {\n\t\t// Re-throw if it's already a RhinoComputeError\n\t\tif (err instanceof RhinoComputeError) {\n\t\t\tthrow err;\n\t\t}\n\t\tthrow new RhinoComputeError(\n\t\t\t'Failed to download files from compute response',\n\t\t\tErrorCodes.INVALID_STATE,\n\t\t\t{\n\t\t\t\tcontext: { originalError: err instanceof Error ? err.message : String(err) },\n\t\t\t\toriginalError: err instanceof Error ? err : undefined\n\t\t\t}\n\t\t);\n\t}\n};\n\n/**\n * Reduce a server-controlled path field to safe relative segments for use inside the zip\n * (zip-slip defense): backslashes normalize to `/`, and empty, `.`, `..`, and drive-letter\n * segments are dropped so no entry can escape the extraction directory via traversal or an\n * absolute path. Returns '' when nothing safe remains.\n */\nconst sanitizeArchivePath = (raw: string): string =>\n\traw\n\t\t.replace(/\\\\/g, '/')\n\t\t.split('/')\n\t\t.map((segment) => segment.trim())\n\t\t.filter(\n\t\t\t(segment) =>\n\t\t\t\tsegment !== '' && segment !== '.' && segment !== '..' && !/^[a-zA-Z]:$/.test(segment)\n\t\t)\n\t\t.join('/');\n\n/**\n * Lenient read of the `isBase64Encoded` wire flag: some server branches serialize\n * booleans as strings (`\"true\"`/`\"True\"`), which must still count as base64 rather\n * than silently dropping the file (issue 95).\n */\nconst isBase64Flag = (flag: unknown): boolean =>\n\tflag === true || (typeof flag === 'string' && flag.trim().toLowerCase() === 'true');\n\n/**\n * Decode the inline files carried in a compute response into `ProcessedFile`s.\n *\n * Pure and synchronous: base64 items are decoded to binary, plain-text items are\n * passed through, and the archive path is derived from `subFolder` + name.\n * Degrades per-file like {@link fetchRemoteFiles}: an item with no usable `data`\n * or with undecodable base64 is logged and skipped, never aborting the batch.\n * This is the half of file handling that both public entry points share; it\n * never touches the network and never throws.\n *\n * Wire fields are read case-insensitively via {@link readField}: mcneel-branch\n * servers serialize PascalCase (`FileName`, `Data`, `IsBase64Encoded`, …) while\n * the VektorNode fork uses camelCase — both must decode (issue 95).\n *\n * @param dataItems - `FileData` items from the compute response.\n * @returns The decoded files.\n */\nconst decodeResponseFiles = (dataItems: FileData[]): ProcessedFile[] => {\n\tconst processedFiles: ProcessedFile[] = [];\n\n\tdataItems.forEach((item) => {\n\t\tconst rawName = readField<string>(item, 'fileName') ?? '';\n\t\tconst rawType = readField<string>(item, 'fileType') ?? '';\n\t\tconst fileName = sanitizeArchivePath(`${rawName}${rawType}`);\n\t\tif (fileName === '') {\n\t\t\tgetLogger().warn(\n\t\t\t\t`Skipping file with unusable name \"${rawName}${rawType}\": no safe archive path remains after sanitization.`\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tconst rawSubFolder = readField<string>(item, 'subFolder');\n\t\tconst subFolder = rawSubFolder ? sanitizeArchivePath(rawSubFolder) : '';\n\t\tconst filePath = subFolder !== '' ? `${subFolder}/${fileName}` : fileName;\n\n\t\t// Only a genuinely absent/empty body is unusable — the flag's exact type\n\t\t// must never decide that (issue 95).\n\t\tconst data = readField<unknown>(item, 'data');\n\t\tif (typeof data !== 'string' || data === '') {\n\t\t\tgetLogger().warn(`Skipping file \"${filePath}\": item carries no usable data.`);\n\t\t\treturn;\n\t\t}\n\n\t\tif (isBase64Flag(readField<unknown>(item, 'isBase64Encoded'))) {\n\t\t\t// `decodeBase64ToBinary` already returns a correctly-bounded view;\n\t\t\t// re-wrapping `.buffer` would discard its byteOffset/byteLength and\n\t\t\t// expose the whole (possibly pooled) backing buffer as corrupt content.\n\t\t\ttry {\n\t\t\t\tprocessedFiles.push({\n\t\t\t\t\tfileName,\n\t\t\t\t\tcontent: decodeBase64ToBinary(data),\n\t\t\t\t\tpath: filePath\n\t\t\t\t});\n\t\t\t} catch (err) {\n\t\t\t\tgetLogger().warn(`Skipping file \"${filePath}\": base64 decode failed.`, err);\n\t\t\t}\n\t\t} else {\n\t\t\tprocessedFiles.push({\n\t\t\t\tfileName,\n\t\t\t\tcontent: data,\n\t\t\t\tpath: filePath\n\t\t\t});\n\t\t}\n\t});\n\n\treturn processedFiles;\n};\n\n/** Abort a hung external-file fetch — one dead URL must degrade the batch, not stall it forever. */\nconst REMOTE_FILE_TIMEOUT_MS = 30_000;\n\n/**\n * Fetch externally-referenced files over HTTP into `ProcessedFile`s.\n *\n * Async and fallible by nature. A failed fetch (network error, non-OK status,\n * or timeout after {@link REMOTE_FILE_TIMEOUT_MS}) is logged and that file is\n * dropped — the rest still resolve — so one dead URL degrades the result rather\n * than aborting the whole batch. This swallow is deliberate and pinned by\n * tests; callers receive only the files that succeeded.\n *\n * @param refs - External file references to fetch.\n * @returns The successfully-fetched files (failures omitted).\n */\nconst fetchRemoteFiles = async (refs: FileBaseInfo[]): Promise<ProcessedFile[]> => {\n\tconst fetched = await Promise.all(\n\t\trefs.map(async (file) => {\n\t\t\ttry {\n\t\t\t\tconst signal =\n\t\t\t\t\ttypeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function'\n\t\t\t\t\t\t? AbortSignal.timeout(REMOTE_FILE_TIMEOUT_MS)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tconst response = await fetch(file.filePath, { signal });\n\t\t\t\tif (!response.ok) {\n\t\t\t\t\tgetLogger().warn(`Failed to fetch additional file from URL: ${file.filePath}`);\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\t// One step, no intermediate Blob allocation (issue 111).\n\t\t\t\tconst arrayBuffer = await response.arrayBuffer();\n\t\t\t\t// Same zip-slip defense as decodeResponseFiles — the name lands in the archive.\n\t\t\t\tconst safeName = sanitizeArchivePath(file.fileName);\n\t\t\t\tif (safeName === '') {\n\t\t\t\t\tgetLogger().warn(`Skipping fetched file with unusable name: ${file.fileName}`);\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tconst subFolder = file.subFolder ? sanitizeArchivePath(file.subFolder) : '';\n\t\t\t\treturn {\n\t\t\t\t\tfileName: safeName,\n\t\t\t\t\tcontent: new Uint8Array(arrayBuffer),\n\t\t\t\t\tpath: subFolder !== '' ? `${subFolder}/${safeName}` : safeName\n\t\t\t\t} as ProcessedFile;\n\t\t\t} catch (error) {\n\t\t\t\tgetLogger().error(`Error fetching additional file from URL: ${file.filePath}`, error);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t})\n\t);\n\n\treturn fetched.filter((f): f is ProcessedFile => f !== null);\n};\n\n/**\n * Compose the decoded response files with any fetched external files.\n *\n * Archive paths are de-duplicated here — on the path both public entry points\n * share — so `extractFilesFromComputeResponse` consumers keying by `path` never\n * lose files silently, matching the zip path's rename behavior (issue 111).\n *\n * @param dataItems - `FileData` items from the compute response.\n * @param additionalFiles - Optional external file references to fetch and include.\n * @returns A Promise resolving to the combined `ProcessedFile` list.\n */\nconst processFiles = async (\n\tdataItems: FileData[],\n\tadditionalFiles: FileBaseInfo[] | FileBaseInfo | null\n): Promise<ProcessedFile[]> => {\n\tconst processedFiles = decodeResponseFiles(dataItems);\n\n\tif (additionalFiles) {\n\t\tconst filesArray = Array.isArray(additionalFiles) ? additionalFiles : [additionalFiles];\n\t\tprocessedFiles.push(...(await fetchRemoteFiles(filesArray)));\n\t}\n\n\tconst taken = new Set<string>();\n\treturn processedFiles.map((file) => {\n\t\tconst path = uniqueArchivePath(file.path, taken);\n\t\ttaken.add(path);\n\t\tif (path === file.path) return file;\n\t\tgetLogger().warn(`Duplicate archive path \"${file.path}\" — storing as \"${path}\".`);\n\t\treturn { ...file, path, fileName: path.slice(path.lastIndexOf('/') + 1) };\n\t});\n};\n\n/** Creates a ZIP archive from processed files and triggers a browser download. */\nasync function createAndDownloadZip(files: ProcessedFile[], zipName: string): Promise<void> {\n\tconst { zip, strToU8 } = await import('fflate');\n\n\t// Convert files to fflate format. Zip entries are keyed by path, so two\n\t// files with the same path would silently overwrite each other — rename\n\t// collisions (\"model.txt\" → \"model-2.txt\") instead of losing data.\n\t// (processFiles already de-duplicates; this is a cheap second line of\n\t// defense in case callers construct ProcessedFiles themselves.)\n\tconst zipData: Record<string, Uint8Array> = {};\n\tconst taken = new Set<string>();\n\tfiles.forEach((file) => {\n\t\tconst path = uniqueArchivePath(file.path, taken);\n\t\ttaken.add(path);\n\t\tif (path !== file.path) {\n\t\t\tgetLogger().warn(`Duplicate archive path \"${file.path}\" — storing as \"${path}\".`);\n\t\t}\n\t\tzipData[path] = typeof file.content === 'string' ? strToU8(file.content) : file.content;\n\t});\n\n\t// Async `zip` deflates on a worker thread instead of blocking the main thread\n\t// like `zipSync` — keeps the UI responsive for large geometry exports.\n\tconst zipped = await new Promise<Uint8Array>((resolve, reject) => {\n\t\tzip(zipData, { level: 6 }, (err, data) => (err ? reject(err) : resolve(data)));\n\t});\n\n\tconst blob = new Blob([zipped as BlobPart], { type: 'application/zip' });\n\tsaveFile(blob, `${zipName}.zip`);\n}\n\n/**\n * First archive path not already taken in `taken`, disambiguating with a\n * numeric suffix before the extension: `dir/model.txt` → `dir/model-2.txt`.\n */\nfunction uniqueArchivePath(path: string, taken: ReadonlySet<string>): string {\n\tif (!taken.has(path)) return path;\n\tconst slash = path.lastIndexOf('/');\n\tconst dot = path.lastIndexOf('.');\n\tconst stemEnd = dot > slash ? dot : path.length;\n\tconst stem = path.slice(0, stemEnd);\n\tconst ext = path.slice(stemEnd);\n\tfor (let i = 2; ; i++) {\n\t\tconst candidate = `${stem}-${i}${ext}`;\n\t\tif (!taken.has(candidate)) return candidate;\n\t}\n}\n\n/** Saves a Blob object as a file in the user's browser. */\nfunction saveFile(blob: Blob, filename: string) {\n\tif (typeof document === 'undefined') {\n\t\tthrow new RhinoComputeError(\n\t\t\t'saveFile requires a browser environment with DOM API access.',\n\t\t\tErrorCodes.BROWSER_ONLY,\n\t\t\t{\n\t\t\t\tcontext: { function: 'saveFile', requiredAPI: 'document' }\n\t\t\t}\n\t\t);\n\t}\n\n\tconst url = URL.createObjectURL(blob);\n\tconst a = document.createElement('a');\n\ta.href = url;\n\ta.download = filename;\n\t// Firefox requires the anchor to be in the DOM for the click to download.\n\tdocument.body.appendChild(a);\n\ta.click();\n\ta.remove();\n\t// Revoking synchronously can abort the download in some browsers — the\n\t// browser only pins the blob once the download has actually started.\n\tsetTimeout(() => URL.revokeObjectURL(url), 10_000);\n}\n"],"mappings":"mOAAO,IAAMA,EAAa,CACzB,cAAe,gBACf,WAAY,aACZ,iBAAkB,mBAClB,kBAAmB,oBACnB,cAAe,gBACf,WAAY,aAEZ,UAAW,YAEX,WAAY,aAOZ,iBAAkB,mBAClB,cAAe,gBACf,cAAe,gBACf,cAAe,gBACf,eAAgB,iBAChB,aAAc,eACd,kBAAmB,oBACnB,eAAgB,iBAEhB,kBAAmB,oBAEnB,WAAY,aAEZ,QAAS,UAOT,WAAY,aAMZ,cAAe,gBAQf,sBAAuB,uBACxB,EASaC,EAAN,MAAMC,UAA0B,KAAM,CAM5C,YACCC,EACAC,EAAkBJ,EAAW,cAC7BK,EACC,CACD,MAAMF,CAAO,EAVdG,EAAA,KAAgB,QAChBA,EAAA,KAAgB,cAChBA,EAAA,KAAgB,WAChBA,EAAA,KAAgB,iBAQf,KAAK,KAAO,oBACZ,KAAK,KAAOF,EACZ,KAAK,WAAaC,GAAS,WAC3B,KAAK,QAAUA,GAAS,QACxB,KAAK,cAAgBA,GAAS,cAC1BA,GAAS,gBACX,KAA6B,MAAQA,EAAQ,cAEhD,CAKA,OAAO,cACNE,EACAC,EACAC,EACC,CACD,OAAO,IAAIP,EACV,UAAUK,CAAS,0BAA0BC,EAAe,cAAcA,CAAY,IAAM,EAAE,GAC9FR,EAAW,cACX,CAAE,QAAS,CAAE,UAAAO,EAAW,aAAAC,EAAc,GAAGC,CA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EAAMb,EAAK,OACnCe,EAAOf,EAAK,MAAM,EAAGc,CAAO,EAC5BE,EAAMhB,EAAK,MAAMc,CAAO,EAC9B,QAAS,EAAI,GAAK,IAAK,CACtB,IAAMG,EAAY,GAAGF,CAAI,IAAI,CAAC,GAAGC,CAAG,GACpC,GAAI,CAACjB,EAAM,IAAIkB,CAAS,EAAG,OAAOA,CACnC,CACD,CAGA,SAASN,GAASD,EAAYQ,EAAkB,CAC/C,GAAI,OAAO,SAAa,IACvB,MAAM,IAAItD,EACT,+DACAC,EAAW,aACX,CACC,QAAS,CAAE,SAAU,WAAY,YAAa,UAAW,CAC1D,CACD,EAGD,IAAMsD,EAAM,IAAI,gBAAgBT,CAAI,EAC9BU,EAAI,SAAS,cAAc,GAAG,EACpCA,EAAE,KAAOD,EACTC,EAAE,SAAWF,EAEb,SAAS,KAAK,YAAYE,CAAC,EAC3BA,EAAE,MAAM,EACRA,EAAE,OAAO,EAGT,WAAW,IAAM,IAAI,gBAAgBD,CAAG,EAAG,GAAM,CAClD","names":["ErrorCodes","RhinoComputeError","_RhinoComputeError","message","code","options","__publicField","inputName","expectedType","context","paramType","paramName","NoOpLogger","ConsoleLogger","message","args","internalLogger","getLogger","setLogger","logger","missing","method","RhinoComputeError","ErrorCodes","enableDebugLogging","getNodeBuffer","buf","encodeStringToBase64","str","Buffer","base64ByteArray","BASE64_DETECT_MIN_LENGTH","B64_ALPHABET","detectBase64Payload","str","data","rem","lastValue","decodeBase64ToBinary","base64File","RhinoComputeError","ErrorCodes","Buffer","getNodeBuffer","binary","bytes","i","utf8ByteLength","code","base64ByteArray","parts","wireSizes","setResponseWireSize","response","size","getResponseWireSize","parseServerTiming","headerValue","timing","sawMetric","part","name","params","durParam","p","dur","key","DEFAULT_RETRY","RETRYABLE_STATUS","RETRY_AFTER_CAP_MS","MAX_CONTEXT_BODY_CHARS","resolveRetryPolicy","policy","parseRetryAfter","seconds","dateMs","delta","backoffDelay","attempt","exponential","jitter","sleep","ms","signal","resolve","reject","id","onAbort","truncateBody","body","throwHttpError","response","fullUrl","requestId","requestSize","serverUrl","errorBody","serverCode","rawBody","status","statusText","responseHeaders","value","trimmed","bodyHint","storedBody","context","error","ErrorCodes","code","mapServerErrorCode","RhinoComputeError","buildUrl","endpoint","base","path","isLocalhost","hostname","warnedNoAuth","buildHeaders","config","headers","getLogger","generateRequestId","log","message","debug","composeSignal","callerSignal","timeoutMs","noCleanup","wantsTimeout","supportsTimeout","ctrl","timeoutSignal","timerId","timeoutCtrl","sources","s","fireServerTiming","onServerTiming","err","handleResponse","startTime","responseTime","parsedForCode","parsed","setResponseWireSize","serverMessage","exceptionType","stack","stackStr","e","contentType","attemptFetch","ctx","retryPolicy","totalAttempts","cleanup","retryAfterMs","delayMs","fatal","inBrowser","errorContext","fetchRhinoCompute","args","utf8ByteLength","sizeKb","emoji","result","DEFAULT_PUBLIC_HOST","validateServerUrl","raw","trimmed","RhinoComputeError","ErrorCodes","parsed","err","_ComputeServerStats","serverUrl","apiKey","__publicField","validateServerUrl","headers","url","init","timeoutMs","merged","value","key","requestInit","err","getLogger","options","initialize","response","text","json","kind","version","activeChildren","children","calls","totalPurged","i","purged","date","seconds","port","path","callback","intervalMs","active","currentTimeoutId","check","_stats","stopMonitoring","stopMonitor","timeoutId","RhinoComputeError","ErrorCodes","ComputeServerStats","toCamelCase","str","options","preserveSpaces","sep","out","_","m","isPlainObject","value","proto","camelcaseKeys","obj","item","result","key","camelKey","getLogger","readField","obj","name","record","hasOwn","key","lowerKeyMap","hasField","lowerKeyCache","keys","cached","map","lower","extractFilesFromComputeResponse","downloadableFiles","additionalFiles","processFiles","err","RhinoComputeError","ErrorCodes","downloadFileData","fileFoldername","processedFiles","createAndDownloadZip","sanitizeArchivePath","raw","segment","isBase64Flag","flag","decodeResponseFiles","dataItems","item","rawName","readField","rawType","fileName","getLogger","rawSubFolder","subFolder","filePath","data","decodeBase64ToBinary","REMOTE_FILE_TIMEOUT_MS","fetchRemoteFiles","refs","file","signal","response","arrayBuffer","safeName","error","f","filesArray","taken","path","uniqueArchivePath","files","zipName","zip","strToU8","zipData","zipped","resolve","reject","blob","saveFile","slash","dot","stemEnd","stem","ext","candidate","filename","url","a"]}
package/dist/core.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkCUQQ3ZBVcjs = require('./chunk-CUQQ3ZBV.cjs');exports.ComputeServerStats = _chunkCUQQ3ZBVcjs.n; exports.ErrorCodes = _chunkCUQQ3ZBVcjs.c; exports.RhinoComputeError = _chunkCUQQ3ZBVcjs.d; exports.camelcaseKeys = _chunkCUQQ3ZBVcjs.p; exports.downloadFileData = _chunkCUQQ3ZBVcjs.t; exports.enableDebugLogging = _chunkCUQQ3ZBVcjs.g; exports.extractFilesFromComputeResponse = _chunkCUQQ3ZBVcjs.s; exports.fetchRhinoCompute = _chunkCUQQ3ZBVcjs.l; exports.getLogger = _chunkCUQQ3ZBVcjs.e; exports.setLogger = _chunkCUQQ3ZBVcjs.f; exports.toCamelCase = _chunkCUQQ3ZBVcjs.o;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkH3FZW6OXcjs = require('./chunk-H3FZW6OX.cjs');exports.ComputeServerStats = _chunkH3FZW6OXcjs.p; exports.ErrorCodes = _chunkH3FZW6OXcjs.c; exports.RhinoComputeError = _chunkH3FZW6OXcjs.d; exports.camelcaseKeys = _chunkH3FZW6OXcjs.r; exports.downloadFileData = _chunkH3FZW6OXcjs.v; exports.enableDebugLogging = _chunkH3FZW6OXcjs.g; exports.extractFilesFromComputeResponse = _chunkH3FZW6OXcjs.u; exports.fetchRhinoCompute = _chunkH3FZW6OXcjs.n; exports.getLogger = _chunkH3FZW6OXcjs.e; exports.getResponseWireSize = _chunkH3FZW6OXcjs.m; exports.setLogger = _chunkH3FZW6OXcjs.f; exports.setResponseWireSize = _chunkH3FZW6OXcjs.l; exports.toCamelCase = _chunkH3FZW6OXcjs.q;
2
2
  //# sourceMappingURL=core.cjs.map
package/dist/core.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/selva/selva/packages/compute/dist/core.cjs"],"names":[],"mappings":"AAAA,iIAA8G,wgBAAmP","file":"/home/runner/work/selva/selva/packages/compute/dist/core.cjs"}
1
+ {"version":3,"sources":["/home/runner/work/selva/selva/packages/compute/dist/core.cjs"],"names":[],"mappings":"AAAA,iIAA4H,8mBAAqS","file":"/home/runner/work/selva/selva/packages/compute/dist/core.cjs"}
package/dist/core.d.cts CHANGED
@@ -48,6 +48,27 @@ export { C as ComputeServerStats, E as ErrorCode, a as ErrorCodes, F as FileBase
48
48
  */
49
49
  declare function fetchRhinoCompute<R = unknown>(endpoint: string, args: Record<string, any>, config: ComputeConfig): Promise<R>;
50
50
 
51
+ /**
52
+ * Side-channel carrying a response's wire size (its JSON text length) alongside
53
+ * the parsed object, so downstream caches can budget by bytes without
54
+ * re-serializing (audit C2/C3 — the response tree can be hundreds of MB, and
55
+ * every extra `JSON.stringify` pass over it is a real cost).
56
+ *
57
+ * A `WeakMap` rather than a property on the response: the response type is the
58
+ * server's schema, and an extra enumerable field would leak into every
59
+ * `JSON.stringify(response)` on the way back out to clients. Derived copies
60
+ * (e.g. the `algo`-stripped shallow copy in `runSolve`) must re-register — the
61
+ * hint follows object identity, not content.
62
+ *
63
+ * The size is `text.length` (UTF-16 code units), not strict UTF-8 bytes —
64
+ * compute responses are ASCII-dominated JSON (base64 + numerals), so the two
65
+ * are interchangeable for budgeting purposes and `.length` is free.
66
+ */
67
+ /** Record `response`'s wire size. No-op for non-object/null values. */
68
+ declare function setResponseWireSize(response: unknown, size: number): void;
69
+ /** The wire size recorded for `response`, or undefined when never registered. */
70
+ declare function getResponseWireSize(response: unknown): number | undefined;
71
+
51
72
  /**
52
73
  * Logger interface for structured logging
53
74
  *
@@ -161,4 +182,4 @@ declare function camelcaseKeys(obj: unknown, options?: {
161
182
  preserveSpaces?: boolean;
162
183
  }): unknown;
163
184
 
164
- export { ComputeConfig, type Logger, camelcaseKeys, enableDebugLogging, fetchRhinoCompute, getLogger, setLogger, toCamelCase };
185
+ export { ComputeConfig, type Logger, camelcaseKeys, enableDebugLogging, fetchRhinoCompute, getLogger, getResponseWireSize, setLogger, setResponseWireSize, toCamelCase };
package/dist/core.d.ts CHANGED
@@ -48,6 +48,27 @@ export { C as ComputeServerStats, E as ErrorCode, a as ErrorCodes, F as FileBase
48
48
  */
49
49
  declare function fetchRhinoCompute<R = unknown>(endpoint: string, args: Record<string, any>, config: ComputeConfig): Promise<R>;
50
50
 
51
+ /**
52
+ * Side-channel carrying a response's wire size (its JSON text length) alongside
53
+ * the parsed object, so downstream caches can budget by bytes without
54
+ * re-serializing (audit C2/C3 — the response tree can be hundreds of MB, and
55
+ * every extra `JSON.stringify` pass over it is a real cost).
56
+ *
57
+ * A `WeakMap` rather than a property on the response: the response type is the
58
+ * server's schema, and an extra enumerable field would leak into every
59
+ * `JSON.stringify(response)` on the way back out to clients. Derived copies
60
+ * (e.g. the `algo`-stripped shallow copy in `runSolve`) must re-register — the
61
+ * hint follows object identity, not content.
62
+ *
63
+ * The size is `text.length` (UTF-16 code units), not strict UTF-8 bytes —
64
+ * compute responses are ASCII-dominated JSON (base64 + numerals), so the two
65
+ * are interchangeable for budgeting purposes and `.length` is free.
66
+ */
67
+ /** Record `response`'s wire size. No-op for non-object/null values. */
68
+ declare function setResponseWireSize(response: unknown, size: number): void;
69
+ /** The wire size recorded for `response`, or undefined when never registered. */
70
+ declare function getResponseWireSize(response: unknown): number | undefined;
71
+
51
72
  /**
52
73
  * Logger interface for structured logging
53
74
  *
@@ -161,4 +182,4 @@ declare function camelcaseKeys(obj: unknown, options?: {
161
182
  preserveSpaces?: boolean;
162
183
  }): unknown;
163
184
 
164
- export { ComputeConfig, type Logger, camelcaseKeys, enableDebugLogging, fetchRhinoCompute, getLogger, setLogger, toCamelCase };
185
+ export { ComputeConfig, type Logger, camelcaseKeys, enableDebugLogging, fetchRhinoCompute, getLogger, getResponseWireSize, setLogger, setResponseWireSize, toCamelCase };
package/dist/core.js CHANGED
@@ -1,2 +1,2 @@
1
- import{c as a,d as b,e as c,f as d,g as e,l as f,n as g,o as h,p as i,s as j,t as k}from"./chunk-WPB2LKCD.js";export{g as ComputeServerStats,a as ErrorCodes,b as RhinoComputeError,i as camelcaseKeys,k as downloadFileData,e as enableDebugLogging,j as extractFilesFromComputeResponse,f as fetchRhinoCompute,c as getLogger,d as setLogger,h as toCamelCase};
1
+ import{c as a,d as b,e as c,f as d,g as e,l as f,m as g,n as h,p as i,q as j,r as k,u as l,v as m}from"./chunk-Y3M7P3BW.js";export{i as ComputeServerStats,a as ErrorCodes,b as RhinoComputeError,k as camelcaseKeys,m as downloadFileData,e as enableDebugLogging,l as extractFilesFromComputeResponse,h as fetchRhinoCompute,c as getLogger,g as getResponseWireSize,d as setLogger,f as setResponseWireSize,j as toCamelCase};
2
2
  //# sourceMappingURL=core.js.map
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkQZECCPT3cjs = require('./chunk-QZECCPT3.cjs');var _chunkCUQQ3ZBVcjs = require('./chunk-CUQQ3ZBV.cjs');exports.GrasshopperClient = _chunkQZECCPT3cjs.g; exports.GrasshopperResponseProcessor = _chunkQZECCPT3cjs.h; exports.RhinoComputeError = _chunkCUQQ3ZBVcjs.d; exports.SolveScheduler = _chunkQZECCPT3cjs.f; exports.TreeBuilder = _chunkQZECCPT3cjs.m; exports.downloadFileData = _chunkCUQQ3ZBVcjs.t; exports.extractFilesFromComputeResponse = _chunkCUQQ3ZBVcjs.s; exports.fetchDefinitionIO = _chunkQZECCPT3cjs.k; exports.fetchParsedDefinitionIO = _chunkQZECCPT3cjs.l; exports.hashDefinition = _chunkQZECCPT3cjs.e; exports.hashSolveInput = _chunkQZECCPT3cjs.d; exports.isDefinitionRef = _chunkQZECCPT3cjs.a; exports.processInput = _chunkQZECCPT3cjs.i; exports.processInputs = _chunkQZECCPT3cjs.j; exports.solveGrasshopperDefinition = _chunkQZECCPT3cjs.b; exports.stableStringify = _chunkQZECCPT3cjs.c;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunk44HGB4C4cjs = require('./chunk-44HGB4C4.cjs');var _chunkH3FZW6OXcjs = require('./chunk-H3FZW6OX.cjs');exports.GrasshopperClient = _chunk44HGB4C4cjs.g; exports.GrasshopperResponseProcessor = _chunk44HGB4C4cjs.h; exports.RhinoComputeError = _chunkH3FZW6OXcjs.d; exports.SolveScheduler = _chunk44HGB4C4cjs.f; exports.TreeBuilder = _chunk44HGB4C4cjs.m; exports.downloadFileData = _chunkH3FZW6OXcjs.v; exports.extractFilesFromComputeResponse = _chunkH3FZW6OXcjs.u; exports.fetchDefinitionIO = _chunk44HGB4C4cjs.k; exports.fetchParsedDefinitionIO = _chunk44HGB4C4cjs.l; exports.hashDefinition = _chunk44HGB4C4cjs.e; exports.hashSolveInput = _chunk44HGB4C4cjs.d; exports.isDefinitionRef = _chunk44HGB4C4cjs.a; exports.processInput = _chunk44HGB4C4cjs.i; exports.processInputs = _chunk44HGB4C4cjs.j; exports.solveGrasshopperDefinition = _chunk44HGB4C4cjs.b; exports.stableStringify = _chunk44HGB4C4cjs.c;
2
2
  //# sourceMappingURL=grasshopper.cjs.map
@@ -65,6 +65,16 @@ type SchedulerMode = 'latest-wins' | 'queue' | 'parallel';
65
65
  interface CacheOptions {
66
66
  /** Maximum entries kept in the LRU. Default: 50. */
67
67
  maxEntries?: number;
68
+ /**
69
+ * Total byte budget for retained responses, evicted LRU alongside
70
+ * `maxEntries` (both bounds apply). Responses range KB→100s of MB, so an
71
+ * entry count alone can't bound heap. Sizing uses the response's wire size
72
+ * (JSON text length, recorded at the fetch boundary — no re-serialization);
73
+ * a response without that hint (custom executor) is sized by a one-off
74
+ * `JSON.stringify`. A single response larger than the whole budget is
75
+ * served but never retained. `0` = no byte bound (count-only, default).
76
+ */
77
+ maxBytes?: number;
68
78
  /** Time-to-live in ms. Set to `0` for no expiry (default). */
69
79
  ttlMs?: number;
70
80
  /**
@@ -211,9 +221,12 @@ declare class SolveScheduler {
211
221
  private readonly retry;
212
222
  private readonly cacheEnabled;
213
223
  private readonly cacheMax;
224
+ private readonly cacheMaxBytes;
214
225
  private readonly cacheTtl;
215
226
  private readonly cacheErroredSolves;
216
227
  private readonly cache;
228
+ /** Sum of `sizeBytes` across retained cache entries. */
229
+ private cacheBytes;
217
230
  /** Optional cache-key-aware executor and whether server-def-cache reuse is on. */
218
231
  private readonly cacheKeyExecutor?;
219
232
  private readonly reuseServerDefinitionCache;
@@ -341,7 +354,14 @@ declare class SolveScheduler {
341
354
  private rejectAsAborted;
342
355
  private readCache;
343
356
  private writeCache;
357
+ /** Remove one cache entry and release its bytes from the running total. */
358
+ private dropCacheEntry;
344
359
  clearCache(): void;
360
+ /** Observability snapshot of the response cache (entries + retained bytes). */
361
+ cacheStats(): {
362
+ entries: number;
363
+ bytes: number;
364
+ };
345
365
  dispose(): void;
346
366
  private runHook;
347
367
  }
@@ -65,6 +65,16 @@ type SchedulerMode = 'latest-wins' | 'queue' | 'parallel';
65
65
  interface CacheOptions {
66
66
  /** Maximum entries kept in the LRU. Default: 50. */
67
67
  maxEntries?: number;
68
+ /**
69
+ * Total byte budget for retained responses, evicted LRU alongside
70
+ * `maxEntries` (both bounds apply). Responses range KB→100s of MB, so an
71
+ * entry count alone can't bound heap. Sizing uses the response's wire size
72
+ * (JSON text length, recorded at the fetch boundary — no re-serialization);
73
+ * a response without that hint (custom executor) is sized by a one-off
74
+ * `JSON.stringify`. A single response larger than the whole budget is
75
+ * served but never retained. `0` = no byte bound (count-only, default).
76
+ */
77
+ maxBytes?: number;
68
78
  /** Time-to-live in ms. Set to `0` for no expiry (default). */
69
79
  ttlMs?: number;
70
80
  /**
@@ -211,9 +221,12 @@ declare class SolveScheduler {
211
221
  private readonly retry;
212
222
  private readonly cacheEnabled;
213
223
  private readonly cacheMax;
224
+ private readonly cacheMaxBytes;
214
225
  private readonly cacheTtl;
215
226
  private readonly cacheErroredSolves;
216
227
  private readonly cache;
228
+ /** Sum of `sizeBytes` across retained cache entries. */
229
+ private cacheBytes;
217
230
  /** Optional cache-key-aware executor and whether server-def-cache reuse is on. */
218
231
  private readonly cacheKeyExecutor?;
219
232
  private readonly reuseServerDefinitionCache;
@@ -341,7 +354,14 @@ declare class SolveScheduler {
341
354
  private rejectAsAborted;
342
355
  private readCache;
343
356
  private writeCache;
357
+ /** Remove one cache entry and release its bytes from the running total. */
358
+ private dropCacheEntry;
344
359
  clearCache(): void;
360
+ /** Observability snapshot of the response cache (entries + retained bytes). */
361
+ cacheStats(): {
362
+ entries: number;
363
+ bytes: number;
364
+ };
345
365
  dispose(): void;
346
366
  private runHook;
347
367
  }
@@ -1,2 +1,2 @@
1
- import{a as d,b as e,c as f,d as g,e as h,f as i,g as j,h as k,i as l,j as m,k as n,l as o,m as p}from"./chunk-C7P43VZF.js";import{d as a,s as b,t as c}from"./chunk-WPB2LKCD.js";export{j as GrasshopperClient,k as GrasshopperResponseProcessor,a as RhinoComputeError,i as SolveScheduler,p as TreeBuilder,c as downloadFileData,b as extractFilesFromComputeResponse,n as fetchDefinitionIO,o as fetchParsedDefinitionIO,h as hashDefinition,g as hashSolveInput,d as isDefinitionRef,l as processInput,m as processInputs,e as solveGrasshopperDefinition,f as stableStringify};
1
+ import{a as d,b as e,c as f,d as g,e as h,f as i,g as j,h as k,i as l,j as m,k as n,l as o,m as p}from"./chunk-3SEQKFGD.js";import{d as a,u as b,v as c}from"./chunk-Y3M7P3BW.js";export{j as GrasshopperClient,k as GrasshopperResponseProcessor,a as RhinoComputeError,i as SolveScheduler,p as TreeBuilder,c as downloadFileData,b as extractFilesFromComputeResponse,n as fetchDefinitionIO,o as fetchParsedDefinitionIO,h as hashDefinition,g as hashSolveInput,d as isDefinitionRef,l as processInput,m as processInputs,e as solveGrasshopperDefinition,f as stableStringify};
2
2
  //# sourceMappingURL=grasshopper.js.map
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkQZECCPT3cjs = require('./chunk-QZECCPT3.cjs');var _chunkCUQQ3ZBVcjs = require('./chunk-CUQQ3ZBV.cjs');exports.ComputeServerStats = _chunkCUQQ3ZBVcjs.n; exports.ErrorCodes = _chunkCUQQ3ZBVcjs.c; exports.GrasshopperClient = _chunkQZECCPT3cjs.g; exports.GrasshopperResponseProcessor = _chunkQZECCPT3cjs.h; exports.RhinoComputeError = _chunkCUQQ3ZBVcjs.d; exports.SolveScheduler = _chunkQZECCPT3cjs.f; exports.TreeBuilder = _chunkQZECCPT3cjs.m; exports.camelcaseKeys = _chunkCUQQ3ZBVcjs.p; exports.downloadFileData = _chunkCUQQ3ZBVcjs.t; exports.enableDebugLogging = _chunkCUQQ3ZBVcjs.g; exports.extractFilesFromComputeResponse = _chunkCUQQ3ZBVcjs.s; exports.fetchDefinitionIO = _chunkQZECCPT3cjs.k; exports.fetchParsedDefinitionIO = _chunkQZECCPT3cjs.l; exports.fetchRhinoCompute = _chunkCUQQ3ZBVcjs.l; exports.getLogger = _chunkCUQQ3ZBVcjs.e; exports.hashDefinition = _chunkQZECCPT3cjs.e; exports.hashSolveInput = _chunkQZECCPT3cjs.d; exports.isDefinitionRef = _chunkQZECCPT3cjs.a; exports.processInput = _chunkQZECCPT3cjs.i; exports.processInputs = _chunkQZECCPT3cjs.j; exports.setLogger = _chunkCUQQ3ZBVcjs.f; exports.solveGrasshopperDefinition = _chunkQZECCPT3cjs.b; exports.stableStringify = _chunkQZECCPT3cjs.c; exports.toCamelCase = _chunkCUQQ3ZBVcjs.o;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunk44HGB4C4cjs = require('./chunk-44HGB4C4.cjs');var _chunkH3FZW6OXcjs = require('./chunk-H3FZW6OX.cjs');exports.ComputeServerStats = _chunkH3FZW6OXcjs.p; exports.ErrorCodes = _chunkH3FZW6OXcjs.c; exports.GrasshopperClient = _chunk44HGB4C4cjs.g; exports.GrasshopperResponseProcessor = _chunk44HGB4C4cjs.h; exports.RhinoComputeError = _chunkH3FZW6OXcjs.d; exports.SolveScheduler = _chunk44HGB4C4cjs.f; exports.TreeBuilder = _chunk44HGB4C4cjs.m; exports.camelcaseKeys = _chunkH3FZW6OXcjs.r; exports.downloadFileData = _chunkH3FZW6OXcjs.v; exports.enableDebugLogging = _chunkH3FZW6OXcjs.g; exports.extractFilesFromComputeResponse = _chunkH3FZW6OXcjs.u; exports.fetchDefinitionIO = _chunk44HGB4C4cjs.k; exports.fetchParsedDefinitionIO = _chunk44HGB4C4cjs.l; exports.fetchRhinoCompute = _chunkH3FZW6OXcjs.n; exports.getLogger = _chunkH3FZW6OXcjs.e; exports.getResponseWireSize = _chunkH3FZW6OXcjs.m; exports.hashDefinition = _chunk44HGB4C4cjs.e; exports.hashSolveInput = _chunk44HGB4C4cjs.d; exports.isDefinitionRef = _chunk44HGB4C4cjs.a; exports.processInput = _chunk44HGB4C4cjs.i; exports.processInputs = _chunk44HGB4C4cjs.j; exports.setLogger = _chunkH3FZW6OXcjs.f; exports.setResponseWireSize = _chunkH3FZW6OXcjs.l; exports.solveGrasshopperDefinition = _chunk44HGB4C4cjs.b; exports.stableStringify = _chunk44HGB4C4cjs.c; exports.toCamelCase = _chunkH3FZW6OXcjs.q;
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/selva/selva/packages/compute/dist/index.cjs"],"names":[],"mappings":"AAAA,iIAA4H,wDAAqG,moCAA4hB","file":"/home/runner/work/selva/selva/packages/compute/dist/index.cjs"}
1
+ {"version":3,"sources":["/home/runner/work/selva/selva/packages/compute/dist/index.cjs"],"names":[],"mappings":"AAAA,iIAA4H,wDAAmH,yuCAA8kB","file":"/home/runner/work/selva/selva/packages/compute/dist/index.cjs"}
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- export { Logger, camelcaseKeys, enableDebugLogging, fetchRhinoCompute, getLogger, setLogger, toCamelCase } from './core.cjs';
1
+ export { Logger, camelcaseKeys, enableDebugLogging, fetchRhinoCompute, getLogger, getResponseWireSize, setLogger, setResponseWireSize, toCamelCase } from './core.cjs';
2
2
  export { C as ComputeServerStats, E as ErrorCode, a as ErrorCodes, F as FileBaseInfo, b as FileData, P as ProcessedFile, R as RhinoComputeError, d as downloadFileData, e as extractFilesFromComputeResponse } from './handle-files-BISo_wob.cjs';
3
3
  export { C as ComputeConfig, R as RetryPolicy, a as RhinoModelUnit, S as ServerTiming } from './types-BGhtYxZ-.cjs';
4
4
  export { CacheOptions, DataTreeValue, DefinitionRef, GetValuesOptions, GetValuesResult, GrasshopperClient, GrasshopperResponseProcessor, ParsedContext, SchedulerMode, SolveContext, SolveDefinition, SolveOptions, SolveResult, SolveScheduler, SolveSchedulerOptions, TreeBuilder, fetchDefinitionIO, fetchParsedDefinitionIO, hashDefinition, hashSolveInput, isDefinitionRef, processInput, processInputs, solveGrasshopperDefinition, stableStringify } from './grasshopper.cjs';
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { Logger, camelcaseKeys, enableDebugLogging, fetchRhinoCompute, getLogger, setLogger, toCamelCase } from './core.js';
1
+ export { Logger, camelcaseKeys, enableDebugLogging, fetchRhinoCompute, getLogger, getResponseWireSize, setLogger, setResponseWireSize, toCamelCase } from './core.js';
2
2
  export { C as ComputeServerStats, E as ErrorCode, a as ErrorCodes, F as FileBaseInfo, b as FileData, P as ProcessedFile, R as RhinoComputeError, d as downloadFileData, e as extractFilesFromComputeResponse } from './handle-files-BISo_wob.js';
3
3
  export { C as ComputeConfig, R as RetryPolicy, a as RhinoModelUnit, S as ServerTiming } from './types-BGhtYxZ-.js';
4
4
  export { CacheOptions, DataTreeValue, DefinitionRef, GetValuesOptions, GetValuesResult, GrasshopperClient, GrasshopperResponseProcessor, ParsedContext, SchedulerMode, SolveContext, SolveDefinition, SolveOptions, SolveResult, SolveScheduler, SolveSchedulerOptions, TreeBuilder, fetchDefinitionIO, fetchParsedDefinitionIO, hashDefinition, hashSolveInput, isDefinitionRef, processInput, processInputs, solveGrasshopperDefinition, stableStringify } from './grasshopper.js';
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import{a as d,b as g,c as h,d as i,e as j,f as k,g as l,h as n,i as q,j as s,k as u,l as v,m as w}from"./chunk-C7P43VZF.js";import{c as o,d as r,e,f,g as m,l as p,n as t,o as x,p as a,s as b,t as c}from"./chunk-WPB2LKCD.js";export{t as ComputeServerStats,o as ErrorCodes,l as GrasshopperClient,n as GrasshopperResponseProcessor,r as RhinoComputeError,k as SolveScheduler,w as TreeBuilder,a as camelcaseKeys,c as downloadFileData,m as enableDebugLogging,b as extractFilesFromComputeResponse,u as fetchDefinitionIO,v as fetchParsedDefinitionIO,p as fetchRhinoCompute,e as getLogger,j as hashDefinition,i as hashSolveInput,d as isDefinitionRef,q as processInput,s as processInputs,f as setLogger,g as solveGrasshopperDefinition,h as stableStringify,x as toCamelCase};
1
+ import{a as h,b as i,c as j,d as k,e as l,f as n,g as q,h as s,i as u,j as v,k as w,l as y,m as z}from"./chunk-3SEQKFGD.js";import{c as o,d as r,e,f,g as m,l as p,m as t,n as x,p as a,q as b,r as c,u as d,v as g}from"./chunk-Y3M7P3BW.js";export{a as ComputeServerStats,o as ErrorCodes,q as GrasshopperClient,s as GrasshopperResponseProcessor,r as RhinoComputeError,n as SolveScheduler,z as TreeBuilder,c as camelcaseKeys,g as downloadFileData,m as enableDebugLogging,d as extractFilesFromComputeResponse,w as fetchDefinitionIO,y as fetchParsedDefinitionIO,x as fetchRhinoCompute,e as getLogger,t as getResponseWireSize,l as hashDefinition,k as hashSolveInput,h as isDefinitionRef,u as processInput,v as processInputs,f as setLogger,p as setResponseWireSize,i as solveGrasshopperDefinition,j as stableStringify,b as toCamelCase};
2
2
  //# sourceMappingURL=index.js.map
@@ -1,2 +1,2 @@
1
- import{A as L,B as S,C as I,D as R,E as D,F as B,G,H as P,I as u,J as F,K as b,L as N,M as V,N as U,a as e,b as r,c as o,d as t,e as a,f as s,g as p,h as i,i as n,j as m,k as l,l as f,m as y,n as x,o as C,p as d,q as h,r as E,s as M,t as _,u as O,v as c,w as A,x as g,y as T,z as j}from"./chunk-PX2YTSHJ.js";import"./chunk-WPB2LKCD.js";export{g as BINARY_MESH_MAGIC,j as BINARY_MESH_VERSION,T as COMPRESSED_MESH_MAGIC,n as EDGE_USERDATA_KIND,R as FLAG_DELTA_ENCODED,S as FLAG_FLOAT32,D as FLAG_HAS_UVS,B as FLAG_HAS_VERTEX_COLORS,I as FLAG_UINT16_INDICES,c as LOOKS,L as MIN_SUPPORTED_VERSION,e as Materials,V as SCALE_FACTORS,h as TEXTURE_CACHE_MAX_ENTRIES,P as UV_FORMAT_FLOAT32,G as UV_FORMAT_UINT16,m as addEdges,t as applyOffset,M as clearTextureCache,a as computeCombinedBoundingBox,s as createCameraController,p as createGrid,x as createLabelLayer,d as createMeasureTool,y as createRenderPipeline,i as createViewGizmo,U as getThreeMeshesFromComputeResponse,O as initThree,l as isEdgeOverlay,_ as materialAppearanceForLook,u as parseBinaryMeshBatch,o as parseColor,A as parseDisplayItems,F as parseMeshBatch,N as parseMeshBatchBlob,b as parseMeshBatchObject,f as removeEdges,E as setTextureAnisotropy,C as snapToVertex,r as updateScene};
2
- //# sourceMappingURL=visualization-MOYO6MDN.js.map
1
+ import{A as L,B as S,C as I,D as R,E as D,F as B,G,H as P,I as u,J as F,K as b,L as N,M as V,N as U,a as e,b as r,c as o,d as t,e as a,f as s,g as p,h as i,i as n,j as m,k as l,l as f,m as y,n as x,o as C,p as d,q as h,r as E,s as M,t as _,u as O,v as c,w as A,x as g,y as T,z as j}from"./chunk-INP5HVA2.js";import"./chunk-Y3M7P3BW.js";export{g as BINARY_MESH_MAGIC,j as BINARY_MESH_VERSION,T as COMPRESSED_MESH_MAGIC,n as EDGE_USERDATA_KIND,R as FLAG_DELTA_ENCODED,S as FLAG_FLOAT32,D as FLAG_HAS_UVS,B as FLAG_HAS_VERTEX_COLORS,I as FLAG_UINT16_INDICES,c as LOOKS,L as MIN_SUPPORTED_VERSION,e as Materials,V as SCALE_FACTORS,h as TEXTURE_CACHE_MAX_ENTRIES,P as UV_FORMAT_FLOAT32,G as UV_FORMAT_UINT16,m as addEdges,t as applyOffset,M as clearTextureCache,a as computeCombinedBoundingBox,s as createCameraController,p as createGrid,x as createLabelLayer,d as createMeasureTool,y as createRenderPipeline,i as createViewGizmo,U as getThreeMeshesFromComputeResponse,O as initThree,l as isEdgeOverlay,_ as materialAppearanceForLook,u as parseBinaryMeshBatch,o as parseColor,A as parseDisplayItems,F as parseMeshBatch,N as parseMeshBatchBlob,b as parseMeshBatchObject,f as removeEdges,E as setTextureAnisotropy,C as snapToVertex,r as updateScene};
2
+ //# sourceMappingURL=visualization-5RH6RSLV.js.map
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkKTKY5M5Scjs = require('./chunk-KTKY5M5S.cjs');require('./chunk-H3FZW6OX.cjs');exports.BINARY_MESH_MAGIC = _chunkKTKY5M5Scjs.x; exports.BINARY_MESH_VERSION = _chunkKTKY5M5Scjs.z; exports.COMPRESSED_MESH_MAGIC = _chunkKTKY5M5Scjs.y; exports.EDGE_USERDATA_KIND = _chunkKTKY5M5Scjs.i; exports.FLAG_DELTA_ENCODED = _chunkKTKY5M5Scjs.D; exports.FLAG_FLOAT32 = _chunkKTKY5M5Scjs.B; exports.FLAG_HAS_UVS = _chunkKTKY5M5Scjs.E; exports.FLAG_HAS_VERTEX_COLORS = _chunkKTKY5M5Scjs.F; exports.FLAG_UINT16_INDICES = _chunkKTKY5M5Scjs.C; exports.LOOKS = _chunkKTKY5M5Scjs.v; exports.MIN_SUPPORTED_VERSION = _chunkKTKY5M5Scjs.A; exports.Materials = _chunkKTKY5M5Scjs.a; exports.SCALE_FACTORS = _chunkKTKY5M5Scjs.M; exports.TEXTURE_CACHE_MAX_ENTRIES = _chunkKTKY5M5Scjs.q; exports.UV_FORMAT_FLOAT32 = _chunkKTKY5M5Scjs.H; exports.UV_FORMAT_UINT16 = _chunkKTKY5M5Scjs.G; exports.addEdges = _chunkKTKY5M5Scjs.j; exports.applyOffset = _chunkKTKY5M5Scjs.d; exports.clearTextureCache = _chunkKTKY5M5Scjs.s; exports.computeCombinedBoundingBox = _chunkKTKY5M5Scjs.e; exports.createCameraController = _chunkKTKY5M5Scjs.f; exports.createGrid = _chunkKTKY5M5Scjs.g; exports.createLabelLayer = _chunkKTKY5M5Scjs.n; exports.createMeasureTool = _chunkKTKY5M5Scjs.p; exports.createRenderPipeline = _chunkKTKY5M5Scjs.m; exports.createViewGizmo = _chunkKTKY5M5Scjs.h; exports.getThreeMeshesFromComputeResponse = _chunkKTKY5M5Scjs.N; exports.initThree = _chunkKTKY5M5Scjs.u; exports.isEdgeOverlay = _chunkKTKY5M5Scjs.k; exports.materialAppearanceForLook = _chunkKTKY5M5Scjs.t; exports.parseBinaryMeshBatch = _chunkKTKY5M5Scjs.I; exports.parseColor = _chunkKTKY5M5Scjs.c; exports.parseDisplayItems = _chunkKTKY5M5Scjs.w; exports.parseMeshBatch = _chunkKTKY5M5Scjs.J; exports.parseMeshBatchBlob = _chunkKTKY5M5Scjs.L; exports.parseMeshBatchObject = _chunkKTKY5M5Scjs.K; exports.removeEdges = _chunkKTKY5M5Scjs.l; exports.setTextureAnisotropy = _chunkKTKY5M5Scjs.r; exports.snapToVertex = _chunkKTKY5M5Scjs.o; exports.updateScene = _chunkKTKY5M5Scjs.b;
2
+ //# sourceMappingURL=visualization-KRP5OPYW.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/selva/selva/packages/compute/dist/visualization-4RSUYQG2.cjs"],"names":[],"mappings":"AAAA,iIAAoT,gCAA6B,k5DAA24B","file":"/home/runner/work/selva/selva/packages/compute/dist/visualization-4RSUYQG2.cjs"}
1
+ {"version":3,"sources":["/home/runner/work/selva/selva/packages/compute/dist/visualization-KRP5OPYW.cjs"],"names":[],"mappings":"AAAA,iIAAoT,gCAA6B,k5DAA24B","file":"/home/runner/work/selva/selva/packages/compute/dist/visualization-KRP5OPYW.cjs"}