| 6 | import path from 'node:path'; |
| 7 | import { fileURLToPath } from 'node:url'; |
| 8 | import type { Page } from '@playwright/test'; |
| 9 | import { PNG } from 'pngjs'; |
| 10 | import type { ContentSafeArea } from '../../packages/core/src/shared/sdk-policy.ts'; |
| 11 |
| 12 | /** path.relative with / separators: what the manifest and the channel table store, on every OS. */ |
| 13 | export const posixRelative = (from: string, to: string) => path.relative(from, to).split(path.sep).join('/'); |
| 14 |
| 15 | export const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..'); |
| 16 | export const CONF = path.join(ROOT, 'packages', 'conformance'); |
| 17 | export const SETS = ['auto', 'visual'] as const; |
| 18 | export type SetName = (typeof SETS)[number]; |
| 19 |
| 20 | /** |
| 21 | * The bubble is at most 600 px tall on every client and on the server (docs/integration.md, "Bubble sizing"). |
| 22 | * Every widget stays within `height` at a narrow bubble width, which leaves room for platform fonts and an |
| 23 | * automatic widget's list of failures; a header's "tall": true exempts a widget that tests the cap |
| 24 | * (13-max-height). build.ts checks the visual set and the client-SDK group drawn natively; heights.ts checks |
| 25 | * every widget through the sandbox (drawn natively, an automatic widget also lists the out-of-profile checks |
| 26 | * Chromium fails, which makes it taller than on a client). |
| 27 | */ |
| 28 | export const MAX_HEIGHT = { width: 320, height: 560 }; |
| 29 |
| 30 | /** Default stage sizes (CSS px) and the auto set's grid. */ |
| 31 | export const STAGE = { auto: { w: 80, h: 60 }, visual: { w: 150, h: 90 } }; |
| 32 | export const AUTO_GRID = { left: 8, top: 8, dx: 88, dy: 68, perRow: 4 }; |
| 33 | /** The pixel rule lives in the package (packages/conformance/tools/diff.mjs), shared with every client's runner. */ |
| 34 | export { DIFF, judgeStage } from '../../packages/conformance/tools/diff.mjs'; |
| 35 |
| 36 | /** |
| 37 | * Scripted input, in widget CSS px or by target name (the widget publishes |
| 38 | * `targets[name]` = [x, y, w, h] from its own layout, so runners need no |
| 39 | * selectors and work on canvas renderers too). |
| 40 | */ |
| 41 | export type Point = string | [number, number]; |
| 42 | /** `ids`: catalogue IDs whose checks depend on this action; a runner that cannot deliver it reports them as skipped. */ |
| 43 | export type Action = ActionKind & { ids?: string[] }; |
| 44 | type ActionKind = |
| 45 | | { tap: Point } |
| 46 | | { dblclick: Point } |
| 47 | | { rightclick: Point } |
| 48 | | { hover: Point } |
| 49 | | { press: Point; ms: number } |
| 50 | | { drag: Point; to: Point | [number, number]; by?: boolean; steps?: number } |
| 51 | | { key: string } |
| 52 | | { wheel: Point; dy: number } |
| 53 | | { theme: 'light' | 'dark' } |
| 54 | | { visible: boolean } |
| 55 | | { wait: number }; |
| 56 |
| 57 | /** Host-side expectations a runner checks itself (the widget cannot observe them). */ |
| 58 | export interface HostCheck { |
| 59 | id: string; |
| 60 | name: string; |
| 61 | /** Bridge calls the host must have seen: method and first argument, exact count. */ |
| 62 | bridge?: { method: string; arg?: string; count: number }; |
| 63 | /** Needs a trusted user gesture (synthetic taps of the canvas renderers cannot grant one): skipped there. */ |
| 64 | gesture?: boolean; |
| 65 | /** Bubble height reported by the host, CSS px. */ |
| 66 | height?: { min?: number; max?: number }; |
| 67 | /** 'chat': the chat's input field (focused by the runner before the widget loads) still has the focus once the widget has run its own checks, before any input. */ |
| 68 | focus?: 'chat'; |
| 69 | xfail?: string; |
| 70 | } |
| 71 |
| 72 | /** |
| 73 | * How the test bot sends a widget and where the tester looks at it (layer 233: docs/tgw-format.md). `kind` is the |
| 74 | * message context the client must report there (WIDGET_MESSAGE_KINDS in sdk-policy.ts); run-web gives the dev app's |
| 75 | * mock bot the first spec's kind and data. The rest are the inputMediaWidget fields the bot sends with |
| 76 | * (`sendWidget`); `chat: 'group'` = into the test group (else the tester's private chat), `forward` = the tester |
| 77 | * forwards it and looks at the forward, `inline` = the bot's inline mode returns it for the query `conf-preview` |
| 78 | * and the tester looks at the list of results. |
| 79 | */ |
| 80 | export interface MessageSpec { |
| 81 | kind: 'private' | 'group' | 'via-bot' | 'no-queries' | 'live-copy' | 'copy' | 'preview'; |
| 82 | allow_queries?: boolean; |
| 83 | fwd_allow_queries?: boolean; |
| 84 | shared_widget?: boolean; |
| 85 | chat_data?: string; |
| 86 | public_data?: string; |
| 87 | chat?: 'private' | 'group'; |
| 88 | forward?: boolean; |
| 89 | inline?: boolean; |
| 90 | /** Where the tester looks, when it is not obvious from the rest. */ |
| 91 | view?: string; |
| 92 | } |
| 93 |
| 94 | /** |
| 95 | * What the test bot does on a widget_query or shared_widget_query with exactly this data |
| 96 | * (scripts/conformance/test-bot.ts, Bot API 10.4): edit the message's state (editMessageWidgetData, by chat and |
| 97 | * message_id or by inline_message_id for a via-bot message), edit the shared widget (editSharedWidgetData by |
| 98 | * widget_id, with cache_time), then answer with `result` (answerWidgetQuery's data). `repeat` runs the edits again |
| 99 | * every `every` s, `times` times in all (a ticker). Templates in the strings: {n} counts the requests with this data |
| 100 | * per message (per widget_id for a copy), {from} is who pressed (first_name), {time} the bot's HH:MM:SS. |
| 101 | */ |
| 102 | export interface BotAction { |
| 103 | result?: string; |
| 104 | edit?: { chat_data?: string; public_data?: string }; |
| 105 | editShared?: { public_data: string; cache_time?: number }; |
| 106 | repeat?: { every: number; times: number }; |
| 107 | } |
| 108 |
| 109 | export interface WidgetMeta { |
| 110 | title: string; |
| 111 | /** How the test bot sends it, one entry per post (default: a plain send to the tester's private chat). */ |
| 112 | message?: MessageSpec[]; |
| 113 | /** What the test bot answers to the widget's requests, by their exact data. */ |
| 114 | bot?: Record<string, BotAction>; |
| 115 | /** One line for a human tester (visual set) or for the report. */ |
| 116 | hint?: string; |
| 117 | actions?: Action[]; |
| 118 | host?: HostCheck[]; |
| 119 | /** Run in these themes (default: light; auto widgets with theme stages: both). */ |
| 120 | themes?: ('light' | 'dark')[]; |
| 121 | /** Catalogue IDs judged by a human only (visual set), beyond the stage covers. */ |
| 122 | covers?: string[]; |
| 123 | /** Client-SDK group: what the client must do, in one line (the hint says what the tester does). */ |
| 124 | expect?: string; |
| 125 | /** The section of docs/sdk-v1.md the test checks. */ |
| 126 | contract?: string; |
| 127 | /** Not runnable yet: what it waits for (e.g. the server). */ |
| 128 | pending?: string; |
| 129 | /** Taller than the bubble's cap on purpose (13-max-height tests the clip): exempt from the build's height gate. */ |
| 130 | tall?: boolean; |
| 131 | /** No harness CSS (the harness script and the stage geometry only): the widget tests the renderer's own defaults (the UA layer). */ |
| 132 | bare?: boolean; |
| 133 | /** |
| 134 | * What the client draws over this widget (docs/sdk-v1.md §2.17): a content safe area, in CSS px (the band of the message |
| 135 | * time at the bottom, its corner). The test bot sends the widget without a caption, so a client draws its own time over |
| 136 | * it and passes its own numbers; the reference runner gives the dev app these, and the reference picture is drawn with |
| 137 | * them and the reference time over the corner. The widget's checks compare with what its host passed, never with these. |
| 138 | */ |
| 139 | safeArea?: Partial<ContentSafeArea>; |
| 140 | /** |
| 141 | * The host must stop this widget (a counted limit under strict, docs/decisions.md "Strict limits from the start"): its |
| 142 | * covers pass when the runtime dies with a reason that starts with this text, and fail on any other end. |
| 143 | */ |
| 144 | stops?: string; |
| 145 | } |
| 146 |
| 147 | export interface StageInfo { |
| 148 | name: string; |
| 149 | w: number; |
| 150 | h: number; |
| 151 | covers: string[]; |
| 152 | themes: ('light' | 'dark')[]; |
| 153 | /** Max differing pixel share for this stage (default DIFF.maxRatio). */ |
| 154 | maxDiff?: number; |
| 155 | /** Has a <template data-ref> (reftest) instead of a self-render reference. */ |
| 156 | reftest: boolean; |
| 157 | /** Expected to differ until something lands (catalogue-level xfail). */ |
| 158 | xfail?: string; |
| 159 | /** |
| 160 | * Colours that carry the feature (e.g. the orange of a text shadow): the |
| 161 | * stage must show about as many pixels of each as the reference. For text |
| 162 | * stages, where glyph shapes differ between platforms but the feature's |
| 163 | * colour does not. |
| 164 | */ |
| 165 | colors?: string[]; |
| 166 | /** |
| 167 | * Visual set: the stage's template illustrates motion or a state after input (the frames a box moves between, the end |
| 168 | * of a transition) rather than a frame the widget draws on load; picture-check.ts leaves the stage out. |
| 169 | */ |
| 170 | illustration?: boolean; |
| 171 | } |
| 172 |
| 173 | export interface Widget { |
| 174 | set: SetName; |
| 175 | stem: string; |
| 176 | id: string; |
| 177 | file: string; |
| 178 | html: string; |
| 179 | meta: WidgetMeta; |
| 180 | stages: StageInfo[]; |
| 181 | } |
| 182 |
| 183 | export function listWidgets(only?: string): Widget[] { |
| 184 | const out: Widget[] = []; |
| 185 | for (const set of SETS) { |
| 186 | const dir = path.join(CONF, set); |
| 187 | if (!fs.existsSync(dir)) continue; |
| 188 | // One level of groups: visual/sdk/01-links.html is `visual/sdk/01-links`. |
| 189 | const files = fs.readdirSync(dir).sort().flatMap((f) => (fs.statSync(path.join(dir, f)).isDirectory() ? fs.readdirSync(path.join(dir, f)).sort().map((g) => `${f}/${g}`) : [f])); |
| 190 | for (const f of files) { |
| 191 | if (!f.endsWith('.html')) continue; |
| 192 | const stem = f.slice(0, -5); |
| 193 | const id = `${set}/${stem}`; |
| 194 | if (only && !only.split(',').some((o) => id.includes(o))) continue; |
| 195 | out.push(parseWidget(set, stem, fs.readFileSync(path.join(dir, f), 'utf8'))); |
| 196 | } |
| 197 | } |
| 198 | return out; |
| 199 | } |
| 200 |
| 201 | export function parseWidget(set: SetName, stem: string, html: string): Widget { |
| 202 | const id = `${set}/${stem}`; |
| 203 | const m = /<!--\s*conformance\s*(\{[\s\S]*?\})\s*-->/.exec(html); |
| 204 | if (!m) throw new Error(`${id}: no <!-- conformance {…} --> header`); |
| 205 | let meta: WidgetMeta; |
| 206 | try { meta = JSON.parse(m[1]); } catch (e) { throw new Error(`${id}: header is not JSON: ${(e as Error).message}`); } |
| 207 | const stages: StageInfo[] = []; |
| 208 | const attr = (tag: string, name: string) => new RegExp(`\\s${name}="([^"]*)"`).exec(tag)?.[1]; |
| 209 | for (const sm of html.matchAll(/<[a-zA-Z][\w-]*\s[^>]*\bdata-stage="([^"]+)"[^>]*>/g)) { |
| 210 | const tag = sm[0]; |
| 211 | const name = sm[1]; |
| 212 | const size = attr(tag, 'data-size'); |
| 213 | const def = STAGE[set]; |
| 214 | const [w, h] = size ? size.split('x').map(Number) : [def.w, def.h]; |
| 215 | const themes = (attr(tag, 'data-themes') ?? 'light').split(/\s+/).filter(Boolean) as ('light' | 'dark')[]; |
| 216 | const covers = (attr(tag, 'data-covers') ?? '').split(/\s+/).filter(Boolean); |
| 217 | const maxDiff = attr(tag, 'data-max-diff'); |
| 218 | const colors = (attr(tag, 'data-colors') ?? '').split(/\s+/).filter(Boolean); |
| 219 | stages.push({ name, w, h, covers, themes, maxDiff: maxDiff ? Number(maxDiff) : undefined, reftest: html.includes(`data-ref="${name}"`), xfail: attr(tag, 'data-xfail'), colors: colors.length ? colors : undefined, illustration: /\sdata-illustration(?=[\s=>])/.test(tag) || undefined }); |
| 220 | } |
| 221 | return { set, stem, id, file: path.join(CONF, set, stem + '.html'), html, meta, stages }; |
| 222 | } |
| 223 |
| 224 | /** Auto set: the fixed position of stage i (CSS px, relative to the widget's top-left). */ |
| 225 | export function autoStagePos(i: number): [number, number] { |
| 226 | return [AUTO_GRID.left + (i % AUTO_GRID.perRow) * AUTO_GRID.dx, AUTO_GRID.top + Math.floor(i / AUTO_GRID.perRow) * AUTO_GRID.dy]; |
| 227 | } |
| 228 |
| 229 | export interface Published { |
| 230 | v: number; |
| 231 | id: string; |
| 232 | mode: string; |
| 233 | status: 'running' | 'awaiting' | 'done'; |
| 234 | n: Record<string, number>; |
| 235 | checks: [string, string, string, string][]; |
| 236 | targets?: Record<string, [number, number, number, number]>; |
| 237 | stages?: Record<string, [number, number, number, number]>; |
| 238 | } |
| 239 |
| 240 | /** Where to send input: page coordinates of the widget's origin, and how to deliver a tap (canvas renderers use __tw.tap). */ |
| 241 | export interface InputSurface { |
| 242 | origin: () => Promise<{ x: number; y: number }>; |
| 243 | setTheme?: (t: 'light' | 'dark') => Promise<void>; |
| 244 | setVisible?: (v: boolean) => Promise<void>; |
| 245 | /** Canvas renderers: no DOM to click; only taps are delivered (through the renderer's own hit test). */ |
| 246 | tapOnly?: (x: number, y: number) => Promise<void>; |
| 247 | } |
| 248 |
| 249 | function resolve(p: Point, pub: Published | null): [number, number] { |
| 250 | if (Array.isArray(p)) return p; |
| 251 | const r = pub?.targets?.[p]; |
| 252 | if (!r) throw new Error(`no target "${p}" published`); |
| 253 | return [r[0] + r[2] / 2, r[1] + r[3] / 2]; |
| 254 | } |
| 255 |
| 256 | /** Perform the scripted actions. Returns the actions that could not be delivered on this surface (with the catalogue IDs they feed). */ |
| 257 | export async function perform(page: Page, actions: Action[], surface: InputSurface, published: () => Promise<Published | null>): Promise<{ skipped: string[]; ids: string[]; indices: number[] }> { |
| 258 | const skipped: string[] = []; |
| 259 | const ids: string[] = []; |
| 260 | const indices: number[] = []; |
| 261 | const skip = (a: Action, what: string) => { skipped.push(what); ids.push(...(a.ids ?? [])); indices.push(actions.indexOf(a)); }; |
| 262 | for (const a of actions) { |
| 263 | const pub = await published(); |
| 264 | const o = await surface.origin(); |
| 265 | const at = (p: Point) => { const [x, y] = resolve(p, pub); return [o.x + x, o.y + y] as [number, number]; }; |
| 266 | if ('wait' in a) { await page.waitForTimeout(a.wait); continue; } |
| 267 | if ('theme' in a) { if (surface.setTheme) await surface.setTheme(a.theme); else skip(a, 'theme'); await page.waitForTimeout(150); continue; } |
| 268 | if ('visible' in a) { if (surface.setVisible) await surface.setVisible(a.visible); else skip(a, 'visible'); await page.waitForTimeout(150); continue; } |
| 269 | if (surface.tapOnly) { |
| 270 | if ('tap' in a) { const [x, y] = resolve(a.tap, pub); await surface.tapOnly(x, y); await page.waitForTimeout(350); } |
| 271 | else skip(a, Object.keys(a).filter((k) => k !== 'ids')[0]); |
| 272 | continue; |
| 273 | } |
| 274 | if ('tap' in a) { const [x, y] = at(a.tap); await page.mouse.click(x, y); } |
| 275 | else if ('dblclick' in a) { const [x, y] = at(a.dblclick); await page.mouse.dblclick(x, y); } |
| 276 | else if ('rightclick' in a) { const [x, y] = at(a.rightclick); await page.mouse.click(x, y, { button: 'right' }); } |
| 277 | else if ('hover' in a) { const [x, y] = at(a.hover); await page.mouse.move(x, y, { steps: 4 }); } |
| 278 | else if ('press' in a) { const [x, y] = at(a.press); await page.mouse.move(x, y); await page.mouse.down(); await page.waitForTimeout(a.ms); await page.mouse.up(); } |
| 279 | else if ('drag' in a) { |
| 280 | const [x0, y0] = at(a.drag); |
| 281 | let x1: number, y1: number; |
| 282 | if (a.by) { const d = a.to as [number, number]; x1 = x0 + d[0]; y1 = y0 + d[1]; } else [x1, y1] = at(a.to); |
| 283 | await page.mouse.move(x0, y0); |
| 284 | await page.mouse.down(); |
| 285 | await page.mouse.move(x1, y1, { steps: a.steps ?? 10 }); |
| 286 | await page.mouse.up(); |
| 287 | } else if ('key' in a) await page.keyboard.press(a.key); |
| 288 | else if ('wheel' in a) { const [x, y] = at(a.wheel); await page.mouse.move(x, y); await page.mouse.wheel(0, a.dy); } |
| 289 | // Let the event cross the worker and the widget react before the next gesture (and keep taps apart from double-clicks). |
| 290 | await page.waitForTimeout(Number(process.env.CONF_GAP ?? 350)); |
| 291 | } |
| 292 | return { skipped, ids, indices }; |
| 293 | } |
| 294 |
| 295 | /** Crop a CSS-px rect out of a DPR-scaled PNG whose widget origin is at device pixel (ox, oy). */ |
| 296 | export function crop(png: PNG, x: number, y: number, w: number, h: number, dpr: number, ox = 0, oy = 0): PNG { |
| 297 | const out = new PNG({ width: Math.round(w * dpr), height: Math.round(h * dpr) }); |
| 298 | out.data.fill(255); |
| 299 | const sx = ox + Math.round(x * dpr), sy = oy + Math.round(y * dpr); |
| 300 | const cw = Math.max(0, Math.min(out.width, png.width - sx)), ch = Math.max(0, Math.min(out.height, png.height - sy)); |
| 301 | if (cw > 0 && ch > 0 && sx >= 0 && sy >= 0) PNG.bitblt(png, out, sx, sy, cw, ch, 0, 0); |
| 302 | return out; |
| 303 | } |
| 304 |
| 305 | export function refPath(w: Widget, stage: string, engine: string, theme: 'light' | 'dark'): string { |
| 306 | return path.join(CONF, 'refs', w.set, w.stem, `${stage}.${engine}${theme === 'dark' ? '.dark' : ''}.png`); |
| 307 | } |
| 308 |
| 309 | /** The picture posted next to a visual or client-SDK widget: refs/visual/<widget>[.dark].png. */ |
| 310 | export function picturePath(w: Widget, theme: 'light' | 'dark'): string { |
| 311 | return path.join(CONF, 'refs', w.set, `${w.stem}${theme === 'dark' ? '.dark' : ''}.png`); |
| 312 | } |
| 313 |
| 314 | export function readJson<T>(file: string, fallback: T): T { |
| 315 | try { return JSON.parse(fs.readFileSync(file, 'utf8')) as T; } catch { return fallback; } |
| 316 | } |
| 317 |