Skip to content

armgit / clipy

Public Imported from GitHub
0

The AI-native screen recorder. Record your screen and talk; the people you share it with and your AI agents both get it.

4.7 KB
Raw Blame
import { execFile } from "node:child_process";
import { accessSync, constants, statSync } from "node:fs";
import { delimiter, join } from "node:path";
import type { Platform } from "./types.js";

export function currentPlatform(): Platform {
  const p = process.platform;
  if (p === "darwin" || p === "win32" || p === "linux") return p;
  throw new Error(`@clipy/capture supports macOS, Windows and Linux, not ${p}`);
}

/** What a command returned; `status` is null when it could not run, timed out, or was killed. */
export interface RunResult {
  status: number | null;
  stdout: string;
  stderr: string;
}

export type Runner = (cmd: string, args: string[], env?: NodeJS.ProcessEnv) => Promise<RunResult>;

export function createRunner(timeoutMs = 15_000): Runner {
  return (cmd, args, env = process.env) =>
    new Promise((resolve) => {
      try {
        execFile(
          cmd,
          args,
          { env, encoding: "utf8", timeout: timeoutMs, maxBuffer: 8 * 1024 * 1024, windowsHide: true },
          (error, stdout, stderr) => {
            const code = error ? (error as NodeJS.ErrnoException & { code?: unknown }).code : 0;
            // A non-zero exit still has output worth parsing (ffmpeg -list_devices
            // always exits 1); only a missing binary, timeout, or signal yields null.
            const status = typeof code === "number" ? code : null;
            resolve({ status, stdout: String(stdout ?? ""), stderr: String(stderr ?? "") });
          },
        );
      } catch {
        // Node throws instead of calling back for a .cmd or .bat (EINVAL).
        resolve({ status: null, stdout: "", stderr: "" });
      }
    });
}

export const realRunner: Runner = createRunner();

function windowsPathext(env: NodeJS.ProcessEnv): string[] {
  return (env.PATHEXT ?? ".EXE;.CMD;.BAT;.COM").split(";").filter(Boolean);
}

// Node will not spawn these without a shell.
function isBatchFile(path: string): boolean {
  return /\.(?:cmd|bat)$/i.test(path);
}

/**
 * Look a program up on PATH (and PATHEXT on Windows) without spawning it.
 * `skipBatchFiles` ignores .cmd and .bat files found by adding an extension.
 */
export function findExecutable(
  name: string,
  platform: Platform = currentPlatform(),
  env: NodeJS.ProcessEnv = process.env,
  skipBatchFiles = false,
): string | null {
  const exts = platform === "win32" ? windowsPathext(env) : [""];
  const lower = name.toLowerCase();
  if (name.includes("/") || (platform === "win32" && name.includes("\\"))) {
    if (isExecutable(name, platform)) return name;
    if (platform === "win32") {
      for (const ext of exts) {
        if (lower.endsWith(ext.toLowerCase())) continue;
        const candidate = name + ext;
        if (skipBatchFiles && isBatchFile(candidate)) continue;
        if (isExecutable(candidate, platform)) return candidate;
      }
    }
    return null;
  }
  const path = env.PATH ?? env.Path ?? "";
  const sep = platform === "win32" ? ";" : delimiter;
  for (const entry of path.split(sep)) {
    // Windows PATH entries may be enclosed in double quotes.
    const dir = platform === "win32" ? entry.replace(/^"(.*)"$/, "$1") : entry;
    if (!dir) continue;
    for (const ext of exts) {
      const candidate = join(dir, name + (platform === "win32" && !lower.endsWith(ext.toLowerCase()) ? ext : ""));
      if (skipBatchFiles && platform === "win32" && isBatchFile(candidate)) continue;
      if (isExecutable(candidate, platform)) return candidate;
    }
  }
  return null;
}

function isExecutable(path: string, platform: Platform): boolean {
  try {
    if (!statSync(path).isFile()) return false;
    if (platform !== "win32") accessSync(path, constants.X_OK);
    return true;
  } catch {
    return false;
  }
}

/** ffmpeg, honouring CLIPY_FFMPEG (blank counts as unset). */
export function ffmpegPath(platform: Platform = currentPlatform(), env: NodeJS.ProcessEnv = process.env): string | null {
  const custom = env.CLIPY_FFMPEG?.trim();
  if (custom) return findExecutable(custom, platform, env, true);
  return findExecutable("ffmpeg", platform, env, true);
}

/** ffprobe, honouring CLIPY_FFPROBE (blank counts as unset), else next to ffmpeg, else on PATH. */
export function ffprobePath(platform: Platform = currentPlatform(), env: NodeJS.ProcessEnv = process.env): string | null {
  const custom = env.CLIPY_FFPROBE?.trim();
  if (custom) return findExecutable(custom, platform, env, true);
  const ffmpeg = ffmpegPath(platform, env);
  if (ffmpeg) {
    const sibling = ffmpeg.replace(/ffmpeg(\.exe)?$/i, (_m, ext: string | undefined) => `ffprobe${ext ?? ""}`);
    if (sibling !== ffmpeg && findExecutable(sibling, platform, env)) return sibling;
  }
  return findExecutable("ffprobe", platform, env, true);
}

export function sleep(ms: number): Promise<void> {
  return new Promise((r) => setTimeout(r, ms));
}