@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 191 lines 6.65 KB
Raw
1 /**
2 * True `alchemy dev` end-to-end for the Next.js site: spawns the REAL CLI
3 * (mirroring examples/aws-dev/test/dev.test.ts), which runs `next dev` as
4 * the local `Website.Server` provider — no Fly Machine, no Fly, no S3;
5 * 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 * - API route → `/api/hello` serves the route handler
12 * - static assets → `/robots.txt` from public/
13 * - HOT RELOAD → editing app/page.jsx is served by Next's HMR
14 * without a redeploy
15 */
16 import { afterAll, expect, test } from "bun:test";
17 import { spawn, spawnSync } from "node:child_process";
18 import * as fs from "node:fs";
19 import * as path from "node:path";
20
21 const root = path.resolve(import.meta.dirname, "..");
22 // Spawn the CLI entry directly (not through `bun run` / the cli.js
23 // launcher) so signals hit the actual CLI process, whose scope teardown
24 // kills the dev server and the provider sidecars.
25 const alchemyBin = path.join(root, "node_modules", "alchemy", "bin", "alchemy.js");
26 // Isolated stage so this suite never fights integ.test.ts (same stack
27 // name) over state rows.
28 const STAGE = "dev-cli-test";
29
30 // Hot-reload surface: the SSR index page. The test rewrites it in place
31 // with the CLI running, then restores it.
32 const pagePath = path.join(root, "app", "page.jsx");
33 const pageSource = fs.readFileSync(pagePath, "utf8");
34 const MARKER = "Next.js on Fly";
35 const MARKER_V2 = "Next.js on Fly [dev-v2]";
36
37 let proc: ReturnType<typeof spawn> | undefined;
38 let output = "";
39
40 const pump = (stream: NodeJS.ReadableStream) => {
41 stream.on("data", (chunk: Buffer) => {
42 const text = chunk.toString();
43 output += text;
44 if (process.env.DEBUG) process.stderr.write(text);
45 });
46 };
47
48 /** Bounded poll for a (possibly async) producer to yield a value. */
49 const pollUntil = async <T>(
50 what: string,
51 f: () => T | undefined | Promise<T | undefined>,
52 { tries = 30, delayMs = 1000 }: { tries?: number; delayMs?: number } = {},
53 ): Promise<T> => {
54 for (let i = 0; i < tries; i++) {
55 const value = await f();
56 if (value !== undefined) return value;
57 await Bun.sleep(delayMs);
58 }
59 throw new Error(
60 `Timed out waiting for ${what}.\n--- alchemy dev output (tail) ---\n${output.slice(-4000)}`,
61 );
62 };
63
64 /** Fetch with retries — the dev server takes a moment to start serving. */
65 const fetchOk = async (
66 url: string | URL,
67 { tries = 30, delayMs = 1000 }: { tries?: number; delayMs?: number } = {},
68 ) => {
69 let last: Response | undefined;
70 for (let i = 0; i < tries; i++) {
71 try {
72 last = await fetch(url);
73 if (last.ok) return last;
74 } catch {
75 // dev server not listening yet
76 }
77 await Bun.sleep(delayMs);
78 }
79 throw new Error(`GET ${url} never returned 2xx (last status: ${last?.status})`);
80 };
81
82 /** Extract the stack-output URL the CLI prints on stdout. */
83 const outputUrl = () => output.match(/\burl:\s*['"]?(http[^\s'",]+)/)?.[1];
84
85 afterAll(async () => {
86 // Always leave the repo tree clean, even on a mid-reload failure.
87 fs.writeFileSync(pagePath, pageSource);
88
89 if (proc?.pid) {
90 // Ctrl-C semantics: signal the whole PROCESS GROUP (the CLI, its
91 // `--watch` exec child, and the provider sidecars).
92 const killGroup = (signal: NodeJS.Signals) => {
93 try {
94 process.kill(-proc!.pid!, signal);
95 } catch {
96 // group already gone
97 }
98 };
99 const exited = new Promise((resolve) => proc!.once("exit", resolve));
100 killGroup("SIGINT");
101 await Promise.race([exited, Bun.sleep(15_000)]);
102 if (proc.exitCode === null && proc.signalCode === null) {
103 killGroup("SIGKILL");
104 await Promise.race([exited, Bun.sleep(5_000)]);
105 }
106 }
107 if (!process.env.NO_DESTROY) {
108 spawnSync("bun", [alchemyBin, "destroy", "--stage", STAGE, "--yes"], {
109 cwd: root,
110 stdio: "inherit",
111 timeout: 120_000,
112 });
113 }
114 }, 180_000);
115
116 test(
117 "alchemy dev serves the Next.js site locally with hot reload",
118 async () => {
119 proc = spawn("bun", [alchemyBin, "dev", "--stage", STAGE], {
120 cwd: root,
121 // Own process group, so teardown can deliver Ctrl-C to the whole
122 // tree the way a terminal would.
123 detached: true,
124 stdio: ["ignore", "pipe", "pipe"],
125 });
126 pump(proc.stdout!);
127 pump(proc.stderr!);
128
129 const url = await pollUntil("url in stack outputs", outputUrl, {
130 tries: 180,
131 delayMs: 1000,
132 });
133
134 // Dev identity: the framework dev server, not Fly. The port is
135 // whatever the framework bound — only the URL captured from the CLI's
136 // stdout is authoritative.
137 // Next.js advertises the bind address, so accept either loopback name.
138 expect(["localhost", "127.0.0.1"]).toContain(new URL(url).hostname);
139 expect(url).not.toContain("example.invalid");
140
141 // SSR env parity: GREETING from alchemy.run.ts reaches the dev server.
142 const home = await (await fetchOk(url)).text();
143 expect(home).toContain("Hello from Next.js on Fly!");
144 expect(home).toContain(MARKER);
145
146 // App Router API route serves through the dev server.
147 const hello = (await (await fetchOk(new URL("/api/hello", url))).json()) as { hello: string };
148 expect(hello).toEqual({ hello: "world" });
149
150 // Static asset from public/.
151 const robots = await (await fetchOk(new URL("/robots.txt", url))).text();
152 expect(robots).toContain("User-agent:");
153
154 // ── HOT RELOAD: rewrite the index page with the CLI still running —
155 // the framework dev server serves the new markup without a deploy ──
156 fs.writeFileSync(pagePath, pageSource.replace(MARKER, MARKER_V2));
157 await pollUntil(
158 "hot-reloaded page (v2 marker)",
159 async () => {
160 try {
161 const res = await fetch(url);
162 if (!res.ok) return undefined;
163 const html = await res.text();
164 return html.includes(MARKER_V2) ? true : undefined;
165 } catch {
166 return undefined; // mid-reload
167 }
168 },
169 { tries: 120, delayMs: 500 },
170 );
171
172 // Restore — the swap back is itself a second hot reload and leaves
173 // the checked-in tree clean.
174 fs.writeFileSync(pagePath, pageSource);
175 await pollUntil(
176 "restored page (v2 marker gone)",
177 async () => {
178 try {
179 const res = await fetch(url);
180 if (!res.ok) return undefined;
181 const html = await res.text();
182 return html.includes(MARKER_V2) ? undefined : true;
183 } catch {
184 return undefined; // mid-reload
185 }
186 },
187 { tries: 120, delayMs: 500 },
188 );
189 },
190 { timeout: 600_000 },
191 );