Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

83.3 KB
Raw Blame
import { type ErrorEvent } from "@sentry/nextjs";

import {
  isDenylistedNoiseEvent,
  isKitesurfInternalEvent,
  isNoisyHttpClientGatewayEvent,
  isNoisyHttpClientPollEvent,
  isPosthogRecorderInternalEvent,
  isReactDevtoolsInternalEvent,
  isStaleChunkLoadErrorEvent,
  isStaleChunkParseErrorEvent,
} from "@/src/utils/sentryFilters";

/**
 * Build an event shaped exactly like the ones `httpClientIntegration` emits:
 * message + a single exception value carrying the
 * `auto.http.client.<fetch|xhr>` mechanism, plus `request.url`.
 */
function httpClientEvent(
  url: string,
  status = 500,
  type: "fetch" | "xhr" = "fetch",
): ErrorEvent {
  const message = `HTTP Client Error with status code: ${status}`;
  return {
    message,
    exception: {
      values: [
        {
          type: "Error",
          value: message,
          mechanism: { type: `auto.http.client.${type}`, handled: false },
        },
      ],
    },
    request: { url, method: "GET" },
    contexts: { response: { status_code: status } },
  } as ErrorEvent;
}

describe("isNoisyHttpClientPollEvent", () => {
  describe("drops expected poll/health 5xx from httpClientIntegration", () => {
    it("drops the NextAuth session poll (fetch)", () => {
      expect(
        isNoisyHttpClientPollEvent(
          httpClientEvent("https://cloud.langfuse.com/api/auth/session", 500),
        ),
      ).toBe(true);
    });

    it("drops the NextAuth session poll (xhr)", () => {
      expect(
        isNoisyHttpClientPollEvent(
          httpClientEvent(
            "https://cloud.langfuse.com/api/auth/session",
            502,
            "xhr",
          ),
        ),
      ).toBe(true);
    });

    it("drops the session poll behind a NEXT_PUBLIC_BASE_PATH prefix", () => {
      expect(
        isNoisyHttpClientPollEvent(
          httpClientEvent(
            "https://example.com/self-hosted/api/auth/session",
            504,
          ),
        ),
      ).toBe(true);
    });

    it("drops the session poll even with a query string", () => {
      expect(
        isNoisyHttpClientPollEvent(
          httpClientEvent(
            "https://cloud.langfuse.com/api/auth/session?foo=bar",
            500,
          ),
        ),
      ).toBe(true);
    });

    it("drops the health and readiness probes", () => {
      expect(
        isNoisyHttpClientPollEvent(
          httpClientEvent("https://cloud.langfuse.com/api/public/health", 503),
        ),
      ).toBe(true);
      expect(
        isNoisyHttpClientPollEvent(
          httpClientEvent("https://cloud.langfuse.com/api/public/ready", 500),
        ),
      ).toBe(true);
    });
  });

  describe("KEEPS genuine 5xx on real endpoints (does not mask real errors)", () => {
    it("keeps a tRPC 5xx", () => {
      expect(
        isNoisyHttpClientPollEvent(
          httpClientEvent(
            "https://cloud.langfuse.com/api/trpc/traces.all?batch=1",
            500,
          ),
        ),
      ).toBe(false);
    });

    it("does not drop a tRPC 502 by path (gateway statuses are a separate predicate)", () => {
      expect(
        isNoisyHttpClientPollEvent(
          httpClientEvent(
            "https://us.cloud.langfuse.com/api/trpc/annotationQueues.byObjectId",
            502,
          ),
        ),
      ).toBe(false);
    });

    it("keeps a public API 5xx (ingestion / traces)", () => {
      expect(
        isNoisyHttpClientPollEvent(
          httpClientEvent(
            "https://cloud.langfuse.com/api/public/ingestion",
            500,
          ),
        ),
      ).toBe(false);
      expect(
        isNoisyHttpClientPollEvent(
          httpClientEvent("https://cloud.langfuse.com/api/public/traces", 502),
        ),
      ).toBe(false);
    });

    it("keeps other /api/auth endpoints (only /session is a poll)", () => {
      expect(
        isNoisyHttpClientPollEvent(
          httpClientEvent("https://cloud.langfuse.com/api/auth/callback", 500),
        ),
      ).toBe(false);
    });

    it("does not match a path that merely contains a noise path as a substring", () => {
      // endsWith on the pathname, so `/api/auth/sessionmanager` must NOT match.
      expect(
        isNoisyHttpClientPollEvent(
          httpClientEvent(
            "https://cloud.langfuse.com/api/auth/sessionmanager",
            500,
          ),
        ),
      ).toBe(false);
    });
  });

  describe("never touches non-httpClient events", () => {
    it("keeps a genuine thrown exception even if its URL looks like a poll endpoint", () => {
      const event = {
        exception: {
          values: [
            {
              type: "TypeError",
              value: "Cannot read properties of undefined",
              mechanism: { type: "onunhandledrejection", handled: false },
            },
          ],
        },
        request: { url: "https://cloud.langfuse.com/api/auth/session" },
      } as ErrorEvent;
      expect(isNoisyHttpClientPollEvent(event)).toBe(false);
    });

    it("keeps an event with no exception/mechanism (e.g. a message event)", () => {
      const event = {
        message: "some message",
        request: { url: "https://cloud.langfuse.com/api/auth/session" },
      } as ErrorEvent;
      expect(isNoisyHttpClientPollEvent(event)).toBe(false);
    });

    it("keeps an httpClient event that has no request url", () => {
      const event = {
        exception: {
          values: [
            {
              type: "Error",
              value: "HTTP Client Error with status code: 500",
              mechanism: { type: "auto.http.client.fetch", handled: false },
            },
          ],
        },
      } as ErrorEvent;
      expect(isNoisyHttpClientPollEvent(event)).toBe(false);
    });
  });
});

describe("isNoisyHttpClientGatewayEvent", () => {
  describe("drops proxy/LB 502/503/504 from httpClientIntegration on app URLs", () => {
    it("drops a tRPC 502 (annotationQueues.byObjectId shape)", () => {
      expect(
        isNoisyHttpClientGatewayEvent(
          httpClientEvent(
            "https://us.cloud.langfuse.com/api/trpc/annotationQueues.byObjectId",
            502,
          ),
        ),
      ).toBe(true);
    });

    it("drops 503 and 504 on tRPC (xhr included)", () => {
      expect(
        isNoisyHttpClientGatewayEvent(
          httpClientEvent(
            "https://cloud.langfuse.com/api/trpc/traces.all?batch=1",
            503,
          ),
        ),
      ).toBe(true);
      expect(
        isNoisyHttpClientGatewayEvent(
          httpClientEvent(
            "https://cloud.langfuse.com/api/trpc/traces.all?batch=1",
            504,
            "xhr",
          ),
        ),
      ).toBe(true);
    });

    it("drops tRPC behind a NEXT_PUBLIC_BASE_PATH prefix", () => {
      expect(
        isNoisyHttpClientGatewayEvent(
          httpClientEvent(
            "https://example.com/self-hosted/api/trpc/traces.all",
            502,
          ),
        ),
      ).toBe(true);
    });

    it("drops a same-origin public API 502 (LB blip, not an app 500)", () => {
      expect(
        isNoisyHttpClientGatewayEvent(
          httpClientEvent(`${window.location.origin}/api/public/traces`, 502),
        ),
      ).toBe(true);
    });

    it("drops a poll-path 503 (overlaps poll filter; still URL-scoped)", () => {
      expect(
        isNoisyHttpClientGatewayEvent(
          httpClientEvent("https://cloud.langfuse.com/api/auth/session", 503),
        ),
      ).toBe(true);
    });

    it("drops when status lives only on the exception message (no response context)", () => {
      const event = {
        exception: {
          values: [
            {
              type: "Error",
              value: "HTTP Client Error with status code: 502",
              mechanism: { type: "auto.http.client.fetch", handled: false },
            },
          ],
        },
        request: {
          url: "https://us.cloud.langfuse.com/api/trpc/annotationQueues.byObjectId",
        },
      } as ErrorEvent;
      expect(isNoisyHttpClientGatewayEvent(event)).toBe(true);
    });
  });

  describe("KEEPS genuine application 5xx, third-party gateways, and non-httpClient events", () => {
    it("keeps an application HTTP 500 on tRPC", () => {
      expect(
        isNoisyHttpClientGatewayEvent(
          httpClientEvent(
            "https://cloud.langfuse.com/api/trpc/traces.all?batch=1",
            500,
          ),
        ),
      ).toBe(false);
    });

    it("keeps an application HTTP 500 on the public API", () => {
      expect(
        isNoisyHttpClientGatewayEvent(
          httpClientEvent(
            "https://cloud.langfuse.com/api/public/ingestion",
            500,
          ),
        ),
      ).toBe(false);
    });

    it("keeps a third-party S3 presigned-upload 503", () => {
      expect(
        isNoisyHttpClientGatewayEvent(
          httpClientEvent(
            "https://my-bucket.s3.us-east-1.amazonaws.com/media/item.bin?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Signature=abc",
            503,
            "fetch",
          ),
        ),
      ).toBe(false);
    });

    it("keeps a third-party GCS presigned-upload 503", () => {
      expect(
        isNoisyHttpClientGatewayEvent(
          httpClientEvent(
            "https://storage.googleapis.com/my-bucket/media/item.bin?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Signature=abc",
            503,
          ),
        ),
      ).toBe(false);
    });

    it("keeps a cross-origin non-tRPC /api/public 502 (not same-origin)", () => {
      // Path alone is not enough outside tRPC / noise paths — only same-origin
      // covers other app routes. A foreign host must not be suppressed.
      expect(
        isNoisyHttpClientGatewayEvent(
          httpClientEvent("https://other.example.com/api/public/traces", 502),
        ),
      ).toBe(false);
    });

    it("keeps a genuine thrown exception even if response context is 502", () => {
      const event = {
        exception: {
          values: [
            {
              type: "TypeError",
              value: "Cannot read properties of undefined",
              mechanism: { type: "onunhandledrejection", handled: false },
            },
          ],
        },
        contexts: { response: { status_code: 502 } },
      } as ErrorEvent;
      expect(isNoisyHttpClientGatewayEvent(event)).toBe(false);
    });

    it("keeps an httpClient event with no readable status", () => {
      const event = {
        exception: {
          values: [
            {
              type: "Error",
              value: "HTTP Client Error with status code: unknown",
              mechanism: { type: "auto.http.client.fetch", handled: false },
            },
          ],
        },
      } as ErrorEvent;
      expect(isNoisyHttpClientGatewayEvent(event)).toBe(false);
    });

    it("keeps an httpClient gateway event with no request url", () => {
      const event = {
        exception: {
          values: [
            {
              type: "Error",
              value: "HTTP Client Error with status code: 503",
              mechanism: { type: "auto.http.client.fetch", handled: false },
            },
          ],
        },
        contexts: { response: { status_code: 503 } },
      } as ErrorEvent;
      expect(isNoisyHttpClientGatewayEvent(event)).toBe(false);
    });
  });
});

/**
 * Build an event carrying a single exception value (type + value), the shape
 * `captureConsoleIntegration` / global error handlers emit.
 */
function exceptionEvent(value: string, type = "Error"): ErrorEvent {
  return {
    exception: {
      values: [{ type, value, mechanism: { type: "generic", handled: false } }],
    },
  } as ErrorEvent;
}

/**
 * Build the shape `captureConsoleIntegration` produces for a string
 * `console.error(...)` with `attachStacktrace` unset (the default): a MESSAGE
 * event with `event.message` and NO `event.exception`. This is how the biggest
 * console-origin families (NextAuth CLIENT_FETCH_ERROR, PostHog notices, the
 * Next.js `_error.js` artifact) actually reach `beforeSend` in production.
 */
function messageEvent(message: string): ErrorEvent {
  return { message } as ErrorEvent;
}

/** Same, but the text lives on `event.logentry.message` (defensive fallback). */
function logentryEvent(message: string): ErrorEvent {
  return { logentry: { message } } as ErrorEvent;
}

describe("isDenylistedNoiseEvent", () => {
  describe("A. drops browser/transport failures (whole-message match)", () => {
    it("drops Chrome 'Failed to fetch'", () => {
      expect(isDenylistedNoiseEvent(exceptionEvent("Failed to fetch"))).toBe(
        true,
      );
    });

    it("drops Chrome 'Failed to fetch (hostname)' (trailing parenthetical)", () => {
      expect(
        isDenylistedNoiseEvent(
          exceptionEvent("Failed to fetch (cloud.langfuse.com)"),
        ),
      ).toBe(true);
      // also when wrapped by TRPCClientError
      expect(
        isDenylistedNoiseEvent(
          exceptionEvent(
            "TRPCClientError: Failed to fetch (cloud.langfuse.com)",
          ),
        ),
      ).toBe(true);
    });

    it("drops Firefox 'NetworkError when attempting to fetch resource' (with trailing period)", () => {
      expect(
        isDenylistedNoiseEvent(
          exceptionEvent("NetworkError when attempting to fetch resource."),
        ),
      ).toBe(true);
    });

    it("drops Safari/WebKit 'Load failed'", () => {
      expect(isDenylistedNoiseEvent(exceptionEvent("Load failed"))).toBe(true);
    });

    it("drops the transport failure when wrapped by TRPCClientError", () => {
      expect(
        isDenylistedNoiseEvent(
          exceptionEvent("TRPCClientError: Failed to fetch"),
        ),
      ).toBe(true);
    });

    it("drops Response.json() on a non-JSON body", () => {
      expect(
        isDenylistedNoiseEvent(
          exceptionEvent(
            "Failed to execute 'json' on 'Response': Unexpected end of JSON input",
          ),
        ),
      ).toBe(true);
    });

    it("drops an HTML error page parsed as JSON (json-parse signature + <html)", () => {
      expect(
        isDenylistedNoiseEvent(
          exceptionEvent(
            `Unexpected token '<', "<html>\n<head>"... is not valid JSON`,
            "SyntaxError",
          ),
        ),
      ).toBe(true);
    });
  });

  describe("B. drops NextAuth session-poll CLIENT_FETCH_ERROR", () => {
    // NextAuth logs a STRING via console.error, so this arrives as a MESSAGE
    // event (no exception) — the shape captureConsoleIntegration produces.
    it("drops the [next-auth][error][CLIENT_FETCH_ERROR] log (message event)", () => {
      expect(
        isDenylistedNoiseEvent(
          messageEvent(
            "[next-auth][error][CLIENT_FETCH_ERROR] https://cloud.langfuse.com/api/auth/session Failed to fetch",
          ),
        ),
      ).toBe(true);
    });

    it("drops it when the text lives on event.logentry.message", () => {
      expect(
        isDenylistedNoiseEvent(
          logentryEvent(
            "[next-auth][error][CLIENT_FETCH_ERROR] https://cloud.langfuse.com/api/auth/session Load failed",
          ),
        ),
      ).toBe(true);
    });
  });

  describe("C. drops expected browser-benign / vendor artifacts", () => {
    it("drops a clipboard permission denial (NotAllowedError + writeText)", () => {
      expect(
        isDenylistedNoiseEvent(
          exceptionEvent(
            "Failed to execute 'writeText' on 'Clipboard': Write permission denied.",
            "NotAllowedError",
          ),
        ),
      ).toBe(true);
    });

    // Firefox (and Chromium) reject HTMLMediaElement resource selection /
    // autoplay as an unhandled NotSupportedError when the codec is unavailable
    // (typical on Linux without proprietary codecs). The splash onboarding
    // videos and inline audio/video players already degrade in the UI; the
    // native promise has no app stack for us to catch.
    const unsupportedMediaResourceEvent = (
      value: string,
      type = "NotSupportedError",
      mechanismType = "auto.browser.global_handlers.onunhandledrejection",
    ): ErrorEvent =>
      ({
        exception: {
          values: [
            {
              type,
              value,
              mechanism: { type: mechanismType, handled: false },
            },
          ],
        },
      }) as ErrorEvent;

    it("drops Firefox HTMLMediaElement NotSupportedError (LANGFUSE-60C)", () => {
      expect(
        isDenylistedNoiseEvent(
          unsupportedMediaResourceEvent(
            "The media resource indicated by the src attribute or assigned media provider object was not suitable.",
          ),
        ),
      ).toBe(true);
    });

    it("drops Chromium HTMLMediaElement NotSupportedError", () => {
      expect(
        isDenylistedNoiseEvent(
          unsupportedMediaResourceEvent(
            "Failed to load because no supported source was found.",
          ),
        ),
      ).toBe(true);
    });

    it("drops the same Firefox media error from the global onerror handler", () => {
      expect(
        isDenylistedNoiseEvent(
          unsupportedMediaResourceEvent(
            "The media resource indicated by the src attribute or assigned media provider object was not suitable.",
            "NotSupportedError",
            "auto.browser.global_handlers.onerror",
          ),
        ),
      ).toBe(true);
    });

    it("drops an intentional request cancellation (AbortError)", () => {
      expect(
        isDenylistedNoiseEvent(
          exceptionEvent("signal is aborted without reason", "AbortError"),
        ),
      ).toBe(true);
      expect(
        isDenylistedNoiseEvent(
          exceptionEvent("The operation was aborted.", "AbortError"),
        ),
      ).toBe(true);
    });

    // PostHog logs a string via console.error, so it arrives as a MESSAGE event
    // (captureConsoleIntegration) — assert against that production shape.
    it("drops a third-party [PostHog.js] notice (message event)", () => {
      expect(
        isDenylistedNoiseEvent(
          messageEvent("[PostHog.js] was already loaded elsewhere."),
        ),
      ).toBe(true);
    });

    it("drops a kitesurf: localhost CORS console error (message event)", () => {
      expect(
        isDenylistedNoiseEvent(
          messageEvent(
            "kitesurf: Access to fetch at 'http://127.0.0.1:8765/' from origin 'https://example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check (preflight response status 403 is not ok)",
          ),
        ),
      ).toBe(true);
    });

    it("does not treat [kitesurf] wraps as denylist prefixes (dedicated predicate)", () => {
      expect(
        isDenylistedNoiseEvent(
          messageEvent(
            "[kitesurf] event listener for load threw: TypeError: Cannot create proxy with a non-object as target or handler",
          ),
        ),
      ).toBe(false);
    });

    it("drops the @sentry/nextjs '_error.js called with falsy error (…)' artifact", () => {
      // Real shape: captureException(`_error.js called with falsy error (${err})`)
      // → exception event whose value STARTS with the prefix.
      expect(
        isDenylistedNoiseEvent(
          exceptionEvent("_error.js called with falsy error (undefined)"),
        ),
      ).toBe(true);
      expect(
        isDenylistedNoiseEvent(
          exceptionEvent("_error.js called with falsy error (null)"),
        ),
      ).toBe(true);
    });
  });

  describe("D. drops known-benign non-Error promise rejections (exact value denylist)", () => {
    // Real shape (LANGFUSE-5T9/5TA): SDK-synthesized `UnhandledRejection` type,
    // `onunhandledrejection` mechanism, NO stack — grouping falls back to the
    // stringified value, so every new value minted a new fingerprint.
    const nonErrorRejectionEvent = (rejectionValue: string): ErrorEvent =>
      ({
        exception: {
          values: [
            {
              type: "UnhandledRejection",
              value: `Non-Error promise rejection captured with value: ${rejectionValue}`,
              mechanism: {
                type: "auto.browser.global_handlers.onunhandledrejection",
                handled: false,
              },
            },
          ],
        },
      }) as ErrorEvent;

    it("drops the wallet/extension shim rejection (LANGFUSE-5T9)", () => {
      expect(
        isDenylistedNoiseEvent(
          nonErrorRejectionEvent("Not implemented on this platform"),
        ),
      ).toBe(true);
    });

    it("drops the empty `Promise.reject(undefined)` rejection (LANGFUSE-5TA)", () => {
      expect(isDenylistedNoiseEvent(nonErrorRejectionEvent("undefined"))).toBe(
        true,
      );
    });

    it("drops the Outlook SafeLinks scanner artifact (LANGFUSE-11Z, variable tail)", () => {
      expect(
        isDenylistedNoiseEvent(
          nonErrorRejectionEvent(
            "Object Not Found Matching Id:2, MethodName:update, ParamCount:4",
          ),
        ),
      ).toBe(true);
    });
  });

  describe("E. drops environmental storage-access SecurityError (console-captured only)", () => {
    // Real shape (LANGFUSE-5TC/5TD/5TE/5TF): our useLocalStorage catch logs the
    // DOMException via console.error → captureConsoleIntegration re-captures it
    // as an exception event (mechanism `auto.core.capture_console`) carrying
    // the browser-generated message.
    const consoleCapturedStorageDenial = (value: string): ErrorEvent =>
      ({
        exception: {
          values: [
            {
              type: "SecurityError",
              value,
              mechanism: { type: "auto.core.capture_console", handled: true },
            },
          ],
        },
      }) as ErrorEvent;

    it("drops the localStorage access denial (LANGFUSE-5TC/5TD/5TE/5TF)", () => {
      expect(
        isDenylistedNoiseEvent(
          consoleCapturedStorageDenial(
            "Failed to read the 'localStorage' property from 'Window': Access is denied for this document.",
          ),
        ),
      ).toBe(true);
    });

    it("drops the sessionStorage variant of the same browser artifact", () => {
      expect(
        isDenylistedNoiseEvent(
          consoleCapturedStorageDenial(
            "Failed to read the 'sessionStorage' property from 'Window': Access is denied for this document.",
          ),
        ),
      ).toBe(true);
    });

    it("KEEPS an UNCAUGHT storage SecurityError (page crash via global onerror)", () => {
      // A bare storage read during render that crashes the page arrives via the
      // global handler, not capture_console — that is a real diagnostic and
      // must survive.
      const event = {
        exception: {
          values: [
            {
              type: "SecurityError",
              value:
                "Failed to read the 'localStorage' property from 'Window': Access is denied for this document.",
              mechanism: {
                type: "auto.browser.global_handlers.onerror",
                handled: false,
              },
            },
          ],
        },
      } as ErrorEvent;
      expect(isDenylistedNoiseEvent(event)).toBe(false);
    });
  });

  describe("A. transport failures also drop when they arrive as message events", () => {
    it("drops a message-event 'Failed to fetch'", () => {
      expect(isDenylistedNoiseEvent(messageEvent("Failed to fetch"))).toBe(
        true,
      );
    });

    it("drops a message-event HTML-parsed-as-JSON error", () => {
      expect(
        isDenylistedNoiseEvent(
          messageEvent(
            `Unexpected token '<', "<html>\n<head>"... is not valid JSON`,
          ),
        ),
      ).toBe(true);
    });
  });

  describe("F. drops browser-extension dynamic import() failures (no stack, so denyUrls misses them)", () => {
    // Real shape (LANGFUSE-5ZS): Chrome TypeError logged via console.error when
    // an extension's own import() fails. No stack frames, so denyUrls (which
    // matches frame filenames) never fires. captureConsoleIntegration then
    // mints a new fingerprint per extension-id + hashed asset.
    const consoleCapturedExtensionImportFailure = (
      moduleUrl: string,
    ): ErrorEvent =>
      ({
        exception: {
          values: [
            {
              type: "TypeError",
              value: `Failed to fetch dynamically imported module: ${moduleUrl}`,
              mechanism: {
                type: "auto.core.capture_console",
                handled: true,
              },
            },
          ],
        },
      }) as ErrorEvent;

    it("drops a Chrome extension module-load TypeError (LANGFUSE-5ZS)", () => {
      expect(
        isDenylistedNoiseEvent(
          consoleCapturedExtensionImportFailure(
            "chrome-extension://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/assets/content-end.js",
          ),
        ),
      ).toBe(true);
    });

    it("drops the same failure as a message event (TypeError prefix, no exception)", () => {
      expect(
        isDenylistedNoiseEvent(
          messageEvent(
            "TypeError: Failed to fetch dynamically imported module: chrome-extension://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/assets/content-end.js",
          ),
        ),
      ).toBe(true);
    });

    it("drops the Firefox / Safari / Edge extension-protocol siblings", () => {
      expect(
        isDenylistedNoiseEvent(
          consoleCapturedExtensionImportFailure(
            "moz-extension://aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee/content.js",
          ),
        ),
      ).toBe(true);
      expect(
        isDenylistedNoiseEvent(
          consoleCapturedExtensionImportFailure(
            "safari-extension://aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee/content.js",
          ),
        ),
      ).toBe(true);
      expect(
        isDenylistedNoiseEvent(
          consoleCapturedExtensionImportFailure(
            "ms-browser-extension://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/content.js",
          ),
        ),
      ).toBe(true);
    });
  });

  describe("G. drops Android WebView Java-bridge listener failures", () => {
    // Real shape (LANGFUSE-60G): Chrome Mobile WebView throws Chromium's
    // `Error invoking <method>: Java bridge method invocation error` from a
    // host-app `@JavascriptInterface` during `unload`. Sentry's
    // addEventListener wrap captures it — stack is SDK wrap + anonymous
    // `batch` frames, no Langfuse frames.
    const webViewJavaBridgeEvent = (
      value: string,
      mechanismType = "auto.browser.browserapierrors.addEventListener",
    ): ErrorEvent =>
      ({
        exception: {
          values: [
            {
              type: "Error",
              value,
              mechanism: { type: mechanismType, handled: false },
            },
          ],
        },
      }) as ErrorEvent;

    it("drops the LANGFUSE-60G addEventListener batch-bridge error", () => {
      expect(
        isDenylistedNoiseEvent(
          webViewJavaBridgeEvent(
            "Error invoking batch: Java bridge method invocation error",
          ),
        ),
      ).toBe(true);
    });

    it("drops the same Chromium wording for another Java method name", () => {
      expect(
        isDenylistedNoiseEvent(
          webViewJavaBridgeEvent(
            "Error invoking onPause: Java bridge method invocation error",
          ),
        ),
      ).toBe(true);
    });

    it("drops the same wording via a global browser handler", () => {
      expect(
        isDenylistedNoiseEvent(
          webViewJavaBridgeEvent(
            "Error invoking batch: Java bridge method invocation error",
            "auto.browser.global_handlers.onerror",
          ),
        ),
      ).toBe(true);
    });
  });

  describe("H. drops Next.js App Router Invalid URL on data: documents", () => {
    // Real shape (LANGFUSE-60K): Electron loads the Next.js HTML as a
    // `data:text/html,…` document. App Router does
    // `new URL(canonicalUrl, window.location.href)` and Chromium throws
    // because a data: URL is not a valid base. Mechanism is the global
    // onerror handler; stack is Next.js Router only.
    const dataDocumentInvalidUrlEvent = (
      value: string,
      url: string,
      mechanismType = "auto.browser.global_handlers.onerror",
    ): ErrorEvent =>
      ({
        exception: {
          values: [
            {
              type: "TypeError",
              value,
              mechanism: { type: mechanismType, handled: false },
            },
          ],
        },
        request: { url },
      }) as ErrorEvent;

    it("drops the Chromium constructor TypeError on a data: page URL", () => {
      expect(
        isDenylistedNoiseEvent(
          dataDocumentInvalidUrlEvent(
            "Failed to construct 'URL': Invalid URL",
            "data:text/html,<!DOCTYPE html><html></html>",
          ),
        ),
      ).toBe(true);
    });

    it("drops the same TypeError when only tags.url is the data: document", () => {
      const event = {
        exception: {
          values: [
            {
              type: "TypeError",
              value: "Failed to construct 'URL': Invalid URL",
              mechanism: {
                type: "auto.browser.global_handlers.onerror",
                handled: false,
              },
            },
          ],
        },
        tags: { url: "data:text/html,probe" },
      } as unknown as ErrorEvent;
      expect(isDenylistedNoiseEvent(event)).toBe(true);
    });

    it("drops the Firefox constructor wording on a data: page URL", () => {
      expect(
        isDenylistedNoiseEvent(
          dataDocumentInvalidUrlEvent(
            "URL constructor: /health is not a valid URL",
            "data:text/html,probe",
          ),
        ),
      ).toBe(true);
    });
  });

  describe("I. drops Chrome extension port lastError (no stack, so denyUrls misses them)", () => {
    // Real shape (LANGFUSE-614): Chrome rejects `chrome.runtime.sendMessage`
    // / `connect` when the extension background or content-script port is
    // gone. Unhandled rejection, no frames, so denyUrls never matches.
    const chromeExtensionPortEvent = (
      value: string,
      mechanismType = "auto.browser.global_handlers.onunhandledrejection",
    ): ErrorEvent =>
      ({
        exception: {
          values: [
            {
              type: "Error",
              value,
              mechanism: { type: mechanismType, handled: false },
            },
          ],
        },
      }) as ErrorEvent;

    it("drops the LANGFUSE-614 receiving-end lastError", () => {
      expect(
        isDenylistedNoiseEvent(
          chromeExtensionPortEvent(
            "Could not establish connection. Receiving end does not exist.",
          ),
        ),
      ).toBe(true);
    });

    it("drops the same wording without a trailing period", () => {
      expect(
        isDenylistedNoiseEvent(
          chromeExtensionPortEvent(
            "Could not establish connection. Receiving end does not exist",
          ),
        ),
      ).toBe(true);
    });

    it("drops the sibling Chrome lastError for a closed message port", () => {
      expect(
        isDenylistedNoiseEvent(
          chromeExtensionPortEvent(
            "The message port closed before a response was received.",
          ),
        ),
      ).toBe(true);
    });

    it("drops the same wording via a global onerror handler", () => {
      expect(
        isDenylistedNoiseEvent(
          chromeExtensionPortEvent(
            "Could not establish connection. Receiving end does not exist.",
            "auto.browser.global_handlers.onerror",
          ),
        ),
      ).toBe(true);
    });
  });

  describe("J. drops console-captured getter-only window.__NEXT_DATA__ TypeError", () => {
    // Real shape (LANGFUSE-61R): Next.js Pages Router `initialize()` does
    // `window.__NEXT_DATA__ = initialData`. When that Window property is
    // getter-only, Chromium throws. An injected wrapper logs
    // `Error was not caught` + the TypeError; captureConsoleIntegration
    // mints the issue. Stack is Next.js / turbopack only. 0 users.
    const getterOnlyWindowNextDataEvent = (
      value: string,
      mechanismType = "auto.core.capture_console",
      type = "TypeError",
    ): ErrorEvent =>
      ({
        exception: {
          values: [
            {
              type,
              value,
              mechanism: { type: mechanismType, handled: true },
            },
          ],
        },
      }) as ErrorEvent;

    it("drops the LANGFUSE-61R Chromium TypeError via capture_console", () => {
      expect(
        isDenylistedNoiseEvent(
          getterOnlyWindowNextDataEvent(
            "Cannot set property __NEXT_DATA__ of #<Window> which has only a getter",
          ),
        ),
      ).toBe(true);
    });

    it("drops the same wording with a trailing period", () => {
      expect(
        isDenylistedNoiseEvent(
          getterOnlyWindowNextDataEvent(
            "Cannot set property __NEXT_DATA__ of #<Window> which has only a getter.",
          ),
        ),
      ).toBe(true);
    });
  });

  describe("K. drops Safari password-manager addMore.click (document-attributed)", () => {
    // Real shape: Safari 26.5 on settings API keys. Injected
    // password-manager / autofill JS does `addMore.click()` after a key is
    // created. `addMore` is undefined. WebKit's TypeError includes the
    // expression. Stack is document-attributed global code — no /_next/
    // chunk — so denyUrls cannot match. Langfuse has no `addMore` identifier.
    const safariAddMoreClickEvent = (
      value: string,
      mechanismType = "auto.browser.global_handlers.onerror",
      frames?: { filename: string; function?: string }[],
    ): ErrorEvent =>
      ({
        exception: {
          values: [
            {
              type: "TypeError",
              value,
              mechanism: { type: mechanismType, handled: false },
              ...(frames
                ? {
                    stacktrace: {
                      frames: frames.map((frame) => ({
                        filename: frame.filename,
                        function: frame.function ?? "?",
                      })),
                    },
                  }
                : {}),
            },
          ],
        },
      }) as ErrorEvent;

    it("drops the WebKit addMore.click TypeError", () => {
      expect(
        isDenylistedNoiseEvent(
          safariAddMoreClickEvent(
            "undefined is not an object (evaluating 'addMore.click')",
          ),
        ),
      ).toBe(true);
    });

    it("drops the null WebKit variant and a trailing period", () => {
      expect(
        isDenylistedNoiseEvent(
          safariAddMoreClickEvent(
            "null is not an object (evaluating 'addMore.click').",
          ),
        ),
      ).toBe(true);
    });

    it("drops the same wording with click()", () => {
      expect(
        isDenylistedNoiseEvent(
          safariAddMoreClickEvent(
            "undefined is not an object (evaluating 'addMore.click()')",
          ),
        ),
      ).toBe(true);
    });

    it("drops the same wording with document-attributed frames", () => {
      expect(
        isDenylistedNoiseEvent(
          safariAddMoreClickEvent(
            "undefined is not an object (evaluating 'addMore.click')",
            "auto.browser.global_handlers.onerror",
            [
              {
                filename: "app:///project/example/settings/api-keys",
                function: "global code",
              },
            ],
          ),
        ),
      ).toBe(true);
    });
  });

  // The heart of the safety contract: prove that real / similar-looking errors
  // are NOT dropped. If any of these regress to `true`, a real bug would be
  // hidden from Sentry.
  describe("KEEPS real errors (never masks a genuine app error)", () => {
    it("keeps a real tRPC error carrying the server's message", () => {
      expect(
        isDenylistedNoiseEvent(exceptionEvent("TRPCClientError: UNAUTHORIZED")),
      ).toBe(false);
      expect(
        isDenylistedNoiseEvent(
          exceptionEvent(
            "TRPCClientError: You are not a member of this organization",
          ),
        ),
      ).toBe(false);
    });

    it("keeps an app error that merely QUOTES a transport phrase", () => {
      // Real messages seen in the codebase — must survive.
      expect(
        isDenylistedNoiseEvent(
          exceptionEvent(
            "Failed to fetch created model",
            "InvalidRequestError",
          ),
        ),
      ).toBe(false);
      expect(
        isDenylistedNoiseEvent(
          exceptionEvent(
            "Failed to fetch channels. Please check your Slack connection and try again.",
          ),
        ),
      ).toBe(false);
      expect(
        isDenylistedNoiseEvent(
          exceptionEvent("Load failed for dataset export job 42"),
        ),
      ).toBe(false);
      // Ends in a parenthetical, but the non-parenthetical part is longer than a
      // bare transport phrase, so stripping the trailing `(…)` still leaves a
      // non-matching whole message — must survive.
      expect(
        isDenylistedNoiseEvent(
          exceptionEvent("Failed to fetch traces (batch 3 of 5)"),
        ),
      ).toBe(false);
    });

    it("keeps a CORS console error that is not namespaced by kitesurf", () => {
      expect(
        isDenylistedNoiseEvent(
          messageEvent(
            "Access to fetch at 'https://example.com/api' from origin 'https://example.com' has been blocked by CORS policy",
          ),
        ),
      ).toBe(false);
    });

    it("keeps an app error that merely mentions kitesurf mid-message", () => {
      expect(
        isDenylistedNoiseEvent(
          messageEvent("Failed to load kitesurf: connection timed out"),
        ),
      ).toBe(false);
    });

    it("keeps a genuine SyntaxError with no <html (not an HTML-as-JSON artifact)", () => {
      expect(
        isDenylistedNoiseEvent(
          exceptionEvent("Unexpected end of JSON input", "SyntaxError"),
        ),
      ).toBe(false);
      expect(
        isDenylistedNoiseEvent(
          exceptionEvent(
            `Unexpected token 'x', "xyz" is not valid JSON`,
            "SyntaxError",
          ),
        ),
      ).toBe(false);
    });

    it("keeps the chunk-load / stale-deploy SyntaxError (handled separately, not dropped)", () => {
      // Script parsing an HTML page: has `Unexpected token '<'` and `<html` but
      // NOT the JSON-parse `is not valid JSON` suffix, so A5 must not catch it.
      expect(
        isDenylistedNoiseEvent(
          exceptionEvent(
            "Unexpected token '<'\n<html><body>502 Bad Gateway</body></html>",
            "SyntaxError",
          ),
        ),
      ).toBe(false);
    });

    it("keeps a real thrown TypeError", () => {
      expect(
        isDenylistedNoiseEvent(
          exceptionEvent(
            "Cannot read properties of undefined (reading 'map')",
            "TypeError",
          ),
        ),
      ).toBe(false);
    });

    it("keeps a first-party chunk dynamic-import failure (stale deploy / CDN)", () => {
      // Same Chrome message as LANGFUSE-5ZS, but the URL is ours. This is a
      // real client failure (stale tab after deploy, truncated download) and
      // must still reach Sentry (grouped, not dropped).
      expect(
        isDenylistedNoiseEvent(
          exceptionEvent(
            "Failed to fetch dynamically imported module: https://us.cloud.langfuse.com/_next/static/chunks/app.js",
            "TypeError",
          ),
        ),
      ).toBe(false);
      expect(
        isDenylistedNoiseEvent(
          messageEvent(
            "Failed to fetch dynamically imported module: http://localhost:3000/_next/static/chunks/app.js",
          ),
        ),
      ).toBe(false);
    });

    it("keeps a first-party chunk failure even if an extension URL appears later in the text", () => {
      // The protocol must be on the FAILED module URL, not anywhere in the
      // event text (query/fragment/trailing console noise).
      expect(
        isDenylistedNoiseEvent(
          exceptionEvent(
            "Failed to fetch dynamically imported module: https://us.cloud.langfuse.com/_next/static/chunks/app.js?ref=chrome-extension://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/x.js",
            "TypeError",
          ),
        ),
      ).toBe(false);
      expect(
        isDenylistedNoiseEvent(
          messageEvent(
            "Failed to fetch dynamically imported module: https://us.cloud.langfuse.com/_next/static/chunks/app.js chrome-extension://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/x.js",
          ),
        ),
      ).toBe(false);
    });

    it("keeps a non-clipboard NotAllowedError (autoplay/fullscreen)", () => {
      expect(
        isDenylistedNoiseEvent(
          exceptionEvent(
            "play() failed because the user didn't interact with the document first",
            "NotAllowedError",
          ),
        ),
      ).toBe(false);
    });

    it("keeps a non-media NotSupportedError (WebGL / WebRTC / etc.)", () => {
      expect(
        isDenylistedNoiseEvent(
          exceptionEvent(
            "The operation is not supported.",
            "NotSupportedError",
          ),
        ),
      ).toBe(false);
    });

    it("keeps an app-captured NotSupportedError even with the media wording", () => {
      // captureException / generic mechanism is our code reporting a real
      // failure. Only the browser global handler shape is dropped.
      expect(
        isDenylistedNoiseEvent(
          exceptionEvent(
            "The media resource indicated by the src attribute or assigned media provider object was not suitable.",
            "NotSupportedError",
          ),
        ),
      ).toBe(false);
    });

    it("keeps a TypeError that merely quotes the media wording", () => {
      expect(
        isDenylistedNoiseEvent(
          exceptionEvent(
            "The media resource indicated by the src attribute or assigned media provider object was not suitable.",
            "TypeError",
          ),
        ),
      ).toBe(false);
    });

    it("keeps the generic prod error-boundary string (LANGFUSE-1MY, deliberately not dropped)", () => {
      expect(
        isDenylistedNoiseEvent(
          exceptionEvent(
            "A client-side exception has occurred while loading cloud.langfuse.com, see the browser console for more information.",
          ),
        ),
      ).toBe(false);
    });

    it("keeps an OAuthCallback sign-in error (deliberately not dropped)", () => {
      expect(
        isDenylistedNoiseEvent(exceptionEvent("OAuthCallback error", "Error")),
      ).toBe(false);
    });

    it("keeps a different next-auth error (only CLIENT_FETCH_ERROR is dropped)", () => {
      expect(
        isDenylistedNoiseEvent(
          messageEvent("[next-auth][error][SIGNIN_OAUTH_ERROR] boom"),
        ),
      ).toBe(false);
    });

    it("keeps a phrase-quoting app error delivered as a MESSAGE event", () => {
      // Same safety contract on the message-event path: whole-message equality
      // means a longer app message is not caught even without an exception.
      expect(
        isDenylistedNoiseEvent(messageEvent("Failed to fetch created model")),
      ).toBe(false);
    });

    it("keeps the generic prod error-boundary string as a MESSAGE event (still excluded)", () => {
      // captureConsoleIntegration delivers this 1MY string as a message event;
      // it must survive on that path too, not just the exception path.
      expect(
        isDenylistedNoiseEvent(
          messageEvent(
            "A client-side exception has occurred while loading cloud.langfuse.com, see the browser console for more information.",
          ),
        ),
      ).toBe(false);
    });

    it("keeps auth/permission and query-timeout errors (routed to UX, not dropped)", () => {
      expect(isDenylistedNoiseEvent(exceptionEvent("UNAUTHORIZED"))).toBe(
        false,
      );
      expect(
        isDenylistedNoiseEvent(
          exceptionEvent("Query could not be completed within the time limit"),
        ),
      ).toBe(false);
    });

    it("keeps a non-Error rejection with an UNKNOWN value (could be app code)", () => {
      const event = {
        exception: {
          values: [
            {
              type: "UnhandledRejection",
              value:
                "Non-Error promise rejection captured with value: Something went wrong loading traces",
              mechanism: {
                type: "auto.browser.global_handlers.onunhandledrejection",
                handled: false,
              },
            },
          ],
        },
      } as ErrorEvent;
      expect(isDenylistedNoiseEvent(event)).toBe(false);
    });

    it("keeps the object-shaped rejection variant (has carried real failures)", () => {
      // LANGFUSE-1BB: `code, message, stack` payloads — a serialized error.
      expect(
        isDenylistedNoiseEvent(
          exceptionEvent(
            "Object captured as promise rejection with keys: code, message, stack",
            "UnhandledRejection",
          ),
        ),
      ).toBe(false);
    });

    it("keeps a real unhandled rejection carrying an Error object", () => {
      // A rejected real Error keeps its own type — never `UnhandledRejection`.
      const event = {
        exception: {
          values: [
            {
              type: "TypeError",
              value: "Cannot read properties of undefined (reading 'map')",
              mechanism: {
                type: "auto.browser.global_handlers.onunhandledrejection",
                handled: false,
              },
            },
          ],
        },
      } as ErrorEvent;
      expect(isDenylistedNoiseEvent(event)).toBe(false);
    });

    it("keeps a benign-looking rejection value with extra text (exact match only)", () => {
      expect(
        isDenylistedNoiseEvent(
          exceptionEvent(
            "Non-Error promise rejection captured with value: undefined is not a function",
            "UnhandledRejection",
          ),
        ),
      ).toBe(false);
    });

    it("keeps a real SecurityError from app-adjacent logic (cross-origin frame access)", () => {
      expect(
        isDenylistedNoiseEvent(
          exceptionEvent(
            'Blocked a frame with origin "https://cloud.langfuse.com" from accessing a cross-origin frame.',
            "SecurityError",
          ),
        ),
      ).toBe(false);
    });

    it("keeps the storage-denial message when the type is NOT SecurityError", () => {
      // Proves the type guard: an app error merely quoting the message survives.
      expect(
        isDenylistedNoiseEvent(
          exceptionEvent(
            "Failed to read the 'localStorage' property from 'Window': Access is denied for this document.",
            "Error",
          ),
        ),
      ).toBe(false);
    });

    it("keeps an app-captured Java-bridge phrase (not a Sentry browser wrap)", () => {
      // Mechanism guard: captureException / capture_console must still surface
      // if our code ever throws or logs this wording.
      expect(
        isDenylistedNoiseEvent(
          exceptionEvent(
            "Error invoking batch: Java bridge method invocation error",
          ),
        ),
      ).toBe(false);
      const consoleCaptured = {
        exception: {
          values: [
            {
              type: "Error",
              value:
                "Error invoking batch: Java bridge method invocation error",
              mechanism: {
                type: "auto.core.capture_console",
                handled: true,
              },
            },
          ],
        },
      } as ErrorEvent;
      expect(isDenylistedNoiseEvent(consoleCaptured)).toBe(false);
    });

    it("keeps an UNCAUGHT getter-only window.__NEXT_DATA__ TypeError (hydration crash)", () => {
      // LANGFUSE-61R drops only the console-captured sibling. A global
      // onerror means Next.js Pages Router failed to boot — keep it.
      const event = {
        exception: {
          values: [
            {
              type: "TypeError",
              value:
                "Cannot set property __NEXT_DATA__ of #<Window> which has only a getter",
              mechanism: {
                type: "auto.browser.global_handlers.onerror",
                handled: false,
              },
            },
          ],
        },
      } as ErrorEvent;
      expect(isDenylistedNoiseEvent(event)).toBe(false);
    });

    it("keeps an app-captured getter-only window.__NEXT_DATA__ TypeError", () => {
      expect(
        isDenylistedNoiseEvent(
          exceptionEvent(
            "Cannot set property __NEXT_DATA__ of #<Window> which has only a getter",
            "TypeError",
          ),
        ),
      ).toBe(false);
    });

    it("keeps a longer message that merely quotes the __NEXT_DATA__ TypeError", () => {
      const event = {
        exception: {
          values: [
            {
              type: "TypeError",
              value:
                "hydrate failed: Cannot set property __NEXT_DATA__ of #<Window> which has only a getter",
              mechanism: {
                type: "auto.core.capture_console",
                handled: true,
              },
            },
          ],
        },
      } as ErrorEvent;
      expect(isDenylistedNoiseEvent(event)).toBe(false);
    });

    it("keeps a listener TypeError that is not the Chromium Java-bridge wording", () => {
      const event = {
        exception: {
          values: [
            {
              type: "TypeError",
              value: "Cannot read properties of undefined (reading 'map')",
              mechanism: {
                type: "auto.browser.browserapierrors.addEventListener",
                handled: false,
              },
            },
          ],
        },
      } as ErrorEvent;
      expect(isDenylistedNoiseEvent(event)).toBe(false);
    });

    it("keeps the same Invalid URL TypeError on an https page (real app bug)", () => {
      const event = {
        exception: {
          values: [
            {
              type: "TypeError",
              value: "Failed to construct 'URL': Invalid URL",
              mechanism: {
                type: "auto.browser.global_handlers.onerror",
                handled: false,
              },
            },
          ],
        },
        request: { url: "https://cloud.langfuse.com/project/abc/traces" },
      } as ErrorEvent;
      expect(isDenylistedNoiseEvent(event)).toBe(false);
    });

    it("keeps an app-captured Invalid URL TypeError even on a data: page", () => {
      // Mechanism guard: captureException / capture_console must still surface.
      expect(
        isDenylistedNoiseEvent(
          exceptionEvent("Failed to construct 'URL': Invalid URL", "TypeError"),
        ),
      ).toBe(false);
      const consoleCaptured = {
        exception: {
          values: [
            {
              type: "TypeError",
              value: "Failed to construct 'URL': Invalid URL",
              mechanism: {
                type: "auto.core.capture_console",
                handled: true,
              },
            },
          ],
        },
        request: { url: "data:text/html,probe" },
      } as ErrorEvent;
      expect(isDenylistedNoiseEvent(consoleCaptured)).toBe(false);
    });

    it("keeps a different TypeError on a data: page", () => {
      const event = {
        exception: {
          values: [
            {
              type: "TypeError",
              value: "Cannot read properties of undefined (reading 'map')",
              mechanism: {
                type: "auto.browser.global_handlers.onerror",
                handled: false,
              },
            },
          ],
        },
        request: { url: "data:text/html,probe" },
      } as ErrorEvent;
      expect(isDenylistedNoiseEvent(event)).toBe(false);
    });

    it("keeps a longer app message that merely quotes the Java-bridge suffix", () => {
      const event = {
        exception: {
          values: [
            {
              type: "Error",
              value:
                "Failed to persist playground batch: Java bridge method invocation error",
              mechanism: {
                type: "auto.browser.browserapierrors.addEventListener",
                handled: false,
              },
            },
          ],
        },
      } as ErrorEvent;
      expect(isDenylistedNoiseEvent(event)).toBe(false);
    });

    it("keeps an app-captured Chrome port lastError (not a Sentry browser wrap)", () => {
      expect(
        isDenylistedNoiseEvent(
          exceptionEvent(
            "Could not establish connection. Receiving end does not exist.",
          ),
        ),
      ).toBe(false);
      const consoleCaptured = {
        exception: {
          values: [
            {
              type: "Error",
              value:
                "Could not establish connection. Receiving end does not exist.",
              mechanism: {
                type: "auto.core.capture_console",
                handled: true,
              },
            },
          ],
        },
      } as ErrorEvent;
      expect(isDenylistedNoiseEvent(consoleCaptured)).toBe(false);
    });
    it("keeps a longer app message that merely quotes the Chrome port lastError", () => {
      const event = {
        exception: {
          values: [
            {
              type: "Error",
              value:
                "Worker handshake failed: Could not establish connection. Receiving end does not exist.",
              mechanism: {
                type: "auto.browser.global_handlers.onunhandledrejection",
                handled: false,
              },
            },
          ],
        },
      } as ErrorEvent;
      expect(isDenylistedNoiseEvent(event)).toBe(false);
    });

    it("keeps a longer app message that merely quotes addMore.click", () => {
      const event = {
        exception: {
          values: [
            {
              type: "TypeError",
              value:
                "Failed to copy secret: undefined is not an object (evaluating 'addMore.click')",
              mechanism: {
                type: "auto.browser.global_handlers.onerror",
                handled: false,
              },
            },
          ],
        },
      } as ErrorEvent;
      expect(isDenylistedNoiseEvent(event)).toBe(false);
    });

    it("keeps a different WebKit evaluating TypeError", () => {
      const event = {
        exception: {
          values: [
            {
              type: "TypeError",
              value: "undefined is not an object (evaluating 'foo.bar')",
              mechanism: {
                type: "auto.browser.global_handlers.onerror",
                handled: false,
              },
            },
          ],
        },
      } as ErrorEvent;
      expect(isDenylistedNoiseEvent(event)).toBe(false);
    });

    it("keeps Chromium's generic undefined.click TypeError", () => {
      const event = {
        exception: {
          values: [
            {
              type: "TypeError",
              value: "Cannot read properties of undefined (reading 'click')",
              mechanism: {
                type: "auto.browser.global_handlers.onerror",
                handled: false,
              },
            },
          ],
        },
      } as ErrorEvent;
      expect(isDenylistedNoiseEvent(event)).toBe(false);
    });

    it("keeps an app-captured addMore.click TypeError (not a Sentry browser wrap)", () => {
      expect(
        isDenylistedNoiseEvent(
          exceptionEvent(
            "undefined is not an object (evaluating 'addMore.click')",
            "TypeError",
          ),
        ),
      ).toBe(false);
      const consoleCaptured = {
        exception: {
          values: [
            {
              type: "TypeError",
              value: "undefined is not an object (evaluating 'addMore.click')",
              mechanism: {
                type: "auto.core.capture_console",
                handled: true,
              },
            },
          ],
        },
      } as ErrorEvent;
      expect(isDenylistedNoiseEvent(consoleCaptured)).toBe(false);
    });

    it("keeps the Safari addMore.click TypeError when a first-party chunk is on the stack", () => {
      const event = {
        exception: {
          values: [
            {
              type: "TypeError",
              value: "undefined is not an object (evaluating 'addMore.click')",
              mechanism: {
                type: "auto.browser.global_handlers.onerror",
                handled: false,
              },
              stacktrace: {
                frames: [
                  {
                    filename:
                      "https://us.cloud.langfuse.com/_next/static/chunks/pages/project/[projectId]/settings/[page]-abc.js",
                    function: "onClick",
                  },
                ],
              },
            },
          ],
        },
      } as ErrorEvent;
      expect(isDenylistedNoiseEvent(event)).toBe(false);
    });

    it("keeps an event with no exception values", () => {
      expect(
        isDenylistedNoiseEvent({ message: "some message" } as ErrorEvent),
      ).toBe(false);
    });

    it("keeps an event with an empty exception value", () => {
      expect(isDenylistedNoiseEvent(exceptionEvent(""))).toBe(false);
    });
  });
});

describe("isReactDevtoolsInternalEvent", () => {
  describe("drops React DevTools internal probes", () => {
    it("drops a message-event probe", () => {
      expect(
        isReactDevtoolsInternalEvent(
          messageEvent(
            "Cannot read properties of undefined (reading '__reactContextDevtoolDebugId')",
          ),
        ),
      ).toBe(true);
    });

    it("drops an exception-value variant", () => {
      expect(
        isReactDevtoolsInternalEvent(
          exceptionEvent(
            "Cannot read properties of undefined (reading '__reactContextDevtoolDebugId')",
            "TypeError",
          ),
        ),
      ).toBe(true);
    });

    it("drops it when the text lives on event.logentry.message", () => {
      expect(
        isReactDevtoolsInternalEvent(
          logentryEvent(
            "Cannot read properties of null (reading '__reactContextDevtoolDebugId')",
          ),
        ),
      ).toBe(true);
    });

    it("drops a mixed event: EMPTY exception value but text on message", () => {
      // An empty-string exception value is not nullish, so a naive `??` chain
      // would keep it and never look at `message`. `eventText` treats it as
      // absent, so this still matches.
      expect(
        isReactDevtoolsInternalEvent({
          exception: { values: [{ value: "" }] },
          message:
            "Cannot read properties of undefined (reading '__reactContextDevtoolDebugId')",
        } as unknown as Parameters<typeof isReactDevtoolsInternalEvent>[0]),
      ).toBe(true);
    });
  });

  // The safety contract: a suppression predicate must not swallow real errors.
  describe("KEEPS real errors (never masks a genuine app error)", () => {
    it("keeps a real thrown TypeError unrelated to DevTools", () => {
      expect(
        isReactDevtoolsInternalEvent(
          exceptionEvent("TypeError: cannot read x", "TypeError"),
        ),
      ).toBe(false);
    });

    it("keeps an unrelated message event", () => {
      expect(
        isReactDevtoolsInternalEvent(messageEvent("some unrelated message")),
      ).toBe(false);
    });

    it("keeps an event with no exception/message/logentry text", () => {
      expect(isReactDevtoolsInternalEvent({} as ErrorEvent)).toBe(false);
    });
  });
});

/**
 * Next.js route-loader `script.onerror`: capture_console from
 * `Error rendering page: ` + `Failed to load script: <hashed chunk URL>`.
 */
function chunkLoadErrorEvent(
  value = "Failed to load script: https://us.cloud.langfuse.com/_next/static/chunks/31w9e6884-o68.js",
): ErrorEvent {
  return {
    exception: {
      values: [
        {
          type: "Error",
          value,
          mechanism: { type: "auto.core.capture_console", handled: true },
          stacktrace: {
            frames: [
              {
                filename: "node_modules/next/src/client/route-loader.ts",
                function: "script.onerror",
              },
            ],
          },
        },
      ],
    },
  } as ErrorEvent;
}

describe("isStaleChunkLoadErrorEvent", () => {
  describe("matches first-party chunk LOAD failures (grouped, not dropped)", () => {
    it("matches Next.js route-loader script.onerror (hashed chunk URL)", () => {
      expect(isStaleChunkLoadErrorEvent(chunkLoadErrorEvent())).toBe(true);
    });

    it("matches regardless of the (per-deploy hashed) chunk filename", () => {
      expect(
        isStaleChunkLoadErrorEvent(
          chunkLoadErrorEvent(
            "Failed to load script: https://static-hipaa.langfuse.com/_next/static/chunks/abc123-xyz.js",
          ),
        ),
      ).toBe(true);
    });

    it("matches a first-party dynamic import() chunk failure", () => {
      expect(
        isStaleChunkLoadErrorEvent(
          exceptionEvent(
            "Failed to fetch dynamically imported module: https://us.cloud.langfuse.com/_next/static/chunks/app.js",
            "TypeError",
          ),
        ),
      ).toBe(true);
      expect(
        isStaleChunkLoadErrorEvent(
          messageEvent(
            "Failed to fetch dynamically imported module: http://localhost:3000/_next/static/chunks/app.js",
          ),
        ),
      ).toBe(true);
    });

    it("is grouped by beforeSend, NOT dropped by the denylist", () => {
      expect(isDenylistedNoiseEvent(chunkLoadErrorEvent())).toBe(false);
    });
  });

  describe("NEVER matches unrelated load failures", () => {
    it("keeps a third-party script.onerror (no Next chunk path)", () => {
      expect(
        isStaleChunkLoadErrorEvent(
          chunkLoadErrorEvent(
            "Failed to load script: https://cdn.example.com/vendor.js",
          ),
        ),
      ).toBe(false);
    });

    it("keeps UI copy that quotes Failed to load without a chunk URL", () => {
      expect(
        isStaleChunkLoadErrorEvent(
          exceptionEvent("Failed to load evaluators: upstream timed out"),
        ),
      ).toBe(false);
    });

    it("keeps worker importScripts failures (separate family)", () => {
      expect(
        isStaleChunkLoadErrorEvent(
          exceptionEvent(
            "[ELK layout] worker failed to load: Uncaught NetworkError: Failed to execute 'importScripts' on 'WorkerGlobalScope': The script at 'https://us.cloud.langfuse.com/_next/static/chunks/27ywx138-jmac.js' failed to load.",
          ),
        ),
      ).toBe(false);
    });

    it("keeps a browser-extension dynamic import() failure", () => {
      expect(
        isStaleChunkLoadErrorEvent(
          exceptionEvent(
            "Failed to fetch dynamically imported module: chrome-extension://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/chunk.js",
            "TypeError",
          ),
        ),
      ).toBe(false);
    });
  });
});

/**
 * Build the exact WIRE shape the SDK hands `beforeSend` for a chunk PARSE
 * failure (LANGFUSE-5WH/5WG/5WD/5S7): global `onerror` mechanism,
 * `SyntaxError`, and a single frame at the chunk URL whose function is the
 * SDK's UNKNOWN_FUNCTION placeholder `"?"` (server-side normalization later
 * strips that — the shape stored events show). Pass `fn: null` to build the
 * normalized shape with the `function` key genuinely absent (an explicit
 * `undefined` would be swallowed by the default parameter).
 */
function chunkParseErrorEvent(
  value: string,
  filename = "app:///_next/static/chunks/0_w4b6l3mpyep.js",
  fn: string | null = "?",
): ErrorEvent {
  return {
    exception: {
      values: [
        {
          type: "SyntaxError",
          value,
          mechanism: {
            type: "auto.browser.global_handlers.onerror",
            handled: false,
          },
          stacktrace: {
            frames: [fn === null ? { filename } : { filename, function: fn }],
          },
        },
      ],
    },
  } as ErrorEvent;
}

describe("isStaleChunkParseErrorEvent", () => {
  describe("matches stale/truncated chunk parse failures (grouped, not dropped)", () => {
    it.each([
      ["Unexpected end of input"], // Chrome, LANGFUSE-5WH
      ['"" literal not terminated before end of script'], // Firefox, LANGFUSE-5WG
      ["missing } after property list"], // Firefox, LANGFUSE-5WD
      ["Invalid or unexpected token"], // Chrome, LANGFUSE-5S7
      ["expected expression, got end of script"], // Firefox, LANGFUSE-5WN
    ])("matches the real parse message %j", (value) => {
      expect(isStaleChunkParseErrorEvent(chunkParseErrorEvent(value))).toBe(
        true,
      );
    });

    it("matches regardless of the (per-deploy hashed) chunk filename", () => {
      expect(
        isStaleChunkParseErrorEvent(
          chunkParseErrorEvent(
            "Unexpected end of input",
            "app:///_next/static/chunks/3g9a8ojcqetek.js",
          ),
        ),
      ).toBe(true);
    });

    it("matches the normalized stored shape too (function key absent instead of '?')", () => {
      const event = chunkParseErrorEvent(
        "Unexpected end of input",
        "app:///_next/static/chunks/3g9a8ojcqetek.js",
        null,
      );
      // Guard the fixture itself: the frame must NOT carry a function key.
      expect(
        event.exception?.values?.[0]?.stacktrace?.frames?.[0],
      ).not.toHaveProperty("function");
      expect(isStaleChunkParseErrorEvent(event)).toBe(true);
    });

    it("is grouped by beforeSend, NOT dropped by the denylist", () => {
      expect(
        isDenylistedNoiseEvent(chunkParseErrorEvent("Unexpected end of input")),
      ).toBe(false);
    });
  });

  describe("NEVER matches a user-authored or app-code SyntaxError", () => {
    it("keeps the evals editor's user-code SyntaxError (LANGFUSE-5W3 shape)", () => {
      // Real shape: console.error capture with app + vendor formatter frames.
      const event = {
        exception: {
          values: [
            {
              type: "SyntaxError",
              value: "Unexpected token (1:38)",
              mechanism: { type: "auto.core.capture_console", handled: true },
              stacktrace: {
                frames: [
                  {
                    filename:
                      "web/src/features/evals/components/code-eval-template-form-body.tsx",
                    function: "P",
                  },
                  {
                    filename:
                      "node_modules/.pnpm/[email protected]/node_modules/prettier/standalone.mjs",
                    function: "Jn",
                  },
                ],
              },
            },
          ],
        },
      } as ErrorEvent;
      expect(isStaleChunkParseErrorEvent(event)).toBe(false);
    });

    it("keeps the evals editor's user-code lint error (LANGFUSE-5W2 shape, type Error)", () => {
      const event = {
        exception: {
          values: [
            {
              type: "Error",
              value:
                "Expected class, function definition or async function definition after decorator at byte range 477..481",
              mechanism: { type: "auto.core.capture_console", handled: true },
              stacktrace: {
                frames: [
                  {
                    filename:
                      "web/src/features/evals/utils/code-eval-template-validation.ts",
                    function: "aa",
                  },
                ],
              },
            },
          ],
        },
      } as ErrorEvent;
      expect(isStaleChunkParseErrorEvent(event)).toBe(false);
    });

    it("keeps a runtime SyntaxError thrown by app code (JSON.parse — multi-frame)", () => {
      const event = {
        exception: {
          values: [
            {
              type: "SyntaxError",
              value: "Unexpected end of JSON input",
              mechanism: {
                type: "auto.browser.global_handlers.onerror",
                handled: false,
              },
              stacktrace: {
                frames: [
                  {
                    filename: "app:///_next/static/chunks/0r47ep231kqhy.js",
                    function: "loadSavedFilters",
                  },
                  {
                    filename: "app:///_next/static/chunks/0r47ep231kqhy.js",
                    function: "JSON.parse",
                  },
                ],
              },
            },
          ],
        },
      } as ErrorEvent;
      expect(isStaleChunkParseErrorEvent(event)).toBe(false);
    });

    it("keeps a single-frame SyntaxError with a NAMED function (runtime throw)", () => {
      const event = {
        exception: {
          values: [
            {
              type: "SyntaxError",
              value: "Unexpected end of JSON input",
              mechanism: {
                type: "auto.browser.global_handlers.onerror",
                handled: false,
              },
              stacktrace: {
                frames: [
                  {
                    filename: "app:///_next/static/chunks/0r47ep231kqhy.js",
                    function: "parseStoredView",
                  },
                ],
              },
            },
          ],
        },
      } as ErrorEvent;
      expect(isStaleChunkParseErrorEvent(event)).toBe(false);
    });

    it("keeps a parse error in a non-chunk script", () => {
      expect(
        isStaleChunkParseErrorEvent(
          chunkParseErrorEvent(
            "Unexpected end of input",
            "app:///some-other-script.js",
          ),
        ),
      ).toBe(false);
    });

    it("keeps a SyntaxError with no stacktrace and a non-SyntaxError parse-like event", () => {
      expect(
        isStaleChunkParseErrorEvent(
          exceptionEvent("Unexpected end of input", "SyntaxError"),
        ),
      ).toBe(false);
      expect(
        isStaleChunkParseErrorEvent(
          chunkParseErrorEvent("Unexpected end of input"),
        ),
      ).toBe(true); // sanity: same builder matches when shape is complete
    });
  });
});

/** Frame helper for recorder-stack fixtures. */
function frame(filename: string, fn?: string) {
  return { filename, function: fn };
}

describe("isPosthogRecorderInternalEvent", () => {
  // Wire shape: the recorder loads with a version query that survives into
  // frame filenames handed to beforeSend (stored events show it on abs_path).
  const RECORDER = "app:///static/posthog-recorder.js?v=1.390.2";

  describe("drops errors thrown wholly inside the PostHog session recorder", () => {
    it("drops the rrweb mutation-processing SyntaxError (LANGFUSE-5VX shape)", () => {
      const event = {
        exception: {
          values: [
            {
              type: "SyntaxError",
              value: "Invalid or unexpected token",
              mechanism: {
                type: "auto.browser.global_handlers.onerror",
                handled: false,
              },
              stacktrace: {
                frames: [
                  frame(RECORDER, "Ut.processMutations"),
                  frame(RECORDER, "Ut.emit"),
                  frame(RECORDER, "Ws.onRRwebEmit"),
                  frame("<anonymous>", "Array.forEach"),
                ],
              },
            },
          ],
        },
      } as ErrorEvent;
      expect(isPosthogRecorderInternalEvent(event)).toBe(true);
    });

    it("drops the same shape without the version query (normalized stored filename)", () => {
      const event = {
        exception: {
          values: [
            {
              type: "SyntaxError",
              value: "Invalid or unexpected token",
              stacktrace: {
                frames: [
                  frame(
                    "app:///static/posthog-recorder.js",
                    "Ut.processMutations",
                  ),
                ],
              },
            },
          ],
        },
      } as ErrorEvent;
      expect(isPosthogRecorderInternalEvent(event)).toBe(true);
    });

    it("drops the path-versioned recorder script (LANGFUSE-621 setTimeout wrap)", () => {
      const recorder = "app:///static/1.417.1/posthog-recorder.js";
      const event = {
        exception: {
          values: [
            {
              type: "TypeError",
              value: 'string "" is not a function',
              mechanism: {
                type: "auto.browser.browserapierrors.setTimeout",
                handled: false,
              },
              stacktrace: {
                frames: [
                  frame(
                    "node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/src/helpers.ts",
                    "r",
                  ),
                  frame(recorder),
                  frame(recorder, "Object.Ec"),
                ],
              },
            },
          ],
        },
      } as ErrorEvent;
      expect(isPosthogRecorderInternalEvent(event)).toBe(true);
    });

    it("drops the path-versioned addEventListener wrap (LANGFUSE-620)", () => {
      const recorder = "app:///static/1.417.1/posthog-recorder.js";
      const event = {
        exception: {
          values: [
            {
              type: "TypeError",
              value: 'string "" is not a function',
              mechanism: {
                type: "auto.browser.browserapierrors.addEventListener",
                handled: false,
              },
              stacktrace: {
                frames: [
                  frame(
                    "node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/src/helpers.ts",
                    "r",
                  ),
                  frame(recorder, "l"),
                  frame(recorder, "callback"),
                  frame(recorder, "fr"),
                  frame(recorder, "emit"),
                  frame(recorder, "Object.onRRwebEmit"),
                ],
              },
            },
          ],
        },
      } as ErrorEvent;
      expect(isPosthogRecorderInternalEvent(event)).toBe(true);
    });

    it("drops the addEventListener-wrapped variant with a source-mapped Sentry SDK frame (LANGFUSE-5VY stored shape)", () => {
      const event = {
        exception: {
          values: [
            {
              type: "SyntaxError",
              value: "Invalid or unexpected token",
              mechanism: {
                type: "auto.browser.browserapierrors.addEventListener",
                handled: false,
              },
              stacktrace: {
                frames: [
                  frame(
                    "node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/src/helpers.ts",
                    "r",
                  ),
                  frame(RECORDER, "l"),
                  frame(RECORDER, "Se"),
                  frame(RECORDER, "Ws.Hd"),
                ],
              },
            },
          ],
        },
      } as ErrorEvent;
      expect(isPosthogRecorderInternalEvent(event)).toBe(true);
    });
  });

  describe("KEEPS any error that touches app code", () => {
    it("keeps a stack that mixes recorder frames with an app chunk frame", () => {
      const event = {
        exception: {
          values: [
            {
              type: "TypeError",
              value: "Cannot read properties of undefined (reading 'map')",
              stacktrace: {
                frames: [
                  frame(RECORDER, "Ws.onRRwebEmit"),
                  frame(
                    "app:///_next/static/chunks/0r47ep231kqhy.js",
                    "onMutation",
                  ),
                ],
              },
            },
          ],
        },
      } as ErrorEvent;
      expect(isPosthogRecorderInternalEvent(event)).toBe(false);
    });

    it("keeps the wrapped-listener variant when the SDK wrapper is bundled into an app chunk (prod wire shape — deliberate coverage gap)", () => {
      // In a prod bundle the Sentry wrap() frame is an app-chunk filename;
      // allowing chunk frames could mask real app listener errors, so this
      // shape stays kept even though it is recorder noise (LANGFUSE-5VY).
      const event = {
        exception: {
          values: [
            {
              type: "SyntaxError",
              value: "Invalid or unexpected token",
              stacktrace: {
                frames: [
                  frame("app:///_next/static/chunks/2-jdgbtsa7jx3.js", "r"),
                  frame(RECORDER, "l"),
                  frame(RECORDER, "Ws.Hd"),
                ],
              },
            },
          ],
        },
      } as ErrorEvent;
      expect(isPosthogRecorderInternalEvent(event)).toBe(false);
    });

    it("keeps an app-only stack (no recorder frame at all)", () => {
      const event = {
        exception: {
          values: [
            {
              type: "TypeError",
              value: "boom",
              stacktrace: {
                frames: [
                  frame("app:///_next/static/chunks/0r47ep231kqhy.js", "fn"),
                ],
              },
            },
          ],
        },
      } as ErrorEvent;
      expect(isPosthogRecorderInternalEvent(event)).toBe(false);
    });

    it("keeps the empty-string TypeError when it is thrown from an app chunk", () => {
      const event = {
        exception: {
          values: [
            {
              type: "TypeError",
              value: 'string "" is not a function',
              stacktrace: {
                frames: [
                  frame("app:///_next/static/chunks/0r47ep231kqhy.js", "fn"),
                ],
              },
            },
          ],
        },
      } as ErrorEvent;
      expect(isPosthogRecorderInternalEvent(event)).toBe(false);
    });

    it("keeps an all-opaque stack (<anonymous>/[native code] only — no recorder attribution)", () => {
      const event = {
        exception: {
          values: [
            {
              type: "TypeError",
              value: "boom",
              stacktrace: {
                frames: [
                  frame("<anonymous>", "Array.forEach"),
                  frame("[native code]"),
                ],
              },
            },
          ],
        },
      } as ErrorEvent;
      expect(isPosthogRecorderInternalEvent(event)).toBe(false);
    });

    it("keeps events with no stacktrace", () => {
      expect(
        isPosthogRecorderInternalEvent(exceptionEvent("boom", "TypeError")),
      ).toBe(false);
      expect(isPosthogRecorderInternalEvent(messageEvent("boom"))).toBe(false);
    });
  });
});

describe("isKitesurfInternalEvent", () => {
  const PROXY_TYPEERROR =
    "Cannot create proxy with a non-object as target or handler";
  const KS_USER = "/__ks_user_classic_regular.js";
  const KS_SHIM = "dom-shim.js";
  const KS_PAGE = "page.js";

  describe("drops Kitesurf recorder / agent-browser internals", () => {
    it("drops the [kitesurf] console.error message event (LANGFUSE-60W)", () => {
      expect(
        isKitesurfInternalEvent(
          messageEvent(
            `[kitesurf] event listener for load threw: TypeError: ${PROXY_TYPEERROR}`,
          ),
        ),
      ).toBe(true);
    });

    it("drops the same [kitesurf] text on event.logentry.message", () => {
      expect(
        isKitesurfInternalEvent(
          logentryEvent("[kitesurf] event listener for click threw: boom"),
        ),
      ).toBe(true);
    });

    it("drops ReferenceError: DOMRect is not defined from the user script (LANGFUSE-60Z)", () => {
      const event = {
        exception: {
          values: [
            {
              type: "ReferenceError",
              value: "DOMRect is not defined",
              mechanism: {
                type: "auto.core.capture_console",
                handled: true,
              },
              stacktrace: {
                frames: [
                  frame(KS_USER, "h"),
                  frame(KS_USER, "o1"),
                  frame(KS_USER, "sl"),
                ],
              },
            },
          ],
        },
      } as ErrorEvent;
      expect(isKitesurfInternalEvent(event)).toBe(true);
    });

    it("drops the proxy TypeError spanning page.js / dom-shim.js / user script (LANGFUSE-60X)", () => {
      const event = {
        exception: {
          values: [
            {
              type: "TypeError",
              value: PROXY_TYPEERROR,
              mechanism: {
                type: "auto.browser.global_handlers.onerror",
                handled: false,
              },
              stacktrace: {
                frames: [
                  frame(KS_PAGE, "fireIframeLoad"),
                  frame(KS_SHIM, "invokeListeners"),
                  frame(KS_USER, "e.recordDOM.c.win"),
                ],
              },
            },
          ],
        },
      } as ErrorEvent;
      expect(isKitesurfInternalEvent(event)).toBe(true);
    });

    it("drops the same TypeError when the injector has an origin + query", () => {
      const event = {
        exception: {
          values: [
            {
              type: "TypeError",
              value: PROXY_TYPEERROR,
              mechanism: {
                type: "auto.browser.global_handlers.onerror",
                handled: false,
              },
              stacktrace: {
                frames: [
                  frame(
                    "https://us.cloud.langfuse.com/__ks_user_classic_regular.js?v=1",
                    "e.recordDOM.c.win",
                  ),
                ],
              },
            },
          ],
        },
      } as ErrorEvent;
      expect(isKitesurfInternalEvent(event)).toBe(true);
    });
  });

  describe("KEEPS real errors (never masks a genuine app error)", () => {
    it("keeps a [kitesurf] wrap that quotes a first-party /_next/ frame", () => {
      expect(
        isKitesurfInternalEvent(
          messageEvent(
            `[kitesurf] event listener for click threw: TypeError: Cannot read properties of undefined (reading 'map')\n    at handleSubmit (https://us.cloud.langfuse.com/_next/static/chunks/app.js:1:1)`,
          ),
        ),
      ).toBe(false);
    });

    it("keeps the same TypeError when a first-party /_next/ frame is present", () => {
      const event = {
        exception: {
          values: [
            {
              type: "TypeError",
              value: PROXY_TYPEERROR,
              mechanism: {
                type: "auto.browser.global_handlers.onerror",
                handled: false,
              },
              stacktrace: {
                frames: [
                  frame(KS_USER, "e.recordDOM.c.win"),
                  frame(
                    "app:///_next/static/chunks/0r47ep231kqhy.js",
                    "createStore",
                  ),
                ],
              },
            },
          ],
        },
      } as ErrorEvent;
      expect(isKitesurfInternalEvent(event)).toBe(false);
    });

    it("keeps a first-party Proxy TypeError with no __ks_ frames", () => {
      const event = {
        exception: {
          values: [
            {
              type: "TypeError",
              value: PROXY_TYPEERROR,
              mechanism: {
                type: "auto.browser.global_handlers.onerror",
                handled: false,
              },
              stacktrace: {
                frames: [
                  frame(
                    "https://us.cloud.langfuse.com/_next/static/chunks/app.js",
                    "createStore",
                  ),
                ],
              },
            },
          ],
        },
      } as ErrorEvent;
      expect(isKitesurfInternalEvent(event)).toBe(false);
    });

    it("keeps an all-page.js stack (too generic without a vendor script)", () => {
      const event = {
        exception: {
          values: [
            {
              type: "TypeError",
              value: PROXY_TYPEERROR,
              stacktrace: {
                frames: [frame(KS_PAGE, "fireIframeLoad")],
              },
            },
          ],
        },
      } as ErrorEvent;
      expect(isKitesurfInternalEvent(event)).toBe(false);
    });

    it("keeps a message that quotes Proxy wording without the [kitesurf] prefix", () => {
      expect(
        isKitesurfInternalEvent(
          messageEvent(`Proxy setup failed: ${PROXY_TYPEERROR}`),
        ),
      ).toBe(false);
    });

    it("does not let the generic denylist swallow this TypeError on its own", () => {
      expect(
        isDenylistedNoiseEvent(exceptionEvent(PROXY_TYPEERROR, "TypeError")),
      ).toBe(false);
    });
  });
});