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