import { parseSemver } from '@sentry/core';
import { app } from 'electron';
import { join } from 'path';
import { RENDERER_ID_HEADER } from '../common/ipc.js';

const parsed = parseSemver(process.versions.electron);
const version = { major: parsed.major || 0, minor: parsed.minor || 0, patch: parsed.patch || 0 };
const ELECTRON_MAJOR_VERSION = version.major;
const EXIT_REASONS = [
    'clean-exit',
    'abnormal-exit',
    'killed',
    'crashed',
    'oom',
    'launch-failed',
    'integrity-failure',
];
const CRASH_REASONS = ['crashed', 'oom'];
/** Gets the Sentry Cache path */
function getSentryCachePath() {
    return join(app.getPath('userData'), 'sentry');
}
/**
 * Electron >= 25 support `protocol.handle`
 */
function supportsProtocolHandle() {
    return version.major >= 25;
}
/**
 * Registers a custom protocol to receive events from the renderer
 *
 * Uses `protocol.handle` if available, otherwise falls back to `protocol.registerStringProtocol`
 */
function registerProtocol(protocol, scheme, callback) {
    if (supportsProtocolHandle()) {
        protocol.handle(scheme, async (request) => {
            callback({
                windowId: request.headers.get(RENDERER_ID_HEADER) || undefined,
                url: request.url,
                body: Buffer.from(await request.arrayBuffer()),
            });
            return new Response('');
        });
    }
    else {
        // eslint-disable-next-line deprecation/deprecation
        protocol.registerStringProtocol(scheme, (request, complete) => {
            callback({
                windowId: request.headers[RENDERER_ID_HEADER],
                url: request.url,
                body: request.uploadData?.[0]?.bytes,
            });
            complete('');
        });
    }
}
/**
 * Adds a preload script to the session.
 *
 * Electron >= v35 supports new `registerPreloadScript` method and `getPreloads` and `setPreloads` are deprecated.
 */
function setPreload(sesh, path) {
    if (sesh.registerPreloadScript) {
        sesh.registerPreloadScript({ type: 'frame', filePath: path });
    }
    else {
        const existing = sesh.getPreloads();
        sesh.setPreloads([path, ...existing]);
    }
}

export { CRASH_REASONS, ELECTRON_MAJOR_VERSION, EXIT_REASONS, getSentryCachePath, registerProtocol, setPreload };
//# sourceMappingURL=electron-normalize.js.map
