All files server-manager.ts

90.32% Statements 168/186
76.05% Branches 54/71
85.29% Functions 29/34
90.27% Lines 167/185

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408                          5x 5x       32x 32x 32x 32x           7x 7x 7x 7x 7x               14x         14x 14x 12x   2x                   6x   6x 3x   3x         3x     3x 2x 2x 1x         1x             2x         3x 3x 1x             2x 2x   1x     1x               5x 5x   5x 5x       5x   5x 1x     5x 4x 3x   1x       5x 1x                       9x 9x   9x         9x 1x 1x   8x 8x     9x 9x 9x   9x                 9x 6x 6x 6x 6x   6x 6x 6x 6x       9x       9x 2x 2x 2x 2x 2x 2x       9x 1x 1x 1x 1x 1x 1x       9x 3x 3x 3x 3x     9x 9x 9x 9x                     7x 7x   7x     7x 7x 2x             5x   2x 2x 2x 2x   3x 3x 3x     5x 5x 5x   5x                         5x 4x 4x 4x 4x   4x 4x 4x 4x       5x       5x 1x 1x 1x 1x 1x 1x       5x                   5x 1x 1x 1x 1x     5x 5x 5x 5x                 7x   4x 1x           3x 1x           5x               6x 6x                   21x     4x 1x     3x 3x   3x 3x 1x 1x 1x 1x 1x 1x       3x 2x 2x 2x 2x 2x 2x     3x     3x      
import { spawn, spawnSync, ChildProcess } from 'child_process';
import { app } from 'electron';
import * as path from 'path';
import * as fs from 'fs';
 
export interface PrerequisiteResult {
  ok: boolean;
  error?: string;
  needsInstall?: boolean;
}
 
// Check if this is a nightly build (version contains 'nightly' or commit hash)
function isNightlyBuild(): boolean {
  const version = app.getVersion();
  return version.includes('nightly') || version.includes('-') || !version.match(/^\d+\.\d+\.\d+$/);
}
 
export class ServerManager {
  private process: ChildProcess | null = null;
  private stopping = false;
  private stopped = false;
  private stopPromise: Promise<void> | null = null;
 
  /**
   * Clean up all listeners from the child process and reset state.
   */
  private cleanup(): void {
    Eif (this.process) {
      this.process.stdout?.removeAllListeners();
      this.process.stderr?.removeAllListeners();
      this.process.removeAllListeners();
      this.process = null;
    }
  }
 
  /**
   * Get the path to the bundled mehr binary (macOS/Linux only).
   */
  private getMehrPath(): string {
    Iif (app.isPackaged) {
      // In packaged app: resources/bin/mehr
      return path.join(process.resourcesPath, 'bin', 'mehr');
    } else {
      // In dev: look in desktop/resources/bin/ or fall back to PATH
      const devPath = path.join(__dirname, '../../resources/bin', 'mehr');
      if (fs.existsSync(devPath)) {
        return devPath;
      }
      return 'mehr'; // Fall back to PATH for dev
    }
  }
 
  /**
   * Preflight check - call on app startup.
   * - macOS/Linux: Check bundled binary exists
   * - Windows: Check WSL exists, auto-install mehr if missing
   */
  checkPrerequisites(): PrerequisiteResult {
    const isWindows = process.platform === 'win32';
 
    if (isWindows) {
      return this.checkWindowsPrerequisites();
    } else {
      return this.checkUnixPrerequisites();
    }
  }
 
  private checkUnixPrerequisites(): PrerequisiteResult {
    const mehrPath = this.getMehrPath();
 
    // In dev mode with fallback to PATH, check if mehr exists
    if (mehrPath === 'mehr') {
      const check = spawnSync('which', ['mehr'], { stdio: 'pipe' });
      if (check.status !== 0) {
        return {
          ok: false,
          error: 'mehr binary not found.\n\nThis is a development build issue.',
        };
      }
    I} else if (!fs.existsSync(mehrPath)) {
      return {
        ok: false,
        error: 'Bundled mehr binary not found.\n\nPlease reinstall the application.',
      };
    }
 
    return { ok: true };
  }
 
  private checkWindowsPrerequisites(): PrerequisiteResult {
    // Check WSL availability
    const wslCheck = spawnSync('wsl', ['--version'], { stdio: 'pipe' });
    if (wslCheck.status !== 0) {
      return {
        ok: false,
        error: 'WSL is not installed.\n\nPlease install WSL2:\nhttps://learn.microsoft.com/en-us/windows/wsl/install',
      };
    }
 
    // Check if mehr is installed in WSL
    const mehrCheck = spawnSync('wsl', ['which', 'mehr'], { stdio: 'pipe' });
    if (mehrCheck.status !== 0) {
      // mehr not found - needs auto-install
      return { ok: true, needsInstall: true };
    }
 
    return { ok: true };
  }
 
  /**
   * Auto-install mehr in WSL (Windows only).
   * Uses the install script with --nightly flag if this is a nightly build.
   */
  async installMehrInWSL(): Promise<void> {
    const nightlyFlag = isNightlyBuild() ? ' -s -- --nightly' : '';
    const installCmd = `curl -fsSL https://raw.githubusercontent.com/valksor/go-mehrhof/master/install.sh | bash${nightlyFlag}`;
 
    return new Promise((resolve, reject) => {
      const proc = spawn('wsl', ['bash', '-c', installCmd], {
        stdio: ['ignore', 'pipe', 'pipe'],
      });
 
      let stderr = '';
 
      proc.stderr?.on('data', (data: Buffer) => {
        stderr += data.toString();
      });
 
      proc.on('exit', (code) => {
        if (code === 0) {
          resolve();
        } else {
          reject(new Error(`Failed to install mehr in WSL:\n${stderr}`));
        }
      });
 
      proc.on('error', (err) => {
        reject(new Error(`Failed to run install script: ${err.message}`));
      });
    });
  }
 
  /**
   * Start mehr serve in global mode.
   * Shows project picker UI.
   * @returns The port number mehr is listening on.
   */
  async startGlobal(): Promise<number> {
    // Stop any existing process first
    await this.stop();
    this.stopped = false; // Reset for new server instance
 
    const isWindows = process.platform === 'win32';
 
    let cmd: string;
    let args: string[];
 
    if (isWindows) {
      cmd = 'wsl';
      args = ['mehr', 'serve', '--global', '--port', '0'];
    } else {
      cmd = this.getMehrPath();
      args = ['serve', '--global', '--port', '0'];
    }
 
    return new Promise((resolve, reject) => {
      this.process = spawn(cmd, args, { shell: false });
      let resolved = false;
 
      const timeout = setTimeout(() => {
        if (!resolved) {
          resolved = true;
          removeListeners();
          reject(new Error('Server startup timed out after 30 seconds.'));
        }
      }, 30000);
 
      // Define named listeners for proper cleanup
      const onStdout = (data: Buffer) => {
        const match = data.toString().match(/localhost:(\d+)/);
        Eif (match && !resolved) {
          resolved = true;
          clearTimeout(timeout);
          // Keep stderr listener for logging, remove startup listeners
          this.process?.off('error', onError);
          this.process?.off('exit', onExit);
          this.process?.stdout?.off('data', onStdout);
          resolve(parseInt(match[1], 10));
        }
      };
 
      const onStderr = (data: Buffer) => {
        console.error('[mehr stderr]', data.toString());
      };
 
      const onError = (err: Error) => {
        Eif (!resolved) {
          resolved = true;
          clearTimeout(timeout);
          removeListeners();
          this.cleanup();
          reject(new Error(`Failed to start mehr: ${err.message}`));
        }
      };
 
      const onExit = (code: number | null) => {
        Eif (!resolved && code !== 0 && code !== null) {
          resolved = true;
          clearTimeout(timeout);
          removeListeners();
          this.cleanup();
          reject(new Error(`mehr exited with code ${code}`));
        }
      };
 
      const removeListeners = () => {
        this.process?.stdout?.off('data', onStdout);
        this.process?.stderr?.off('data', onStderr);
        this.process?.off('error', onError);
        this.process?.off('exit', onExit);
      };
 
      this.process.stdout?.on('data', onStdout);
      this.process.stderr?.on('data', onStderr);
      this.process.on('error', onError);
      this.process.on('exit', onExit);
    });
  }
 
  /**
   * Start mehr serve for a project.
   * Uses random port (--port 0) to avoid conflicts.
   * @returns The port number mehr is listening on.
   */
  async start(projectPath: string): Promise<number> {
    // Stop any existing process first
    await this.stop();
    this.stopped = false; // Reset for new server instance
 
    const isWindows = process.platform === 'win32';
 
    // Validate path
    const validation = this.validatePath(projectPath);
    if (!validation.ok) {
      throw new Error(validation.error);
    }
 
    let cmd: string;
    let args: string[];
    let cwd: string | undefined;
 
    if (isWindows) {
      // Convert Windows path → WSL path, use cd to set working directory
      const wslPath = this.toWslPath(projectPath);
      cmd = 'wsl';
      args = ['bash', '-c', `cd '${wslPath}' && mehr serve --port 0`];
      cwd = undefined;
    } else {
      cmd = this.getMehrPath();
      args = ['serve', '--port', '0'];
      cwd = projectPath;
    }
 
    return new Promise((resolve, reject) => {
      this.process = spawn(cmd, args, { cwd, shell: false });
      let resolved = false;
 
      const timeout = setTimeout(() => {
        if (!resolved) {
          resolved = true;
          removeListeners();
          reject(
            new Error(
              'Server startup timed out after 30 seconds.\n\nCheck that mehr is working: mehr --version'
            )
          );
        }
      }, 30000);
 
      // Define named listeners for proper cleanup
      const onStdout = (data: Buffer) => {
        const match = data.toString().match(/localhost:(\d+)/);
        Eif (match && !resolved) {
          resolved = true;
          clearTimeout(timeout);
          // Keep stderr listener for logging, remove startup listeners
          this.process?.off('error', onError);
          this.process?.off('exit', onExit);
          this.process?.stdout?.off('data', onStdout);
          resolve(parseInt(match[1], 10));
        }
      };
 
      const onStderr = (data: Buffer) => {
        console.error('[mehr stderr]', data.toString());
      };
 
      const onError = (err: Error) => {
        Eif (!resolved) {
          resolved = true;
          clearTimeout(timeout);
          removeListeners();
          this.cleanup();
          reject(new Error(`Failed to start mehr: ${err.message}`));
        }
      };
 
      const onExit = (code: number | null) => {
        if (!resolved && code !== 0 && code !== null) {
          resolved = true;
          clearTimeout(timeout);
          removeListeners();
          this.cleanup();
          reject(new Error(`mehr exited with code ${code}`));
        }
      };
 
      const removeListeners = () => {
        this.process?.stdout?.off('data', onStdout);
        this.process?.stderr?.off('data', onStderr);
        this.process?.off('error', onError);
        this.process?.off('exit', onExit);
      };
 
      this.process.stdout?.on('data', onStdout);
      this.process.stderr?.on('data', onStderr);
      this.process.on('error', onError);
      this.process.on('exit', onExit);
    });
  }
 
  /**
   * Validate a project path.
   * Rejects UNC paths on Windows.
   */
  private validatePath(winPath: string): PrerequisiteResult {
    if (process.platform === 'win32') {
      // Reject network paths (UNC)
      if (winPath.startsWith('\\\\')) {
        return {
          ok: false,
          error: 'Network paths (\\\\server\\share) are not supported.\n\nPlease use a local drive.',
        };
      }
      // Validate drive letter format
      if (!/^[A-Za-z]:\\/.test(winPath)) {
        return {
          ok: false,
          error: 'Invalid path format.\n\nExpected: C:\\path\\to\\project',
        };
      }
    }
    return { ok: true };
  }
 
  /**
   * Convert Windows path to WSL path.
   * C:\Users\foo -> /mnt/c/Users/foo
   */
  private toWslPath(winPath: string): string {
    return winPath
      .replace(/^([A-Za-z]):\\/, (_, drive: string) => `/mnt/${drive.toLowerCase()}/`)
      .replace(/\\/g, '/');
  }
 
  /**
   * Graceful shutdown: SIGTERM -> wait 5s -> SIGKILL.
   * Safe to call multiple times - subsequent calls wait for the first to complete.
   */
  async stop(): Promise<void> {
    // Already stopped
    if (this.stopped || !this.process) return;
 
    // If already stopping, wait for that operation to complete
    if (this.stopping && this.stopPromise) {
      return this.stopPromise;
    }
 
    this.stopping = true;
    const proc = this.process;
 
    this.stopPromise = new Promise((resolve) => {
      const forceKill = setTimeout(() => {
        proc.kill('SIGKILL');
        this.cleanup();
        this.stopping = false;
        this.stopped = true;
        this.stopPromise = null;
        resolve();
      }, 5000);
 
      // Use once() to auto-remove listener after first call
      proc.once('exit', () => {
        clearTimeout(forceKill);
        this.cleanup();
        this.stopping = false;
        this.stopped = true;
        this.stopPromise = null;
        resolve();
      });
 
      proc.kill('SIGTERM');
    });
 
    return this.stopPromise;
  }
}