@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, 04:45 UTC

main
ts 246 lines 8.34 KB
Raw
1 import * as NodeHttp from "node:http";
2 import type { AddressInfo } from "node:net";
3 import path from "node:path";
4 import * as vite from "vite";
5 import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
6 import { WebSocketServer } from "ws";
7 import { DistilledDevEnvironment } from "../dev-environment.ts";
8 import cloudflareVitePlugin from "../plugin.ts";
9
10 // Stand-in for the workerd dev runtime: a plain HTTP server (every proxied
11 // request responds with "worker") that also accepts the module-runner
12 // WebSocket connections `DistilledDevEnvironment.connect` opens.
13 let runtimeAddress: string;
14
15 vi.mock("../dev-server.ts", () => ({
16 createDefaultContext: async () => ({}),
17 startServer: async () => ({
18 address: runtimeAddress,
19 proxySharedSecret: "dev-secret",
20 close: async () => {},
21 }),
22 }));
23
24 const root = path.join(import.meta.dirname, "fixtures");
25
26 const listen = (server: NodeHttp.Server): Promise<string> =>
27 new Promise((resolve, reject) => {
28 server.once("error", reject);
29 server.listen(0, "127.0.0.1", () => {
30 const { port } = server.address() as AddressInfo;
31 resolve(`http://127.0.0.1:${port}`);
32 });
33 });
34
35 describe("dev plugin", () => {
36 let runtimeServer: NodeHttp.Server;
37 let webSocketServer: WebSocketServer;
38
39 beforeAll(async () => {
40 runtimeServer = NodeHttp.createServer((_req, res) => {
41 res.end("worker");
42 });
43 webSocketServer = new WebSocketServer({ server: runtimeServer });
44 runtimeAddress = await listen(runtimeServer);
45 });
46
47 afterAll(async () => {
48 for (const client of webSocketServer.clients) {
49 client.terminate();
50 }
51 webSocketServer.close();
52 runtimeServer.closeAllConnections();
53 await new Promise((resolve) => runtimeServer.close(resolve));
54 });
55
56 const createDevServer = (plugins: vite.PluginOption, config: vite.UserConfig = {}) =>
57 vite.createServer({
58 ...config,
59 configFile: false,
60 cacheDir: path.resolve(import.meta.dirname, "../.cache/dev-plugin-vite"),
61 root,
62 logLevel: "silent",
63 plugins: [plugins],
64 server: { middlewareMode: true, hmr: false },
65 });
66
67 const request = async (
68 server: vite.ViteDevServer,
69 url: string,
70 ): Promise<{ status: number; text: string }> => {
71 const httpServer = NodeHttp.createServer(server.middlewares);
72 const address = await listen(httpServer);
73 try {
74 const response = await fetch(`${address}${url}`);
75 return { status: response.status, text: await response.text() };
76 } finally {
77 httpServer.closeAllConnections();
78 await new Promise((resolve) => httpServer.close(resolve));
79 }
80 };
81
82 const frameworkPlugin = (): vite.Plugin => ({
83 name: "fake-framework",
84 configureServer(server) {
85 return () => {
86 // Mimics a framework's Node request bridge (e.g. Waku's RSC bridge):
87 // a catch-all post middleware registered by a plugin that precedes
88 // ours in the plugin order.
89 server.middlewares.use(function frameworkCatchAll(_req, res) {
90 res.statusCode = 200;
91 res.end("framework");
92 });
93 };
94 },
95 });
96
97 it("degrades to a runnable environment when configureServer is stripped (framework typegen servers)", async () => {
98 // Frameworks strip `configureServer` off the plugin instances when they
99 // create throwaway dev servers (e.g. Astro's type generation during
100 // `build`/`sync`) so no workerd runtime boots mid-build.
101 const plugins = cloudflareVitePlugin({
102 main: "./worker-entry.ts",
103 }) as Array<vite.Plugin>;
104 for (const plugin of plugins) {
105 plugin.configureServer = undefined;
106 }
107 const server = await createDevServer(plugins);
108 try {
109 const environment = server.environments["ssr"];
110 expect(environment).toBeDefined();
111 expect(environment).not.toBeInstanceOf(DistilledDevEnvironment);
112 expect(vite.isRunnableDevEnvironment(environment!)).toBe(true);
113 } finally {
114 await server.close();
115 }
116 });
117
118 it("leaves the environment runnable when there is no Worker entry", async () => {
119 // An assets-only dev run boots workerd for the asset layer but evaluates
120 // no modules, so the `ssr` environment stays Vite's own: a framework
121 // plugin that renders through `ssrLoadModule` in dev keeps working.
122 const server = await createDevServer(cloudflareVitePlugin({}));
123 try {
124 const environment = server.environments["ssr"];
125 expect(environment).toBeDefined();
126 expect(environment).not.toBeInstanceOf(DistilledDevEnvironment);
127 expect(vite.isRunnableDevEnvironment(environment!)).toBe(true);
128 } finally {
129 await server.close();
130 }
131 });
132
133 it("creates the Distilled environment when configureServer is intact", async () => {
134 const server = await createDevServer(cloudflareVitePlugin({ main: "./worker-entry.ts" }));
135 try {
136 expect(server.environments["ssr"]).toBeInstanceOf(DistilledDevEnvironment);
137 } finally {
138 await server.close();
139 }
140 });
141
142 it("accepts multiple aliases for the same Worker entry", async () => {
143 const server = await createDevServer([
144 {
145 name: "framework-entry-aliases",
146 config: () => ({
147 environments: {
148 ssr: {
149 build: {
150 rollupOptions: {
151 input: {
152 worker: "./worker-entry.ts",
153 "entry.worker": path.join(root, "worker-entry.ts"),
154 },
155 },
156 },
157 },
158 },
159 }),
160 },
161 cloudflareVitePlugin({}),
162 ]);
163 try {
164 expect(server.environments["ssr"]).toBeInstanceOf(DistilledDevEnvironment);
165 expect((await request(server, "/")).text).toBe("worker");
166 } finally {
167 await server.close();
168 }
169 });
170
171 it("rejects distinct Worker entries", async () => {
172 await expect(
173 createDevServer(cloudflareVitePlugin({}), {
174 environments: {
175 ssr: {
176 build: {
177 rollupOptions: {
178 input: {
179 first: "./worker-entry.ts",
180 second: "./other-entry.ts",
181 },
182 },
183 },
184 },
185 },
186 }),
187 ).rejects.toThrow("Expected exactly one entry in the input, got 2 entries");
188 });
189
190 it("registers the proxy middleware after other plugins' post middlewares by default", async () => {
191 const server = await createDevServer([
192 frameworkPlugin(),
193 cloudflareVitePlugin({ main: "./worker-entry.ts" }),
194 ]);
195 try {
196 const response = await request(server, "/");
197 expect(response.text).toBe("framework");
198 } finally {
199 await server.close();
200 }
201 });
202
203 it('registers the proxy middleware ahead of other plugins\' post middlewares with middlewareOrder: "pre"', async () => {
204 const server = await createDevServer([
205 frameworkPlugin(),
206 cloudflareVitePlugin({
207 main: "./worker-entry.ts",
208 dev: { middlewareOrder: "pre" },
209 }),
210 ]);
211 try {
212 // Appended after the framework's plugins, the proxy still sees requests
213 // first, so the framework's Node bridge never fires.
214 const response = await request(server, "/");
215 expect(response.text).toBe("worker");
216 // ...but it must not shadow Vite's own internal middlewares.
217 const viteClient = await request(server, "/@vite/client");
218 expect(viteClient.status).toBe(200);
219 expect(viteClient.text).not.toBe("worker");
220 expect(viteClient.text).not.toBe("framework");
221 } finally {
222 await server.close();
223 }
224 });
225
226 // `@cloudflare/vite-plugin` warns in dev, once imports go quiet, when a
227 // Worker without `nodejs_compat` imports Node.js built-ins.
228 it("warns about Node.js imports without nodejs_compat in dev", async () => {
229 const warnings: Array<string> = [];
230 const logger = vite.createLogger("silent");
231 logger.warn = (message) => void warnings.push(message);
232 const server = await createDevServer(
233 cloudflareVitePlugin({ main: "./node-import-entry.ts", compatibilityDate: "2024-01-01" }),
234 { customLogger: logger },
235 );
236 try {
237 await server.environments.ssr!.transformRequest("/node-import-entry.ts");
238 await vi.waitFor(() => expect(warnings.join("\n")).toContain("Unexpected Node.js imports"), {
239 timeout: 5_000,
240 });
241 expect(warnings.join("\n")).toContain(`"node:fs" imported from "node-import-entry.ts"`);
242 } finally {
243 await server.close();
244 }
245 });
246 });