"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.__ΩIErrorContext = exports.__ΩDecoratedError = exports.SentryLiftKeysToTagsFromLoggerContext = void 0;
exports.isError = isError;
exports.getErrorMessage = getErrorMessage;
exports.toError = toError;
exports.tryOrErrorSync = tryOrErrorSync;
exports.tryOrError = tryOrError;
exports.tryWithReject = tryWithReject;
exports.setGlobalErrorReporter = setGlobalErrorReporter;
exports.reportError = reportError;
const tslib_1 = require("tslib");
const __ΩError = ['name', 'message', 'stack', 'Error', 'P&4!&4"&4#8Mw$y'];
const __ΩReturnType = ['T', 'args', '', 'ReturnType', 'l>e"!R"RPde#!P"@2"h"!/#qk#\'QRb!Pde"!p)w$y'];
const __ΩRecord = ['K', 'T', 'Record', 'l\'e#"Rb!b"Pde"!N#!w#y'];
function __assignType(fn, args) {
    fn.__type = args;
    return fn;
}
/*@ts-ignore*/
var { __ΩLoggerLevel } = require('@deepkit/logger');
const logger_1 = require("@deepkit/logger");
const Sentry = tslib_1.__importStar(require("@sentry/node"));
const lodash_1 = require("lodash");
const types_1 = require("util/types");
const resolver_1 = require("../../app/resolver");
const telemetry_1 = require("../../telemetry");
const sentry_1 = require("../../telemetry/sentry");
exports.SentryLiftKeysToTagsFromLoggerContext = [];
const __ΩDecoratedError = [() => __ΩError, () => __ΩError, 'cause', () => __ΩRecord, 'context', 'DecoratedError', 'Pn!n"4#8&"o$#4%8Mw&y'];
exports.__ΩDecoratedError = __ΩDecoratedError;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function isError(e) {
    return e instanceof Error || (0, types_1.isNativeError)(e);
}
isError.__type = ['e', 'isError', 'P"2!!/"'];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function getErrorMessage(e) {
    return isError(e) ? e.message : String(e);
}
getErrorMessage.__type = ['e', 'getErrorMessage', 'P"2!&/"'];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function toError(e, cause) {
    const baseError = isError(e) ? e : new Error(String(e));
    if (cause) {
        baseError.cause = toError(cause);
    }
    return baseError;
}
toError.__type = ['e', 'cause', () => __ΩError, 'toError', 'P"2!"2"8n#/$'];
function tryOrErrorSync(fn) {
    try {
        return fn();
    }
    catch (e) {
        return toError(e);
    }
}
tryOrErrorSync.__type = ['fn', () => __ΩReturnType, () => __ΩError, 'tryOrErrorSync', 'P"2!P"o""n#J/$'];
async function tryOrError(fn) {
    try {
        return await fn();
    }
    catch (e) {
        return toError(e);
    }
}
tryOrError.__type = ['fn', () => __ΩReturnType, () => __ΩError, 'tryOrError', 'P"2!P"o""n#J`/$'];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function tryWithReject(fn) {
    // eslint-disable-next-line no-async-promise-executor
    return new Promise(__assignType(async (resolve, reject) => {
        try {
            resolve(await fn(reject));
        }
        catch (e) {
            reject(e);
        }
    }, ['resolve', 'reject', '', 'P"2!"2""/#']));
}
tryWithReject.__type = ['fn', () => __ΩReturnType, 'tryWithReject', 'P"2!"o""`/#'];
const __ΩIErrorContext = ['scope', () => __ΩRecord, 'scopeData', () => __ΩRecord, 'loggerContext', () => __ΩRecord, 'data', 'IErrorContext', 'P&4!8&"o"#4#8&"o$#4%8&"o&#4\'8Mw(y'];
exports.__ΩIErrorContext = __ΩIErrorContext;
const errorHandlerState = {};
function setGlobalErrorReporter(reporter) {
    errorHandlerState.reporter = reporter;
}
setGlobalErrorReporter.__type = [() => __ΩLoggerLevel, 'label', () => __ΩError, 'err', () => __ΩIErrorContext, 'context', '', 'reporter', 'setGlobalErrorReporter', 'PPn!2"n#2$n%2&$/\'2("/)'];
function reportError(level, err, context) {
    if (errorHandlerState.reporter) {
        errorHandlerState.reporter(level, err, context);
    }
    if ((0, sentry_1.isSentryInstalled)()) {
        const tags = context.loggerContext ? (0, lodash_1.pick)(context.loggerContext, exports.SentryLiftKeysToTagsFromLoggerContext) : {};
        const Details = {
            ...context,
            loggerContext: (0, lodash_1.omit)(context.loggerContext, exports.SentryLiftKeysToTagsFromLoggerContext)
        };
        Sentry.captureException(err, {
            tags,
            extra: { Details },
            level: level === logger_1.LoggerLevel.alert ? 'fatal' : level === logger_1.LoggerLevel.warning ? 'warning' : 'error'
        });
    }
    if (level === logger_1.LoggerLevel.alert) {
        sendSlackAlertNotification(err, context);
    }
}
reportError.__type = [() => __ΩLoggerLevel, 'level', () => __ΩError, 'err', () => __ΩIErrorContext, 'context', 'reportError', 'Pn!2"n#2$n%2&"/\''];
async function sendSlackAlertNotification(err, context) {
    try {
        const traceContext = (0, telemetry_1.getTraceContext)();
        const url = (0, resolver_1.getAppConfig)().ALERTS_SLACK_WEBHOOK_URL;
        if (!url)
            return;
        await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                text: (0, lodash_1.compact)([`:rotating_light: *${err.message}*`, err.cause && `cause: ${err.cause.message}`]).join('\n'),
                attachments: [
                    {
                        color: 'danger',
                        fields: (0, lodash_1.compact)([
                            context.scope && {
                                title: 'Scope',
                                value: context.scope,
                                short: true
                            },
                            traceContext && {
                                title: 'Trace ID',
                                value: traceContext.traceId,
                                short: true
                            },
                            context.data && {
                                title: 'Alert Data',
                                value: JSON.stringify(context.data, null, 2),
                                short: false
                            },
                            err.context && {
                                title: 'Error Context',
                                value: JSON.stringify(err.context, null, 2),
                                short: false
                            },
                            context.scopeData && {
                                title: 'Scope Data',
                                value: JSON.stringify(context.scopeData, null, 2),
                                short: false
                            },
                            context.loggerContext && {
                                title: 'Logger Context',
                                value: JSON.stringify(context.loggerContext, null, 2),
                                short: false
                            }
                        ])
                    }
                ]
            })
        });
    }
    catch (err) {
        console.error('Failed to send slack alert notification', err);
    }
}
sendSlackAlertNotification.__type = [() => __ΩDecoratedError, 'err', () => __ΩIErrorContext, 'context', 'sendSlackAlertNotification', 'Pn!2"n#2$"/%'];
//# sourceMappingURL=error.js.map