const core = require('@sentry/core');
const electron = require('electron');
const fs = require('fs');
const path = require('path');
const url = require('url');
const ipc = require('../../common/ipc.js');
const electronNormalize = require('../electron-normalize.js');

var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
// After bundling with webpack, require.resolve can return number so we include that in the types
// to ensure we check for that!
function getPreloadPath() {
    try {
        return require.resolve('../../preload/default.js');
    }
    catch {
        try {
            // This could be ESM
            const currentDir = url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('main/integrations/preload-injection.js', document.baseURI).href)));
            // Use the CJS preload
            return path.resolve(currentDir, '..', '..', '..', '..', 'preload', 'default.js');
        }
        catch {
            //
        }
    }
    return undefined;
}
/**
 * Injects the preload script into the provided sessions.
 *
 * Defaults to injecting into the defaultSession
 */
const preloadInjectionIntegration = core.defineIntegration(() => {
    return {
        name: 'PreloadInjection',
        setup(client) {
            const options = client.getOptions();
            // If classic IPC mode is disabled, we shouldn't attempt to inject preload scripts
            // eslint-disable-next-line no-bitwise
            if ((options.ipcMode & ipc.IPCMode.Classic) === 0) {
                return;
            }
            electron.app.once('ready', () => {
                const path$1 = getPreloadPath();
                if (path$1 && typeof path$1 === 'string' && path.isAbsolute(path$1) && fs.existsSync(path$1)) {
                    for (const sesh of options.getSessions()) {
                        electronNormalize.setPreload(sesh, path$1);
                    }
                }
                else {
                    core.debug.log('The preload script could not be injected automatically. This is most likely caused by bundling of the main process');
                }
            });
        },
    };
});

exports.preloadInjectionIntegration = preloadInjectionIntegration;
//# sourceMappingURL=preload-injection.js.map
