{"record":{"id":"7ac0003f431e0218","repo":"JuliusBrussee/caveman","slug":"runtime-policy-response-stream-returned-invalid-by","errorCode":null,"errorMessage":"runtime policy response stream returned invalid bytes","messagePattern":"runtime policy response stream returned invalid bytes","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"packages/sdk/typescript/src/index.ts","lineNumber":890,"sourceCode":"/** Runtime-policy envelopes are KB-sized; stop a hostile body after 1 MiB. */\nconst RUNTIME_POLICY_MAX_RESPONSE_BYTES = 1024 * 1024;\n\nasync function readRuntimePolicyResponseText(response: Response): Promise<string> {\n  const contentLength = response.headers?.get?.(\"content-length\");\n  if (typeof contentLength === \"string\" && /^[0-9]+$/.test(contentLength) && Number(contentLength) > RUNTIME_POLICY_MAX_RESPONSE_BYTES) {\n    await Promise.resolve(response.body?.cancel?.()).catch(() => undefined);\n    throw new Error(\"oversized_response\");\n  }\n\n  const reader = response.body?.getReader?.();\n  if (!reader) throw new Error(\"bounded_response_unavailable\");\n  const chunks: Uint8Array[] = [];\n  let total = 0;\n  try {\n    while (true) {\n      const { done, value } = await reader.read();\n      if (done) break;\n      if (!(value instanceof Uint8Array)) throw new Error(\"runtime policy response stream returned invalid bytes\");\n      total += value.byteLength;\n      if (total > RUNTIME_POLICY_MAX_RESPONSE_BYTES) {\n        await Promise.resolve(reader.cancel()).catch(() => undefined);\n        throw new Error(\"oversized_response\");\n      }\n      chunks.push(value);\n    }\n  } finally {\n    try {\n      reader.releaseLock();\n    } catch {\n      // A broken fetch implementation must not mask the bounded-read result.\n    }\n  }\n  const joined = new Uint8Array(total);\n  let offset = 0;\n  for (const chunk of chunks) {\n    joined.set(chunk, offset);","sourceCodeStart":872,"sourceCodeEnd":908,"githubUrl":"https://github.com/JuliusBrussee/caveman/blob/3ee70a102609e550bd2e68004bf5990a9341c851/packages/sdk/typescript/src/index.ts#L872-L908","documentation":"While streaming the policy response, each chunk must be a Uint8Array. If reader.read() returns a value that is not a Uint8Array, the library throws this error indicating the byte stream contract was violated.","triggerScenarios":"A reader whose read() yields non-Uint8Array chunks — typically a mocked or custom ReadableStream in tests, or a runtime returning a different typed-array/window type (e.g. cross-realm Uint8Array).","commonSituations":"Test doubles queuing strings or plain objects as chunks; cross-realm issues (chunk from another iframe/vm context failing instanceof); custom TransformStreams emitting decoded strings.","solutions":["Ensure chunks enqueued into the stream are Uint8Array instances (encode strings with TextEncoder)","In mocks, use real Uint8Array values instead of strings/objects","If chunk is a different typed array, wrap it: new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength)","Check for cross-realm issues and compare via ArrayBuffer.isView/constructor instead of relying on the library fix"],"exampleFix":"// before\nstream.enqueue(\"policy-json-text\");\n// after\nstream.enqueue(new TextEncoder().encode(\"policy-json-text\"));","handlingStrategy":"validation","validationCode":"const chunks = [new TextEncoder().encode(\"policy\")];\nif (!chunks.every(c => c instanceof Uint8Array)) throw new Error(\"mock stream must enqueue Uint8Array chunks\");","typeGuard":"function isByteChunk(v: unknown): v is Uint8Array {\n  return v instanceof Uint8Array;\n}","tryCatchPattern":"try {\n  const text = await readRuntimePolicyResponseText(response);\n} catch (e) {\n  if (/invalid bytes/.test(e.message)) console.error(\"stream produced non-byte chunks — fix encoder/mock\");\n  else throw e;\n}","preventionTips":["Always TextEncoder-encode strings before enqueueing to streams","Use Uint8Array (not Buffer subclasses from other realms) in mocks","Beware cross-realm Uint8Array in iframe/vm test setups"],"tags":["streaming","typescript","type-mismatch","validation"],"backgroundTag":"type-mismatch","analyzedSha":"3ee70a102609e550bd2e68004bf5990a9341c851","analyzedAt":"2026-09-20T15:53:39.229Z","contentChangedAt":"2026-09-20T15:53:39.229Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}