@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 306 lines 11.9 KB
Raw
1 import * as NodeFs from "node:fs/promises";
2 import type { IncomingMessage, ServerResponse } from "node:http";
3 import * as Effect from "effect/Effect";
4 import * as Layer from "effect/Layer";
5 import mime from "mime";
6 import type * as vite from "vite";
7 import * as Assets from "../../core/bindings/assets/Assets.ts";
8 import * as Loopback from "../../core/globals/Loopback.ts";
9 import { DEFAULT_COMPATIBILITY_DATE } from "../../core/internal/constants.ts";
10 // Alchemy modifications are licensed under Apache-2.0.
11 // This file includes third-party code; see /THIRD_PARTY_LICENSES.md.
12 import { loadInternalWorker } from "../../core/internal/internal-worker.ts";
13 import { PluginContext } from "../../core/PluginContext.ts";
14 const AssetsWorker = {
15 worker: () => loadInternalWorker("#cloudflare-runtime-vite-worker/assets/assets.worker"),
16 };
17 const RouterWorker = {
18 worker: () => loadInternalWorker("#cloudflare-runtime-vite-worker/assets/router.worker"),
19 };
20 const ViteProxyWorker = {
21 worker: () => loadInternalWorker("#cloudflare-runtime-vite-worker/assets/vite-proxy.worker"),
22 };
23 /** Must match `VITE_MISS_HEADER` in `vite-proxy.worker.ts`. */
24 const VITE_MISS_HEADER = "x-alchemy-vite-asset-miss";
25 /**
26 * Marks a request the dev `ASSETS` binding sent through Vite's middleware, so
27 * the proxy middleware passes it on instead of sending it back to the Worker.
28 */
29 export const VITE_ASSET_REQUEST = Symbol.for("alchemy.cloudflare-runtime.vite-asset-request");
30 /**
31 * Marker prefix used by the vite-aware asset worker to indicate that a
32 * path lives inside Vite's `publicDir` (and so should be served verbatim,
33 * without running through `transformIndexHtml`). It carries a leading slash
34 * because the asset worker reads the key back as a URL pathname.
35 */
36 const PUBLIC_DIR_PREFIX = "/__vite_public_dir__";
37
38 /**
39 * Asset plugin layer wired to a Vite dev server.
40 *
41 * Unlike {@link Assets.AssetsLive}, this implementation does not build a
42 * disk-backed asset manifest or KV namespace at all: the vite-aware asset
43 * worker overrides `unstable_exists` / `unstable_getByETag` to delegate
44 * every HTML lookup back to Vite via Loopback bindings, so HMR,
45 * `transformIndexHtml`, virtual routes, and files in `publicDir` all
46 * resolve through the dev server instead of through a static snapshot.
47 *
48 * Mirrors the dev-mode asset wiring in
49 * `upstream/workers-sdk/packages/vite-plugin-cloudflare/src/miniflare-options.ts`.
50 */
51 export const ViteAssetsLive = (
52 viteDevServer: vite.ViteDevServer,
53 options: {
54 /** `false` for an assets-only site: requests no asset serves get a 404 instead of the Worker. */
55 readonly hasUserWorker: boolean;
56 },
57 ) =>
58 Layer.effect(
59 Assets.Assets,
60 Effect.gen(function* () {
61 const loopback = yield* Loopback.Loopback;
62
63 if (Effect.isEffect(loopback)) {
64 return yield* Effect.die("Expected loopback to be initialized");
65 }
66
67 return Assets.Assets.of(
68 Effect.gen(function* () {
69 const { worker } = yield* PluginContext;
70 const { assetsConfig, routerConfig } = yield* Assets.buildAssetConfigs(worker);
71
72 const prefix = `vite-assets:${encodeURIComponent(worker.name)}`;
73 const htmlExistsService = yield* loopback.api.route(
74 `${prefix}:html-exists`,
75 viteHtmlExistsHandler(viteDevServer),
76 );
77 const fetchHtmlService = yield* loopback.api.route(
78 `${prefix}:fetch-html`,
79 viteFetchHtmlHandler(viteDevServer),
80 );
81 const viteMiddlewareService = yield* loopback.api.route(
82 `${prefix}:vite-middleware`,
83 viteMiddlewareHandler(viteDevServer),
84 );
85 const [assetsWorker, routerWorker, viteProxyWorker] = yield* Effect.forEach(
86 [AssetsWorker, RouterWorker, ViteProxyWorker],
87 (worker) =>
88 Effect.map(Effect.promise(worker.worker), ({ modules }) => modulesToWorkerd(modules)),
89 { concurrency: "unbounded" },
90 );
91
92 return {
93 services: [
94 {
95 // What a Worker's `ASSETS` binding calls (see
96 // `vite-proxy.worker.ts`).
97 name: "assets:worker",
98 worker: {
99 compatibilityDate: DEFAULT_COMPATIBILITY_DATE,
100 bindings: [
101 { name: "__VITE_MIDDLEWARE__", service: viteMiddlewareService },
102 { name: "ASSET_WORKER", service: { name: "assets:vite" } },
103 ],
104 modules: viteProxyWorker,
105 },
106 },
107 {
108 name: "assets:vite",
109 worker: {
110 compatibilityDate: DEFAULT_COMPATIBILITY_DATE,
111 // Node.js compatibility is supplied by the 2026-08-31
112 // internal compatibility date.
113 bindings: [
114 {
115 name: "CONFIG",
116 json: JSON.stringify(assetsConfig),
117 },
118 {
119 name: "__VITE_HEADERS__",
120 json: JSON.stringify(viteDevServer.config.server.headers ?? {}),
121 },
122 {
123 name: "__VITE_HTML_EXISTS__",
124 service: htmlExistsService,
125 },
126 {
127 name: "__VITE_FETCH_HTML__",
128 service: fetchHtmlService,
129 },
130 ],
131 modules: assetsWorker,
132 },
133 },
134 ],
135 middlewares: [
136 {
137 name: "assets:router",
138 worker: {
139 compatibilityDate: DEFAULT_COMPATIBILITY_DATE,
140 // The date supplies nodejs_compat; this worker deliberately
141 // retains only its v2 opt-out.
142 compatibilityFlags: ["no_nodejs_compat_v2"],
143 bindings: [
144 {
145 name: "ASSET_WORKER",
146 service: { name: "assets:vite" },
147 },
148 {
149 name: "CONFIG",
150 json: JSON.stringify({
151 ...routerConfig,
152 has_user_worker: options.hasUserWorker,
153 }),
154 },
155 ],
156 modules: routerWorker,
157 },
158 upstreamBindingName: "USER_WORKER",
159 order: -1,
160 },
161 ],
162 api: { isConfigured: true },
163 };
164 }),
165 );
166 }),
167 );
168
169 /**
170 * Returns the asset key for a pathname (or `null`): any file in Vite's
171 * `publicDir`, or an HTML file under the root.
172 * Files under Vite's `publicDir` are prefixed with `PUBLIC_DIR_PREFIX` so
173 * the companion handler knows to skip `transformIndexHtml`.
174 */
175 const viteHtmlExistsHandler =
176 (viteDevServer: vite.ViteDevServer) => async (req: IncomingMessage, res: ServerResponse) => {
177 const pathname = new URL(req.url ?? "/", "http://localhost").pathname;
178 const json = (body: unknown) => {
179 res.writeHead(200, { "content-type": "application/json" });
180 res.end(JSON.stringify(body));
181 };
182
183 const { root, publicDir } = viteDevServer.config;
184 const publicDirInRoot = publicDir.startsWith(withTrailingSlash(root));
185 const publicPath = withTrailingSlash(publicDir.slice(root.length));
186
187 // Files served from the public dir are addressed from the root path.
188 if (publicDirInRoot && pathname.startsWith(publicPath)) {
189 return json(null);
190 }
191
192 // Vite resolves a disabled `publicDir` to `""`; joining that would read
193 // the pathname as an absolute path on the host.
194 const publicDirFilePath = publicDir ? `${publicDir}${pathname}` : undefined;
195 const rootDirFilePath = `${root}${pathname}`;
196
197 // Beyond the public dir only HTML resolves: other files under the root are Vite's modules.
198 const candidates = [
199 publicDirFilePath,
200 pathname.endsWith(".html") ? rootDirFilePath : undefined,
201 ].filter((candidate) => candidate !== undefined);
202 for (const resolved of candidates) {
203 try {
204 const stats = await NodeFs.stat(resolved);
205 if (stats.isFile()) {
206 return json(
207 resolved === publicDirFilePath ? `${PUBLIC_DIR_PREFIX}${pathname}` : pathname,
208 );
209 }
210 } catch {
211 // continue
212 }
213 }
214 return json(null);
215 };
216
217 /**
218 * Returns the body for a path previously resolved by
219 * {@link viteHtmlExistsHandler}. Non-public HTML is run through
220 * `viteDevServer.transformIndexHtml` so that HMR and plugin transforms
221 * apply; other public files are served as raw bytes.
222 */
223 const viteFetchHtmlHandler =
224 (viteDevServer: vite.ViteDevServer) => async (req: IncomingMessage, res: ServerResponse) => {
225 const pathname = new URL(req.url ?? "/", "http://localhost").pathname;
226 const { root, publicDir } = viteDevServer.config;
227 const isInPublicDir = pathname.startsWith(PUBLIC_DIR_PREFIX);
228 const resolved = isInPublicDir
229 ? `${publicDir}${pathname.slice(PUBLIC_DIR_PREFIX.length)}`
230 : `${root}${pathname}`;
231
232 try {
233 if (isInPublicDir && !resolved.endsWith(".html")) {
234 const body = await NodeFs.readFile(resolved);
235 res.writeHead(200, {
236 "content-type": mime.getType(resolved) ?? "application/octet-stream",
237 });
238 res.end(body);
239 return;
240 }
241 // Vite's bundled dev mode (`experimental.bundledDev`) serves HTML from
242 // its in-memory bundle, as `@cloudflare/vite-plugin` reads it.
243 const bundledDev = isInPublicDir ? undefined : bundledDevOf(viteDevServer);
244 if (bundledDev) {
245 const source = await readBundledFile(bundledDev, pathname.slice(1));
246 res.writeHead(200, { "content-type": "text/html" });
247 res.end(typeof source === "string" ? source : Buffer.from(source));
248 return;
249 }
250 let html = await NodeFs.readFile(resolved, "utf-8");
251 if (!isInPublicDir) {
252 html = await viteDevServer.transformIndexHtml(resolved, html);
253 }
254 res.writeHead(200, { "content-type": "text/html" });
255 res.end(html);
256 } catch {
257 res.writeHead(500, { "content-type": "text/plain" });
258 res.end(`Unexpected error. Failed to load "${pathname}".`);
259 }
260 };
261
262 interface BundledDev {
263 triggerBundleRegenerationIfStale(): Promise<unknown>;
264 memoryFiles: { get(key: string): { source: string | Uint8Array } | undefined };
265 }
266
267 const bundledDevOf = (viteDevServer: vite.ViteDevServer): BundledDev | undefined =>
268 (viteDevServer.environments.client as { bundledDev?: BundledDev } | undefined)?.bundledDev;
269
270 /** A bundled file, once a regeneration the request triggered has written it. */
271 const readBundledFile = async (bundledDev: BundledDev, key: string) => {
272 await bundledDev.triggerBundleRegenerationIfStale();
273 const deadline = Date.now() + 10_000;
274 let file = bundledDev.memoryFiles.get(key);
275 while (!file && Date.now() < deadline) {
276 await new Promise((resolve) => setTimeout(resolve, 10));
277 file = bundledDev.memoryFiles.get(key);
278 }
279 if (!file) {
280 throw new Error(`No bundled file for "/${key}" after waiting for bundle regeneration.`);
281 }
282 return file.source;
283 };
284
285 /**
286 * Runs a dev `ASSETS` request through Vite's middleware, as
287 * `@cloudflare/vite-plugin` binds `ASSETS` in dev. A request no middleware
288 * serves answers with {@link VITE_MISS_HEADER} so the proxy worker falls back
289 * to the asset worker.
290 */
291 const viteMiddlewareHandler =
292 (viteDevServer: vite.ViteDevServer) => (req: IncomingMessage, res: ServerResponse) => {
293 (req as IncomingMessage & { [VITE_ASSET_REQUEST]?: true })[VITE_ASSET_REQUEST] = true;
294 viteDevServer.middlewares(req, res, () => {
295 res.writeHead(404, { [VITE_MISS_HEADER]: "1" });
296 res.end();
297 });
298 };
299
300 const withTrailingSlash = (s: string) => (s.endsWith("/") ? s : `${s}/`);
301
302 const modulesToWorkerd = (modules: Record<string, string>) =>
303 Object.entries(modules).map(([name, esModule]) => ({
304 name,
305 esModule,
306 }));