@sloppy-ai/verify 0.0.0-stage → 1.1.0

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.
@@ -0,0 +1,401 @@
1
+ import { readFile } from 'node:fs/promises'
2
+ import { resolve } from 'node:path'
3
+
4
+ // Shared reporting and page discovery. Browser functions below are deliberately
5
+ // self-contained: Playwright installs their source before application code runs.
6
+ export function visibleStages(selector = null) {
7
+ const targets = [...document.querySelectorAll(selector || '.ss-fit, .ss-stage')]
8
+ const stages = new Set()
9
+ for (const target of targets) {
10
+ for (const stage of target.matches('.ss-stage') ? [target] : target.querySelectorAll('.ss-stage')) {
11
+ const r = stage.getBoundingClientRect()
12
+ const cs = getComputedStyle(stage)
13
+ if (r.width && r.height && cs.display !== 'none' && cs.visibility !== 'hidden' && stage.checkVisibility?.({ visibilityProperty: true, opacityProperty: false }) !== false) stages.add(stage)
14
+ }
15
+ }
16
+ return [...stages]
17
+ }
18
+
19
+ export function watchStages({ selector = null } = {}) {
20
+ const keys = new WeakMap()
21
+ let next = 1
22
+ const state = window.__ssVerification = { selector, stages: {}, stopped: false, errors: [] }
23
+ window.__ssStageKey = (stage) => {
24
+ if (!keys.has(stage)) {
25
+ const key = `stage-${next++}`
26
+ keys.set(stage, key)
27
+ stage.setAttribute('data-ss-verification-stage', key)
28
+ state.stages[key] = { label: stage.getAttribute('aria-label') || stage.parentElement?.className || key, startedAt: performance.now(), frames: [] }
29
+ window.__ssRecord(stage, { key })
30
+ }
31
+ return keys.get(stage)
32
+ }
33
+ const discover = () => {
34
+ if (state.stopped) return
35
+ try {
36
+ for (const stage of window.__ssVisibleStages(selector)) window.__ssStageKey(stage)
37
+ } catch (error) {
38
+ state.errors.push(String(error))
39
+ state.stopped = true
40
+ return
41
+ }
42
+ requestAnimationFrame(discover)
43
+ }
44
+ requestAnimationFrame(discover)
45
+ }
46
+
47
+ export function instrumentationSource(record, selector = null) {
48
+ return `window.__ssVisibleStages = ${visibleStages.toString()};\nwindow.__ssRecord = ${record.toString()};\n(${watchStages.toString()})(${JSON.stringify({ selector })});`
49
+ }
50
+
51
+ export function coverage(frames = [], { requestedMs = 0, slow = 1 } = {}) {
52
+ const intervals = frames.slice(1).map((frame, i) => frame.t - frames[i].t)
53
+ const sorted = intervals.filter((ms) => ms > 0 && Number.isFinite(ms)).sort((a, b) => a - b)
54
+ const medianMs = sorted[Math.floor(sorted.length / 2)] || 16.7
55
+ const late = intervals.filter((ms) => ms > medianMs * 1.6)
56
+ const durationMs = frames.length > 1 ? frames.at(-1).t - frames[0].t : 0
57
+ const reasons = []
58
+ if (frames.length < 4) reasons.push(`only ${frames.length} animation frames recorded`)
59
+ if (requestedMs && durationMs + Math.max(100, medianMs * 3) < requestedMs) reasons.push(`recorded ${Math.round(durationMs)}ms of the requested ${Math.round(requestedMs)}ms`)
60
+ if (late.length) reasons.push(`${late.length} sampling gap(s) exceeded ${Math.round(medianMs * 1.6)}ms; motion during those gaps was not judged`)
61
+ if (medianMs > 40) reasons.push(`typical sampling interval was ${Math.round(medianMs)}ms; too sparse to judge short motion`)
62
+ if (intervals.some((ms) => !Number.isFinite(ms) || ms <= 0)) reasons.push('recording contained invalid or non-increasing frame timestamps')
63
+ if (frames.length && !frames.some((frame) => frame.items?.length)) reasons.push('no visible elements were sampled')
64
+ const cameraFrames = frames.filter((frame) => frame.cameraMoving).length
65
+ return { status: reasons.length ? 'inconclusive' : 'complete', frames: frames.length, durationMs: durationMs / slow, medianMs, maxGapMs: Math.max(0, ...intervals), skippedGaps: late.length, cameraFrames, reasons }
66
+ }
67
+
68
+ export function reportResult({ stages = [], errors = [], strict = false, still = false } = {}) {
69
+ const incomplete = errors.length > 0 || stages.length === 0 || stages.some((stage) => stage.coverage?.status !== 'complete')
70
+ const findings = stages.reduce((n, stage) => n + (stage.findings?.length || 0), 0)
71
+ const manual = stages.reduce((n, stage) => n + (stage.manual?.length || 0), 0)
72
+ const status = incomplete ? 'inconclusive' : findings ? 'issues' : 'no-issues-detected'
73
+ return { status, mode: still ? 'still' : 'motion', stages, errors, manualReviewRequired: !still || manual > 0, exitCode: incomplete ? 2 : strict && findings ? 1 : 0 }
74
+ }
75
+
76
+ export function printCoverage(key, sample) {
77
+ console.log(`coverage ${key}: ${sample.frames} frames, ${(sample.durationMs / 1000).toFixed(2)}s, largest gap ${sample.maxGapMs.toFixed(1)}ms (${sample.status})`)
78
+ for (const reason of sample.reasons) console.log(` incomplete: ${reason}`)
79
+ if (sample.cameraFrames) console.log(` manual: camera contents excluded during ${sample.cameraFrames} moving-camera frames`)
80
+ }
81
+
82
+ export function motionFindings(motion, slow = 1) {
83
+ if (!motion) return []
84
+ const lines = [...new Set(motion.flagged)]
85
+ const ink = motion.ink.filter((i) => i.at >= motion.start).map((i) => ({ n: i.n, t: (i.at - motion.start) / 1000 / slow }))
86
+ const most = Math.max(0, ...ink.map((i) => i.n))
87
+ const runs = []
88
+ // An initial fade may start with no ink. Judge a loss of established
89
+ // content, not the baseline before the first entrance has appeared.
90
+ const firstContent = ink.findIndex((sample) => sample.n >= most * 0.2 && sample.n > 0)
91
+ for (const sample of firstContent < 0 ? [] : ink.slice(firstContent)) {
92
+ const last = runs.at(-1)
93
+ if (sample.n < most * 0.2 && last && !last.done) { last.end = sample.t; last.min = Math.min(last.min, sample.n) }
94
+ else if (sample.n < most * 0.2) runs.push({ start: sample.t, end: sample.t, min: sample.n })
95
+ else if (last) last.done = true
96
+ }
97
+ const low = runs.filter((r) => r.end - r.start >= 0.12)
98
+ if (most && low.length) lines.push(`near-empty frames: visible content falls to ${Math.min(...low.map((r) => r.min))} of ${most} elements around ${low[0].start.toFixed(1)}s for ${Math.round((low[0].end - low[0].start) * 1000)}ms${low.length > 1 ? ` (${low.length} times)` : ''}; inspect the handoff and overlap the old and new content`)
99
+ return lines
100
+ }
101
+
102
+ const violation = (rule, message, evidence) => ({ rule, message, ...(evidence ? { evidence } : {}) })
103
+
104
+ export function parseRgba(colorStr) {
105
+ if (!colorStr) return [0, 0, 0, 1];
106
+ const m = colorStr.match(/rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)(?:\s*,\s*([\d.]+))?\s*\)/i);
107
+ if (m) {
108
+ return [Number(m[1]), Number(m[2]), Number(m[3]), m[4] !== undefined ? Number(m[4]) : 1];
109
+ }
110
+ if (colorStr.startsWith('#')) {
111
+ const hex = colorStr.slice(1);
112
+ if (hex.length === 3 || hex.length === 4) {
113
+ const [r, g, b] = [0, 1, 2].map(i => parseInt(hex[i] + hex[i], 16));
114
+ const a = hex.length === 4 ? parseInt(hex[3] + hex[3], 16) / 255 : 1;
115
+ return [r, g, b, a];
116
+ }
117
+ const [r, g, b] = [0, 2, 4].map(i => parseInt(hex.slice(i, i + 2), 16));
118
+ const a = hex.length >= 8 ? parseInt(hex.slice(6, 8), 16) / 255 : 1;
119
+ return [r, g, b, a];
120
+ }
121
+ return [0, 0, 0, 1];
122
+ }
123
+
124
+ export function relativeLuminance([r, g, b]) {
125
+ const [rs, gs, bs] = [r, g, b].map(c => {
126
+ const s = c / 255;
127
+ return s <= 0.04045 ? s / 12.92 : Math.pow((s + 0.055) / 1.055, 2.4);
128
+ });
129
+ return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;
130
+ }
131
+
132
+ export function calculateContrastRatio(fgColor, bgColor) {
133
+ const fg = Array.isArray(fgColor) ? fgColor : parseRgba(fgColor);
134
+ const bg = Array.isArray(bgColor) ? bgColor : parseRgba(bgColor);
135
+ const alpha = fg[3] !== undefined ? fg[3] : 1;
136
+ const blended = [
137
+ Math.round(fg[0] * alpha + bg[0] * (1 - alpha)),
138
+ Math.round(fg[1] * alpha + bg[1] * (1 - alpha)),
139
+ Math.round(fg[2] * alpha + bg[2] * (1 - alpha))
140
+ ];
141
+ const l1 = relativeLuminance(blended);
142
+ const l2 = relativeLuminance(bg.slice(0, 3));
143
+ const lighter = Math.max(l1, l2);
144
+ const darker = Math.min(l1, l2);
145
+ return (lighter + 0.05) / (darker + 0.05);
146
+ }
147
+
148
+ function staticVerify(target, source) {
149
+ const lines = source.split(/\r?\n/)
150
+ const findings = []
151
+ const report = (rule, message, line) => findings.push(violation(rule, message, line ? `${line.number}: ${line.text.trim()}` : undefined))
152
+ const evidenceAt = (index) => {
153
+ const number = source.slice(0, index).split(/\r?\n/).length
154
+ return { number, text: lines[number - 1] || '' }
155
+ }
156
+ const stages = [...source.matchAll(/<Stage\b[^>]*>/g)]
157
+ const stage = stages.find((match) => {
158
+ const width = /\bwidth\s*=\s*\{?['"]?(\d+)/.exec(match[0])
159
+ const height = /\bheight\s*=\s*\{?['"]?(\d+)/.exec(match[0])
160
+ return width && height && +width[1] >= 320 && +height[1] >= 200
161
+ })
162
+ const root = source.match(/<[A-Za-z][\w.-]*\b[^>]*>/)
163
+ const rootWidth = root && !/^<Stage\b/i.test(root[0]) && /\bwidth\s*=\s*\{?['"]?(\d+)/i.exec(root[0])
164
+ const rootHeight = root && !/^<Stage\b/i.test(root[0]) && /\bheight\s*=\s*\{?['"]?(\d+)/i.exec(root[0])
165
+ const rootSized = rootWidth && rootHeight && +rootWidth[1] >= 320 && +rootHeight[1] >= 200
166
+ if (!stage && !rootSized) report('framing.stage', 'A Stage or root element with explicit width >= 320 and height >= 200 is required.', stages[0] ? evidenceAt(stages[0].index) : root ? evidenceAt(root.index) : undefined)
167
+
168
+ const frameNames = ['Window', 'Phone', 'BrowserWindow', 'DeviceFrame']
169
+ const frameRegex = new RegExp(`<(${frameNames.join('|')})\\b([^>]*)>`, 'g')
170
+ const frames = [...source.matchAll(frameRegex)]
171
+ if (!frames.length) report('framing.dominantFrame', 'No Window, Phone, BrowserWindow, or DeviceFrame element was found.', lines.map((text, i) => ({ text, number: i + 1 })).find(({ text }) => /<(?:Stage|[a-z][\w.-]*)\b/.test(text)))
172
+ const bleed = /(?:^|\s)(?:-mx-[\w./-]+|w-full|h-full|absolute|inset(?:-[\w./-]+)?|rounded-t-[\w./-]+|overflow-hidden)(?:\s|$)/
173
+ const margin = /(?:^|\s)m-[4-9](?:\s|$)/
174
+ const floating = frames.find((match) => {
175
+ const classes = /className\s*=\s*['"`]([^'"`]*)/.exec(match[2])?.[1] || ''
176
+ const centeredMargins = /(?:^|\s)mx-auto(?:\s|$)/.test(classes) && /(?:^|\s)my-[4-9](?:\s|$)/.test(classes)
177
+ return (margin.test(classes) || centeredMargins) && !bleed.test(classes)
178
+ })
179
+ if (floating) report('framing.floating', 'A framed element has uniform outer margins and no detectable bleed signal.', lines[0] && { number: source.slice(0, floating.index).split(/\r?\n/).length, text: lines[source.slice(0, floating.index).split(/\r?\n/).length - 1] })
180
+
181
+ const purpleHex = (hex) => {
182
+ const value = hex.slice(1)
183
+ const rgb = value.length <= 4 ? [...value].map((part) => parseInt(part + part, 16)) : [0, 2, 4].map((offset) => parseInt(value.slice(offset, offset + 2), 16))
184
+ return rgb[2] > rgb[1] * 1.08 && rgb[0] > rgb[1] * 0.55 && rgb[2] > 75
185
+ }
186
+ const hasPurpleColor = (value) => /\b(?:purple|indigo|violet|fuchsia|magenta)\b/i.test(value) || [...value.matchAll(/#[\da-f]{3,8}\b/gi)].some(([hex]) => purpleHex(hex)) || [...value.matchAll(/rgba?\(([^)]*)\)/gi)].some(([, body]) => {
187
+ const [r, g, b] = body.match(/[\d.]+/g)?.slice(0, 3).map(Number) || []
188
+ return Number.isFinite(b) && b > g * 1.08 && r > g * 0.55 && b > 75
189
+ })
190
+ const purple = /(?:bg-gradient|from|via|to)-(?:purple|indigo|violet|fuchsia)(?:-[\w./]+)?/i
191
+ const purpleLine = lines.map((text, i) => ({ text, number: i + 1 })).find(({ text }) => purple.test(text) || [...text.matchAll(/(?:linear|radial|conic)-gradient\(([^)]*)\)/gi)].some(([, body]) => hasPurpleColor(body)))
192
+ if (purpleLine) report('accent.purpleGradient', 'Purple, indigo, violet, or fuchsia gradient styling was found.', purpleLine)
193
+
194
+ const sparkleLine = lines.map((text, i) => ({ text, number: i + 1 })).find(({ text }) => /(?:Sparkles?|MagicWand|WandSparkles|Wand2)\b|icon-(?:sparkles?|magic-wand)|lucide-(?:sparkles?|wand-sparkles|wand-2)/i.test(text))
195
+ if (sparkleLine) report('icon.sparkle', 'Sparkle or magic-wand icon usage was found.', sparkleLine)
196
+
197
+ const motionLine = lines.map((text, i) => ({ text, number: i + 1 })).find(({ text }) => {
198
+ if (/animate-(?:bounce|ping)\b/.test(text)) return true
199
+ const loop = /animate-(?:pulse|spin)\b|animate-\[[^\]]*infinite[^\]]*\]|animation\s*:\s*[^;]*\binfinite\b|animation-iteration-count\s*:\s*infinite/i.test(text)
200
+ if (!loop) return false
201
+ return !/(?:progress|loading|busy|role\s*=\s*["']progressbar|aria-valuenow)/i.test(source)
202
+ })
203
+ if (motionLine) report('motion.unearned', 'Unearned looping motion was found without a progress signal.', motionLine)
204
+ return { ok: findings.length === 0, target, mode: 'static', stages: [], violations: findings }
205
+ }
206
+
207
+ async function browserVerify(target, { timeoutMs, selector }) {
208
+ const unavailable = (reason) => ({ ok: false, target, mode: 'browser', unavailable: reason, stages: [], violations: [] })
209
+ let browser
210
+ const task = (async () => {
211
+ let chromium
212
+ try { ({ chromium } = await import('playwright-core')) }
213
+ catch { return unavailable('playwright-core is not installed; install the declared package to enable browser verification.') }
214
+ const executablePath = process.env.CHROME_PATH || chromium.executablePath()
215
+ try {
216
+ const { access } = await import('node:fs/promises')
217
+ await access(executablePath)
218
+ } catch { return unavailable(`No Chromium executable is available at ${executablePath}; install a browser or set CHROME_PATH.`) }
219
+ try { browser = await chromium.launch({ executablePath }) }
220
+ catch (error) { return unavailable(`Chromium could not be launched: ${error?.message || String(error)}`) }
221
+ try {
222
+ const page = await browser.newPage()
223
+ const failedRequests = []
224
+ page.on('response', (response) => {
225
+ if (response.status() >= 400 && response.request().resourceType() !== 'document') {
226
+ failedRequests.push({ url: response.url(), status: response.status() })
227
+ }
228
+ })
229
+ await page.goto(target, { waitUntil: 'domcontentloaded', timeout: timeoutMs })
230
+ const initial = await page.evaluate((requestedSelector) => {
231
+ const selector = requestedSelector || '.ss-stage, .ss-window, [data-stage], [data-window], [class*="Phone"], [class*="BrowserWindow"], [class*="DeviceFrame"]'
232
+ const candidates = [...document.querySelectorAll(selector)].filter((el) => { const r = el.getBoundingClientRect(); return r.width > 0 && r.height > 0 })
233
+ const el = candidates.sort((a, b) => b.getBoundingClientRect().width * b.getBoundingClientRect().height - a.getBoundingClientRect().width * a.getBoundingClientRect().height)[0]
234
+ const purple = [...document.querySelectorAll('[class], [style]')].some((node) => {
235
+ const value = `${node.getAttribute('class') || ''} ${node.getAttribute('style') || ''} ${getComputedStyle(node).backgroundImage}`
236
+ if (/(?:from|via|to)-(?:purple|indigo|violet|fuchsia)|(?:purple|indigo|violet|fuchsia)\b/i.test(value) && /gradient/i.test(value)) return true
237
+ if (!/gradient/i.test(value)) return false
238
+ const hexes = [...value.matchAll(/#([\da-f]{3,8})\b/gi)].map(([, hex]) => hex.length <= 4 ? [...hex].map((c) => parseInt(c + c, 16)) : [0, 2, 4].map((i) => parseInt(hex.slice(i, i + 2), 16)))
239
+ const rgbs = [...value.matchAll(/rgba?\(([^)]*)\)/gi)].map(([, body]) => body.match(/[\d.]+/g)?.slice(0, 3).map(Number) || [])
240
+ return [...hexes, ...rgbs].some(([r, g, b]) => Number.isFinite(b) && b > g * 1.08 && r > g * 0.55 && b > 75)
241
+ })
242
+ const sparkle = !!document.querySelector('[class*="sparkle" i], [class*="wand" i], [data-icon*="sparkle" i], [aria-label*="sparkle" i], [aria-label*="magic wand" i]')
243
+ if (!el) return { viewport: { width: innerWidth, height: innerHeight }, frame: null, purple, sparkle }
244
+ const r = el.getBoundingClientRect()
245
+ return { viewport: { width: innerWidth, height: innerHeight }, frame: { x: r.left, y: r.top, width: r.width, height: r.height, label: el.getAttribute('aria-label') || el.getAttribute('class') || el.tagName.toLowerCase() }, purple, sparkle }
246
+ }, selector)
247
+
248
+ // Audit UX, accessibility, contrast, and broken assets
249
+ const uxAudit = await page.evaluate(() => {
250
+ const issues = []
251
+
252
+ // Broken images check
253
+ const images = [...document.querySelectorAll('img')]
254
+ for (const img of images) {
255
+ if (img.complete && img.naturalWidth === 0 && img.naturalHeight === 0 && !img.src.startsWith('data:image/svg')) {
256
+ issues.push({
257
+ rule: 'asset.brokenImage',
258
+ message: 'Broken image detected on stage.',
259
+ evidence: img.src || img.getAttribute('src') || 'img[src]'
260
+ })
261
+ }
262
+ }
263
+
264
+ // WCAG AA contrast computed-style evaluation
265
+ const parseColor = (str) => {
266
+ const m = (str || '').match(/rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)(?:\s*,\s*([\d.]+))?\s*\)/i)
267
+ if (!m) return [0, 0, 0, 1]
268
+ return [Number(m[1]), Number(m[2]), Number(m[3]), m[4] !== undefined ? Number(m[4]) : 1]
269
+ }
270
+ const lum = ([r, g, b]) => {
271
+ const [rs, gs, bs] = [r, g, b].map(c => {
272
+ const s = c / 255
273
+ return s <= 0.04045 ? s / 12.92 : Math.pow((s + 0.055) / 1.055, 2.4)
274
+ })
275
+ return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs
276
+ }
277
+ const getEffectiveBg = (el) => {
278
+ let curr = el
279
+ while (curr && curr !== document.documentElement) {
280
+ const cs = getComputedStyle(curr)
281
+ const [r, g, b, a] = parseColor(cs.backgroundColor)
282
+ if (a > 0.05) return [r, g, b, a]
283
+ curr = curr.parentElement
284
+ }
285
+ return [255, 255, 255, 1]
286
+ }
287
+
288
+ const textNodes = [...document.querySelectorAll('p, span, h1, h2, h3, h4, h5, h6, a, button, li, label')]
289
+ for (const el of textNodes) {
290
+ const text = (el.innerText || el.textContent || '').trim()
291
+ if (!text || text.length > 80 || el.children.length > 2) continue
292
+ const r = el.getBoundingClientRect()
293
+ if (r.width === 0 || r.height === 0) continue
294
+ const cs = getComputedStyle(el)
295
+ if (cs.display === 'none' || cs.visibility === 'hidden' || cs.opacity === '0') continue
296
+ const fg = parseColor(cs.color)
297
+ const bg = getEffectiveBg(el)
298
+ const alpha = fg[3]
299
+ const blended = [
300
+ Math.round(fg[0] * alpha + bg[0] * (1 - alpha)),
301
+ Math.round(fg[1] * alpha + bg[1] * (1 - alpha)),
302
+ Math.round(fg[2] * alpha + bg[2] * (1 - alpha))
303
+ ]
304
+ const l1 = lum(blended)
305
+ const l2 = lum(bg.slice(0, 3))
306
+ const ratio = (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05)
307
+ const isLarge = parseFloat(cs.fontSize) >= 24 || (parseFloat(cs.fontSize) >= 18.66 && (parseInt(cs.fontWeight) >= 700 || cs.fontWeight === 'bold'))
308
+ const minRatio = isLarge ? 3.0 : 4.5
309
+ if (ratio < minRatio && ratio > 1.01) {
310
+ issues.push({
311
+ rule: 'a11y.contrast',
312
+ message: `Rendered text fails WCAG AA contrast (${ratio.toFixed(2)}:1 vs ${minRatio}:1 minimum).`,
313
+ evidence: `"${text.slice(0, 30)}" (${cs.fontSize}, ${cs.color} on rgb(${bg.slice(0, 3).join(',')}))`
314
+ })
315
+ break
316
+ }
317
+ }
318
+
319
+ // Keyboard focus visible
320
+ const interactives = [...document.querySelectorAll('button, a[href], input, select, textarea, [tabindex="0"], [role="button"]')]
321
+ for (const el of interactives.slice(0, 10)) {
322
+ const cs = getComputedStyle(el)
323
+ const noOutline = cs.outlineStyle === 'none' || parseFloat(cs.outlineWidth) === 0
324
+ const noShadow = !cs.boxShadow || cs.boxShadow === 'none'
325
+ const noBorder = cs.borderStyle === 'none' || parseFloat(cs.borderWidth) === 0
326
+ if (noOutline && noShadow && noBorder && el.getAttribute('tabindex') !== '-1') {
327
+ issues.push({
328
+ rule: 'a11y.focusVisible',
329
+ message: 'Interactive control lacks visible keyboard focus affordance.',
330
+ evidence: `${el.tagName.toLowerCase()}${el.id ? '#' + el.id : el.className ? '.' + String(el.className).split(' ')[0] : ''}`
331
+ })
332
+ break
333
+ }
334
+ }
335
+
336
+ return issues
337
+ })
338
+
339
+ // Test 375px mobile viewport overflow
340
+ await page.setViewportSize({ width: 375, height: 667 })
341
+ const mobileAudit = await page.evaluate(() => {
342
+ const issues = []
343
+ const scrollWidth = document.documentElement.scrollWidth
344
+ if (scrollWidth > 375 + 2) {
345
+ issues.push({
346
+ rule: 'layout.mobileOverflow',
347
+ message: `Horizontal content overflow detected on 375px mobile viewport (${scrollWidth}px vs 375px).`,
348
+ evidence: `scrollWidth ${scrollWidth}px exceeds viewport width 375px`
349
+ })
350
+ }
351
+ return issues
352
+ })
353
+
354
+ const frames = await page.evaluate(async (requestedSelector) => {
355
+ const selector = requestedSelector || '.ss-stage, .ss-window, [data-stage], [data-window], [class*="Phone"], [class*="BrowserWindow"], [class*="DeviceFrame"]'
356
+ const pick = () => [...document.querySelectorAll(selector)].filter((el) => { const r = el.getBoundingClientRect(); return r.width > 0 && r.height > 0 }).sort((a, b) => b.getBoundingClientRect().width * b.getBoundingClientRect().height - a.getBoundingClientRect().width * a.getBoundingClientRect().height)[0]
357
+ const items = [], end = performance.now() + 1500
358
+ while (performance.now() < end) { const el = pick(); if (el) { const r = el.getBoundingClientRect(); items.push([r.x, r.y, r.width, r.height]) } await new Promise(requestAnimationFrame) }
359
+ return items
360
+ }, selector)
361
+ const violations = []
362
+ const frame = initial.frame, vp = initial.viewport
363
+ if (!frame || Math.max(frame.width / vp.width, frame.height / vp.height) < 0.66) violations.push(violation('framing.coverage', 'No dominant stage or frame reaches 66% of either viewport axis.', frame ? `${frame.width}x${frame.height} in ${vp.width}x${vp.height}` : 'No visible stage or frame was found.'))
364
+ if (frame && frame.x > 1 && frame.y > 1 && vp.width - frame.x - frame.width > 1 && vp.height - frame.y - frame.height > 1) violations.push(violation('framing.floating', 'The dominant frame has positive gaps on all four viewport edges.', `gaps ${frame.x}, ${frame.y}, ${vp.width - frame.x - frame.width}, ${vp.height - frame.y - frame.height}px`))
365
+ if (initial.purple) violations.push(violation('accent.purpleGradient', 'Purple, indigo, violet, or fuchsia gradient styling was found.'))
366
+ if (initial.sparkle) violations.push(violation('icon.sparkle', 'Sparkle or magic-wand icon markup was found.'))
367
+ let maxDelta = 0
368
+ for (let i = 1; i < frames.length; i++) maxDelta = Math.max(maxDelta, ...frames[i].map((n, j) => Math.abs(n - frames[i - 1][j])))
369
+ if (maxDelta > 2) violations.push(violation('motion.layoutJump', `The dominant frame moved or resized by ${maxDelta.toFixed(1)}px between sampled frames.`, `${frames.length} samples over approximately 1.5 seconds`))
370
+
371
+ for (const issue of uxAudit) {
372
+ violations.push(violation(issue.rule, issue.message, issue.evidence))
373
+ }
374
+ for (const issue of mobileAudit) {
375
+ violations.push(violation(issue.rule, issue.message, issue.evidence))
376
+ }
377
+ for (const req of failedRequests) {
378
+ violations.push(violation('asset.brokenLink', `Resource failed to load with HTTP ${req.status}.`, req.url))
379
+ }
380
+
381
+ return { ok: violations.length === 0, target, mode: 'browser', stages: frame ? [{ label: String(frame.label).slice(0, 100), coverage: Math.max(frame.width / vp.width, frame.height / vp.height), bleeds: [frame.x <= 1 && 'left', frame.y <= 1 && 'top', vp.width - frame.x - frame.width <= 1 && 'right', vp.height - frame.y - frame.height <= 1 && 'bottom'].filter(Boolean) }] : [], violations }
382
+ } catch (error) {
383
+ return unavailable(`Browser verification could not complete: ${error?.message || String(error)}`)
384
+ } finally { await browser?.close().catch(() => {}) }
385
+ })()
386
+ let timer
387
+ const timeout = new Promise((resolve) => { timer = setTimeout(() => resolve(unavailable(`Browser verification exceeded timeoutMs=${timeoutMs}.`)), timeoutMs) })
388
+ const result = await Promise.race([task, timeout])
389
+ clearTimeout(timer)
390
+ if (result.unavailable) await browser?.close().catch(() => {})
391
+ return result
392
+ }
393
+
394
+ export async function verifyTarget(target, options = {}) {
395
+ const timeoutMs = Number.isFinite(options.timeoutMs) && options.timeoutMs > 0 ? options.timeoutMs : 15000
396
+ if (/^https?:\/\//.test(target)) return browserVerify(target, { timeoutMs, selector: options.selector ?? null })
397
+ try { return staticVerify(target, await readFile(resolve(target), 'utf8')) }
398
+ catch (error) { return { ok: false, target, mode: 'static', stages: [], violations: [violation('input.unreadable', `Could not read target file: ${error?.message || String(error)}`)] } }
399
+ }
400
+
401
+ export default verifyTarget
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
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.