const http = require('http');
const WebSocket = require('ws');

http.get('http://localhost:9223/json', res => {
    let d = '';
    res.on('data', c => d += c);
    res.on('end', () => {
        const pages = JSON.parse(d);
        const wsUrl = pages[0].webSocketDebuggerUrl;
        const ws = new WebSocket(wsUrl);
        ws.on('open', () => {
            ws.send(JSON.stringify({id: 1, method: 'Runtime.evaluate', params: {expression: 'document.getElementById("ver").innerText'}}));
        });
        ws.on('message', data => {
            try {
                const msg = JSON.parse(data);
                if (msg.id === 1) {
                    console.log('VERSION:', msg.result?.result?.value ?? JSON.stringify(msg.result));
                    ws.send(JSON.stringify({id: 2, method: 'Runtime.evaluate', params: {expression: 'localStorage.getItem("gca_ver") || "none"'}}));
                }
                if (msg.id === 2) {
                    console.log('LOCALSTORAGE gca_ver:', msg.result?.result?.value ?? JSON.stringify(msg.result));
                    ws.send(JSON.stringify({id: 3, method: 'Runtime.evaluate', params: {expression: 'document.getElementById("log").innerText'}}));
                }
                if (msg.id === 3) {
                    console.log('LOG:', msg.result?.result?.value?.substring(0, 500) ?? JSON.stringify(msg.result));
                    ws.close();
                    process.exit(0);
                }
            } catch(e) {}
        });
    });
}).on('error', e => { console.log('HTTP ERR:', e.message); process.exit(1); });

setTimeout(() => process.exit(0), 8000);
