Repository navigation
Expand file tree
/
Copy pathengine.ts
More file actions
1711 lines (1608 loc) · 66.5 KB
/
Copy pathengine.ts
File metadata and controls
1711 lines (1608 loc) · 66.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// The measured visual checks engine (docs/runtime/VISUAL.md sections 2.3, 7, 8, 9, 11): settle gates, passes in
// idle slices with budgets on the injected Clock, persistence re-checks, incremental re-checks of dirty subtrees,
// the interaction hooks, reports and the fix gate.
//
// Invariants:
// - Reads only, except fix.ts behind the fix gate (guard or heal mode, visual.fix, sampled in, visible tab). In
// observe mode nothing on the page changes: no attributes, styles, inserted elements, scrolling or focus.
// - Measurements (computed styles, layout, hit tests) never run inside the app's event handlers or in plain timers:
// passes, re-checks, fix checks, the periodic read, the interaction checks and page-blank run in idle callbacks,
// timed on the Clock and counted in the summary's cost and the session budget (`idleWork`, `run`). Event handlers
// record the event; while a scroll lock is held, a scroll attempt also reads the scroll position.
// - Time comes from host.clock and idle callbacks from host.global.requestIdleCallback (AGENTS.md rule 5). Event
// timestamps the browser hands over (font loadingdone, layout-shift startTime) are compared only with each other.
// - Never throws into the page: every listener and timer body runs in try/catch.
// - Findings reach the runtime only through host.report / host.note / host.audit: never as RtEvents, facts or
// situations, and they never feed a decision (AGENTS.md rule 2 exception).
import type { CheckFinding, CheckKind, Clock, VisualFixKind, VisualOptions, VisualSummary } from "../types.js";
import type { VisualController, VisualHost } from "./host.js";
import type { Ctx, Draft } from "./draft.js";
import { DIALOG_SEL, fivePoints, INTERACTIVE_SEL, Reader, rootInfo, safeMatches, selectorOf, type Win } from "./measure.js";
import { fold, toFinding } from "./report.js";
import { CONTEXT_CHANGED, FIX_KINDS, Fixer } from "./fix.js";
import { INVISIBLE_RATIO, parseColor } from "./math.js";
import * as A from "./checks/assets.js";
import * as T from "./checks/text.js";
import * as L from "./checks/layout.js";
import * as I from "./checks/interact.js";
import * as S from "./checks/stall.js";
import * as AD from "./checks/ads.js";
import * as W from "./checks/warped.js";
export const KINDS: CheckKind[] = [
"image-broken",
"image-css-broken",
"media-failed",
"stylesheet-failed",
"font-failed",
"icon-font-failed",
"csp-blocked",
"text-invisible",
"text-template-leak",
"text-placeholder",
"text-encoding",
"css-var-undefined",
"image-distorted",
"page-overflow-x",
"viewport-meta-missing",
"layout-shift",
"page-blank",
"click-blocked",
"pointer-events-leak",
"scroll-lock-stuck",
"control-unreachable",
"focus-obscured",
"dialog-covered",
"request-stalled",
"ad-heavy",
"text-warped",
];
/** The near-free kinds: browser-reported facts and interaction hooks. Low-end and sampled-out sessions run only these. */
export const LIGHT = new Set<CheckKind>([
"image-broken",
"image-css-broken",
"media-failed",
"stylesheet-failed",
"font-failed",
"icon-font-failed",
"csp-blocked",
"viewport-meta-missing",
"layout-shift",
"click-blocked",
"pointer-events-leak",
"scroll-lock-stuck",
"control-unreachable",
"focus-obscured",
"dialog-covered",
"request-stalled",
]);
const COLOUR = new Set<CheckKind>(["text-invisible"]);
/**
* Kinds judged from events the whole session shares (CSP violations, layout-shift entries): one report per session,
* not one per route, so an SPA navigation does not report the first page's events again on the next route.
*/
const SESSION_WIDE = new Set<CheckKind>(["csp-blocked", "layout-shift"]);
/** Resource timing entries the asset checks read (images, CSS-initiated requests, stylesheets). */
const RES_TYPES = new Set(["img", "image", "input", "css", "link"]);
const MO_OPTS: MutationObserverInit = { childList: true, subtree: true, characterData: true, attributes: true, attributeFilter: ["class", "style", "hidden", "src", "srcset", "width", "height", "open", "data-genclass-fix"] };
/** Mutation records per second above which the observer rests for 5 s (an animation library writing styles every frame). */
const MO_RATE = 3000;
let engines = 0;
const TEXT = new Set<CheckKind>(["text-invisible", "text-template-leak", "text-placeholder", "text-encoding", "page-overflow-x", "text-warped"]);
const LAYOUT = new Set<CheckKind>(["page-overflow-x", "viewport-meta-missing", "control-unreachable", "focus-obscured", "dialog-covered", "click-blocked", "ad-heavy"]);
export interface Cfg {
checks: Record<CheckKind, boolean>;
fix: Set<VisualFixKind>;
/** visual.ignore as given (hosts for text-placeholder). */
ignore: string[];
/** The entries that are valid selectors. */
ignoreSel: string[];
budgetMs: number;
passBudgetMs: number;
maxElements: number;
lowEnd: "light" | "full" | "off";
sample: number;
maxConsoleLines: number;
/** request-stalled: pending this long (visual.checks.stallMs, default 15 s, clamped to 1 s..10 min). */
stallMs: number;
}
const num = (v: unknown, d: number): number => (typeof v === "number" && Number.isFinite(v) ? v : d);
const clamp = (v: number, lo: number, hi: number): number => Math.min(hi, Math.max(lo, v));
/**
* InitOptions.visual (object form) with defaults and clamps (VISUAL.md 7.1). Runtime fixes need `on: true`: "local"
* (the default, and whatever ?genclass-visual=on turns on) never fixes.
*/
export function resolveCfg(o: VisualOptions, doc: Document | null): Cfg {
const checks = {} as Record<CheckKind, boolean>;
for (const k of KINDS) checks[k] = o.checks?.[k] !== false;
const asked = o.on !== true ? [] : o.fix === true ? FIX_KINDS : Array.isArray(o.fix) ? o.fix.filter((k) => FIX_KINDS.includes(k)) : [];
const fix = new Set<VisualFixKind>(asked);
const ignore = (Array.isArray(o.ignore) ? o.ignore : []).filter((s): s is string => typeof s === "string" && !!s.trim()).slice(0, 50);
const ignoreSel = ignore.filter((s) => {
try {
doc?.querySelector(s);
return !!doc;
} catch {
return false;
}
});
return {
checks,
fix,
ignore,
ignoreSel,
budgetMs: clamp(num(o.budgetMs, 8), 2, 16),
passBudgetMs: clamp(num(o.passBudgetMs, 100), 10, 2000),
maxElements: Math.floor(clamp(num(o.maxElements, 2000), 50, 20000)),
lowEnd: o.lowEnd === "full" || o.lowEnd === "off" ? o.lowEnd : "light",
sample: clamp(num(o.sample, 1), 0, 1),
maxConsoleLines: Math.floor(clamp(num(o.maxConsoleLines, 10), 0, 100)),
stallMs: clamp(num(o.checks?.stallMs, S.STALL_MS), 1000, 600_000),
};
}
/** FNV-1a: session sampling is a hash of the session id, never Math.random. */
export function hash32(s: string): number {
let h = 0x811c9dc5;
for (let i = 0; i < s.length; i++) {
h ^= s.charCodeAt(i);
h = Math.imul(h, 0x01000193) >>> 0;
}
return h >>> 0;
}
type Abstain = { all?: string; colour?: string; text?: string; layout?: string };
type Listen = EventTarget & { addEventListener(t: string, fn: (e: Event) => void, o?: AddEventListenerOptions | boolean): void };
export class Visual implements VisualController {
private readonly win: Win;
private readonly doc: Document;
private readonly clock: Clock;
readonly cfg: Cfg;
private tier: "full" | "light" = "full";
private dead = false;
private readonly stats: Omit<VisualSummary, "checks" | "checksByRoute" | "fixes"> = { passes: 0, elements: 0, ms: 0, maxSliceMs: 0, partial: 0, abstained: 0, unsupported: [], tier: "full" };
private readonly counts: Partial<Record<CheckKind, number>> = {};
private readonly byRoute: Record<string, Partial<Record<CheckKind, number>>> = {};
private readonly reported = new Map<string, CheckFinding>();
private ids = 0;
private readonly fixer: Fixer;
private readonly env: A.AssetEnv;
/** Resource timing entries by URL (bounded, least recently added dropped first): successful ones and failed ones. */
private readonly okRes = new Map<string, PerformanceResourceTiming>();
private readonly failedRes = new Map<string, PerformanceResourceTiming>();
private readonly failedCss: PerformanceResourceTiming[] = [];
private readonly shifts: L.ShiftEntry[] = [];
private readonly fontSwaps: number[] = [];
/** Scroll event times (the performance timeline, as layout-shift entries), the last 200. */
private readonly scrolls: number[] = [];
private readonly rest = new WeakMap<Element, number>();
private offs: (() => void)[] = [];
private timers = new Set<unknown>();
private chain: Promise<unknown> = Promise.resolve();
private mo: MutationObserver | null = null;
private dirty = new Set<Element>();
private fullWanted = false;
private dirtyTimer: unknown = null;
private lastMut: number;
private muts = 0;
private settledAt: number | null = null;
private lastFull = -Infinity;
private budget: { start: number; spent: number };
private slow = 1;
private maxEl: number;
private route: string;
private lastClick: { overlay: Element; at: number; muts: number; href: string; active: Element | null } | null = null;
private rootClicks: number[] = [];
private dragging = false;
private stateAt = -Infinity;
private peSince: number | null = null;
private lockSince: number | null = null;
private attempts = 0;
private attemptPending = false;
private touch: { x: number; y: number } | null = null;
/** A periodic read saw html and body without a scroll lock (so a lock seen later appeared after the page settled). */
private lockSeenFree = false;
/** A dialog, menu or drawer was seen open in this session. */
private overlayEver = false;
/** visibilitychange events to hidden (page-blank requires a tab visible for its whole window). */
private hides = 0;
private mutWin = { start: 0, n: 0 };
private moResting = false;
private reverifyTimer: unknown = null;
private dialogSeen = new WeakSet<Element>();
private dialogTries = new WeakMap<Element, number>();
private dialogTimer: unknown = null;
private scrollTimer: unknown = null;
private cssVarSig = "";
private warned = new Set<string>();
/** request-stalled: when each control last became busy; requests already judged; whether controls are watched. */
private busyAt = new WeakMap<Element, number>();
private stalled = new Set<string>();
private busySince: number | null = null;
constructor(
private readonly host: VisualHost,
opts: VisualOptions,
early: Event[] = [],
auto = true,
) {
this.win = host.global as unknown as Win;
this.doc = this.win.document;
this.clock = host.clock;
this.cfg = resolveCfg(opts, this.doc);
this.maxEl = this.cfg.maxElements;
this.lastMut = this.clock.now();
this.budget = { start: this.clock.now(), spent: 0 };
this.route = this.safeRoute();
const PRT = (this.win as unknown as { PerformanceResourceTiming?: { prototype: object } }).PerformanceResourceTiming;
this.env = {
entry: (u) => this.entry(u),
failedCss: () => this.failedCss,
statusSupported: !!PRT && "responseStatus" in PRT.prototype,
linkErrors: new WeakSet(),
csp: [],
fontsReadyAt: null,
};
this.fixer = new Fixer({
win: this.win,
clock: this.clock,
audit: (f) => this.host.audit(f),
note: (m, f, imp) => this.host.note(m, f, imp),
warn: (m) => this.warn(m),
quietly: (fn) => this.quietly(fn),
defer: (fn, ms) => void this.later(() => void this.idleWork(fn), ms),
prefix: `${(hash32(`${host.seed}/${++engines}`) % 1679616).toString(36)}-`,
});
for (const e of early) this.onCsp(e as SecurityPolicyViolationEvent);
if (!this.env.statusSupported) this.stats.unsupported.push("image-css-broken");
const nav: NonNullable<Win["navigator"]> = this.win.navigator ?? {};
const lowEndDevice = (nav.deviceMemory ?? 8) <= 2 || (nav.hardwareConcurrency ?? 8) <= 2 || !!nav.connection?.saveData;
if (lowEndDevice && this.cfg.lowEnd === "off") {
this.dead = true;
return;
}
if (lowEndDevice && this.cfg.lowEnd === "light") this.tier = "light";
if (this.cfg.sample < 1 && hash32(host.seed) / 4294967296 >= this.cfg.sample) this.tier = "light";
this.stats.tier = this.tier;
if (!this.hasLayout()) {
// jsdom, happy-dom, hidden iframes: zero findings, nothing installed
this.dead = true;
return;
}
try {
this.install();
} catch {
/* a missing API: the checks that need it stay quiet */
}
if (this.cfg.checks["request-stalled"] && this.host.pending) this.watchStalls();
if (auto) void this.boot().catch(() => undefined);
}
// ------------------------------------------------------------------------------------------- controller
now(): Promise<CheckFinding[]> {
if (this.dead) return Promise.resolve([]);
return this.enqueue(() => this.pass(null, true));
}
/** checkPage: wait for fonts and a settled page, then one pass with its re-checks. */
async once(): Promise<CheckFinding[]> {
if (this.dead) return [];
await this.fontsReady();
await this.settle();
this.settledAt = this.clock.now();
return this.now();
}
private async fontsReady(): Promise<void> {
const fonts = (this.doc as Document & { fonts?: { ready?: Promise<unknown> } }).fonts;
await Promise.race([Promise.resolve(fonts?.ready).then(() => undefined, () => undefined), this.sleep(3000)]);
this.env.fontsReadyAt ??= this.clock.now();
}
summary(): { visual: VisualSummary } | null {
if (!this.stats.passes && !this.ids) return null;
const byRoute: Record<string, Partial<Record<CheckKind, number>>> = {};
for (const [r, c] of Object.entries(this.byRoute)) byRoute[r] = { ...c };
return {
visual: {
checks: { ...this.counts },
checksByRoute: byRoute,
fixes: { applied: this.fixer.applied, undone: this.fixer.undone },
...this.stats,
unsupported: [...this.stats.unsupported],
maxSliceMs: Math.round(this.stats.maxSliceMs * 10) / 10,
ms: Math.round(this.stats.ms * 10) / 10,
},
};
}
stop(): void {
if (this.dead) return;
try {
this.fixer.undoAll("the runtime stopped");
} catch {
/* ignore */
}
this.dead = true;
for (const off of this.offs.splice(0)) {
try {
off();
} catch {
/* ignore */
}
}
for (const t of this.timers) this.clock.clearTimeout(t);
this.timers.clear();
this.mo?.disconnect();
this.mo = null;
}
// ----------------------------------------------------------------------------------------------- setup
private hasLayout(): boolean {
try {
return this.doc.documentElement.getBoundingClientRect().width > 0 && this.win.innerWidth > 0;
} catch {
return false;
}
}
private safeRoute(): string {
try {
return this.host.route();
} catch {
return "/";
}
}
private warn(m: string): void {
if (this.warned.has(m)) return;
this.warned.add(m);
(this.win as unknown as { console?: Console }).console?.warn?.(`[GenClass] ${m}`);
}
private on(t: EventTarget | null | undefined, type: string, fn: (e: Event) => void, opts: AddEventListenerOptions): void {
if (!t || typeof (t as Listen).addEventListener !== "function") return;
const safe = (e: Event) => {
if (this.dead) return;
try {
fn(e);
} catch {
/* checks never break the page */
}
};
(t as Listen).addEventListener(type, safe, opts);
this.offs.push(() => t.removeEventListener(type, safe, opts));
}
private install(): void {
const doc = this.doc;
const win = this.win as unknown as EventTarget;
const cap = { capture: true, passive: true };
const pas = { passive: true };
this.on(doc, "error", (e) => this.onError(e), cap);
this.on(doc, "load", (e) => this.onLoadEvent(e), cap);
this.on(doc, "securitypolicyviolation", (e) => this.onCsp(e as SecurityPolicyViolationEvent), cap);
this.on(doc, "click", (e) => this.onClick(e as MouseEvent), cap);
this.on(doc, "pointerover", (e) => this.onState(e, "hover"), cap);
this.on(doc, "focusin", (e) => {
this.onState(e, "focus");
this.onFocus(e);
}, cap);
this.on(doc, "pointerdown", () => (this.dragging = true), cap);
this.on(doc, "pointerup", () => (this.dragging = false), cap);
this.on(doc, "pointercancel", () => (this.dragging = false), cap);
this.on(doc, "keydown", (e) => this.onKey(e as KeyboardEvent), cap);
this.on(win, "wheel", (e) => this.onAttempt(e), cap);
this.on(win, "touchstart", (e) => {
const t = (e as TouchEvent).touches?.[0];
this.touch = t ? { x: t.clientX, y: t.clientY } : null;
}, cap);
this.on(win, "touchmove", (e) => this.onAttempt(e), cap);
this.on(doc, "visibilitychange", () => {
if (doc.visibilityState === "hidden") this.hides++;
}, pas);
try {
// a colour fix is computed for one colour scheme: re-measure when the visitor's scheme changes (no DOM mutation)
this.on(this.win.matchMedia?.("(prefers-color-scheme: dark)"), "change", () => this.scheduleReverify(), pas);
} catch {
/* no matchMedia */
}
this.on(win, "scroll", (e) => {
if (this.scrolls.length >= 200) this.scrolls.shift();
this.scrolls.push(e.timeStamp);
this.onScroll();
}, pas);
this.on(win, "hashchange", () => this.onAnchor(), pas);
this.on(win, "popstate", () => this.checkRoute(), pas);
this.on(win, "resize", () => this.onResize(), pas);
this.on(win, "pageshow", (e) => {
if ((e as PageTransitionEvent).persisted) this.requestFull();
}, pas);
const fonts = (doc as Document & { fonts?: EventTarget }).fonts;
this.on(fonts, "loadingdone", (e) => {
if (this.fontSwaps.length < 200) this.fontSwaps.push(e.timeStamp);
}, pas);
const PO = this.win.PerformanceObserver;
if (typeof PO === "function") {
const types = (PO as unknown as { supportedEntryTypes?: string[] }).supportedEntryTypes ?? [];
if (types.includes("layout-shift")) {
try {
const po = new PO((list) => {
for (const e of list.getEntries() as (PerformanceEntry & { value: number; hadRecentInput: boolean; sources?: L.ShiftEntry["sources"] })[]) {
if (e.hadRecentInput) continue;
this.shifts.push({ t: e.startTime, value: e.value, sources: [...(e.sources ?? [])].slice(0, 5) });
// full passes prune judged windows (pruneShifts); this only bounds a page that shifts without pause
if (this.shifts.length > 500) this.shifts.shift();
}
});
po.observe({ type: "layout-shift", buffered: true });
this.offs.push(() => po.disconnect());
} catch {
/* unsupported */
}
} else this.stats.unsupported.push("layout-shift");
if (types.includes("resource")) {
try {
const po = new PO((list) => {
for (const e of list.getEntries() as PerformanceResourceTiming[]) this.addResource(e);
});
po.observe({ type: "resource", buffered: true });
this.offs.push(() => po.disconnect());
} catch {
/* unsupported */
}
}
} else this.stats.unsupported.push("layout-shift");
const MO = this.win.MutationObserver;
if (typeof MO === "function") {
this.mo = new MO((recs) => {
try {
this.onMutations(recs);
} catch {
/* ignore */
}
});
this.mo.observe(doc.documentElement, MO_OPTS);
}
}
/**
* Keep the entries the asset checks read: images, CSS-initiated requests and stylesheets (never fetch, XHR or
* beacons), at most 500 successful and 200 failed ones, the oldest dropped first. entry() falls back to the browser's
* own resource timeline for the rest.
*/
private addResource(e: PerformanceResourceTiming): void {
if (!RES_TYPES.has(e.initiatorType)) return;
const st = (e as { responseStatus?: number }).responseStatus;
const failed = typeof st === "number" && st >= 400;
const m = failed ? this.failedRes : this.okRes;
m.delete(e.name);
m.set(e.name, e);
if (m.size > (failed ? 200 : 500)) m.delete(m.keys().next().value as string);
if (failed && e.initiatorType === "css" && this.failedCss.length < 50) {
try {
if (new URL(e.name).origin === new URL(this.win.location?.href ?? "").origin) this.failedCss.push(e);
} catch {
/* ignore */
}
}
}
private entry(url: string): PerformanceResourceTiming | undefined {
const a = this.okRes.get(url);
const b = this.failedRes.get(url);
const e = a && b ? (a.startTime > b.startTime ? a : b) : a ?? b;
if (e) return e;
try {
const list = this.win.performance?.getEntriesByName(url, "resource") as PerformanceResourceTiming[] | undefined;
return list && list.length ? list[list.length - 1] : undefined;
} catch {
return undefined;
}
}
private async boot(): Promise<void> {
await this.fontsReady();
if (this.dead) return;
await this.settle();
if (this.dead) return;
this.settledAt = this.clock.now();
await this.enqueue(() => this.pass(null));
this.tick();
this.scheduleBlank();
this.unreachable(false);
}
// ------------------------------------------------------------------------------------- timing helpers
private later(fn: () => void, ms: number): unknown {
const h = this.clock.setTimeout(() => {
this.timers.delete(h);
if (this.dead) return;
try {
fn();
} catch {
/* ignore */
}
}, ms);
this.timers.add(h);
return h;
}
private cancel(h: unknown): void {
if (h === null || h === undefined) return;
this.clock.clearTimeout(h);
this.timers.delete(h);
}
private sleep(ms: number): Promise<void> {
return new Promise((res) => {
const h = this.clock.setTimeout(() => {
this.timers.delete(h);
res();
}, ms);
this.timers.add(h);
});
}
private idle(): Promise<{ timeRemaining(): number; didTimeout?: boolean } | null> {
return new Promise((res) => {
const ric = this.win.requestIdleCallback;
if (typeof ric === "function") {
try {
ric.call(this.win, (d) => res(d), { timeout: 1000 });
return;
} catch {
/* fall through */
}
}
const h = this.clock.setTimeout(() => {
this.timers.delete(h);
res(null);
}, 0);
this.timers.add(h);
});
}
/**
* Run `fn` in an idle callback, timed on the Clock and counted like a pass slice (summary cost, longest slice, the
* session budget): interaction and periodic reads never run inside the app's event handlers (VISUAL.md 8).
*/
private idleWork(fn: () => void): Promise<void> {
return this.idle().then(() => {
if (this.dead) return;
const t0 = this.clock.now();
try {
fn();
} catch {
/* checks never break the page */
}
this.account(this.clock.now() - t0);
});
}
private visibleNow(): boolean {
return this.doc.visibilityState !== "hidden" && !(this.doc as Document & { prerendering?: boolean }).prerendering;
}
private whenVisible(): Promise<void> {
if (this.visibleNow()) return Promise.resolve();
return new Promise((res) => {
const check = () => {
if (!this.dead && !this.visibleNow()) return;
this.doc.removeEventListener("visibilitychange", check);
this.doc.removeEventListener("prerenderingchange", check);
res();
};
this.doc.addEventListener("visibilitychange", check);
this.doc.addEventListener("prerenderingchange", check);
this.offs.push(() => {
this.doc.removeEventListener("visibilitychange", check);
this.doc.removeEventListener("prerenderingchange", check);
});
});
}
/**
* VISUAL.md 2.3, 8 step 3: 500 ms with nothing in flight (host.inflight) and no counted mutation, together; one 10 s
* cap for both from here, after the fonts wait. Runs once, before the first pass, so `slow` is 1 unless a manual
* pass (rt.checkNow) hit a slow read before it ended.
*/
private async settle(): Promise<void> {
await this.whenVisible();
const start = this.clock.now();
let busy = start;
for (;;) {
if (this.dead) return;
const t = this.clock.now();
if (this.host.inflight() > 0) busy = t;
if ((t - busy >= 500 * this.slow && t - this.lastMut >= 500 * this.slow) || t - start >= 10_000) return;
await this.sleep(100);
}
}
private async quietNet(cap: number): Promise<void> {
const start = this.clock.now();
while (!this.dead && this.host.inflight() > 0 && this.clock.now() - start < cap) await this.sleep(250);
}
private enqueue<T>(fn: () => Promise<T>): Promise<T> {
const p = this.chain.then(fn, fn);
this.chain = p.catch(() => undefined);
return p;
}
private overSession(): boolean {
const now = this.clock.now();
if (now - this.budget.start >= 600_000) this.budget = { start: now, spent: 0 };
return this.budget.spent >= 1000;
}
/** Run a generator in idle slices of budgetMs until done or the pass budget is spent. */
private async run(gen: Generator<void>, b: { spent: number; partial: boolean }): Promise<boolean> {
for (;;) {
if (this.dead) return false;
const deadline = await this.idle();
if (this.dead) return false;
if (!this.visibleNow()) await this.whenVisible();
const t0 = this.clock.now();
let done = false;
for (;;) {
const u0 = this.clock.now();
let r: IteratorResult<void>;
try {
r = gen.next();
} catch {
r = { done: true, value: undefined };
}
const u = this.clock.now() - u0;
if (u > 16) {
// one read forced a long layout: end the pass, double later persistence waits (2x at most), measure fewer
// elements
this.slow = Math.min(8, this.slow * 2);
this.maxEl = Math.max(50, Math.floor(this.maxEl / 2));
this.account(this.clock.now() - t0);
b.partial = true;
return false;
}
if (r.done) {
done = true;
break;
}
const elapsed = this.clock.now() - t0;
// an idle callback that fired on its 1 s timeout (a page that is never idle, for example one that animates
// on every frame) has no idle time left: it still gets one slice of budgetMs, or a pass would advance by one
// step per second (measured on a public site by bench/visual)
if (elapsed >= this.cfg.budgetMs || (deadline && !deadline.didTimeout && deadline.timeRemaining() <= 0)) break;
}
const slice = this.clock.now() - t0;
this.account(slice);
b.spent += slice;
if (done) return true;
if (b.spent >= this.cfg.passBudgetMs) {
b.partial = true;
return false;
}
}
}
private account(ms: number): void {
this.stats.ms += ms;
if (ms > this.stats.maxSliceMs) this.stats.maxSliceMs = ms;
this.budget.spent += ms;
}
// --------------------------------------------------------------------------------------------- context
private mm(q: string): boolean {
try {
return !!this.win.matchMedia?.(q).matches;
} catch {
return false;
}
}
/** VISUAL.md 2.2: page conditions under which measurements are not trustworthy. */
private pageAbstain(): Abstain {
const html = this.doc.documentElement;
const o: Abstain = {};
if (this.mm("print")) o.all = "print";
if (this.mm("(forced-colors: active)")) o.colour = "forced-colors";
else if (this.doc.querySelector('meta[name="darkreader"]') || html.hasAttribute("data-darkreader-mode") || html.hasAttribute("data-darkreader-scheme")) o.colour = "dark-reader";
if (html.classList.contains("translated-ltr") || html.classList.contains("translated-rtl")) o.text = "translated";
if ((this.win.visualViewport?.scale ?? 1) > 1.01) o.layout = "pinch-zoom";
return o;
}
private scheme(): "light" | "dark" {
const html = this.doc.documentElement;
const theme = html.getAttribute("data-theme");
if (html.classList.contains("dark") || theme === "dark") return "dark";
if (html.classList.contains("light") || theme === "light") return "light";
return this.mm("(prefers-color-scheme: dark)") ? "dark" : "light";
}
private ctx(r: Reader, ab: Abstain = this.pageAbstain()): Ctx {
return {
r,
win: this.win,
now: this.clock.now(),
scheme: this.scheme(),
describe: (el) => {
try {
return this.host.describe(el);
} catch {
return el.tagName.toLowerCase();
}
},
sel: (el) => selectorOf(el, this.win).selector,
abstain: () => {
this.stats.abstained++;
},
on: (k) =>
this.cfg.checks[k] && (this.tier === "full" || LIGHT.has(k)) && !ab.all && !(ab.colour && COLOUR.has(k)) && !(ab.text && TEXT.has(k)) && !(ab.layout && LAYOUT.has(k)),
max: this.maxEl,
ignore: this.cfg.ignore,
};
}
private reader(): Reader {
return new Reader(this.win, this.cfg.ignoreSel);
}
/** The runtime is on for this page: not destroyed, not paused, enabled, the route not off. */
private live(): boolean {
return !this.dead && this.host.active() && this.host.mode() !== "off";
}
// ------------------------------------------------------------------------------------------------ passes
private async pass(roots: Element[] | null, manual = false): Promise<CheckFinding[]> {
if (!this.live()) return [];
if (!this.visibleNow()) await this.whenVisible();
const ab = this.pageAbstain();
if (ab.all) {
this.stats.abstained++;
return [];
}
if (!manual && roots && this.overSession()) {
this.stats.stopped = true;
return [];
}
const body = this.doc.body;
if (!body) return [];
const full = !roots;
const rts = roots ?? [body];
const r = this.reader();
const ctx = this.ctx(r, ab);
const drafts: Draft[] = [];
const scan = T.newScan();
const env = this.env;
// eslint-disable-next-line @typescript-eslint/no-this-alias
const self = this;
function* steps(): Generator<void> {
yield* A.brokenImages(ctx, env, rts, drafts);
yield* A.failedMedia(ctx, rts, drafts);
if (full) {
yield* A.failedStylesheets(ctx, env, drafts);
yield* A.failedFonts(ctx, env, drafts);
yield* A.failedIconFonts(ctx, env, drafts);
yield;
A.cspBlocked(ctx, env, drafts);
yield;
L.viewportMeta(ctx, drafts);
yield;
L.layoutShifts(ctx, self.shifts, self.fontSwaps, drafts, self.scrolls);
L.pruneShifts(self.shifts);
yield* A.brokenCssImages(ctx, env, drafts);
yield* L.pageOverflow(ctx, drafts);
yield* self.cssVars(ctx, drafts);
yield* AD.adHeavy(ctx, drafts);
}
yield* L.distortedImages(ctx, rts, drafts);
const text = ctx.on("text-template-leak") || ctx.on("text-placeholder") || ctx.on("text-encoding");
const cands = ctx.on("text-invisible") || ctx.on("text-warped");
if (text || cands) {
yield* T.walkText(ctx, rts, scan, 5000, cands);
T.placeholderImages(ctx, rts, scan);
T.patternDrafts(ctx, scan, drafts);
yield* T.measureContrast(ctx, scan.cands, drafts, self.rest);
yield* W.measureWarped(ctx, scan.cands, drafts);
}
yield;
self.dialogs(ctx, drafts);
}
const b = { spent: 0, partial: false };
const done = await this.run(steps(), b);
this.stats.passes++;
this.stats.elements += r.reads;
this.stats.abstained += scan.weak;
if (!done) this.stats.partial++;
if (full) this.lastFull = this.clock.now();
return this.confirm(drafts);
}
/** Persistence (VISUAL.md 2.3): re-measure the drafts that need it, then report the confirmed ones. */
private async confirm(drafts: Draft[]): Promise<CheckFinding[]> {
const out: Draft[] = drafts.filter((d) => !d.recheck);
const pending = drafts.filter((d) => d.recheck);
if (pending.length) {
const wait = Math.max(0, ...pending.map((d) => d.persistMs ?? 0));
if (wait) await this.sleep(wait * Math.min(2, this.slow));
if (pending.some((d) => d.quiet)) await this.quietNet(5000);
if (this.dead || !this.live()) return [];
const r = this.reader();
const asyncs: Promise<Draft | null>[] = [];
function* rechecks(): Generator<void> {
for (const d of pending) {
yield;
const res = d.recheck!(r);
if (res && typeof (res as Promise<Draft | null>).then === "function") asyncs.push(res as Promise<Draft | null>);
else if (res) out.push(res as Draft);
}
}
await this.run(rechecks(), { spent: 0, partial: false });
for (const a of await Promise.all(asyncs.map((p) => p.catch(() => null)))) if (a) out.push(a);
}
return this.publish(out);
}
private publish(drafts: Draft[]): CheckFinding[] {
const out: CheckFinding[] = [];
let printed = 0;
let quiet = 0;
let last: CheckFinding | null = null;
for (const d of fold(drafts)) {
if (this.dead) break;
if (!d.text) continue;
const key = SESSION_WIDE.has(d.kind) ? d.key : `${d.key}|${this.route}`;
const known = this.reported.get(key);
if (known) {
// a colour fix undone because its context changed (the item stopped being active, the scheme changed) may
// apply again when the same element is unreadable again (at most twice per finding and page)
if (d.plan && known.fix && !known.fix.applied && known.fix.reason === CONTEXT_CHANGED) {
this.maybeFix(d, known, key);
if (known.fix?.applied) this.host.note(`[GenClass] Applied a CSS fix for check ${known.id} again: ${known.fix.css}.`, known, true);
}
out.push(known);
continue;
}
const f = this.finding(d);
if (this.reported.size >= 1000) this.reported.delete(this.reported.keys().next().value as string);
this.reported.set(key, f);
this.count(f);
this.maybeFix(d, f, key);
const loud = printed < this.cfg.maxConsoleLines;
if (loud) printed++;
else quiet++;
try {
this.host.report(f, loud);
if (f.fix?.applied) this.host.note(`[GenClass] Applied a CSS fix for check ${f.id}: ${f.fix.css}. Undo: GenClass.runtime.checks().find(c => c.id === "${f.id}").fix.undo()`, f, true);
} catch {
/* reporting never breaks the page */
}
last = f;
out.push(f);
}
if (quiet && last) this.host.note(`[GenClass] ${quiet} more measured check${quiet === 1 ? "" : "s"}: GenClass.runtime.checks() or the devtools Checks tab.`, last, false);
return out;
}
private finding(d: Draft): CheckFinding {
const el = d.el;
const s = el ? selectorOf(el, this.win) : { selector: "page", structural: false };
let target = d.target ?? "page";
if (el) {
try {
target = this.host.describe(el);
} catch {
target = s.selector;
}
}
return toFinding(d, {
id: `c${++this.ids}`,
at: this.clock.now(),
route: this.route,
scheme: this.scheme(),
viewport: { w: this.win.innerWidth, h: this.win.innerHeight },
coarse: this.mm("(pointer: coarse)"),
tier: this.tier,
target,
selector: s.selector,
structural: s.structural,
});
}
private count(f: CheckFinding): void {
this.counts[f.kind] = (this.counts[f.kind] ?? 0) + 1;
const r = this.route;
if (!this.byRoute[r] && Object.keys(this.byRoute).length >= 20) return;
const c = (this.byRoute[r] ??= {});
c[f.kind] = (c[f.kind] ?? 0) + 1;
}
// -------------------------------------------------------------------------------------------------- fixes
/** VISUAL.md 11.1: why a fix may not run now (null: it may). */
private fixGate(kind: VisualFixKind, key: string): string | null {
if (!this.cfg.fix.has(kind)) return "not enabled (visual.fix)";
const m = this.host.mode();
if (m !== "guard" && m !== "heal") return `the mode here is ${m}; fixes run only in guard or heal mode`;
if (!this.host.sampled()) return "this session is sampled out";
if (!this.visibleNow()) return "the tab is hidden";
if (!this.host.active()) return "GenClass is paused";
const ab = this.pageAbstain();
if (ab.all || (kind === "text-invisible" && ab.colour)) return `the page cannot be measured reliably (${ab.all ?? ab.colour})`;
if (!this.fixer.allowed(kind, key)) return "fixes of this kind are off for this session or page";
return null;
}
private maybeFix(d: Draft, f: CheckFinding, key: string): void {
const plan = d.plan;
if (!plan) return;
const i = f.details.findIndex((l) => l.startsWith("Runtime fix:"));
const set = (line: string) => {
if (i >= 0) f.details[i] = line;
else f.details.splice(Math.max(0, f.details.length - 2), 0, line);
};
const why = this.fixGate(plan.kind, key);
if (why) {
if (this.cfg.fix.has(plan.kind)) set(`Runtime fix: not applied (${why}).`);
return;
}
f.fix = this.fixer.apply(plan, f, key, () => this.verifyFix(d, true), plan.type === "color" ? () => this.verifyFix(d, false) : undefined);
set(f.fix.applied ? `Runtime fix: applied (${f.fix.css}). Undo: GenClass.runtime.checks().find(c => c.id === "${f.id}").fix.undo()` : `Runtime fix: not applied (${f.fix.reason}).`);
}
/**
* Re-measure a fix (VISUAL.md 11.2): the threshold must be cleared, else the fix is undone. A colour fix also needs
* the background it was computed for, unchanged; `deep` (the check 50 ms after applying) also searches for a painted
* layer that hit testing skips, which the resolver cannot see.
*/
private verifyFix(d: Draft, deep: boolean): boolean {
const plan = d.plan!;
const r = this.reader();
if (plan.type === "color") {
if (!plan.el.isConnected) return false;
// out of the viewport there is nothing to measure (hit testing finds no points there): the fix stays as it is
// until the element is back in view
const b = r.rect(plan.el);
if (!deep && (b.bottom <= 0 || b.top >= r.win.innerHeight || b.right <= 0 || b.left >= r.win.innerWidth)) return true;
// a re-measure, not a pass: its abstentions are not counted again
const ctx = { ...this.ctx(r), abstain: () => undefined };
// hit testing skips the text while pointer-events: none reaches it (a click block on body): a re-measure then
// finds no points, which is no evidence the background changed, so the fix stays until a measure says so
if (!deep && r.cs(plan.el).pointerEvents === "none") return true;
const read = T.readContrast(ctx, r, plan.el, rootInfo(r));
if (!read || read.v.verdict === "unknown" || read.v.ratio < plan.target || !nearColor(read.v.bg, plan.bg)) return false;
return !deep || !T.hiddenLayer(ctx, r, plan.el, read.input);
}
const s = r.cs(plan.el);
return plan.kind === "pointer-events-leak" ? s.pointerEvents !== "none" : s.overflowY !== "hidden" && s.overflowY !== "clip";
}
/** Re-measure the colour fixes soon (a class or style change, a colour scheme change), debounced. */
private scheduleReverify(): void {
if (this.dead || !this.fixer.colour) return;
this.cancel(this.reverifyTimer);
this.reverifyTimer = this.later(() => {
this.reverifyTimer = null;
void this.idleWork(() => this.fixer.reverify());
}, 300);
}