(options?: ServerOptions)
| 19 | } |
| 20 | |
| 21 | export async function createArcticServer(options?: ServerOptions) { |
| 22 | options = Object.assign( |
| 23 | { |
| 24 | hostname: "127.0.0.1", |
| 25 | port: 4096, |
| 26 | timeout: 5000, |
| 27 | }, |
| 28 | options ?? {}, |
| 29 | ) |
| 30 | |
| 31 | const proc = spawn(`arctic`, [`serve`, `--hostname=${options.hostname}`, `--port=${options.port}`], { |
| 32 | signal: options.signal, |
| 33 | env: { |
| 34 | ...process.env, |
| 35 | ARCTIC_CONFIG_CONTENT: JSON.stringify(options.config ?? {}), |
| 36 | }, |
| 37 | }) |
| 38 | |
| 39 | const url = await new Promise<string>((resolve, reject) => { |
| 40 | const id = setTimeout(() => { |
| 41 | reject(new Error(`Timeout waiting for server to start after ${options.timeout}ms`)) |
| 42 | }, options.timeout) |
| 43 | let output = "" |
| 44 | proc.stdout?.on("data", (chunk) => { |
| 45 | output += chunk.toString() |
| 46 | const lines = output.split("\n") |
| 47 | for (const line of lines) { |
| 48 | if (line.startsWith("arctic server listening")) { |
| 49 | const match = line.match(/on\s+(https?:\/\/[^\s]+)/) |
| 50 | if (!match) { |
| 51 | throw new Error(`Failed to parse server url from output: ${line}`) |
| 52 | } |
| 53 | clearTimeout(id) |
| 54 | resolve(match[1]!) |
| 55 | return |
| 56 | } |
| 57 | } |
| 58 | }) |
| 59 | proc.stderr?.on("data", (chunk) => { |
| 60 | output += chunk.toString() |
| 61 | }) |
| 62 | proc.on("exit", (code) => { |
| 63 | clearTimeout(id) |
| 64 | let msg = `Server exited with code ${code}` |
| 65 | if (output.trim()) { |
| 66 | msg += `\nServer output: ${output}` |
| 67 | } |
| 68 | reject(new Error(msg)) |
| 69 | }) |
| 70 | proc.on("error", (error) => { |
| 71 | clearTimeout(id) |
| 72 | reject(error) |
| 73 | }) |
| 74 | if (options.signal) { |
| 75 | options.signal.addEventListener("abort", () => { |
| 76 | clearTimeout(id) |
| 77 | reject(new Error("Aborted")) |
| 78 | }) |
no test coverage detected