"use strict";
const abort_signal_1 = require("./abort-signal");
const ipc_handler_1 = require("./ipc-handler");
const ipc_object_1 = require("./ipc-object");
const ipc_target_1 = require("./ipc-target");
// IMPORTANT: Do not use destructuring here - use direct assignment instead.
// tsgo has a bug that incorrectly transpiles destructured exports, resulting in
// `exports.SomeName = void 0;` which causes runtime errors.
// See: https://github.com/SocketDev/socket-packageurl-js/issues/3
const ObjectAssign = Object.assign;
const ObjectFreeze = Object.freeze;
module.exports = new Promise(
// The Promise executor is immediately executed.
resolve => {
    if (!(typeof process === 'object' && process !== null) ||
        // Manually check instead of lazily accessing constants.SUPPORTS_PROCESS_SEND
        // because constants is not initialized yet.
        typeof process.send !== 'function') {
        resolve(ipc_object_1);
        return;
    }
    const finish = () => {
        abort_signal_1.removeEventListener('abort', finish);
        process.removeListener('message', onmessage);
        resolve(ipc_object_1);
    };
    const onmessage = (rawData) => {
        if (rawData !== null && typeof rawData === 'object') {
            const data = { __proto__: null, ...rawData };
            const { SOCKET_IPC_HANDSHAKE: source } = data;
            ObjectAssign(ipc_target_1, source);
            ObjectFreeze(ipc_target_1);
            // The handler of a Proxy is mutable after proxy instantiation.
            // We delete the traps to defer to native behavior.
            for (const trapName in ipc_handler_1) {
                delete ipc_handler_1[trapName];
            }
        }
        finish();
    };
    abort_signal_1.addEventListener('abort', finish, { once: true });
    process.on('message', onmessage);
    // The timeout of 1,000 milliseconds, i.e. 1 second, is to prevent an unresolved
    // promised. It should be more than enough time for the ipc object handshake.
    setTimeout(finish, 1000);
});
