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

main
ts 136 lines 5.28 KB
Raw
1 import { pathToFileURL } from "node:url";
2 /**
3 * Dev-only nitro plugin: serves the `cloudflare_module` preset's runtime
4 * contract inside nitro's dev SSR worker thread, wrangler-free.
5 *
6 * Injected by the framework host (`Nuxt.dev()` via the Cloudflare target's
7 * dev platform, `./host.ts`) through `overrides.nitro.plugins`; a project
8 * running under its own `nuxi dev` never loads it. On every request it sets
9 * (the same contract `nitro-cloudflare-dev` provides, and production serves
10 * natively):
11 *
12 * - `event.context.cf` — the static `request.cf` mock;
13 * - `event.context.waitUntil` — accepted and dropped (long-lived dev
14 * process: background work simply runs);
15 * - `event.context.cloudflare = { request, env, context }` — `env` is the
16 * live proxied environment (bindings round-trip to the host's workerd
17 * instance over HTTP, so state is SHARED with the host proxy), `request`
18 * is a synthesized `Request` carrying `cf`, `context` is the no-op
19 * `ExecutionContext` mock.
20 *
21 * The platform is reconstructed by `cloudflare-runtime`'s runtime-free
22 * client (`platform-proxy/connect`, imported by the absolute path the host
23 * resolved into the connect info). The connection is established lazily on
24 * the first request and re-created after a failure, so a nitro dev reload
25 * (worker-thread replacement) reconnects on its own with binding state
26 * intact. When the host proxy is gone, requests fail fast with a
27 * descriptive cause instead of hanging.
28 */
29 import type * as ConnectClient from "@alchemy.run/cloudflare-runtime/core/platform-proxy/connect";
30 import { defineNitroPlugin, useRuntimeConfig } from "nitropack/runtime";
31 import { RUNTIME_CONFIG_KEY, type DevConnectInfo } from "./shared.ts";
32
33 /** The runtime-free client module's shape (`platform-proxy/connect`). */
34 type ConnectModule = typeof ConnectClient;
35
36 interface ConnectedPlatform {
37 readonly module: ConnectModule;
38 readonly env: Record<string, unknown>;
39 readonly cf: Record<string, unknown>;
40 }
41
42 /** The structural slice of the h3 event the bridge touches. */
43 interface DevEventSlice {
44 context: Record<string, unknown>;
45 node?: {
46 req?: {
47 url?: string | undefined;
48 method?: string | undefined;
49 headers?: Record<string, string | Array<string> | undefined>;
50 socket?: { encrypted?: boolean | undefined } | undefined;
51 };
52 };
53 }
54
55 const isConnectInfo = (value: unknown): value is DevConnectInfo =>
56 typeof value === "object" &&
57 value !== null &&
58 typeof (value as DevConnectInfo).url === "string" &&
59 typeof (value as DevConnectInfo).token === "string" &&
60 typeof (value as DevConnectInfo).clientModule === "string";
61
62 /**
63 * Synthesize the per-event `Request` (what the preset's runtime hands the
64 * worker). Body is intentionally omitted: the node request stream belongs
65 * to h3's own body parsing — read bodies through h3 (`readBody`), not
66 * `context.cloudflare.request`.
67 */
68 const synthesizeRequest = (
69 event: DevEventSlice,
70 cf: Record<string, unknown>,
71 ): Request | undefined => {
72 try {
73 const req = event.node?.req;
74 if (req === undefined) return undefined;
75 const host = (typeof req.headers?.host === "string" && req.headers.host) || "localhost";
76 const protocol = req.socket?.encrypted === true ? "https" : "http";
77 const url = new URL(req.url ?? "/", `${protocol}://${host}`);
78 const headers = new Headers();
79 for (const [name, value] of Object.entries(req.headers ?? {})) {
80 if (typeof value === "string") headers.set(name, value);
81 else if (Array.isArray(value)) for (const entry of value) headers.append(name, entry);
82 }
83 const request = new Request(url.toString(), {
84 method: req.method ?? "GET",
85 headers,
86 });
87 Object.defineProperty(request, "cf", { value: cf, configurable: true });
88 return request;
89 } catch {
90 return undefined;
91 }
92 };
93
94 export default defineNitroPlugin((nitroApp) => {
95 const config = useRuntimeConfig() as Record<string, unknown>;
96 const info = config[RUNTIME_CONFIG_KEY];
97 if (!isConnectInfo(info)) {
98 // Not running under the distilled dev host — stay inert.
99 return;
100 }
101 let connected: Promise<ConnectedPlatform> | undefined;
102 const connect = () =>
103 (connected ??= (async () => {
104 const module = (await import(
105 /* @vite-ignore */ pathToFileURL(info.clientModule).href
106 )) as ConnectModule;
107 const platform = await module.connect({
108 url: info.url,
109 token: info.token,
110 });
111 // Literal env values overlay the proxied bindings (a same-named
112 // literal always wins).
113 const env: Record<string, unknown> = { ...platform.env };
114 for (const [name, value] of Object.entries(info.env ?? {})) {
115 env[name] = value;
116 }
117 return { module, env, cf: platform.cf };
118 })().catch((error: unknown) => {
119 // Reset so the next request retries (host proxy restarts, races).
120 connected = undefined;
121 throw error;
122 }));
123
124 nitroApp.hooks.hook("request", async (event) => {
125 const slice = event as unknown as DevEventSlice;
126 const platform = await connect();
127 const context = new platform.module.ExecutionContext();
128 slice.context.cf = platform.cf;
129 slice.context.waitUntil = context.waitUntil.bind(context);
130 slice.context.cloudflare = {
131 request: synthesizeRequest(slice, platform.cf),
132 env: platform.env,
133 context,
134 };
135 });
136 });