Files
iwb-plugins-desktop/image-vectorize/tools/e2e-site.mjs
T
qiqi d151de74a1 feat(image-vectorize): v0.2.1 精度可调 + 复制到剪贴板 + 高级默认展开
用户反馈三项:
1. 高级参数默认展开(不再藏起来),折叠按钮保留、展开状态记忆在 ctx.settings
2. 新增「复制 SVG」:一次写入 image/svg+xml + text/html + text/plain 三种口味,
   粘到 Figma / Illustrator 直接是真矢量。Chrome 对可写 MIME 有白名单,
   塞了不支持的类型会整次 write 失败,所以先 ClipboardItem.supports() 探测再逐级降级
3. 边缘精度可调:optTolerance 默认 0.2 → 0.05(三档 精细/标准/轻量),
   大图降采样上限 2000 → 3000px(实测单色 3200px 96ms、灰度 4 层 3000px 179ms)

预览底部的说明改为胶囊提示(原 #75758a 裸文字在浅灰棋盘上几乎看不见),
面板间距压紧,高级区展开后整列参数在 980px 高下不用滚。

验证:本地 harness 38 项、真站 e2e 17 项(含真实剪贴板读回校验)全绿。
2026-11-05 08:33:51 +08:00

209 lines
10 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.
// 真实站点端到端(开发用,不进 CI)。
//
// 与 harness 的分工:harness 用合成宿主,能验功能但不能验真实 CSP/网络;这里走真站 ——
// 真实的 `_headers`(**不含 wasm-unsafe-eval**)、真实 KV、浏览器 SRI 校验、真实画布桥。
// v0.2 是纯 JS potrace,所以这里反而要断言「wasm 仍被 CSP 拦住」——防止有人为了别的功能
// 悄悄把 'wasm-unsafe-eval' 加回去。
//
// 运行:
// node image-vectorize/tools/e2e-site.mjs
// IWB_BASE_URL=https://iwb.maqiart.eu.org node image-vectorize/tools/e2e-site.mjs
import { createRequire } from 'node:module'
import { readFileSync } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const HERE = path.dirname(fileURLToPath(import.meta.url))
const REPO = path.resolve(HERE, '../..')
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-web'
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')
process.exit(2)
}
const BASE = process.env.IWB_BASE_URL || 'https://test.image-workbench-web.pages.dev'
const PLUGIN_ID = 'image-vectorize'
const WANT_VERSION = JSON.parse(readFileSync(path.join(REPO, 'image-vectorize/package.json'), 'utf8')).version
const CFG = { providers: [], canvas: {} }
const WS = { workspaces: [{ id: 'w1', name: 'W', nodes: [], edges: [], groups: [] }], activeId: 'w1', rev: 1 }
let failed = 0
const check = (name, ok, detail) => {
if (!ok) failed++
console.log((ok ? '✓ ' : '✗ ') + name + (detail ? ' ' + detail : ''))
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
const poll = async (fn, timeout = 25000, step = 250) => {
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 sleep(step)
}
}
console.log('目标站点:' + BASE + '(期望插件版本 ' + WANT_VERSION + ')')
const browser = await chromium.launch()
// 剪贴板要显式授权(真站是 https,安全上下文成立;本地 file/about:blank 测不到这条)
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } })
try {
await context.grantPermissions(['clipboard-read', 'clipboard-write'], { origin: new URL(BASE).origin })
} catch (error) {
console.log('(剪贴板授权失败,相关断言会跳过:' + (error && error.message) + ')')
}
const page = await context.newPage()
const consoleErrors = []
page.on('console', (m) => { if (m.type() === 'error') consoleErrors.push(m.text()) })
page.on('pageerror', (e) => consoleErrors.push('pageerror: ' + e.message))
page.on('dialog', (d) => { consoleErrors.push('unexpected dialog: ' + d.message()); d.dismiss().catch(() => {}) })
await page.goto('about:blank')
const PNG = await page.evaluate(() => {
const c = document.createElement('canvas')
c.width = 320; c.height = 320
const g = c.getContext('2d')
g.fillStyle = '#ffffff'; g.fillRect(0, 0, 320, 320)
g.fillStyle = '#e8422f'; g.beginPath(); g.arc(96, 96, 58, 0, Math.PI * 2); g.fill()
g.fillStyle = '#1f5fa8'; g.beginPath(); g.roundRect(170, 130, 120, 84, 12); g.fill()
g.fillStyle = '#111111'; g.font = 'bold 38px "PingFang SC", sans-serif'; g.fillText('菜单', 96, 250)
return c.toDataURL('image/png')
})
await page.addInitScript((d) => {
localStorage.clear()
localStorage.setItem('iwb_web_cfg', JSON.stringify(d.cfg))
const ws = JSON.parse(JSON.stringify(d.ws))
ws.workspaces[0].nodes = [{ id: 'r1', type: 'ref', x: 140, y: 140, data: { url: '', data: d.png, name: 'src.png', localName: null } }]
localStorage.setItem('iwb_web_workspaces', JSON.stringify(ws))
localStorage.setItem('iwb_ws_active', ws.activeId)
localStorage.setItem('iwb_ws_w1', JSON.stringify(ws.workspaces[0]))
localStorage.setItem('iwb_web_outputs', JSON.stringify([]))
localStorage.setItem('iwb_plugins', JSON.stringify({ [d.id]: { enabled: true, settings: {}, data: {} } }))
}, { cfg: CFG, ws: WS, png: PNG, id: PLUGIN_ID })
const resp = await page.goto(BASE + '/', { waitUntil: 'domcontentloaded' })
check('站点可达', Boolean(resp && resp.ok()), resp && String(resp.status()))
// ---------- 1) 真实 KV 加载 + SRI ----------
await page.waitForFunction(() => Boolean(window.IWBPluginHost) && window.IWBPluginHost.snapshot().initialized === true, null, { timeout: 30000 })
const active = await poll(async () => page.evaluate((id) => {
const p = window.IWBPluginHost.list().find((x) => x.id === id)
return p && p.active ? { version: p.version, enabled: p.enabled, capabilities: p.capabilities, error: p.error } : false
}, PLUGIN_ID))
check('从真实 KV 加载并启用(SRI 通过)', Boolean(active), JSON.stringify(active))
check('线上版本 = package.json(' + WANT_VERSION + ')', Boolean(active && active.version === WANT_VERSION), active && active.version)
const scripts = await page.evaluate(() => Array.from(document.querySelectorAll('script[src*="/plugins/"]')).map((s) => ({ src: s.getAttribute('src'), integrity: s.getAttribute('integrity') || '' })))
check('插件脚本用 SRI(sha256) 加载',
scripts.some((s) => s.src.indexOf('/plugins/plugin-' + PLUGIN_ID + '.') === 0 && /^sha256-/.test(s.integrity)),
JSON.stringify(scripts.map((s) => s.src)))
// ---------- 2) 宿主 CSP 不再放行 wasm(v0.2 纯 JS,不需要放宽) ----------
const cspProbe = await page.evaluate(async () => {
try {
const b = Uint8Array.from(atob('AGFzbQEAAAA='), (c) => c.charCodeAt(0))
await WebAssembly.instantiate(b)
return 'ok'
} catch (e) { return 'blocked: ' + e.message }
})
check('宿主 CSP 仍禁止 wasm 编译(本插件是纯 JS,不该再放宽)', cspProbe.indexOf('blocked') === 0, cspProbe.slice(0, 120))
// ---------- 3) 打开工作区 ----------
await page.locator('.iwb-home-card:not(.iwb-home-new)').first().dblclick()
await page.locator('.iwb-canvas:not(.iwb-canvas-hidden)').waitFor({ state: 'visible', timeout: 30000 })
check('工作区打开、种子节点在画布', (await page.locator('.iwb-node[data-node-id="r1"]').count()) === 1)
// ---------- 4) 入口 → 模态 ----------
await page.locator('.iwb-node[data-node-id="r1"]').click()
const floatBtn = page.locator('.iwb-node-floatbar button[title="位图转矢量"]')
let entry = ''
if (await floatBtn.count()) {
await floatBtn.click()
entry = '漂浮菜单'
} else {
await page.locator('.iwb-canvas').click({ button: 'right', position: { x: 900, y: 620 } })
await page.locator('.iwb-ctxmenu .iwb-ctx-item').filter({ hasText: '位图转矢量' }).first().click()
entry = '右键命令'
}
await page.locator('.vz-modal').waitFor({ state: 'visible', timeout: 30000 })
check('节点入口可触发(' + entry + ')', true)
check('样式注入生效(CSP unsafe-inline)', await page.evaluate(() => {
const s = document.getElementById('iwb-vectorize-style')
return Boolean(s && s.textContent.indexOf('.vz-') >= 0)
}))
// ---------- 5) 真站 CSP 下引擎能跑 ----------
const paths = await poll(async () => {
const t = await page.locator('[data-stat="paths"]').textContent()
return t && t !== '–' && Number(t) > 0 ? t : false
}, 30000)
check('真站描摹成功(纯 JS 引擎,无 wasm)', Boolean(paths), 'paths=' + paths)
check('预览为 blob: SVG', await page.evaluate(() => {
const v = document.querySelector('[data-stage="vector"]')
return Boolean(v && /^blob:/.test(v.src) && !v.hidden)
}))
const stats = await page.evaluate(() => ({
levels: Number(document.querySelector('[data-stat="levels"]').textContent),
bytes: document.querySelector('[data-stat="bytes"]').textContent,
ms: document.querySelector('[data-stat="ms"]').textContent,
}))
check('灰度层数正常(3 层)', stats.levels >= 3, JSON.stringify(stats))
// ---------- 5.5) 面板形态:高级默认打开 + 精度默认精细 ----------
check('高级参数默认展开', await page.evaluate(() => {
const box = document.querySelector('[data-adv]')
return Boolean(box && !box.hidden)
}))
check('精度默认「精细」', await page.evaluate(() => {
const a = document.querySelector('[data-seg-group="precision"] button.active')
return Boolean(a && a.dataset.value === 'fine')
}))
// ---------- 5.6) 复制到剪贴板(真写,读回校验口味) ----------
await page.locator('[data-act="copy"]').click()
await sleep(400)
const clip = await page.evaluate(async () => {
try {
const items = await navigator.clipboard.read()
const types = items[0] ? items[0].types : []
let svg = ''
if (types.indexOf('image/svg+xml') >= 0) svg = await (await items[0].getType('image/svg+xml')).text()
return { types, svg, status: (document.querySelector('[data-status-text]') || {}).textContent || '' }
} catch (e) { return { error: String(e && e.message) } }
})
if (clip.error) {
check('复制 SVG 写入剪贴板', false, clip.error)
} else {
check('复制 SVG:剪贴板含 image/svg+xml(Figma 按矢量粘贴)',
clip.types.indexOf('image/svg+xml') >= 0 && clip.svg.indexOf('<svg') === 0 && clip.svg.indexOf('<path') > 0,
clip.types.join(',') + ' / ' + clip.svg.length + 'B')
check('复制后给了反馈', /已复制/.test(clip.status), clip.status)
}
// ---------- 6) 保存为节点(真实画布桥) ----------
await page.locator('[data-act="save"]').click()
const saved = await poll(async () => (await page.locator('.iwb-node').count()) >= 2, 25000)
check('保存为节点:画布新增一个图片节点', Boolean(saved), 'nodes=' + await page.locator('.iwb-node').count())
check('模态已关闭', (await page.locator('.vz-root').count()) === 0)
const fatal = consoleErrors.filter((e) => /Content Security Policy|Refused to|SRI|integrity/i.test(e))
check('无 CSP / SRI 报错', fatal.length === 0, fatal.slice(0, 2).join(' | '))
if (consoleErrors.length) {
console.log('')
console.log('控制台错误(' + consoleErrors.length + ' 条,前 5 条):')
for (const e of consoleErrors.slice(0, 5)) console.log(' ' + String(e).slice(0, 180))
}
console.log('')
console.log(failed ? '✗ 失败 ' + failed + ' 项' : '✓ 全部通过')
await browser.close()
process.exit(failed ? 1 : 0)