|
| 1 | +import { type ChildProcessWithoutNullStreams, spawn } from "node:child_process"; |
| 2 | +import { createInterface, type Interface } from "node:readline"; |
| 3 | +import type { RuntimeEnv } from "../../../src/runtime.js"; |
| 4 | +import { resolveUserPath } from "../../../src/utils.js"; |
| 5 | +import { DEFAULT_IMESSAGE_PROBE_TIMEOUT_MS } from "./constants.js"; |
| 6 | + |
| 7 | +export type IMessageRpcError = { |
| 8 | + code?: number; |
| 9 | + message?: string; |
| 10 | + data?: unknown; |
| 11 | +}; |
| 12 | + |
| 13 | +export type IMessageRpcResponse<T> = { |
| 14 | + jsonrpc?: string; |
| 15 | + id?: string | number | null; |
| 16 | + result?: T; |
| 17 | + error?: IMessageRpcError; |
| 18 | + method?: string; |
| 19 | + params?: unknown; |
| 20 | +}; |
| 21 | + |
| 22 | +export type IMessageRpcNotification = { |
| 23 | + method: string; |
| 24 | + params?: unknown; |
| 25 | +}; |
| 26 | + |
| 27 | +export type IMessageRpcClientOptions = { |
| 28 | + cliPath?: string; |
| 29 | + dbPath?: string; |
| 30 | + runtime?: RuntimeEnv; |
| 31 | + onNotification?: (msg: IMessageRpcNotification) => void; |
| 32 | +}; |
| 33 | + |
| 34 | +type PendingRequest = { |
| 35 | + resolve: (value: unknown) => void; |
| 36 | + reject: (error: Error) => void; |
| 37 | + timer?: NodeJS.Timeout; |
| 38 | +}; |
| 39 | + |
| 40 | +function isTestEnv(): boolean { |
| 41 | + if (process.env.NODE_ENV === "test") { |
| 42 | + return true; |
| 43 | + } |
| 44 | + const vitest = process.env.VITEST?.trim().toLowerCase(); |
| 45 | + return Boolean(vitest); |
| 46 | +} |
| 47 | + |
| 48 | +export class IMessageRpcClient { |
| 49 | + private readonly cliPath: string; |
| 50 | + private readonly dbPath?: string; |
| 51 | + private readonly runtime?: RuntimeEnv; |
| 52 | + private readonly onNotification?: (msg: IMessageRpcNotification) => void; |
| 53 | + private readonly pending = new Map<string, PendingRequest>(); |
| 54 | + private readonly closed: Promise<void>; |
| 55 | + private closedResolve: (() => void) | null = null; |
| 56 | + private child: ChildProcessWithoutNullStreams | null = null; |
| 57 | + private reader: Interface | null = null; |
| 58 | + private nextId = 1; |
| 59 | + |
| 60 | + constructor(opts: IMessageRpcClientOptions = {}) { |
| 61 | + this.cliPath = opts.cliPath?.trim() || "imsg"; |
| 62 | + this.dbPath = opts.dbPath?.trim() ? resolveUserPath(opts.dbPath) : undefined; |
| 63 | + this.runtime = opts.runtime; |
| 64 | + this.onNotification = opts.onNotification; |
| 65 | + this.closed = new Promise((resolve) => { |
| 66 | + this.closedResolve = resolve; |
| 67 | + }); |
| 68 | + } |
| 69 | + |
| 70 | + async start(): Promise<void> { |
| 71 | + if (this.child) { |
| 72 | + return; |
| 73 | + } |
| 74 | + if (isTestEnv()) { |
| 75 | + throw new Error("Refusing to start imsg rpc in test environment; mock iMessage RPC client"); |
| 76 | + } |
| 77 | + const args = ["rpc"]; |
| 78 | + if (this.dbPath) { |
| 79 | + args.push("--db", this.dbPath); |
| 80 | + } |
| 81 | + const child = spawn(this.cliPath, args, { |
| 82 | + stdio: ["pipe", "pipe", "pipe"], |
| 83 | + }); |
| 84 | + this.child = child; |
| 85 | + this.reader = createInterface({ input: child.stdout }); |
| 86 | + |
| 87 | + this.reader.on("line", (line) => { |
| 88 | + const trimmed = line.trim(); |
| 89 | + if (!trimmed) { |
| 90 | + return; |
| 91 | + } |
| 92 | + this.handleLine(trimmed); |
| 93 | + }); |
| 94 | + |
| 95 | + child.stderr?.on("data", (chunk) => { |
| 96 | + const lines = chunk.toString().split(/\r?\n/); |
| 97 | + for (const line of lines) { |
| 98 | + if (!line.trim()) { |
| 99 | + continue; |
| 100 | + } |
| 101 | + this.runtime?.error?.(`imsg rpc: ${line.trim()}`); |
| 102 | + } |
| 103 | + }); |
| 104 | + |
| 105 | + child.on("error", (err) => { |
| 106 | + this.failAll(err instanceof Error ? err : new Error(String(err))); |
| 107 | + this.closedResolve?.(); |
| 108 | + }); |
| 109 | + |
| 110 | + child.on("close", (code, signal) => { |
| 111 | + if (code !== 0 && code !== null) { |
| 112 | + const reason = signal ? `signal ${signal}` : `code ${code}`; |
| 113 | + this.failAll(new Error(`imsg rpc exited (${reason})`)); |
| 114 | + } else { |
| 115 | + this.failAll(new Error("imsg rpc closed")); |
| 116 | + } |
| 117 | + this.closedResolve?.(); |
| 118 | + }); |
| 119 | + } |
| 120 | + |
| 121 | + async stop(): Promise<void> { |
| 122 | + if (!this.child) { |
| 123 | + return; |
| 124 | + } |
| 125 | + this.reader?.close(); |
| 126 | + this.reader = null; |
| 127 | + this.child.stdin?.end(); |
| 128 | + const child = this.child; |
| 129 | + this.child = null; |
| 130 | + |
| 131 | + await Promise.race([ |
| 132 | + this.closed, |
| 133 | + new Promise<void>((resolve) => { |
| 134 | + setTimeout(() => { |
| 135 | + if (!child.killed) { |
| 136 | + child.kill("SIGTERM"); |
| 137 | + } |
| 138 | + resolve(); |
| 139 | + }, 500); |
| 140 | + }), |
| 141 | + ]); |
| 142 | + } |
| 143 | + |
| 144 | + async waitForClose(): Promise<void> { |
| 145 | + await this.closed; |
| 146 | + } |
| 147 | + |
| 148 | + async request<T = unknown>( |
| 149 | + method: string, |
| 150 | + params?: Record<string, unknown>, |
| 151 | + opts?: { timeoutMs?: number }, |
| 152 | + ): Promise<T> { |
| 153 | + if (!this.child || !this.child.stdin) { |
| 154 | + throw new Error("imsg rpc not running"); |
| 155 | + } |
| 156 | + const id = this.nextId++; |
| 157 | + const payload = { |
| 158 | + jsonrpc: "2.0", |
| 159 | + id, |
| 160 | + method, |
| 161 | + params: params ?? {}, |
| 162 | + }; |
| 163 | + const line = `${JSON.stringify(payload)}\n`; |
| 164 | + const timeoutMs = opts?.timeoutMs ?? DEFAULT_IMESSAGE_PROBE_TIMEOUT_MS; |
| 165 | + |
| 166 | + const response = new Promise<T>((resolve, reject) => { |
| 167 | + const key = String(id); |
| 168 | + const timer = |
| 169 | + timeoutMs > 0 |
| 170 | + ? setTimeout(() => { |
| 171 | + this.pending.delete(key); |
| 172 | + reject(new Error(`imsg rpc timeout (${method})`)); |
| 173 | + }, timeoutMs) |
| 174 | + : undefined; |
| 175 | + this.pending.set(key, { |
| 176 | + resolve: (value) => resolve(value as T), |
| 177 | + reject, |
| 178 | + timer, |
| 179 | + }); |
| 180 | + }); |
| 181 | + |
| 182 | + this.child.stdin.write(line); |
| 183 | + return await response; |
| 184 | + } |
| 185 | + |
| 186 | + private handleLine(line: string) { |
| 187 | + let parsed: IMessageRpcResponse<unknown>; |
| 188 | + try { |
| 189 | + parsed = JSON.parse(line) as IMessageRpcResponse<unknown>; |
| 190 | + } catch (err) { |
| 191 | + const detail = err instanceof Error ? err.message : String(err); |
| 192 | + this.runtime?.error?.(`imsg rpc: failed to parse ${line}: ${detail}`); |
| 193 | + return; |
| 194 | + } |
| 195 | + |
| 196 | + if (parsed.id !== undefined && parsed.id !== null) { |
| 197 | + const key = String(parsed.id); |
| 198 | + const pending = this.pending.get(key); |
| 199 | + if (!pending) { |
| 200 | + return; |
| 201 | + } |
| 202 | + if (pending.timer) { |
| 203 | + clearTimeout(pending.timer); |
| 204 | + } |
| 205 | + this.pending.delete(key); |
| 206 | + |
| 207 | + if (parsed.error) { |
| 208 | + const baseMessage = parsed.error.message ?? "imsg rpc error"; |
| 209 | + const details = parsed.error.data; |
| 210 | + const code = parsed.error.code; |
| 211 | + const suffixes = [] as string[]; |
| 212 | + if (typeof code === "number") { |
| 213 | + suffixes.push(`code=${code}`); |
| 214 | + } |
| 215 | + if (details !== undefined) { |
| 216 | + const detailText = |
| 217 | + typeof details === "string" ? details : JSON.stringify(details, null, 2); |
| 218 | + if (detailText) { |
| 219 | + suffixes.push(detailText); |
| 220 | + } |
| 221 | + } |
| 222 | + const msg = suffixes.length > 0 ? `${baseMessage}: ${suffixes.join(" ")}` : baseMessage; |
| 223 | + pending.reject(new Error(msg)); |
| 224 | + return; |
| 225 | + } |
| 226 | + pending.resolve(parsed.result); |
| 227 | + return; |
| 228 | + } |
| 229 | + |
| 230 | + if (parsed.method) { |
| 231 | + this.onNotification?.({ |
| 232 | + method: parsed.method, |
| 233 | + params: parsed.params, |
| 234 | + }); |
| 235 | + } |
| 236 | + } |
| 237 | + |
| 238 | + private failAll(err: Error) { |
| 239 | + for (const [key, pending] of this.pending.entries()) { |
| 240 | + if (pending.timer) { |
| 241 | + clearTimeout(pending.timer); |
| 242 | + } |
| 243 | + pending.reject(err); |
| 244 | + this.pending.delete(key); |
| 245 | + } |
| 246 | + } |
| 247 | +} |
| 248 | + |
| 249 | +export async function createIMessageRpcClient( |
| 250 | + opts: IMessageRpcClientOptions = {}, |
| 251 | +): Promise<IMessageRpcClient> { |
| 252 | + const client = new IMessageRpcClient(opts); |
| 253 | + await client.start(); |
| 254 | + return client; |
| 255 | +} |
0 commit comments