@pixsame/analysis 0.0.0-canary-20261116-x0egu3nf → 0.0.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/package.json CHANGED
@@ -1,61 +1 @@
1
- {
2
- "name": "@pixsame/analysis",
3
- "description": "Says what changed in a failed screenshot comparison: changed areas, layout shifts and rendering noise, in plain words, with a key that groups the same change across screenshots. Runner-agnostic, no dependencies.",
4
- "version": "0.0.0-canary-20261116-x0egu3nf",
5
- "author": "Jakub Freisler <jakub.freisler@frsource.org>",
6
- "homepage": "https://pixsame.com",
7
- "repository": {
8
- "type": "git",
9
- "url": "https://github.com/pixsame/pixsame.git",
10
- "directory": "packages/analysis"
11
- },
12
- "license": "MIT",
13
- "sideEffects": false,
14
- "main": "dist/index.js",
15
- "types": "dist/index.d.ts",
16
- "exports": {
17
- ".": {
18
- "types": "./dist/index.d.ts",
19
- "default": "./dist/index.js"
20
- },
21
- "./package.json": "./package.json"
22
- },
23
- "engines": {
24
- "node": ">=20.9.0"
25
- },
26
- "devDependencies": {
27
- "@frsource/prettier-config": "^1.11.0",
28
- "@types/node": "20.19.43",
29
- "@vitest/coverage-v8": "4.1.11",
30
- "del-cli": "7.0.0",
31
- "prettier": "3.9.8",
32
- "typescript": "6.0.3",
33
- "vitest": "4.1.11"
34
- },
35
- "keywords": [
36
- "visual regression testing",
37
- "visual diff",
38
- "image diff",
39
- "diff regions",
40
- "layout shift",
41
- "screenshot testing"
42
- ],
43
- "publishConfig": {
44
- "access": "public"
45
- },
46
- "files": [
47
- "dist",
48
- "package.json",
49
- "README.md",
50
- "LICENSE"
51
- ],
52
- "scripts": {
53
- "build": "del-cli dist && tsc -p tsconfig.build.json",
54
- "format": "prettier --write .",
55
- "format:ci": "prettier --check .",
56
- "test:integration": "vitest run",
57
- "test:integration:watch": "vitest",
58
- "test:integration:coverage": "vitest run --coverage",
59
- "test:integration:ci": "CI=true vitest run --coverage"
60
- }
61
- }
1
+ {"name":"@pixsame/analysis","version":"0.0.0","license":"MIT","description":"Placeholder. The first real release is coming."}
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2021 FRSOURCE - Let's shape your web
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
package/README.md DELETED
@@ -1,74 +0,0 @@
1
- # @pixsame/analysis
2
-
3
- Says what changed in a failed screenshot comparison, from the pixels alone. No model, no network, no dependencies.
4
-
5
- A pixel diff gives you one number. This package turns the same comparison into something a person or an agent can act on:
6
-
7
- - the changed areas, each with its box and pixel count;
8
- - whether the content only moved, as a whole ("Everything below y=340 moved down by 12 px.") or one area ("One area moved right by 12 px: 52x16 px at x=130, y=250.");
9
- - whether the difference looks like rendering noise;
10
- - one sentence describing it;
11
- - a key that is equal for screenshots that changed in the same way, so one change showing in 14 screenshots is one thing to decide.
12
-
13
- It never decides whether a comparison passes. `@pixsame/cypress-plugin-visual-regression-diff` and `@pixsame/playwright-visual-regression-diff` use it out of the box and record the result in the run manifest under `extra.pixsame.analysis`.
14
-
15
- ## Use it on two images
16
-
17
- ```ts
18
- import { analyze } from '@pixsame/analysis';
19
-
20
- // baseline and actual: { width, height, data } with 8-bit RGBA data, the same size
21
- // mask: Uint8Array with 1 for every pixel your comparison counted as different
22
- const analysis = analyze({ baseline, actual, mask });
23
-
24
- analysis.label; // 'content-change' | 'moved' | 'noise-like' | 'size-change'
25
- analysis.description; // 'One area changed: 220x40 px at x=40, y=120.'
26
- analysis.regions; // [{ x, y, width, height, area, fillRatio, kind, hash, moved }]
27
- analysis.shift; // { fromX, fromY, dx, dy, coverage } or null
28
- analysis.bundleKey; // equal for entries that changed in the same way
29
- ```
30
-
31
- With pixelmatch, `maskFromPixelmatchDiff(diffImage, pixelmatchOptions)` reads the mask back from the diff image it drew.
32
-
33
- Pass `descriptions` to `analyze` for another language or wording: one function per label.
34
-
35
- ## Group the entries of a run
36
-
37
- ```ts
38
- import { bundle } from '@pixsame/analysis';
39
-
40
- // entries of a visual-regression-manifest run manifest
41
- for (const { description, entries } of bundle(manifest.entries)) {
42
- console.log(`${description} (${entries.length} screenshots)`);
43
- }
44
- ```
45
-
46
- ## How it decides
47
-
48
- | label | when |
49
- | ---------------- | --------------------------------------------------------------------------------------------------------------------------- |
50
- | `size-change` | the two images had different sizes |
51
- | `moved` | at least 90% of the changed lines equal a baseline line a fixed distance away, for the whole page or for every changed area |
52
- | `noise-like` | the differing pixels sit in specks of at most 4 px, or are thinly scattered |
53
- | `content-change` | anything else |
54
-
55
- Differing pixels closer than 8 px form one area, so a changed word is one area and not one per letter. Moves are searched up, down, left and right, up to 64 px, one direction at a time: first for the page as a whole (everything below a row or right of a column), then for each changed area on its own, which gets `moved: { dx, dy }`. A move is only recognised when the moved pixels are identical, so content that was re-rendered with different anti-aliasing counts as a content change.
56
-
57
- ## Use it in your own `visual-regression-compare` adapter
58
-
59
- ```ts
60
- import {
61
- analysisPlugin,
62
- captureComparison,
63
- withAnalysis,
64
- } from '@pixsame/analysis';
65
-
66
- // 1. register the plugin: createComparer({ ..., plugins: [analysisPlugin()] })
67
- // 2. in your pixelmatch engine, after pixelmatch ran:
68
- // captureComparison(baseline, actual, { width, height, data: diff }, options);
69
- // 3. wrap each call: await withAnalysis(() => comparer.compare(input));
70
- ```
71
-
72
- ## License
73
-
74
- MIT
package/dist/analyze.d.ts DELETED
@@ -1,22 +0,0 @@
1
- import { type Descriptions } from './describe';
2
- import type { Analysis, RgbaImage, Size } from './types';
3
- export type AnalyzeInput = {
4
- /** Both images as they were compared: the same size. */
5
- baseline: RgbaImage;
6
- actual: RgbaImage;
7
- /** 1 for every pixel that counted as different, row by row. */
8
- mask: Uint8Array;
9
- /** The sizes before any padding or cropping, when known. */
10
- sizes?: {
11
- baseline: Size;
12
- actual: Size;
13
- };
14
- descriptions?: Partial<Descriptions>;
15
- };
16
- /**
17
- * What changed between two images, from the pixels alone: the changed areas,
18
- * whether content only moved, whether it looks like noise, one sentence about
19
- * it and a key shared by entries that changed in the same way. Deterministic;
20
- * it never decides whether the comparison passes.
21
- */
22
- export declare const analyze: ({ baseline, actual, mask, sizes, descriptions, }: AnalyzeInput) => Analysis;
package/dist/analyze.js DELETED
@@ -1,99 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.analyze = void 0;
4
- const describe_1 = require("./describe");
5
- const hash_1 = require("./hash");
6
- const regions_1 = require("./regions");
7
- const shift_1 = require("./shift");
8
- /** Regions that get a hash: the ones a person would look at. */
9
- const HASHED_REGIONS = 5;
10
- /** Specks make up at least this share of the differing pixels. */
11
- const NOISE_SPECK_RATIO = 0.9;
12
- /** Or every area is this sparse: a few scattered pixels in a large box. */
13
- const NOISE_FILL_RATIO = 0.03;
14
- /**
15
- * What changed between two images, from the pixels alone: the changed areas,
16
- * whether content only moved, whether it looks like noise, one sentence about
17
- * it and a key shared by entries that changed in the same way. Deterministic;
18
- * it never decides whether the comparison passes.
19
- */
20
- const analyze = ({ baseline, actual, mask, sizes, descriptions, }) => {
21
- const words = { ...describe_1.descriptions, ...descriptions };
22
- const { width, height } = actual;
23
- const { regions, truncated, diffPixels } = (0, regions_1.findRegions)(mask, width, height);
24
- regions.slice(0, HASHED_REGIONS).forEach((region) => {
25
- if (region.kind !== 'speck')
26
- region.hash = (0, hash_1.regionHash)(actual, region);
27
- });
28
- const speckPixels = regions.reduce((sum, region) => sum + (region.kind === 'speck' ? region.area : 0), 0);
29
- const speckRatio = diffPixels === 0 ? 0 : speckPixels / diffPixels;
30
- const resized = sizes !== undefined &&
31
- (sizes.baseline.width !== sizes.actual.width ||
32
- sizes.baseline.height !== sizes.actual.height);
33
- const shift = (0, shift_1.detectShift)(baseline, actual);
34
- const regionCount = regions.length + (truncated?.count ?? 0);
35
- const noisy = !truncated &&
36
- regions.length > 0 &&
37
- (speckRatio >= NOISE_SPECK_RATIO ||
38
- regions.every((region) => region.kind === 'speck' || region.fillRatio < NOISE_FILL_RATIO));
39
- const largest = regions[0];
40
- // areas that moved on their own (a badge, a sidebar), when the page as a whole did not
41
- const parts = regions.filter((region) => region.kind !== 'speck');
42
- if (!resized && !shift) {
43
- for (const region of parts) {
44
- const moved = (0, shift_1.detectRegionShift)(baseline, actual, region);
45
- if (moved)
46
- region.moved = moved;
47
- }
48
- }
49
- const allMoved = !truncated && parts.length > 0 && parts.every((region) => region.moved);
50
- let label;
51
- let description;
52
- let bundleKey;
53
- if (resized) {
54
- label = 'size-change';
55
- description = words['size-change'](sizes);
56
- bundleKey = `size:${sizes.baseline.width}x${sizes.baseline.height}>${sizes.actual.width}x${sizes.actual.height}`;
57
- }
58
- else if (shift) {
59
- label = 'moved';
60
- description = words.moved(shift);
61
- bundleKey = `moved:${shift.dx},${shift.dy}`;
62
- }
63
- else if (allMoved && largest) {
64
- const { dx, dy } = largest.moved;
65
- const same = parts.every((region) => region.moved?.dx === dx && region.moved?.dy === dy);
66
- label = 'moved';
67
- description = words['moved-areas']({
68
- regions: parts.length,
69
- largest: parts[0],
70
- ...(same && { offset: { dx, dy } }),
71
- });
72
- bundleKey = `moved-area:${dx},${dy}:${parts[0].width}x${parts[0].height}:${parts[0].hash ?? (0, hash_1.regionHash)(actual, parts[0])}`;
73
- }
74
- else if (noisy || !largest) {
75
- label = 'noise-like';
76
- description = words['noise-like']({
77
- pixels: diffPixels,
78
- regions: regionCount,
79
- });
80
- bundleKey = 'noise';
81
- }
82
- else {
83
- label = 'content-change';
84
- description = words['content-change']({ regions: regionCount, largest });
85
- bundleKey = `change:${largest.width}x${largest.height}:${largest.hash ?? (0, hash_1.regionHash)(actual, largest)}`;
86
- }
87
- return {
88
- version: 1,
89
- label,
90
- description,
91
- regions,
92
- ...(truncated && { truncated }),
93
- speckRatio,
94
- shift,
95
- ...(resized && { sizes }),
96
- bundleKey,
97
- };
98
- };
99
- exports.analyze = analyze;
package/dist/bundle.d.ts DELETED
@@ -1,23 +0,0 @@
1
- import type { Analysis, Label } from './types';
2
- /** The part of a manifest entry `bundle` reads. */
3
- export type BundleEntry = {
4
- name: string;
5
- extra?: Record<string, Record<string, unknown> | undefined>;
6
- };
7
- export type Bundle = {
8
- key: string;
9
- label: Label;
10
- /** The description of the first entry; the others changed in the same way. */
11
- description: string;
12
- /** Entry names, in the order given. */
13
- entries: string[];
14
- };
15
- /** The analysis recorded on a manifest entry, if any. */
16
- export declare const analysisOf: (entry: BundleEntry) => Analysis | undefined;
17
- /**
18
- * Groups entries that changed in the same way (the same area with the same
19
- * new pixels, the same move, the same size change), so a change that shows
20
- * in 14 screenshots is one thing to decide. Largest group first. Entries
21
- * without an analysis are left out.
22
- */
23
- export declare const bundle: (entries: BundleEntry[]) => Bundle[];
package/dist/bundle.js DELETED
@@ -1,36 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.bundle = exports.analysisOf = void 0;
4
- /** The analysis recorded on a manifest entry, if any. */
5
- const analysisOf = (entry) => {
6
- const analysis = entry.extra?.pixsame?.analysis;
7
- return analysis?.version === 1 ? analysis : undefined;
8
- };
9
- exports.analysisOf = analysisOf;
10
- /**
11
- * Groups entries that changed in the same way (the same area with the same
12
- * new pixels, the same move, the same size change), so a change that shows
13
- * in 14 screenshots is one thing to decide. Largest group first. Entries
14
- * without an analysis are left out.
15
- */
16
- const bundle = (entries) => {
17
- const bundles = new Map();
18
- for (const entry of entries) {
19
- const analysis = (0, exports.analysisOf)(entry);
20
- if (!analysis)
21
- continue;
22
- const existing = bundles.get(analysis.bundleKey);
23
- if (existing)
24
- existing.entries.push(entry.name);
25
- else {
26
- bundles.set(analysis.bundleKey, {
27
- key: analysis.bundleKey,
28
- label: analysis.label,
29
- description: analysis.description,
30
- entries: [entry.name],
31
- });
32
- }
33
- }
34
- return [...bundles.values()].sort((a, b) => b.entries.length - a.entries.length);
35
- };
36
- exports.bundle = bundle;
@@ -1,30 +0,0 @@
1
- import type { Region, Shift, Size } from './types';
2
- /**
3
- * The words of a description, one function per label: a language. English is
4
- * built in; pass other functions to `analyze` for another language or wording.
5
- */
6
- export type Descriptions = {
7
- 'size-change': (params: {
8
- baseline: Size;
9
- actual: Size;
10
- }) => string;
11
- moved: (params: Shift) => string;
12
- /** Every changed area only moved. `offset` is set when they all moved the same way. */
13
- 'moved-areas': (params: {
14
- regions: number;
15
- largest: Region;
16
- offset?: {
17
- dx: number;
18
- dy: number;
19
- };
20
- }) => string;
21
- 'noise-like': (params: {
22
- pixels: number;
23
- regions: number;
24
- }) => string;
25
- 'content-change': (params: {
26
- regions: number;
27
- largest: Region;
28
- }) => string;
29
- };
30
- export declare const descriptions: Descriptions;
package/dist/describe.js DELETED
@@ -1,30 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.descriptions = void 0;
4
- const size = ({ width, height }) => `${width}x${height}`;
5
- const direction = ({ dx, dy }) => dy !== 0
6
- ? `${dy > 0 ? 'down' : 'up'} by ${Math.abs(dy)} px`
7
- : `${dx > 0 ? 'right' : 'left'} by ${Math.abs(dx)} px`;
8
- const grew = (by, more, less) => by === 0 ? [] : [`${Math.abs(by)} px ${by > 0 ? more : less}`];
9
- exports.descriptions = {
10
- 'size-change': ({ baseline, actual }) => `The screenshot is ${[
11
- ...grew(actual.width - baseline.width, 'wider', 'narrower'),
12
- ...grew(actual.height - baseline.height, 'taller', 'shorter'),
13
- ].join(' and ')} than the baseline.`,
14
- moved: ({ fromX, fromY, dx, dy }) => dy !== 0
15
- ? `Everything below y=${fromY} moved ${direction({ dx, dy })}.`
16
- : `Everything right of x=${fromX} moved ${direction({ dx, dy })}.`,
17
- 'moved-areas': ({ regions, largest, offset }) => {
18
- const where = `${size(largest)} px at x=${largest.x}, y=${largest.y}`;
19
- if (regions === 1 && offset) {
20
- return `One area moved ${direction(offset)}: ${where}.`;
21
- }
22
- return offset
23
- ? `${regions} areas moved ${direction(offset)}. The largest is ${where}.`
24
- : `${regions} areas moved. The largest is ${where}.`;
25
- },
26
- 'noise-like': ({ pixels }) => `${pixels} ${pixels === 1 ? 'pixel differs' : 'pixels differ'} in tiny scattered spots, which looks like rendering noise.`,
27
- 'content-change': ({ regions, largest }) => regions === 1
28
- ? `One area changed: ${size(largest)} px at x=${largest.x}, y=${largest.y}.`
29
- : `${regions} areas changed. The largest is ${size(largest)} px at x=${largest.x}, y=${largest.y}.`,
30
- };
package/dist/hash.d.ts DELETED
@@ -1,7 +0,0 @@
1
- import type { Box, RgbaImage } from './types';
2
- /**
3
- * Difference hash (dHash) of the pixels inside `box`: the box is averaged
4
- * down to 9x8 grey cells and each cell is compared with its right neighbour.
5
- * 16 hex characters. The same change in two screenshots gives the same hash.
6
- */
7
- export declare const regionHash: (image: RgbaImage, box: Box) => string;
package/dist/hash.js DELETED
@@ -1,44 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.regionHash = void 0;
4
- const COLS = 9;
5
- const ROWS = 8;
6
- /**
7
- * Difference hash (dHash) of the pixels inside `box`: the box is averaged
8
- * down to 9x8 grey cells and each cell is compared with its right neighbour.
9
- * 16 hex characters. The same change in two screenshots gives the same hash.
10
- */
11
- const regionHash = (image, box) => {
12
- const { data, width } = image;
13
- const grey = new Float64Array(COLS * ROWS);
14
- for (let row = 0; row < ROWS; row++) {
15
- const y0 = box.y + Math.floor((row * box.height) / ROWS);
16
- const y1 = Math.max(y0 + 1, box.y + Math.floor(((row + 1) * box.height) / ROWS));
17
- for (let col = 0; col < COLS; col++) {
18
- const x0 = box.x + Math.floor((col * box.width) / COLS);
19
- const x1 = Math.max(x0 + 1, box.x + Math.floor(((col + 1) * box.width) / COLS));
20
- let sum = 0;
21
- let count = 0;
22
- for (let y = y0; y < y1 && y < image.height; y++) {
23
- for (let x = x0; x < x1 && x < width; x++) {
24
- const p = (y * width + x) * 4;
25
- sum += data[p] * 0.299 + data[p + 1] * 0.587 + data[p + 2] * 0.114;
26
- count++;
27
- }
28
- }
29
- grey[row * COLS + col] = count === 0 ? 0 : sum / count;
30
- }
31
- }
32
- let hex = '';
33
- for (let row = 0; row < ROWS; row++) {
34
- let byte = 0;
35
- for (let col = 0; col < COLS - 1; col++) {
36
- byte =
37
- (byte << 1) |
38
- (grey[row * COLS + col] > grey[row * COLS + col + 1] ? 1 : 0);
39
- }
40
- hex += byte.toString(16).padStart(2, '0');
41
- }
42
- return hex;
43
- };
44
- exports.regionHash = regionHash;
package/dist/index.d.ts DELETED
@@ -1,8 +0,0 @@
1
- export { analyze, type AnalyzeInput } from './analyze';
2
- export { analysisOf, bundle, type Bundle, type BundleEntry } from './bundle';
3
- export { descriptions, type Descriptions } from './describe';
4
- export { regionHash } from './hash';
5
- export { analysisPlugin, captureComparison, withAnalysis, type AnalysisPlugin, } from './plugin';
6
- export { findRegions, maskFromPixelmatchDiff, type Regions } from './regions';
7
- export { detectRegionShift, detectShift } from './shift';
8
- export type { Analysis, Box, Label, Region, RegionKind, RgbaImage, Shift, Size, } from './types';
package/dist/index.js DELETED
@@ -1,22 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.detectShift = exports.detectRegionShift = exports.maskFromPixelmatchDiff = exports.findRegions = exports.withAnalysis = exports.captureComparison = exports.analysisPlugin = exports.regionHash = exports.descriptions = exports.bundle = exports.analysisOf = exports.analyze = void 0;
4
- var analyze_1 = require("./analyze");
5
- Object.defineProperty(exports, "analyze", { enumerable: true, get: function () { return analyze_1.analyze; } });
6
- var bundle_1 = require("./bundle");
7
- Object.defineProperty(exports, "analysisOf", { enumerable: true, get: function () { return bundle_1.analysisOf; } });
8
- Object.defineProperty(exports, "bundle", { enumerable: true, get: function () { return bundle_1.bundle; } });
9
- var describe_1 = require("./describe");
10
- Object.defineProperty(exports, "descriptions", { enumerable: true, get: function () { return describe_1.descriptions; } });
11
- var hash_1 = require("./hash");
12
- Object.defineProperty(exports, "regionHash", { enumerable: true, get: function () { return hash_1.regionHash; } });
13
- var plugin_1 = require("./plugin");
14
- Object.defineProperty(exports, "analysisPlugin", { enumerable: true, get: function () { return plugin_1.analysisPlugin; } });
15
- Object.defineProperty(exports, "captureComparison", { enumerable: true, get: function () { return plugin_1.captureComparison; } });
16
- Object.defineProperty(exports, "withAnalysis", { enumerable: true, get: function () { return plugin_1.withAnalysis; } });
17
- var regions_1 = require("./regions");
18
- Object.defineProperty(exports, "findRegions", { enumerable: true, get: function () { return regions_1.findRegions; } });
19
- Object.defineProperty(exports, "maskFromPixelmatchDiff", { enumerable: true, get: function () { return regions_1.maskFromPixelmatchDiff; } });
20
- var shift_1 = require("./shift");
21
- Object.defineProperty(exports, "detectRegionShift", { enumerable: true, get: function () { return shift_1.detectRegionShift; } });
22
- Object.defineProperty(exports, "detectShift", { enumerable: true, get: function () { return shift_1.detectShift; } });
package/dist/plugin.d.ts DELETED
@@ -1,50 +0,0 @@
1
- import type { Descriptions } from './describe';
2
- import type { RgbaImage, Size } from './types';
3
- type Color = [number, number, number];
4
- /**
5
- * Runs one `comparer.compare()` call so that the images its engine sees can
6
- * be analyzed for that call's entry. Without it nothing is recorded.
7
- */
8
- export declare const withAnalysis: <T>(compare: () => Promise<T>) => Promise<T>;
9
- /**
10
- * For a pixelmatch engine to call with the images it compared and the diff
11
- * image pixelmatch drew. `options` are pixelmatch's, for the diff colors.
12
- */
13
- export declare const captureComparison: (baseline: RgbaImage, actual: RgbaImage, diff: RgbaImage, options?: {
14
- diffColor?: Color;
15
- diffColorAlt?: Color;
16
- }) => void;
17
- type Measured = {
18
- kind: string;
19
- baselineSize?: Size;
20
- actualSize?: Size;
21
- result?: {
22
- diffPixels: number;
23
- };
24
- };
25
- type Context = {
26
- input: {
27
- extra?: Record<string, Record<string, unknown>>;
28
- };
29
- };
30
- type Decided = {
31
- status: string;
32
- message: string;
33
- };
34
- export type AnalysisPlugin = {
35
- name: string;
36
- setup(api: {
37
- on(event: 'afterCompare', fn: (ctx: Context, measurement: Measured) => void): void;
38
- on(event: 'decide', fn: <D extends Decided>(ctx: Context, decision: D) => D): void;
39
- }): void;
40
- };
41
- /**
42
- * A `visual-regression-compare` plugin: after a comparison that found
43
- * differences it writes the analysis to the entry's `extra.pixsame.analysis`,
44
- * and a failed comparison's message ends with the description. It needs `withAnalysis` around the call and `captureComparison` in the
45
- * engine; pass or fail is not touched.
46
- */
47
- export declare const analysisPlugin: ({ descriptions, }?: {
48
- descriptions?: Partial<Descriptions>;
49
- }) => AnalysisPlugin;
50
- export {};
package/dist/plugin.js DELETED
@@ -1,76 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.analysisPlugin = exports.captureComparison = exports.withAnalysis = void 0;
4
- const node_async_hooks_1 = require("node:async_hooks");
5
- const analyze_1 = require("./analyze");
6
- const regions_1 = require("./regions");
7
- /** One comparison's hand-over point between the engine (which has the pixels) and the hook (which has the entry). */
8
- const comparison = new node_async_hooks_1.AsyncLocalStorage();
9
- /**
10
- * Runs one `comparer.compare()` call so that the images its engine sees can
11
- * be analyzed for that call's entry. Without it nothing is recorded.
12
- */
13
- const withAnalysis = (compare) => comparison.run({}, compare);
14
- exports.withAnalysis = withAnalysis;
15
- /**
16
- * For a pixelmatch engine to call with the images it compared and the diff
17
- * image pixelmatch drew. `options` are pixelmatch's, for the diff colors.
18
- */
19
- const captureComparison = (baseline, actual, diff, options = {}) => {
20
- const slot = comparison.getStore();
21
- if (!slot)
22
- return;
23
- slot.captured = {
24
- baseline,
25
- actual,
26
- mask: (0, regions_1.maskFromPixelmatchDiff)(diff, options),
27
- };
28
- };
29
- exports.captureComparison = captureComparison;
30
- /**
31
- * A `visual-regression-compare` plugin: after a comparison that found
32
- * differences it writes the analysis to the entry's `extra.pixsame.analysis`,
33
- * and a failed comparison's message ends with the description. It needs `withAnalysis` around the call and `captureComparison` in the
34
- * engine; pass or fail is not touched.
35
- */
36
- const analysisPlugin = ({ descriptions, } = {}) => ({
37
- name: '@pixsame/analysis',
38
- setup: (api) => {
39
- api.on('afterCompare', (ctx, measurement) => {
40
- const slot = comparison.getStore();
41
- const captured = slot?.captured;
42
- if (!slot ||
43
- !captured ||
44
- measurement.kind !== 'compared' ||
45
- !measurement.result?.diffPixels) {
46
- return;
47
- }
48
- const analysis = (0, analyze_1.analyze)({
49
- ...captured,
50
- descriptions,
51
- ...(measurement.baselineSize &&
52
- measurement.actualSize && {
53
- sizes: {
54
- baseline: measurement.baselineSize,
55
- actual: measurement.actualSize,
56
- },
57
- }),
58
- });
59
- slot.analysis = analysis;
60
- ctx.input.extra = {
61
- ...ctx.input.extra,
62
- pixsame: { ...ctx.input.extra?.pixsame, analysis },
63
- };
64
- });
65
- api.on('decide', (_ctx, decision) => {
66
- const analysis = comparison.getStore()?.analysis;
67
- return analysis && decision.status === 'failed'
68
- ? {
69
- ...decision,
70
- message: `${decision.message} ${analysis.description}`,
71
- }
72
- : decision;
73
- });
74
- },
75
- });
76
- exports.analysisPlugin = analysisPlugin;
package/dist/regions.d.ts DELETED
@@ -1,32 +0,0 @@
1
- import type { Region, RgbaImage } from './types';
2
- type Color = [number, number, number];
3
- /** Differing pixels closer than this are one area: a changed word is one region, not one per letter. */
4
- export declare const CELL = 8;
5
- /**
6
- * Which pixels pixelmatch counted as different, read back from its diff
7
- * image: those painted with `diffColor` (or `diffColorAlt`). Anti-aliased and
8
- * unchanged pixels are not. A `diffColor` that is a shade of grey can collide
9
- * with unchanged pixels.
10
- */
11
- export declare const maskFromPixelmatchDiff: (diff: RgbaImage, { diffColor, diffColorAlt, }?: {
12
- diffColor?: Color;
13
- diffColorAlt?: Color;
14
- }) => Uint8Array;
15
- export type Regions = {
16
- /** Largest first. */
17
- regions: Region[];
18
- truncated?: {
19
- count: number;
20
- area: number;
21
- };
22
- diffPixels: number;
23
- };
24
- /**
25
- * Groups the differing pixels of `mask` (1 = differs, row by row) into areas.
26
- * Pixels are connected through a grid of `CELL`-sized cells, so nearby
27
- * differences form one area; each area's box and pixel count are exact.
28
- */
29
- export declare const findRegions: (mask: Uint8Array, width: number, height: number, { maxRegions }?: {
30
- maxRegions?: number;
31
- }) => Regions;
32
- export {};
package/dist/regions.js DELETED
@@ -1,138 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.findRegions = exports.maskFromPixelmatchDiff = exports.CELL = void 0;
4
- /** Differing pixels closer than this are one area: a changed word is one region, not one per letter. */
5
- exports.CELL = 8;
6
- const SPECK_SIDE = 4;
7
- const BAND_SPAN = 0.9;
8
- const BAND_THICKNESS = 0.05;
9
- /**
10
- * Which pixels pixelmatch counted as different, read back from its diff
11
- * image: those painted with `diffColor` (or `diffColorAlt`). Anti-aliased and
12
- * unchanged pixels are not. A `diffColor` that is a shade of grey can collide
13
- * with unchanged pixels.
14
- */
15
- const maskFromPixelmatchDiff = (diff, { diffColor = [255, 0, 0], diffColorAlt, } = {}) => {
16
- const colors = diffColorAlt ? [diffColor, diffColorAlt] : [diffColor];
17
- const { data } = diff;
18
- const mask = new Uint8Array(diff.width * diff.height);
19
- for (let at = 0; at < mask.length; at++) {
20
- const p = at * 4;
21
- if (data[p + 3] !== 255)
22
- continue;
23
- for (const [r, g, b] of colors) {
24
- if (data[p] === r && data[p + 1] === g && data[p + 2] === b) {
25
- mask[at] = 1;
26
- break;
27
- }
28
- }
29
- }
30
- return mask;
31
- };
32
- exports.maskFromPixelmatchDiff = maskFromPixelmatchDiff;
33
- const kindOf = (box, image) => {
34
- if (box.width <= SPECK_SIDE && box.height <= SPECK_SIDE)
35
- return 'speck';
36
- const thin = (side, of) => side <= Math.max(exports.CELL, of * BAND_THICKNESS);
37
- const horizontal = box.width >= image.width * BAND_SPAN && thin(box.height, image.height);
38
- const vertical = box.height >= image.height * BAND_SPAN && thin(box.width, image.width);
39
- return horizontal || vertical ? 'band' : 'block';
40
- };
41
- /**
42
- * Groups the differing pixels of `mask` (1 = differs, row by row) into areas.
43
- * Pixels are connected through a grid of `CELL`-sized cells, so nearby
44
- * differences form one area; each area's box and pixel count are exact.
45
- */
46
- const findRegions = (mask, width, height, { maxRegions = 50 } = {}) => {
47
- const cols = Math.ceil(width / exports.CELL);
48
- const rows = Math.ceil(height / exports.CELL);
49
- const on = new Uint8Array(cols * rows);
50
- for (let y = 0; y < height; y++) {
51
- const row = Math.floor(y / exports.CELL) * cols;
52
- for (let x = 0; x < width; x++) {
53
- if (mask[y * width + x])
54
- on[row + Math.floor(x / exports.CELL)] = 1;
55
- }
56
- }
57
- // label the cells: 0 = none, n = component n
58
- const label = new Int32Array(cols * rows);
59
- let components = 0;
60
- const stack = [];
61
- for (let start = 0; start < on.length; start++) {
62
- if (!on[start] || label[start])
63
- continue;
64
- label[start] = ++components;
65
- stack.push(start);
66
- while (stack.length > 0) {
67
- const cell = stack.pop();
68
- const cx = cell % cols;
69
- const cy = (cell - cx) / cols;
70
- for (let dy = -1; dy <= 1; dy++) {
71
- for (let dx = -1; dx <= 1; dx++) {
72
- const nx = cx + dx;
73
- const ny = cy + dy;
74
- if (nx < 0 || ny < 0 || nx >= cols || ny >= rows)
75
- continue;
76
- const next = ny * cols + nx;
77
- if (on[next] && !label[next]) {
78
- label[next] = components;
79
- stack.push(next);
80
- }
81
- }
82
- }
83
- }
84
- }
85
- const minX = new Int32Array(components + 1).fill(width);
86
- const minY = new Int32Array(components + 1).fill(height);
87
- const maxX = new Int32Array(components + 1).fill(-1);
88
- const maxY = new Int32Array(components + 1).fill(-1);
89
- const area = new Int32Array(components + 1);
90
- let diffPixels = 0;
91
- for (let y = 0; y < height; y++) {
92
- const row = Math.floor(y / exports.CELL) * cols;
93
- for (let x = 0; x < width; x++) {
94
- if (!mask[y * width + x])
95
- continue;
96
- const id = label[row + Math.floor(x / exports.CELL)];
97
- diffPixels++;
98
- area[id]++;
99
- if (x < minX[id])
100
- minX[id] = x;
101
- if (x > maxX[id])
102
- maxX[id] = x;
103
- if (y < minY[id])
104
- minY[id] = y;
105
- if (y > maxY[id])
106
- maxY[id] = y;
107
- }
108
- }
109
- const all = [];
110
- for (let id = 1; id <= components; id++) {
111
- const box = {
112
- x: minX[id],
113
- y: minY[id],
114
- width: maxX[id] - minX[id] + 1,
115
- height: maxY[id] - minY[id] + 1,
116
- };
117
- all.push({
118
- ...box,
119
- area: area[id],
120
- fillRatio: area[id] / (box.width * box.height),
121
- kind: kindOf(box, { width, height }),
122
- });
123
- }
124
- all.sort((a, b) => b.area - a.area || a.y - b.y || a.x - b.x);
125
- const regions = all.slice(0, maxRegions);
126
- const rest = all.slice(maxRegions);
127
- return {
128
- regions,
129
- diffPixels,
130
- ...(rest.length > 0 && {
131
- truncated: {
132
- count: rest.length,
133
- area: rest.reduce((sum, region) => sum + region.area, 0),
134
- },
135
- }),
136
- };
137
- };
138
- exports.findRegions = findRegions;
package/dist/shift.d.ts DELETED
@@ -1,22 +0,0 @@
1
- import type { Box, RgbaImage, Shift } from './types';
2
- type Options = {
3
- maxShift?: number;
4
- minExplained?: number;
5
- minLines?: number;
6
- };
7
- /**
8
- * Is the screenshot the baseline with everything below some row moved up or
9
- * down, or everything right of some column moved left or right? That is what
10
- * an element that grew or shrank causes. One direction at a time.
11
- */
12
- export declare const detectShift: (baseline: RgbaImage, actual: RgbaImage, options?: Options) => Shift | null;
13
- /**
14
- * Did the content of one changed area only move, up, down, left or right? A
15
- * moved element leaves an area that covers its old and its new place; inside
16
- * it the screenshot equals the baseline a fixed number of pixels away.
17
- */
18
- export declare const detectRegionShift: (baseline: RgbaImage, actual: RgbaImage, box: Box, options?: Options) => {
19
- dx: number;
20
- dy: number;
21
- } | null;
22
- export {};
package/dist/shift.js DELETED
@@ -1,129 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.detectRegionShift = exports.detectShift = void 0;
4
- /**
5
- * FNV-1a over the bytes of every line along `axis` (rows for `y`, columns for
6
- * `x`), for the lines `from..to` and only the part of each line inside
7
- * `across`. Equal lines have equal hashes. Index 0 of the result is line `from`.
8
- */
9
- const lineHashes = ({ width, data }, axis, from, to, across) => {
10
- const hashes = new Uint32Array(Math.max(0, to - from));
11
- for (let line = from; line < to; line++) {
12
- let hash = 0x811c9dc5;
13
- for (let other = across.from; other < across.to; other++) {
14
- const at = (axis === 'y' ? line * width + other : other * width + line) * 4;
15
- hash = Math.imul(hash ^ data[at], 0x01000193);
16
- hash = Math.imul(hash ^ data[at + 1], 0x01000193);
17
- hash = Math.imul(hash ^ data[at + 2], 0x01000193);
18
- hash = Math.imul(hash ^ data[at + 3], 0x01000193);
19
- }
20
- hashes[line - from] = hash >>> 0;
21
- }
22
- return hashes;
23
- };
24
- /**
25
- * The offset that explains the changed lines between `start` and `end`: at
26
- * least `minExplained` of them equal the baseline line `offset` lines away.
27
- * Lines that did not change (a blank page) prove nothing and are left out of
28
- * that share.
29
- */
30
- const findOffset = (before, after, start, end, { maxShift = 64, minExplained = 0.9, minLines = 4 }) => {
31
- let best = null;
32
- for (let step = 1; step <= maxShift; step++) {
33
- for (const offset of [step, -step]) {
34
- const lo = Math.max(start + Math.max(offset, 0), offset, 0);
35
- const hi = Math.min(end - Math.max(-offset, 0), before.length + Math.min(offset, 0));
36
- let changed = 0;
37
- let explained = 0;
38
- let matching = 0;
39
- for (let at = lo; at < hi; at++) {
40
- const moved = after[at] === before[at - offset];
41
- if (moved)
42
- matching++;
43
- if (after[at] !== before[at]) {
44
- changed++;
45
- if (moved)
46
- explained++;
47
- }
48
- }
49
- if (changed < minLines)
50
- continue;
51
- const share = explained / changed;
52
- if (share >= minExplained && (!best || share > best.explained)) {
53
- best = { offset, coverage: matching / (hi - lo), explained: share };
54
- }
55
- }
56
- }
57
- return best;
58
- };
59
- const better = (a, b) => !b || (a && a.found.explained >= b.found.explained) ? a : b;
60
- /**
61
- * Is the screenshot the baseline with everything below some row moved up or
62
- * down, or everything right of some column moved left or right? That is what
63
- * an element that grew or shrank causes. One direction at a time.
64
- */
65
- const detectShift = (baseline, actual, options = {}) => {
66
- if (baseline.width !== actual.width || baseline.height !== actual.height) {
67
- return null;
68
- }
69
- const along = (axis) => {
70
- const length = axis === 'y' ? baseline.height : baseline.width;
71
- const across = {
72
- from: 0,
73
- to: axis === 'y' ? baseline.width : baseline.height,
74
- };
75
- const before = lineHashes(baseline, axis, 0, length, across);
76
- const after = lineHashes(actual, axis, 0, length, across);
77
- let first = 0;
78
- while (first < length && before[first] === after[first])
79
- first++;
80
- if (first === length)
81
- return null;
82
- const found = findOffset(before, after, first, length, options);
83
- return found && { axis, first, found };
84
- };
85
- const best = better(along('y'), along('x'));
86
- if (!best)
87
- return null;
88
- const { axis, first, found } = best;
89
- return {
90
- fromX: axis === 'x' ? first : 0,
91
- fromY: axis === 'y' ? first : 0,
92
- dx: axis === 'x' ? found.offset : 0,
93
- dy: axis === 'y' ? found.offset : 0,
94
- coverage: found.coverage,
95
- };
96
- };
97
- exports.detectShift = detectShift;
98
- /**
99
- * Did the content of one changed area only move, up, down, left or right? A
100
- * moved element leaves an area that covers its old and its new place; inside
101
- * it the screenshot equals the baseline a fixed number of pixels away.
102
- */
103
- const detectRegionShift = (baseline, actual, box, options = {}) => {
104
- if (baseline.width !== actual.width || baseline.height !== actual.height) {
105
- return null;
106
- }
107
- const reach = options.maxShift ?? 64;
108
- const along = (axis) => {
109
- const length = axis === 'y' ? baseline.height : baseline.width;
110
- const start = axis === 'y' ? box.y : box.x;
111
- const end = start + (axis === 'y' ? box.height : box.width);
112
- const across = axis === 'y'
113
- ? { from: box.x, to: box.x + box.width }
114
- : { from: box.y, to: box.y + box.height };
115
- // lines around the area too: the content came from, or went, outside of it
116
- const from = Math.max(0, start - reach);
117
- const to = Math.min(length, end + reach);
118
- const found = findOffset(lineHashes(baseline, axis, from, to, across), lineHashes(actual, axis, from, to, across), start - from, end - from, options);
119
- return found && { axis, found };
120
- };
121
- const best = better(along('y'), along('x'));
122
- if (!best)
123
- return null;
124
- return {
125
- dx: best.axis === 'x' ? best.found.offset : 0,
126
- dy: best.axis === 'y' ? best.found.offset : 0,
127
- };
128
- };
129
- exports.detectRegionShift = detectRegionShift;
package/dist/types.d.ts DELETED
@@ -1,76 +0,0 @@
1
- /** Decoded image: 8-bit RGBA, row by row. */
2
- export type RgbaImage = {
3
- width: number;
4
- height: number;
5
- data: Uint8ClampedArray | Uint8Array;
6
- };
7
- export type Size = {
8
- width: number;
9
- height: number;
10
- };
11
- export type Box = {
12
- x: number;
13
- y: number;
14
- width: number;
15
- height: number;
16
- };
17
- /**
18
- * Coarse shape of a changed area:
19
- * - `speck`: at most 4 px on either side;
20
- * - `band`: spans (almost) the whole width or height and is thin;
21
- * - `block`: anything else.
22
- */
23
- export type RegionKind = 'speck' | 'band' | 'block';
24
- export type Region = Box & {
25
- /** Differing pixels inside the box. */
26
- area: number;
27
- /** `area` as a share of the box, 0..1. */
28
- fillRatio: number;
29
- kind: RegionKind;
30
- /** Difference hash of the screenshot's pixels inside the box; the largest regions have one. */
31
- hash?: string;
32
- /** Set when the content of this area only moved, by this many pixels. */
33
- moved?: {
34
- dx: number;
35
- dy: number;
36
- };
37
- };
38
- /**
39
- * The whole screenshot equals the baseline moved by `dy` rows from row `fromY`
40
- * down, or by `dx` columns from column `fromX` to the right, for `coverage` of
41
- * those lines. One of `dx` and `dy` is 0, and so is the `from` of the other
42
- * direction.
43
- */
44
- export type Shift = {
45
- fromX: number;
46
- fromY: number;
47
- dx: number;
48
- dy: number;
49
- coverage: number;
50
- };
51
- export type Label = 'size-change' | 'moved' | 'noise-like' | 'content-change';
52
- /** What `extra.pixsame.analysis` of a manifest entry holds. */
53
- export type Analysis = {
54
- version: 1;
55
- label: Label;
56
- /** One sentence for a person. */
57
- description: string;
58
- /** Changed areas, largest first, at most 50. */
59
- regions: Region[];
60
- /** The areas that did not fit in `regions`. */
61
- truncated?: {
62
- count: number;
63
- area: number;
64
- };
65
- /** Share of the differing pixels that sit in specks; near 1 means rendering noise. */
66
- speckRatio: number;
67
- /** A move of everything below a row or right of a column; `null` when searched and not found. Areas that moved on their own have `moved` set instead. */
68
- shift: Shift | null;
69
- /** Both sizes, when they differed. */
70
- sizes?: {
71
- baseline: Size;
72
- actual: Size;
73
- };
74
- /** Entries with the same key changed in the same way. */
75
- bundleKey: string;
76
- };
package/dist/types.js DELETED
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });