@keboola/validate-ui 0.2.0 → 0.4.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.
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { chromium } from 'playwright';
2
2
  import { createReadStream } from 'fs';
3
- import { stat } from 'fs/promises';
3
+ import { stat, writeFile, readFile } from 'fs/promises';
4
4
  import { createServer } from 'http';
5
5
  import { join, resolve, normalize, sep, extname } from 'path';
6
6
  import axe from 'axe-core';
@@ -8,6 +8,7 @@ import { z } from 'zod';
8
8
  import Anthropic from '@anthropic-ai/sdk';
9
9
  import pixelmatch from 'pixelmatch';
10
10
  import { PNG } from 'pngjs';
11
+ import { brands, checkInteractiveContrast } from '@keboola/brand-registry';
11
12
 
12
13
  // src/types.ts
13
14
  var SEVERITIES = ["critical", "serious", "moderate", "minor"];
@@ -333,6 +334,302 @@ ${domExcerpt}`
333
334
  }
334
335
  };
335
336
 
337
+ // src/compare/diff.ts
338
+ var matchesGlob = (pattern, value) => {
339
+ if (!pattern.includes("*")) return pattern === value;
340
+ const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
341
+ return new RegExp(`^${escaped}$`).test(value);
342
+ };
343
+ var multisetMissing = (from, to) => {
344
+ const remaining = /* @__PURE__ */ new Map();
345
+ for (const value of to) remaining.set(value, (remaining.get(value) ?? 0) + 1);
346
+ const missing = [];
347
+ for (const value of from) {
348
+ const count = remaining.get(value) ?? 0;
349
+ if (count > 0) remaining.set(value, count - 1);
350
+ else missing.push(value);
351
+ }
352
+ return missing;
353
+ };
354
+ var signature = (regionKey, tokens) => `${regionKey}::${[...tokens].sort().join("|")}`;
355
+ var regionRemovalRule = (rules, key) => rules.find(
356
+ (rule) => rule.value === void 0 && rule.region !== void 0 && matchesGlob(rule.region, key)
357
+ );
358
+ var valueRuleMatches = (rule, key, value) => rule.value !== void 0 && matchesGlob(rule.value, value) && (rule.region === void 0 || matchesGlob(rule.region, key));
359
+ var removedFinding = (region, rule) => ({
360
+ regionKey: region.key,
361
+ kind: "region-removed",
362
+ valueSignature: signature(region.key, region.values),
363
+ message: rule === void 0 ? `region "${region.label}" was removed` : `region "${region.label}" removed as expected`,
364
+ severity: rule === void 0 ? "serious" : "minor",
365
+ ...rule !== void 0 && { suppressed: { reason: rule.reason } }
366
+ });
367
+ var degradedFinding = (region) => ({
368
+ regionKey: region.key,
369
+ kind: "region-degraded",
370
+ valueSignature: signature(region.key, [region.state]),
371
+ message: `region "${region.label}" degraded to ${region.state} state \u2014 not compared as value loss`,
372
+ severity: "minor"
373
+ });
374
+ var addedFinding = (region) => ({
375
+ regionKey: region.key,
376
+ kind: "region-added",
377
+ valueSignature: signature(region.key, []),
378
+ message: `region "${region.label}" is new`,
379
+ severity: "minor"
380
+ });
381
+ var diffRegionValues = (oldRegion, newRegion, rules) => {
382
+ const missing = multisetMissing(oldRegion.values, newRegion.values);
383
+ if (missing.length === 0) return [];
384
+ const active = [];
385
+ const suppressed = [];
386
+ const reasons = /* @__PURE__ */ new Set();
387
+ for (const value of missing) {
388
+ const rule = rules.find((r) => valueRuleMatches(r, newRegion.key, value));
389
+ if (rule === void 0) active.push(value);
390
+ else {
391
+ suppressed.push(value);
392
+ reasons.add(rule.reason);
393
+ }
394
+ }
395
+ const findings = [];
396
+ if (active.length > 0) {
397
+ findings.push({
398
+ regionKey: newRegion.key,
399
+ kind: "value-missing",
400
+ valueSignature: signature(newRegion.key, active),
401
+ message: `region "${newRegion.label}" is missing ${active.length} value(s)`,
402
+ severity: "moderate",
403
+ detail: active.join(", ")
404
+ });
405
+ }
406
+ if (suppressed.length > 0) {
407
+ findings.push({
408
+ regionKey: newRegion.key,
409
+ kind: "value-missing",
410
+ valueSignature: signature(newRegion.key, suppressed),
411
+ message: `region "${newRegion.label}" is missing ${suppressed.length} expected value(s)`,
412
+ severity: "minor",
413
+ detail: suppressed.join(", "),
414
+ suppressed: { reason: [...reasons].join("; ") }
415
+ });
416
+ }
417
+ return findings;
418
+ };
419
+ var diffSnapshots = (oldSnap, newSnap, config = {}) => {
420
+ const rules = config.expectedAbsent ?? [];
421
+ const newByKey = new Map(newSnap.regions.map((region) => [region.key, region]));
422
+ const oldKeys = new Set(oldSnap.regions.map((region) => region.key));
423
+ const findings = [];
424
+ for (const oldRegion of oldSnap.regions) {
425
+ const newRegion = newByKey.get(oldRegion.key);
426
+ if (newRegion === void 0) {
427
+ findings.push(removedFinding(oldRegion, regionRemovalRule(rules, oldRegion.key)));
428
+ continue;
429
+ }
430
+ if (oldRegion.state === "ok" && newRegion.state !== "ok") {
431
+ findings.push(degradedFinding(newRegion));
432
+ continue;
433
+ }
434
+ findings.push(...diffRegionValues(oldRegion, newRegion, rules));
435
+ }
436
+ for (const newRegion of newSnap.regions) {
437
+ if (!oldKeys.has(newRegion.key)) findings.push(addedFinding(newRegion));
438
+ }
439
+ return findings;
440
+ };
441
+ var comparePass = (findings) => !findings.some(
442
+ (f) => f.suppressed === void 0 && (f.severity === "serious" || f.severity === "critical")
443
+ );
444
+
445
+ // src/compare/regions.ts
446
+ var CANDIDATE_SELECTOR = [
447
+ "[data-region]",
448
+ "main",
449
+ "nav",
450
+ "header",
451
+ "aside",
452
+ "footer",
453
+ "section[aria-label]",
454
+ "[role=main]",
455
+ "[role=navigation]",
456
+ "[role=banner]",
457
+ "[role=complementary]",
458
+ "[role=contentinfo]",
459
+ "[role=region]"
460
+ ].join(",");
461
+ var DEFAULT_EMPTY_MARKERS = [
462
+ "no data",
463
+ "no results",
464
+ "nothing to show",
465
+ "nothing here",
466
+ "get started"
467
+ ];
468
+ var DEFAULT_ERROR_MARKERS = [
469
+ "something went wrong",
470
+ "failed to load",
471
+ "could not load",
472
+ "unavailable",
473
+ "try again"
474
+ ];
475
+ var extractRegions = async (page, config = {}) => {
476
+ const emptyMarkers = [...DEFAULT_EMPTY_MARKERS, ...config.emptyStateMarkers ?? []];
477
+ const errorMarkers = [...DEFAULT_ERROR_MARKERS, ...config.errorStateMarkers ?? []];
478
+ return page.evaluate(
479
+ ({ selector, emptyMarkers: emptyMarkers2, errorMarkers: errorMarkers2 }) => {
480
+ const STATES = ["ok", "empty", "error", "loading"];
481
+ const isState = (value) => STATES.includes(value);
482
+ const slugify = (raw) => raw.toLowerCase().trim().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "region";
483
+ const roleOf = (el) => {
484
+ const explicit = el.getAttribute("role");
485
+ if (explicit !== null && explicit !== "") return explicit;
486
+ const tag = el.tagName.toLowerCase();
487
+ if (tag === "main") return "main";
488
+ if (tag === "nav") return "navigation";
489
+ if (tag === "aside") return "complementary";
490
+ if (tag === "header" || tag === "footer") {
491
+ if (el.closest("main,nav,section,article,aside") !== null) return void 0;
492
+ return tag === "header" ? "banner" : "contentinfo";
493
+ }
494
+ return void 0;
495
+ };
496
+ const headingOf = (el) => {
497
+ const heading = el.querySelector("h1,h2,h3,h4,h5,h6");
498
+ const text = heading?.textContent?.trim();
499
+ return text !== void 0 && text !== "" ? text : void 0;
500
+ };
501
+ const keyOf = (el) => {
502
+ const region = el.getAttribute("data-region");
503
+ if (region !== null && region !== "") return slugify(region);
504
+ const testid = el.getAttribute("data-testid");
505
+ if (testid !== null && testid !== "") return slugify(testid);
506
+ const role = roleOf(el);
507
+ if (role !== void 0) return role;
508
+ const label = el.getAttribute("aria-label");
509
+ if (label !== null && label !== "") return slugify(label);
510
+ const heading = headingOf(el);
511
+ if (heading !== void 0) return slugify(heading);
512
+ return slugify(el.tagName);
513
+ };
514
+ const labelOf = (el, key) => {
515
+ const label = el.getAttribute("aria-label");
516
+ if (label !== null && label.trim() !== "") return label.trim();
517
+ const heading = headingOf(el);
518
+ if (heading !== void 0) return heading;
519
+ const testid = el.getAttribute("data-testid");
520
+ if (testid !== null && testid !== "") return testid;
521
+ return key;
522
+ };
523
+ const textOf = (el) => (el.innerText || el.textContent || "").trim();
524
+ const stateOf = (el, text) => {
525
+ const explicit = (el.getAttribute("data-state") ?? "").toLowerCase();
526
+ if (isState(explicit)) return explicit;
527
+ const lower = text.toLowerCase();
528
+ if (errorMarkers2.some((marker) => lower.includes(marker))) return "error";
529
+ if (lower.includes("loading")) return "loading";
530
+ if (emptyMarkers2.some((marker) => lower.includes(marker))) return "empty";
531
+ return "ok";
532
+ };
533
+ const valuesOf = (text) => (text.match(/-?\$?\s?\d[\d,]*(?:\.\d+)?%?/g) ?? []).map((token) => token.replace(/[$\s,]/g, "")).filter((token) => token !== "" && token !== "-");
534
+ const qualifies = (el) => {
535
+ const dataRegion = el.getAttribute("data-region");
536
+ if (dataRegion !== null && dataRegion !== "") {
537
+ const parent = el.parentElement;
538
+ return parent === null || parent.closest("[data-region]") === null;
539
+ }
540
+ return el.querySelector(selector) === null && el.closest("[data-region]") === null;
541
+ };
542
+ const candidates = Array.from(document.querySelectorAll(selector));
543
+ const regions = candidates.filter(qualifies);
544
+ const elements = regions.length > 0 ? regions : [document.body];
545
+ const used = {};
546
+ const uniqueKey = (key) => {
547
+ const count = (used[key] ?? 0) + 1;
548
+ used[key] = count;
549
+ return count === 1 ? key : `${key}-${count}`;
550
+ };
551
+ return elements.map((el) => {
552
+ const text = textOf(el);
553
+ const key = uniqueKey(keyOf(el));
554
+ return {
555
+ key,
556
+ label: labelOf(el, key),
557
+ state: stateOf(el, text),
558
+ values: valuesOf(text)
559
+ };
560
+ });
561
+ },
562
+ { selector: CANDIDATE_SELECTOR, emptyMarkers, errorMarkers }
563
+ );
564
+ };
565
+ var REGION_STATES = ["ok", "empty", "error", "loading"];
566
+ var Region = z.object({
567
+ /** Stable id: data-region → data-testid → role → aria-label → heading slug. */
568
+ key: z.string(),
569
+ /** Human label for the report. */
570
+ label: z.string(),
571
+ state: z.enum(REGION_STATES),
572
+ /** Normalized numeric / currency / percent tokens found in the region. */
573
+ values: z.array(z.string())
574
+ });
575
+ var CompareSnapshot = z.object({
576
+ /** Route the snapshot was captured at, e.g. `/financials`. */
577
+ route: z.string(),
578
+ regions: z.array(Region)
579
+ }).refine(
580
+ (snap) => new Set(snap.regions.map((region) => region.key)).size === snap.regions.length,
581
+ {
582
+ message: "region keys must be unique"
583
+ }
584
+ );
585
+ var ExpectedAbsentRule = z.object({
586
+ region: z.string().optional(),
587
+ value: z.string().optional(),
588
+ reason: z.string().min(1)
589
+ }).refine((rule) => rule.region !== void 0 || rule.value !== void 0, {
590
+ message: "expectedAbsent rule needs at least one of `region` or `value`"
591
+ });
592
+ var CompareConfig = z.object({
593
+ expectedAbsent: z.array(ExpectedAbsentRule).optional(),
594
+ emptyStateMarkers: z.array(z.string()).optional(),
595
+ errorStateMarkers: z.array(z.string()).optional()
596
+ });
597
+
598
+ // src/compare/snapshot.ts
599
+ var captureSnapshot = async (page, route, config) => ({
600
+ route,
601
+ regions: await extractRegions(page, config)
602
+ });
603
+ var saveSnapshot = async (snapshot, path) => {
604
+ await writeFile(path, JSON.stringify(snapshot, null, 2));
605
+ };
606
+ var loadSnapshot = async (path) => {
607
+ const raw = await readFile(path, "utf8");
608
+ return CompareSnapshot.parse(JSON.parse(raw));
609
+ };
610
+
611
+ // src/axes/compare.ts
612
+ var skip2 = (message) => ({
613
+ axis: "compare",
614
+ pass: true,
615
+ findings: [{ message, severity: "minor" }]
616
+ });
617
+ var compareAxis = {
618
+ name: "compare",
619
+ run: async (context) => {
620
+ const { comparison, compareConfig, page } = context;
621
+ if (comparison === void 0) {
622
+ return skip2("no comparison snapshot provided; old-vs-new not assessed");
623
+ }
624
+ if (page === void 0) {
625
+ return skip2("compare needs a live page to extract the new snapshot");
626
+ }
627
+ const newSnapshot = await captureSnapshot(page, comparison.route, compareConfig);
628
+ const findings = diffSnapshots(comparison, newSnapshot, compareConfig);
629
+ return { axis: "compare", pass: comparePass(findings), findings };
630
+ }
631
+ };
632
+
336
633
  // src/axes/runtime-health.ts
337
634
  var ERROR_MARKERS = [
338
635
  "something went wrong",
@@ -471,6 +768,11 @@ var altBrandFinding = (screenshot, altScreenshot, brand) => {
471
768
  }
472
769
  return null;
473
770
  };
771
+ var interactiveContrastFindings = (brand) => checkInteractiveContrast(brand).map((warning) => ({
772
+ message: `brand '${brand.id}' ${warning.message}`,
773
+ severity: "moderate",
774
+ detail: `${warning.foreground} on ${warning.background} (${warning.palette})`
775
+ }));
474
776
  var overflowFinding = async (page) => {
475
777
  const overflows = await page.evaluate(
476
778
  () => document.documentElement.scrollWidth > document.documentElement.clientWidth
@@ -497,6 +799,8 @@ var visualBrandAxis = {
497
799
  DEFAULT_ALT_BRAND
498
800
  );
499
801
  if (finding !== null) findings.push(finding);
802
+ const altBrand = brands.find((brand) => brand.id === DEFAULT_ALT_BRAND);
803
+ if (altBrand !== void 0) findings.push(...interactiveContrastFindings(altBrand));
500
804
  }
501
805
  if (page !== void 0) {
502
806
  const finding = await overflowFinding(page);
@@ -512,7 +816,8 @@ var ALL_AXES = [
512
816
  runtimeHealthAxis,
513
817
  accessibilityAxis,
514
818
  visualBrandAxis,
515
- briefConformanceAxis
819
+ briefConformanceAxis,
820
+ compareAxis
516
821
  ];
517
822
 
518
823
  // src/aggregate.ts
@@ -556,6 +861,8 @@ var validate = async (options) => {
556
861
  browser,
557
862
  brief: options.brief,
558
863
  baseline: options.baseline,
864
+ comparison: options.comparison,
865
+ compareConfig: options.compareConfig,
559
866
  captureUnderBrand: async (brand) => {
560
867
  const brandContext = await browser.newContext({
561
868
  viewport: { width: viewport.width, height: viewport.height }
@@ -581,6 +888,93 @@ var validate = async (options) => {
581
888
  }
582
889
  };
583
890
 
584
- export { ALL_AXES, DEFAULT_VIEWPORTS, DESKTOP_VIEWPORT, MOBILE_VIEWPORT, SEVERITIES, accessibilityAxis, aggregatePass, briefConformanceAxis, capture, capturePage, prepareForScreenshot, runAxes, runtimeHealthAxis, serveStatic, validate, visualBrandAxis };
891
+ // src/compare/dedup.ts
892
+ var groupKey = (finding) => `${finding.kind}::${finding.valueSignature}`;
893
+ var dedupeSharedChrome = (perRoute) => {
894
+ const routesByGroup = /* @__PURE__ */ new Map();
895
+ for (const { route, findings } of perRoute) {
896
+ for (const finding of findings) {
897
+ const key = groupKey(finding);
898
+ const routes = routesByGroup.get(key) ?? /* @__PURE__ */ new Set();
899
+ routes.add(route);
900
+ routesByGroup.set(key, routes);
901
+ }
902
+ }
903
+ const sharedGroups = new Set(
904
+ [...routesByGroup].filter(([, routes]) => routes.size >= 2).map(([key]) => key)
905
+ );
906
+ const sharedChrome = [];
907
+ const seenShared = /* @__PURE__ */ new Set();
908
+ const trimmedPerRoute = perRoute.map(({ route, findings }) => ({
909
+ route,
910
+ findings: findings.filter((finding) => !sharedGroups.has(groupKey(finding)))
911
+ }));
912
+ for (const { findings } of perRoute) {
913
+ for (const finding of findings) {
914
+ const key = groupKey(finding);
915
+ if (!sharedGroups.has(key) || seenShared.has(key)) continue;
916
+ seenShared.add(key);
917
+ const routes = [...routesByGroup.get(key) ?? []].sort();
918
+ sharedChrome.push({
919
+ ...finding,
920
+ message: `${finding.message} (shared across ${routes.length} routes: ${routes.join(", ")})`
921
+ });
922
+ }
923
+ }
924
+ return { sharedChrome, perRoute: trimmedPerRoute };
925
+ };
926
+ var DEFAULT_TIMEOUT_MS2 = 3e4;
927
+ var joinUrl = (base, route) => `${base.replace(/\/$/, "")}/${route.replace(/^\//, "")}`;
928
+ var routeSnapshotFile = (route) => `${route.replace(/^\//, "").replace(/\/+$/, "").replace(/\//g, "_") || "index"}.json`;
929
+ var compareRoutes = async (options) => {
930
+ if (options.oldBaseUrl === void 0 === (options.oldSnapshotDir === void 0)) {
931
+ throw new Error("compareRoutes: provide exactly one of oldBaseUrl or oldSnapshotDir");
932
+ }
933
+ const viewport = options.viewport ?? DESKTOP_VIEWPORT;
934
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
935
+ const browser = options.browser ?? await chromium.launch();
936
+ const ownsBrowser = options.browser === void 0;
937
+ const { oldBaseUrl, oldSnapshotDir } = options;
938
+ const snapshotUrl = async (url, route) => {
939
+ const context = await browser.newContext({
940
+ viewport: { width: viewport.width, height: viewport.height }
941
+ });
942
+ const page = await context.newPage();
943
+ try {
944
+ await page.goto(url, { waitUntil: "networkidle", timeout: timeoutMs });
945
+ await prepareForScreenshot(page);
946
+ return await captureSnapshot(page, route, options.config);
947
+ } finally {
948
+ await context.close();
949
+ }
950
+ };
951
+ const oldSnapshotFor = (route) => {
952
+ if (oldBaseUrl !== void 0) return snapshotUrl(joinUrl(oldBaseUrl, route), route);
953
+ if (oldSnapshotDir !== void 0) {
954
+ return loadSnapshot(join(oldSnapshotDir, routeSnapshotFile(route)));
955
+ }
956
+ throw new Error("compareRoutes: provide exactly one of oldBaseUrl or oldSnapshotDir");
957
+ };
958
+ try {
959
+ const perRoute = [];
960
+ for (const route of options.routes) {
961
+ const oldSnapshot = await oldSnapshotFor(route);
962
+ const newSnapshot = await snapshotUrl(joinUrl(options.newBaseUrl, route), route);
963
+ perRoute.push({ route, findings: diffSnapshots(oldSnapshot, newSnapshot, options.config) });
964
+ }
965
+ const { sharedChrome, perRoute: trimmed } = dedupeSharedChrome(perRoute);
966
+ const routes = trimmed.map(({ route, findings }) => ({
967
+ route,
968
+ findings,
969
+ pass: comparePass(findings)
970
+ }));
971
+ const pass = comparePass(sharedChrome) && routes.every((route) => route.pass);
972
+ return { routes, sharedChrome, pass };
973
+ } finally {
974
+ if (ownsBrowser) await browser.close();
975
+ }
976
+ };
977
+
978
+ export { ALL_AXES, CompareConfig, CompareSnapshot, DEFAULT_VIEWPORTS, DESKTOP_VIEWPORT, ExpectedAbsentRule, MOBILE_VIEWPORT, REGION_STATES, Region, SEVERITIES, accessibilityAxis, aggregatePass, briefConformanceAxis, capture, capturePage, captureSnapshot, compareAxis, comparePass, compareRoutes, dedupeSharedChrome, diffSnapshots, extractRegions, loadSnapshot, prepareForScreenshot, routeSnapshotFile, runAxes, runtimeHealthAxis, saveSnapshot, serveStatic, validate, visualBrandAxis };
585
979
  //# sourceMappingURL=index.js.map
586
980
  //# sourceMappingURL=index.js.map