The best way to control Claude Code, Codex and more from any computer or phone

main
ts 122 lines 4.39 KB
Raw
1 // Alchemy modifications are licensed under Apache-2.0.
2 // This file includes third-party code; see /THIRD_PARTY_LICENSES.md.
3 /**
4 * Vendored from `@astrojs/cloudflare` v14.4.2 (`src/utils/prerender.ts`).
5 *
6 * Prerender utilities for the Cloudflare adapter. These endpoints are only
7 * active during the (workerd) prerender build phase and are not available in
8 * production or development; the workerd prerenderer (`../../prerenderer.ts`)
9 * drives them. The `cloudflare-binding` image transform endpoint is not
10 * vendored (the IMAGES binding is not supported).
11 */
12 import type { BaseApp, RenderErrorOptions } from "astro/app";
13 import { renderForPrerender } from "astro/app";
14 import { deserializeRouteData, serializeRouteData } from "astro/app/manifest";
15 import { StaticPaths } from "astro:static-paths";
16 import type { PrerenderRequest, StaticPathsResponse } from "../prerender-types.ts";
17 import { PRERENDER_ENDPOINT, STATIC_PATHS_ENDPOINT } from "./prerender-constants.ts";
18 import { createFramedPrerenderResponse } from "./prerender-response.ts";
19
20 /**
21 * Replicates core's `BuildErrorHandler` semantics on the worker app during
22 * the prerender phase.
23 */
24 export function installPrerenderErrorPropagation(app: BaseApp): void {
25 const originalRenderError = app.renderError.bind(app);
26 app.renderError = async (request: Request, options: RenderErrorOptions): Promise<Response> => {
27 if (options.status === 500) {
28 if (options.response) {
29 return options.response;
30 }
31 throw options.error;
32 }
33 return originalRenderError(request, options);
34 };
35 }
36
37 /**
38 * Checks if the request is for the static paths prerender endpoint.
39 */
40 export function isStaticPathsRequest(request: Request): boolean {
41 const { pathname } = new URL(request.url);
42 return pathname === STATIC_PATHS_ENDPOINT && request.method === "POST";
43 }
44
45 /**
46 * Checks if the request is for the prerender endpoint.
47 */
48 export function isPrerenderRequest(request: Request): boolean {
49 const { pathname } = new URL(request.url);
50 return pathname === PRERENDER_ENDPOINT && request.method === "POST";
51 }
52
53 interface PrerenderOptions {
54 /** Whether prerendered pages get build-time image URLs, for the build to generate. */
55 staticImages: boolean;
56 }
57
58 /**
59 * Handles the static paths request, returning all paths that need prerendering.
60 */
61 export async function handleStaticPathsRequest(
62 app: BaseApp,
63 { staticImages }: PrerenderOptions,
64 ): Promise<Response> {
65 const staticPaths = new StaticPaths(app);
66 const { paths, metadata } = await staticPaths.getAllWithMetadata({ staticImages });
67 const response: StaticPathsResponse = {
68 paths: paths.map(({ pathname, route, cacheKey }) => ({
69 pathname,
70 route: serializeRouteData(route, app.manifest.trailingSlash),
71 cacheKey,
72 })),
73 metadata,
74 };
75 return new Response(JSON.stringify(response), {
76 headers: { "Content-Type": "application/json" },
77 });
78 }
79
80 /**
81 * Handles a prerender request, rendering the specified page. The response
82 * body is fully buffered so streaming errors surface as a 500.
83 */
84 export async function handlePrerenderRequest(
85 app: BaseApp,
86 request: Request,
87 { staticImages }: PrerenderOptions,
88 ): Promise<Response> {
89 const headers = new Headers();
90 for (const [key, value] of request.headers.entries()) {
91 headers.append(key, value);
92 }
93 const body: PrerenderRequest = await request.json();
94 const routeData = deserializeRouteData(body.routeData);
95 const prerenderRequest = new Request(body.url, {
96 method: "GET",
97 headers,
98 });
99 try {
100 // `renderForPrerender` buffers the body (so streaming errors surface
101 // here) and collects the content entries and image transforms resolved
102 // during this render — scoped to this request's async context, so
103 // concurrent prerender requests attribute correctly. A length-prefixed
104 // JSON header carries the metadata before the raw response bytes.
105 const { response, metadata } = await renderForPrerender(app, prerenderRequest, {
106 routeData,
107 staticImages,
108 });
109 return createFramedPrerenderResponse(response, metadata);
110 } catch (err: unknown) {
111 const message = err instanceof Error ? err.message : String(err);
112 // HTTP headers cannot contain newlines.
113 const headerSafe = message.replace(/[\r\n]+/g, " ");
114 return new Response(message, {
115 status: 500,
116 headers: {
117 "Content-Type": "text/plain",
118 "x-astro-prerender-error": headerSafe,
119 },
120 });
121 }
122 }