| 474 | } |
| 475 | |
| 476 | function assertResponseWithin(value: unknown, maxBytes: number) { |
| 477 | let bytes = 0; |
| 478 | let nodes = 0; |
| 479 | const visit = (item: unknown): void => { |
| 480 | nodes += 1; |
| 481 | if (nodes > 4096) throw new Error("Workspace capability response has too many values."); |
| 482 | if (typeof item === "string") bytes += item.length * 3; |
| 483 | else if (item instanceof Uint8Array) bytes += item.byteLength * 4; |
| 484 | else if (typeof item === "number" || typeof item === "boolean" || item === null) bytes += 16; |
| 485 | else if (Array.isArray(item)) for (const child of item) visit(child); |
| 486 | else if (item && typeof item === "object") { |
| 487 | for (const [key, child] of Object.entries(item)) { |
| 488 | bytes += key.length * 3; |
| 489 | visit(child); |
| 490 | } |
| 491 | } |
| 492 | if (bytes > maxBytes) { |
| 493 | throw new Error(`Workspace capability response exceeds ${maxBytes} bytes.`); |
| 494 | } |
| 495 | }; |
| 496 | visit(value); |
| 497 | } |
| 498 | |
| 499 | function encodeBoundedError(error: unknown, maxPayloadBytes: number) { |
| 500 | const value = error as { code?: unknown; path?: unknown }; |