/** * Global configuration for HAPI CLI * * Centralizes all configuration including environment variables and paths * Environment files should be loaded using Node's --env-file flag */ import { existsSync, mkdirSync } from 'node:fs' import { homedir } from 'node:os' import { join } from 'node:path' import packageJson from '../package.json' import { getCliArgs } from '@/utils/cliArgs' export function normalizeExtraHeaders( value: unknown, source: string, warn: (message: string) => void = console.warn ): Record { if (!value || typeof value !== 'object' || Array.isArray(value)) { warn(`[WARN] ${source} must be a JSON object. Ignoring value.`) return {} } const entries = Object.entries(value) const headers = Object.fromEntries( entries.filter((entry): entry is [string, string] => typeof entry[1] === 'string') ) if (Object.keys(headers).length !== entries.length) { warn(`[WARN] ${source} only supports string header values. Ignoring non-string entries.`) } return headers } export function parseExtraHeaders(raw: string | undefined, warn: (message: string) => void = console.warn): Record { if (!raw) { return {} } try { const parsed = JSON.parse(raw) as unknown return normalizeExtraHeaders(parsed, 'HAPI_EXTRA_HEADERS_JSON', warn) } catch { warn('[WARN] Failed to parse HAPI_EXTRA_HEADERS_JSON. Ignoring value.') return {} } } /** * Resolves HAPI's home directory: the `HAPI_HOME` env override (with a * leading `~` expanded to the current user's home) takes priority, else * `~/.hapi`. Takes an explicit env object (defaulting to `process.env`) so * callers that need a fresh read on every call — rather than the cached * `Configuration.happyHomeDir` singleton value, which is fixed at process * startup — can reuse this instead of re-deriving the same priority logic. */ export function resolveHapiHomeDir(env: NodeJS.ProcessEnv = process.env): string { if (env.HAPI_HOME) { return env.HAPI_HOME.replace(/^~/, homedir()) } return join(homedir(), '.hapi') } class Configuration { private _apiUrl: string private _cliApiToken: string private _extraHeaders: Record public readonly isRunnerProcess: boolean // Directories and paths (from persistence) public readonly happyHomeDir: string public readonly logsDir: string public readonly settingsFile: string public readonly privateKeyFile: string public readonly runnerStateFile: string public readonly runnerLockFile: string public readonly currentCliVersion: string public readonly isExperimentalEnabled: boolean constructor() { // Server configuration this._apiUrl = process.env.HAPI_API_URL || 'http://localhost:3006' this._cliApiToken = process.env.CLI_API_TOKEN || '' this._extraHeaders = parseExtraHeaders(process.env.HAPI_EXTRA_HEADERS_JSON) // Check if we're running as runner based on process args const args = getCliArgs() this.isRunnerProcess = args.length >= 2 && args[0] === 'runner' && (args[1] === 'start-sync') // Directory configuration - Priority: HAPI_HOME env > default home dir this.happyHomeDir = resolveHapiHomeDir() this.logsDir = join(this.happyHomeDir, 'logs') this.settingsFile = join(this.happyHomeDir, 'settings.json') this.privateKeyFile = join(this.happyHomeDir, 'access.key') this.runnerStateFile = join(this.happyHomeDir, 'runner.state.json') this.runnerLockFile = join(this.happyHomeDir, 'runner.state.json.lock') this.isExperimentalEnabled = ['true', '1', 'yes'].includes(process.env.HAPI_EXPERIMENTAL?.toLowerCase() || '') this.currentCliVersion = packageJson.version if (!existsSync(this.happyHomeDir)) { mkdirSync(this.happyHomeDir, { recursive: true }) } // Ensure directories exist if (!existsSync(this.logsDir)) { mkdirSync(this.logsDir, { recursive: true }) } } get apiUrl(): string { return this._apiUrl } _setApiUrl(url: string): void { this._apiUrl = url } get cliApiToken(): string { return this._cliApiToken } _setCliApiToken(token: string): void { this._cliApiToken = token } get extraHeaders(): Record { return this._extraHeaders } _setExtraHeaders(headers: Record): void { this._extraHeaders = { ...headers } } } export const configuration: Configuration = new Configuration()