From 4d35df3051326070dd85564962cd9edbc39f897f Mon Sep 17 00:00:00 2001 From: Tom Butcher Date: Sun, 26 Jul 2026 23:21:07 +0100 Subject: [PATCH] Refactor headless mode initialization and enhance index.js structure Replace the previous headless mode implementation in headless.js with a streamlined init function in index.js that accepts options. This change improves modularity and error handling during initialization. The logger setup and socket client connection have been removed from headless.js, centralizing the logic in index.js. --- src/headless.js | 24 +++++------------------- src/index.js | 22 ++++++++++++++++------ 2 files changed, 21 insertions(+), 25 deletions(-) diff --git a/src/headless.js b/src/headless.js index dc79053..dc744bb 100644 --- a/src/headless.js +++ b/src/headless.js @@ -1,20 +1,6 @@ -import { loadConfig } from './config.js' -import log4js from 'log4js' -import { SocketClient } from './socket/socketclient.js' +import { init } from "./index.js"; -const config = loadConfig() - -const logger = log4js.getLogger('App') -logger.level = config.logLevel - -logger.info('Running in headless mode.') - -const socketClient = new SocketClient() -global.socketClient = socketClient -socketClient.connect() - -process.on('SIGINT', () => { - logger.info('Shutting down...') - socketClient.disconnect() - process.exit(0) -}) +init({ headless: true }).catch((err) => { + console.error(err.message); + process.exit(1); +}); diff --git a/src/index.js b/src/index.js index cf9d9dc..2867e5b 100644 --- a/src/index.js +++ b/src/index.js @@ -1,3 +1,5 @@ +import { fileURLToPath } from "node:url"; +import path from "node:path"; import { loadConfig } from "./config.js"; import axios from "axios"; import log4js from "log4js"; @@ -81,7 +83,9 @@ async function authenticateWithOtp(otpCode) { throw new Error("Failed to authenticate with OTP"); } } -export async function init() { +export async function init(options = {}) { + const headless = options.headless ?? isHeadless; + logger.info("⌛ Checking if Farm Control Server is running..."); const runningServer = await checkRunning(); @@ -127,7 +131,7 @@ export async function init() { return runningServer; } - if (!isHeadless) { + if (!headless) { // Create Electron window first logger.info("Creating electron window..."); await createElectronWindow().catch((err) => { @@ -159,7 +163,13 @@ export async function init() { }); } -init().catch((err) => { - logger.error(err.message); - process.exit(1); -}); +const isMainModule = + process.argv[1] && + fileURLToPath(import.meta.url) === path.resolve(process.argv[1]); + +if (isMainModule) { + init().catch((err) => { + logger.error(err.message); + process.exit(1); + }); +}