@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

main
ts 219 lines 7.43 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 * Wrangler-free fork of waku's cloudflare adapter
5 * (upstream `packages/waku/src/adapters/cloudflare.ts` @ waku 1.0.0-beta.7).
6 *
7 * The ONLY functional change: `buildEnhancers` no longer references waku's
8 * cloudflare build-enhancer module, which is the sole code path in waku that
9 * writes wrangler.jsonc / dist/server/wrangler.json /
10 * .wrangler/deploy/config.json. Everything else (Hono app, cloudflare:workers
11 * env access, SSG via the preview server) is behavior-identical.
12 *
13 * Built entirely on public `waku/adapter-builders` + `waku/internals` exports.
14 *
15 * This module is bundled into the Worker by waku's vite pipeline (selected via
16 * the in-memory `Config.unstable_adapter`); it is not Node service code.
17 */
18 import type { MiddlewareHandler } from "hono";
19 import { bodyLimit } from "hono/body-limit";
20 import { Hono } from "hono/tiny";
21 import {
22 unstable_createServerEntryAdapter as createServerEntryAdapter,
23 unstable_startPreviewServer as startPreviewServer,
24 } from "waku/adapter-builders";
25 import {
26 unstable_constants as constants,
27 unstable_consumeMultiplexedStream as consumeMultiplexedStream,
28 unstable_honoMiddleware as honoMiddleware,
29 unstable_produceMultiplexedStream as produceMultiplexedStream,
30 } from "waku/internals";
31
32 const { DIST_PUBLIC } = constants;
33 const { rscMiddleware, middlewareRunner } = honoMiddleware;
34
35 const DEFAULT_BODY_LIMIT_MAX_SIZE = 100 * 1024 * 1024;
36
37 const DO_NOT_BUNDLE = "";
38
39 const PRUNABLE_KEY_PREFIX = "\0__prunable__/";
40
41 const emptyStream = () =>
42 new ReadableStream<Uint8Array>({
43 start(controller) {
44 controller.close();
45 },
46 });
47
48 function isProductionWorker(req: Request): boolean {
49 // This header seems to only be set for production cloudflare workers
50 return !!req.headers.get("cf-visitor");
51 }
52
53 function isLoopbackRequest(req: Request): boolean {
54 const { hostname } = new URL(req.url);
55 return (
56 hostname === "localhost" ||
57 hostname === "127.0.0.1" ||
58 hostname === "::1" ||
59 hostname === "[::1]"
60 );
61 }
62
63 function removeGzipEncoding(res: Response): Response {
64 const contentType = res.headers.get("content-type");
65 if (!contentType || contentType.includes("text/html") || contentType.includes("text/plain")) {
66 const headers = new Headers(res.headers);
67 headers.set("content-encoding", "Identity");
68 return new Response(res.body, {
69 status: res.status,
70 statusText: res.statusText,
71 headers,
72 });
73 }
74 return res;
75 }
76
77 /** Options accepted by the adapter (identical to upstream's). */
78 export interface CloudflareAdapterOptions {
79 static?: boolean;
80 handlers?: Record<string, unknown>;
81 assetsDir?: string;
82 bodyLimit?: Parameters<typeof bodyLimit>[0] | false;
83 middlewareFns?: Array<(opts: { app: Hono }) => MiddlewareHandler>;
84 middlewareModules?: Record<string, () => Promise<unknown>>;
85 internalPathToBuildStaticFiles?: string;
86 }
87
88 /**
89 * Annotated via an instantiation expression over the public
90 * `createServerEntryAdapter` so the emitted declaration never references
91 * waku's non-exported `lib/types` module (TS2883).
92 */
93 const cloudflareAdapter: ReturnType<
94 typeof createServerEntryAdapter<CloudflareAdapterOptions | undefined>
95 > = createServerEntryAdapter(
96 (
97 { processRequest, processBuild, unstable_setAllEnv: setAllEnv, config, notFoundHtml },
98 options?: CloudflareAdapterOptions,
99 ) => {
100 const {
101 bodyLimit: bodyLimitOptions,
102 middlewareFns = [],
103 middlewareModules = {},
104 internalPathToBuildStaticFiles = "__waku_internal_build_static_files",
105 } = options || {};
106 const app = new Hono();
107 app.notFound((c) => {
108 if (notFoundHtml) {
109 return c.html(notFoundHtml, 404);
110 }
111 return c.text("404 Not Found", 404);
112 });
113 if (bodyLimitOptions !== false) {
114 app.use(bodyLimit(bodyLimitOptions ?? { maxSize: DEFAULT_BODY_LIMIT_MAX_SIZE }));
115 }
116 for (const middlewareFn of middlewareFns) {
117 app.use(middlewareFn({ app }));
118 }
119 app.use(middlewareRunner(middlewareModules as never, { app }));
120 app.use(rscMiddleware({ processRequest }));
121 const buildOptions = {
122 srcDir: config.srcDir,
123 distDir: config.distDir,
124 DIST_PUBLIC,
125 serverless: !options?.static,
126 };
127
128 const buildBody = () =>
129 produceMultiplexedStream(async (emitFile) => {
130 await processBuild({
131 emitFile,
132 unstable_registerPrunableFile: (srcPath) =>
133 emitFile(PRUNABLE_KEY_PREFIX + srcPath, emptyStream()),
134 });
135 });
136
137 const fetchFn = async (req: Request) => {
138 if (
139 new URL(req.url).pathname === `/${internalPathToBuildStaticFiles}` &&
140 isLoopbackRequest(req) &&
141 !isProductionWorker(req)
142 ) {
143 return new Response(buildBody());
144 }
145 let cloudflareContext;
146 try {
147 cloudflareContext = await import(/* @vite-ignore */ DO_NOT_BUNDLE + "cloudflare:workers");
148 } catch {
149 // Not in a Cloudflare environment
150 }
151 let res: Response | Promise<Response>;
152 if (cloudflareContext) {
153 const { env, waitUntil, passThroughOnException } = cloudflareContext;
154 res = app.fetch(req, env, {
155 waitUntil,
156 passThroughOnException,
157 props: undefined,
158 });
159 } else {
160 res = app.fetch(req);
161 }
162 // Workaround https://github.com/cloudflare/workers-sdk/issues/6577
163 // NOTE: must stay the literal `import.meta.env?.PROD` expression — the
164 // bundler replaces it statically; any other access pattern throws
165 // "[module runner] Dynamic access of import.meta.env" in dev.
166 if (import.meta.env?.PROD && !isProductionWorker(req)) {
167 if ("then" in res) {
168 res = res.then((res) => removeGzipEncoding(res));
169 } else {
170 res = removeGzipEncoding(res);
171 }
172 }
173 return res;
174 };
175
176 return {
177 fetch: fetchFn,
178 build: async (utils) => {
179 const server = await startPreviewServer();
180 // Fallback middleware for the case without a Cloudflare vite plugin
181 // preview server: streams the SSG output directly from Node.
182 server.middlewares.use(async (_req, res, next) => {
183 try {
184 const { Readable } = await import(/* @vite-ignore */ DO_NOT_BUNDLE + "node:stream");
185 Readable.fromWeb(buildBody() as never).pipe(res as never);
186 } catch (err) {
187 next(err);
188 }
189 });
190 const response = await fetch(server.baseUrl + internalPathToBuildStaticFiles, {
191 headers: { connection: "close" },
192 });
193 await consumeMultiplexedStream(response.body!, async (key, stream) => {
194 if (key.startsWith(PRUNABLE_KEY_PREFIX)) {
195 utils.unstable_registerPrunableFile(key.slice(PRUNABLE_KEY_PREFIX.length));
196 return;
197 }
198 await utils.emitFile(key, stream);
199 });
200 // https://github.com/nodejs/node/issues/56645
201 await new Promise((resolve) => setTimeout(resolve, 100));
202 await server.close();
203 },
204 buildOptions,
205 // Upstream lists its build-enhancer module here — the ONLY
206 // wrangler-config writer in waku. Dropped: no wrangler files, ever.
207 buildEnhancers: [],
208 defaultExport: {
209 ...options?.handlers,
210 fetch(req: Request, env: Record<string, unknown>) {
211 setAllEnv(env);
212 return fetchFn(req);
213 },
214 },
215 };
216 },
217 );
218
219 export default cloudflareAdapter;