"use strict";
exports.ids = [
    "215"
];
exports.modules = {
    "./webpack/plugin-browsers/run-chromium/chromium-source-inspection/cdp-client.ts" (__unused_rspack_module, __webpack_exports__, __webpack_require__) {
        __webpack_require__.d(__webpack_exports__, {
            n: ()=>CDPClient
        });
        var external_ws_ = __webpack_require__("ws");
        var external_ws_default = /*#__PURE__*/ __webpack_require__.n(external_ws_);
        var messages = __webpack_require__("./webpack/plugin-browsers/browsers-lib/messages.ts");
        async function getExtensionInfo(cdp, extensionId) {
            return await cdp.sendCommand('Extensions.getExtensionInfo', {
                extensionId
            });
        }
        async function loadUnpackedExtension(cdp, absPath) {
            const response = await cdp.sendCommand('Extensions.loadUnpacked', {
                extensionPath: absPath,
                options: {
                    failOnError: false
                }
            });
            return String(response?.extensionId || '');
        }
        async function unloadExtension(cdp, extensionId) {
            try {
                await cdp.sendCommand('Extensions.unload', {
                    extensionId
                });
                return true;
            } catch  {
                return false;
            }
        }
        var discovery = __webpack_require__("./webpack/plugin-browsers/run-chromium/chromium-source-inspection/discovery.ts");
        function establishBrowserConnection(url, isDev, onMessage, onRejectPending) {
            return new Promise((resolve, reject)=>{
                const ws = new (external_ws_default())(url);
                ws.on('open', ()=>{
                    if (isDev) console.log(messages.F1E());
                    resolve(ws);
                });
                ws.on('message', (data)=>{
                    onMessage(data.toString());
                });
                ws.on('error', (error)=>{
                    if (isDev) console.error(messages.fRy(error.message));
                    onRejectPending(error.message);
                    reject(error);
                });
                ws.on('close', ()=>{
                    if (isDev) console.log(messages.hE8());
                    onRejectPending('CDP connection closed');
                });
            });
        }
        function mergeShadowIntoDocument(mainHTML, shadowContent) {
            try {
                if (!mainHTML) return '';
                const hasRoot = /<div id=(["'])extension-root\1/i.test(mainHTML);
                if (hasRoot) {
                    const emptyRoot = /<div id=(["'])extension-root\1[^>]*><\/div>/i;
                    const replacedEmpty = mainHTML.replace(emptyRoot, `<div id="extension-root">${shadowContent}</div>`);
                    if (replacedEmpty !== mainHTML) return replacedEmpty;
                    return mainHTML.replace(/<div id=(["'])extension-root\1[^>]*>[\s\S]*?<\/div>/i, `<div id="extension-root">${shadowContent}</div>`);
                }
                const hostOpen = /(<[^>]*data-extension-root=(["'])true\2[^>]*>)/i;
                if (hostOpen.test(mainHTML)) return mainHTML.replace(hostOpen, `$1<div id="extension-root">${shadowContent}</div>`);
                if (/<\/body>/i.test(mainHTML)) return mainHTML.replace(/<\/body>/i, `<div id="extension-root">${shadowContent}</div></body>`);
                return `${mainHTML}\n<div id="extension-root">${shadowContent}</div>`;
            } catch  {
                return mainHTML;
            }
        }
        async function getPageHTML(cdp, sessionId, includeShadow = 'open-only') {
            try {
                await cdp.evaluate(sessionId, 'document.title');
            } catch  {}
            const mainHTMLRaw = await cdp.evaluate(sessionId, `(() => {
        try {
          const serialize = () => {
            const doctype = document.doctype  
            const dt = doctype
              ? '<!DOCTYPE '
                + doctype.name
                + (doctype.publicId ? ' PUBLIC "' + doctype.publicId + '"' : '')
                + (doctype.systemId ? ' "' + doctype.systemId + '"' : '')
                + '>'
              : ''
            return dt + '\n' + document.documentElement.outerHTML
          }
          return serialize()
        } catch (e) {
          return ''
        }
      })()`);
            const mainHTML = 'string' == typeof mainHTMLRaw ? mainHTMLRaw : String(mainHTMLRaw || '');
            if ('off' === includeShadow) return mainHTML;
            try {
                const mergedHtmlRaw = await cdp.evaluate(sessionId, `(() => { try { 
        var cloned = document.documentElement.cloneNode(true); 
        var host = cloned.querySelector('#extension-root,[data-extension-root="true"]'); 
        if (!host) { 
          var body = cloned.querySelector('body') || cloned; 
          var newRoot = document.createElement('div'); 
          newRoot.id='extension-root'; 
          body.appendChild(newRoot); 
          host = newRoot; 
        } 
        var s = new XMLSerializer(); 
        var shadow = ''; 
        try { 
          var liveHost = document.querySelector('[data-extension-root=\"true\"]') || document.getElementById('extension-root'); 
          if (liveHost && liveHost.shadowRoot) { 
            shadow = Array.from(liveHost.shadowRoot.childNodes).map(function(n){ 
              try { return s.serializeToString(n) } catch(e){ return '' } 
            }).join(''); 
          } 
        } catch(e) {} 
        try { host.innerHTML = shadow; } catch(e) {} 
        var doctype = document.doctype; 
        var dt = doctype ? '<!DOCTYPE ' + doctype.name + (doctype.publicId ? ' PUBLIC \"' + doctype.publicId + '\"' : '') + (doctype.systemId ? ' \"' + doctype.systemId + '\"' : '') + '>' : ''; 
        return String(dt + '\\n' + (cloned.outerHTML || document.documentElement.outerHTML)); 
      } catch(e) { try { return String(document.documentElement.outerHTML); } catch(_) { return '' } } })()`);
                const mergedHtml = 'string' == typeof mergedHtmlRaw ? mergedHtmlRaw : String(mergedHtmlRaw || '');
                if (mergedHtml && /<html[\s>]/i.test(mergedHtml)) return mergedHtml;
            } catch  {}
            let shadowContent = '';
            try {
                shadowContent = await cdp.evaluate(sessionId, `(() => {
          try {
            const hosts = Array.from(document.querySelectorAll('[data-extension-root="true"]'));
            if (!hosts.length) return '';
            const preferMarkers = ['iskilar_box','content_script','content_title','js-probe'];
            let firstNonEmpty = '';
            for (const host of hosts) {
              try {
                const sr = host && host.shadowRoot;
                if (!sr) continue;
                const html = String(sr.innerHTML || '');
                if (html && html.length) {
                  if (preferMarkers.some((m) => html.includes(m))) return html;
                  if (!firstNonEmpty) firstNonEmpty = html;
                  continue;
                }
                try {
                  const parts = Array.from(sr.children)
                    .map((n) => (n && n.outerHTML) ? String(n.outerHTML) : '')
                    .join('');
                  if (parts && parts.length) {
                    if (preferMarkers.some((m) => parts.includes(m))) return parts;
                    if (!firstNonEmpty) firstNonEmpty = parts;
                  }
                } catch { /* ignore */ }
              } catch { /* ignore */ }
            }
            return firstNonEmpty || '';
          } catch { return '' }
        })()`);
            } catch  {}
            if (shadowContent) try {
                const sc = 'string' == typeof shadowContent ? shadowContent : String(shadowContent || '');
                return mergeShadowIntoDocument(mainHTML, sc);
            } catch  {}
            return mainHTML;
        }
        async function waitForLoadEvent(cdp, sessionId) {
            return new Promise((resolve)=>{
                let resolved = false;
                const listener = (data)=>{
                    try {
                        const message = JSON.parse(data);
                        if ('Page.loadEventFired' === message.method && message.sessionId === sessionId && !resolved) {
                            resolved = true;
                            resolve();
                        }
                    } catch  {}
                };
                const clientWithHandle = cdp;
                const original = clientWithHandle.handleMessage.bind(cdp);
                clientWithHandle.handleMessage = (data)=>{
                    original(data);
                    listener(data);
                };
                setTimeout(()=>{
                    if (!resolved) {
                        resolved = true;
                        console.log(messages.Qiq());
                        resolve();
                    }
                    clientWithHandle.handleMessage = original;
                }, 2000);
            });
        }
        async function waitForContentScriptInjection(cdp, sessionId) {
            const deadline = Date.now() + 30000;
            const started = Date.now();
            while(Date.now() < deadline){
                try {
                    const injected = await cdp.evaluate(sessionId, `(() => { try {
          const hosts = Array.from(document.querySelectorAll('#extension-root,[data-extension-root="true"]'));
          if (!hosts.length) return false;
          const markers = ['iskilar_box','content_script','content_title','js-probe'];
          for (const h of hosts) {
            try {
              const sr = h && h.shadowRoot;
              if (!sr) continue;
              const html = String(sr.innerHTML||'');
              if (html.length > 0) return true;
              if (markers.some((m) => html.includes(m))) return true;
              try {
                const parts = Array.from(sr.children).map((n) => (n && n.outerHTML) ? String(n.outerHTML) : '').join('');
                if (parts && parts.length) return true;
                if (markers.some((m) => parts.includes(m))) return true;
              } catch { /* ignore */ }
            } catch { /* ignore */ }
          }
          return false;
        } catch { return false } })()`);
                    if (Boolean(injected)) return;
                } catch  {}
                const elapsed = Date.now() - started;
                const delay = elapsed < 2000 ? 150 : 500;
                await new Promise((r)=>setTimeout(r, delay));
            }
        }
        function _define_property(obj, key, value) {
            if (key in obj) Object.defineProperty(obj, key, {
                value: value,
                enumerable: true,
                configurable: true,
                writable: true
            });
            else obj[key] = value;
            return obj;
        }
        class CDPClient {
            isDev() {
                return 'true' === process.env.EXTENSION_AUTHOR_MODE;
            }
            async connect() {
                return new Promise(async (resolve, reject)=>{
                    try {
                        this.targetWebSocketUrl = await (0, discovery.N)(this.host, this.port, this.isDev());
                        this.ws = await establishBrowserConnection(this.targetWebSocketUrl, this.isDev(), (data)=>this.handleMessage(data), (reason)=>{
                            this.pendingRequests.forEach(({ reject, timeout }, id)=>{
                                try {
                                    reject(new Error(reason));
                                } catch (error) {
                                    if (this.isDev()) {
                                        const err = error;
                                        console.warn(messages.r0s(String(err.message || err)));
                                    }
                                }
                                if (timeout) clearTimeout(timeout);
                                this.pendingRequests.delete(id);
                            });
                        });
                        if (this.isDev()) console.log(messages.M3V(this.host, this.port));
                        resolve();
                    } catch (error) {
                        const err = error;
                        reject(new Error(`Failed to connect to CDP: ${err.message || err}`));
                    }
                });
            }
            disconnect() {
                if (this.ws) {
                    try {
                        this.ws.close();
                    } catch  {}
                    this.ws = null;
                }
            }
            onProtocolEvent(handler) {
                this.eventCallback = handler;
            }
            handleMessage(data) {
                try {
                    const message = JSON.parse(data);
                    if (message.id) {
                        const pending = this.pendingRequests.get(message.id);
                        if (pending) {
                            if (pending.timeout) clearTimeout(pending.timeout);
                            this.pendingRequests.delete(message.id);
                            if (message.error) pending.reject(new Error(JSON.stringify(message.error)));
                            else pending.resolve(message.result);
                        }
                        return;
                    }
                    if ('Target.attachedToTarget' === message.method) {
                        const params = message.params || {};
                        if (this.isDev()) console.log(messages.p8m(String(params.sessionId || ''), String(params.targetInfo?.type || '')));
                    }
                    if (this.eventCallback) this.eventCallback(message);
                } catch (error) {
                    if (this.isDev()) {
                        const err = error;
                        console.warn(messages.xxG(String(err.message || err)));
                    }
                }
            }
            async sendCommand(method, params = {}, sessionId, timeoutMs = 12000) {
                return new Promise((resolve, reject)=>{
                    if (!this.ws || this.ws.readyState !== external_ws_default().OPEN) return reject(new Error('WebSocket is not open'));
                    const id = ++this.messageId;
                    const message = {
                        id,
                        method,
                        params
                    };
                    if (sessionId) message.sessionId = sessionId;
                    try {
                        const timeout = setTimeout(()=>{
                            const pending = this.pendingRequests.get(id);
                            if (!pending) return;
                            this.pendingRequests.delete(id);
                            pending.reject(new Error(`CDP command timed out (${timeoutMs}ms): ${String(pending.method || method)}`));
                        }, timeoutMs);
                        this.pendingRequests.set(id, {
                            resolve,
                            reject,
                            timeout,
                            method
                        });
                        this.ws.send(JSON.stringify(message));
                    } catch (error) {
                        const pending = this.pendingRequests.get(id);
                        if (pending?.timeout) clearTimeout(pending.timeout);
                        this.pendingRequests.delete(id);
                        reject(error);
                    }
                });
            }
            async getTargets() {
                const response = await this.sendCommand('Target.getTargets');
                return response?.targetInfos || [];
            }
            async getBrowserVersion() {
                const response = await this.sendCommand('Browser.getVersion');
                return response || {};
            }
            async attachToTarget(targetId) {
                const response = await this.sendCommand('Target.attachToTarget', {
                    targetId,
                    flatten: true
                });
                return response.sessionId || '';
            }
            async enableAutoAttach() {
                await this.sendCommand('Target.setAutoAttach', {
                    autoAttach: true,
                    waitForDebuggerOnStart: false,
                    flatten: true
                });
            }
            async enableRuntimeAndLog(sessionId) {
                await this.sendCommand('Log.enable', {}, sessionId);
                if (sessionId) await this.sendCommand('Runtime.enable', {}, sessionId);
            }
            async navigate(sessionId, url) {
                await this.sendCommand('Page.navigate', {
                    url
                }, sessionId);
            }
            async createTarget(url) {
                const res = await this.sendCommand('Target.createTarget', {
                    url
                });
                return String(res?.targetId || '');
            }
            async activateTarget(targetId) {
                await this.sendCommand('Target.activateTarget', {
                    targetId
                });
            }
            async waitForLoadEvent(sessionId) {
                return waitForLoadEvent(this, sessionId);
            }
            async waitForContentScriptInjection(sessionId) {
                return waitForContentScriptInjection(this, sessionId);
            }
            async evaluate(sessionId, expression) {
                const response = await this.sendCommand('Runtime.evaluate', {
                    expression,
                    returnByValue: true
                }, sessionId);
                return response.result?.value;
            }
            async getPageHTML(sessionId, includeShadow = 'open-only') {
                return getPageHTML(this, sessionId, includeShadow);
            }
            async closeTarget(targetId) {
                await this.sendCommand('Target.closeTarget', {
                    targetId
                });
            }
            async forceReloadExtension(extensionId) {
                try {
                    await this.sendCommand('Extensions.reload', {
                        extensionId,
                        forceReload: true
                    });
                    return true;
                } catch (error) {
                    const attempts = 8;
                    for(let i = 0; i < attempts; i++){
                        try {
                            const ok = await this.reloadExtensionViaTargetEval(extensionId);
                            if (ok) return true;
                        } catch  {}
                        const backoffMs = Math.min(1200, 150 * (i + 1));
                        await new Promise((r)=>setTimeout(r, backoffMs));
                    }
                    console.warn(messages.ccn(extensionId, error.message || String(error)));
                    return false;
                }
            }
            async getExtensionInfo(extensionId) {
                try {
                    return await getExtensionInfo(this, extensionId);
                } catch (error) {
                    throw new Error(messages.Z5i(extensionId, error.message));
                }
            }
            async reloadExtensionViaTargetEval(extensionId) {
                try {
                    const targets = await this.getTargets();
                    const preferredOrder = [
                        'service_worker',
                        'background_page',
                        'worker',
                        'page'
                    ];
                    for (const type of preferredOrder){
                        const matchingTargets = (targets || []).filter((t)=>{
                            const url = String(t?.url || '');
                            const tt = String(t?.type || '');
                            const inExtensionScope = url.startsWith(`chrome-extension://${extensionId}/`);
                            return tt === type && inExtensionScope;
                        });
                        for (const target of matchingTargets){
                            const targetId = target?.targetId;
                            if (targetId) try {
                                const sessionId = await this.attachToTarget(targetId);
                                await this.sendCommand('Runtime.enable', {}, sessionId);
                                await this.sendCommand('Runtime.evaluate', {
                                    expression: '(function(){ try { if (!chrome || !chrome.runtime || !chrome.runtime.reload) return false; chrome.runtime.reload(); return true; } catch (error) { return false; } })()',
                                    returnByValue: true
                                }, sessionId);
                                return true;
                            } catch  {}
                        }
                    }
                    return false;
                } catch  {
                    return false;
                }
            }
            async loadUnpackedExtension(path) {
                try {
                    return await loadUnpackedExtension(this, path);
                } catch (error) {
                    throw new Error(messages.xlM(path, error.message));
                }
            }
            async unloadExtension(extensionId) {
                try {
                    return await unloadExtension(this, extensionId);
                } catch (error) {
                    console.error(messages.yEr(extensionId, error.message));
                    return false;
                }
            }
            constructor(port = 9222, host = '127.0.0.1'){
                _define_property(this, "port", void 0);
                _define_property(this, "host", void 0);
                _define_property(this, "ws", null);
                _define_property(this, "targetWebSocketUrl", null);
                _define_property(this, "eventCallback", void 0);
                _define_property(this, "messageId", 0);
                _define_property(this, "pendingRequests", new Map());
                this.port = port;
                this.host = host;
            }
        }
    },
    "./webpack/plugin-browsers/run-chromium/chromium-source-inspection/discovery.ts" (__unused_rspack_module, __webpack_exports__, __webpack_require__) {
        __webpack_require__.d(__webpack_exports__, {
            N: ()=>discoverWebSocketDebuggerUrl,
            z: ()=>checkChromeRemoteDebugging
        });
        var http__rspack_import_0 = __webpack_require__("http");
        var net__rspack_import_1 = __webpack_require__("net");
        var _browsers_lib_messages__rspack_import_2 = __webpack_require__("./webpack/plugin-browsers/browsers-lib/messages.ts");
        const CDP_HTTP_REQUEST_TIMEOUT_MS = 1200;
        async function getJson(host, port, path) {
            return new Promise((resolve, reject)=>{
                const req = http__rspack_import_0.request({
                    hostname: host,
                    port,
                    path,
                    method: 'GET'
                }, (res)=>{
                    let data = '';
                    res.on('data', (chunk)=>data += chunk);
                    res.on('end', ()=>{
                        try {
                            resolve(JSON.parse(data));
                        } catch (e) {
                            reject(new Error(`Failed to parse ${path}: ${e}`));
                        }
                    });
                });
                req.on('error', (err)=>reject(err));
                req.setTimeout(CDP_HTTP_REQUEST_TIMEOUT_MS, ()=>{
                    req.destroy(new Error(`CDP endpoint timed out: ${path}`));
                });
                req.end();
            });
        }
        async function discoverWebSocketDebuggerUrl(host, port, isDev) {
            try {
                const version = await getJson(host, port, '/json/version');
                const wsUrl = 'string' == typeof version?.webSocketDebuggerUrl ? version.webSocketDebuggerUrl : void 0;
                if (wsUrl) {
                    if (isDev) console.log(_browsers_lib_messages__rspack_import_2.Ter());
                    return wsUrl;
                }
            } catch (error) {
                if (isDev) console.warn('[CDP] Failed to read /json/version:', String(error?.message || error));
            }
            const targets = await getJson(host, port, '/json');
            if (isDev) console.log(_browsers_lib_messages__rspack_import_2.FFz((targets || []).length || 0));
            const pageTarget = (targets || []).find((target)=>{
                const type = String(target?.type || '');
                const ws = 'string' == typeof target?.webSocketDebuggerUrl ? target.webSocketDebuggerUrl : '';
                return 'page' === type && ws;
            });
            const pageWs = 'string' == typeof pageTarget?.webSocketDebuggerUrl ? pageTarget.webSocketDebuggerUrl : '';
            if (pageWs) {
                if (isDev) console.log(_browsers_lib_messages__rspack_import_2.Ter());
                return pageWs;
            }
            throw new Error('No CDP WebSocket URL available');
        }
        async function checkChromeRemoteDebugging(port = 9222) {
            return new Promise((resolve)=>{
                const socket = new net__rspack_import_1.Socket();
                socket.on('connect', ()=>{
                    socket.destroy();
                    resolve(true);
                });
                socket.on('error', ()=>{
                    resolve(false);
                });
                socket.on('timeout', ()=>{
                    socket.destroy();
                    resolve(false);
                });
                socket.setTimeout(2000);
                socket.connect(port, 'localhost');
            });
        }
    }
};
