All files / backend/src/ssg-providers/jekyll jekyll-server.ts

10.25% Statements 8/78
0% Branches 0/27
8.33% Functions 1/12
10.25% Lines 8/78

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                                                                                                    6x 6x 6x 6x 6x 6x 6x 6x                                                                                                                                                                                                                                                                                                                                                                                                                                                                      
/**
 * Jekyll Server
 *
 * Manages the Jekyll development server process.
 */
 
import { spawn, ChildProcess } from 'child_process';
import fs from 'fs-extra';
import path from 'path';
import type { PathHelper } from '../../utils/path-helper.js';
import type { AppConfig } from '../../config/app-config.js';
import type { AppContainer } from '../../config/container.js';
import type { WindowAdapter, OutputConsole } from '../../adapters/types.js';
import type { SSGDevServer } from '../types.js';
import { SITE_CATEGORIES } from '../../logging/index.js';
 
/**
 * Jekyll server configuration
 */
export interface JekyllServerConfig {
  workspacePath: string;
  version: string;
  config?: string;
  port?: number;
}
 
/**
 * JekyllServer - Manages Jekyll development server
 */
export class JekyllServer implements SSGDevServer {
  private config: JekyllServerConfig;
  private pathHelper: PathHelper;
  private appConfig: AppConfig;
  private windowAdapter: WindowAdapter;
  private outputConsole: OutputConsole;
  private container: AppContainer;
  private siteKey: string;
  private workspaceKey: string;
  private currentServerProcess?: ChildProcess;
 
  constructor(
    config: JekyllServerConfig,
    pathHelper: PathHelper,
    appConfig: AppConfig,
    windowAdapter: WindowAdapter,
    outputConsole: OutputConsole,
    container: AppContainer,
    siteKey: string,
    workspaceKey: string
  ) {
    this.config = config;
    this.pathHelper = pathHelper;
    this.appConfig = appConfig;
    this.windowAdapter = windowAdapter;
    this.outputConsole = outputConsole;
    this.container = container;
    this.siteKey = siteKey;
    this.workspaceKey = workspaceKey;
  }
 
  /**
   * Emit lines from a stream
   */
  private emitLines(stream: NodeJS.ReadableStream): void {
    let backlog = '';
    stream.on('data', (data) => {
      backlog += data;
      let n = backlog.indexOf('\n');
      // got a \n? emit one or more 'line' events
      while (~n) {
        stream.emit('line', backlog.substring(0, n));
        backlog = backlog.substring(n + 1);
        n = backlog.indexOf('\n');
      }
    });
    stream.on('end', () => {
      if (backlog) {
        stream.emit('line', backlog);
      }
    });
  }
 
  /**
   * Stop the server if it's running
   * Implementation of SSGDevServer.stopIfRunning()
   */
  stopIfRunning(): void {
    if (this.currentServerProcess) {
      this.outputConsole.appendLine('Stopping Jekyll Server...');
      this.outputConsole.appendLine('');
      
      // Log server stop
      this.container.logger.infoSite(
        this.siteKey,
        this.workspaceKey,
        SITE_CATEGORIES.BUILDACTION,
        'Jekyll Server stopping',
        { workspacePath: this.config.workspacePath }
      );
 
      this.currentServerProcess.kill();
      this.currentServerProcess = undefined;
    }
  }
 
  /**
   * Get the current server process
   * Implementation of SSGDevServer.getCurrentProcess()
   */
  getCurrentProcess(): ChildProcess | undefined {
    return this.currentServerProcess;
  }
 
  /**
   * Get the Jekyll wrapper script path
   */
  private getJekyllCommand(): string {
    const installDir = this.pathHelper.getSSGBinDirForVer('jekyll', this.config.version);
    const platform = process.platform;
 
    if (platform === 'win32') {
      return path.join(installDir, 'jekyll.cmd');
    } else {
      return path.join(installDir, 'jekyll.sh');
    }
  }
 
  /**
   * Start the Jekyll development server
   * Implementation of SSGDevServer.serve()
   */
  async serve(): Promise<void> {
    this.stopIfRunning();
 
    const jekyllCommand = this.getJekyllCommand();
 
    if (!fs.existsSync(jekyllCommand)) {
      throw new Error(`Jekyll not found for version ${this.config.version}. Command: ${jekyllCommand}`);
    }
 
    this.outputConsole.appendLine('======================================');
    this.outputConsole.appendLine('Starting Jekyll Server');
    this.outputConsole.appendLine('======================================');
    this.outputConsole.appendLine('');
    this.outputConsole.appendLine(`Workspace: ${this.config.workspacePath}`);
    this.outputConsole.appendLine(`Jekyll: ${this.config.version}`);
    this.outputConsole.appendLine('');
 
    const args: string[] = ['serve'];
 
    // Add port (default to 13131 for consistency with other SSGs)
    const port = this.config.port || 13131;
    args.push('--port', port.toString());
 
    // Add live reload
    args.push('--livereload');
 
    // Incremental builds for faster rebuilds
    args.push('--incremental');
 
    // Add config file if specified (convert to absolute path)
    if (this.config.config) {
      const configPath = path.isAbsolute(this.config.config)
        ? this.config.config
        : path.join(this.config.workspacePath, this.config.config);
      args.push('--config', configPath);
    }
 
    this.outputConsole.appendLine(`Command: ${jekyllCommand} ${args.join(' ')}`);
    this.outputConsole.appendLine('');
    
    // Log server start
    this.container.logger.infoSite(
      this.siteKey,
      this.workspaceKey,
      SITE_CATEGORIES.BUILDACTION,
      'Jekyll Server started',
      { 
        port,
        workspacePath: this.config.workspacePath,
        version: this.config.version,
        command: `${jekyllCommand} ${args.join(' ')}`
      }
    );
 
    // Spawn Jekyll server
    this.currentServerProcess = spawn(jekyllCommand, args, {
      cwd: this.config.workspacePath,
      env: {
        ...process.env,
        JEKYLL_ENV: 'development',
      },
      shell: true, // Use shell to properly execute the wrapper script
    });
 
    // Handle stdout
    if (this.currentServerProcess.stdout) {
      this.emitLines(this.currentServerProcess.stdout);
      this.currentServerProcess.stdout.on('line', (line: string) => {
        this.outputConsole.appendLine(line);
        
        // Also log to structured logs
        // Determine log level based on content
        if (line.includes('ERROR') || line.includes('FATAL') || line.includes('Error')) {
          this.container.logger.errorSite(
            this.siteKey,
            this.workspaceKey,
            SITE_CATEGORIES.BUILDACTION,
            'Jekyll output',
            { message: line }
          );
        } else if (line.includes('WARN') || line.includes('Warning')) {
          this.container.logger.warningSite(
            this.siteKey,
            this.workspaceKey,
            SITE_CATEGORIES.BUILDACTION,
            'Jekyll output',
            { message: line }
          );
        } else {
          // Regular info messages
          this.container.logger.infoSite(
            this.siteKey,
            this.workspaceKey,
            SITE_CATEGORIES.BUILDACTION,
            'Jekyll output',
            { message: line }
          );
        }
      });
    }
 
    // Handle stderr
    if (this.currentServerProcess.stderr) {
      this.emitLines(this.currentServerProcess.stderr);
      this.currentServerProcess.stderr.on('line', (line: string) => {
        this.outputConsole.appendLine(line);
        
        // Log stderr as errors
        this.container.logger.errorSite(
          this.siteKey,
          this.workspaceKey,
          SITE_CATEGORIES.BUILDACTION,
          'Jekyll error output',
          { message: line }
        );
      });
    }
 
    // Handle process exit
    this.currentServerProcess.on('exit', (code) => {
      this.outputConsole.appendLine('');
      this.outputConsole.appendLine(`Jekyll Server exited with code ${code}`);
      
      // Log exit
      this.container.logger.infoSite(
        this.siteKey,
        this.workspaceKey,
        SITE_CATEGORIES.BUILDACTION,
        'Jekyll Server exited',
        { exitCode: code }
      );
      
      this.currentServerProcess = undefined;
    });
 
    // Handle errors
    this.currentServerProcess.on('error', (error) => {
      this.outputConsole.appendLine('');
      this.outputConsole.appendLine(`Jekyll Server error: ${error.message}`);
      
      // Log error
      this.container.logger.errorSite(
        this.siteKey,
        this.workspaceKey,
        SITE_CATEGORIES.BUILDACTION,
        'Jekyll Server error',
        { error: error.message, stack: error.stack }
      );
      
      this.currentServerProcess = undefined;
    });
  }
}