@storysnap/cli 1.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/LICENSE +21 -0
- package/README.md +297 -0
- package/dist/api/client.js +156 -0
- package/dist/cli/commands/init.js +55 -0
- package/dist/cli/commands/login.js +114 -0
- package/dist/cli/commands/logout.js +36 -0
- package/dist/cli/commands/test.js +366 -0
- package/dist/cli/commands/update.js +229 -0
- package/dist/cli/index.js +93 -0
- package/dist/cli/reporter.js +140 -0
- package/dist/config/credentials.js +69 -0
- package/dist/config/loader.js +102 -0
- package/dist/config/schema.js +59 -0
- package/dist/core/compare.js +139 -0
- package/dist/core/screenshot.js +123 -0
- package/dist/core/storybook.js +124 -0
- package/dist/core/types.js +2 -0
- package/dist/storage/index.js +15 -0
- package/dist/storage/local.js +64 -0
- package/dist/storage/s3.js +109 -0
- package/package.json +79 -0
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import chalk from 'chalk';
|
|
2
|
+
import ora from 'ora';
|
|
3
|
+
export class Reporter {
|
|
4
|
+
spinner = null;
|
|
5
|
+
verbose;
|
|
6
|
+
constructor(options = {}) {
|
|
7
|
+
this.verbose = options.verbose ?? false;
|
|
8
|
+
}
|
|
9
|
+
startSpinner(text) {
|
|
10
|
+
this.spinner = ora(text).start();
|
|
11
|
+
}
|
|
12
|
+
updateSpinner(text) {
|
|
13
|
+
if (this.spinner) {
|
|
14
|
+
this.spinner.text = text;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
succeedSpinner(text) {
|
|
18
|
+
if (this.spinner) {
|
|
19
|
+
this.spinner.succeed(text);
|
|
20
|
+
this.spinner = null;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
failSpinner(text) {
|
|
24
|
+
if (this.spinner) {
|
|
25
|
+
this.spinner.fail(text);
|
|
26
|
+
this.spinner = null;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
stopSpinner() {
|
|
30
|
+
if (this.spinner) {
|
|
31
|
+
this.spinner.stop();
|
|
32
|
+
this.spinner = null;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
info(message) {
|
|
36
|
+
console.log(chalk.blue('ℹ'), message);
|
|
37
|
+
}
|
|
38
|
+
success(message) {
|
|
39
|
+
console.log(chalk.green('✓'), message);
|
|
40
|
+
}
|
|
41
|
+
warning(message) {
|
|
42
|
+
console.log(chalk.yellow('⚠'), message);
|
|
43
|
+
}
|
|
44
|
+
error(message) {
|
|
45
|
+
console.log(chalk.red('✗'), message);
|
|
46
|
+
}
|
|
47
|
+
newLine() {
|
|
48
|
+
console.log();
|
|
49
|
+
}
|
|
50
|
+
header(title) {
|
|
51
|
+
console.log();
|
|
52
|
+
console.log(chalk.bold.underline(title));
|
|
53
|
+
console.log();
|
|
54
|
+
}
|
|
55
|
+
reportResult(story, result) {
|
|
56
|
+
const storyName = `${story.title}/${story.name}`;
|
|
57
|
+
switch (result.status) {
|
|
58
|
+
case 'pass':
|
|
59
|
+
console.log(chalk.green(' ✓'), chalk.dim(storyName));
|
|
60
|
+
// Surface a pass that was not pixel-identical, so drift toward the
|
|
61
|
+
// tolerance is visible rather than silent.
|
|
62
|
+
if (result.diffPercentage) {
|
|
63
|
+
console.log(chalk.dim(` → ${result.diffPercentage.toFixed(3)}% differed, within tolerance`));
|
|
64
|
+
}
|
|
65
|
+
break;
|
|
66
|
+
case 'fail':
|
|
67
|
+
console.log(chalk.red(' ✗'), storyName);
|
|
68
|
+
if (result.diffPercentage !== undefined) {
|
|
69
|
+
console.log(chalk.dim(` → ${result.diffPixels} pixels different (${result.diffPercentage.toFixed(2)}%)`));
|
|
70
|
+
}
|
|
71
|
+
if (result.errorMessage) {
|
|
72
|
+
console.log(chalk.dim(` → ${result.errorMessage}`));
|
|
73
|
+
}
|
|
74
|
+
if (result.diffImagePath) {
|
|
75
|
+
console.log(chalk.dim(` → Diff saved: ${result.diffImagePath}`));
|
|
76
|
+
}
|
|
77
|
+
break;
|
|
78
|
+
case 'new':
|
|
79
|
+
console.log(chalk.yellow(' ○'), chalk.yellow(storyName), chalk.dim('(new)'));
|
|
80
|
+
break;
|
|
81
|
+
case 'error':
|
|
82
|
+
console.log(chalk.red(' ✗'), storyName, chalk.red('(error)'));
|
|
83
|
+
if (result.errorMessage) {
|
|
84
|
+
console.log(chalk.dim(` → ${result.errorMessage}`));
|
|
85
|
+
}
|
|
86
|
+
break;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
reportSummary(summary, maxDiffPercent) {
|
|
90
|
+
this.newLine();
|
|
91
|
+
console.log(chalk.bold('Summary:'));
|
|
92
|
+
this.newLine();
|
|
93
|
+
if (maxDiffPercent !== undefined) {
|
|
94
|
+
console.log(chalk.dim(` Tolerance: up to ${maxDiffPercent}% of pixels may differ`));
|
|
95
|
+
this.newLine();
|
|
96
|
+
}
|
|
97
|
+
const parts = [];
|
|
98
|
+
if (summary.passed > 0) {
|
|
99
|
+
parts.push(chalk.green(`${summary.passed} passed`));
|
|
100
|
+
}
|
|
101
|
+
if (summary.failed > 0) {
|
|
102
|
+
parts.push(chalk.red(`${summary.failed} failed`));
|
|
103
|
+
}
|
|
104
|
+
if (summary.newStories > 0) {
|
|
105
|
+
parts.push(chalk.yellow(`${summary.newStories} new`));
|
|
106
|
+
}
|
|
107
|
+
if (summary.errors > 0) {
|
|
108
|
+
parts.push(chalk.red(`${summary.errors} errors`));
|
|
109
|
+
}
|
|
110
|
+
console.log(` ${parts.join(', ')} of ${summary.total} stories`);
|
|
111
|
+
this.newLine();
|
|
112
|
+
if (summary.failed > 0 || summary.errors > 0) {
|
|
113
|
+
console.log(chalk.red('Visual regression tests failed.'), chalk.dim('Run "storysnap update" to update baselines if changes are intentional.'));
|
|
114
|
+
}
|
|
115
|
+
else if (summary.newStories > 0) {
|
|
116
|
+
console.log(chalk.yellow('New stories detected.'), chalk.dim('Run "storysnap update" to create baselines.'));
|
|
117
|
+
}
|
|
118
|
+
else {
|
|
119
|
+
console.log(chalk.green('All visual regression tests passed!'));
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
reportUpdateSummary(updated, total) {
|
|
123
|
+
this.newLine();
|
|
124
|
+
console.log(chalk.bold('Update Summary:'));
|
|
125
|
+
this.newLine();
|
|
126
|
+
console.log(` Updated ${chalk.green(updated)} of ${total} baselines`);
|
|
127
|
+
this.newLine();
|
|
128
|
+
}
|
|
129
|
+
formatStoryCount(count) {
|
|
130
|
+
return count === 1 ? '1 story' : `${count} stories`;
|
|
131
|
+
}
|
|
132
|
+
progress(current, total, message) {
|
|
133
|
+
const percentage = Math.round((current / total) * 100);
|
|
134
|
+
this.updateSpinner(`[${current}/${total}] ${percentage}% ${message}`);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
export function createReporter(options) {
|
|
138
|
+
return new Reporter(options);
|
|
139
|
+
}
|
|
140
|
+
//# sourceMappingURL=reporter.js.map
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { existsSync, mkdirSync } from 'node:fs';
|
|
2
|
+
import { readFile, writeFile, unlink } from 'node:fs/promises';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
const STORYSNAP_DIR = join(homedir(), '.storysnap');
|
|
6
|
+
const CREDENTIALS_FILE = join(STORYSNAP_DIR, 'credentials');
|
|
7
|
+
function ensureStorysnapDir() {
|
|
8
|
+
if (!existsSync(STORYSNAP_DIR)) {
|
|
9
|
+
mkdirSync(STORYSNAP_DIR, { recursive: true, mode: 0o700 });
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
export async function saveCredentials(credentials) {
|
|
13
|
+
ensureStorysnapDir();
|
|
14
|
+
const content = JSON.stringify(credentials, null, 2);
|
|
15
|
+
await writeFile(CREDENTIALS_FILE, content, { encoding: 'utf-8', mode: 0o600 });
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Credentials from the environment, if both parts are present.
|
|
19
|
+
*
|
|
20
|
+
* CI runners have no `storysnap login` step and no home directory to persist
|
|
21
|
+
* one, so this is how a pipeline authenticates.
|
|
22
|
+
*/
|
|
23
|
+
function credentialsFromEnv() {
|
|
24
|
+
const apiUrl = process.env.STORYSNAP_API_URL?.trim();
|
|
25
|
+
const apiToken = process.env.STORYSNAP_API_TOKEN?.trim();
|
|
26
|
+
if (apiUrl && apiToken) {
|
|
27
|
+
return { apiUrl: apiUrl.replace(/\/$/, ''), apiToken };
|
|
28
|
+
}
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
export async function loadCredentials() {
|
|
32
|
+
const fromEnv = credentialsFromEnv();
|
|
33
|
+
if (fromEnv) {
|
|
34
|
+
return fromEnv;
|
|
35
|
+
}
|
|
36
|
+
if (!existsSync(CREDENTIALS_FILE)) {
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
try {
|
|
40
|
+
const content = await readFile(CREDENTIALS_FILE, 'utf-8');
|
|
41
|
+
const parsed = JSON.parse(content);
|
|
42
|
+
if (typeof parsed.apiUrl !== 'string' || typeof parsed.apiToken !== 'string') {
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
return {
|
|
46
|
+
apiUrl: parsed.apiUrl,
|
|
47
|
+
apiToken: parsed.apiToken,
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
export async function deleteCredentials() {
|
|
55
|
+
if (!existsSync(CREDENTIALS_FILE)) {
|
|
56
|
+
return false;
|
|
57
|
+
}
|
|
58
|
+
try {
|
|
59
|
+
await unlink(CREDENTIALS_FILE);
|
|
60
|
+
return true;
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
export function getCredentialsPath() {
|
|
67
|
+
return CREDENTIALS_FILE;
|
|
68
|
+
}
|
|
69
|
+
//# sourceMappingURL=credentials.js.map
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { readFile } from 'node:fs/promises';
|
|
3
|
+
import { resolve, join } from 'node:path';
|
|
4
|
+
import { pathToFileURL } from 'node:url';
|
|
5
|
+
import { validateConfig } from './schema.js';
|
|
6
|
+
const CONFIG_FILE_NAMES = [
|
|
7
|
+
'storysnap.config.ts',
|
|
8
|
+
'storysnap.config.js',
|
|
9
|
+
'storysnap.config.mjs',
|
|
10
|
+
'storysnap.config.json',
|
|
11
|
+
];
|
|
12
|
+
export async function findConfigFile(cwd = process.cwd()) {
|
|
13
|
+
for (const fileName of CONFIG_FILE_NAMES) {
|
|
14
|
+
const filePath = join(cwd, fileName);
|
|
15
|
+
if (existsSync(filePath)) {
|
|
16
|
+
return filePath;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
return null;
|
|
20
|
+
}
|
|
21
|
+
export async function loadConfig(configPath, cwd = process.cwd()) {
|
|
22
|
+
const resolvedPath = configPath
|
|
23
|
+
? resolve(cwd, configPath)
|
|
24
|
+
: await findConfigFile(cwd);
|
|
25
|
+
if (!resolvedPath) {
|
|
26
|
+
throw new Error('No config file found. Create storysnap.config.ts or run "storysnap init"');
|
|
27
|
+
}
|
|
28
|
+
if (!existsSync(resolvedPath)) {
|
|
29
|
+
throw new Error(`Config file not found: ${resolvedPath}`);
|
|
30
|
+
}
|
|
31
|
+
let rawConfig;
|
|
32
|
+
if (resolvedPath.endsWith('.json')) {
|
|
33
|
+
const content = await readFile(resolvedPath, 'utf-8');
|
|
34
|
+
rawConfig = JSON.parse(content);
|
|
35
|
+
}
|
|
36
|
+
else {
|
|
37
|
+
// For .ts, .js, .mjs files - use dynamic import
|
|
38
|
+
// Note: For .ts files, the project should be run with tsx or ts-node
|
|
39
|
+
const fileUrl = pathToFileURL(resolvedPath).href;
|
|
40
|
+
const module = await import(fileUrl);
|
|
41
|
+
rawConfig = module.default || module;
|
|
42
|
+
}
|
|
43
|
+
try {
|
|
44
|
+
return validateConfig(rawConfig);
|
|
45
|
+
}
|
|
46
|
+
catch (error) {
|
|
47
|
+
if (error instanceof Error) {
|
|
48
|
+
throw new Error(`Invalid config: ${error.message}`);
|
|
49
|
+
}
|
|
50
|
+
throw error;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
export function getDefaultConfig() {
|
|
54
|
+
return `import type { StorySnapConfig } from '@storysnap/cli';
|
|
55
|
+
|
|
56
|
+
const config: StorySnapConfig = {
|
|
57
|
+
// Storybook location (choose one)
|
|
58
|
+
storybookUrl: 'http://localhost:6006',
|
|
59
|
+
// storybookStaticDir: './storybook-static',
|
|
60
|
+
|
|
61
|
+
// Storage configuration
|
|
62
|
+
storage: {
|
|
63
|
+
type: 's3',
|
|
64
|
+
bucket: 'my-snapshots',
|
|
65
|
+
region: 'us-east-1',
|
|
66
|
+
prefix: 'storysnap/',
|
|
67
|
+
},
|
|
68
|
+
|
|
69
|
+
// Screenshot settings
|
|
70
|
+
viewport: { width: 1280, height: 720 },
|
|
71
|
+
|
|
72
|
+
// Comparison settings.
|
|
73
|
+
// threshold - how different one pixel must be before it counts (0-1)
|
|
74
|
+
// maxDiffPercent - how much of the image may differ before failing (0-100).
|
|
75
|
+
// Set to 0 to fail on any change at all; expect that to be
|
|
76
|
+
// noisy when baselines and runs come from different machines.
|
|
77
|
+
threshold: 0.1,
|
|
78
|
+
maxDiffPercent: 0.1,
|
|
79
|
+
|
|
80
|
+
// Local snapshots directory (optional, for reviewing diffs)
|
|
81
|
+
localSnapshotsDir: './.snapshots',
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
export default config;
|
|
85
|
+
`;
|
|
86
|
+
}
|
|
87
|
+
export function getDefaultConfigJson() {
|
|
88
|
+
return JSON.stringify({
|
|
89
|
+
storybookUrl: 'http://localhost:6006',
|
|
90
|
+
storage: {
|
|
91
|
+
type: 's3',
|
|
92
|
+
bucket: 'my-snapshots',
|
|
93
|
+
region: 'us-east-1',
|
|
94
|
+
prefix: 'storysnap/',
|
|
95
|
+
},
|
|
96
|
+
viewport: { width: 1280, height: 720 },
|
|
97
|
+
threshold: 0.1,
|
|
98
|
+
maxDiffPercent: 0.1,
|
|
99
|
+
localSnapshotsDir: './.snapshots',
|
|
100
|
+
}, null, 2);
|
|
101
|
+
}
|
|
102
|
+
//# sourceMappingURL=loader.js.map
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
const viewportSchema = z.object({
|
|
3
|
+
width: z.number().min(1).default(1280),
|
|
4
|
+
height: z.number().min(1).default(720),
|
|
5
|
+
});
|
|
6
|
+
const browserSchema = z.enum(['chromium', 'firefox', 'webkit']);
|
|
7
|
+
const s3StorageSchema = z.object({
|
|
8
|
+
type: z.literal('s3'),
|
|
9
|
+
bucket: z.string().min(1),
|
|
10
|
+
region: z.string().min(1),
|
|
11
|
+
prefix: z.string().optional(),
|
|
12
|
+
endpoint: z.string().optional(),
|
|
13
|
+
accessKeyId: z.string().optional(),
|
|
14
|
+
secretAccessKey: z.string().optional(),
|
|
15
|
+
});
|
|
16
|
+
const localStorageSchema = z.object({
|
|
17
|
+
type: z.literal('local'),
|
|
18
|
+
directory: z.string().min(1),
|
|
19
|
+
});
|
|
20
|
+
const storageSchema = z.discriminatedUnion('type', [
|
|
21
|
+
s3StorageSchema,
|
|
22
|
+
localStorageSchema,
|
|
23
|
+
]);
|
|
24
|
+
export const configSchema = z.object({
|
|
25
|
+
storybookUrl: z.string().url().optional(),
|
|
26
|
+
storybookStaticDir: z.string().optional(),
|
|
27
|
+
// Only used by local mode; in API mode the server owns storage. Defaulted so
|
|
28
|
+
// a cloud-only config does not have to declare storage it never touches.
|
|
29
|
+
storage: storageSchema.default({ type: 'local', directory: '.storysnap/baselines' }),
|
|
30
|
+
viewport: viewportSchema.default({ width: 1280, height: 720 }),
|
|
31
|
+
browsers: z.array(browserSchema).default(['chromium']),
|
|
32
|
+
// The two comparison settings are deliberately left undefined when the config
|
|
33
|
+
// omits them, rather than defaulted here. In API mode an undefined value is
|
|
34
|
+
// omitted from the request so the server applies the project's own default -
|
|
35
|
+
// defaulting here would silently override whatever was set with
|
|
36
|
+
// `PATCH /projects/me` and make that endpoint pointless. Local mode falls back
|
|
37
|
+
// to DEFAULT_THRESHOLD / DEFAULT_MAX_DIFF_PERCENT at the comparison itself.
|
|
38
|
+
//
|
|
39
|
+
// pixelmatch's per-pixel colour sensitivity: how different one pixel must be
|
|
40
|
+
// before it is counted at all. Not an allowance for how much may change.
|
|
41
|
+
threshold: z.number().min(0).max(1).optional(),
|
|
42
|
+
// How much of the image may differ before a story fails, as a percentage.
|
|
43
|
+
// Screenshots captured on different machines differ slightly even when
|
|
44
|
+
// nothing changed - different rasterizers, different glyph shapes - so 0
|
|
45
|
+
// means any run whose baseline came from elsewhere fails wholesale.
|
|
46
|
+
maxDiffPercent: z.number().min(0).max(100).optional(),
|
|
47
|
+
localSnapshotsDir: z.string().optional(),
|
|
48
|
+
include: z.array(z.string()).optional(),
|
|
49
|
+
exclude: z.array(z.string()).optional(),
|
|
50
|
+
waitForSelector: z.string().default('#storybook-root'),
|
|
51
|
+
waitTimeout: z.number().min(0).default(30000),
|
|
52
|
+
// API configuration (optional - can also use ~/.storysnap/credentials)
|
|
53
|
+
apiUrl: z.string().url().optional(),
|
|
54
|
+
apiToken: z.string().optional(),
|
|
55
|
+
}).refine((data) => data.storybookUrl || data.storybookStaticDir, { message: 'Either storybookUrl or storybookStaticDir must be provided' });
|
|
56
|
+
export function validateConfig(input) {
|
|
57
|
+
return configSchema.parse(input);
|
|
58
|
+
}
|
|
59
|
+
//# sourceMappingURL=schema.js.map
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import pixelmatch from 'pixelmatch';
|
|
2
|
+
import { PNG } from 'pngjs';
|
|
3
|
+
import { getStoryKey } from './storybook.js';
|
|
4
|
+
import { ensureDir } from '../storage/local.js';
|
|
5
|
+
import { writeFile } from 'node:fs/promises';
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
/**
|
|
8
|
+
* Local-mode fallbacks. In API mode the equivalent defaults live on the
|
|
9
|
+
* `projects` row so they can be changed without editing a config file; there is
|
|
10
|
+
* no server here to ask, so the same numbers are repeated.
|
|
11
|
+
*/
|
|
12
|
+
export const DEFAULT_THRESHOLD = 0.1;
|
|
13
|
+
export const DEFAULT_MAX_DIFF_PERCENT = 0.1;
|
|
14
|
+
export async function compareScreenshot(screenshot, options) {
|
|
15
|
+
// Use browser-aware storage key
|
|
16
|
+
const storyKey = getStoryKey(screenshot.storyId, screenshot.browser);
|
|
17
|
+
// Check for capture error
|
|
18
|
+
if (screenshot.buffer.length === 0) {
|
|
19
|
+
return {
|
|
20
|
+
storyId: screenshot.storyId,
|
|
21
|
+
browser: screenshot.browser,
|
|
22
|
+
status: 'error',
|
|
23
|
+
errorMessage: 'Failed to capture screenshot',
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
const threshold = options.threshold ?? DEFAULT_THRESHOLD;
|
|
27
|
+
const maxDiffPercent = options.maxDiffPercent ?? DEFAULT_MAX_DIFF_PERCENT;
|
|
28
|
+
// Try to fetch baseline from storage
|
|
29
|
+
const baselineBuffer = await options.storage.download(storyKey);
|
|
30
|
+
if (!baselineBuffer) {
|
|
31
|
+
// No baseline exists - this is a new story
|
|
32
|
+
return {
|
|
33
|
+
storyId: screenshot.storyId,
|
|
34
|
+
browser: screenshot.browser,
|
|
35
|
+
status: 'new',
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
try {
|
|
39
|
+
// Parse PNG images
|
|
40
|
+
const currentPng = PNG.sync.read(screenshot.buffer);
|
|
41
|
+
const baselinePng = PNG.sync.read(baselineBuffer);
|
|
42
|
+
// Check dimensions match
|
|
43
|
+
if (currentPng.width !== baselinePng.width || currentPng.height !== baselinePng.height) {
|
|
44
|
+
// Dimensions changed - treat as a diff
|
|
45
|
+
const diffImagePath = await saveDiffImage(screenshot, baselineBuffer, options.localSnapshotsDir);
|
|
46
|
+
return {
|
|
47
|
+
storyId: screenshot.storyId,
|
|
48
|
+
browser: screenshot.browser,
|
|
49
|
+
status: 'fail',
|
|
50
|
+
diffPercentage: 100,
|
|
51
|
+
diffPixels: currentPng.width * currentPng.height,
|
|
52
|
+
diffImagePath,
|
|
53
|
+
errorMessage: `Dimensions changed: ${baselinePng.width}x${baselinePng.height} → ${currentPng.width}x${currentPng.height}`,
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
// Create diff image buffer
|
|
57
|
+
const diffPng = new PNG({ width: currentPng.width, height: currentPng.height });
|
|
58
|
+
// Run pixelmatch comparison
|
|
59
|
+
const diffPixels = pixelmatch(baselinePng.data, currentPng.data, diffPng.data, currentPng.width, currentPng.height, { threshold });
|
|
60
|
+
const totalPixels = currentPng.width * currentPng.height;
|
|
61
|
+
const diffPercentage = (diffPixels / totalPixels) * 100;
|
|
62
|
+
if (diffPercentage <= maxDiffPercent) {
|
|
63
|
+
return {
|
|
64
|
+
storyId: screenshot.storyId,
|
|
65
|
+
browser: screenshot.browser,
|
|
66
|
+
status: 'pass',
|
|
67
|
+
diffPercentage,
|
|
68
|
+
diffPixels,
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
// Save diff image if there are differences
|
|
72
|
+
const diffImagePath = await saveDiffImageFromPng(screenshot.storyId, screenshot.browser, diffPng, screenshot.buffer, baselineBuffer, options.localSnapshotsDir);
|
|
73
|
+
return {
|
|
74
|
+
storyId: screenshot.storyId,
|
|
75
|
+
browser: screenshot.browser,
|
|
76
|
+
status: 'fail',
|
|
77
|
+
diffPercentage,
|
|
78
|
+
diffPixels,
|
|
79
|
+
diffImagePath,
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
catch (error) {
|
|
83
|
+
return {
|
|
84
|
+
storyId: screenshot.storyId,
|
|
85
|
+
browser: screenshot.browser,
|
|
86
|
+
status: 'error',
|
|
87
|
+
errorMessage: error instanceof Error ? error.message : 'Unknown comparison error',
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
async function saveDiffImage(screenshot, baselineBuffer, localSnapshotsDir) {
|
|
92
|
+
if (!localSnapshotsDir) {
|
|
93
|
+
return undefined;
|
|
94
|
+
}
|
|
95
|
+
const diffDir = join(localSnapshotsDir, 'diffs');
|
|
96
|
+
await ensureDir(diffDir);
|
|
97
|
+
const baseName = getStoryKey(screenshot.storyId, screenshot.browser).replace('.png', '');
|
|
98
|
+
// Save current screenshot
|
|
99
|
+
const currentPath = join(diffDir, `${baseName}.current.png`);
|
|
100
|
+
await writeFile(currentPath, screenshot.buffer);
|
|
101
|
+
// Save baseline
|
|
102
|
+
const baselinePath = join(diffDir, `${baseName}.baseline.png`);
|
|
103
|
+
await writeFile(baselinePath, baselineBuffer);
|
|
104
|
+
return currentPath;
|
|
105
|
+
}
|
|
106
|
+
async function saveDiffImageFromPng(storyId, browser, diffPng, currentBuffer, baselineBuffer, localSnapshotsDir) {
|
|
107
|
+
if (!localSnapshotsDir) {
|
|
108
|
+
return undefined;
|
|
109
|
+
}
|
|
110
|
+
const diffDir = join(localSnapshotsDir, 'diffs');
|
|
111
|
+
await ensureDir(diffDir);
|
|
112
|
+
const baseName = getStoryKey(storyId, browser).replace('.png', '');
|
|
113
|
+
// Save diff image
|
|
114
|
+
const diffPath = join(diffDir, `${baseName}.diff.png`);
|
|
115
|
+
const diffBuffer = PNG.sync.write(diffPng);
|
|
116
|
+
await writeFile(diffPath, diffBuffer);
|
|
117
|
+
// Save current screenshot
|
|
118
|
+
const currentPath = join(diffDir, `${baseName}.current.png`);
|
|
119
|
+
await writeFile(currentPath, currentBuffer);
|
|
120
|
+
// Save baseline
|
|
121
|
+
const baselinePath = join(diffDir, `${baseName}.baseline.png`);
|
|
122
|
+
await writeFile(baselinePath, baselineBuffer);
|
|
123
|
+
return diffPath;
|
|
124
|
+
}
|
|
125
|
+
export async function compareAllScreenshots(screenshots, options, onProgress) {
|
|
126
|
+
const results = new Map();
|
|
127
|
+
let completed = 0;
|
|
128
|
+
const total = screenshots.size;
|
|
129
|
+
for (const [key, screenshot] of screenshots) {
|
|
130
|
+
const result = await compareScreenshot(screenshot, options);
|
|
131
|
+
results.set(key, result);
|
|
132
|
+
completed++;
|
|
133
|
+
if (onProgress) {
|
|
134
|
+
onProgress(completed, total, key);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return results;
|
|
138
|
+
}
|
|
139
|
+
//# sourceMappingURL=compare.js.map
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { chromium, firefox, webkit } from 'playwright';
|
|
2
|
+
import { getStoryUrl } from './storybook.js';
|
|
3
|
+
const BROWSER_MAP = {
|
|
4
|
+
chromium,
|
|
5
|
+
firefox,
|
|
6
|
+
webkit,
|
|
7
|
+
};
|
|
8
|
+
export class ScreenshotEngine {
|
|
9
|
+
browsers = new Map();
|
|
10
|
+
config;
|
|
11
|
+
baseUrl;
|
|
12
|
+
constructor(config) {
|
|
13
|
+
this.config = config;
|
|
14
|
+
this.baseUrl = config.storybookUrl || `file://${config.storybookStaticDir}`;
|
|
15
|
+
}
|
|
16
|
+
async initialize() {
|
|
17
|
+
// Launch all configured browsers
|
|
18
|
+
for (const browserName of this.config.browsers) {
|
|
19
|
+
const browserType = BROWSER_MAP[browserName];
|
|
20
|
+
if (!browserType) {
|
|
21
|
+
throw new Error(`Unsupported browser: ${browserName}`);
|
|
22
|
+
}
|
|
23
|
+
const browser = await browserType.launch({
|
|
24
|
+
headless: true,
|
|
25
|
+
});
|
|
26
|
+
this.browsers.set(browserName, browser);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
async close() {
|
|
30
|
+
for (const browser of this.browsers.values()) {
|
|
31
|
+
await browser.close();
|
|
32
|
+
}
|
|
33
|
+
this.browsers.clear();
|
|
34
|
+
}
|
|
35
|
+
async captureStory(story, browserName) {
|
|
36
|
+
const browser = this.browsers.get(browserName);
|
|
37
|
+
if (!browser) {
|
|
38
|
+
throw new Error(`Browser ${browserName} not initialized. Call initialize() first.`);
|
|
39
|
+
}
|
|
40
|
+
const page = await browser.newPage({
|
|
41
|
+
viewport: this.config.viewport,
|
|
42
|
+
});
|
|
43
|
+
try {
|
|
44
|
+
const url = getStoryUrl(this.baseUrl, story.id);
|
|
45
|
+
await page.goto(url, { waitUntil: 'networkidle' });
|
|
46
|
+
// Wait for the story root element to be visible
|
|
47
|
+
const selector = this.config.waitForSelector ?? '#storybook-root';
|
|
48
|
+
await page.waitForSelector(selector, {
|
|
49
|
+
state: 'visible',
|
|
50
|
+
timeout: this.config.waitTimeout,
|
|
51
|
+
});
|
|
52
|
+
// Additional wait for any animations or lazy loading
|
|
53
|
+
await this.waitForStability(page);
|
|
54
|
+
const buffer = await page.screenshot({
|
|
55
|
+
fullPage: false,
|
|
56
|
+
type: 'png',
|
|
57
|
+
});
|
|
58
|
+
return {
|
|
59
|
+
storyId: story.id,
|
|
60
|
+
browser: browserName,
|
|
61
|
+
buffer: Buffer.from(buffer),
|
|
62
|
+
width: this.config.viewport.width,
|
|
63
|
+
height: this.config.viewport.height,
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
finally {
|
|
67
|
+
await page.close();
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
async captureStories(stories, onProgress) {
|
|
71
|
+
const screenshots = new Map();
|
|
72
|
+
const totalTests = stories.length * this.config.browsers.length;
|
|
73
|
+
let completed = 0;
|
|
74
|
+
for (const story of stories) {
|
|
75
|
+
for (const browserName of this.config.browsers) {
|
|
76
|
+
const screenshotKey = getScreenshotKey(story.id, browserName);
|
|
77
|
+
try {
|
|
78
|
+
const screenshot = await this.captureStory(story, browserName);
|
|
79
|
+
screenshots.set(screenshotKey, screenshot);
|
|
80
|
+
}
|
|
81
|
+
catch (error) {
|
|
82
|
+
// Store error indicator - will be handled by comparison
|
|
83
|
+
screenshots.set(screenshotKey, {
|
|
84
|
+
storyId: story.id,
|
|
85
|
+
browser: browserName,
|
|
86
|
+
buffer: Buffer.alloc(0),
|
|
87
|
+
width: 0,
|
|
88
|
+
height: 0,
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
completed++;
|
|
92
|
+
if (onProgress) {
|
|
93
|
+
onProgress(completed, totalTests, story, browserName);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return screenshots;
|
|
98
|
+
}
|
|
99
|
+
async waitForStability(page) {
|
|
100
|
+
// Wait for network to be idle
|
|
101
|
+
await page.waitForLoadState('networkidle');
|
|
102
|
+
// Wait a short time for any CSS animations to complete and render to stabilize
|
|
103
|
+
await page.waitForTimeout(200);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
export function getScreenshotKey(storyId, browser) {
|
|
107
|
+
return `${storyId}::${browser}`;
|
|
108
|
+
}
|
|
109
|
+
export function parseScreenshotKey(key) {
|
|
110
|
+
const [storyId, browser] = key.split('::');
|
|
111
|
+
return { storyId, browser: browser };
|
|
112
|
+
}
|
|
113
|
+
export async function captureScreenshots(config, stories, onProgress) {
|
|
114
|
+
const engine = new ScreenshotEngine(config);
|
|
115
|
+
try {
|
|
116
|
+
await engine.initialize();
|
|
117
|
+
return await engine.captureStories(stories, onProgress);
|
|
118
|
+
}
|
|
119
|
+
finally {
|
|
120
|
+
await engine.close();
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
//# sourceMappingURL=screenshot.js.map
|