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

main
ts 168 lines 5.49 KB
Raw
1 /**
2 * True `alchemy dev` end-to-end for the TanStack Start site: spawns the
3 * REAL CLI (mirroring examples/aws-dev/test/dev.test.ts), which runs the
4 * Vite dev server as the local `Website.Server` provider — no Railway
5 * Service, no Railway, no S3; the only cloud touch is the state store.
6 *
7 * Coverage:
8 * - stack output → `url` is a local dev-server address (port is
9 * whatever the framework bound — never hard-coded)
10 * - SSR env parity → `/` renders the GREETING declared in alchemy.run.ts
11 * (read via a TanStack Start server function)
12 * - HOT RELOAD → editing src/routes/index.tsx is served by
13 * Vite's HMR without a redeploy
14 */
15 import { afterAll, expect, test } from "bun:test";
16 import { spawn, spawnSync } from "node:child_process";
17 import * as fs from "node:fs";
18 import * as path from "node:path";
19
20 const root = path.resolve(import.meta.dirname, "..");
21 const alchemyBin = path.join(root, "node_modules", "alchemy", "bin", "alchemy.js");
22 const STAGE = "dev-cli-test";
23
24 const pagePath = path.join(root, "src", "routes", "index.tsx");
25 const pageSource = fs.readFileSync(pagePath, "utf8");
26 const MARKER = "Styled with Tailwind CSS";
27 const MARKER_V2 = "Styled with Tailwind CSS [dev-v2]";
28
29 let proc: ReturnType<typeof spawn> | undefined;
30 let output = "";
31
32 const pump = (stream: NodeJS.ReadableStream) => {
33 stream.on("data", (chunk: Buffer) => {
34 const text = chunk.toString();
35 output += text;
36 if (process.env.DEBUG) process.stderr.write(text);
37 });
38 };
39
40 /** Bounded poll for a (possibly async) producer to yield a value. */
41 const pollUntil = async <T>(
42 what: string,
43 f: () => T | undefined | Promise<T | undefined>,
44 { tries = 30, delayMs = 1000 }: { tries?: number; delayMs?: number } = {},
45 ): Promise<T> => {
46 for (let i = 0; i < tries; i++) {
47 const value = await f();
48 if (value !== undefined) return value;
49 await Bun.sleep(delayMs);
50 }
51 throw new Error(
52 `Timed out waiting for ${what}.\n--- alchemy dev output (tail) ---\n${output.slice(-4000)}`,
53 );
54 };
55
56 /** Fetch with retries — the dev server takes a moment to start serving. */
57 const fetchOk = async (
58 url: string | URL,
59 { tries = 30, delayMs = 1000 }: { tries?: number; delayMs?: number } = {},
60 ) => {
61 let last: Response | undefined;
62 for (let i = 0; i < tries; i++) {
63 try {
64 last = await fetch(url);
65 if (last.ok) return last;
66 } catch {
67 // dev server not listening yet
68 }
69 await Bun.sleep(delayMs);
70 }
71 throw new Error(`GET ${url} never returned 2xx (last status: ${last?.status})`);
72 };
73
74 /** Extract the stack-output URL the CLI prints on stdout. */
75 const outputUrl = () => output.match(/\burl:\s*['"]?(http[^\s'",]+)/)?.[1];
76
77 afterAll(async () => {
78 fs.writeFileSync(pagePath, pageSource);
79
80 if (proc?.pid) {
81 const killGroup = (signal: NodeJS.Signals) => {
82 try {
83 process.kill(-proc!.pid!, signal);
84 } catch {
85 // group already gone
86 }
87 };
88 const exited = new Promise((resolve) => proc!.once("exit", resolve));
89 killGroup("SIGINT");
90 await Promise.race([exited, Bun.sleep(15_000)]);
91 if (proc.exitCode === null && proc.signalCode === null) {
92 killGroup("SIGKILL");
93 await Promise.race([exited, Bun.sleep(5_000)]);
94 }
95 }
96 if (!process.env.NO_DESTROY) {
97 spawnSync("bun", [alchemyBin, "destroy", "--stage", STAGE, "--yes"], {
98 cwd: root,
99 stdio: "inherit",
100 timeout: 120_000,
101 });
102 }
103 }, 180_000);
104
105 test(
106 "alchemy dev serves the TanStack Start site locally with hot reload",
107 async () => {
108 proc = spawn("bun", [alchemyBin, "dev", "--stage", STAGE], {
109 cwd: root,
110 detached: true,
111 stdio: ["ignore", "pipe", "pipe"],
112 });
113 pump(proc.stdout!);
114 pump(proc.stderr!);
115
116 const url = await pollUntil("url in stack outputs", outputUrl, {
117 tries: 180,
118 delayMs: 1000,
119 });
120
121 // Dev identity: the framework dev server, not Railway. The port is
122 // whatever the framework bound — only the URL captured from the CLI's
123 // stdout is authoritative.
124 expect(new URL(url).hostname).toBe("localhost");
125 expect(url).not.toContain("example.invalid");
126
127 // SSR env parity: GREETING from alchemy.run.ts reaches the dev server
128 // (read via a TanStack Start server function).
129 const home = await (await fetchOk(url)).text();
130 expect(home).toContain("Hello from TanStack Start on Railway!");
131 expect(home).toContain(MARKER);
132
133 // ── HOT RELOAD: rewrite the index page with the CLI still running —
134 // the framework dev server serves the new markup without a deploy ──
135 fs.writeFileSync(pagePath, pageSource.replace(MARKER, MARKER_V2));
136 await pollUntil(
137 "hot-reloaded page (v2 marker)",
138 async () => {
139 try {
140 const res = await fetch(url);
141 if (!res.ok) return undefined;
142 const html = await res.text();
143 return html.includes(MARKER_V2) ? true : undefined;
144 } catch {
145 return undefined; // mid-reload
146 }
147 },
148 { tries: 120, delayMs: 500 },
149 );
150
151 fs.writeFileSync(pagePath, pageSource);
152 await pollUntil(
153 "restored page (v2 marker gone)",
154 async () => {
155 try {
156 const res = await fetch(url);
157 if (!res.ok) return undefined;
158 const html = await res.text();
159 return html.includes(MARKER_V2) ? undefined : true;
160 } catch {
161 return undefined; // mid-reload
162 }
163 },
164 { tries: 120, delayMs: 500 },
165 );
166 },
167 { timeout: 600_000 },
168 );