"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.patchIOSTarget = exports.getIWDPPages = void 0;
const tslib_1 = require("tslib");
/**
 * 缩写说明：
 *  IWDP: ios webkit debug proxy
 *  CDP: chrome debug protocol
 */
const request_promise_1 = tslib_1.__importDefault(require("request-promise"));
const enum_1 = require("@/@types/enum");
const config_1 = require("@/config");
const url_1 = require("@/utils/url");
const log_1 = require("@/utils/log");
const timer_1 = require("@/utils/timer");
const debug_target_1 = require("@/utils/debug-target");
const log = new log_1.Logger('IWDP-util');
/**
 * 获取所有 usb 连接设备的 IWDP 页面列表
 */
const getIWDPPages = (iWDPPort) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
    if (config_1.config.isCluster)
        return [];
    try {
        // IWDP 检查页面列表会稍有延迟，这里简单做下 sleep
        yield timer_1.sleep(800);
        const deviceList = yield request_promise_1.default({
            url: '/json',
            // IWDP 必定是本地启动的服务，因为必须通过 USB 连接才能检测到设备
            baseUrl: `http://127.0.0.1:${iWDPPort}`,
            json: true,
        });
        const debugTargets = (yield Promise.all(deviceList.map(getDeviceIWDPPages))) || [];
        return debugTargets.flat().filter(iWDPPagesFilter);
    }
    catch (e) {
        return [];
    }
});
exports.getIWDPPages = getIWDPPages;
/**
 * use IWDP info extend debugTarget
 */
const patchIOSTarget = (debugTarget, iOSPages) => {
    if (debugTarget.platform !== enum_1.DevicePlatform.IOS)
        return debugTarget;
    const iOSPage = findIOSPage(debugTarget, iOSPages);
    if (!iOSPage) {
        const i = debugTarget.appClientTypeList.indexOf("IWDPAppClient" /* IWDP */);
        if (i !== -1)
            debugTarget.appClientTypeList.splice(i, 1);
        delete debugTarget.deviceOSVersion;
        delete debugTarget.deviceId;
        delete debugTarget.deviceOSVersion;
        return debugTarget;
    }
    iOSPage.shouldRemove = true;
    const iWDPWsUrl = iOSPage.webSocketDebuggerUrl;
    const wsUrl = url_1.makeUrl(`${config_1.config.wsDomain}${config_1.config.wsPath}`, {
        clientId: debugTarget.clientId,
        role: enum_1.ClientRole.Devtools,
    });
    const devtoolsFrontendUrl = url_1.makeUrl(`${config_1.config.domain}/front_end/inspector.html`, {
        remoteFrontend: true,
        experiments: true,
        ws: debug_target_1.wsUrlWithoutProtocol(wsUrl),
        env: global.debugAppArgv.env,
    });
    const { appClientTypeList } = debugTarget;
    if (appClientTypeList.indexOf("IWDPAppClient" /* IWDP */) === -1)
        appClientTypeList.push("IWDPAppClient" /* IWDP */);
    return Object.assign(Object.assign({}, debugTarget), { iWDPWsUrl,
        appClientTypeList, deviceName: iOSPage.device.deviceName, deviceId: iOSPage.device.deviceId, deviceOSVersion: iOSPage.device.deviceOSVersion, title: iOSPage.title, devtoolsFrontendUrl, webSocketDebuggerUrl: wsUrl });
};
exports.patchIOSTarget = patchIOSTarget;
/**
 * 获取一台设备的 IWDP 页面列表
 */
const getDeviceIWDPPages = (device) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
    var _a;
    const port = device.url.match(/:(\d+)/)[1];
    try {
        const targets = yield request_promise_1.default({
            url: '/json',
            baseUrl: `http://127.0.0.1:${port}`,
            json: true,
        });
        targets.forEach((target) => (target.device = device));
        return targets;
    }
    catch (e) {
        log.error('getDeviceIWDPPages error, %s', (_a = e) === null || _a === void 0 ? void 0 : _a.stack);
        return [];
    }
});
const iWDPPagesFilter = (iWDPPage) => /^HippyContext/.test(iWDPPage.title) && !/\(delete\)/.test(iWDPPage.title);
//  && Boolean(iWDPPage.devtoolsFrontendUrl);
const findIOSPage = (debugTarget, iOSPages) => {
    const iOSPagesWithFlag = iOSPages;
    return iOSPagesWithFlag.find((iOSPage) => (debugTarget.appClientTypeList.includes("WSAppClient" /* WS */) &&
        debugTarget.title === iOSPage.title &&
        debugTarget.deviceName === iOSPage.device.deviceName) ||
        (debugTarget.appClientTypeList[0] === "TunnelAppClient" /* Tunnel */ &&
            debugTarget.deviceName === iOSPage.device.deviceName));
};
