Skip to content

armgit / Pake

Public Imported from GitHub
0

Turn any website into a lightweight desktop app with one command, on macOS, Windows and Linux.

2.3 KB
Raw Blame
import chalk from 'chalk';
import log from 'loglevel';

/**
 * Machine-readable output support (`--json`).
 *
 * In machine mode stdout carries exactly one JSON result object; every log,
 * spinner, and subprocess output is routed to stderr so automation and AI
 * agents can `JSON.parse(stdout)` without scraping terminal text.
 */

export type PakeErrorCode =
  'INVALID_INPUT' | 'ENV_MISSING' | 'BUILD_FAILED' | 'NETWORK' | 'UNEXPECTED';

// Stable exit-code contract: 0 success, 2 invalid input, 3 build/network
// failure, 4 missing environment, 1 unexpected. Documented in cli-usage docs.
export const ERROR_EXIT_CODES: Record<PakeErrorCode, number> = {
  INVALID_INPUT: 2,
  BUILD_FAILED: 3,
  NETWORK: 3,
  ENV_MISSING: 4,
  UNEXPECTED: 1,
};

export interface BuildArtifact {
  path: string;
  sizeBytes: number;
  format: string;
}

export interface PakeJsonResult {
  ok: boolean;
  name: string | null;
  platform: NodeJS.Platform;
  arch: string | null;
  outputs: BuildArtifact[];
  warnings: string[];
  error: {
    code: PakeErrorCode;
    message: string;
    hint: string | null;
  } | null;
}

let machineMode = false;
const capturedWarnings: string[] = [];

/**
 * Route all loglevel output to stderr, capture warnings for the final JSON
 * result, and strip ANSI colors. Must be called before any logging happens.
 */
export function enableMachineMode(): void {
  if (machineMode) return;
  machineMode = true;
  chalk.level = 0;
  log.methodFactory = (methodName) => {
    return (...args: unknown[]) => {
      if (methodName === 'warn') {
        capturedWarnings.push(args.map(String).join(' '));
      }
      console.error(...args);
    };
  };
  // Rebuild logging methods with the new factory.
  log.setLevel(log.getLevel());
}

export function isMachineMode(): boolean {
  return machineMode;
}

export function getCapturedWarnings(): string[] {
  return [...capturedWarnings];
}

/**
 * Whether Pake may prompt the user. False in machine mode, without a TTY,
 * or inside CI, where prompts would hang or produce garbage.
 */
export function isInteractive(): boolean {
  return (
    !machineMode &&
    Boolean(process.stdin.isTTY) &&
    Boolean(process.stdout.isTTY) &&
    !process.env.CI &&
    !process.env.GITHUB_ACTIONS
  );
}

export function printJsonResult(result: PakeJsonResult): void {
  process.stdout.write(`${JSON.stringify(result)}\n`);
}