All files / src/utils global.ts

0% Statements 0/107
0% Branches 0/142
0% Functions 0/10
0% Lines 0/105

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
import { buildFallbackError } from "@common/Error/ErrorCatcher";
import { safeParse } from ".";
 
const globePathSVG =
  "M128,24h0A104,104,0,1,0,232,128,104.12,104.12,0,0,0,128,24Zm88,104a87.61,87.61,0,0,1-3.33,24H174.16a157.44,157.44,0,0,0,0-48h38.51A87.61,87.61,0,0,1,216,128ZM102,168H154a115.11,115.11,0,0,1-26,45A115.27,115.27,0,0,1,102,168Zm-3.9-16a140.84,140.84,0,0,1,0-48h59.88a140.84,140.84,0,0,1,0,48ZM40,128a87.61,87.61,0,0,1,3.33-24H81.84a157.44,157.44,0,0,0,0,48H43.33A87.61,87.61,0,0,1,40,128ZM154,88H102a115.11,115.11,0,0,1,26-45A115.27,115.27,0,0,1,154,88Zm52.33,0H170.71a135.28,135.28,0,0,0-22.3-45.6A88.29,88.29,0,0,1,206.37,88ZM107.59,42.4A135.28,135.28,0,0,0,85.29,88H49.63A88.29,88.29,0,0,1,107.59,42.4ZM49.63,168H85.29a135.28,135.28,0,0,0,22.3,45.6A88.29,88.29,0,0,1,49.63,168Zm98.78,45.6a135.28,135.28,0,0,0,22.3-45.6h35.66A88.29,88.29,0,0,1,148.41,213.6Z";
 
export const handlerCallback = (error: any) => {
  const versionEl = document.head.querySelector('meta[name="script-version"]');
  const version = versionEl?.getAttribute("content") ?? "";
 
  if (
    process.env.VITE_ENVIRONMENT === "local.development" ||
    process.env.VITE_ENVIRONMENT === "local.staging"
  ) {
    return;
  }
 
  // Filter out XMLHttpRequest errors that occur during page navigation/redirect
  // These are expected when XHR requests are aborted due to navigation (e.g., redirecting to login on 401)
  if (isXHRAbortError(error)) {
    console.debug("Ignoring aborted XHR request during navigation:", error);
    return;
  }
 
  // Filter out OperationError - native browser error from IndexedDB/Cache API
  // that occurs when storage is unavailable or corrupted. These are non-recoverable
  // browser-level errors that don't indicate application bugs.
  if (isOperationError(error)) {
    console.debug("Ignoring OperationError (browser storage error):", error);
    return;
  }
 
  // Filter out fetch AbortError "signal is aborted without reason", which commonly occurs
  // when pdf.js or other consumers cancel in-flight fetches during navigation or re-render.
  if (isAbortSignalError(error)) {
    error.preventDefault?.();
    console.debug("Ignoring aborted fetch signal error:", error);
    return;
  }
 
  if (isChunkLoadError(error)) {
    // Prevent Sentry from logging this as unhandled
    error.preventDefault();
 
    fetch(`${process.env.VITE_ASSETS_CDN_HOST}/ui/version.json`, {
      headers: {
        "Cache-Control": "no-cache, no-store, must-revalidate",
        Pragma: "no-cache", //For older browsers
      },
    })
      .then((res) => res.text())
      .then((text) => {
        const data = safeParse<{ version: string }>(text);
        const cdnVersion = data?.version;
 
        if (version !== cdnVersion && cdnVersion) {
          buildFallbackError();
        }
      })
      .catch((err) => {
        console.log("Failed to fetch version.json:", err);
        buildFallbackError({
          customTitle: "Technical Difficulties",
          customBody:
            "There seems to be a temporary network issue. We're working on resolving it.",
          customSvg: {
            viewBox: "0 0 256 256",
            svgPath: globePathSVG,
          },
        });
      });
  } else {
    console.log(error);
  }
 
  // Filter out network/XHR failures on mobile Safari or transient connectivity issues.
  // These errors are often caused by aborted requests or temporary network drops,
  // and are not actionable
  if (isNetworkXHRFailure(error)) {
    error.preventDefault?.();
    console.debug("Ignoring mobile network/XHR failure:", error);
    return;
  }
 
  // Filter out "Tab not found" errors from extensions
  if (isTabNotFoundError(error)) {
    console.debug("Ignoring browser extension 'Tab not found' error:", error);
    return;
  }
 
  // Filter out Flagsmith internal errors:
  // - "feature named `performanceMetrics` was not found"
  // - "feature named `pageObserver` was not found"
  if (
    error.reason?.message?.includes("performanceMetrics") ||
    error.reason?.message?.includes("pageObserver")
  ) {
    console.warn("Suppressed Flagsmith feature error:", error.reason);
    error.preventDefault?.(); // Prevent Sentry from capturing this
    return;
  }
  // Browser extensions such as (Privacy Badger, Ghostery, anti-fingerprinting tools)
  // inject scripts that can interfere with our application code, causing spurious
  // promise rejections that appear in Sentry, we're filtering out these extension-specific errors to prevent false positives
  //  in our error monitoring. These are not bugs in our code and cannot be fixed
  //  on the frontend
  if (
    error.reason &&
    typeof error.reason === "string" &&
    error.reason.includes("Object Not Found Matching Id")
  ) {
    error.preventDefault?.();
    console.debug("Ignoring Object Not Found failure:", error);
    return;
  }
};
 
const chunkLoadErrorMessageRegex =
  /Failed to fetch dynamically imported module|error loading dynamically imported module|importing a module script failed/i;
 
function isChunkLoadError(error: ErrorEvent | Error): boolean {
  if (!error) {
    return false;
  }
 
  let actualError = null;
  let errorMessage = "";
 
  if (error instanceof ErrorEvent) {
    errorMessage = error.message || "";
    actualError = error.error;
  } else if (error instanceof Error) {
    actualError = error;
    errorMessage = error.message || "";
  } else if (
    error &&
    typeof error === "object" &&
    typeof (error as any).message === "string"
  ) {
    errorMessage = (error as any).message;
  } else {
    return false;
  }
 
  const hasMatchingMessage = chunkLoadErrorMessageRegex.test(errorMessage);
 
  // Also check the nested error's message directly if available, as it might be more specific
  const hasMatchingNestedMessage =
    actualError &&
    typeof actualError.message === "string" &&
    chunkLoadErrorMessageRegex.test(actualError.message);
 
  // We primarily rely on the message pattern.
  // The TypeError check adds confidence but might be too strict if browser behaviour changes.
  // Let's return true if any of the relevant messages match the pattern.
  if (hasMatchingMessage || hasMatchingNestedMessage) {
    return true;
  }
 
  return false;
}
 
/**
 * Checks if an error is related to an aborted XMLHttpRequest during navigation.
 * IMPORTANT: This is conservative - we only return true when we're confident it's a navigation-related
 * abort, NOT a genuine network error that could impact user experience.
 */
function isXHRAbortError(error: any): boolean {
  if (!error) {
    return false;
  }
 
  // Only filter if we're on the login page (indicating a redirect happened)
  const isOnLoginPage = window.location.pathname === "/login";
  if (!isOnLoginPage) {
    return false; // Don't filter errors during normal app usage
  }
 
  if (error.type === "unhandledrejection" && error.reason) {
    const reason = error.reason;
 
    // Check if it's an XMLHttpRequestProgressEvent with error type
    if (
      reason?.constructor?.name === "XMLHttpRequestProgressEvent" &&
      reason?.type === "error" &&
      typeof reason === "object" &&
      reason.target?.constructor?.name === "XMLHttpRequest"
    ) {
      // Additional check: the XHR should have readyState indicating abort (0 or 4)
      // and status 0 (aborted before completion)
      const xhr = reason.target;
      if (xhr && (xhr.readyState === 0 || xhr.status === 0)) {
        return true; // Confirmed: aborted XHR during navigation
      }
    }
  }
 
  return false;
}
 
/**
 * Checks if an error is an OperationError from IndexedDB/Cache API operations.
 * OperationError is a native browser error that occurs when storage operations fail
 * in a non-recoverable way (e.g., database corrupted, storage quota exceeded, etc.).
 * These are browser-level errors that don't indicate application bugs.
 */
function isOperationError(error: any): boolean {
  if (!error) {
    return false;
  }
 
  // Check for OperationError in unhandled rejection events
  if (error.type === "unhandledrejection" && error.reason) {
    const reason = error.reason;
 
    // Check if it's an OperationError by name or message
    if (
      reason?.name === "OperationError" ||
      reason?.constructor?.name === "OperationError" ||
      (reason?.message &&
        typeof reason.message === "string" &&
        (reason.message.includes("OperationError") ||
          (reason.message.includes("Non-recoverable error") &&
            reason.message.includes("Do not retry"))))
    ) {
      return true;
    }
  }
 
  // Check for OperationError in regular error events
  if (error.error) {
    const actualError = error.error;
    if (
      actualError?.name === "OperationError" ||
      actualError?.constructor?.name === "OperationError" ||
      (actualError?.message &&
        typeof actualError.message === "string" &&
        (actualError.message.includes("OperationError") ||
          (actualError.message.includes("Non-recoverable error") &&
            actualError.message.includes("Do not retry"))))
    ) {
      return true;
    }
  }
 
  // Check error message directly
  if (error.message && typeof error.message === "string") {
    if (
      error.message.includes("OperationError") ||
      (error.message.includes("Non-recoverable error") &&
        error.message.includes("Do not retry"))
    ) {
      return true;
    }
  }
 
  return false;
}
 
 
function isNetworkXHRFailure(event: any): boolean {
  // unhandled promise rejection with XHR error
  if (event?.type === "unhandledrejection" && event?.reason) {
    const reason = event.reason;
 
    // Axios network error
    if (reason?.isAxiosError && reason.message === "Network Error") {
      return true;
    }
 
    // Safari XHR ProgressEvent surfaced as rejection
    if (
      reason?.constructor?.name === "XMLHttpRequestProgressEvent" ||
      reason?.type === "error"
    ) {
      return true;
    }
  }
 
  return false;
}
 
function isTabNotFoundError(error: any): boolean {
  if (!error) return false;
 
  // Check the message of the error or nested error.reason
  const errorMessage =
    error?.message || error?.reason?.message || error?.error?.message || "";
 
  // Mobile Safari / Chrome extension runtime sendMessage tab not found
  return /Invalid call to runtime\.sendMessage\(\)\. Tab not found/i.test(
    errorMessage,
  );
}
 
function isAbortSignalError(event: any): boolean {
  if (!event) return false;
 
  // Handle unhandledrejection events where the reason is an AbortError
  if (event.type === "unhandledrejection" && event.reason) {
    const reason = event.reason;
    if (
      (reason.name === "AbortError" ||
        reason.constructor?.name === "AbortError") &&
      typeof reason.message === "string" &&
      reason.message.includes("signal is aborted without reason")
    ) {
      return true;
    }
  }
 
  // Fallback: direct AbortError instance
  if (
    event.name === "AbortError" &&
    typeof event.message === "string" &&
    event.message.includes("signal is aborted without reason")
  ) {
    return true;
  }
 
  return false;
}