repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/ui/rpc.ts
RawFile outline
- RpcState line 5
- RpcResponse line 7
- RpcRequest line 16
- ParsedJsonLines line 21
- StartRpcOptions line 26
- RpcClient line 38
- RpcSpawnPlan line 45
- Pending line 51
- parseJsonLines line 57
- startRpc line 69
- handleMessage line 120
- send line 136
- close line 155
- isResponse line 174
- type line 178
- rpcSpawnPlan line 182
- defaultPiBin line 197
import { type ChildProcessWithoutNullStreams, spawn } from "node:child_process";
import { randomUUID } from "node:crypto";
import { once } from "node:events";
export type RpcState = "starting" | "connected" | "slow-start" | "exit";
export type RpcResponse = {
id?: string;
type: "response";
command?: string;
success: boolean;
data?: unknown;
error?: string;
};
export type RpcRequest = Record<string, unknown> & {
id?: string;
type: string;
};
export type ParsedJsonLines = {
messages: unknown[];
rest: string;
};
export type StartRpcOptions = {
sessionPath: string;
cwd: string;
command?: string;
args?: string[];
env?: NodeJS.ProcessEnv;
requestTimeoutMs?: number;
slowStartMs?: number;
onEvent?: (event: unknown) => void;
onState?: (state: RpcState, details?: unknown) => void;
};
export type RpcClient = {
child: ChildProcessWithoutNullStreams;
send(request: RpcRequest): Promise<RpcResponse>;
stderr(): string;
close(reason: string): Promise<void>;
};
export type RpcSpawnPlan = {
command: string;
args: string[];
windowsHide?: boolean;
};
type Pending = {
resolve(response: RpcResponse): void;
reject(error: Error): void;
timer: NodeJS.Timeout;
};
export function parseJsonLines(input: string): ParsedJsonLines {
const messages: unknown[] = [];
const parts = input.split("\n");
const rest = parts.pop() ?? "";
for (const raw of parts) {
const line = raw.endsWith("\r") ? raw.slice(0, -1) : raw;
if (!line) continue;
messages.push(JSON.parse(line));
}
return { messages, rest };
}
export function startRpc(options: StartRpcOptions): RpcClient {
const command =
options.command ?? process.env.PI_UI_RPC_BIN ?? defaultPiBin();
const args = options.args ?? [
"--mode",
"rpc",
"--session",
options.sessionPath,
];
const spawnPlan = rpcSpawnPlan(command, args);
const child = spawn(spawnPlan.command, spawnPlan.args, {
cwd: options.cwd,
env: { ...process.env, ...options.env },
stdio: "pipe",
windowsHide: spawnPlan.windowsHide,
});
const pending = new Map<string, Pending>();
const stderrChunks: string[] = [];
let stdoutRest = "";
let closed = false;
let connected = false;
const timeoutMs = options.requestTimeoutMs ?? 30_000;
const slowTimer = setTimeout(() => {
if (!connected && !closed) options.onState?.("slow-start");
}, options.slowStartMs ?? 8_000);
child.stdout.on("data", (chunk) => {
const parsed = parseJsonLines(stdoutRest + String(chunk));
stdoutRest = parsed.rest;
for (const message of parsed.messages) handleMessage(message);
});
child.stderr.on("data", (chunk) => {
stderrChunks.push(String(chunk));
});
child.once("spawn", () => options.onState?.("starting"));
child.once("exit", (code, signal) => {
closed = true;
clearTimeout(slowTimer);
const error = new Error(
`RPC process exited: code=${code ?? "null"} signal=${signal ?? "null"}`,
);
for (const item of pending.values()) {
clearTimeout(item.timer);
item.reject(error);
}
pending.clear();
options.onState?.("exit", { code, signal });
});
function handleMessage(message: unknown): void {
connected = true;
options.onState?.("connected");
if (isResponse(message) && message.id && pending.has(message.id)) {
const item = pending.get(message.id);
if (!item) return;
pending.delete(message.id);
clearTimeout(item.timer);
item.resolve(message);
return;
}
options.onEvent?.(message);
}
return {
child,
send(request) {
if (closed) return Promise.reject(new Error("RPC process is closed"));
const id = request.id ?? randomUUID();
const payload = { ...request, id };
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
pending.delete(id);
reject(new Error(`RPC request timed out: ${request.type}`));
}, timeoutMs);
pending.set(id, { resolve, reject, timer });
child.stdin.write(`${JSON.stringify(payload)}\n`, (error) => {
if (!error) return;
pending.delete(id);
clearTimeout(timer);
reject(error);
});
});
},
stderr: () => stderrChunks.join(""),
async close(reason) {
void reason;
if (closed) return;
closed = true;
clearTimeout(slowTimer);
for (const item of pending.values()) {
clearTimeout(item.timer);
item.reject(new Error("RPC process closed"));
}
pending.clear();
child.kill();
await Promise.race([
once(child, "exit"),
new Promise((resolve) => setTimeout(resolve, 1000)),
]);
},
};
}
function isResponse(value: unknown): value is RpcResponse {
return (
!!value &&
typeof value === "object" &&
(value as { type?: unknown }).type === "response"
);
}
export function rpcSpawnPlan(
command: string,
args: string[],
platform: NodeJS.Platform = process.platform,
): RpcSpawnPlan {
if (platform === "win32" && command.toLowerCase().endsWith(".cmd")) {
return {
command: "cmd.exe",
args: ["/d", "/s", "/c", command, ...args],
windowsHide: true,
};
}
return { command, args, windowsHide: platform === "win32" };
}
function defaultPiBin(): string {
return process.platform === "win32" ? "pi.cmd" : "pi";
}