@storywright/cli 0.1.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.
@@ -0,0 +1,748 @@
1
+ // src/config/index.ts
2
+ import { loadConfig as unconfigLoad } from "unconfig";
3
+
4
+ // src/config/defaults.ts
5
+ var DEFAULT_CONFIG = {
6
+ storybook: {
7
+ staticDir: "storybook-static",
8
+ buildCommand: "npx storybook build --stats-json",
9
+ url: void 0,
10
+ compatibility: "auto"
11
+ },
12
+ browsers: ["chromium"],
13
+ browserOptions: {},
14
+ screenshot: {
15
+ fullPage: true,
16
+ animations: "disabled",
17
+ threshold: 0.02,
18
+ maxDiffPixelRatio: 0.02,
19
+ freezeTime: "2024-01-01T00:00:00",
20
+ timezone: "UTC",
21
+ locale: "en-US",
22
+ seed: 1
23
+ },
24
+ diffDetection: {
25
+ enabled: true,
26
+ watchFiles: ["package.json", "package-lock.json", ".storybook/**/*"],
27
+ baseBranch: "main"
28
+ },
29
+ storage: {
30
+ provider: "local",
31
+ local: {
32
+ baselineDir: ".storywright/baselines"
33
+ },
34
+ s3: {
35
+ bucket: "",
36
+ prefix: "storywright/baselines",
37
+ region: "ap-northeast-1",
38
+ compression: "zstd"
39
+ }
40
+ },
41
+ report: {
42
+ outputDir: ".storywright/report",
43
+ title: "Storywright Report"
44
+ },
45
+ workers: "auto",
46
+ timeout: {
47
+ test: 3e4,
48
+ navigation: 2e4,
49
+ expect: 1e4
50
+ },
51
+ include: ["**"],
52
+ exclude: [],
53
+ hooks: {}
54
+ };
55
+
56
+ // src/config/index.ts
57
+ function defineConfig(config) {
58
+ return config;
59
+ }
60
+ function isPlainObject(value) {
61
+ return value !== null && typeof value === "object" && !Array.isArray(value);
62
+ }
63
+ function deepMerge(target, source) {
64
+ const result = { ...target };
65
+ for (const key of Object.keys(source)) {
66
+ const sourceVal = source[key];
67
+ const targetVal = result[key];
68
+ if (isPlainObject(sourceVal) && isPlainObject(targetVal)) {
69
+ result[key] = deepMerge(targetVal, sourceVal);
70
+ } else if (sourceVal !== void 0) {
71
+ result[key] = sourceVal;
72
+ }
73
+ }
74
+ return result;
75
+ }
76
+ async function loadConfig(cwd = process.cwd(), overrides) {
77
+ const { config: userConfig } = await unconfigLoad({
78
+ sources: [
79
+ {
80
+ files: "storywright.config",
81
+ extensions: ["ts", "js", "mjs"]
82
+ }
83
+ ],
84
+ cwd
85
+ });
86
+ let merged = DEFAULT_CONFIG;
87
+ if (userConfig) {
88
+ merged = deepMerge(merged, userConfig);
89
+ }
90
+ if (overrides) {
91
+ merged = deepMerge(merged, overrides);
92
+ }
93
+ return merged;
94
+ }
95
+
96
+ // src/reporter/cli-reporter.ts
97
+ function formatSummary(summary, options) {
98
+ const durationSec = Math.round(summary.duration / 1e3);
99
+ const minutes = Math.floor(durationSec / 60);
100
+ const seconds = durationSec % 60;
101
+ const durationStr = minutes > 0 ? `${minutes}m ${seconds}s` : `${seconds}s`;
102
+ const lines = [
103
+ "",
104
+ "Storywright Results",
105
+ "\u2550".repeat(42),
106
+ ` Total: ${summary.total} Passed: ${summary.passed} Failed: ${summary.failed} Skipped: ${summary.skipped}`,
107
+ ` Duration: ${durationStr}`,
108
+ ` Browsers: ${summary.browsers.join(", ")}`
109
+ ];
110
+ const newFailures = summary.failures.filter((f) => f.type === "new");
111
+ const diffFailures = summary.failures.filter((f) => f.type !== "new");
112
+ if (newFailures.length > 0) {
113
+ lines.push("");
114
+ lines.push(" New (no baseline):");
115
+ for (const failure of newFailures) {
116
+ lines.push(` \u25CB ${failure.story}: ${failure.variant} (${failure.browser})`);
117
+ }
118
+ }
119
+ if (diffFailures.length > 0) {
120
+ lines.push("");
121
+ lines.push(" Failed:");
122
+ for (const failure of diffFailures) {
123
+ lines.push(` \u2717 ${failure.story}: ${failure.variant} (${failure.browser})`);
124
+ if (failure.diffRatio > 0) {
125
+ const pct = (failure.diffRatio * 100).toFixed(1);
126
+ lines.push(` \u2192 Diff: ${pct}% pixels changed`);
127
+ }
128
+ }
129
+ }
130
+ const reportPath = options?.reportPath ?? ".storywright/report/index.html";
131
+ lines.push("");
132
+ lines.push(` Report: ${reportPath}`);
133
+ lines.push("\u2550".repeat(42));
134
+ lines.push("");
135
+ return lines.join("\n");
136
+ }
137
+
138
+ // src/storage/index.ts
139
+ import { createRequire } from "module";
140
+
141
+ // src/storage/local.ts
142
+ import fs from "fs/promises";
143
+ import path from "path";
144
+ var LocalStorageAdapter = class {
145
+ constructor(baselineDir) {
146
+ this.baselineDir = baselineDir;
147
+ }
148
+ async download(options) {
149
+ const sourceDir = path.resolve(this.baselineDir, options.branch);
150
+ try {
151
+ await fs.access(sourceDir);
152
+ } catch {
153
+ return;
154
+ }
155
+ await fs.cp(sourceDir, options.destDir, { recursive: true });
156
+ }
157
+ async upload(options) {
158
+ const destDir = path.resolve(this.baselineDir, options.branch);
159
+ await fs.mkdir(destDir, { recursive: true });
160
+ await fs.cp(options.sourceDir, destDir, { recursive: true });
161
+ }
162
+ async exists(branch) {
163
+ const dir = path.resolve(this.baselineDir, branch);
164
+ try {
165
+ await fs.access(dir);
166
+ return true;
167
+ } catch {
168
+ return false;
169
+ }
170
+ }
171
+ };
172
+
173
+ // src/storage/index.ts
174
+ function createStorageAdapter(config) {
175
+ switch (config.provider) {
176
+ case "local":
177
+ return new LocalStorageAdapter(config.local.baselineDir);
178
+ case "s3":
179
+ return loadS3Adapter(config);
180
+ default:
181
+ throw new Error(`Unknown storage provider: ${config.provider}`);
182
+ }
183
+ }
184
+ function loadS3Adapter(config) {
185
+ try {
186
+ const require2 = createRequire(import.meta.url);
187
+ const { S3StorageAdapter } = require2("@storywright/storage-s3");
188
+ return new S3StorageAdapter(config.s3);
189
+ } catch {
190
+ throw new Error(
191
+ "S3 storage adapter requires the @storywright/storage-s3 package.\nInstall it with: pnpm add @storywright/storage-s3"
192
+ );
193
+ }
194
+ }
195
+
196
+ // src/utils/logger.ts
197
+ import { createConsola } from "consola";
198
+ var isCI = !!(process.env.CI || process.env.GITHUB_ACTIONS || process.env.CIRCLECI || process.env.GITLAB_CI);
199
+ var logger = createConsola({
200
+ fancy: !isCI,
201
+ level: process.env.STORYWRIGHT_DEBUG ? 5 : 3
202
+ });
203
+
204
+ // src/core/engine.ts
205
+ import fs4 from "fs/promises";
206
+ import path5 from "path";
207
+ import picomatch3 from "picomatch";
208
+
209
+ // src/playwright/config-generator.ts
210
+ function generatePlaywrightConfig(config, options) {
211
+ const projects = config.browsers.map((browser) => {
212
+ const browserOptions = config.browserOptions[browser];
213
+ const useObj = browserOptions ? JSON.stringify(browserOptions, null, " ") : getDefaultBrowserUse(browser);
214
+ return ` {
215
+ name: '${browser}',
216
+ use: ${useObj},
217
+ }`;
218
+ });
219
+ const workers = config.workers === "auto" ? "'50%'" : String(config.workers);
220
+ const shard = options.shard ? ` shard: { current: ${options.shard.split("/")[0]}, total: ${options.shard.split("/")[1]} },` : "";
221
+ const reporterEntries = [];
222
+ const requestedReporters = options.reporters ?? ["default", "html"];
223
+ for (const r of requestedReporters) {
224
+ if (r === "default" || r === "list") {
225
+ reporterEntries.push(" ['list']");
226
+ } else if (r !== "html") {
227
+ reporterEntries.push(` ['${r}']`);
228
+ }
229
+ }
230
+ reporterEntries.push(` ['${escapeBackslash(options.reporterPath)}']`);
231
+ return `import { defineConfig } from '@playwright/test';
232
+
233
+ export default defineConfig({
234
+ testDir: '${escapeBackslash(options.tmpDir)}',
235
+ testMatch: '${escapeBackslash(options.testFile)}',
236
+ snapshotDir: '${escapeBackslash(options.snapshotDir)}',
237
+ snapshotPathTemplate: '{snapshotDir}/{arg}-{projectName}-${config.screenshot.locale}-${config.screenshot.timezone}{ext}',
238
+ timeout: ${config.timeout.test},
239
+ expect: {
240
+ toHaveScreenshot: {
241
+ maxDiffPixelRatio: ${config.screenshot.maxDiffPixelRatio},
242
+ threshold: ${config.screenshot.threshold},
243
+ },
244
+ timeout: ${config.timeout.expect},
245
+ },
246
+ fullyParallel: true,
247
+ forbidOnly: !!process.env.CI,
248
+ workers: ${workers},
249
+ ${shard}
250
+ reporter: [
251
+ ${reporterEntries.join(",\n")}
252
+ ],
253
+ use: {
254
+ baseURL: '${options.storybookUrl}',
255
+ navigationTimeout: ${config.timeout.navigation},
256
+ timezoneId: '${config.screenshot.timezone}',
257
+ locale: '${config.screenshot.locale}',
258
+ },
259
+ projects: [
260
+ ${projects.join(",\n")}
261
+ ],
262
+ });
263
+ `;
264
+ }
265
+ function getDefaultBrowserUse(browser) {
266
+ switch (browser) {
267
+ case "chromium":
268
+ return "{ browserName: 'chromium' }";
269
+ case "firefox":
270
+ return "{ browserName: 'firefox' }";
271
+ case "webkit":
272
+ return "{ browserName: 'webkit' }";
273
+ default:
274
+ return `{ browserName: '${browser}' }`;
275
+ }
276
+ }
277
+ function escapeBackslash(str) {
278
+ return str.replace(/\\/g, "/");
279
+ }
280
+
281
+ // src/playwright/test-generator.ts
282
+ function generateTestFile(config, options) {
283
+ return `import { test, expect } from '@playwright/test';
284
+ import { readFileSync } from 'node:fs';
285
+
286
+ const targetList = JSON.parse(
287
+ readFileSync('${escapeBackslash2(options.targetStoriesPath)}', 'utf-8'),
288
+ );
289
+
290
+ test.describe.parallel('visual regression testing', () => {
291
+ if (Object.keys(targetList.entries).length === 0) {
292
+ test('no stories to test', () => {
293
+ expect(true).toBeTruthy();
294
+ });
295
+ }
296
+
297
+ for (const story of Object.values(targetList.entries)) {
298
+ test(\`\${story.title}: \${story.name}\`, async ({ page }) => {
299
+ // Freeze time for reproducibility
300
+ await page.clock.install({ time: new Date('${config.freezeTime}') });
301
+
302
+ // Seed Math.random for reproducibility
303
+ await page.addInitScript((seed) => {
304
+ let s = seed;
305
+ Math.random = () => {
306
+ s = (s * 16807 + 0) % 2147483647;
307
+ return (s - 1) / 2147483646;
308
+ };
309
+ }, ${config.seed});
310
+
311
+ await page.goto(\`/iframe.html?id=\${story.id}\`, {
312
+ waitUntil: 'networkidle',
313
+ });
314
+
315
+ await expect(page).toHaveScreenshot(
316
+ [story.title, \`\${story.id}.png\`],
317
+ {
318
+ animations: '${config.animations}',
319
+ fullPage: ${config.fullPage},
320
+ threshold: ${config.threshold},
321
+ maxDiffPixelRatio: ${config.maxDiffPixelRatio},
322
+ },
323
+ );
324
+ });
325
+ }
326
+ });
327
+ `;
328
+ }
329
+ function escapeBackslash2(str) {
330
+ return str.replace(/\\/g, "/");
331
+ }
332
+
333
+ // src/resolver/index.ts
334
+ import fs2 from "fs/promises";
335
+ import path3 from "path";
336
+ import picomatch from "picomatch";
337
+ import { simpleGit } from "simple-git";
338
+
339
+ // src/utils/path.ts
340
+ import path2 from "path";
341
+ function normalizePath(filePath) {
342
+ const normalized = filePath.replace(/\\/g, "/");
343
+ if (normalized.startsWith("./")) {
344
+ return normalized;
345
+ }
346
+ return `./${normalized}`;
347
+ }
348
+ function stripLeadingDotSlash(filePath) {
349
+ return filePath.replace(/^\.\//, "");
350
+ }
351
+ function resolveOutputDir(outputDir, ...segments) {
352
+ return path2.resolve(outputDir, ...segments);
353
+ }
354
+
355
+ // src/resolver/index.ts
356
+ var STORY_FILE_PATTERNS = [".stories.", ".mdx"];
357
+ function isStoryFile(moduleName) {
358
+ return STORY_FILE_PATTERNS.some((p) => moduleName.includes(p));
359
+ }
360
+ var StorybookStatsDependencyResolver = class {
361
+ constructor(statsJson, storiesJson) {
362
+ this.statsJson = statsJson;
363
+ this.storiesJson = storiesJson;
364
+ this.moduleMap = {};
365
+ for (const mod of statsJson.modules) {
366
+ const normalizedName = normalizePath(mod.name);
367
+ this.moduleMap[normalizedName] = mod;
368
+ const normalizedId = normalizePath(mod.id);
369
+ if (normalizedId !== normalizedName) {
370
+ this.moduleMap[normalizedId] ??= mod;
371
+ }
372
+ }
373
+ }
374
+ moduleMap;
375
+ getDependencies(filePath) {
376
+ const normalizedPath = normalizePath(filePath);
377
+ const dependencies = this.collectDependencies(normalizedPath);
378
+ if (this.moduleMap[normalizedPath]) {
379
+ dependencies.add(normalizedPath);
380
+ }
381
+ return [...dependencies];
382
+ }
383
+ getStoriesForFiles(pathList) {
384
+ const result = { v: this.storiesJson.v, entries: {} };
385
+ for (const filePath of pathList) {
386
+ const normalizedPath = normalizePath(filePath);
387
+ const stats = this.moduleMap[normalizedPath];
388
+ if (!stats) continue;
389
+ const storyReasons = stats.reasons.filter((r) => isStoryFile(r.moduleName));
390
+ for (const reason of storyReasons) {
391
+ const normalizedImportPath = normalizePath(reason.moduleName);
392
+ for (const storyObj of Object.values(this.storiesJson.entries)) {
393
+ if (storyObj.type !== "story") continue;
394
+ if (normalizePath(storyObj.importPath) === normalizedImportPath) {
395
+ result.entries[storyObj.id] = storyObj;
396
+ }
397
+ }
398
+ }
399
+ }
400
+ return result;
401
+ }
402
+ collectDependencies(name, result = /* @__PURE__ */ new Set()) {
403
+ const mod = this.moduleMap[normalizePath(name)];
404
+ if (mod) {
405
+ for (const reason of mod.reasons) {
406
+ if (!result.has(reason.moduleName)) {
407
+ result.add(reason.moduleName);
408
+ this.collectDependencies(reason.moduleName, result);
409
+ }
410
+ }
411
+ }
412
+ return result;
413
+ }
414
+ };
415
+ async function resolveAffectedStories(storiesJson, config, storybookStaticDir, cwd) {
416
+ const git = simpleGit({ baseDir: cwd });
417
+ let diffEntries;
418
+ try {
419
+ const mergeBase = await git.raw(["merge-base", config.baseBranch, "HEAD"]);
420
+ const diff = await git.diffSummary([mergeBase.trim(), "HEAD"]);
421
+ diffEntries = diff.files.map((f) => ({
422
+ file: f.file,
423
+ // Handle renames: include both old and new paths
424
+ from: "from" in f ? f.from : void 0
425
+ }));
426
+ } catch {
427
+ logger.warn("Failed to resolve git diff, running all stories");
428
+ return { allStories: true, targetStories: storiesJson };
429
+ }
430
+ if (diffEntries.length === 0) {
431
+ logger.info("No changed files detected");
432
+ return { allStories: false, targetStories: { v: storiesJson.v, entries: {} } };
433
+ }
434
+ const allPaths = [];
435
+ for (const entry of diffEntries) {
436
+ allPaths.push(entry.file);
437
+ if (entry.from) {
438
+ allPaths.push(entry.from);
439
+ }
440
+ }
441
+ for (const file of allPaths) {
442
+ for (const pattern of config.watchFiles) {
443
+ if (picomatch(pattern)(file)) {
444
+ logger.info(`Watch file changed: ${file}, running all stories`);
445
+ return { allStories: true, targetStories: storiesJson };
446
+ }
447
+ }
448
+ }
449
+ const statsPath = path3.resolve(storybookStaticDir, "preview-stats.json");
450
+ let statsJson;
451
+ try {
452
+ statsJson = JSON.parse(await fs2.readFile(statsPath, "utf-8"));
453
+ } catch {
454
+ logger.warn("preview-stats.json not found, running all stories");
455
+ return { allStories: true, targetStories: storiesJson };
456
+ }
457
+ const resolver = new StorybookStatsDependencyResolver(statsJson, storiesJson);
458
+ const targetStories = { v: storiesJson.v, entries: {} };
459
+ for (const file of allPaths) {
460
+ const matchedStories = Object.values(storiesJson.entries).filter(
461
+ (story) => stripLeadingDotSlash(story.importPath) === file
462
+ );
463
+ for (const story of matchedStories) {
464
+ targetStories.entries[story.id] = story;
465
+ }
466
+ }
467
+ for (const file of allPaths) {
468
+ const deps = resolver.getDependencies(normalizePath(file));
469
+ const depStories = resolver.getStoriesForFiles(deps);
470
+ for (const [id, story] of Object.entries(depStories.entries)) {
471
+ targetStories.entries[id] = story;
472
+ }
473
+ }
474
+ logger.info(`Resolved ${Object.keys(targetStories.entries).length} affected stories`);
475
+ return { allStories: false, targetStories };
476
+ }
477
+
478
+ // src/utils/process.ts
479
+ import { spawn } from "child_process";
480
+ function exec(command, args, options) {
481
+ return new Promise((resolve, reject) => {
482
+ const proc = spawn(command, args, {
483
+ cwd: options?.cwd,
484
+ env: { ...process.env, ...options?.env },
485
+ stdio: ["ignore", "pipe", "pipe"],
486
+ shell: false
487
+ });
488
+ let stdout = "";
489
+ let stderr = "";
490
+ proc.stdout.on("data", (data) => {
491
+ stdout += data.toString();
492
+ });
493
+ proc.stderr.on("data", (data) => {
494
+ stderr += data.toString();
495
+ });
496
+ proc.on("error", reject);
497
+ proc.on("close", (code) => {
498
+ resolve({ exitCode: code ?? 1, stdout, stderr });
499
+ });
500
+ });
501
+ }
502
+
503
+ // src/core/storybook.ts
504
+ import fs3 from "fs/promises";
505
+ import path4 from "path";
506
+ import picomatch2 from "picomatch";
507
+ async function buildStorybook(config, cwd) {
508
+ if (config.storybook.url) {
509
+ logger.info("Using running Storybook at", config.storybook.url);
510
+ return;
511
+ }
512
+ const staticDir = path4.resolve(cwd, config.storybook.staticDir);
513
+ try {
514
+ await fs3.access(path4.join(staticDir, "index.json"));
515
+ logger.info("Storybook already built at", staticDir);
516
+ return;
517
+ } catch {
518
+ }
519
+ logger.start("Building Storybook...");
520
+ const [command, ...args] = config.storybook.buildCommand.split(" ");
521
+ const result = await exec(command, args, { cwd });
522
+ if (result.exitCode !== 0) {
523
+ throw new Error(
524
+ `Storybook build failed (exit code ${result.exitCode}):
525
+ ${result.stderr}
526
+
527
+ Error code: SW_E_STORYBOOK_BUILD_FAILED`
528
+ );
529
+ }
530
+ logger.success("Storybook built");
531
+ }
532
+ async function discoverStories(config, cwd) {
533
+ const staticDir = path4.resolve(cwd, config.storybook.staticDir);
534
+ const indexPath = path4.join(staticDir, "index.json");
535
+ try {
536
+ await fs3.access(indexPath);
537
+ } catch {
538
+ throw new Error(
539
+ `Storybook build directory not found at '${config.storybook.staticDir}/'
540
+
541
+ Run one of the following:
542
+ $ npx storybook build --stats-json
543
+ $ npx storywright test --storybook-url http://localhost:6006
544
+
545
+ Error code: SW_E_STORYBOOK_DIR_NOT_FOUND`
546
+ );
547
+ }
548
+ const raw = JSON.parse(await fs3.readFile(indexPath, "utf-8"));
549
+ const indexJson = normalizeStoryIndex(raw, config.storybook.compatibility);
550
+ if (indexJson.v < 3) {
551
+ throw new Error(
552
+ "Storybook version 6.x or earlier is not supported.\n\nError code: SW_E_STORYBOOK_UNSUPPORTED"
553
+ );
554
+ }
555
+ return indexJson;
556
+ }
557
+ function normalizeStoryIndex(raw, compatibility) {
558
+ const version = typeof raw.v === "number" ? raw.v : 4;
559
+ let entries;
560
+ if (compatibility === "v7" || compatibility === "auto" && raw.stories && !raw.entries) {
561
+ entries = raw.stories ?? raw.entries ?? {};
562
+ } else {
563
+ entries = raw.entries ?? raw.stories ?? {};
564
+ }
565
+ for (const [id, entry] of Object.entries(entries)) {
566
+ if (!entry.type) {
567
+ entries[id] = { ...entry, type: entry.name === "Docs" ? "docs" : "story" };
568
+ }
569
+ }
570
+ return { v: version, entries };
571
+ }
572
+ function filterStories(storyIndex, config) {
573
+ const entries = {};
574
+ const includeMatchers = config.include.map((p) => picomatch2(p));
575
+ const excludeMatchers = config.exclude.map((p) => picomatch2(p));
576
+ for (const [id, story] of Object.entries(storyIndex.entries)) {
577
+ if (story.type === "docs") continue;
578
+ if (story.name === "Docs") continue;
579
+ if (story.tags?.includes("!vrt")) continue;
580
+ const fullName = `${story.title}/${story.name}`;
581
+ const isIncluded = includeMatchers.some((m) => m(fullName));
582
+ if (!isIncluded) continue;
583
+ const isExcluded = excludeMatchers.some((m) => m(fullName));
584
+ if (isExcluded) continue;
585
+ entries[id] = story;
586
+ }
587
+ return { ...storyIndex, entries };
588
+ }
589
+
590
+ // src/core/engine.ts
591
+ function resolveReporterPath() {
592
+ const thisDir = new URL(".", import.meta.url).pathname;
593
+ return path5.resolve(thisDir, "playwright", "reporter.js");
594
+ }
595
+ async function runTests(config, options = {}, cwd = process.cwd()) {
596
+ const outputRoot = options.outputDir ? path5.resolve(cwd, options.outputDir) : resolveOutputDir(cwd, ".storywright");
597
+ const tmpDir = path5.join(outputRoot, "tmp");
598
+ const reportDir = options.outputDir ? path5.join(outputRoot, "report") : path5.resolve(cwd, config.report.outputDir);
599
+ const storybookDir = path5.resolve(cwd, config.storybook.staticDir);
600
+ await buildStorybook(config, cwd);
601
+ logger.start("Discovering stories...");
602
+ const allStories = await discoverStories(config, cwd);
603
+ let targetStories = filterStories(allStories, config);
604
+ if (options.filter) {
605
+ targetStories = applyFilter(targetStories, options.filter);
606
+ }
607
+ logger.info(`${Object.keys(targetStories.entries).length} stories found`);
608
+ if (options.diffOnly && config.diffDetection.enabled) {
609
+ logger.start("Resolving dependencies...");
610
+ const diffResult = await resolveAffectedStories(
611
+ targetStories,
612
+ config.diffDetection,
613
+ storybookDir,
614
+ cwd
615
+ );
616
+ if (!diffResult.allStories) {
617
+ targetStories = diffResult.targetStories;
618
+ }
619
+ logger.info(`${Object.keys(targetStories.entries).length} stories affected by changes`);
620
+ }
621
+ await fs4.mkdir(tmpDir, { recursive: true });
622
+ const targetStoriesPath = path5.join(tmpDir, "target-stories.json");
623
+ await fs4.writeFile(targetStoriesPath, JSON.stringify(targetStories));
624
+ const snapshotDir = path5.join(tmpDir, "snapshots");
625
+ await fs4.mkdir(snapshotDir, { recursive: true });
626
+ const storage = createStorageAdapter(config.storage);
627
+ try {
628
+ await storage.download({ branch: "current", destDir: snapshotDir });
629
+ } catch {
630
+ logger.info("No existing baselines found");
631
+ }
632
+ const reporterWrapperPath = path5.join(tmpDir, "reporter.mjs");
633
+ const resolvedReporterPath = resolveReporterPath().replace(/\\/g, "/");
634
+ const reporterOutputDir = reportDir.replace(/\\/g, "/");
635
+ await fs4.writeFile(
636
+ reporterWrapperPath,
637
+ `import StorywrightReporter from '${resolvedReporterPath}';
638
+ export default class extends StorywrightReporter {
639
+ constructor() { super({ outputDir: '${reporterOutputDir}' }); }
640
+ }
641
+ `
642
+ );
643
+ const testFileName = "storywright-test.spec.ts";
644
+ const testFilePath = path5.join(tmpDir, testFileName);
645
+ const testContent = generateTestFile(config.screenshot, {
646
+ targetStoriesPath: targetStoriesPath.replace(/\\/g, "/")
647
+ });
648
+ await fs4.writeFile(testFilePath, testContent);
649
+ let actualStorybookUrl = config.storybook.url;
650
+ const needsServer = !actualStorybookUrl;
651
+ if (needsServer) {
652
+ actualStorybookUrl = "http://localhost:6007";
653
+ }
654
+ const playwrightConfig = generatePlaywrightConfig(config, {
655
+ tmpDir: tmpDir.replace(/\\/g, "/"),
656
+ storybookUrl: actualStorybookUrl ?? "http://localhost:6007",
657
+ snapshotDir: snapshotDir.replace(/\\/g, "/"),
658
+ reporterPath: reporterWrapperPath.replace(/\\/g, "/"),
659
+ testFile: testFileName,
660
+ shard: options.shard,
661
+ reporters: options.reporters
662
+ });
663
+ const configPath = path5.join(tmpDir, "playwright.config.ts");
664
+ await fs4.writeFile(configPath, playwrightConfig);
665
+ logger.start("Running tests...");
666
+ const args = ["playwright", "test", "--config", configPath];
667
+ if (options.updateSnapshots) {
668
+ args.push("--update-snapshots");
669
+ }
670
+ let serverProc;
671
+ if (needsServer) {
672
+ serverProc = await startStaticServer(storybookDir, 6007);
673
+ }
674
+ try {
675
+ const result = await exec("npx", args, { cwd });
676
+ let summary;
677
+ try {
678
+ const summaryPath = path5.join(reportDir, "summary.json");
679
+ const summaryContent = await fs4.readFile(summaryPath, "utf-8");
680
+ summary = JSON.parse(summaryContent);
681
+ } catch {
682
+ }
683
+ const exitCode = mapExitCode(result.exitCode, summary);
684
+ return { exitCode, summary, reportDir };
685
+ } finally {
686
+ serverProc?.kill();
687
+ }
688
+ }
689
+ async function updateBaselines(config, options = {}, cwd = process.cwd()) {
690
+ const result = await runTests(config, { updateSnapshots: true, diffOnly: !options.all }, cwd);
691
+ if (result.exitCode !== 0) {
692
+ logger.warn("Some tests failed during baseline update");
693
+ }
694
+ if (options.upload) {
695
+ const storage = createStorageAdapter(config.storage);
696
+ const baselineDir = path5.resolve(cwd, config.storage.local.baselineDir);
697
+ await storage.upload({
698
+ branch: "current",
699
+ sourceDir: baselineDir
700
+ });
701
+ logger.success("Baselines uploaded");
702
+ }
703
+ logger.success("Baselines updated");
704
+ }
705
+ function applyFilter(storyIndex, filter) {
706
+ const matcher = picomatch3(filter);
707
+ const entries = {};
708
+ for (const [id, story] of Object.entries(storyIndex.entries)) {
709
+ const fullName = `${story.title}/${story.name}`;
710
+ if (matcher(fullName) || matcher(story.title) || matcher(story.id)) {
711
+ entries[id] = story;
712
+ }
713
+ }
714
+ return { ...storyIndex, entries };
715
+ }
716
+ function mapExitCode(playwrightCode, summary) {
717
+ if (playwrightCode === 130 || playwrightCode === 143) {
718
+ return 130;
719
+ }
720
+ if (summary) {
721
+ if (summary.failed > 0) return 1;
722
+ if (summary.total === 0 && playwrightCode !== 0) return 2;
723
+ return 0;
724
+ }
725
+ return playwrightCode === 0 ? 0 : 2;
726
+ }
727
+ async function startStaticServer(dir, port) {
728
+ const { createServer } = await import("http");
729
+ const sirv = (await import("sirv")).default;
730
+ const handler = sirv(dir, { single: false, dev: false });
731
+ const server = createServer(handler);
732
+ await new Promise((resolve, reject) => {
733
+ server.on("error", reject);
734
+ server.listen(port, () => resolve());
735
+ });
736
+ return { kill: () => server.close() };
737
+ }
738
+
739
+ export {
740
+ defineConfig,
741
+ loadConfig,
742
+ formatSummary,
743
+ createStorageAdapter,
744
+ logger,
745
+ runTests,
746
+ updateBaselines
747
+ };
748
+ //# sourceMappingURL=chunk-U4KT4Y42.js.map