repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

pi/agent/extensions/web/spawn.ts

Raw
File outline
// Shared spawn helper for running external commands

import { spawn } from "node:child_process";

export function spawnToText(cmd: string, args: string[], input?: string): Promise<string> {
  return new Promise((resolve, reject) => {
    const proc = spawn(cmd, args);
    let stdout = "";
    let stderr = "";
    proc.stdout.on("data", (d: Buffer) => (stdout += d));
    proc.stderr.on("data", (d: Buffer) => (stderr += d));
    proc.on("close", (code) => {
      if (code === 0) resolve(stdout);
      else reject(new Error(stderr || `${cmd}: ${code}`));
    });
    proc.on("error", reject);
    if (input !== undefined) {
      proc.stdin.write(input);
      proc.stdin.end();
    }
  });
}

/**
 * Check if a command is available on PATH.
 * Returns null if available, or an install hint string if not.
 */
const availableCommands = new Map<string, string | null>();

export async function checkToolAvailability(
  cmd: string,
  installHint: string,
): Promise<string | null> {
  const cached = availableCommands.get(cmd);
  if (cached !== undefined) return cached;

  try {
    await spawnToText("which", [cmd]);
    availableCommands.set(cmd, null);
    return null;
  } catch {
    availableCommands.set(cmd, installHint);
    return installHint;
  }
}

// Tool install hints
export const TOOL_HINTS = {
  pandoc: "pandoc is not installed. Install with: brew install pandoc / apt install pandoc / conda install pandoc",
  pdftotext: "pdftotext (poppler-utils) is not installed. Install with: brew install poppler / apt install poppler-utils",
  identify: "identify (ImageMagick) is not installed. Install with: brew install imagemagick / apt install imagemagick",
  ffprobe: "ffprobe (ffmpeg) is not installed. Install with: brew install ffmpeg / apt install ffmpeg",
} as const;