|
1 | 1 | import { spawn } from "node:child_process" |
2 | 2 |
|
3 | 3 | export type ServerConfig = { |
4 | | - host?: string |
| 4 | + hostname?: string |
5 | 5 | port?: number |
| 6 | + signal?: AbortSignal |
| 7 | + timeout?: number |
6 | 8 | } |
7 | 9 |
|
8 | 10 | export async function createOpencodeServer(config?: ServerConfig) { |
9 | 11 | config = Object.assign( |
10 | 12 | { |
11 | | - host: "127.0.0.1", |
| 13 | + hostname: "127.0.0.1", |
12 | 14 | port: 4096, |
| 15 | + timeout: 5000, |
13 | 16 | }, |
14 | 17 | config ?? {}, |
15 | 18 | ) |
16 | 19 |
|
17 | | - const proc = spawn(`opencode`, [`serve`, `--host=${config.host}`, `--port=${config.port}`]) |
18 | | - const url = `http://${config.host}:${config.port}` |
| 20 | + const proc = spawn(`opencode`, [`servel`, `--hostname=${config.hostname}`, `--port=${config.port}`], { |
| 21 | + signal: config.signal, |
| 22 | + }) |
| 23 | + |
| 24 | + const url = await new Promise<string>((resolve, reject) => { |
| 25 | + const id = setTimeout(() => { |
| 26 | + reject(new Error(`Timeout waiting for server to start after ${config.timeout}ms`)) |
| 27 | + }, config.timeout) |
| 28 | + let output = "" |
| 29 | + proc.stdout?.on("data", (chunk) => { |
| 30 | + output += chunk.toString() |
| 31 | + const lines = output.split("\n") |
| 32 | + for (const line of lines) { |
| 33 | + if (line.startsWith("opencode server listening")) { |
| 34 | + const match = line.match(/on\s+(https?:\/\/[^\s]+)/) |
| 35 | + if (!match) { |
| 36 | + throw new Error(`Failed to parse server url from output: ${line}`) |
| 37 | + } |
| 38 | + clearTimeout(id) |
| 39 | + resolve(match[1]) |
| 40 | + return |
| 41 | + } |
| 42 | + } |
| 43 | + }) |
| 44 | + proc.stderr?.on("data", (chunk) => { |
| 45 | + output += chunk.toString() |
| 46 | + }) |
| 47 | + proc.on("exit", (code) => { |
| 48 | + clearTimeout(id) |
| 49 | + let msg = `Server exited with code ${code}` |
| 50 | + if (output.trim()) { |
| 51 | + msg += `\nServer output: ${output}` |
| 52 | + } |
| 53 | + reject(new Error(msg)) |
| 54 | + }) |
| 55 | + proc.on("error", (error) => { |
| 56 | + clearTimeout(id) |
| 57 | + reject(error) |
| 58 | + }) |
| 59 | + if (config.signal) { |
| 60 | + config.signal.addEventListener("abort", () => { |
| 61 | + clearTimeout(id) |
| 62 | + reject(new Error("Aborted")) |
| 63 | + }) |
| 64 | + } |
| 65 | + }) |
19 | 66 |
|
20 | 67 | return { |
21 | 68 | url, |
|
0 commit comments