- 粘贴优先级:剪贴板图片文件 > text/html 的 <img src> > text/plain 图片 URL/data URL - 命中后进入既有「图片放置」模式(拖动/缩放,点外部或回车确认,Esc 取消) - URL 一律 fetch→blob→dataURL(跨域图直接挂 <img> 会污染画布,导出时 toBlob 抛 SecurityError); data: URL 反而不能 fetch(CSP connect-src 无 data:),直接走 loadImage - 命中即 stopImmediatePropagation:宿主在 window 气泡阶段也监听 paste(建 ref 节点+下载), 不掐断会一次粘贴双响应,且宿主抢先建节点会破坏后续「覆盖」写回(e2e 实测抓到) - 正在文字输入框打字时不抢 text/html 与 text/plain 的粘贴 - e2e 新增合成 ClipboardEvent 粘贴用例;修过期 SRI 断言(内容寻址名带哈希)
189 lines
10 KiB
JavaScript
189 lines
10 KiB
JavaScript
// 真实站点端到端(开发用,不进 CI)。
|
||
//
|
||
// 为什么需要它:mock 页没有 CSP,`connect-src` 一类问题(例如 `fetch(dataURL)` 被
|
||
// `connect-src 'self' https: …` 拦掉)在 mock 下永远绿,只有带 CSP 的真站能抓出来。
|
||
// 它不 mock /plugins/*:走真实 KV + 浏览器 SRI 校验 + 真实画布桥。
|
||
//
|
||
// 运行:
|
||
// node image-annotate/tools/e2e-site.mjs
|
||
// IWB_BASE_URL=https://iwb.maqiart.eu.org node image-annotate/tools/e2e-site.mjs
|
||
// 依赖:playwright(本仓/宿主仓 node_modules 均可;或用 IWB_PLAYWRIGHT_ROOT 指定)。
|
||
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)) // <repo>/image-annotate/tools
|
||
const REPO = path.resolve(HERE, '../..') // <repo>
|
||
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:')
|
||
console.error(' npm i -D playwright # 本仓或宿主仓皆可')
|
||
console.error(' IWB_PLAYWRIGHT_ROOT=/path/to/repo node image-annotate/tools/e2e-site.mjs')
|
||
process.exit(2)
|
||
}
|
||
|
||
const BASE = process.env.IWB_BASE_URL || 'https://test.image-workbench-web.pages.dev'
|
||
const WANT_VERSION = JSON.parse(readFileSync(path.join(REPO, 'image-annotate/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 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 new Promise((r) => setTimeout(r, step))
|
||
}
|
||
}
|
||
|
||
console.log('目标站点:' + BASE + '(期望插件版本 ' + WANT_VERSION + ')')
|
||
const browser = await chromium.launch()
|
||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } })
|
||
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(() => {}) })
|
||
|
||
// 造一张真实的 96x64 PNG 作为节点图片
|
||
await page.goto('about:blank')
|
||
const PNG = await page.evaluate(() => {
|
||
const c = document.createElement('canvas')
|
||
c.width = 96; c.height = 64
|
||
const x = c.getContext('2d')
|
||
x.fillStyle = '#2f6fed'; x.fillRect(0, 0, 96, 64)
|
||
x.fillStyle = '#ffffff'; x.fillRect(20, 12, 56, 40)
|
||
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({ 'image-annotate': { enabled: true, settings: {}, data: {} } }))
|
||
}, { cfg: CFG, ws: WS, png: PNG })
|
||
|
||
const resp = await page.goto(BASE + '/', { waitUntil: 'domcontentloaded' })
|
||
check('站点可达', Boolean(resp && resp.ok()), resp && String(resp.status()))
|
||
await page.waitForFunction(() => Boolean(window.IWBPluginHost) && window.IWBPluginHost.snapshot().initialized === true, null, { timeout: 30000 })
|
||
|
||
// ---------- 1) 真实 KV 加载 + SRI + 启用 ----------
|
||
const active = await poll(async () => page.evaluate(() => {
|
||
const p = window.IWBPluginHost.list().find((x) => x.id === 'image-annotate')
|
||
return p && p.active ? { version: p.version, enabled: p.enabled, capabilities: p.capabilities, error: p.error } : false
|
||
}))
|
||
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) => /^\/plugins\/plugin-image-annotate\.[a-f0-9]{12}\.js$/.test(s.src) && /^sha256-/.test(s.integrity)), JSON.stringify(scripts))
|
||
|
||
// ---------- 2) 打开工作区 + 节点存在 ----------
|
||
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)
|
||
|
||
// ---------- 3) 入口:节点漂浮菜单(回落右键插件命令)----------
|
||
const openEditor = async () => {
|
||
await page.locator('.iwb-node[data-node-id="r1"]').click()
|
||
const btn = page.locator('.iwb-node-floatbar button[title="标注 / 修图"]')
|
||
if (await btn.count()) { await btn.click(); return '漂浮菜单' }
|
||
await page.locator('.iwb-canvas').click({ button: 'right', position: { x: 900, y: 620 } })
|
||
await page.locator('.iwb-ctxmenu .iwb-ctx-item').filter({ hasText: '标注 / 修图:选中节点' }).click()
|
||
return '右键命令'
|
||
}
|
||
const entry = await openEditor()
|
||
check('节点入口可触发(漂浮菜单或右键命令)', true, entry)
|
||
|
||
// ---------- 4) 编辑器打开(真实 CSP 下注入样式)----------
|
||
await page.locator('#iwb-editor-overlay').waitFor({ state: 'visible', timeout: 30000 })
|
||
const opened = await page.evaluate(() => {
|
||
const el = document.querySelector('#iwb-editor-overlay')
|
||
const style = document.getElementById('iwb-annotate-style')
|
||
return {
|
||
display: getComputedStyle(el).display,
|
||
position: getComputedStyle(el).position,
|
||
zIndex: getComputedStyle(el).zIndex,
|
||
bg: getComputedStyle(el).backgroundColor,
|
||
styleInjected: Boolean(style && style.textContent.includes('.iwb-editor-')),
|
||
}
|
||
})
|
||
check('编辑器浮层可见', opened.display === 'flex' && opened.position === 'fixed')
|
||
check('样式注入生效(CSP unsafe-inline)', opened.styleInjected)
|
||
check('浮层压住宿主 UI', Number(opened.zIndex) >= 999998, 'z=' + opened.zIndex + ' bg=' + opened.bg)
|
||
|
||
// ---------- 4.5) 剪贴板粘贴:⌘V 把剪贴板图片贴为新图层 ----------
|
||
// 合成 ClipboardEvent(带 image/png File),粘贴应进入「图片放置」模式;回车确认后图层面板 +1 项。
|
||
// SKIP_PASTE=1 可跳过(隔离「粘贴」与「覆盖写回」两条链路的排查用)。
|
||
const SKIP_PASTE = process.env.SKIP_PASTE === '1'
|
||
const layersBefore = await page.evaluate(() => document.querySelectorAll('.iwb-editor-layer-list > *').length)
|
||
if (!SKIP_PASTE) {
|
||
await page.evaluate((png) => {
|
||
const bin = atob(png.split(',')[1])
|
||
const bytes = new Uint8Array(bin.length)
|
||
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
|
||
const dt = new DataTransfer()
|
||
dt.items.add(new File([bytes], 'paste.png', { type: 'image/png' }))
|
||
document.dispatchEvent(new ClipboardEvent('paste', { clipboardData: dt, bubbles: true, cancelable: true }))
|
||
}, PNG)
|
||
await page.waitForTimeout(800) // FileReader → loadImage → 进入放置模式
|
||
await page.keyboard.press('Enter') // 确认放置 → 落层
|
||
const pasted = await poll(async () => page.evaluate((n) => document.querySelectorAll('.iwb-editor-layer-list > *').length > n, layersBefore))
|
||
check('⌘V 粘贴剪贴板图片 → 确认后图层面板 +1', Boolean(pasted), '图层项 ' + layersBefore + ' → ' + await page.evaluate(() => document.querySelectorAll('.iwb-editor-layer-list > *').length))
|
||
}
|
||
|
||
// ---------- 5) 覆盖:回写真机画布 ----------
|
||
await page.mouse.move(400, 300)
|
||
await page.mouse.down()
|
||
await page.mouse.move(760, 520, { steps: 8 })
|
||
await page.mouse.up()
|
||
await page.locator('[data-action="replace"]').click()
|
||
|
||
const replaced = await poll(async () => page.evaluate((orig) => {
|
||
const ws = JSON.parse(localStorage.getItem('iwb_ws_w1') || '{}')
|
||
const n = (ws.nodes || []).find((x) => x.id === 'r1')
|
||
if (!n) return false
|
||
const v = n.data && (typeof n.data.data === 'string' ? n.data.data : (n.data.data && (n.data.data.__blob || JSON.stringify(n.data.data))))
|
||
return (ws.nodes.length === 1 && v && v !== orig) ? { nodes: ws.nodes.length, changed: true } : false
|
||
}, PNG))
|
||
check('「覆盖」写回原节点(节点数不变、内容已变)', Boolean(replaced), JSON.stringify(replaced))
|
||
check('编辑器导出后关闭', (await page.locator('#iwb-editor-overlay').isVisible().catch(() => false)) === false)
|
||
|
||
// ---------- 6) 新建:真机画布新增节点 ----------
|
||
await openEditor()
|
||
await page.locator('#iwb-editor-overlay').waitFor({ state: 'visible', timeout: 30000 })
|
||
await page.locator('[data-action="newNode"]').click()
|
||
const created = await poll(async () => page.evaluate(() => {
|
||
const ws = JSON.parse(localStorage.getItem('iwb_ws_w1') || '{}')
|
||
return (ws.nodes || []).length === 2 ? { nodes: 2 } : false
|
||
}))
|
||
check('「新建」在真机画布新增节点', Boolean(created), JSON.stringify(created))
|
||
await page.locator('.iwb-canvas').waitFor({ state: 'visible' })
|
||
check('画布渲染出 2 个节点', (await page.locator('.iwb-node').count()) === 2)
|
||
|
||
// ---------- 7) 无 CSP / 运行时错误 ----------
|
||
const bad = consoleErrors.filter((t) => /Content Security Policy|integrity|Refused to (execute|load|connect)/i.test(t))
|
||
check('无 CSP / SRI 拦截报错', bad.length === 0, bad.slice(0, 2).join(' | '))
|
||
check('无页面级运行时错误', consoleErrors.length === 0, consoleErrors.slice(0, 3).join(' | '))
|
||
|
||
await browser.close()
|
||
console.log('\n' + (failed ? '✗ 失败 ' + failed + ' 项' : '✓ 全部通过'))
|
||
process.exit(failed ? 1 : 0)
|