const core = require('@sentry/core');
const electron = require('electron');
const context = require('../context.js');
const merge = require('../merge.js');

function getAppMemory() {
    return electron.app.getAppMetrics().reduce((acc, metric) => acc + metric.memory.workingSetSize * 1024, 0);
}
const electronContextIntegration = core.defineIntegration(() => {
    return {
        name: 'ElectronContext',
        processEvent(event, _, client) {
            // We delete the Node runtime context so our Electron runtime context is used instead
            delete event.contexts?.runtime;
            // Electron is multi-process so the Node process memory will be inaccurate
            delete event.contexts?.app?.app_memory;
            // The user agent is parsed by Sentry and would overwrite certain context
            // information, which we don't want. Generally remove it, since we know that
            // we are browsing with Chrome.
            if (event.request?.headers) {
                delete event.request.headers['User-Agent'];
            }
            const { release = context.getDefaultReleaseName(), environment = context.getDefaultEnvironment() } = client.getOptions();
            return merge.mergeEvents({
                contexts: {
                    app: {
                        app_name: electron.app.name || electron.app.getName(),
                        app_version: electron.app.getVersion(),
                        build_type: process.mas ? 'app-store' : process.windowsStore ? 'windows-store' : undefined,
                        app_memory: getAppMemory(),
                        app_arch: process.arch,
                    },
                    browser: {
                        name: 'Chrome',
                    },
                    chrome: {
                        name: 'Chrome',
                        type: 'runtime',
                        version: process.versions.chrome,
                    },
                    device: {
                        family: 'Desktop',
                    },
                    node: {
                        name: 'Node',
                        type: 'runtime',
                        version: process.versions.node,
                    },
                    runtime: {
                        name: 'Electron',
                        version: process.versions.electron,
                    },
                },
                environment,
                release,
                tags: {
                    'event.origin': 'electron',
                    'event.environment': 'javascript',
                    'event.process': 'browser',
                },
            }, event);
        },
    };
});

exports.electronContextIntegration = electronContextIntegration;
//# sourceMappingURL=electron-context.js.map
