-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.d.ts
More file actions
1273 lines (1159 loc) · 39.2 KB
/
index.d.ts
File metadata and controls
1273 lines (1159 loc) · 39.2 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
/**
* TypeScript definitions for @vizzly-testing/honeydiff
* High-performance image diffing for Node.js
*/
// ============================================================================
// Core Types
// ============================================================================
export interface BoundingBox {
/** X coordinate of top-left corner */
x: number;
/** Y coordinate of top-left corner */
y: number;
/** Width of the bounding box */
width: number;
/** Height of the bounding box */
height: number;
}
export interface HeightDiff {
/** Height of the first image in pixels */
height1: number;
/** Height of the second image in pixels */
height2: number;
/** Number of extra pixels due to height difference */
extraPixels: number;
}
export interface DiffPixel {
/** X coordinate of the differing pixel */
x: number;
/** Y coordinate of the differing pixel */
y: number;
/** Intensity of the difference (0-255, higher = more different) */
intensity: number;
}
export interface IntensityStats {
/** Maximum difference intensity observed (0-255) */
max: number;
/** Minimum difference intensity observed (0-255) */
min: number;
/** Mean (average) difference intensity */
mean: number;
/** Median difference intensity */
median: number;
/** Standard deviation of difference intensities */
stdDev: number;
}
export interface DiffCluster {
/** Number of pixels in this cluster */
pixelCount: number;
/** Center of mass [x, y] coordinates */
centerOfMass: [number, number];
/** Average intensity of differences in this cluster */
avgIntensity: number;
/** Bounding box containing this cluster */
boundingBox: BoundingBox;
}
export interface DiffResult {
/**
* Whether the images are different based on the comparison threshold
* Note: This respects minClusterSize filtering - small clusters may be filtered as noise
*/
isDifferent: boolean;
/** Percentage of pixels that differ (0.0 - 100.0) */
diffPercentage: number;
/** Total number of pixels compared */
totalPixels: number;
/**
* Number of pixels that differ (raw count, unaffected by minClusterSize filtering)
* Note: This may be > 0 even when isDifferent is false if small clusters were filtered as noise
*/
diffPixels: number;
/** Number of pixels ignored due to anti-aliasing detection */
aaPixelsIgnored: number;
/** Percentage of pixels ignored as anti-aliasing (0.0 - 100.0) */
aaPercentage: number;
/** Bounding box containing all differences (null if identical) */
boundingBox: BoundingBox | null;
/** Height difference information (null if same height) */
heightDiff: HeightDiff | null;
/** List of differing pixels with positions and intensities (null unless includeDiffPixels is enabled) */
diffPixelsList: DiffPixel[] | null;
/** Clustered groups of connected differing pixels (null unless includeClusters is enabled) */
diffClusters: DiffCluster[] | null;
/** Statistical metrics about difference intensities (null unless includeDiffPixels is enabled) */
intensityStats: IntensityStats | null;
/** SSIM (Structural Similarity Index) perceptual score 0.0-1.0 (null unless includeSSIM is enabled) */
perceptualScore: number | null;
/**
* GMSD (Gradient Magnitude Similarity Deviation) score (null unless includeGMSD is enabled)
* Lower values (closer to 0.0) indicate more similar images
* Typical range: 0.0 to ~0.3 for natural images
*/
gmsdScore: number | null;
}
// ============================================================================
// Options
// ============================================================================
/**
* Options for merging nearby clusters
*
* These heuristics are designed to merge fragmented text regions (like individual
* characters in a date string) into logical regions while avoiding merging
* unrelated visual changes.
*
* Inspired by the Stroke Width Transform (SWT) text detection algorithm:
* Epshtein, B., Ofek, E., & Wexler, Y. (2010). "Detecting Text in Natural Scenes
* with Stroke Width Transform." CVPR 2010.
*/
export interface ClusterMergeOptions {
/**
* Maximum horizontal distance to merge clusters in same Y-band (pixels)
*
* Clusters within this horizontal distance and overlapping Y-ranges
* will be merged. Suitable for merging characters in text.
* @default 15
*/
horizontalDistance?: number;
/**
* Maximum vertical tolerance for "same Y-band" (pixels)
*
* Clusters with Y-ranges within this tolerance of each other are
* considered to be on the same line.
* @default 5
*/
yBandTolerance?: number;
/**
* Maximum height ratio between clusters to allow merging
*
* Prevents merging clusters of very different sizes (e.g., a word
* with a large image). Based on SWT heuristic.
* @default 2.0
*/
maxHeightRatio?: number;
/**
* Maximum width ratio between clusters to allow merging
*
* Additional SWT-inspired heuristic to prevent merging dissimilar
* regions.
* @default 3.0
*/
maxWidthRatio?: number;
}
export interface CompareOptions {
/**
* Perceptual color difference threshold using CIEDE2000 (Delta E units)
*
* The CIEDE2000 standard provides intuitive, perceptually uniform thresholds:
* - 0.0 = Exact pixel matching (strictest)
* - 1.0 = Just Noticeable Difference (JND) - barely perceptible to trained observers
* - 2.0 = Recommended default - ignores sub-pixel rendering variance, catches real differences
* - 3.0+ = Permissive - high tolerance for rendering variations
*
* @default 2.0
*/
threshold?: number;
/**
* Enable anti-aliasing detection to ignore AA differences
* @default true
*/
antialiasing?: boolean;
/**
* Maximum number of differences to detect before stopping
* @default undefined (unlimited)
*/
maxDiffs?: number;
/**
* Include list of differing pixels with positions and intensities
* WARNING: This can use significant memory for images with many differences
* @default false
*/
includeDiffPixels?: boolean;
/**
* Include clustered groups of connected differing pixels
* Automatically enables includeDiffPixels if not already enabled
* Clusters are sorted by size (largest first)
* @default false
*/
includeClusters?: boolean;
/**
* Calculate SSIM (Structural Similarity Index) perceptual score
* WARNING: SSIM can be computationally expensive on large images
* @default false
*/
includeSSIM?: boolean;
/**
* Calculate GMSD (Gradient Magnitude Similarity Deviation) score
*
* GMSD is very fast and highly sensitive to edge/structural changes.
* Useful for detecting border thickness changes, font weight shifts,
* and icon updates.
*
* **Note:** GMSD requires images with identical dimensions. For variable-height
* comparisons, `gmsdScore` will be `null`. Use SSIM for variable-height images.
*
* Reference: Xue et al. 2014 - "Gradient Magnitude Similarity Deviation:
* A Highly Efficient Perceptual Image Quality Index"
*
* @default false
*/
includeGMSD?: boolean;
/**
* Minimum cluster size to count as a real difference
*
* Clusters smaller than this threshold are filtered out as noise.
* This helps ignore run-to-run rendering variance (scattered single pixels)
* while still catching real visual changes (grouped pixel differences).
*
* - 1 = Exact matching - any different pixel counts
* - 2 = Default - filters single isolated pixels as noise
* - 3+ = More permissive - only larger clusters detected
*
* When set to a value > 1, clustering is automatically enabled.
* @default 2
*/
minClusterSize?: number;
/**
* Merge nearby clusters into logical regions
*
* When enabled, nearby clusters are merged using horizontal-biased heuristics
* that work well for text regions. This helps consolidate fragmented text
* changes (e.g., "2024-01-01" showing as 59 clusters) into logical regions.
*
* Automatically enables clustering when set.
*
* @default undefined (no merging)
*
* @example
* ```typescript
* // Simple: enable merging with sensible defaults
* { clusterMerge: true }
*
* // Advanced: tune the merging behavior
* { clusterMerge: { horizontalDistance: 20, yBandTolerance: 10 } }
* ```
*/
clusterMerge?: boolean | ClusterMergeOptions;
/**
* Path to save the diff image (highlighted differences)
* @default undefined
*/
diffPath?: string;
/**
* Path to save the mask image (binary diff mask)
* @default undefined
*/
maskPath?: string;
/**
* Path to save the overlay image (side-by-side comparison)
* @default undefined
*/
overlayPath?: string;
/**
* Whether to overwrite existing output files
* @default false
*/
overwrite?: boolean;
/**
* Color to use for highlighting differences in diff/mask output
*
* Accepts either:
* - Hex string: "ff0000", "#ff0000", "ff0000ff" (with alpha)
* - RGBA array: [255, 0, 0] or [255, 0, 0, 255]
*
* @default "ff0000" (red)
*
* @example
* ```typescript
* // Green highlight using hex
* { diffMaskColor: "00ff00" }
*
* // Blue with 50% transparency using RGBA array
* { diffMaskColor: [0, 0, 255, 128] }
*
* // Magenta using hex with #
* { diffMaskColor: "#ff00ff" }
* ```
*/
diffMaskColor?: string | [number, number, number] | [number, number, number, number];
}
// ============================================================================
// Input Types
// ============================================================================
/** Image input can be a file path or a Buffer containing image data */
export type ImageInput = string | Buffer;
// ============================================================================
// API Functions
// ============================================================================
/**
* Compare two images asynchronously (recommended)
*
* @param img1 - First image (file path or Buffer)
* @param img2 - Second image (file path or Buffer)
* @param options - Comparison options
* @returns Promise resolving to detailed diff results
*
* @example
* ```typescript
* const result = await compare('baseline.png', 'current.png', {
* threshold: 2.0, // CIEDE2000 Delta E (default)
* includeSSIM: true
* });
*
* console.log(`Diff: ${result.diffPercentage.toFixed(2)}%`);
* console.log(`SSIM: ${result.perceptualScore}`);
* ```
*/
export function compare(
img1: ImageInput,
img2: ImageInput,
options?: CompareOptions
): Promise<DiffResult>;
/**
* Quick asynchronous comparison (returns only boolean)
*
* @param img1 - First image (file path or Buffer)
* @param img2 - Second image (file path or Buffer)
* @returns Promise resolving to true if different, false if identical
*
* @example
* ```typescript
* if (await quickCompare('baseline.png', 'current.png')) {
* console.log('Visual regression detected!');
* }
* ```
*/
export function quickCompare(img1: ImageInput, img2: ImageInput): Promise<boolean>;
/**
* Compare two images synchronously (blocks event loop)
*
* Use this only when you need blocking behavior.
* For most cases, prefer the async compare() function.
*
* @param img1 - First image (file path or Buffer)
* @param img2 - Second image (file path or Buffer)
* @param options - Comparison options
* @returns Detailed diff results
*
* @example
* ```typescript
* const result = compareSync('baseline.png', 'current.png', {
* threshold: 3.0, // More lenient threshold
* includeClusters: true
* });
*
* if (result.diffClusters) {
* console.log(`Found ${result.diffClusters.length} diff regions`);
* }
* ```
*/
export function compareSync(
img1: ImageInput,
img2: ImageInput,
options?: CompareOptions
): DiffResult;
/**
* Quick synchronous comparison (returns only boolean, blocks event loop)
*
* @param img1 - First image (file path or Buffer)
* @param img2 - Second image (file path or Buffer)
* @returns true if different, false if identical
*
* @example
* ```typescript
* if (quickCompareSync('baseline.png', 'current.png')) {
* console.log('Images differ');
* }
* ```
*/
export function quickCompareSync(img1: ImageInput, img2: ImageInput): boolean;
// ============================================================================
// Dimensions API
// ============================================================================
export interface ImageDimensions {
/** Image width in pixels */
width: number;
/** Image height in pixels */
height: number;
}
export interface ImageMetadata {
/** Image width in pixels */
width: number;
/** Image height in pixels */
height: number;
/** Size of the image data in bytes */
fileSizeBytes: number;
/** Detected image format (e.g., "png", "jpeg", "webp") or null if unknown */
format: string | null;
}
/**
* Get image dimensions asynchronously (recommended)
*
* Fast utility to retrieve image width and height without loading the full image data.
* Useful for pre-flight checks before comparison.
*
* @param img - Image (file path or Buffer)
* @returns Promise resolving to { width, height } in pixels
*
* @example
* ```typescript
* const dims = await getDimensions('screenshot.png');
* console.log(`Image is ${dims.width}x${dims.height} pixels`);
* // Output: Image is 1920x1080 pixels
* ```
*/
export function getDimensions(img: ImageInput): Promise<ImageDimensions>;
/**
* Get image dimensions synchronously (blocks event loop)
*
* Fast utility to retrieve image width and height without loading the full image data.
* Use this only when you need blocking behavior.
*
* @param img - Image (file path or Buffer)
* @returns { width, height } in pixels
*
* @example
* ```typescript
* const dims = getDimensionsSync('screenshot.png');
* console.log(`Image is ${dims.width}x${dims.height} pixels`);
* // Output: Image is 1920x1080 pixels
* ```
*/
export function getDimensionsSync(img: ImageInput): ImageDimensions;
// ============================================================================
// Image Metadata API
// ============================================================================
/**
* Get image metadata asynchronously (recommended)
*
* Retrieves image dimensions, file size, and format detection.
* Useful for storage tracking and billing purposes.
*
* @param img - Image Buffer
* @returns Promise resolving to ImageMetadata
*
* @example
* ```typescript
* const buffer = fs.readFileSync('screenshot.png');
* const metadata = await getImageMetadata(buffer);
* console.log(`Image: ${metadata.width}x${metadata.height}`);
* console.log(`Size: ${metadata.fileSizeBytes} bytes`);
* console.log(`Format: ${metadata.format}`);
* // Output: Image: 1920x1080
* // Size: 245760 bytes
* // Format: png
* ```
*/
export function getImageMetadata(img: Buffer): Promise<ImageMetadata>;
/**
* Get image metadata synchronously (blocks event loop)
*
* Retrieves image dimensions, file size, and format detection.
* Use this only when you need blocking behavior.
*
* @param img - Image Buffer
* @returns ImageMetadata
*
* @example
* ```typescript
* const buffer = fs.readFileSync('screenshot.png');
* const metadata = getImageMetadataSync(buffer);
* console.log(`${metadata.width}x${metadata.height}, ${metadata.fileSizeBytes} bytes`);
* ```
*/
export function getImageMetadataSync(img: Buffer): ImageMetadata;
/**
* Get image metadata from file asynchronously (recommended)
*
* Retrieves image dimensions, file size (from disk), and format detection.
* The file size is read from filesystem metadata for accuracy.
*
* @param path - Path to the image file
* @returns Promise resolving to ImageMetadata
*
* @example
* ```typescript
* const metadata = await getImageMetadataFromFile('screenshot.png');
* console.log(`Image: ${metadata.width}x${metadata.height}`);
* console.log(`Size: ${metadata.fileSizeBytes} bytes`);
* console.log(`Format: ${metadata.format}`);
* ```
*/
export function getImageMetadataFromFile(path: string): Promise<ImageMetadata>;
/**
* Get image metadata from file synchronously (blocks event loop)
*
* Retrieves image dimensions, file size (from disk), and format detection.
* Use this only when you need blocking behavior.
*
* @param path - Path to the image file
* @returns ImageMetadata
*
* @example
* ```typescript
* const metadata = getImageMetadataFromFileSync('screenshot.png');
* console.log(`${metadata.width}x${metadata.height}, ${metadata.fileSizeBytes} bytes`);
* ```
*/
export function getImageMetadataFromFileSync(path: string): ImageMetadata;
// ============================================================================
// WCAG Accessibility API
// ============================================================================
/**
* Options for WCAG color contrast analysis
*/
export interface WcagOptions {
/**
* Edge detection threshold (0-255)
* Differences below this threshold are not considered edges
* @default 60
*/
edgeThreshold?: number;
/**
* Minimum region size (in pixels)
* Regions smaller than this are filtered out to reduce noise
* @default 50
*/
minRegionSize?: number;
/**
* Maximum contrast threshold
* Regions with contrast above this are excluded (gradient filtering)
* @default 3.5
*/
maxContrastThreshold?: number;
/**
* Check WCAG AA compliance (4.5:1 for normal text, 3.0:1 for large text)
* @default true
*/
checkAA?: boolean;
/**
* Check WCAG AAA compliance (7.0:1 for normal text, 4.5:1 for large text)
* @default false
*/
checkAAA?: boolean;
}
/**
* A single WCAG color contrast violation region
*/
export interface ContrastViolation {
/** Bounding box containing this violation region */
boundingBox: BoundingBox;
/** List of pixel coordinates [x, y] in this violation */
pixels: [number, number][];
/** Center of mass [x, y] of the violation region */
centerOfMass: [number, number];
/** Number of pixels in this violation */
pixelCount: number;
/** Foreground color [r, g, b, a] (0-255) */
foregroundColor: [number, number, number, number];
/** Background color [r, g, b, a] (0-255) */
backgroundColor: [number, number, number, number];
/** Foreground relative luminance (0.0-1.0, sRGB) */
foregroundLuminance: number;
/** Background relative luminance (0.0-1.0, sRGB) */
backgroundLuminance: number;
/** Average contrast ratio for this region (1.0-21.0) */
contrastRatio: number;
/** Minimum contrast ratio in this region (worst case) */
minContrastRatio: number;
/** Maximum contrast ratio in this region (best case) */
maxContrastRatio: number;
/** Whether this region fails WCAG AA for normal text (< 4.5:1) */
failsAaNormal: boolean;
/** Whether this region fails WCAG AA for large text (< 3.0:1) */
failsAaLarge: boolean;
/** Whether this region fails WCAG AAA for normal text (< 7.0:1) */
failsAaaNormal: boolean;
/** Whether this region fails WCAG AAA for large text (< 4.5:1) */
failsAaaLarge: boolean;
}
/**
* Complete WCAG accessibility analysis result
*/
export interface WcagAnalysis {
/** Total number of edges analyzed */
totalEdges: number;
/** Number of edges passing WCAG AA for normal text */
aaNormalPass: number;
/** Number of edges passing WCAG AA for large text */
aaLargePass: number;
/** Number of edges passing WCAG AAA for normal text */
aaaNormalPass: number;
/** Number of edges passing WCAG AAA for large text */
aaaLargePass: number;
/** List of contrast violations found */
violations: ContrastViolation[];
/** Percentage of edges passing WCAG AA for normal text (0.0-100.0) */
aaNormalPassPercentage: number;
/** Percentage of edges passing WCAG AA for large text (0.0-100.0) */
aaLargePassPercentage: number;
/** Percentage of edges passing WCAG AAA for normal text (0.0-100.0) */
aaaNormalPassPercentage: number;
/** Percentage of edges passing WCAG AAA for large text (0.0-100.0) */
aaaLargePassPercentage: number;
}
/**
* Analyze WCAG color contrast accessibility asynchronously (recommended)
*
* Detects text/content edges in an image and checks if they meet WCAG contrast requirements.
* This is useful for catching accessibility issues in screenshots and UI designs.
*
* @param img - Image to analyze (file path or Buffer)
* @param options - WCAG analysis options
* @returns Promise resolving to detailed accessibility analysis
*
* @example
* ```typescript
* const analysis = await analyzeWcagContrast('screenshot.png', {
* edgeThreshold: 60,
* checkAA: true,
* checkAAA: true
* });
*
* console.log(`Total edges: ${analysis.totalEdges}`);
* console.log(`AA pass rate: ${analysis.aaNormalPassPercentage.toFixed(1)}%`);
* console.log(`Found ${analysis.violations.length} violations`);
*
* for (let violation of analysis.violations.slice(0, 5)) {
* console.log(`Region at (${violation.boundingBox.x}, ${violation.boundingBox.y})`);
* console.log(` Contrast: ${violation.contrastRatio.toFixed(2)}:1`);
* console.log(` Fails AA: ${violation.failsAaNormal}`);
* }
* ```
*/
export function analyzeWcagContrast(img: ImageInput, options?: WcagOptions): Promise<WcagAnalysis>;
/**
* Analyze WCAG color contrast accessibility synchronously (blocks event loop)
*
* Use this only when you need blocking behavior.
* For most cases, prefer the async analyzeWcagContrast() function.
*
* @param img - Image to analyze (file path or Buffer)
* @param options - WCAG analysis options
* @returns Detailed accessibility analysis
*
* @example
* ```typescript
* const analysis = analyzeWcagContrastSync('screenshot.png', {
* minRegionSize: 50
* });
*
* if (analysis.violations.length > 0) {
* console.log('Accessibility issues found!');
* }
* ```
*/
export function analyzeWcagContrastSync(img: ImageInput, options?: WcagOptions): WcagAnalysis;
/**
* Options for saving WCAG overlay images
*/
export interface WcagOutputOptions {
/**
* Highlight color for violations [r, g, b, a] (0-255)
* @default [255, 0, 0, 180] (semi-transparent red)
*/
highlightColor?: [number, number, number, number];
/**
* Whether to overwrite existing output file
* @default false
*/
overwrite?: boolean;
}
/**
* Save WCAG violation overlay image asynchronously (recommended)
*
* Generates an image with contrast violations highlighted in red (or custom color).
* Useful for visual debugging of accessibility issues.
*
* @param img - Original image (file path or Buffer)
* @param analysis - WCAG analysis result from analyzeWcagContrast()
* @param outputPath - Path to save the overlay image
* @param options - Output options
* @returns Promise that resolves when the file is saved
*
* @example
* ```typescript
* const analysis = await analyzeWcagContrast('screenshot.png');
*
* await saveWcagOverlay(
* 'screenshot.png',
* analysis,
* 'violations-overlay.png',
* { highlightColor: [255, 0, 0, 180] }
* );
*
* console.log('Overlay saved to violations-overlay.png');
* ```
*/
export function saveWcagOverlay(
img: ImageInput,
analysis: WcagAnalysis,
outputPath: string,
options?: WcagOutputOptions
): Promise<void>;
/**
* Save WCAG violation overlay image synchronously (blocks event loop)
*
* Use this only when you need blocking behavior.
* For most cases, prefer the async saveWcagOverlay() function.
*
* @param img - Original image (file path or Buffer)
* @param analysis - WCAG analysis result from analyzeWcagContrastSync()
* @param outputPath - Path to save the overlay image
* @param options - Output options
*
* @example
* ```typescript
* const analysis = analyzeWcagContrastSync('screenshot.png');
* saveWcagOverlaySync('screenshot.png', analysis, 'violations.png');
* ```
*/
export function saveWcagOverlaySync(
img: ImageInput,
analysis: WcagAnalysis,
outputPath: string,
options?: WcagOutputOptions
): void;
// ============================================================================
// Color Vision Deficiency (CVD) Simulation API
// ============================================================================
/**
* Types of color vision deficiency (color blindness) that can be simulated.
*
* - `protanopia` - Red-blind (~1% of males). Reds appear dark/muddy, red-green confusion.
* - `deuteranopia` - Green-blind (~1% of males, most common). Greens shift toward red/brown.
* - `tritanopia` - Blue-blind (~0.003% of population). Blues appear greenish, yellow-purple confusion.
* - `achromatopsia` - Complete color blindness (very rare). Only luminance is perceived.
*
* Short aliases are also accepted: `protan`, `deutan`, `tritan`, `achroma`, `monochromacy`
*/
export type ColorBlindnessType =
| 'protanopia'
| 'deuteranopia'
| 'tritanopia'
| 'achromatopsia'
| 'protan'
| 'deutan'
| 'tritan'
| 'achroma'
| 'monochromacy';
/**
* Information about a color blindness type
*/
export interface ColorBlindnessTypeInfo {
/** The canonical type identifier (e.g., "protanopia") */
type: string;
/** Human-readable name (e.g., "Protanopia") */
name: string;
/** Description of what colors are affected */
description: string;
/** Approximate prevalence in the population */
prevalence: string;
}
/**
* Comprehensive WCAG analysis report for all color vision deficiency types.
*
* Contains WCAG contrast analysis for normal vision and all three main types
* of dichromatic color blindness (protanopia, deuteranopia, tritanopia).
*/
export interface CvdWcagReport {
/** WCAG analysis for normal (typical) color vision */
normalVision: WcagAnalysis;
/** WCAG analysis simulating protanopia (red-blind) */
protanopia: WcagAnalysis;
/** WCAG analysis simulating deuteranopia (green-blind) */
deuteranopia: WcagAnalysis;
/** WCAG analysis simulating tritanopia (blue-blind) */
tritanopia: WcagAnalysis;
/** Whether any CVD type has violations */
hasAnyViolations: boolean;
/** Total number of violations across all CVD types */
totalViolations: number;
/**
* Estimated count of violations unique to colorblind users.
* These are violations present in CVD analysis but not in normal vision.
*/
cvdOnlyViolationCount: number;
}
/**
* Simulate color blindness for an image asynchronously (recommended)
*
* Transforms the input image to show how it appears to someone with the
* specified type of color vision deficiency. Uses the Brettel, Viénot & Mollon
* 1997 algorithm, which is considered the gold standard for CVD simulation.
*
* @param img - Image to transform (file path or Buffer)
* @param cvdType - Type of color blindness to simulate
* @returns Promise resolving to a Buffer containing the simulated PNG image
*
* @example
* ```typescript
* import { simulateColorBlindness } from '@vizzly-testing/honeydiff';
* import fs from 'fs';
*
* // Simulate how an image appears to someone with red-green color blindness
* const simulated = await simulateColorBlindness('chart.png', 'deuteranopia');
*
* // Save the result
* fs.writeFileSync('chart-deuteranopia.png', simulated);
*
* // Or use directly with image comparison
* const result = await compare('chart.png', simulated);
* ```
*/
export function simulateColorBlindness(
img: ImageInput,
cvdType: ColorBlindnessType
): Promise<Buffer>;
/**
* Simulate color blindness for an image synchronously (blocks event loop)
*
* Use this only when you need blocking behavior.
* For most cases, prefer the async simulateColorBlindness() function.
*
* @param img - Image to transform (file path or Buffer)
* @param cvdType - Type of color blindness to simulate
* @returns Buffer containing the simulated PNG image
*
* @example
* ```typescript
* const simulated = simulateColorBlindnessSync('button.png', 'protanopia');
* fs.writeFileSync('button-protanopia.png', simulated);
* ```
*/
export function simulateColorBlindnessSync(img: ImageInput, cvdType: ColorBlindnessType): Buffer;
/**
* Simulate and save color blindness image to file asynchronously (recommended)
*
* Convenience function that simulates CVD and saves the output in one step.
*
* @param img - Image to transform (file path or Buffer)
* @param cvdType - Type of color blindness to simulate
* @param outputPath - Path where the simulated image should be saved
* @returns Promise that resolves when the file is saved
*
* @example
* ```typescript
* // Save a single simulation
* await saveColorBlindnessSimulation('ui.png', 'deuteranopia', 'ui-deutan.png');
*
* // Generate simulations for all types you care about
* for (const type of ['protanopia', 'deuteranopia', 'tritanopia']) {
* await saveColorBlindnessSimulation('ui.png', type, `ui-${type}.png`);
* }
* ```
*/
export function saveColorBlindnessSimulation(
img: ImageInput,
cvdType: ColorBlindnessType,
outputPath: string
): Promise<void>;
/**
* Simulate and save color blindness image to file synchronously (blocks event loop)
*
* Use this only when you need blocking behavior.
*
* @param img - Image to transform (file path or Buffer)
* @param cvdType - Type of color blindness to simulate
* @param outputPath - Path where the simulated image should be saved
*
* @example
* ```typescript
* saveColorBlindnessSimulationSync('chart.png', 'tritanopia', 'chart-tritan.png');
* ```
*/
export function saveColorBlindnessSimulationSync(
img: ImageInput,
cvdType: ColorBlindnessType,
outputPath: string
): void;
/**
* Generate and save all CVD simulations to files asynchronously (recommended)
*
* Generates simulated images for all CVD types (protanopia, deuteranopia,
* tritanopia, achromatopsia), saving each with a suffix indicating the type.
*
* @param img - Image to transform (file path or Buffer)
* @param outputPrefix - Base path for output files (without extension)
* @param extension - File extension to use (default: "png")
* @returns Promise that resolves when all files are saved
*
* @example
* ```typescript
* // Creates: dashboard_protanopia.png, dashboard_deuteranopia.png,
* // dashboard_tritanopia.png, dashboard_achromatopsia.png
* await saveAllColorBlindnessSimulations('dashboard.png', 'dashboard', 'png');
*
* // With different extension
* await saveAllColorBlindnessSimulations('ui.png', './artifacts/ui', 'jpg');
* ```
*/
export function saveAllColorBlindnessSimulations(
img: ImageInput,
outputPrefix: string,
extension?: string
): Promise<void>;
/**
* Generate and save all CVD simulations to files synchronously (blocks event loop)
*
* Use this only when you need blocking behavior.
*
* @param img - Image to transform (file path or Buffer)
* @param outputPrefix - Base path for output files (without extension)
* @param extension - File extension to use (default: "png")
*
* @example