All files / server/services arduino-compiler.ts

97.54% Statements 119/122
81.35% Branches 48/59
100% Functions 11/11
97.5% Lines 117/120

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    7x 7x 7x 7x                                     60x 60x             20x 20x 20x       20x 20x   1x                     51x 51x 51x 51x   51x 51x     51x 51x     51x 51x     51x   51x   51x 51x   51x 7x 7x 7x   7x                               44x     43x 43x   43x 11x 11x   13x     13x         13x 13x 14x 13x       13x 13x                   13x       13x   13x 13x     13x       13x               43x     42x 11x     11x 13x 13x 13x         42x 42x         42x 42x   42x 2x 2x 40x 11x 11x 11x   29x 29x 29x       42x     42x               42x   51x                   2x                     51x 51x   1x                 38x   38x   38x                 38x   38x   38x 38x   38x 35x     38x 11x 11x   11x     38x 37x   27x   27x   27x 27x   27x 27x 7x   20x     27x             10x 10x     10x       10x                   10x 5x     7x       7x         10x               38x   1x 1x           7x  
//arduino-compiler.ts
 
import { spawn } from "child_process";
import { writeFile, mkdir, rm } from "fs/promises";
import { join } from "path";
import { randomUUID } from "crypto";
import { Logger } from "@shared/logger";
import { ParserMessage, IOPinRecord } from "@shared/schema";
import { CodeParser } from "@shared/code-parser";
import { reservedNamesValidator } from "@shared/reserved-names-validator";
// Removed unused mock imports to satisfy TypeScript
 
export interface CompilationResult {
  success: boolean;
  output: string;
  errors?: string;
  binary?: Buffer;
  arduinoCliStatus: "idle" | "compiling" | "success" | "error";
  gccStatus: "idle" | "compiling" | "success" | "error";
  parserMessages?: ParserMessage[]; // Parser validation messages
  ioRegistry?: IOPinRecord[]; // I/O Registry for visualization
}
 
export class ArduinoCompiler {
  private tempDir = join(process.cwd(), "temp");
  private logger = new Logger("ArduinoCompiler");
 
  constructor() {
    //this.ensureTempDir();
  }
 
  static async create(): Promise<ArduinoCompiler> {
    const instance = new ArduinoCompiler();
    await instance.ensureTempDir();
    return instance;
  }
 
  private async ensureTempDir() {
    try {
      await mkdir(this.tempDir, { recursive: true });
    } catch (error) {
      this.logger.warn(
        `Failed to create temp directory: ${error instanceof Error ? error.message : error}`,
      );
    }
  }
 
  async compile(
    code: string,
    headers?: Array<{ name: string; content: string }>,
    tempRoot?: string,
  ): Promise<CompilationResult> {
    const sketchId = randomUUID();
    const baseTempDir = tempRoot || this.tempDir;
    const sketchDir = join(baseTempDir, sketchId);
    const sketchFile = join(sketchDir, `${sketchId}.ino`);
 
    let arduinoCliStatus: "idle" | "compiling" | "success" | "error" = "idle";
    let warnings: string[] = []; // NEW: Collect warnings
 
    // NEW: Parse code for issues
    const parser = new CodeParser();
    const parserMessages = parser.parseAll(code);
 
    // Check for reserved name conflicts
    const reservedNameMessages = reservedNamesValidator.validateReservedNames(code);
    const allParserMessages = [...parserMessages, ...reservedNameMessages];
 
    // I/O Registry is now populated at runtime, not from static parsing
    const ioRegistry: any[] = [];
 
    try {
      // Validierung: setup() und loop()
      const hasSetup = /void\s+setup\s*\(\s*\)/.test(code);
      const hasLoop = /void\s+loop\s*\(\s*\)/.test(code);
 
      if (!hasSetup || !hasLoop) {
        const missingFunctions = [];
        if (!hasSetup) missingFunctions.push("setup()");
        if (!hasLoop) missingFunctions.push("loop()");
 
        return {
          success: false,
          output: "",
          errors: `Missing Arduino functions: ${missingFunctions.join(" and ")}\n\nArduino sketches require:\n- void setup() { }\n- void loop() { }`,
          arduinoCliStatus: "error",
          gccStatus: "idle",
          parserMessages: allParserMessages, // Include parser messages even on error
          ioRegistry, // Include I/O registry
        };
      }
 
      // Serial.begin warnings are now ONLY in parserMessages, not in output
      // The code-parser.ts handles all Serial configuration warnings
      // No need to add them to the warnings array anymore
 
      // Create files
      await mkdir(sketchDir, { recursive: true });
 
      // Process code: replace #include statements with actual header content
      let processedCode = code;
      let lineOffset = 0; // Track how many lines were added by header insertion
 
      if (headers && headers.length > 0) {
        this.logger.debug(`Processing ${headers.length} header includes`);
        for (const header of headers) {
          // Try to find includes with both the full name (header_1.h) and without extension (header_1)
          const headerWithoutExt = header.name.replace(/\.[^/.]+$/, ""); // Remove extension
 
          // Search for both variants: #include "header_1.h" and #include "header_1"
          const includeVariants = [
            `#include "${header.name}"`,
            `#include "${headerWithoutExt}"`,
          ];
 
          let found = false;
          for (const includeStatement of includeVariants) {
            if (processedCode.includes(includeStatement)) {
              this.logger.debug(
                `Found include for: ${header.name} (pattern: ${includeStatement})`,
              );
              // Replace the #include with the actual header content
              const replacement = `// --- Start of ${header.name} ---\n${header.content}\n// --- End of ${header.name} ---`;
              processedCode = processedCode.replace(
                new RegExp(
                  `#include\\s*"${includeStatement.split('"')[1].replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}"`,
                  "g",
                ),
                replacement,
              );
 
              // Calculate line offset by counting newlines: replacement newlines - 0 (original #include line stays as 1 line)
              // The #include statement is replaced, so we count how many MORE lines we added
              const newlinesInReplacement = (replacement.match(/\n/g) || [])
                .length;
              // Each #include is 1 line, replacement has newlinesInReplacement+1 lines
              // So offset is: (newlinesInReplacement+1) - 1 = newlinesInReplacement
              lineOffset += newlinesInReplacement;
 
              found = true;
              this.logger.debug(
                `Replaced include for: ${header.name}, line offset now: ${lineOffset}`,
              );
              break;
            }
          }
 
          Iif (!found) {
            this.logger.debug(
              `Include not found for: ${header.name} (tried: ${includeVariants.join(", ")})`,
            );
          }
        }
      }
 
      await writeFile(sketchFile, processedCode);
 
      // Write header files to disk as separate files
      if (headers && headers.length > 0) {
        this.logger.debug(
          `Writing ${headers.length} header files to ${sketchDir}`,
        );
        for (const header of headers) {
          const headerPath = join(sketchDir, header.name);
          this.logger.debug(`Writing header: ${headerPath}`);
          await writeFile(headerPath, header.content);
        }
      }
 
      // 1. Arduino CLI
      arduinoCliStatus = "compiling";
      const cliResult = await this.compileWithArduinoCli(
        sketchFile,
        lineOffset,
      );
 
      let cliOutput = "";
      let cliErrors = "";
 
      if (cliResult === null) {
        arduinoCliStatus = "error";
        cliErrors = "Arduino CLI not available";
      } else if (!cliResult.success) {
        arduinoCliStatus = "error";
        cliOutput = "";
        cliErrors = cliResult.errors || "Compilation failed";
      } else {
        arduinoCliStatus = "success";
        cliOutput = cliResult.output || "";
        cliErrors = cliResult.errors || "";
      }
 
      // Kombinierte Ausgabe
      let combinedOutput = cliOutput;
 
      // Add warnings to output
      Iif (warnings.length > 0) {
        const warningText = "\n\n" + warnings.join("\n");
        combinedOutput = combinedOutput
          ? combinedOutput + warningText
          : warningText.trim();
      }
 
      // Erfolg = arduino-cli erfolgreich (g++ Syntax-Check entfernt - wird in Runner gemacht)
      const success = cliResult?.success ?? false;
 
      return {
        success,
        output: combinedOutput,
        errors: cliErrors || undefined,
        arduinoCliStatus,
        gccStatus: "idle", // Nicht mehr verwendet in Compiler
        parserMessages: allParserMessages, // Include parser messages
        ioRegistry, // Include I/O registry
      };
    } catch (error) {
      return {
        success: false,
        output: "",
        errors: `Compilation failed: ${error instanceof Error ? error.message : String(error)}`,
        arduinoCliStatus:
          arduinoCliStatus === "compiling" ? "error" : arduinoCliStatus,
        gccStatus: "idle",
        parserMessages: allParserMessages, // Include parser messages even on error
        ioRegistry, // Include I/O registry
      };
    } finally {
      try {
        await rm(sketchDir, { recursive: true, force: true });
      } catch (error) {
        this.logger.warn(`Failed to clean up temp directory: ${error}`);
      }
    }
  }
 
  private async compileWithArduinoCli(
    sketchFile: string,
    lineOffset: number = 0,
  ): Promise<{ success: boolean; output: string; errors?: string } | null> {
    return new Promise((resolve) => {
      // Arduino CLI expects the sketch DIRECTORY, not the file
      const sketchDir = sketchFile.substring(0, sketchFile.lastIndexOf("/"));
 
      const args = [
        "compile",
        "--fqbn",
        "arduino:avr:uno",
        "--verbose",
        sketchDir,
      ];
 
      // LOG: Command being executed
      this.logger.info(`Executing arduino-cli ${args.join(" ")}`);
 
      const arduino = spawn("arduino-cli", args);
 
      let output = "";
      let errors = "";
 
      arduino.stdout?.on("data", (data) => {
        output += data.toString();
      });
 
      arduino.stderr?.on("data", (data) => {
        const chunk = data.toString();
        errors += chunk;
        // LOG: Real-time stderr output for CI debugging
        this.logger.debug(`arduino-cli stderr: ${chunk.trim()}`);
      });
 
      arduino.on("close", (code) => {
        if (code === 0) {
          const progSizeRegex =
            /(Sketch uses[^\n]*\.|Der Sketch verwendet[^\n]*\.)/;
          const ramSizeRegex =
            /(Global variables use[^\n]*\.|Globale Variablen verwenden[^\n]*\.)/;
 
          const progSizeMatch = output.match(progSizeRegex);
          const ramSizeMatch = output.match(ramSizeRegex);
 
          let parsedOutput = "";
          if (progSizeMatch && ramSizeMatch) {
            parsedOutput = `${progSizeMatch[0]}\n${ramSizeMatch[0]}\n\nBoard: Arduino UNO`;
          } else {
            parsedOutput = `Board: Arduino UNO (Simulation)`;
          }
 
          resolve({
            success: true,
            output: parsedOutput,
          });
        } else {
          // Compilation failed (syntax error etc.)
          // LOG: Full stderr and exit code on failure
          this.logger.error(`arduino-cli compilation failed with exit code ${code}`);
          this.logger.error(`Full stderr output:\n${errors}`);
 
          // Bereinige Fehlermeldungen von Pfaden
          const escapedPath = sketchFile.replace(
            /[-\/\\^$*+?.()|[\]{}]/g,
            "\\$&",
          );
          let cleanedErrors = errors
            .replace(new RegExp(escapedPath, "g"), "sketch.ino")
            .replace(
              /\/[^\s:]+\/temp\/[a-f0-9-]+\/[a-f0-9-]+\.ino/gi,
              "sketch.ino",
            )
            .replace(/Error during build: exit status \d+\s*/g, "")
            .trim();
 
          // Correct line numbers if headers were embedded
          if (lineOffset > 0) {
            cleanedErrors = cleanedErrors.replace(
              /sketch\.ino:(\d+):/g,
              (_match, lineNum) => {
                const correctedLine = Math.max(
                  1,
                  parseInt(lineNum) - lineOffset,
                );
                return `sketch.ino:${correctedLine}:`;
              },
            );
          }
 
          resolve({
            success: false,
            output: "",
            errors: cleanedErrors || "Compilation failed",
          });
        }
      });
 
      arduino.on("error", (err) => {
        // LOG: Command spawn error
        this.logger.error(`arduino-cli spawn error: ${err.message}`);
        resolve(null);
      });
    });
  }
}
 
export const compiler = new ArduinoCompiler();