|
| 1 | +import { CliUsageError, printData, rejectArgs, runCliAction, runtimeRequest, takeFlag, type RuntimeApiDeps } from "./runtime-api"; |
| 2 | + |
| 3 | +const USAGE = `Usage: |
| 4 | + ocx companion [show] [--json] |
| 5 | + ocx companion set <key>=<value> [...] [--json] |
| 6 | + ocx companion reset [--json]`; |
| 7 | + |
| 8 | +function parseValue(raw: string): unknown { |
| 9 | + if (raw === "null") return null; |
| 10 | + try { return JSON.parse(raw); } catch { return raw; } |
| 11 | +} |
| 12 | + |
| 13 | +async function show(argv: string[], deps: RuntimeApiDeps): Promise<void> { |
| 14 | + const args = [...argv]; |
| 15 | + const wantsJson = takeFlag(args, "--json"); |
| 16 | + rejectArgs(args, USAGE); |
| 17 | + printData(await runtimeRequest("/api/companion/settings", {}, deps), wantsJson); |
| 18 | +} |
| 19 | + |
| 20 | +async function set(argv: string[], deps: RuntimeApiDeps): Promise<void> { |
| 21 | + const args = [...argv]; |
| 22 | + const wantsJson = takeFlag(args, "--json"); |
| 23 | + if (args.length === 0) throw new CliUsageError("companion set requires key=value assignments", USAGE); |
| 24 | + const patch: Record<string, unknown> = {}; |
| 25 | + for (const assignment of args) { |
| 26 | + const separator = assignment.indexOf("="); |
| 27 | + if (separator <= 0) throw new CliUsageError(`invalid companion setting "${assignment}"; use key=value`, USAGE); |
| 28 | + patch[assignment.slice(0, separator)] = parseValue(assignment.slice(separator + 1)); |
| 29 | + } |
| 30 | + printData(await runtimeRequest("/api/companion/settings", { |
| 31 | + method: "PUT", |
| 32 | + body: JSON.stringify({ settings: patch }), |
| 33 | + }, deps), wantsJson, ["Companion settings saved."]); |
| 34 | +} |
| 35 | + |
| 36 | +async function reset(argv: string[], deps: RuntimeApiDeps): Promise<void> { |
| 37 | + const args = [...argv]; |
| 38 | + const wantsJson = takeFlag(args, "--json"); |
| 39 | + rejectArgs(args, USAGE); |
| 40 | + printData(await runtimeRequest("/api/companion/settings", { |
| 41 | + method: "PUT", |
| 42 | + body: JSON.stringify({ reset: true }), |
| 43 | + }, deps), wantsJson, ["Companion settings reset."]); |
| 44 | +} |
| 45 | + |
| 46 | +export async function handleCompanionCommand(argv: string[], deps: RuntimeApiDeps = {}): Promise<number> { |
| 47 | + return runCliAction(async () => { |
| 48 | + const [sub = "show", ...rest] = argv; |
| 49 | + if (sub === "show") await show(rest, deps); |
| 50 | + else if (sub === "set") await set(rest, deps); |
| 51 | + else if (sub === "reset") await reset(rest, deps); |
| 52 | + else throw new CliUsageError(`unknown companion command ${sub}`, USAGE); |
| 53 | + }); |
| 54 | +} |
| 55 | + |
| 56 | +export const COMPANION_USAGE = USAGE; |
0 commit comments