@edjbarron/ux-guard 0.0.0-stage → 0.6.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,344 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { JourneyReportError } from './journeys.mjs';
3
+ import {
4
+ pngDimensions,
5
+ validateVisualProfile,
6
+ visualImageId,
7
+ VisualContractError,
8
+ } from './visuals.mjs';
9
+
10
+ export const PLAYWRIGHT_JOURNEY_METRICS = Object.freeze([
11
+ 'clicks',
12
+ 'keystrokes',
13
+ 'editedFields',
14
+ 'routeChanges',
15
+ ]);
16
+
17
+ const BROWSER_METRICS = new Set(PLAYWRIGHT_JOURNEY_METRICS.filter((metric) => metric !== 'routeChanges'));
18
+
19
+ // This adapter intentionally uses only Playwright's structural Page API. The
20
+ // consumer supplies its Page; ux-guard has no Playwright runtime dependency.
21
+ export async function attachPlaywrightMeasurements(
22
+ page,
23
+ { bindingName = '__uxGuardJourneyMeasurementV1' } = {},
24
+ ) {
25
+ validatePage(page);
26
+ if (typeof bindingName !== 'string' || !/^[_A-Za-z][_A-Za-z0-9]*$/.test(bindingName)) {
27
+ throw new JourneyReportError('Playwright measurement bindingName must be a JavaScript identifier');
28
+ }
29
+
30
+ const totals = Object.fromEntries(PLAYWRIGHT_JOURNEY_METRICS.map((metric) => [metric, 0]));
31
+ const flushed = structuredClone(totals);
32
+ let disposed = false;
33
+ let currentUrl = page.url();
34
+
35
+ await page.exposeBinding(bindingName, (_source, event) => {
36
+ if (disposed) return;
37
+ validateBrowserEvent(event);
38
+ totals[event.metric] += event.amount;
39
+ });
40
+ await page.addInitScript(installBrowserMeasurements, bindingName);
41
+ await page.evaluate(installBrowserMeasurements, bindingName);
42
+
43
+ const onFrameNavigated = (frame) => {
44
+ if (disposed || frame !== page.mainFrame()) return;
45
+ const nextUrl = frame.url();
46
+ if (nextUrl === currentUrl) return;
47
+ currentUrl = nextUrl;
48
+ totals.routeChanges += 1;
49
+ };
50
+ page.on('framenavigated', onFrameNavigated);
51
+
52
+ return Object.freeze({
53
+ metrics: PLAYWRIGHT_JOURNEY_METRICS,
54
+
55
+ async flush(recorder) {
56
+ if (disposed) throw new JourneyReportError('Playwright measurement adapter is disposed');
57
+ if (!recorder || typeof recorder.record !== 'function') {
58
+ throw new JourneyReportError('flush needs an active journey recorder step');
59
+ }
60
+ try {
61
+ await page.evaluate(flushBrowserMeasurements, bindingName);
62
+ } catch (error) {
63
+ if (!isNavigationEvaluationError(error)) throw error;
64
+ if (typeof page.waitForLoadState === 'function') {
65
+ await page.waitForLoadState('domcontentloaded');
66
+ }
67
+ await page.evaluate(flushBrowserMeasurements, bindingName);
68
+ }
69
+ for (const metric of PLAYWRIGHT_JOURNEY_METRICS) {
70
+ const delta = totals[metric] - flushed[metric];
71
+ recorder.record(metric, delta);
72
+ flushed[metric] = totals[metric];
73
+ }
74
+ },
75
+
76
+ dispose() {
77
+ if (disposed) return;
78
+ disposed = true;
79
+ page.off('framenavigated', onFrameNavigated);
80
+ },
81
+ });
82
+ }
83
+
84
+ export async function capturePlaywrightCheckpoint(
85
+ page,
86
+ {
87
+ profile,
88
+ checkpoint,
89
+ styleContent = '',
90
+ waitUntilReady = null,
91
+ } = {},
92
+ ) {
93
+ validateVisualPage(page);
94
+ validateVisualProfile(profile);
95
+ if (!checkpoint || !checkpoint.profiles?.includes(profile.id)) {
96
+ throw new VisualContractError('visual checkpoint is not approved for this profile');
97
+ }
98
+ if (typeof styleContent !== 'string') {
99
+ throw new VisualContractError('visual consumer styleContent must be text');
100
+ }
101
+ if (waitUntilReady !== null && typeof waitUntilReady !== 'function') {
102
+ throw new VisualContractError('visual consumer waitUntilReady must be a function');
103
+ }
104
+ const viewport = page.viewportSize();
105
+ if (
106
+ !viewport ||
107
+ viewport.width !== profile.viewport.width ||
108
+ viewport.height !== profile.viewport.height
109
+ ) {
110
+ throw new VisualContractError('Playwright viewport does not match visual profile');
111
+ }
112
+ const browser = page.context().browser();
113
+ if (!browser || browser.version() !== profile.browser.version) {
114
+ throw new VisualContractError('Playwright browser version does not match visual profile');
115
+ }
116
+ await page.emulateMedia({
117
+ colorScheme: profile.colorScheme,
118
+ reducedMotion: profile.reducedMotion,
119
+ });
120
+ await page.addStyleTag({
121
+ content: [
122
+ styleContent,
123
+ '*, *::before, *::after {',
124
+ ' animation: none !important;',
125
+ ' animation-duration: 0s !important;',
126
+ ' transition: none !important;',
127
+ ' transition-duration: 0s !important;',
128
+ ' caret-color: transparent !important;',
129
+ '}',
130
+ ].filter(Boolean).join('\n'),
131
+ });
132
+ const fontQueries = [
133
+ ...new Set(profile.fonts.map((font) => cssFontQuery(font))),
134
+ ];
135
+ await page.evaluate(async ({ expected, fontQueries: expectedFonts }) => {
136
+ await document.fonts.ready;
137
+ const facts = {
138
+ width: window.innerWidth,
139
+ height: window.innerHeight,
140
+ dpr: window.devicePixelRatio,
141
+ locale: navigator.language,
142
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
143
+ clock: new Date(Date.now()).toISOString(),
144
+ reducedMotion: matchMedia('(prefers-reduced-motion: reduce)').matches,
145
+ dark: matchMedia('(prefers-color-scheme: dark)').matches,
146
+ externalResources: performance
147
+ .getEntriesByType('resource')
148
+ .map((entry) => entry.name)
149
+ .filter(
150
+ (url) =>
151
+ !url.startsWith(location.origin) &&
152
+ !url.startsWith('data:') &&
153
+ !url.startsWith('blob:'),
154
+ ),
155
+ fonts: expectedFonts.map((query) => ({
156
+ query,
157
+ available: document.fonts.check(query),
158
+ })),
159
+ };
160
+ if (
161
+ facts.width !== expected.viewport.width ||
162
+ facts.height !== expected.viewport.height ||
163
+ facts.dpr !== expected.viewport.deviceScaleFactor ||
164
+ facts.locale !== expected.locale ||
165
+ facts.timezone !== expected.timezone ||
166
+ facts.clock !== expected.clock ||
167
+ !facts.reducedMotion ||
168
+ facts.dark !== (expected.colorScheme === 'dark') ||
169
+ facts.externalResources.length !== 0 ||
170
+ facts.fonts.some(({ available }) => !available)
171
+ ) {
172
+ throw new Error(`visual profile mismatch: ${JSON.stringify(facts)}`);
173
+ }
174
+ }, { expected: profile, fontQueries });
175
+ if (waitUntilReady) {
176
+ await waitUntilReady(page, { profile, checkpoint });
177
+ }
178
+ const masks = [];
179
+ for (const mask of checkpoint.masks) {
180
+ const locator = page.locator(mask.selector);
181
+ if ((await locator.count()) === 0) {
182
+ throw new VisualContractError(`reviewed visual mask ${mask.id} matched nothing`);
183
+ }
184
+ masks.push(locator);
185
+ }
186
+ const bytes = await page.screenshot({
187
+ fullPage: profile.screenshot.fullPage,
188
+ animations: profile.screenshot.animations,
189
+ caret: profile.screenshot.caret,
190
+ scale: profile.screenshot.scale,
191
+ omitBackground: profile.screenshot.omitBackground,
192
+ mask: masks,
193
+ maskColor: profile.screenshot.maskColor,
194
+ });
195
+ const dimensions = pngDimensions(bytes, 'Playwright screenshot');
196
+ const image = {
197
+ id: visualImageId({
198
+ ...checkpoint,
199
+ scheme: profile.colorScheme,
200
+ profileId: profile.id,
201
+ }),
202
+ useCaseId: checkpoint.useCaseId,
203
+ journeyId: checkpoint.journeyId,
204
+ checkpointId: checkpoint.checkpointId,
205
+ scheme: profile.colorScheme,
206
+ profileId: profile.id,
207
+ profileHash: profile.canonicalHash,
208
+ tier: checkpoint.tier,
209
+ purpose: checkpoint.purpose,
210
+ path: '',
211
+ sha256: createHash('sha256').update(bytes).digest('hex'),
212
+ width: dimensions.width,
213
+ height: dimensions.height,
214
+ masks: checkpoint.masks.map(({ id }) => id),
215
+ tolerance: structuredClone(checkpoint.tolerance),
216
+ };
217
+ return { image, bytes };
218
+ }
219
+
220
+ function isNavigationEvaluationError(error) {
221
+ const message = error instanceof Error ? error.message : String(error);
222
+ return /execution context was destroyed|cannot find context|navigation/i.test(message);
223
+ }
224
+
225
+ function installBrowserMeasurements(bindingName) {
226
+ const stateKey = '__uxGuardJourneyMeasurementStateV1';
227
+ const existing = globalThis[stateKey];
228
+ if (existing?.bindingName === bindingName) return;
229
+ if (existing) throw new Error('ux-guard journey measurement is already installed');
230
+
231
+ const pending = [];
232
+ const completedFields = new WeakSet();
233
+ const modifiers = new Set([
234
+ 'Alt',
235
+ 'AltGraph',
236
+ 'CapsLock',
237
+ 'Control',
238
+ 'Fn',
239
+ 'FnLock',
240
+ 'Meta',
241
+ 'NumLock',
242
+ 'ScrollLock',
243
+ 'Shift',
244
+ 'Symbol',
245
+ 'SymbolLock',
246
+ ]);
247
+ const send = (metric) => {
248
+ const binding = globalThis[bindingName];
249
+ if (typeof binding !== 'function') return;
250
+ pending.push(Promise.resolve(binding({ metric, amount: 1 })));
251
+ };
252
+
253
+ globalThis.addEventListener(
254
+ 'click',
255
+ (event) => {
256
+ // Keyboard activation also emits click, but with detail=0. Count only
257
+ // primary pointer clicks so clicks and keystrokes remain independent.
258
+ if (event.isTrusted && event.detail > 0) send('clicks');
259
+ },
260
+ true,
261
+ );
262
+ globalThis.addEventListener(
263
+ 'keydown',
264
+ (event) => {
265
+ if (event.isTrusted && !modifiers.has(event.key)) send('keystrokes');
266
+ },
267
+ true,
268
+ );
269
+ globalThis.addEventListener(
270
+ 'input',
271
+ (event) => {
272
+ if (!event.isTrusted || !event.target || completedFields.has(event.target)) return;
273
+ const tag = event.target.tagName?.toLowerCase();
274
+ const field =
275
+ tag === 'input' ||
276
+ tag === 'select' ||
277
+ tag === 'textarea' ||
278
+ event.target.isContentEditable === true;
279
+ if (!field) return;
280
+ completedFields.add(event.target);
281
+ send('editedFields');
282
+ },
283
+ true,
284
+ );
285
+
286
+ globalThis[stateKey] = {
287
+ bindingName,
288
+ async flush() {
289
+ await Promise.all(pending.splice(0));
290
+ },
291
+ };
292
+ }
293
+
294
+ async function flushBrowserMeasurements(bindingName) {
295
+ const state = globalThis.__uxGuardJourneyMeasurementStateV1;
296
+ if (state?.bindingName === bindingName) await state.flush();
297
+ }
298
+
299
+ function validateBrowserEvent(event) {
300
+ if (
301
+ event === null ||
302
+ typeof event !== 'object' ||
303
+ !BROWSER_METRICS.has(event.metric) ||
304
+ !Number.isSafeInteger(event.amount) ||
305
+ event.amount < 0
306
+ ) {
307
+ throw new JourneyReportError('Playwright emitted an invalid journey measurement');
308
+ }
309
+ }
310
+
311
+ function validatePage(page) {
312
+ const methods = [
313
+ 'url',
314
+ 'exposeBinding',
315
+ 'addInitScript',
316
+ 'evaluate',
317
+ 'mainFrame',
318
+ 'on',
319
+ 'off',
320
+ ];
321
+ if (!page || methods.some((method) => typeof page[method] !== 'function')) {
322
+ throw new JourneyReportError('Playwright adapter needs a Page-compatible object');
323
+ }
324
+ }
325
+
326
+ function validateVisualPage(page) {
327
+ const methods = [
328
+ 'viewportSize',
329
+ 'context',
330
+ 'emulateMedia',
331
+ 'addStyleTag',
332
+ 'evaluate',
333
+ 'locator',
334
+ 'screenshot',
335
+ ];
336
+ if (!page || methods.some((method) => typeof page[method] !== 'function')) {
337
+ throw new VisualContractError('visual adapter needs a Page-compatible object');
338
+ }
339
+ }
340
+
341
+ function cssFontQuery({ family, style, weight }) {
342
+ const escapedFamily = family.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
343
+ return `${style} ${weight} 16px "${escapedFamily}"`;
344
+ }