/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
import { logger } from './logger.js';
let _browser = undefined;
let _server = undefined;
async function close() {
    logger('close called..');
    try {
        if (_browser) {
            logger('closeBrowser...');
            await _browser.close();
            _browser = undefined;
        }
        if (_server) {
            logger('closeServer..');
            await _server.close();
            _server = undefined;
        }
    }
    catch {
        // ignore
    }
}
export function setServer(server) {
    _server = server;
}
export function setBrowser(browser) {
    _browser = browser;
}
export function watchClose() {
    // 监听stdin关闭事件 - 当MCP client退出时会触发
    process.stdin.on('close', async () => {
        logger('Stdin closed, MCP client disconnected, shutting down...');
        await close();
    });
    process.on('SIGINT', async () => {
        logger('Received SIGINT, shutting down gracefully...');
        await close();
        process.exit(0);
    });
    // 程序正常退出时也清理进程
    process.on('exit', () => {
        logger('on exit...');
    });
}
