import { afterEach, describe, expect, it, vi } from "vitest"; import { createSentryErrorReporter, sanitizeSentryEvent, type SentryLikeModule } from "./sentry.js"; import type { ErrorReportSeverity } from "./index.js"; function makeFakeSentry(overrides: Partial = {}): SentryLikeModule { return { init: vi.fn(), captureException: vi.fn(), captureMessage: vi.fn(), ...overrides, }; } describe("createSentryErrorReporter dynamic-import fallback", () => { afterEach(() => { vi.restoreAllMocks(); }); it("uses the real @sentry/node loader and falls back to noop when the package is absent", async () => { // No `loadSentry` override => the adapter goes through the production // `loadSentryFromNodeModules` path. `@sentry/node` is not installed in this // workspace, so the dynamic import rejects and we degrade to the noop. const warn = vi.fn(); const reporter = createSentryErrorReporter({ dsn: "https://example@sentry.io/1", onMissingDependency: warn, }); await reporter.report({ component: "api", operation: "request", errorMessage: "boom" }); expect(warn).toHaveBeenCalledWith(expect.stringContaining("@sentry/node is not installed")); }); it("routes the missing-DSN warning through the default console.warn logger", async () => { const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => undefined); // No onMissingDependency => exercise defaultMissingDependencyLogger. const reporter = createSentryErrorReporter({ dsn: "" }); await reporter.report({ component: "api", operation: "request" }); expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("SENTRY_DSN is empty")); }); }); describe("createSentryErrorReporter init failures", () => { it("logs an init failure with the Error message and degrades to noop", async () => { const warn = vi.fn(); const captureMessage = vi.fn(); const sentry = makeFakeSentry({ init: () => { throw new Error("transport boot failed"); }, captureMessage, }); const reporter = createSentryErrorReporter({ dsn: "https://example@sentry.io/1", loadSentry: async () => sentry, onMissingDependency: warn, }); await reporter.report({ component: "api", operation: "request", errorMessage: "boom" }); expect(warn).toHaveBeenCalledWith(expect.stringContaining("failed to initialize @sentry/node (transport boot failed)")); // Initialization failed => nothing is captured. expect(captureMessage).not.toHaveBeenCalled(); }); it("stringifies non-Error init failures via describeCause", async () => { const warn = vi.fn(); const sentry = makeFakeSentry({ init: () => { // eslint-disable-next-line @typescript-eslint/only-throw-error throw "string-shaped boot failure"; }, }); const reporter = createSentryErrorReporter({ dsn: "https://example@sentry.io/1", loadSentry: async () => sentry, onMissingDependency: warn, }); await reporter.report({ component: "api", operation: "request" }); expect(warn).toHaveBeenCalledWith(expect.stringContaining("string-shaped boot failure")); }); it("initializes the SDK only once across multiple reports", async () => { const init = vi.fn(); const captureMessage = vi.fn(); const sentry = makeFakeSentry({ init, captureMessage }); const reporter = createSentryErrorReporter({ dsn: "https://example@sentry.io/1", loadSentry: async () => sentry, }); await reporter.report({ component: "api", operation: "a", errorMessage: "1" }); await reporter.report({ component: "api", operation: "b", errorMessage: "2" }); expect(init).toHaveBeenCalledTimes(1); expect(captureMessage).toHaveBeenCalledTimes(2); }); }); describe("createSentryErrorReporter delivery paths", () => { it("suppresses delivery when beforeSend throws", async () => { const captureException = vi.fn(); const captureMessage = vi.fn(); const sentry = makeFakeSentry({ captureException, captureMessage }); const reporter = createSentryErrorReporter({ dsn: "https://example@sentry.io/1", loadSentry: async () => sentry, beforeSend: () => { throw new Error("beforeSend exploded"); }, }); await expect(reporter.report({ component: "api", operation: "request", errorMessage: "boom" })).resolves.toBeUndefined(); expect(captureException).not.toHaveBeenCalled(); expect(captureMessage).not.toHaveBeenCalled(); }); it("captures via captureException when the event carries an error", async () => { const captureException = vi.fn(); const captureMessage = vi.fn(); const sentry = makeFakeSentry({ captureException, captureMessage }); const reporter = createSentryErrorReporter({ dsn: "https://example@sentry.io/1", loadSentry: async () => sentry, }); const boom = new Error("kaboom"); await reporter.report({ component: "worker", operation: "job.failed", severity: "fatal", error: boom }); expect(captureException).toHaveBeenCalledTimes(1); const [capturedError, context] = captureException.mock.calls[0] ?? []; // The error is recursively sanitized before delivery, so the Error instance // becomes a plain { errorName, errorMessage } object (no leaking metadata). expect(capturedError).toMatchObject({ errorName: "Error", errorMessage: "kaboom" }); expect((context as { level?: string } | undefined)?.level).toBe("fatal"); expect((context as { tags?: Record } | undefined)?.tags).toMatchObject({ component: "worker", operation: "job.failed", }); expect(captureMessage).not.toHaveBeenCalled(); }); it("falls back to a component:operation message when no errorMessage is present", async () => { const captureMessage = vi.fn(); const sentry = makeFakeSentry({ captureMessage }); const reporter = createSentryErrorReporter({ dsn: "https://example@sentry.io/1", loadSentry: async () => sentry, }); await reporter.report({ component: "mail", operation: "send" }); expect(captureMessage).toHaveBeenCalledTimes(1); expect(captureMessage.mock.calls[0]?.[0]).toBe("mail:send"); }); it("defaults the level to error for absent and unknown severities", async () => { const captureMessage = vi.fn(); const sentry = makeFakeSentry({ captureMessage }); const reporter = createSentryErrorReporter({ dsn: "https://example@sentry.io/1", loadSentry: async () => sentry, }); await reporter.report({ component: "api", operation: "a", errorMessage: "no severity" }); await reporter.report({ component: "api", operation: "b", errorMessage: "bogus severity", severity: "totally-invalid" as ErrorReportSeverity, }); const levels = captureMessage.mock.calls.map((call) => (call[1] as { level?: string } | undefined)?.level); expect(levels).toEqual(["error", "error"]); }); it("maps the warn severity to the Sentry 'warning' level", async () => { const captureMessage = vi.fn(); const sentry = makeFakeSentry({ captureMessage }); const reporter = createSentryErrorReporter({ dsn: "https://example@sentry.io/1", loadSentry: async () => sentry, }); await reporter.report({ component: "api", operation: "request", errorMessage: "heads up", severity: "warn" }); expect((captureMessage.mock.calls[0]?.[1] as { level?: string } | undefined)?.level).toBe("warning"); }); it("swallows capture transport failures without rethrowing", async () => { const sentry = makeFakeSentry({ captureMessage: () => { throw new Error("network down"); }, }); const reporter = createSentryErrorReporter({ dsn: "https://example@sentry.io/1", loadSentry: async () => sentry, }); await expect(reporter.report({ component: "api", operation: "request", errorMessage: "boom" })).resolves.toBeUndefined(); }); }); describe("sanitizeSentryEvent shouldDropEvent edge cases", () => { it("keeps events whose exception has an empty values array", () => { const event: Record = { exception: { values: [] } }; expect(sanitizeSentryEvent(event)).not.toBeNull(); }); it("keeps events whose exception is not an object", () => { const event: Record = { exception: "boom" }; expect(sanitizeSentryEvent(event)).not.toBeNull(); }); it("keeps events whose first exception value is not an object", () => { expect(sanitizeSentryEvent({ exception: { values: [null] } })).not.toBeNull(); expect(sanitizeSentryEvent({ exception: { values: [42] } })).not.toBeNull(); }); it("keeps events whose first exception value has no string type", () => { expect(sanitizeSentryEvent({ exception: { values: [{ value: "no type field" }] } })).not.toBeNull(); expect(sanitizeSentryEvent({ exception: { values: [{ type: 123 }] } })).not.toBeNull(); }); it("still drops a known abort type even when extra values follow", () => { const result = sanitizeSentryEvent({ exception: { values: [{ type: "AbortError" }, { type: "TypeError" }] }, }); expect(result).toBeNull(); }); }); describe("sanitizeSentryEvent passthrough", () => { it("returns a shallow clone for events without sensitive sub-objects", () => { const raw: Record = { message: "plain", level: "info" }; const result = sanitizeSentryEvent(raw); expect(result).toEqual(raw); // Must be a copy, not the same reference, so the SDK's object is untouched. expect(result).not.toBe(raw); }); });