| 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( |
| 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. |
| 34 | const 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. |
| 38 | const pagePath = path.join(root, "app", "page.jsx"); |
| 39 | const pageSource = fs.readFileSync(pagePath, "utf8"); |
| 40 | const MARKER = "Next.js on Fly"; |
| 41 | const MARKER_V2 = "Next.js on Fly [dev-v2]"; |
| 42 | |
| 43 | let proc: ReturnType<typeof spawn> | undefined; |
| 44 | let output = ""; |
| 45 | |
| 46 | const 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. */ |
| 55 | const 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. */ |
| 71 | const 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. */ |
| 91 | const outputUrl = () => output.match(/\burl:\s*['"]?(http[^\s'",]+)/)?.[1]; |
| 92 | |
| 93 | afterAll(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 | |
| 124 | test( |
| 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 Fly. The port is |
| 143 | // whatever the framework bound — only the URL captured from the CLI's |
| 144 | // stdout is authoritative. |
| 145 | // Next.js advertises the bind address, so accept either loopback name. |
| 146 | expect(["localhost", "127.0.0.1"]).toContain(new URL(url).hostname); |
| 147 | expect(url).not.toContain("example.invalid"); |
| 148 | |
| 149 | // SSR env parity: GREETING from alchemy.run.ts reaches the dev server. |
| 150 | const home = await (await fetchOk(url)).text(); |
| 151 | expect(home).toContain("Hello from Next.js on Fly!"); |
| 152 | expect(home).toContain(MARKER); |
| 153 | |
| 154 | // App Router API route serves through the dev server. |
| 155 | const hello = (await ( |
| 156 | await fetchOk(new URL("/api/hello", url)) |
| 157 | ).json()) as { hello: string }; |
| 158 | expect(hello).toEqual({ hello: "world" }); |
| 159 | |
| 160 | // Static asset from public/. |
| 161 | const robots = await (await fetchOk(new URL("/robots.txt", url))).text(); |
| 162 | expect(robots).toContain("User-agent:"); |
| 163 | |
| 164 | // ── HOT RELOAD: rewrite the index page with the CLI still running — |
| 165 | // the framework dev server serves the new markup without a deploy ── |
| 166 | fs.writeFileSync(pagePath, pageSource.replace(MARKER, MARKER_V2)); |
| 167 | await pollUntil( |
| 168 | "hot-reloaded page (v2 marker)", |
| 169 | async () => { |
| 170 | try { |
| 171 | const res = await fetch(url); |
| 172 | if (!res.ok) return undefined; |
| 173 | const html = await res.text(); |
| 174 | return html.includes(MARKER_V2) ? true : undefined; |
| 175 | } catch { |
| 176 | return undefined; // mid-reload |
| 177 | } |
| 178 | }, |
| 179 | { tries: 120, delayMs: 500 }, |
| 180 | ); |
| 181 | |
| 182 | // Restore — the swap back is itself a second hot reload and leaves |
| 183 | // the checked-in tree clean. |
| 184 | fs.writeFileSync(pagePath, pageSource); |
| 185 | await pollUntil( |
| 186 | "restored page (v2 marker gone)", |
| 187 | async () => { |
| 188 | try { |
| 189 | const res = await fetch(url); |
| 190 | if (!res.ok) return undefined; |
| 191 | const html = await res.text(); |
| 192 | return html.includes(MARKER_V2) ? undefined : true; |
| 193 | } catch { |
| 194 | return undefined; // mid-reload |
| 195 | } |
| 196 | }, |
| 197 | { tries: 120, delayMs: 500 }, |
| 198 | ); |
| 199 | }, |
| 200 | { timeout: 600_000 }, |
| 201 | ); |