The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 06:00 UTC
| 1 | // Alchemy modifications are licensed under Apache-2.0. |
| 2 | // This file includes third-party code; see /THIRD_PARTY_LICENSES.md. |
| 3 | // Vendored from `@astrojs/cloudflare` v14.4.2 (`src/utils/prerender-response.ts`). |
| 4 | /** |
| 5 | * Frames prerender response metadata as length-prefixed JSON followed by the |
| 6 | * raw body bytes. This private protocol transports arbitrary output without |
| 7 | * base64 encoding or state shared between requests. |
| 8 | */ |
| 9 | import type { PrerenderRenderMetadata } from "astro"; |
| 10 | import type { PrerenderResponseMetadata } from "../prerender-types.ts"; |
| 11 | |
| 12 | export const METADATA_LENGTH_BYTES = 4; |
| 13 | export const MAX_METADATA_LENGTH = 16 * 1024 * 1024; |
| 14 | export const PRERENDER_RESPONSE_CONTENT_TYPE = "application/vnd.astro.prerender"; |
| 15 | |
| 16 | export function createFramedPrerenderResponse( |
| 17 | response: Response, |
| 18 | metadata: PrerenderRenderMetadata | undefined, |
| 19 | ): Response { |
| 20 | const responseMetadata: PrerenderResponseMetadata = { |
| 21 | status: response.status, |
| 22 | statusText: response.statusText, |
| 23 | headers: [...response.headers.entries()], |
| 24 | hasBody: response.body !== null, |
| 25 | metadata, |
| 26 | }; |
| 27 | const metadataBytes = new TextEncoder().encode(JSON.stringify(responseMetadata)); |
| 28 | if (metadataBytes.byteLength > MAX_METADATA_LENGTH) { |
| 29 | throw new RangeError("Prerender response metadata is too large to encode."); |
| 30 | } |
| 31 | |
| 32 | const lengthBytes = new Uint8Array(METADATA_LENGTH_BYTES); |
| 33 | new DataView(lengthBytes.buffer).setUint32(0, metadataBytes.byteLength); |
| 34 | const bodyReader = response.body?.getReader(); |
| 35 | let phase = 0; |
| 36 | const framedBody = new ReadableStream<Uint8Array>({ |
| 37 | async pull(controller) { |
| 38 | if (phase === 0) { |
| 39 | phase = 1; |
| 40 | controller.enqueue(lengthBytes); |
| 41 | return; |
| 42 | } |
| 43 | if (phase === 1) { |
| 44 | phase = 2; |
| 45 | controller.enqueue(metadataBytes); |
| 46 | if (!bodyReader) controller.close(); |
| 47 | return; |
| 48 | } |
| 49 | if (!bodyReader) { |
| 50 | controller.close(); |
| 51 | return; |
| 52 | } |
| 53 | const { done, value } = await bodyReader.read(); |
| 54 | if (done) { |
| 55 | controller.close(); |
| 56 | } else { |
| 57 | controller.enqueue(value); |
| 58 | } |
| 59 | }, |
| 60 | cancel(reason) { |
| 61 | return bodyReader?.cancel(reason); |
| 62 | }, |
| 63 | }); |
| 64 | |
| 65 | return new Response(framedBody, { |
| 66 | headers: { |
| 67 | "Cache-Control": "no-store", |
| 68 | "Content-Type": PRERENDER_RESPONSE_CONTENT_TYPE, |
| 69 | }, |
| 70 | }); |
| 71 | } |