validate / validate (push) Canceled after 0s
本仓只服务桌面宿主 image-workbench-desktop,与网页端无限画布工具无关。 14 个测试/工具脚本里共 15 处仍把 image-workbench-web 当 playwright/esbuild 的依赖后备目录(含 path.resolve、报错文案、album viewer-e2e 的多余候选), 全部改为 image-workbench-desktop;album 里重复的 web 仓候选直接删掉。 这些常量只用于找 node_modules,不参与任何插件逻辑,行为零变化。 桌面仓已确认有 playwright 1.64.1 / esbuild 0.28.2,改后依赖解析有效。 本轮不动 6 处 test.image-workbench-web.pages.dev 网址(属于网页端 e2e 脚本的废弃处理,另案);插件源码与版本未动,不需要发市场。
466 lines
23 KiB
JavaScript
466 lines
23 KiB
JavaScript
// 批量出图插件本地端到端(开发用,不进 CI)。
|
||
//
|
||
// 为什么需要它:面板 UI + 串行队列 + Canvas 编码 + ZIP 打包都是浏览器行为,node 侧测不了。
|
||
// 这里装一个合成宿主(可注入的 ctx + panels 容器),addScriptTag 加载插件源码本体,在真实 Chromium 里验证
|
||
// 注册 / 面板挂载 / 节点过滤 / 队列 / 双版本出图 / ZIP 结构与系统可解压性 / 抠图分支 / 失败行内提示 / 参数持久化。
|
||
//
|
||
// 运行:
|
||
// node batch-export/tools/harness.mjs
|
||
// 依赖:playwright(本仓/宿主仓 node_modules 均可;或用 IWB_PLAYWRIGHT_ROOT 指定)+ 系统 unzip(校验 ZIP)
|
||
import { createRequire } from 'node:module'
|
||
import { writeFileSync, mkdtempSync } from 'node:fs'
|
||
import { execFileSync } from 'node:child_process'
|
||
import { tmpdir } from 'node:os'
|
||
import path from 'node:path'
|
||
import { fileURLToPath } from 'node:url'
|
||
|
||
const HERE = path.dirname(fileURLToPath(import.meta.url)) // <repo>/batch-export/tools
|
||
const REPO = path.resolve(HERE, '../..')
|
||
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-desktop'
|
||
const PLUGIN_ENTRY = path.resolve(HERE, '../src/index.js')
|
||
|
||
let chromium = null
|
||
for (const base of [process.env.IWB_PLAYWRIGHT_ROOT, REPO, HOST_REPO, process.cwd()].filter(Boolean)) {
|
||
try { chromium = createRequire(path.join(base, 'package.json'))('playwright').chromium; break } catch { /* 试下一个 */ }
|
||
}
|
||
if (!chromium) {
|
||
console.error('✗ 找不到 playwright。请在含 node_modules 的目录执行,或指定 IWB_PLAYWRIGHT_ROOT:')
|
||
console.error(' IWB_PLAYWRIGHT_ROOT=/path/to/repo node batch-export/tools/harness.mjs')
|
||
process.exit(2)
|
||
}
|
||
|
||
let failed = 0
|
||
const check = (name, ok, detail) => {
|
||
if (!ok) failed++
|
||
console.log((ok ? '✓ ' : '✗ ') + name + (detail ? ' ' + detail : ''))
|
||
}
|
||
const poll = async (fn, timeout = 30000, step = 100) => {
|
||
const end = Date.now() + timeout
|
||
for (;;) {
|
||
let v
|
||
try { v = await fn() } catch { v = false }
|
||
if (v) return v
|
||
if (Date.now() > end) return false
|
||
await new Promise((r) => setTimeout(r, step))
|
||
}
|
||
}
|
||
|
||
// ---------- 页内环境:合成宿主 + 记录器(__H__)+ 源图 ----------
|
||
const HOST_SETUP = () => {
|
||
const H = {
|
||
manifest: null,
|
||
panels: [],
|
||
nodes: [],
|
||
images: {},
|
||
settings: {},
|
||
defaults: {},
|
||
storage: {},
|
||
logs: [],
|
||
rmbgCalls: 0,
|
||
zip: null,
|
||
}
|
||
|
||
const ctx = {
|
||
ui: { registerPanel: (p) => { H.panels.push(p); return true } },
|
||
canvas: {
|
||
getNodes: () => H.nodes,
|
||
listNodeTypes: () => [],
|
||
getSelectedNode: () => null,
|
||
getNodeImage: async (id) => H.images[id] || null,
|
||
},
|
||
settings: { get: (k) => (Object.prototype.hasOwnProperty.call(H.settings, k) ? H.settings[k] : H.defaults[k]) },
|
||
storage: {
|
||
namespace: (ns) => {
|
||
const key = String(ns === undefined || ns === null ? '' : ns)
|
||
if (!H.storage[key]) H.storage[key] = {}
|
||
return {
|
||
get: (k) => H.storage[key][String(k)],
|
||
set: (k, v) => { H.storage[key][String(k)] = v },
|
||
remove: (k) => { delete H.storage[key][String(k)] },
|
||
keys: () => Object.keys(H.storage[key]),
|
||
}
|
||
},
|
||
},
|
||
log: Object.assign(function () { H.logs.push(Array.prototype.slice.call(arguments).join(' ')) }, {
|
||
info: function () { H.logs.push(Array.prototype.slice.call(arguments).join(' ')) },
|
||
warn: function () { H.logs.push(Array.prototype.slice.call(arguments).join(' ')) },
|
||
error: function () { H.logs.push(Array.prototype.slice.call(arguments).join(' ')) },
|
||
}),
|
||
events: { on() {}, off() {}, emit() {} },
|
||
}
|
||
|
||
window.IWBPluginHost = {
|
||
register(manifest, factory) {
|
||
H.manifest = manifest
|
||
H.defaults = {}
|
||
for (const k of Object.keys(manifest.settings || {})) H.defaults[k] = manifest.settings[k].default
|
||
factory(ctx)
|
||
},
|
||
}
|
||
window.__H__ = H
|
||
|
||
// 拦下 createObjectURL 拿 ZIP(about:blank 下不依赖真实下载事件)
|
||
const origCreate = URL.createObjectURL.bind(URL)
|
||
URL.createObjectURL = function (blob) {
|
||
if (blob && String(blob.type) === 'application/zip') H.zip = blob
|
||
return origCreate(blob)
|
||
}
|
||
}
|
||
|
||
console.log('目标:本地 mock 页(about:blank)+ 插件源码 ' + PLUGIN_ENTRY)
|
||
const browser = await chromium.launch()
|
||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 }, acceptDownloads: true })
|
||
const consoleErrors = []
|
||
page.on('console', (m) => { if (m.type() === 'error') consoleErrors.push(m.text()) })
|
||
page.on('pageerror', (e) => consoleErrors.push('pageerror: ' + e.message))
|
||
|
||
await page.addInitScript(HOST_SETUP)
|
||
await page.goto('about:blank')
|
||
await page.addScriptTag({ path: PLUGIN_ENTRY })
|
||
|
||
// ---------- 源图与假节点 ----------
|
||
await page.evaluate(async () => {
|
||
const H = window.__H__
|
||
const make = (w, h, color) => {
|
||
const c = document.createElement('canvas')
|
||
c.width = w; c.height = h
|
||
const x = c.getContext('2d')
|
||
x.fillStyle = color; x.fillRect(0, 0, w, h)
|
||
return c.toDataURL('image/png')
|
||
}
|
||
const makeBlob = (w, h, color) => new Promise((resolve) => {
|
||
const c = document.createElement('canvas')
|
||
c.width = w; c.height = h
|
||
const x = c.getContext('2d')
|
||
x.fillStyle = color; x.fillRect(0, 0, w, h)
|
||
c.toBlob(resolve, 'image/png')
|
||
})
|
||
|
||
const rect = make(400, 200, '#2f6fed')
|
||
const square = make(300, 300, '#e8a13c')
|
||
const noise = (() => {
|
||
const c = document.createElement('canvas')
|
||
c.width = 800; c.height = 800
|
||
const x = c.getContext('2d')
|
||
const img = x.createImageData(800, 800)
|
||
for (let i = 0; i < img.data.length; i += 4) {
|
||
img.data[i] = (Math.random() * 256) | 0
|
||
img.data[i + 1] = (Math.random() * 256) | 0
|
||
img.data[i + 2] = (Math.random() * 256) | 0
|
||
img.data[i + 3] = 255
|
||
}
|
||
x.putImageData(img, 0, 0)
|
||
return c.toDataURL('image/png')
|
||
})()
|
||
|
||
H.nodes = [
|
||
{ id: 'n1', type: 'ref', x: 0, y: 0, data: { name: '菜单A.png', data: rect } },
|
||
{ id: 'n2', type: 'ref', x: 0, y: 0, data: { name: '菜单B.png', data: square } },
|
||
{ id: 'n3', type: 'ref', x: 0, y: 0, data: { name: 'DQ_主图.png', data: rect } },
|
||
{ id: 'n4', type: 'ref', x: 0, y: 0, data: { name: '空节点', data: '' } },
|
||
{ id: 'n5', type: 'gen', x: 0, y: 0, data: { name: '生图结果', data: rect } },
|
||
{ id: 'n6', type: 'ref', x: 0, y: 0, data: { name: '噪声图.png', data: noise } },
|
||
]
|
||
H.images = {
|
||
n1: { dataUrl: rect },
|
||
n2: { dataUrl: square },
|
||
n3: { dataUrl: rect },
|
||
n6: { dataUrl: noise },
|
||
}
|
||
|
||
// rmbg mock:返回一张 200×100 的 PNG 字节(抠图服务契约:二进制进、PNG 字节出)
|
||
window.__RMBG_BLOB__ = await makeBlob(200, 100, '#2fbf71')
|
||
const origFetch = window.fetch
|
||
window.fetch = function (url) {
|
||
if (String(url).indexOf('/rmbg') >= 0) {
|
||
H.rmbgCalls++
|
||
return Promise.resolve(new Response(window.__RMBG_BLOB__, { status: 200, headers: { 'Content-Type': 'image/png' } }))
|
||
}
|
||
return origFetch.apply(this, arguments)
|
||
}
|
||
})
|
||
|
||
// ---------- 1) manifest / 注册 ----------
|
||
const m = await page.evaluate(() => window.__H__.manifest)
|
||
check('manifest:id = batch-export', m && m.id === 'batch-export', String(m && m.id))
|
||
check('manifest:name = 批量出图', m && m.name === '批量出图', String(m && m.name))
|
||
// 版本号从 package.json 读,不在测试里钉死 —— 否则每次发版都要记得改测试(1.2.0 这次就漏了)
|
||
const PKG_VERSION = createRequire(import.meta.url)('../package.json').version
|
||
check('manifest:version = package.json(' + PKG_VERSION + ')', m && m.version === PKG_VERSION, String(m && m.version))
|
||
check('manifest:apiVersion = 1', m && m.apiVersion === 1, String(m && m.apiVersion))
|
||
check('manifest:capabilities = [panels, canvas](只读画布,不写节点)',
|
||
m && JSON.stringify(m.capabilities) === JSON.stringify(['panels', 'canvas']), JSON.stringify(m && m.capabilities))
|
||
check('manifest:settings = apiUrl / timeoutMs',
|
||
m && JSON.stringify(Object.keys(m.settings || {}).sort()) === JSON.stringify(['apiUrl', 'timeoutMs']),
|
||
JSON.stringify(Object.keys(m.settings || {})))
|
||
|
||
const panels = await page.evaluate(() => window.__H__.panels.map((p) => ({ id: p.id, title: p.title, hasMount: typeof p.mount === 'function' })))
|
||
check('面板:恰好注册 1 个(batch-panel / 批量出图 / 有 mount)',
|
||
panels.length === 1 && panels[0].id === 'batch-panel' && panels[0].title === '批量出图' && panels[0].hasMount,
|
||
JSON.stringify(panels))
|
||
|
||
// ---------- 2) 挂载 + 列表 ----------
|
||
await page.evaluate(() => {
|
||
const host = document.createElement('div')
|
||
host.className = 'iwb-full-panel-plugin'
|
||
host.style.height = '700px'
|
||
document.body.appendChild(host)
|
||
window.__PANEL__ = host
|
||
window.__H__.panels[0].mount(host)
|
||
})
|
||
check('挂载:面板根节点已注入(.iwb-bx)', await page.evaluate(() => Boolean(document.querySelector('.iwb-bx'))))
|
||
|
||
const rows = () => page.evaluate(() => Array.from(document.querySelectorAll('.iwb-bx-item')).map((r) => r.querySelector('.iwb-bx-name').textContent))
|
||
const rowCount = await page.evaluate(() => document.querySelectorAll('.iwb-bx-item').length)
|
||
check('列表:只列 ref 且有图的节点(4 行:过滤空 ref 与 gen)', rowCount === 4, String(rowCount))
|
||
check('列表:顺序与节点一致', JSON.stringify(await rows()) === JSON.stringify(['菜单A.png', '菜单B.png', 'DQ_主图.png', '噪声图.png']),
|
||
JSON.stringify(await rows()))
|
||
|
||
// ---------- 2b) 隔断 / 缩略图 / 全选清空 ----------
|
||
const sec = await page.evaluate(() => {
|
||
const s = document.querySelector('.iwb-bx-sec')
|
||
if (!s) return null
|
||
return { text: (s.textContent || '').trim(), btns: Array.from(s.querySelectorAll('button')).map((b) => b.textContent.trim()) }
|
||
})
|
||
check('隔断:配置区下方有「待处理节点」小节头,操作按钮归到列表区',
|
||
Boolean(sec) && sec.text.indexOf('待处理节点') === 0 && JSON.stringify(sec.btns) === JSON.stringify(['全选', '清空', '刷新']),
|
||
JSON.stringify(sec))
|
||
|
||
const thumbInfo = await poll(() => page.evaluate(() => {
|
||
const imgs = Array.from(document.querySelectorAll('.iwb-bx-item img.iwb-bx-thumb'))
|
||
return imgs.length === 4 && imgs.every((i) => i.complete && i.naturalWidth > 0)
|
||
? { n: imgs.length, w: imgs[0].naturalWidth, h: imgs[0].naturalHeight }
|
||
: false
|
||
}))
|
||
check('缩略图:每行都有源图缩略图且已解码(缩到 64px 长边)',
|
||
Boolean(thumbInfo) && thumbInfo.w === 64, JSON.stringify(thumbInfo))
|
||
|
||
// 清空必须真的取消勾选:1.1.0 前 el() 用 setAttribute('checked','false'),属性有值 ⇒ 视觉上仍勾着
|
||
await page.getByRole('button', { name: '清空', exact: true }).click()
|
||
const afterClear = await page.evaluate(() => Array.from(document.querySelectorAll('.iwb-bx-item input[type=checkbox]')).map((c) => c.checked))
|
||
check('清空:点击后勾选框全部取消(checked 属性为 false)', afterClear.every((v) => v === false), JSON.stringify(afterClear))
|
||
|
||
await page.getByRole('button', { name: '全选', exact: true }).click()
|
||
const afterAll = await page.evaluate(() => Array.from(document.querySelectorAll('.iwb-bx-item input[type=checkbox]')).map((c) => c.checked))
|
||
check('全选:点击后勾选框全部勾上', afterAll.length === 4 && afterAll.every((v) => v === true), JSON.stringify(afterAll))
|
||
|
||
const dflt = await page.evaluate(() => ({
|
||
size: document.querySelectorAll('.iwb-bx-bar select')[0].value,
|
||
mode: document.querySelectorAll('.iwb-bx-bar select')[1].value,
|
||
ratio: document.querySelector('.iwb-bx-bar input[type=number]').value,
|
||
max: document.querySelectorAll('.iwb-bx-bar input[type=number]')[1].value,
|
||
cutout: document.querySelector('.iwb-bx-bar input[type=checkbox]').checked,
|
||
}))
|
||
check('默认参数:800 / dual / 80% / 500KB / 抠图未勾',
|
||
dflt.size === '800' && dflt.mode === 'dual' && dflt.ratio === '80' && dflt.max === '500' && dflt.cutout === false,
|
||
JSON.stringify(dflt))
|
||
|
||
// ---------- 2.5) 行内单张下载:未处理时必须灰 ----------
|
||
const dlButtons = () => page.evaluate(() => Array.from(document.querySelectorAll('.iwb-bx-item .iwb-bx-dl')).map((b) => ({
|
||
text: b.textContent, disabled: b.disabled, title: b.title,
|
||
})))
|
||
const idleDl = await dlButtons()
|
||
check('下载按钮:每行都有 JPG / PNG 两个(4 行 = 8 个)',
|
||
idleDl.length === 8 && idleDl[0].text === 'JPG' && idleDl[1].text === 'PNG',
|
||
JSON.stringify(idleDl.slice(0, 2)))
|
||
check('下载按钮:未处理时全部灰不可点', idleDl.every((b) => b.disabled === true), JSON.stringify(idleDl.map((b) => b.disabled)))
|
||
check('下载按钮:未处理时提示「处理完成后可下载」',
|
||
idleDl.every((b) => b.title.indexOf('处理完成后可下载') === 0), idleDl[0].title)
|
||
|
||
// ---------- 3) 跑队列 ----------
|
||
const clickBtn = (text) => page.evaluate((t) => {
|
||
const btn = Array.from(document.querySelectorAll('.iwb-bx-foot button')).find((b) => b.textContent === t)
|
||
if (btn) btn.click()
|
||
return Boolean(btn)
|
||
}, text)
|
||
|
||
check('队列:找到「开始出图」按钮', await clickBtn('开始出图'))
|
||
await poll(() => page.evaluate(() => document.querySelector('.iwb-bx-foot .iwb-bx-tag').textContent === '4/4'))
|
||
const afterRun = await page.evaluate(() => ({
|
||
progress: document.querySelector('.iwb-bx-foot .iwb-bx-tag').textContent,
|
||
tags: Array.from(document.querySelectorAll('.iwb-bx-item .iwb-bx-tag')).map((t) => t.textContent),
|
||
}))
|
||
check('队列:进度 4/4', afterRun.progress === '4/4', afterRun.progress)
|
||
check('队列:每行「2 个文件」(双版本)', afterRun.tags.every((t) => t.indexOf('2 个文件') === 0), JSON.stringify(afterRun.tags))
|
||
|
||
// ---------- 3.5) 双版本跑完后:两个按钮都亮,点击能真的触发下载 ----------
|
||
const doneDl = await dlButtons()
|
||
check('下载按钮:双版本跑完后 JPG / PNG 全部可点', doneDl.every((b) => b.disabled === false), JSON.stringify(doneDl.map((b) => b.disabled)))
|
||
check('下载按钮:提示里带真实文件名与体积',
|
||
/\.jpg([\d.]+KB)/.test(doneDl[0].title) && /\.png([\d.]+KB)/.test(doneDl[1].title),
|
||
doneDl[0].title + ' | ' + doneDl[1].title)
|
||
|
||
// 拦截 a.click 记录 download 属性:jsdom 不会真下载,但能验证「点了哪个文件」
|
||
await page.evaluate(() => {
|
||
window.__DL__ = []
|
||
const orig = HTMLAnchorElement.prototype.click
|
||
HTMLAnchorElement.prototype.click = function () {
|
||
if (this.download) window.__DL__.push(this.download)
|
||
return orig.apply(this, arguments)
|
||
}
|
||
})
|
||
await page.evaluate(() => {
|
||
const btn = document.querySelectorAll('.iwb-bx-item')[0].querySelectorAll('.iwb-bx-dl')
|
||
btn[0].click() // JPG
|
||
btn[1].click() // PNG
|
||
})
|
||
const dlNames = await page.evaluate(() => window.__DL__)
|
||
check('下载按钮:点 JPG / PNG 各触发一次下载,扩展名与按钮一致',
|
||
dlNames.length === 2 && /\.jpg$/.test(dlNames[0]) && /\.png$/.test(dlNames[1]),
|
||
JSON.stringify(dlNames))
|
||
|
||
// ---------- 4) ZIP ----------
|
||
check('ZIP:找到「导出 ZIP」按钮', await clickBtn('导出 ZIP'))
|
||
await poll(() => page.evaluate(() => Boolean(window.__H__.zip)))
|
||
|
||
const zipB64 = await page.evaluate(async () => {
|
||
const buf = await window.__H__.zip.arrayBuffer()
|
||
const u8 = new Uint8Array(buf)
|
||
let bin = ''
|
||
for (let i = 0; i < u8.length; i += 0x8000) bin += String.fromCharCode.apply(null, u8.subarray(i, i + 0x8000))
|
||
return btoa(bin)
|
||
})
|
||
const tmp = mkdtempSync(path.join(tmpdir(), 'iwb-batch-'))
|
||
const zipPath = path.join(tmp, 'out.zip')
|
||
writeFileSync(zipPath, Buffer.from(zipB64, 'base64'))
|
||
check('ZIP:非空', Buffer.from(zipB64, 'base64').length > 1000, Buffer.from(zipB64, 'base64').length + ' bytes')
|
||
|
||
let zipTest = ''
|
||
try {
|
||
zipTest = execFileSync('unzip', ['-t', zipPath], { encoding: 'utf8' })
|
||
} catch (error) {
|
||
zipTest = String(error.stdout || error.message)
|
||
}
|
||
check('ZIP:系统 unzip -t 校验通过(结构与 CRC 合法)', /No errors detected/.test(zipTest), zipTest.trim().split('\n').pop())
|
||
|
||
// 命名与条目内容用 python3 的 zipfile 验 —— macOS 自带的 Info-ZIP 6.0 不认 ZIP 的 UTF-8 标志位(bit 11),
|
||
// 会把中文名按本地编码解成乱码并报 "Illegal byte sequence";那是验证工具的锅,不是 ZIP 的。
|
||
// python3 zipfile / Windows 资源管理器 / macOS 归档实用工具(libarchive)都正确支持 bit 11。
|
||
const pythonProbe = `
|
||
import sys, zipfile
|
||
z = zipfile.ZipFile(sys.argv[1])
|
||
for n in z.namelist():
|
||
print("ENTRY|" + n + "|" + z.read(n)[:4].hex())
|
||
`
|
||
let probeOut = ''
|
||
try {
|
||
probeOut = execFileSync('python3', ['-c', pythonProbe, zipPath], { encoding: 'utf8' })
|
||
} catch (error) {
|
||
probeOut = 'PROBE_FAILED ' + String(error.stdout || error.message)
|
||
}
|
||
const entries = probeOut.split('\n').filter((l) => l.startsWith('ENTRY|')).map((l) => {
|
||
const [, name, magic] = l.split('|')
|
||
return { name, magic }
|
||
})
|
||
const wantNames = ['菜单A_800x800.png', '菜单A_800x800.jpg', '菜单B_800x800.png', '菜单B_800x800.jpg', 'DQ_主图_800x800.png', 'DQ_主图_800x800.jpg', '噪声图_800x800.png', '噪声图_800x800.jpg']
|
||
const matched = wantNames.filter((n) => entries.some((e) => e.name === n))
|
||
check('ZIP:8 个条目、中文名与双版本命名正确', matched.length === 8 && entries.length === 8,
|
||
entries.map((e) => e.name).join(' / ') || probeOut.slice(0, 120))
|
||
|
||
const pngOk = entries.filter((e) => e.name.endsWith('.png')).every((e) => e.magic === '89504e47')
|
||
const jpgOk = entries.filter((e) => e.name.endsWith('.jpg')).every((e) => /^ffd8ff/.test(e.magic))
|
||
check('ZIP:解出的 .png 都是 PNG 头(89504e47)、.jpg 都是 JPEG 头(ffd8ff)', pngOk && jpgOk,
|
||
entries.map((e) => e.name.split('.').pop() + '=' + e.magic).join(' '))
|
||
|
||
// ---------- 6) 抠图分支 ----------
|
||
await page.evaluate(() => {
|
||
const chk = document.querySelector('.iwb-bx-bar input[type=checkbox]')
|
||
chk.checked = true
|
||
chk.dispatchEvent(new Event('change'))
|
||
})
|
||
await clickBtn('开始出图')
|
||
await poll(() => page.evaluate(() => document.querySelector('.iwb-bx-foot .iwb-bx-tag').textContent === '4/4'))
|
||
const cutStats = await page.evaluate(() => ({ calls: window.__H__.rmbgCalls, tags: Array.from(document.querySelectorAll('.iwb-bx-item .iwb-bx-tag')).map((t) => t.textContent) }))
|
||
check('抠图:勾选后每张都走 rmbg(4 次)', cutStats.calls === 4, String(cutStats.calls))
|
||
check('抠图:走完仍全部成功(2 个文件/行)', cutStats.tags.every((t) => t.indexOf('2 个文件') === 0), JSON.stringify(cutStats.tags))
|
||
|
||
// ---------- 7) 体积上限失败行内提示 ----------
|
||
await page.evaluate(() => {
|
||
const chk = document.querySelector('.iwb-bx-bar input[type=checkbox]')
|
||
chk.checked = false
|
||
chk.dispatchEvent(new Event('change'))
|
||
const max = document.querySelectorAll('.iwb-bx-bar input[type=number]')[1]
|
||
max.value = '1'
|
||
max.dispatchEvent(new Event('change'))
|
||
})
|
||
await clickBtn('开始出图')
|
||
await poll(() => page.evaluate(() => document.querySelector('.iwb-bx-foot .iwb-bx-tag').textContent === '4/4'))
|
||
const failTags = await page.evaluate(() => Array.from(document.querySelectorAll('.iwb-bx-item .iwb-bx-tag')).map((t) => t.textContent))
|
||
check('失败:maxKB=1 时行内显示失败原因(含「已压到质量 20」)',
|
||
failTags.every((t) => t.indexOf('失败 · 已压到质量 20') === 0), JSON.stringify(failTags.slice(0, 2)))
|
||
check('失败:出现「重试」按钮', await page.evaluate(() => Array.from(document.querySelectorAll('.iwb-bx-item button')).some((b) => b.textContent === '重试')))
|
||
|
||
// ---------- 8) 参数持久化(此时已改过 cutout / maxKB,应该有落盘记录) ----------
|
||
const saved = await page.evaluate(() => (window.__H__.storage.opts ? window.__H__.storage.opts.panel : null))
|
||
check('持久化:参数写入 storage(namespace=opts),含改过的 cutout / maxKB',
|
||
Boolean(saved) && saved.cutout === false && saved.maxKB === 1 && saved.size === 800 && saved.mode === 'dual',
|
||
JSON.stringify(saved))
|
||
|
||
// ---------- 8) 静态检查 ----------
|
||
const offenders = []
|
||
const src = (await import('node:fs')).readFileSync(PLUGIN_ENTRY, 'utf8')
|
||
for (const [i, line] of src.split('\n').entries()) {
|
||
const n = i + 1
|
||
if (/fetch\(\s*(['"])data:/.test(line)) offenders.push(n + ': fetch(data:)')
|
||
if (/\beval\s*\(/.test(line)) offenders.push(n + ': eval')
|
||
if (/new\s+Function\s*\(/.test(line)) offenders.push(n + ': new Function')
|
||
if (/\bimport\b/.test(line)) offenders.push(n + ': import')
|
||
if (/\brequire\s*\(/.test(line)) offenders.push(n + ': require')
|
||
}
|
||
check('静态检查:无 fetch(data:) / eval / new Function / import / require', offenders.length === 0, offenders.slice(0, 3).join(' | '))
|
||
check('静态检查:ZIP 文件名 UTF-8 标志位(bit 11 = 0x0800)已写', /setUint16\(6,\s*0x0800/.test(src))
|
||
|
||
// ---------- 12) 宿主复用容器(切到图库/节点组)时必须自行摘除 ----------
|
||
// 真机现象:切到「图库」后批量面板仍留在上方,因为宿主两端都渲染成 div 且无 key,React 复用同一节点,
|
||
// 只清它自己管理的子节点,插件 append 的根节点留在原地。这里模拟宿主复用行为。
|
||
const switchAway = await page.evaluate(async () => {
|
||
const host = window.__PANEL__
|
||
host.className = 'iwb-history-embedded'
|
||
host.appendChild(document.createElement('div')) // 宿主渲染的图库内容
|
||
await new Promise((r) => setTimeout(r, 60))
|
||
return { hasPanel: Boolean(document.querySelector('.iwb-bx')), hostKids: host.children.length }
|
||
})
|
||
check('切换 tab:容器被复用给图库后,插件根节点自动摘除(不串页)',
|
||
switchAway.hasPanel === false, JSON.stringify(switchAway))
|
||
|
||
const switchBack = await page.evaluate(async () => {
|
||
const host = window.__PANEL__
|
||
host.className = 'iwb-full-panel-plugin'
|
||
host.textContent = '' // 宿主先卸掉图库内容,再挂载插件
|
||
await new Promise((r) => setTimeout(r, 60))
|
||
return { hasPanel: Boolean(document.querySelector('.iwb-bx')), rows: document.querySelectorAll('.iwb-bx-item').length }
|
||
})
|
||
check('切回插件 tab:面板自动重新挂载、节点列表仍在',
|
||
switchBack.hasPanel === true && switchBack.rows > 0, JSON.stringify(switchBack))
|
||
|
||
// ---------- 6) 单版本模式:不产出的格式必须灰(而不是亮着却点不出东西) ----------
|
||
await page.evaluate(() => {
|
||
const modeSel = document.querySelectorAll('.iwb-bx-bar select')[1]
|
||
modeSel.value = 'jpeg'
|
||
modeSel.dispatchEvent(new Event('change', { bubbles: true }))
|
||
const maxIn = document.querySelectorAll('.iwb-bx-bar input[type=number]')[1]
|
||
maxIn.value = '500'
|
||
maxIn.dispatchEvent(new Event('change', { bubbles: true }))
|
||
const cut = document.querySelector('.iwb-bx-bar input[type=checkbox]')
|
||
if (cut.checked) { cut.checked = false; cut.dispatchEvent(new Event('change', { bubbles: true })) }
|
||
})
|
||
await page.getByRole('button', { name: '全选', exact: true }).click()
|
||
check('仅 JPG:找到「开始出图」按钮', await clickBtn('开始出图'))
|
||
// 不能用「进度 4/4」当完成信号:上一轮结束时已经是 4/4,会立刻返回而状态还没刷新
|
||
await poll(() => page.evaluate(() => {
|
||
const tags = Array.from(document.querySelectorAll('.iwb-bx-item .iwb-bx-tag'))
|
||
return tags.length === 4 && tags.every((t) => t.textContent.indexOf('1 个文件') === 0)
|
||
}))
|
||
const jpegOnly = await dlButtons()
|
||
check('仅 JPG 模式:JPG 可点、PNG 灰',
|
||
jpegOnly.length === 8 && jpegOnly.every((b, i) => (i % 2 === 0 ? b.disabled === false : b.disabled === true)),
|
||
JSON.stringify(jpegOnly.map((b) => b.disabled)))
|
||
check('仅 JPG 模式:PNG 灰态提示说明「本次设置不产出」',
|
||
jpegOnly[1] && jpegOnly[1].title.indexOf('本次设置不产出 PNG') === 0, jpegOnly[1] && jpegOnly[1].title)
|
||
|
||
check('无页面级运行时错误', consoleErrors.length === 0, consoleErrors.slice(0, 3).join(' | '))
|
||
|
||
await browser.close()
|
||
console.log('\n' + (failed ? '✗ 失败 ' + failed + ' 项' : '✓ 全部通过'))
|
||
process.exit(failed ? 1 : 0)
|