server.ts 1.8 KB

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