jroshell/lib/niri/action-client.ts
2026-06-08 13:03:54 +02:00

38 lines
No EOL
1.3 KiB
TypeScript

import Gio from "gi://Gio";
import GLib from "gi://GLib";
export class NiriActionClient {
private socketPath: string;
constructor() {
this.socketPath = GLib.getenv("NIRI_SOCKET") ?? "";
if (!this.socketPath) throw new Error("NIRI_SOCKET not set");
}
async send(request: any): Promise<any> {
const client = new Gio.SocketClient();
const address = Gio.UnixSocketAddress.new(this.socketPath);
const conn = await new Promise<Gio.SocketConnection>((resolve, reject) => {
client.connect_async(address, null, (src, res) => {
try { resolve(src!.connect_finish(res)); }
catch (e) { reject(e); }
});
});
const ostream = conn.get_output_stream();
const requestStr = JSON.stringify(request) + "\n";
ostream.write_bytes(new GLib.Bytes(requestStr), null);
ostream.flush(null);
const istream = new Gio.DataInputStream({ base_stream: conn.get_input_stream() });
const [line] = await new Promise<[string|null]>((resolve) => {
istream.read_line_async(GLib.PRIORITY_DEFAULT, null, (src, res) => {
const [bytes] = src!.read_line_finish(res);
resolve([bytes ? new TextDecoder().decode(bytes).trim() : null]);
});
});
conn.close(null);
return line ? JSON.parse(line) : null;
}
}