dsh-sansheng-liubu/preview/check-live.mjs

182 lines
11 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 真机检查:无头 Edge 打开独立测试 DSH,确认入口出现、点击后工作台渲染十席。
import { spawn } from 'node:child_process'
import { mkdtemp, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join, dirname } from 'node:path'
import { fileURLToPath } from 'node:url'
const url = process.argv[2]
if (!url) { console.error('usage: check-live.mjs <url>'); process.exit(2) }
const EDGE = process.env.EDGE ?? 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe'
const dir = dirname(fileURLToPath(import.meta.url))
const profile = await mkdtemp(join(tmpdir(), 'sansheng-live-'))
const errors = []
const result = { url, entry: null, workbench: null, consoleErrors: errors }
let browser, ws
const sleep = ms => new Promise(r => setTimeout(r, ms))
async function main() {
browser = spawn(EDGE, ['--headless=new', '--disable-gpu', '--no-first-run', '--no-default-browser-check', '--remote-debugging-port=0', '--user-data-dir=' + profile, 'about:blank'], { stdio: ['ignore', 'ignore', 'pipe'] })
const endpoint = await new Promise((resolve, reject) => {
let log = ''
const timer = setTimeout(() => reject(new Error('browser startup timeout')), 20000)
browser.stderr.on('data', b => { log += b; const m = log.match(/DevTools listening on (.+)/); if (m) { clearTimeout(timer); resolve(m[1].trim()) } })
browser.on('error', reject)
})
ws = new WebSocket(endpoint)
await new Promise((resolve, reject) => { ws.onopen = resolve; ws.onerror = reject })
let n = 0
const pending = new Map()
ws.onmessage = e => {
const m = JSON.parse(e.data)
if (m.id) { const p = pending.get(m.id); pending.delete(m.id); if (m.error) p.reject(Error(JSON.stringify(m.error))); else p.resolve(m.result) }
else if (m.method === 'Runtime.exceptionThrown') errors.push('exception: ' + (m.params.exceptionDetails.exception?.description || m.params.exceptionDetails.text))
else if (m.method === 'Runtime.consoleAPICalled' && ['error', 'warning'].includes(m.params.type)) {
const text = (m.params.args || []).map(a => a.value ?? a.description ?? '').join(' ')
if (/sansheng|error|failed|did not activate|duplicate/i.test(text)) errors.push(m.params.type + ': ' + text.slice(0, 400))
}
}
const cdp = (method, params = {}, sessionId) => new Promise((resolve, reject) => { const id = ++n; pending.set(id, { resolve, reject }); ws.send(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) })) })
const { targetId } = await cdp('Target.createTarget', { url: 'about:blank' })
const { sessionId } = await cdp('Target.attachToTarget', { targetId, flatten: true })
const call = (m, p = {}) => cdp(m, p, sessionId)
await call('Page.enable'); await call('Runtime.enable')
const evaluate = async expression => {
const r = await call('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true })
if (r.exceptionDetails) throw Error(r.exceptionDetails.exception?.description || r.exceptionDetails.text)
return r.result.value
}
const waitFor = async (expr, timeout = 45000, step = 250) => { const end = Date.now() + timeout; while (Date.now() < end) { try { if (await evaluate(expr)) return true } catch {} await sleep(step) } return false }
const shot = async name => { const r = await call('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }); await writeFile(join(dir, name), Buffer.from(r.data, 'base64')) }
await call('Emulation.setDeviceMetricsOverride', { width: 1440, height: 900, deviceScaleFactor: 1, mobile: false })
await call('Page.navigate', { url })
await waitFor("document.readyState === 'complete'", 30000)
// 关掉 DSH 自身“预览版说明”首启弹层,避免遮挡截图
try { await evaluate("(() => { const b = [...document.querySelectorAll('button')].find(x => (x.innerText || '').trim() === '继续'); if (b) { b.click(); return true } return false })()") } catch {}
await sleep(500)
try { await call('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 }); await call('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 }) } catch {}
await sleep(800)
const foundEntry = await waitFor("!!document.querySelector('.ssw-entry')", 60000)
result.entry = await evaluate(`(() => ({ found: !!document.querySelector('.ssw-entry'), text: document.querySelector('.ssw-entry')?.innerText?.trim() ?? null, title: document.title }))()`)
await shot('live-01-entry.png')
if (foundEntry) {
await evaluate("document.querySelector('.ssw-entry').click(); true")
const foundRoot = await waitFor("!!(document.querySelector('.ssw-root') || document.querySelector('.ssw-float'))", 15000)
await sleep(3000)
result.workbench = await evaluate(`(() => {
const root = document.querySelector('.ssw-root') || document.querySelector('.ssw-float')
const seats = document.querySelectorAll('.ssw-seat')
return {
found: !!root,
rootClass: root ? root.className : null,
headTitle: document.querySelector('.ssw-head-title')?.innerText?.trim() ?? null,
seatCount: seats.length,
seatNames: Array.from(seats).map(s => s.querySelector('.ssw-role-name')?.innerText?.trim()).filter(Boolean),
countLabel: document.querySelector('.ssw-count')?.innerText?.trim() ?? null,
enableText: document.querySelector('.ssw-enable .ssw-primary')?.innerText?.trim() ?? null,
currentName: document.querySelector('.ssw-current-name')?.innerText?.trim() ?? null,
error: document.querySelector('.ssw-error')?.innerText?.trim() ?? null,
empty: document.querySelector('.ssw-empty')?.innerText?.replace(/\\s+/g, ' ').trim() ?? null,
loading: !!document.querySelector('.ssw-loading'),
floating: !!document.querySelector('.ssw-float'),
inDock: !!(document.querySelector('.ssw-root') && document.querySelector('.ssw-root').closest('[data-sidebar-right-session]')),
dockTabLabels: Array.from(document.querySelectorAll('[data-sidebar-right-tab]')).map(x => x.innerText.trim()).filter(Boolean),
rootText: root ? root.innerText.replace(/\\s+/g, ' ').trim().slice(0, 700) : null,
}
})()`)
await shot('live-02-workbench.png')
if (process.argv.includes('--report')) {
const toggled = await evaluate("(() => { const b = document.querySelector('.ssw-report-toggle'); if (!b) return false; b.click(); return true })()")
await sleep(700)
result.report = await evaluate(`(() => ({
toggled: ${toggled},
count: document.querySelectorAll('.ssw-report-item').length,
items: Array.from(document.querySelectorAll('.ssw-report-item')).map(el => ({
seat: el.getAttribute('data-seat'),
name: el.querySelector('strong')?.innerText?.trim() ?? null,
model: el.querySelector('.ssw-report-model')?.innerText?.trim() ?? null,
text: el.querySelector('.ssw-report-text')?.innerText?.trim() ?? null,
})),
}))()`)
await shot('live-05-report.png')
try {
await evaluate("(() => { const el = document.querySelector('.ssw-report-item[data-seat=lipu]'); if (el) { el.scrollIntoView({ block: 'center' }); return true } return false })()")
await sleep(500)
await shot('live-06-report-lipu.png')
} catch {}
}
const oi = process.argv.indexOf('--open')
if (oi >= 0) {
const seatId = process.argv[oi + 1]
const order = { lead: 0, zhongshu: 1, shangshu: 2, menxia: 3, libu: 4, hubu: 5, lipu: 6, bingbu: 7, xingbu: 8, gongbu: 9 }
const idx = order[seatId]
if (idx !== undefined) {
const clicked = await evaluate(`(() => { const s = document.querySelectorAll('.ssw-seat'); if (s[${idx}]) { s[${idx}].click(); return true } return false })()`)
const noticeEarly = await evaluate("document.querySelector('.ssw-notice')?.innerText?.trim() ?? null")
await sleep(1800)
result.open = await evaluate(`(() => ({
mainText: (document.querySelector('main')?.innerText || '').replace(/\\s+/g, ' ').trim().slice(0, 320),
composer: (document.querySelector('.composer')?.innerText || '').replace(/\\s+/g, ' ').trim().slice(0, 120),
title: document.title,
}))()`)
result.open.seatId = seatId
result.open.clicked = clicked
result.open.noticeEarly = noticeEarly
await shot('live-07-' + seatId + '-session.png')
}
}
if (process.argv.includes('--each')) {
result.each = []
const n = await evaluate("document.querySelectorAll('.ssw-seat').length")
for (let i = 0; i < n; i++) {
await evaluate(`(() => { const s = document.querySelectorAll('.ssw-seat'); if (s[${i}]) s[${i}].click(); return true })()`)
await sleep(1200)
const info = await evaluate(`(() => ({
name: document.querySelector('.ssw-current-name')?.innerText?.trim() ?? null,
notice: document.querySelector('.ssw-notice')?.innerText?.trim() ?? null,
selected: document.querySelector('.ssw-seat[aria-pressed=true] .ssw-role-name')?.innerText?.trim() ?? null,
}))()`)
await shot('seat-' + String(i + 1).padStart(2, '0') + '.png')
result.each.push({ i: i + 1, ...info })
}
}
if (process.argv.includes('--seat')) {
const clicked = await evaluate("(() => { const s = document.querySelectorAll('.ssw-seat'); if (s.length >= 10) { s[9].click(); return true } return false })()")
await sleep(1500)
result.seatNav = await evaluate(`(() => ({
clicked: ${clicked},
notice: document.querySelector('.ssw-notice')?.innerText?.trim() ?? null,
currentName: document.querySelector('.ssw-current-name')?.innerText?.trim() ?? null,
}))()`)
await shot('live-04-seat.png')
}
if (process.argv.includes('--enable') && await evaluate("!!document.querySelector('.ssw-enable .ssw-primary')")) {
await evaluate("document.querySelector('.ssw-enable .ssw-primary').click(); true")
const done = await waitFor("(() => { const c = document.querySelector('.ssw-count'); return c && /10 个会话/.test(c.innerText) })()", 60000)
await sleep(1500)
result.enable = await evaluate(`(() => ({
done: !!done_placeholder,
count: document.querySelector('.ssw-count')?.innerText?.trim() ?? null,
bound: document.querySelectorAll('.ssw-dot[data-status=bound]').length,
failed: document.querySelectorAll('.ssw-dot[data-status=failed]').length,
error: document.querySelector('.ssw-error')?.innerText?.trim() ?? null,
notice: document.querySelector('.ssw-notice')?.innerText?.trim() ?? null,
}))()`.replace('done_placeholder', String(done)))
await shot('live-03-enabled.png')
}
}
result.pass = !!(result.entry?.found && result.workbench?.found && (result.workbench?.seatCount === 10 || result.workbench?.enableText)
&& (!process.argv.includes('--report') || (result.report?.count === 10 && result.report.items.every(it => it.name && it.text)))
&& (!process.argv.includes('--each') || result.each?.length === 10))
}
try { await main() } catch (error) { result.fatal = String(error?.stack ?? error) } finally { try { ws?.close() } catch {}; try { browser?.kill() } catch {} }
console.log(JSON.stringify(result, null, 2))