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

main
ts 71 lines 2.6 KB
Raw
1 // Alchemy modifications are licensed under Apache-2.0.
2 // This file includes third-party code; see /THIRD_PARTY_LICENSES.md.
3 import {
4 AssetWorkerInner,
5 type Env as BaseEnv,
6 } from "../../internal/workers-shared/workers/asset-worker/index.ts";
7
8 const UNKNOWN_HOST = "http://localhost";
9
10 interface Env extends BaseEnv {
11 __VITE_HTML_EXISTS__: Fetcher;
12 __VITE_FETCH_HTML__: Fetcher;
13 __VITE_HEADERS__: Record<string, string | Array<string> | undefined>;
14 }
15
16 /**
17 * Asset worker that integrates with the Vite dev server.
18 *
19 * - {@link unstable_exists} delegates lookups to Vite so that HTML routes
20 * and files in `publicDir` are discoverable even though they are not in
21 * the on-disk manifest at startup.
22 * - {@link unstable_getByETag} streams the body back through Vite so
23 * `transformIndexHtml` runs on HTML (enabling HMR, script injection, etc.)
24 * and keeps the content type Vite answered with.
25 * - {@link fetch} strips `ETag` / `Cache-Control` (Vite has its own caching
26 * semantics during dev) and appends any custom headers configured via
27 * `server.headers` in the Vite config.
28 *
29 * Mirrors the behavior of `CustomAssetWorker` in
30 * `upstream/workers-sdk/packages/vite-plugin-cloudflare/src/workers/asset-worker`.
31 */
32 export default class ViteAssetWorker extends AssetWorkerInner<Env> {
33 override async fetch(request: Request): Promise<Response> {
34 const response = await super.fetch(request);
35 const modified = new Response(response.body, response);
36 modified.headers.delete("ETag");
37 modified.headers.delete("Cache-Control");
38
39 for (const [key, value] of Object.entries(this.env.__VITE_HEADERS__)) {
40 if (Array.isArray(value)) {
41 for (const item of value) {
42 modified.headers.append(key, item);
43 }
44 } else if (value !== undefined) {
45 modified.headers.set(key, String(value));
46 }
47 }
48
49 return modified;
50 }
51
52 override async unstable_getByETag(eTag: string) {
53 const url = new URL(eTag, UNKNOWN_HOST);
54 const response = await this.env.__VITE_FETCH_HTML__.fetch(url);
55 if (!response.body) {
56 throw new Error(`Unexpected error. No HTML found for "${eTag}".`);
57 }
58 return {
59 readableStream: response.body,
60 contentType: response.headers.get("content-type") ?? "text/html",
61 cacheStatus: "MISS",
62 } as const;
63 }
64
65 override async unstable_exists(pathname: string) {
66 // Guard against `//` collapsing into an invalid URL.
67 const url = new URL(pathname.replace(/^\/{2,}/, "/"), UNKNOWN_HOST);
68 const response = await this.env.__VITE_HTML_EXISTS__.fetch(url);
69 return response.json() as Promise<string | null>;
70 }
71 }