| 25 | error?: Error; |
| 26 | |
| 27 | constructor( |
| 28 | private readonly calls: Call[], |
| 29 | private readonly changed: (call: Call, phase: "start" | "output" | "end") => void, |
| 30 | ) { |
| 31 | this.server = createServer(socket => { |
| 32 | let text = ""; |
| 33 | socket.setEncoding("utf8"); |
| 34 | socket.setTimeout(5_000, () => socket.destroy()); |
| 35 | socket.on("error", error => { this.error = error; }); |
| 36 | socket.on("data", chunk => { |
| 37 | text += chunk; |
| 38 | if (text.length > 2 * 1024 * 1024) { |
| 39 | this.error = new Error("Command observer message exceeded 2 MiB"); |
| 40 | socket.destroy(); |
| 41 | return; |
| 42 | } |
| 43 | if (!text.endsWith("\n")) return; |
| 44 | try { |
| 45 | const message = record(JSON.parse(text)); |
| 46 | if (typeof message.id !== "string" || !/^gh:[0-9a-f-]{36}$/.test(message.id)) { |
| 47 | throw new Error("Invalid command observer ID"); |
| 48 | } |
| 49 | if (message.type === "start") { |
| 50 | if (!Array.isArray(message.args) || !message.args.every(arg => typeof arg === "string") |
| 51 | || this.calls.some(call => call.id === message.id)) throw new Error("Invalid observed command"); |
| 52 | this.calls.push({ id: message.id, kind: "gh", arguments: message.args, startedAt: Date.now(), output: [] }); |
| 53 | } else if (message.type === "output") { |
| 54 | const call = this.calls.find(item => item.id === message.id); |
| 55 | if (!call || call.kind !== "gh" || call.endedAt !== undefined || typeof message.text !== "string" |
| 56 | || (message.stream !== "stdout" && message.stream !== "stderr")) throw new Error("Invalid command output"); |
| 57 | if (call.output.reduce((size, chunk) => size + Buffer.byteLength(chunk.text), 0) |
| 58 | + Buffer.byteLength(message.text) > 2 * 1024 * 1024) throw new Error("Observed command output exceeded 2 MiB"); |
| 59 | call.output.push({ stream: message.stream, at: Date.now(), text: message.text }); |
| 60 | } else if (message.type === "end") { |
| 61 | const call = this.calls.find(item => item.id === message.id); |
| 62 | if (!call || call.kind !== "gh" || call.endedAt !== undefined) throw new Error("Invalid command completion"); |
| 63 | call.endedAt = Date.now(); |
| 64 | call.success = message.code === 0; |
| 65 | call.exitCode = typeof message.code === "number" ? message.code : null; |
| 66 | } else throw new Error("Invalid command observer message"); |
| 67 | const observed = this.calls.find(call => call.id === message.id); |
| 68 | if (!observed) throw new Error("Missing observed command"); |
| 69 | this.changed(observed, message.type); |
| 70 | socket.end("ok\n"); |
| 71 | } catch (error) { |
| 72 | this.error = error instanceof Error ? error : new Error(String(error)); |
| 73 | socket.destroy(); |
| 74 | } |
| 75 | }); |
| 76 | }); |
| 77 | this.server.on("error", error => { this.error = error; }); |
| 78 | } |
| 79 | |
| 80 | async listen(path: string): Promise<void> { |
| 81 | await new Promise<void>((resolve, reject) => { |