All files / client/src/lib monaco-error-suppressor.ts

72.94% Statements 62/85
59.72% Branches 43/72
50% Functions 6/12
72.28% Lines 60/83

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            14x     14x 14x 38x         14x                       14x   5x 5x   5x 2x 2x   3x     5x       1x     1x       4x 4x           14x 14x   14x 13x   12x 12x   6x 6x   6x 5x 5x   1x 1x       6x         13x 4x     6x     14x 11x 3x 3x   8x     14x 2x 1x 1x   1x       14x 14x 2x 2x   2x         1x 1x     1x     1x       14x                             14x                           14x 14x                                                       14x 14x 14x                            
/**
 * Global error interceptor to suppress Monaco's hitTest null reference errors
 * This module should be imported once at the application root
 */
 
// Debug mode
const DEBUG = false; // Disable after testing
 
import { Logger } from "../../../shared/logger";
const logger = new Logger("MonacoErrorSuppressor");
const log = (msg: string, ...args: unknown[]) => {
  Iif (DEBUG) {
    logger.debug(`[Monaco Error Suppressor] ${msg}`, ...(args as []));
  }
};
 
log("Module loaded");
 
// First, patch the global error handler used by Monaco itself
// This prevents the error from being thrown in the first place
declare global {
  interface GlobalThis {
    __MONACO_EDITOR_ERROR_HANDLER__?: {
      onUnexpectedError: (error: unknown) => void;
    };
  }
}
 
(globalThis as any).__MONACO_EDITOR_ERROR_HANDLER__ = {
  onUnexpectedError: (error: unknown) => {
    let message = "";
    let stack = "";
    
    if (error instanceof Error) {
      message = error.message;
      stack = error.stack ?? "";
    } else {
      message = String(error);
    }
 
    if (
      (message.includes("offsetNode") && message.includes("hitResult")) ||
      stack.includes("_doHitTestWithCaretPositionFromPoint")
    ) {
      log(
        "Intercepted Monaco internal error handler - suppressing hitTest error",
      );
      return; // Suppress by not rethrowing
    }
 
    // Let other errors through
    Eif (typeof console !== "undefined" && console.error) {
      console.error(error);
    }
  },
};
 
// Suppress Monaco hitTest errors globally
const originalError = console.error;
const originalWarn = console.warn;
 
const isMonacoHitTestError = (args: unknown[]): boolean => {
  if (args.length === 0) return false;
  
  const firstArg = args[0];
  if (!firstArg || typeof firstArg !== 'object') return false;
 
  let message = "";
  let stack = "";
 
  if (firstArg instanceof Error) {
    message = firstArg.message;
    stack = firstArg.stack ?? "";
  } else {
    const obj = firstArg as Record<string, unknown>;
    message = typeof obj.message === "string" ? obj.message : JSON.stringify(firstArg);
  }
 
  const isError =
    (message.includes("offsetNode") && message.includes("hitResult")) ||
    stack.includes("_doHitTestWithCaretPositionFromPoint") ||
    (message.includes("can't access property") &&
      message.includes("hitResult is null"));
 
  if (isError) {
    log(`Detected Monaco hitTest error: ${message.slice(0, 150)}`);
  }
 
  return isError;
};
 
console.error = function (...args: unknown[]) {
  if (isMonacoHitTestError(args)) {
    log("Suppressed error via console.error");
    return;
  }
  originalError.apply(console, args as any);
};
 
console.warn = function (...args: unknown[]) {
  if (isMonacoHitTestError(args)) {
    log("Suppressed warning via console.warn");
    return;
  }
  originalWarn.apply(console, args as any);
};
 
// Intercept uncaught errors at the earliest point
const originalErrorHandler = globalThis.onerror;
globalThis.onerror = function (message, source, lineno, colno, error) {
  const errorMessage = typeof message === "string" ? message : "";
  const errorStack = error?.stack || "";
 
  if (
    (errorMessage.includes("offsetNode") &&
      errorMessage.includes("hitResult")) ||
    errorStack.includes("_doHitTestWithCaretPositionFromPoint")
  ) {
    log("Suppressed error via window.onerror");
    return true; // Suppress
  }
 
  Iif (originalErrorHandler) {
    return originalErrorHandler(message, source, lineno, colno, error);
  }
  return false;
};
 
// Capture errors before they bubble up
globalThis.addEventListener(
  "error",
  (event: ErrorEvent) => {
    if (isMonacoHitTestError([event.error])) {
      log(
        "Suppressed error via error event listener (stopImmediatePropagation)",
      );
      event.preventDefault();
      event.stopImmediatePropagation();
    }
  },
  true,
);
 
// Handle unhandled promise rejections
globalThis.addEventListener(
  "unhandledrejection",
  (event: PromiseRejectionEvent) => {
    const reason = event.reason;
 
    if (reason && isMonacoHitTestError([reason])) {
      log("Suppressed rejection via unhandledrejection listener");
      event.preventDefault();
    }
  },
  true,
);
 
// Remove error overlays if they appear (Replit's runtime error modal)
Eif (typeof MutationObserver !== "undefined") {
  const observer = new MutationObserver((mutations) => {
    mutations.forEach((mutation) => {
      if (mutation.addedNodes.length) {
        mutation.addedNodes.forEach((node) => {
          if (node.nodeType === 1) {
            // Element node
            const element = node as HTMLElement;
            const textContent = element.textContent || "";
            const innerHTML = element.innerHTML || "";
 
            // Check if this is an error overlay/modal
            if (
              textContent.includes("offsetNode") ||
              innerHTML.includes("offsetNode") ||
              textContent.includes("_doHitTestWithCaretPositionFromPoint")
            ) {
              log("Found Monaco hitTest error overlay, removing:", {
                class: element.className,
              });
              element.remove();
            }
          }
        });
      }
    });
  });
 
  // Start observing when DOM is ready
  if (document.body) {
    log("Attaching MutationObserver to document.body");
    observer.observe(document.body, {
      childList: true,
      subtree: true,
    });
  } else E{
    document.addEventListener("DOMContentLoaded", () => {
      log("Attaching MutationObserver on DOMContentLoaded");
      observer.observe(document.body, {
        childList: true,
        subtree: true,
      });
    });
  }
}