@iqual/playwright-vrt 0.1.1 → 0.1.3

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/src/cli.ts DELETED
@@ -1,339 +0,0 @@
1
- #!/usr/bin/env bun
2
-
3
- import * as path from 'path';
4
- import * as fs from 'fs';
5
- import { loadConfig, validateConfig, type CLIOptions } from './config';
6
- import { collectURLs } from './collect';
7
- import { runVisualTests, printResults, hasExistingSnapshots } from './runner';
8
- import { createHash } from 'crypto';
9
-
10
- /**
11
- * Compute SHA-256 hash of a file
12
- */
13
- function computeFileHash(filePath: string): string {
14
- const content = fs.readFileSync(filePath, 'utf-8');
15
- return createHash('sha256').update(content).digest('hex');
16
- }
17
-
18
- /**
19
- * Compute SHA-256 hash of a config object
20
- */
21
- function computeConfigHash(config: any): string {
22
- // Create a stable JSON representation (sorted keys)
23
- const configStr = JSON.stringify(config, Object.keys(config).sort());
24
- return createHash('sha256').update(configStr).digest('hex');
25
- }
26
-
27
- /**
28
- * Check if cache is valid by comparing stored hashes
29
- */
30
- function isCacheValid(snapshotDir: string, config: any): boolean {
31
- const hashFile = path.join(snapshotDir, '.cache-hash.json');
32
-
33
- if (!fs.existsSync(hashFile)) {
34
- return false;
35
- }
36
-
37
- try {
38
- const stored = JSON.parse(fs.readFileSync(hashFile, 'utf-8'));
39
- const packageDir = path.join(__dirname, '..');
40
- const testFilePath = path.join(packageDir, 'tests', 'vrt.spec.ts');
41
-
42
- const currentHashes = {
43
- config: computeConfigHash(config),
44
- testFile: fs.existsSync(testFilePath) ? computeFileHash(testFilePath) : '',
45
- };
46
-
47
- // Log cache timestamp
48
- console.log(` Cache timestamp: ${stored.timestamp}`);
49
-
50
- return stored.config === currentHashes.config &&
51
- stored.testFile === currentHashes.testFile;
52
- } catch {
53
- return false;
54
- }
55
- }
56
-
57
- /**
58
- * Save current config and test file hashes to cache
59
- */
60
- function saveCacheHashes(snapshotDir: string, config: any): void {
61
- const packageDir = path.join(__dirname, '..');
62
- const testFilePath = path.join(packageDir, 'tests', 'vrt.spec.ts');
63
-
64
- const hashes = {
65
- config: computeConfigHash(config),
66
- testFile: fs.existsSync(testFilePath) ? computeFileHash(testFilePath) : '',
67
- timestamp: new Date().toISOString(),
68
- };
69
-
70
- const hashFile = path.join(snapshotDir, '.cache-hash.json');
71
- fs.writeFileSync(hashFile, JSON.stringify(hashes, null, 2), 'utf-8');
72
- }
73
-
74
- async function main() {
75
- const args = parseArgs();
76
-
77
- // Either --config or --test is required
78
- if (!args.config && !args.test) {
79
- console.error('Error: Either --config or --test is required');
80
- printUsage();
81
- process.exit(2);
82
- }
83
-
84
- try {
85
- // Load and validate configuration
86
- let config;
87
- let configPath: string | undefined;
88
-
89
- if (args.config) {
90
- // Load from config file
91
- configPath = path.resolve(args.config);
92
- config = await loadConfig(configPath);
93
- } else {
94
- // Use defaults
95
- const { DEFAULT_CONFIG } = await import('./config');
96
- config = { ...DEFAULT_CONFIG } as any;
97
- }
98
-
99
- // Override with CLI args
100
- if (args.test) config.testUrl = args.test;
101
- if (args.reference) config.referenceUrl = args.reference;
102
-
103
- let hasExplicitReference = true;
104
-
105
- // If no reference URL set, default to test URL
106
- if (!config.referenceUrl && config.testUrl) {
107
- config.referenceUrl = config.testUrl;
108
- hasExplicitReference = false;
109
- }
110
-
111
- if (args.maxUrls) config.maxUrls = args.maxUrls;
112
-
113
- validateConfig(config);
114
-
115
- console.log('🚀 Starting Visual Regression Testing');
116
- console.log(` Reference: ${config.referenceUrl}`);
117
- console.log(` Test: ${config.testUrl}`);
118
-
119
- // Create snapshot directory for URLs and snapshots
120
- const snapshotDir = path.resolve('playwright-snapshots');
121
- const outputDir = path.resolve(args.output || 'playwright-report');
122
-
123
- if (!fs.existsSync(snapshotDir)) {
124
- fs.mkdirSync(snapshotDir, { recursive: true });
125
- }
126
-
127
- if (args.verbose) {
128
- console.log(`📁 Snapshots: ${snapshotDir}`);
129
- console.log(`📁 Output: ${outputDir}`);
130
- }
131
-
132
- // Check if URLs already exist (unless --update-baseline)
133
- const urlsPath = path.join(snapshotDir, 'urls.json');
134
- let urls: string[] = [];
135
-
136
- // Check cache validity based on config object and test file hashes
137
- const cacheValid = isCacheValid(snapshotDir, config);
138
- const shouldRegenerate = args.updateBaseline || !cacheValid;
139
-
140
- if (!hasExplicitReference && !cacheValid && !args.updateBaseline) {
141
- console.error('\n❌ Error: No baseline snapshots found and no reference URL provided.');
142
- console.error(' Either:');
143
- console.error(' 1. Provide --reference <url> to create baseline from a reference system');
144
- console.error(' 2. Use --update-baseline to create baseline from test URL');
145
- console.error(' 3. Add referenceUrl to your config file\n');
146
- process.exit(2);
147
- }
148
-
149
- if (fs.existsSync(urlsPath) && !shouldRegenerate) {
150
- // Load existing URLs
151
- console.log('\n📋 Using cached URLs from previous run');
152
- urls = JSON.parse(fs.readFileSync(urlsPath, 'utf-8'));
153
- console.log(`✓ Loaded ${urls.length} URLs from cache`);
154
-
155
- if (args.verbose) {
156
- console.log(' (Use --update-baseline to regenerate URLs)');
157
- }
158
- } else {
159
- // Collect URLs from sitemap/crawler
160
- if (args.updateBaseline) {
161
- console.log('\n🔄 Updating baseline (regenerating URLs)...');
162
- } else if (!cacheValid && fs.existsSync(urlsPath)) {
163
- console.log('\n🔄 Config or test file changed, regenerating URLs...');
164
- } else {
165
- console.log('\n🔍 Collecting URLs (first run)...');
166
- }
167
-
168
- console.log(` Source: ${config.referenceUrl}${config.sitemapPath || '/sitemap.xml'}`);
169
- const urlResult = await collectURLs(config);
170
-
171
- console.log(`✓ Found ${urlResult.total} URLs, filtered to ${urlResult.filtered}, using top ${urlResult.urls.length}`);
172
- console.log(` Source: ${urlResult.source}`);
173
-
174
- urls = urlResult.urls;
175
-
176
- // Save URLs to snapshot directory (co-located with snapshots for easy caching)
177
- fs.writeFileSync(urlsPath, JSON.stringify(urls, null, 2), 'utf-8');
178
-
179
- // Save cache hashes based on final config object
180
- saveCacheHashes(snapshotDir, config);
181
- }
182
-
183
- if (urls.length === 0) {
184
- throw new Error('No URLs found to test');
185
- }
186
-
187
- if (args.verbose) {
188
- console.log('\n📝 URLs to test:');
189
- urls.forEach((url, i) => console.log(` ${i + 1}. ${url}`));
190
- }
191
-
192
- // Run visual regression tests using shipped Playwright config and tests
193
- const results = await runVisualTests({
194
- config,
195
- outputDir,
196
- verbose: args.verbose,
197
- project: args.project,
198
- updateBaseline: shouldRegenerate,
199
- hasExplicitReference,
200
- headed: args.headed,
201
- });
202
-
203
- // Print results
204
- printResults(results, config);
205
-
206
- // Report location
207
- const reportPath = path.join(outputDir, 'index.html');
208
- console.log(`\n📊 Report: ${reportPath}`);
209
-
210
- if (args.verbose) {
211
- console.log(`📁 Snapshots: ${snapshotDir}`);
212
- }
213
-
214
- // Exit with appropriate code
215
- process.exit(results.failed > 0 ? 1 : 0);
216
- } catch (error) {
217
- console.error('\n❌ Error:', error instanceof Error ? error.message : error);
218
- if (args.verbose && error instanceof Error) {
219
- console.error(error.stack);
220
- }
221
- process.exit(2);
222
- }
223
- }
224
-
225
- function parseArgs(): CLIOptions {
226
- const args: CLIOptions = {
227
- config: '',
228
- };
229
-
230
- for (let i = 2; i < process.argv.length; i++) {
231
- const arg = process.argv[i];
232
- const next = process.argv[i + 1];
233
-
234
- switch (arg) {
235
- case '--reference':
236
- args.reference = next;
237
- i++;
238
- break;
239
- case '--test':
240
- args.test = next;
241
- i++;
242
- break;
243
- case '--config':
244
- args.config = next;
245
- i++;
246
- break;
247
- case '--output':
248
- args.output = next;
249
- i++;
250
- break;
251
- case '--max-urls':
252
- args.maxUrls = parseInt(next, 10);
253
- i++;
254
- break;
255
- case '--project':
256
- args.project = next;
257
- i++;
258
- break;
259
- case '--verbose':
260
- args.verbose = true;
261
- break;
262
- case '--headed':
263
- args.headed = true;
264
- break;
265
- case '--update-baseline':
266
- args.updateBaseline = true;
267
- break;
268
- case '--clean':
269
- // Clean snapshots and reports
270
- console.log('🗑️ Cleaning...');
271
- ['playwright-snapshots', 'playwright-report', 'playwright-tmp'].forEach(dir => {
272
- const fullPath = path.resolve(dir);
273
- if (fs.existsSync(fullPath)) {
274
- fs.rmSync(fullPath, { recursive: true, force: true });
275
- console.log(` Removed: ${dir}/`);
276
- }
277
- });
278
- console.log('✓ Clean complete');
279
- process.exit(0);
280
- break;
281
- case '--help':
282
- case '-h':
283
- printUsage();
284
- process.exit(0);
285
- break;
286
- }
287
- }
288
-
289
- return args;
290
- }
291
-
292
- function printUsage(): void {
293
- console.log(`
294
- Usage: playwright-vrt run [options]
295
-
296
- Required (one of):
297
- --test <url> Test URL
298
- --config <path> Path to config file with testUrl/referenceUrl
299
-
300
- Optional:
301
- --reference <url> Reference URL (defaults to --test URL or config)
302
- --output <dir> Output directory (default: ./playwright-report)
303
- --max-urls <number> Override config maxUrls
304
- --project <name> Playwright project to run (default: all)
305
- --verbose Detailed logging
306
- --headed Run browser in headed mode (visible)
307
- --update-baseline Force regenerate URLs and baseline snapshots
308
- --clean Clean playwright-snapshots/ and playwright-report/
309
- --help, -h Show this help message
310
-
311
- Examples:
312
- # Minimal - compare staging against itself (first run creates baseline)
313
- bunx playwright-vrt run --test https://staging.example.com
314
-
315
- # Compare staging against production
316
- bunx playwright-vrt run \\
317
- --reference https://production.com \\
318
- --test https://staging.com
319
-
320
- # With config file only (contains testUrl and referenceUrl)
321
- bunx playwright-vrt run --config ./playwright-vrt.config.json
322
-
323
- # With config file + URL override
324
- bunx playwright-vrt run \\
325
- --test https://preview-123.staging.com \\
326
- --config ./playwright-vrt.config.json
327
-
328
- Directories:
329
- playwright-snapshots/ Baseline snapshots and URLs (cache this!)
330
- playwright-report/ HTML test report
331
- playwright-tmp/ Temporary test artifacts (cleared on each run)
332
-
333
- Clean with: playwright-vrt run --clean
334
- Or manually: rm -rf playwright-snapshots playwright-report playwright-tmp
335
- `);
336
- }
337
-
338
- // Run the CLI
339
- main();
package/src/collect.ts DELETED
@@ -1,171 +0,0 @@
1
- #!/usr/bin/env bun
2
-
3
- import Sitemapper from 'sitemapper';
4
- import micromatch from 'micromatch';
5
- import { chromium } from 'playwright';
6
- import type { VRTConfig } from './config';
7
-
8
- export interface URLCollectionResult {
9
- urls: string[];
10
- source: 'sitemap' | 'crawl';
11
- total: number;
12
- filtered: number;
13
- }
14
-
15
- export async function collectURLs(config: VRTConfig): Promise<URLCollectionResult> {
16
- let urls: string[] = [];
17
- let source: 'sitemap' | 'crawl' = 'sitemap';
18
-
19
- // Try sitemap first
20
- try {
21
- urls = await collectFromSitemap(config.referenceUrl, config.sitemapPath || '/sitemap.xml');
22
- } catch (error) {
23
- console.warn('⚠️ Sitemap fetch failed, falling back to crawler');
24
- // Fallback to crawling
25
- urls = await crawlWebsite(config.referenceUrl, config.crawlOptions);
26
- source = 'crawl';
27
- }
28
-
29
- const totalUrls = urls.length;
30
-
31
- // Filter URLs
32
- urls = filterURLs(urls, config.referenceUrl, config.include || ['*'], config.exclude || []);
33
-
34
- // Remove duplicate URLs but keep order
35
- urls = Array.from(new Set(urls));
36
-
37
- // Limit to maxUrls
38
- const maxUrls = config.maxUrls || 25;
39
- const filteredCount = urls.length;
40
- urls = urls.slice(0, maxUrls);
41
-
42
- return {
43
- urls,
44
- source,
45
- total: totalUrls,
46
- filtered: filteredCount,
47
- };
48
- }
49
-
50
- async function collectFromSitemap(baseUrl: string, sitemapPath: string): Promise<string[]> {
51
- const sitemapUrl = new URL(sitemapPath, baseUrl).toString();
52
-
53
- const sitemap = new Sitemapper({
54
- url: sitemapUrl,
55
- timeout: 15000,
56
- });
57
-
58
- const { sites } = await sitemap.fetch();
59
-
60
- if (!sites || sites.length === 0) {
61
- throw new Error('No URLs found in sitemap');
62
- }
63
-
64
- return sites;
65
- }
66
-
67
- async function crawlWebsite(
68
- baseUrl: string,
69
- options?: VRTConfig['crawlOptions']
70
- ): Promise<string[]> {
71
- const urls = new Set<string>();
72
-
73
- console.log(' Using crawler (homepage links only)...');
74
-
75
- const browser = await chromium.launch({ headless: true });
76
- const page = await browser.newPage();
77
-
78
- const baseUrlObj = new URL(baseUrl);
79
-
80
- try {
81
- // Visit the homepage
82
- await page.goto(baseUrl, {
83
- waitUntil: 'networkidle',
84
- timeout: 30000
85
- });
86
-
87
- // Add the homepage itself, by adding the current page URL
88
- urls.add(page.url());
89
-
90
- // Extract all links from the page
91
- const links = await page.evaluate(() => {
92
- // @ts-ignore - runs in browser context
93
- const anchors = Array.from(document.querySelectorAll('a[href]'));
94
- // @ts-ignore - runs in browser context
95
- return anchors.map(a => (a as HTMLAnchorElement).href);
96
- });
97
-
98
- // Filter links to same domain and add to set
99
- for (const link of links) {
100
- try {
101
- const linkUrl = new URL(link);
102
-
103
- // Only include links from the same domain
104
- if (linkUrl.hostname === baseUrlObj.hostname) {
105
- // Normalize URL (remove hash)
106
- linkUrl.hash = '';
107
- const normalizedUrl = linkUrl.toString();
108
-
109
- if (options?.removeTrailingSlash) {
110
- // Remove trailing slash for consistency (except for root)
111
- const cleanUrl = normalizedUrl.endsWith('/') && normalizedUrl !== baseUrl + '/'
112
- ? normalizedUrl.slice(0, -1)
113
- : normalizedUrl;
114
- urls.add(cleanUrl);
115
- } else {
116
- urls.add(normalizedUrl);
117
- }
118
- }
119
- } catch {
120
- // Skip invalid URLs
121
- }
122
- }
123
-
124
- console.log(` Found ${urls.size} URLs from homepage`);
125
-
126
- } catch (error) {
127
- console.error(' Crawler error:', error instanceof Error ? error.message : error);
128
- // At minimum, return the base URL
129
- urls.add(baseUrl);
130
- } finally {
131
- await browser.close();
132
- }
133
-
134
- return Array.from(urls);
135
- }
136
-
137
- function filterURLs(urls: string[], baseUrl: string, include: string[], exclude: string[]): string[] {
138
- return urls.filter((url) => {
139
- // Convert URL to path for pattern matching
140
- const urlObj = new URL(url);
141
- const path = urlObj.pathname + urlObj.search;
142
-
143
- // Filter URLs that don't match the reference URL domain
144
- const baseObj = new URL(baseUrl);
145
- if (urlObj.hostname !== baseObj.hostname) {
146
- return false;
147
- }
148
-
149
- // Also match against full URL for more flexibility
150
- const fullUrl = url;
151
-
152
- // Check if excluded
153
- if (exclude.length > 0) {
154
- if (micromatch.isMatch(path, exclude, {bash: true})) {
155
- return false;
156
- }
157
- }
158
-
159
- // Check if included
160
- if (include.length > 0) {
161
- return micromatch.isMatch(path, include, {bash: true});
162
- }
163
-
164
- return true;
165
- });
166
- }
167
-
168
- export function saveURLs(urls: string[], filepath: string): void {
169
- const content = JSON.stringify(urls, null, 2);
170
- Bun.write(filepath, content);
171
- }
package/src/config.ts DELETED
@@ -1,119 +0,0 @@
1
- #!/usr/bin/env bun
2
-
3
- export interface VRTConfig {
4
- referenceUrl: string;
5
- testUrl: string;
6
- sitemapPath?: string;
7
- maxUrls?: number;
8
- exclude?: string[];
9
- include?: string[];
10
- crawlOptions?: {
11
- maxDepth?: number;
12
- removeTrailingSlash?: boolean;
13
- };
14
- viewports?: Array<{
15
- name: string;
16
- width: number;
17
- height: number;
18
- }>;
19
- threshold?: {
20
- maxDiffPixels?: number;
21
- maxDiffPixelRatio?: number;
22
- };
23
- }
24
-
25
- export interface CLIOptions {
26
- reference?: string;
27
- test?: string;
28
- config: string;
29
- output?: string;
30
- maxUrls?: number;
31
- project?: string;
32
- verbose?: boolean;
33
- identifier?: string;
34
- updateBaseline?: boolean;
35
- headed?: boolean;
36
- }
37
-
38
- export const DEFAULT_CONFIG: Partial<VRTConfig> = {
39
- sitemapPath: '/sitemap.xml',
40
- maxUrls: 25,
41
- exclude: [],
42
- include: ['*'],
43
- crawlOptions: {
44
- maxDepth: 1,
45
- removeTrailingSlash: true,
46
- },
47
- viewports: [
48
- { name: 'desktop', width: 1920, height: 1080 },
49
- { name: 'mobile', width: 375, height: 667 },
50
- ],
51
- threshold: {
52
- maxDiffPixels: 100,
53
- maxDiffPixelRatio: 0.01,
54
- },
55
- };
56
-
57
- export async function loadConfig(configPath: string): Promise<VRTConfig> {
58
- try {
59
- const file = Bun.file(configPath);
60
- const config = await file.json();
61
-
62
- // Merge with defaults
63
- return {
64
- ...DEFAULT_CONFIG,
65
- ...config,
66
- crawlOptions: {
67
- ...DEFAULT_CONFIG.crawlOptions,
68
- ...config.crawlOptions,
69
- },
70
- viewports: config.viewports || DEFAULT_CONFIG.viewports,
71
- threshold: {
72
- ...DEFAULT_CONFIG.threshold,
73
- ...config.threshold,
74
- },
75
- };
76
- } catch (error) {
77
- if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
78
- throw new Error(`Config file not found: ${configPath}`);
79
- }
80
- throw error;
81
- }
82
- }
83
-
84
- export function validateConfig(config: VRTConfig): void {
85
- // Validate required URLs
86
- if (!config.testUrl) {
87
- throw new Error('testUrl is required');
88
- }
89
- if (!config.referenceUrl) {
90
- throw new Error('referenceUrl is required');
91
- }
92
-
93
- // Validate URL format
94
- try {
95
- new URL(config.referenceUrl);
96
- new URL(config.testUrl);
97
- } catch {
98
- throw new Error('Invalid URL format in referenceUrl or testUrl');
99
- }
100
-
101
- // Validate viewports
102
- if (!config.viewports || config.viewports.length === 0) {
103
- throw new Error('At least one viewport must be defined');
104
- }
105
-
106
- for (const vp of config.viewports) {
107
- if (!vp.name || vp.width <= 0 || vp.height <= 0) {
108
- throw new Error(`Invalid viewport configuration: ${JSON.stringify(vp)}`);
109
- }
110
- }
111
-
112
- // Validate threshold
113
- if (config.threshold) {
114
- if (config.threshold.maxDiffPixelRatio &&
115
- (config.threshold.maxDiffPixelRatio < 0 || config.threshold.maxDiffPixelRatio > 1)) {
116
- throw new Error('maxDiffPixelRatio must be between 0 and 1');
117
- }
118
- }
119
- }