dsh-plugin-ui-actions 0.0.0-stage → 0.2.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +12 -2
  3. package/package.json +35 -4
  4. package/src/index.mjs +184 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 dsh-plugin-e2e contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,13 @@
1
- # Temporary Holding Version
1
+ # dsh-plugin-ui-actions
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ DSH UI 自动化动作库(Playwright):插件无关的通用动作,供 DSH 插件 E2E/spec 复用。
4
+
5
+ ```js
6
+ import { launchBrowser, dismissOnboarding, enableSetting, mockPost, typeDraft, click, waitFor, rects, golden, ariaSnapshot, smoke } from 'dsh-plugin-ui-actions'
7
+ const { browser, context, page } = await launchBrowser({ channel: 'msedge' })
8
+ ```
9
+
10
+ 导出:`launchBrowser` / `dismissOnboarding` / `enableSetting` / `mockPost` / `typeDraft` / `clickAttr` / `click` / `waitFor` / `smoke` / `rects` / `shot` / `golden`(像素容差金标准)/ `ariaSnapshot` / `goldenAria`(aria 容差金标准)。
11
+
12
+ - 依赖 `playwright-core`(浏览器通道由调用方给:`msedge` 系统 Edge 或 `chromium` 自带)。
13
+ - 原 `dsh-plugin-e2e/browser` 现转发到本包,向后兼容。
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
1
  {
2
2
  "name": "dsh-plugin-ui-actions",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.9",
4
+ "private": false,
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "description": "DSH UI automation kit (Playwright): launch, dismiss onboarding, set localStorage switches, mock POST, type draft, click/attr/waitFor, geometry, screenshot/golden pixel, aria snapshot — plugin-agnostic helpers for DSH UI testing.",
8
+ "exports": {
9
+ ".": "./src/index.mjs"
10
+ },
11
+ "files": [
12
+ "src/",
13
+ "README.md"
14
+ ],
15
+ "dependencies": {
16
+ "playwright-core": "^1.49.0",
17
+ "pngjs": "^7.0.0",
18
+ "pixelmatch": "^6.0.0"
19
+ },
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/metal-huang/dsh-devtools.git",
23
+ "directory": "packages/dsh-plugin-ui-actions"
24
+ },
25
+ "publishConfig": {
26
+ "access": "public",
27
+ "registry": "https://registry.npmjs.org/"
28
+ },
29
+ "engines": {
30
+ "dsh": ">=0.2.2-rc.5",
31
+ "node": ">=22.15.0"
32
+ },
33
+ "dshTestedOn": [
34
+ "0.2.2-rc.5",
35
+ "0.2.3-alpha.2"
36
+ ]
37
+ }
package/src/index.mjs ADDED
@@ -0,0 +1,184 @@
1
+ // Playwright 薄封装:只做"插件无关"的通用动作,供各插件 spec 复用。
2
+ import { chromium } from 'playwright-core'
3
+ import { readFile, writeFile, mkdir } from 'node:fs/promises'
4
+ import { join } from 'node:path'
5
+
6
+ export async function launchBrowser(opts = {}) {
7
+ const launch = { headless: opts.headless !== false, chromiumSandbox: false }
8
+ // channel 未给 / 'chromium' / 'bundled' → 用 Playwright 自带 chromium(Linux/CI);'msedge' → 系统 Edge。
9
+ if (opts.channel && opts.channel !== 'chromium' && opts.channel !== 'bundled') launch.channel = opts.channel
10
+ const browser = await chromium.launch(launch)
11
+ const context = await browser.newContext({ viewport: opts.viewport || { width: 1440, height: 900 } })
12
+ const page = await context.newPage()
13
+ return { browser, context, page }
14
+ }
15
+
16
+ /** 关掉首启的「预览版说明」引导弹窗(背景会 inert);没有就跳过。 */
17
+ export async function dismissOnboarding(page) {
18
+ const cont = page.locator('button', { hasText: /继续|Continue|Got it|知道了/i })
19
+ if (await cont.count()) {
20
+ try {
21
+ await cont.first().click({ timeout: 4000 })
22
+ await page.waitForTimeout(800)
23
+ } catch {}
24
+ }
25
+ }
26
+
27
+ /** 写 localStorage 开关(插件设置多以 localStorage 存)。 */
28
+ export async function enableSetting(page, key, value) {
29
+ await page.evaluate(([k, v]) => localStorage.setItem(k, v), [key, String(value)])
30
+ }
31
+
32
+ /** 拦某个 POST 请求并返回固定 JSON(浏览器层 mock,避免真模型)。 */
33
+ export async function mockPost(page, pattern, body, status = 200) {
34
+ await page.route(pattern, (route) =>
35
+ route.fulfill({ status, contentType: 'application/json', body: JSON.stringify(body) }),
36
+ )
37
+ }
38
+
39
+ /** 在主输入框键入草稿(Lexical contenteditable)。 */
40
+ export async function typeDraft(page, text) {
41
+ const ed = page.locator('[contenteditable="true"]').first()
42
+ await ed.click()
43
+ await page.keyboard.type(text)
44
+ await page.waitForTimeout(600)
45
+ }
46
+
47
+ /** 点带某 data-* 属性的按钮(如 data-dsh-prompt-wit)。 */
48
+ export async function clickAttr(page, attr) {
49
+ await page.locator(`[${attr}]`).first().click({ force: true })
50
+ await page.waitForTimeout(1200)
51
+ }
52
+
53
+ /** 取两个元素相对几何(left/width 差、垂直间距)。 */
54
+ export async function rects(page, prevSel, cardSel) {
55
+ return page.evaluate(
56
+ ([ps, cs]) => {
57
+ const p = document.querySelector(ps)
58
+ const c = document.querySelector(cs)
59
+ const pr = p ? p.getBoundingClientRect() : null
60
+ const cr = c ? c.getBoundingClientRect() : null
61
+ if (!pr || !cr) return { found: false, hasPreview: !!p, hasCard: !!c }
62
+ return {
63
+ found: true,
64
+ preview: { left: Math.round(pr.left), top: Math.round(pr.top), bottom: Math.round(pr.bottom), width: Math.round(pr.width) },
65
+ card: { left: Math.round(cr.left), top: Math.round(cr.top), width: Math.round(cr.width) },
66
+ leftDiff: Math.round(pr.left) - Math.round(cr.left),
67
+ widthDiff: Math.round(pr.width) - Math.round(cr.width),
68
+ gapAboveCard: Math.round(cr.top) - Math.round(pr.bottom),
69
+ }
70
+ },
71
+ [prevSel, cardSel],
72
+ )
73
+ }
74
+
75
+ /**
76
+ * 像素金标准:截图(可限定元素)与 golden/name.png 比较。
77
+ * 首次=创建(created),之后=精确 sha 比较(match/diff)。返回 {status, file, hash}。
78
+ */
79
+ export async function golden(page, name, opts = {}) {
80
+ const dir = opts.goldenDir
81
+ await mkdir(dir, { recursive: true })
82
+ const file = join(dir, name + '.png')
83
+ // 稳定化:关动画/过渡、等字体加载,降低跨机器/跨次抖动
84
+ if (opts.stabilize !== false) {
85
+ try {
86
+ await page.addStyleTag({ content: '*,*::before,*::after{animation:none!important;transition:none!important;caret-color:transparent!important}' })
87
+ } catch {}
88
+ try {
89
+ await page.evaluate(() => document.fonts && document.fonts.ready)
90
+ } catch {}
91
+ }
92
+ const buf = opts.sel
93
+ ? await page.locator(opts.sel).first().screenshot({ animations: 'disabled' })
94
+ : await page.screenshot({ animations: 'disabled' })
95
+ const prev = await readFile(file).catch(() => null)
96
+ if (prev === null) {
97
+ await writeFile(file, buf)
98
+ return { status: 'created', file }
99
+ }
100
+ // 容忍度像素比对(默认允许 0.2% 像素差),避免跨机器字体/抗锯齿导致误报
101
+ const pkgPNG = await import('pngjs')
102
+ const PNG = pkgPNG.PNG || pkgPNG.default?.PNG
103
+ const pmMod = await import('pixelmatch')
104
+ const pixelmatch = pmMod.default || pmMod
105
+ const a = PNG.sync.read(prev)
106
+ const b = PNG.sync.read(buf)
107
+ if (a.width !== b.width || a.height !== b.height) {
108
+ return { status: 'diff', file, reason: `尺寸不同 ${a.width}x${a.height} vs ${b.width}x${b.height}` }
109
+ }
110
+ const diff = new PNG({ width: a.width, height: a.height })
111
+ const diffPixels = pixelmatch(a.data, b.data, diff.data, a.width, a.height, { threshold: opts.pixelThreshold ?? 0.1 })
112
+ const diffRatio = diffPixels / (a.width * a.height)
113
+ const maxDiffRatio = opts.maxDiffRatio ?? 0.002
114
+ if (diffRatio <= maxDiffRatio) return { status: 'match', file, diffPixels, diffRatio }
115
+ const diffFile = join(dir, name + '.diff.png')
116
+ await writeFile(diffFile, PNG.sync.write(diff))
117
+ return { status: 'diff', file, diffFile, diffPixels, diffRatio }
118
+ }
119
+
120
+ /** 取 aria 快照(Playwright Locator.ariaSnapshot)。 */
121
+ export async function ariaSnapshot(page, sel = 'body') {
122
+ const loc = sel === 'body' ? page.locator('body') : page.locator(sel).first()
123
+ if (typeof loc.ariaSnapshot !== 'function') throw new Error('ariaSnapshot 不可用(需较新 Playwright)')
124
+ return loc.ariaSnapshot()
125
+ }
126
+
127
+ function normalizeAria(s) {
128
+ return String(s)
129
+ .split('\n')
130
+ .map((l) => l.trim().replace(/\s+/g, ' '))
131
+ .filter(Boolean)
132
+ .join('\n')
133
+ }
134
+
135
+ /** aria 金标准:归一化 + 行级容差(默认允许 2% 或 ≥3 行差异),跨机器/小改动不误报;`GOLDEN_UPDATE=1` 重建基线。 */
136
+ export async function goldenAria(page, name, opts = {}) {
137
+ const dir = opts.dir
138
+ await mkdir(dir, { recursive: true })
139
+ const file = join(dir, name + '.aria.txt')
140
+ const snap = normalizeAria(await ariaSnapshot(page, opts.sel || 'body'))
141
+ const prevRaw = await readFile(file, 'utf8').catch(() => null)
142
+ if (prevRaw === null || process.env.GOLDEN_UPDATE === '1') {
143
+ await writeFile(file, snap)
144
+ return { status: prevRaw === null ? 'created' : 'updated', file }
145
+ }
146
+ const a = normalizeAria(prevRaw).split('\n')
147
+ const b = snap.split('\n')
148
+ const tally = new Map()
149
+ for (const l of a) tally.set(l, (tally.get(l) || 0) + 1)
150
+ let diffLines = 0
151
+ for (const l of b) {
152
+ const n = tally.get(l) || 0
153
+ if (n > 0) tally.set(l, n - 1)
154
+ else diffLines++
155
+ }
156
+ for (const v of tally.values()) diffLines += v
157
+ const maxDiffLines = opts.maxDiffLines ?? Math.max(3, Math.ceil(Math.max(a.length, b.length) * 0.02))
158
+ if (diffLines <= maxDiffLines) return { status: 'match', file, diffLines }
159
+ const diffFile = join(dir, name + '.aria.diff.txt')
160
+ await writeFile(diffFile, snap)
161
+ return { status: 'diff', file, diffFile, diffLines }
162
+ }
163
+
164
+ /** 截图到指定文件(spec 可直接用;CLI 的 h.shot 绑定到感知目录,签名 h.shot(name))。 */
165
+ export async function shot(page, filePath) {
166
+ await page.screenshot({ path: filePath })
167
+ return filePath
168
+ }
169
+
170
+ /** 点任意选择器(不只 data-*)。 */
171
+ export async function click(page, selector, opts = {}) {
172
+ await page.locator(selector).first().click(opts)
173
+ await page.waitForTimeout(opts.settleMs ?? 300)
174
+ }
175
+
176
+ /** 等元素可见。 */
177
+ export async function waitFor(page, selector, timeout = 15000) {
178
+ await page.locator(selector).first().waitFor({ state: 'visible', timeout })
179
+ }
180
+
181
+ /** 插件已装载的 DOM 证据:返回带该 data-* 属性的元素是否存在。 */
182
+ export async function smoke(page, attr) {
183
+ return (await page.locator(`[${attr}]`).count()) > 0
184
+ }