All files / cli/serve ServeCommand.ts

85.71% Statements 60/70
88.23% Branches 45/51
82.35% Functions 14/17
85.71% Lines 60/70

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                                                                                                                  2x 2x 2x 2x         2x                                                                                                   54x 2x                             6x 13x 6x           7x         13x                 25x 2x     23x     23x   23x 1x 1x 1x     22x 22x     22x 22x     22x 3x                     22x   22x 1x             21x   21x 13x     8x                     23x             2x                         5x 1x             4x 4x   4x   4x                 5x       5x                         3x 1x             2x   2x       3x         2x                                     2x         2x 1x 1x                   2x   2x                         2x   2x   2x                   1x 1x                
/**
 * ServeCommand
 * JSON-RPC server for VS Code extension communication
 *
 * Phase 2b (ADR-060): Uses the full Transpiler for transpilation and symbol
 * extraction, enabling include resolution, C++ auto-detection, and cross-file
 * symbol support.
 */
 
import { createInterface, Interface } from "node:readline";
import { dirname } from "node:path";
import JsonRpcHandler from "./JsonRpcHandler";
import IJsonRpcRequest from "./types/IJsonRpcRequest";
import IJsonRpcResponse from "./types/IJsonRpcResponse";
import ConfigPrinter from "../ConfigPrinter";
import ConfigLoader from "../ConfigLoader";
import Transpiler from "../../transpiler/Transpiler";
import parseWithSymbols from "../../lib/parseWithSymbols";
import parseCHeader from "../../lib/parseCHeader";
 
/**
 * Method handler type (async to support Transpiler.transpileSource)
 */
type MethodHandler = (
  params?: Record<string, unknown>,
) => Promise<IMethodResult>;
 
/**
 * Result from a method handler
 */
interface IMethodResult {
  success: boolean;
  result?: unknown;
  errorCode?: number;
  errorMessage?: string;
}
 
/**
 * Result of validating and extracting source parameters.
 */
interface ISourceParams {
  source: string;
  filePath: string | undefined;
}
 
/**
 * Options for the serve command
 */
interface IServeOptions {
  /** Enable debug logging to stderr */
  debug?: boolean;
}
 
/**
 * JSON-RPC server command
 */
class ServeCommand {
  private static shouldShutdown = false;
  private static readline: Interface | null = null;
  private static debugMode = false;
  private static transpiler: Transpiler | null = null;
 
  /**
   * Method handlers registry
   */
  private static readonly methods: Record<string, MethodHandler> = {
    getVersion: ServeCommand.handleGetVersion,
    initialize: ServeCommand.handleInitialize,
    transpile: ServeCommand._withSourceValidation(
      ServeCommand._handleTranspile,
    ),
    parseSymbols: ServeCommand._withSourceValidation(
      ServeCommand._handleParseSymbols,
    ),
    parseCHeader: ServeCommand._withSourceValidation(
      ServeCommand._handleParseCHeader,
    ),
    shutdown: ServeCommand.handleShutdown,
  };
 
  /**
   * Run the JSON-RPC server
   * Reads requests from stdin, writes responses to stdout
   * @param options - Server options
   */
  static async run(options: IServeOptions = {}): Promise<void> {
    this.debugMode = options.debug ?? false;
    this.shouldShutdown = false;
 
    this.log("server starting");
 
    this.readline = createInterface({
      input: process.stdin,
      output: process.stdout,
      terminal: false,
    });
 
    // Disable default output - we write responses manually
    this.readline.on("line", (line: string) => {
      this.handleLine(line);
    });
 
    // Wait for close or shutdown
    await new Promise<void>((resolve) => {
      this.readline!.on("close", () => {
        this.log("server stopped");
        resolve();
      });
    });
  }
 
  /**
   * Log a debug message to stderr
   */
  private static log(message: string): void {
    if (this.debugMode) {
      process.stderr.write(`[serve] ${message}\n`);
    }
  }
 
  // ========================================================================
  // Parameter Validation Helpers (Issue #707: Reduce code duplication)
  // ========================================================================
 
  /**
   * Wrapper that validates source params before calling handler.
   * Eliminates duplicate validation code across handlers.
   */
  private static _withSourceValidation(
    handler: (params: ISourceParams) => Promise<IMethodResult>,
  ): MethodHandler {
    return async (params?: Record<string, unknown>): Promise<IMethodResult> => {
      if (!params || typeof params.source !== "string") {
        return {
          success: false,
          errorCode: JsonRpcHandler.ERROR_INVALID_PARAMS,
          errorMessage: "Missing required param: source",
        };
      }
      const validated: ISourceParams = {
        source: String(params.source),
        filePath:
          typeof params.filePath === "string" ? params.filePath : undefined,
      };
      return handler(validated);
    };
  }
 
  /**
   * Handle a single line of input
   */
  private static handleLine(line: string): void {
    // Skip empty lines
    if (line.trim() === "") {
      return;
    }
 
    this.log(`received: ${line}`);
 
    // Parse the request
    const parseResult = JsonRpcHandler.parseRequest(line);
 
    if (!parseResult.success) {
      this.log(`parse error`);
      this.writeResponse(parseResult.error!);
      return;
    }
 
    const request = parseResult.request!;
    this.log(`method: ${request.method}`);
 
    // Dispatch to method handler (async)
    this.dispatch(request).then((response) => {
      this.writeResponse(response);
 
      // Handle shutdown after response is written
      if (this.shouldShutdown) {
        this.readline?.close();
      }
    });
  }
 
  /**
   * Dispatch a request to the appropriate handler
   */
  private static async dispatch(
    request: IJsonRpcRequest,
  ): Promise<IJsonRpcResponse> {
    const handler = this.methods[request.method];
 
    if (!handler) {
      return JsonRpcHandler.formatError(
        request.id,
        JsonRpcHandler.ERROR_METHOD_NOT_FOUND,
        `Method not found: ${request.method}`,
      );
    }
 
    const result = await handler(request.params);
 
    if (result.success) {
      return JsonRpcHandler.formatResponse(request.id, result.result);
    }
 
    return JsonRpcHandler.formatError(
      request.id,
      result.errorCode ?? JsonRpcHandler.ERROR_INVALID_PARAMS,
      result.errorMessage ?? "Unknown error",
    );
  }
 
  /**
   * Write a JSON response to stdout
   */
  private static writeResponse(response: IJsonRpcResponse): void {
    process.stdout.write(JSON.stringify(response) + "\n");
  }
 
  /**
   * Handle getVersion method
   */
  private static async handleGetVersion(): Promise<IMethodResult> {
    return {
      success: true,
      result: { version: ConfigPrinter.getVersion() },
    };
  }
 
  /**
   * Handle initialize method
   * Loads project config and creates a Transpiler instance
   */
  private static async handleInitialize(
    params?: Record<string, unknown>,
  ): Promise<IMethodResult> {
    if (!params || typeof params.workspacePath !== "string") {
      return {
        success: false,
        errorCode: JsonRpcHandler.ERROR_INVALID_PARAMS,
        errorMessage: "Missing required param: workspacePath",
      };
    }
 
    const workspacePath = params.workspacePath;
    ServeCommand.log(`initializing with workspace: ${workspacePath}`);
 
    const config = ConfigLoader.load(workspacePath);
 
    ServeCommand.transpiler = new Transpiler({
      inputs: [],
      includeDirs: config.include ?? [],
      cppRequired: config.cppRequired ?? false,
      target: config.target ?? "",
      debugMode: config.debugMode ?? false,
      noCache: config.noCache ?? false,
    });
 
    ServeCommand.log(
      `initialized (cppRequired=${config.cppRequired ?? false}, includeDirs=${(config.include ?? []).length})`,
    );
 
    return {
      success: true,
      result: { success: true },
    };
  }
 
  /**
   * Handle transpile method (called via _withSourceValidation wrapper)
   * Uses full Transpiler for include resolution and C++ auto-detection
   */
  private static async _handleTranspile(
    params: ISourceParams,
  ): Promise<IMethodResult> {
    if (!ServeCommand.transpiler) {
      return {
        success: false,
        errorCode: JsonRpcHandler.ERROR_INVALID_PARAMS,
        errorMessage: "Server not initialized. Call initialize first.",
      };
    }
 
    const { source, filePath } = params;
 
    const options = filePath
      ? { workingDir: dirname(filePath), sourcePath: filePath }
      : undefined;
 
    const result = await ServeCommand.transpiler.transpileSource(
      source,
      options,
    );
 
    return {
      success: true,
      result: {
        success: result.success,
        code: result.code,
        errors: result.errors,
        cppDetected: ServeCommand.transpiler.isCppDetected(),
      },
    };
  }
 
  /**
   * Handle parseSymbols method (called via _withSourceValidation wrapper)
   * Runs full transpilation for include/C++ detection, then extracts symbols
   * from the parse tree (preserving "extract symbols even with parse errors" behavior)
   */
  private static async _handleParseSymbols(
    params: ISourceParams,
  ): Promise<IMethodResult> {
    const { source, filePath } = params;
 
    // If transpiler is initialized, run transpileSource to trigger header
    // resolution and C++ detection (results are discarded, we just want
    // the side effects on the symbol table)
    if (ServeCommand.transpiler && filePath) {
      try {
        await ServeCommand.transpiler.transpileSource(source, {
          workingDir: dirname(filePath),
          sourcePath: filePath,
        });
      } catch {
        // Ignore transpilation errors - we still extract symbols below
      }
    }
 
    // Delegate symbol extraction to parseWithSymbols (shared with WorkspaceIndex)
    const result = parseWithSymbols(source);
 
    return {
      success: true,
      result,
    };
  }
 
  /**
   * Handle parseCHeader method (called via _withSourceValidation wrapper)
   * Parses C/C++ header files and extracts symbols
   */
  private static async _handleParseCHeader(
    params: ISourceParams,
  ): Promise<IMethodResult> {
    const { source, filePath } = params;
 
    const result = parseCHeader(source, filePath);
 
    return {
      success: true,
      result,
    };
  }
 
  /**
   * Handle shutdown method
   */
  private static async handleShutdown(): Promise<IMethodResult> {
    ServeCommand.shouldShutdown = true;
    return {
      success: true,
      result: { success: true },
    };
  }
}
 
export default ServeCommand;