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

main
ts 229 lines 7.49 KB
Raw
1 import { spawn, spawnSync, type ChildProcess } from "node:child_process";
2 import * as path from "node:path";
3
4 export type PollOptions = {
5 readonly tries?: number;
6 readonly delayMs?: number;
7 };
8
9 export const pollUntil = async <T>(
10 what: string,
11 effect: () => T | undefined | Promise<T | undefined>,
12 options: PollOptions & {
13 readonly diagnostics?: () => string;
14 /**
15 * Returns a reason to give up early (e.g. "the process exited"), or
16 * `undefined` to keep polling. Checked after every unsuccessful attempt so
17 * a dead subject fails in one tick instead of burning the whole budget.
18 */
19 readonly abandonIf?: () => string | undefined;
20 } = {},
21 ): Promise<T> => {
22 const { tries = 30, delayMs = 1_000, diagnostics, abandonIf } = options;
23 for (let attempt = 0; attempt < tries; attempt++) {
24 const value = await effect();
25 if (value !== undefined) return value;
26 const reason = abandonIf?.();
27 if (reason !== undefined) {
28 const detail = diagnostics?.();
29 throw new Error(`Gave up waiting for ${what}: ${reason}.${detail ? `\n${detail}` : ""}`);
30 }
31 await Bun.sleep(delayMs);
32 }
33 const detail = diagnostics?.();
34 throw new Error(`Timed out waiting for ${what}.${detail ? `\n${detail}` : ""}`);
35 };
36
37 export function fetchOk(url: string | URL, options?: PollOptions): Promise<Response>;
38 export function fetchOk(
39 url: string | URL,
40 init?: RequestInit,
41 options?: PollOptions,
42 ): Promise<Response>;
43 export async function fetchOk(
44 url: string | URL,
45 initOrOptions: RequestInit | PollOptions = {},
46 explicitOptions?: PollOptions,
47 ): Promise<Response> {
48 const optionsOnly =
49 explicitOptions === undefined && ("tries" in initOrOptions || "delayMs" in initOrOptions);
50 const init = optionsOnly ? undefined : (initOrOptions as RequestInit);
51 const options = optionsOnly ? (initOrOptions as PollOptions) : (explicitOptions ?? {});
52 const { tries = 20, delayMs = 500 } = options;
53 let last: Response | undefined;
54 for (let attempt = 0; attempt < tries; attempt++) {
55 try {
56 last = await fetch(url, init);
57 if (last.ok) return last;
58 } catch {
59 // The dev endpoint may not be listening yet.
60 }
61 await Bun.sleep(delayMs);
62 }
63 throw new Error(
64 `${init?.method ?? "GET"} ${url} never returned 2xx (last status: ${last?.status})`,
65 );
66 }
67
68 export type DevCliOptions = {
69 readonly root: string;
70 readonly stage?: string;
71 readonly alchemyBin?: string;
72 readonly env?: NodeJS.ProcessEnv;
73 };
74
75 export const parseOutputUrl = (output: string, key: string): string | undefined => {
76 const escaped = key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
77 return output.match(
78 new RegExp(`\\b${escaped}(?:\\s*:\\s*|\\s+)['"]?(http[^\\s'",]+)['"]?(?=[\\s,}])`),
79 )?.[1];
80 };
81
82 export const parseOutputValue = (output: string, key: string): string | undefined => {
83 const escaped = key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
84 return output.match(new RegExp(`\\b${escaped}(?:\\s*:\\s*|\\s+)['"]?([^\\s'",]+)`))?.[1];
85 };
86
87 /** Owns a real `alchemy dev` child and its complete detached process group. */
88 export class DevCli {
89 readonly root: string;
90 readonly stage: string;
91 readonly alchemyBin: string;
92 readonly env: NodeJS.ProcessEnv;
93 #process: ReturnType<typeof spawn> | undefined;
94 #output = "";
95
96 constructor(options: DevCliOptions) {
97 this.root = options.root;
98 this.stage = options.stage ?? "dev-cli-test";
99 this.alchemyBin =
100 options.alchemyBin ?? path.join(this.root, "node_modules", "alchemy", "bin", "alchemy.js");
101 this.env = { ...process.env, ...options.env };
102 }
103
104 get output(): string {
105 return this.#output;
106 }
107
108 get outputTail(): string {
109 return `--- alchemy dev output (tail) ---\n${this.#output.slice(-4_000)}`;
110 }
111
112 start(): void {
113 if (this.#process !== undefined) throw new Error("alchemy dev is running");
114 const child = spawn("bun", [this.alchemyBin, "dev", "--stage", this.stage], {
115 cwd: this.root,
116 detached: true,
117 env: this.env,
118 stdio: ["ignore", "pipe", "pipe"],
119 });
120 this.#process = child;
121 forwardSignals(child);
122 const capture = (chunk: Buffer) => {
123 const text = chunk.toString();
124 this.#output += text;
125 if (process.env.DEBUG) process.stderr.write(text);
126 };
127 child.stdout.on("data", capture);
128 child.stderr.on("data", capture);
129 }
130
131 outputUrl(key: string): string | undefined {
132 return parseOutputUrl(this.#output, key);
133 }
134
135 outputValue(key: string): string | undefined {
136 return parseOutputValue(this.#output, key);
137 }
138
139 pollUntil<T>(
140 what: string,
141 effect: () => T | undefined | Promise<T | undefined>,
142 options: PollOptions = {},
143 ): Promise<T> {
144 return pollUntil(what, effect, {
145 ...options,
146 diagnostics: () => this.outputTail,
147 // A dev child that died (crash, failed apply) never produces what we're
148 // waiting for — fail immediately with its output instead of sitting
149 // through the full poll budget.
150 abandonIf: () => {
151 const child = this.#process;
152 if (child === undefined) return "alchemy dev is not running";
153 if (child.exitCode !== null) {
154 return `alchemy dev exited with code ${child.exitCode}`;
155 }
156 if (child.signalCode !== null) {
157 return `alchemy dev was killed by ${child.signalCode}`;
158 }
159 return undefined;
160 },
161 });
162 }
163
164 outputUrlWhenReady(key: string, options?: PollOptions): Promise<string> {
165 return this.pollUntil(`${key} url in stack outputs`, () => this.outputUrl(key), options);
166 }
167
168 async stop(): Promise<void> {
169 const child = this.#process;
170 if (child?.pid === undefined) return;
171 if (child.exitCode !== null || child.signalCode !== null) {
172 this.#process = undefined;
173 return;
174 }
175 const killGroup = (signal: NodeJS.Signals) => {
176 try {
177 process.kill(-child.pid!, signal);
178 } catch {
179 // The group has already exited.
180 }
181 };
182 const exited = new Promise<void>((resolve) => child.once("exit", () => resolve()));
183 killGroup("SIGINT");
184 await Promise.race([exited, Bun.sleep(15_000)]);
185 if (child.exitCode === null && child.signalCode === null) {
186 killGroup("SIGKILL");
187 await Promise.race([exited, Bun.sleep(5_000)]);
188 }
189 this.#process = undefined;
190 }
191
192 destroy(options: { readonly timeout?: number } = {}): void {
193 const result = spawnSync("bun", [this.alchemyBin, "destroy", "--stage", this.stage, "--yes"], {
194 cwd: this.root,
195 env: this.env,
196 stdio: "inherit",
197 timeout: options.timeout ?? 120_000,
198 });
199 if (result.error !== undefined) throw result.error;
200 if (result.status !== 0) {
201 throw new Error(`alchemy destroy exited ${result.status ?? "by signal"}`);
202 }
203 }
204 }
205
206 /** Forward Ctrl-C to a detached CLI and let it finish its own cleanup. */
207 export const forwardSignals = (child: ChildProcess): void => {
208 let interrupted: NodeJS.Signals | undefined;
209 const forward = (signal: NodeJS.Signals) => {
210 if (interrupted !== undefined) return;
211 interrupted = signal;
212 child.kill(signal);
213 };
214 const removeListeners = () => {
215 process.off("SIGINT", forward);
216 process.off("SIGTERM", forward);
217 };
218 process.on("SIGINT", forward);
219 process.on("SIGTERM", forward);
220 child.once("error", removeListeners);
221 child.once("exit", () => {
222 removeListeners();
223 // Bun skips afterAll on Ctrl-C. Exit only after the CLI has shut down,
224 // without resuming the interrupted tests or starting the next command.
225 if (interrupted !== undefined) {
226 process.exit(interrupted === "SIGINT" ? 130 : 143);
227 }
228 });
229 };