MCPcopy Create free account
hub / github.com/cloudflare/computer / encodeBoundedError

Function encodeBoundedError

packages/computer/src/runtime/bridge.ts:499–519  ·  view source on GitHub ↗
(error: unknown, maxPayloadBytes: number)

Source from the content-addressed store, hash-verified

497}
498
499function encodeBoundedError(error: unknown, maxPayloadBytes: number) {
500 const value = error as { code?: unknown; path?: unknown };
501 const message = error instanceof Error ? error.message : String(error);
502 const detailed = JSON.stringify({
503 error: {
504 message,
505 ...(typeof value?.code === "string" ? { code: value.code } : {}),
506 ...(typeof value?.path === "string" ? { path: value.path } : {}),
507 },
508 });
509 const encoder = new TextEncoder();
510 if (encoder.encode(detailed).byteLength <= maxPayloadBytes) return detailed;
511
512 let budget = Math.max(0, maxPayloadBytes - 40);
513 while (budget >= 0) {
514 const bounded = JSON.stringify({ error: { message: truncateUtf8(message, budget) } });
515 if (encoder.encode(bounded).byteLength <= maxPayloadBytes) return bounded;
516 budget -= 1;
517 }
518 return JSON.stringify({ error: { message: "Capability call failed" } });
519}
520
521function truncateUtf8(value: string, maxBytes: number) {
522 const bytes = new TextEncoder().encode(value);

Callers 4

rejectMethod · 0.85
callMethod · 0.85
withDeadlineFunction · 0.85
encodeCallFunction · 0.85

Calls 1

truncateUtf8Function · 0.70

Tested by

no test coverage detected