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