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

main
ts 124 lines 4.36 KB
Raw
1 import type { RouteData } from "astro";
2 import type { RenderOptions } from "astro/app";
3 import { createApp } from "astro/app/entrypoint";
4 import { setGetEnv } from "astro/env/setup";
5 // Alchemy modifications are licensed under Apache-2.0.
6 // This file includes third-party code; see /THIRD_PARTY_LICENSES.md.
7 /**
8 * Vendored from `@astrojs/cloudflare` v14.4.2 (`src/utils/handler.ts`).
9 *
10 * The Worker `fetch` handler. Imports zero wrangler code; bindings are read
11 * from `cloudflare:workers` env and the `virtual:astro-cloudflare:config`
12 * virtual module served by this package's config plugin.
13 */
14 import { env as globalEnv } from "cloudflare:workers";
15 import {
16 cacheProviderEnabled,
17 compileImageConfig,
18 isPrerender,
19 loadPrerenderScope,
20 } from "virtual:astro-cloudflare:config";
21 import {
22 createErrorPageFetch,
23 createLocals,
24 fallbackToAssets,
25 getClientAddress,
26 injectSessionBinding,
27 matchStaticAsset,
28 type Runtime,
29 } from "./cf.ts";
30 import { createGetEnv } from "./env.ts";
31 import {
32 handlePrerenderRequest,
33 handleStaticPathsRequest,
34 installPrerenderErrorPropagation,
35 isPrerenderRequest,
36 isStaticPathsRequest,
37 } from "./prerender.ts";
38 import { applyCloudflareResponseHeaders } from "./response.ts";
39
40 export type { Runtime };
41
42 setGetEnv(createGetEnv(globalEnv));
43
44 declare global {
45 // This is not a real global, but is injected using Vite define to allow us to specify the Images binding name in the config.
46 var __ASTRO_IMAGES_BINDING_NAME: string;
47 }
48
49 type CfResponse = Awaited<ReturnType<Required<ExportedHandler<Env>>["fetch"]>>;
50
51 const app = createApp();
52
53 if (isPrerender) {
54 installPrerenderErrorPropagation(app);
55 }
56
57 export async function handle(
58 request: Request,
59 env: Env,
60 context: ExecutionContext,
61 ): Promise<CfResponse> {
62 // Sessions must be wired before the prerender branch below — prerender
63 // requests return from `handlePrerenderRequest` without falling through,
64 // and session-touching pages render inside it.
65 injectSessionBinding(app.manifest, env);
66
67 // Handle prerender endpoints (only active during build prerender phase)
68 if (isPrerender) {
69 const isStaticPaths = isStaticPathsRequest(request);
70 if (isStaticPaths || isPrerenderRequest(request)) {
71 await app.getLogger();
72 // Install the isolate's render scope so concurrent prerender requests
73 // each collect their metadata in their own per-render store. The
74 // loader thunk is generated into the virtual config module only for the
75 // prerender environment, keeping the module — and its `node:async_hooks`
76 // import — out of production worker output entirely; the install
77 // itself is first-wins, making the per-request call idempotent.
78 (await loadPrerenderScope?.())?.ensurePrerenderScope();
79 // Without build-time image optimization, prerendered pages keep the runtime image URLs.
80 const options = { staticImages: compileImageConfig !== null };
81 return (isStaticPaths
82 ? handleStaticPathsRequest(app, options)
83 : handlePrerenderRequest(app, request, options)) as unknown as CfResponse;
84 }
85 }
86
87 // NOTE this ASSETS binding path is needed for users who are using `run_worker_first` routing
88 const staticAsset = matchStaticAsset(app.manifest, request.url, env);
89 if (staticAsset) return staticAsset as CfResponse;
90
91 let routeData: RouteData | undefined = undefined;
92 if (app.isDev()) {
93 const result = await app.devMatch(app.getPathnameFromRequest(request));
94 if (result) {
95 routeData = result.routeData;
96 }
97 } else {
98 routeData = app.match(request);
99 }
100
101 if (!routeData) {
102 // NOTE this ASSETS binding path is needed for users who are using `run_worker_first` routing
103 const asset = await fallbackToAssets(request.url, env);
104 if (asset) return asset as CfResponse;
105 }
106
107 const locals = createLocals(context);
108
109 const waitUntil: RenderOptions["waitUntil"] = context.waitUntil.bind(context);
110
111 const response = await app.render(request, {
112 routeData,
113 locals,
114 waitUntil,
115 prerenderedErrorPageFetch: createErrorPageFetch(env),
116 clientAddress: getClientAddress(request),
117 });
118
119 // Collect cookies before any rebuild: `setCookieHeaders` looks the
120 // response up by identity, so it must see the original object.
121 const setCookieHeaders = app.setCookieHeaders ? [...app.setCookieHeaders(response)] : [];
122
123 return applyCloudflareResponseHeaders(response, setCookieHeaders, cacheProviderEnabled);
124 }