All files / client/src/hooks use-compile-controller.ts

94.25% Statements 82/87
87.03% Branches 47/54
100% Functions 10/10
94.04% Lines 79/84

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                                4x                                                                                                                                                                       216x 59x 59x 59x 59x     216x   56x 55x 55x   56x 56x 52x   56x 52x 52x 52x                         52x 38x 33x   5x       4x 3x 3x 3x 1x   2x         216x 48x     216x   33x 33x 33x 33x 33x 33x 33x 33x     33x 33x         216x   5x 5x 5x 5x   5x 1x 4x 4x     5x 5x 5x 5x 5x 5x 2x   5x         216x 16x 15x 15x 15x         15x 1x     14x 11x 11x   3x 3x     15x 1x 1x     14x 14x                             216x 1x 1x 1x     216x                                      
import { useCallback } from "react";
import { useMutation, type UseMutationResult } from "@tanstack/react-query";
import { apiRequest } from "@/lib/queryClient";
import { Logger } from "@shared/logger";
import type { IOPinRecord, OutputLine, ParserMessage } from "@shared/schema";
import type { CompilationStatus, CompilationResultType } from "@/types/compilation.types";
import type {
  CompileConfig,
  CompileResult,
  CompilerError,
} from "@/types/websocket";
import { buildCompileCommand } from "./compile-command-builder";
import { isCompileResult } from "@/types/websocket";
import type { SourceProject } from "@shared/source-project";
import type { ServerCapabilities } from "@/lib/server-capabilities";
 
const logger = new Logger("use-compile-controller");
 
export type SetState<T> = (value: T | ((prev: T) => T)) => void;
type ArduinoCliStatus = "idle" | "compiling" | "success" | "error";
 
/** UI Feedback Adapter interface for compile controller */
interface UiFeedbackAdapter {
  logCompileRequest: (codeLength: number) => void;
  logCompilationSuccess: () => void;
  logCompilationError: (errors: CompilationErrors) => void;
  triggerCompileErrorGlitch: () => void;
  showCompileSuccessToast: () => void;
  showCompileErrorToast: () => void;
  showBackendUnreachableToast: () => void;
  showCompilationFailedWithErrorsToast: () => void;
  showNoCodeToast: () => void;
  setCompileSuccessOutput: (output: string) => void;
  setCompileErrorOutput: (errors: CompilationErrors) => void;
}
 
export type CompilationErrors = CompilerError[] | string | undefined;
 
export interface UseCompileControllerParams {
  readonly capabilities?: ServerCapabilities;
  /** Ignore completions whose compile-to-start owner was invalidated. */
  isCompileResultCurrent?: (payload: CompileConfig) => boolean;
  // State
  compilationStatus: CompilationStatus;
  setCompilationStatus: SetState<CompilationStatus>;
  arduinoCliStatus: ArduinoCliStatus;
  setArduinoCliStatus: SetState<ArduinoCliStatus>;
  hasCompilationErrors: boolean;
  setHasCompilationErrors: SetState<boolean>;
  compilerErrors: CompilerError[];
  setCompilerErrors: SetState<CompilerError[]>;
  lastCompilationResult: CompilationResultType;
  setLastCompilationResult: SetState<CompilationResultType>;
  cliOutput: string;
  setCliOutput: SetState<string>;
 
  // Callbacks
  setParserMessages: SetState<ParserMessage[]>;
  setParserPanelDismissed: SetState<boolean>;
  /** Clears the runtime snapshot when a new compilation/run begins. */
  setIoRegistry: SetState<IOPinRecord[] | null>;
  setIsModified: SetState<boolean>;
  resetPinUI: (opts?: { keepDetected?: boolean }) => void;
 
  // UI Feedback
  uiFeedback: UiFeedbackAdapter;
  isBackendUnreachableError: (error: unknown) => boolean;
 
  // Editor
  editorRef: React.RefObject<{ getValue: () => string } | null>;
  tabs: Array<{ id: string; name: string; path?: string; content: string }>;
  activeTabId: string | null;
  code: string;
  sourceProject?: SourceProject | null;
 
  // Simulation coordination
  clearSerialOutput: () => void;
  setSerialOutput: SetState<OutputLine[]>;
}
 
interface UseCompileControllerResult {
  compilationStatus: CompilationStatus;
  setCompilationStatus: SetState<CompilationStatus>;
  arduinoCliStatus: ArduinoCliStatus;
  setArduinoCliStatus: SetState<ArduinoCliStatus>;
  hasCompilationErrors: boolean;
  setHasCompilationErrors: SetState<boolean>;
  compilerErrors: CompilerError[];
  setCompilerErrors: SetState<CompilerError[]>;
  lastCompilationResult: CompilationResultType;
  setLastCompilationResult: SetState<CompilationResultType>;
  cliOutput: string;
  setCliOutput: SetState<string>;
  compileMutation: UseMutationResult<CompileResult, unknown, CompileConfig, unknown>;
  handleCompile: () => void;
  handleClearCompilationOutput: () => void;
  clearOutputs: () => void;
}
 
export function useCompileController(params: UseCompileControllerParams): UseCompileControllerResult {
  const clearOutputs = useCallback(() => {
    params.setCliOutput("");
    params.setSerialOutput([]);
    params.clearSerialOutput();
    params.setParserMessages([]);
  }, [params]);
 
  const compileMutation = useMutation<CompileResult, unknown, CompileConfig, unknown>({
    mutationFn: async (payload: CompileConfig): Promise<CompileResult> => {
      if (params.isCompileResultCurrent?.(payload) !== false) {
        params.setArduinoCliStatus("compiling");
        params.setLastCompilationResult(null);
      }
      params.uiFeedback.logCompileRequest(payload.code.length);
      const response = await apiRequest("POST", "/api/compile", payload);
      const ct = (response.headers.get("content-type") || "").toLowerCase();
 
      if (ct.includes("application/json")) {
        try {
          const parsed = await response.json();
          return isCompileResult(parsed)
            ? parsed
            : { success: false, errors: JSON.stringify(parsed), raw: JSON.stringify(parsed) };
        } catch {
          const txt = await response.text();
          return { success: false, errors: txt, raw: txt };
        }
      }
 
      const txt = await response.text();
      return { success: false, errors: txt, raw: txt };
    },
    onSuccess: (data, payload) => {
      if (params.isCompileResultCurrent?.(payload) === false) return;
      if (data.success) {
        handleCompileSuccess(data);
      } else {
        handleCompileError(data);
      }
    },
    onError: (error: unknown, payload) => {
      if (params.isCompileResultCurrent?.(payload) === false) return;
      params.setArduinoCliStatus("error");
      params.uiFeedback.triggerCompileErrorGlitch();
      if (params.isBackendUnreachableError(error)) {
        params.uiFeedback.showBackendUnreachableToast();
      } else {
        params.uiFeedback.showCompileErrorToast();
      }
    },
  });
 
  const clearRuntimeRegistry = useCallback(() => {
    params.setIoRegistry(null);
  }, [params]);
 
  const handleCompileSuccess = useCallback(
    (data: CompileResult) => {
      params.setArduinoCliStatus("success");
      params.setHasCompilationErrors(false);
      params.setLastCompilationResult("success");
      params.setCompilerErrors([]);
      params.uiFeedback.setCompileSuccessOutput(data.output ?? "");
      params.uiFeedback.logCompilationSuccess();
      params.setParserMessages(data.parserMessages ?? []);
      Iif (data.parserMessages && data.parserMessages.length > 0) {
        params.setParserPanelDismissed(false);
      }
      params.uiFeedback.showCompileSuccessToast();
      clearRuntimeRegistry();
    },
    [params, clearRuntimeRegistry],
  );
 
  const handleCompileError = useCallback(
    (data: CompileResult) => {
      params.setArduinoCliStatus("error");
      params.setHasCompilationErrors(true);
      params.setLastCompilationResult("error");
      let errs: CompilerError[] = [];
 
      if (Array.isArray(data.errors)) {
        errs = data.errors;
      } else Eif (typeof data.errors === "string") {
        errs = [{ file: "", line: 0, column: 0, type: "error", message: data.errors }];
      }
 
      params.setCompilerErrors(errs);
      params.uiFeedback.triggerCompileErrorGlitch();
      params.uiFeedback.setCompileErrorOutput(data.errors);
      params.uiFeedback.logCompilationError(data.errors);
      params.setParserMessages(data.parserMessages ?? []);
      if (data.parserMessages && data.parserMessages.length > 0) {
        params.setParserPanelDismissed(false);
      }
      params.uiFeedback.showCompileErrorToast();
    },
    [params],
  );
 
  const handleCompile = useCallback(() => {
    if (params.capabilities && !params.capabilities.canCompile) return;
    clearOutputs();
    params.resetPinUI();
    clearRuntimeRegistry();
 
    let mainSketchCode: string;
    let headers: Array<{ name: string; content: string }>;
    let entryFile: string | undefined;
    if (params.sourceProject !== undefined) {
      ({ code: mainSketchCode, headers, entryFile } = params.sourceProject
        ? buildCompileCommand(params.sourceProject)
        : { code: "", headers: [], entryFile: undefined });
    } else if (params.activeTabId === params.tabs[0]?.id && params.editorRef.current) {
      mainSketchCode = params.editorRef.current.getValue();
      ({ headers } = buildCompileCommand(mainSketchCode, params.tabs));
    } else {
      mainSketchCode = params.tabs[0]?.content || params.code;
      ({ headers } = buildCompileCommand(mainSketchCode, params.tabs));
    }
 
    if (!mainSketchCode || mainSketchCode.trim().length === 0) {
      params.uiFeedback.showNoCodeToast();
      return;
    }
 
    logger.info(`[CLIENT] Compiling with ${headers.length} headers`);
    compileMutation.mutate({ code: mainSketchCode, headers, ...(entryFile ? { entryFile } : {}) });
  }, [
    params.activeTabId,
    clearOutputs,
    params.code,
    compileMutation,
    params.editorRef,
    params.resetPinUI,
    params.tabs,
    params.sourceProject,
    clearRuntimeRegistry,
    params.uiFeedback,
    params.capabilities,
  ]);
 
  const handleClearCompilationOutput = useCallback(() => {
    params.setCliOutput("");
    params.setLastCompilationResult(null);
    params.setParserMessages([]);
  }, [params]);
 
  return {
    compilationStatus: params.compilationStatus,
    setCompilationStatus: params.setCompilationStatus,
    arduinoCliStatus: params.arduinoCliStatus,
    setArduinoCliStatus: params.setArduinoCliStatus,
    hasCompilationErrors: params.hasCompilationErrors,
    setHasCompilationErrors: params.setHasCompilationErrors,
    compilerErrors: params.compilerErrors,
    setCompilerErrors: params.setCompilerErrors,
    lastCompilationResult: params.lastCompilationResult,
    setLastCompilationResult: params.setLastCompilationResult,
    cliOutput: params.cliOutput,
    setCliOutput: params.setCliOutput,
    compileMutation,
    handleCompile,
    handleClearCompilationOutput,
    clearOutputs,
  };
}