@storysnap/cli 1.0.0 → 1.2.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/README.md CHANGED
@@ -66,23 +66,17 @@ StorySnap looks for configuration in the following order:
66
66
 
67
67
  ```typescript
68
68
  // storysnap.config.ts
69
- import { defineConfig } from 'storysnap';
69
+ import { defineConfig } from '@storysnap/cli';
70
70
 
71
71
  export default defineConfig({
72
- // Storybook URL (required)
72
+ // Storybook URL, or storybookStaticDir for a static build (one is required)
73
73
  storybookUrl: 'http://localhost:6006',
74
74
 
75
- // Output directory for screenshots
76
- outputDir: '.storysnap',
77
-
78
75
  // Browsers to test (default: ['chromium'])
79
76
  browsers: ['chromium', 'firefox', 'webkit'],
80
77
 
81
- // Viewport sizes
82
- viewports: [
83
- { width: 1280, height: 720, name: 'desktop' },
84
- { width: 375, height: 667, name: 'mobile' },
85
- ],
78
+ // Viewport size (default: 1280x720)
79
+ viewport: { width: 1280, height: 720 },
86
80
 
87
81
  // Comparison threshold (0-1, default: 0.1)
88
82
  threshold: 0.1,
@@ -118,7 +112,9 @@ npx @storysnap/cli test [options]
118
112
 
119
113
  Options:
120
114
  -c, --config <path> Path to config file
121
- -s, --story <pattern> Filter stories by pattern (supports * wildcards)
115
+ -s, --story <pattern> Only stories matching a pattern (repeatable)
116
+ -x, --exclude <pattern> Skip stories matching a pattern (repeatable)
117
+ --changed [ref] Only stories changed since branching off ref (default: main)
122
118
  -b, --browser <browsers> Browsers to test (chromium,firefox,webkit)
123
119
  --ci CI mode - fail on any visual diff or new story
124
120
  --local Force local-only mode without using the API
@@ -134,7 +130,9 @@ npx @storysnap/cli update [options]
134
130
 
135
131
  Options:
136
132
  -c, --config <path> Path to config file
137
- -s, --story <pattern> Filter stories by pattern (supports * wildcards)
133
+ -s, --story <pattern> Only stories matching a pattern (repeatable)
134
+ -x, --exclude <pattern> Skip stories matching a pattern (repeatable)
135
+ --changed [ref] Only stories changed since branching off ref (default: main)
138
136
  -b, --browser <browsers> Browsers to test (chromium,firefox,webkit)
139
137
  --dry-run Show what would be updated without making changes
140
138
  --local Force local-only mode without using the API
@@ -149,7 +147,7 @@ Authenticate with the StorySnap API (for cloud mode).
149
147
  npx @storysnap/cli login [options]
150
148
 
151
149
  Options:
152
- -u, --api-url <url> API URL
150
+ -u, --api-url <url> StorySnap server URL, without /api
153
151
  -t, --token <token> API token (will prompt if not provided)
154
152
  -v, --verbose Verbose output
155
153
  ```
@@ -0,0 +1,129 @@
1
+ export interface ApiClientOptions {
2
+ apiUrl: string;
3
+ apiToken: string;
4
+ }
5
+ export interface TestRunInput {
6
+ storybookUrl?: string;
7
+ branch?: string;
8
+ commit?: string;
9
+ /** pixelmatch per-pixel colour sensitivity (0-1). */
10
+ threshold?: number;
11
+ /** Percentage of the image allowed to differ before a story fails (0-100). */
12
+ maxDiffPercent?: number;
13
+ }
14
+ export interface CreateResultInput {
15
+ storyId: string;
16
+ storyTitle: string;
17
+ storyName: string;
18
+ browser: string;
19
+ viewportWidth: number;
20
+ viewportHeight: number;
21
+ }
22
+ export interface ResultUploadTarget {
23
+ resultId: string;
24
+ storageKey: string;
25
+ uploadUrl: string;
26
+ expiresIn: number;
27
+ }
28
+ export interface TestRun {
29
+ id: string;
30
+ projectId: string;
31
+ status: 'pending' | 'running' | 'passed' | 'failed' | 'error';
32
+ branch?: string;
33
+ commit?: string;
34
+ totalStories: number;
35
+ passedStories: number;
36
+ failedStories: number;
37
+ newStories: number;
38
+ errorStories: number;
39
+ /** The settings this run was judged against. */
40
+ threshold: number;
41
+ maxDiffPercent: number;
42
+ startedAt?: string;
43
+ completedAt?: string;
44
+ createdAt: string;
45
+ }
46
+ export interface TestResult {
47
+ id: string;
48
+ storyId: string;
49
+ storyTitle: string;
50
+ storyName: string;
51
+ browser: string;
52
+ viewportWidth: number;
53
+ viewportHeight: number;
54
+ status: 'pending' | 'pass' | 'fail' | 'new' | 'error';
55
+ diffPercentage?: number;
56
+ diffPixels?: number;
57
+ screenshotUrl?: string;
58
+ baselineUrl?: string;
59
+ diffUrl?: string;
60
+ errorMessage?: string;
61
+ }
62
+ export interface TestRunWithResults extends TestRun {
63
+ results: TestResult[];
64
+ }
65
+ export interface BaselineUploadUrl {
66
+ url: string;
67
+ storageKey: string;
68
+ expiresIn: number;
69
+ }
70
+ export interface Baseline {
71
+ id: string;
72
+ projectId: string;
73
+ storyId: string;
74
+ browser: string;
75
+ viewportWidth: number;
76
+ viewportHeight: number;
77
+ storageKey: string;
78
+ approvedBy?: string;
79
+ approvedAt?: string;
80
+ createdAt: string;
81
+ updatedAt: string;
82
+ }
83
+ export declare class ApiError extends Error {
84
+ statusCode: number;
85
+ response?: unknown | undefined;
86
+ constructor(message: string, statusCode: number, response?: unknown | undefined);
87
+ }
88
+ export declare class ApiClient {
89
+ private apiUrl;
90
+ private apiToken;
91
+ constructor(options: ApiClientOptions);
92
+ private request;
93
+ verifyCredentials(): Promise<boolean>;
94
+ createTestRun(input: TestRunInput): Promise<TestRun>;
95
+ /**
96
+ * Registers one captured screenshot against a run and returns where to PUT it.
97
+ */
98
+ createResult(testRunId: string, input: CreateResultInput): Promise<ResultUploadTarget>;
99
+ /**
100
+ * Closes the run for new results; the server queues the comparisons.
101
+ */
102
+ finalizeTestRun(testRunId: string): Promise<TestRun>;
103
+ /**
104
+ * Uploads a PNG to a presigned URL.
105
+ *
106
+ * Only the host is covered by the signature, so this Content-Type is what the
107
+ * object ends up stored with rather than something S3 validates.
108
+ */
109
+ uploadImage(uploadUrl: string, imageBuffer: Buffer): Promise<void>;
110
+ getTestRun(id: string): Promise<TestRunWithResults>;
111
+ listTestRuns(limit?: number, offset?: number): Promise<TestRun[]>;
112
+ getBaselineUploadUrl(storyId: string, browser: string, viewportWidth: number, viewportHeight: number): Promise<BaselineUploadUrl>;
113
+ uploadBaseline(uploadUrl: string, imageBuffer: Buffer): Promise<void>;
114
+ /**
115
+ * Points the baseline record at an already-uploaded image. Without this the
116
+ * object sits in S3 with nothing referencing it and every story stays "new".
117
+ */
118
+ registerBaseline(input: {
119
+ storyId: string;
120
+ browser: string;
121
+ viewportWidth: number;
122
+ viewportHeight: number;
123
+ storageKey: string;
124
+ }): Promise<Baseline>;
125
+ listBaselines(limit?: number, offset?: number, storyId?: string, browser?: string): Promise<Baseline[]>;
126
+ approveBaseline(baselineId: string, testResultId?: string): Promise<Baseline>;
127
+ waitForTestRun(testRunId: string, onProgress?: (testRun: TestRun) => void, pollInterval?: number, timeout?: number): Promise<TestRunWithResults>;
128
+ }
129
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1,6 @@
1
+ export interface InitOptions {
2
+ format?: 'ts' | 'js' | 'json';
3
+ force?: boolean;
4
+ }
5
+ export declare function initCommand(options?: InitOptions): Promise<void>;
6
+ //# sourceMappingURL=init.d.ts.map
@@ -1,7 +1,7 @@
1
1
  import { writeFile } from 'node:fs/promises';
2
2
  import { join } from 'node:path';
3
3
  import { createReporter } from '../reporter.js';
4
- import { getDefaultConfig, getDefaultConfigJson, findConfigFile } from '../../config/loader.js';
4
+ import { getDefaultConfig, getDefaultConfigJs, getDefaultConfigJson, findConfigFile } from '../../config/loader.js';
5
5
  export async function initCommand(options = {}) {
6
6
  const reporter = createReporter();
7
7
  const cwd = process.cwd();
@@ -24,10 +24,7 @@ export async function initCommand(options = {}) {
24
24
  break;
25
25
  case 'js':
26
26
  fileName = 'storysnap.config.js';
27
- content = getDefaultConfig()
28
- .replace('import type { StorySnapConfig } from \'storysnap\';', '')
29
- .replace('const config: StorySnapConfig = ', 'export default ')
30
- .replace(/;\s*export default config;/, ';');
27
+ content = getDefaultConfigJs();
31
28
  break;
32
29
  case 'json':
33
30
  fileName = 'storysnap.config.json';
@@ -43,9 +40,10 @@ export async function initCommand(options = {}) {
43
40
  reporter.success(`Created ${fileName}`);
44
41
  reporter.newLine();
45
42
  reporter.info('Next steps:');
46
- reporter.info(' 1. Update the config with your S3 bucket and Storybook settings');
47
- reporter.info(' 2. Run "storysnap test" to capture screenshots');
43
+ reporter.info(' 1. Check the Storybook settings in the config');
44
+ reporter.info(' 2. Run "storysnap login" to use a StorySnap server, or skip it to keep baselines local');
48
45
  reporter.info(' 3. Run "storysnap update" to save baselines');
46
+ reporter.info(' 4. Run "storysnap test" to compare against them');
49
47
  }
50
48
  catch (error) {
51
49
  reporter.error(`Failed to create config: ${error instanceof Error ? error.message : 'Unknown error'}`);
@@ -0,0 +1,7 @@
1
+ export interface LoginOptions {
2
+ apiUrl?: string;
3
+ token?: string;
4
+ verbose?: boolean;
5
+ }
6
+ export declare function loginCommand(options?: LoginOptions): Promise<void>;
7
+ //# sourceMappingURL=login.d.ts.map
@@ -57,10 +57,10 @@ export async function loginCommand(options = {}) {
57
57
  reporter.info('Run "storysnap logout" first to log out, or continue to overwrite.');
58
58
  reporter.newLine();
59
59
  }
60
- // Get API URL
60
+ // Get server URL
61
61
  let apiUrl = options.apiUrl;
62
62
  if (!apiUrl) {
63
- apiUrl = await readInput('API URL (default: https://api.storysnap.dev): ');
63
+ apiUrl = await readInput('StorySnap server URL, without /api (default: https://api.storysnap.dev): ');
64
64
  if (!apiUrl.trim()) {
65
65
  apiUrl = 'https://api.storysnap.dev';
66
66
  }
@@ -90,7 +90,7 @@ export async function loginCommand(options = {}) {
90
90
  if (!isValid) {
91
91
  reporter.failSpinner('Invalid credentials');
92
92
  reporter.error('Could not authenticate with the provided credentials.');
93
- reporter.info('Please check your API URL and token and try again.');
93
+ reporter.info('Please check your token, and that the server URL is the base address without /api.');
94
94
  process.exit(1);
95
95
  }
96
96
  reporter.succeedSpinner('Credentials verified');
@@ -0,0 +1,5 @@
1
+ export interface LogoutOptions {
2
+ verbose?: boolean;
3
+ }
4
+ export declare function logoutCommand(options?: LogoutOptions): Promise<void>;
5
+ //# sourceMappingURL=logout.d.ts.map
@@ -0,0 +1,13 @@
1
+ import { type StorySelectionOptions } from '../select-stories.js';
2
+ export interface TestOptions extends StorySelectionOptions {
3
+ config?: string;
4
+ browser?: string;
5
+ storybookUrl?: string;
6
+ branch?: string;
7
+ commit?: string;
8
+ ci?: boolean;
9
+ verbose?: boolean;
10
+ local?: boolean;
11
+ }
12
+ export declare function testCommand(options?: TestOptions): Promise<void>;
13
+ //# sourceMappingURL=test.d.ts.map
@@ -1,10 +1,10 @@
1
1
  import { loadConfig } from '../../config/loader.js';
2
2
  import { loadCredentials } from '../../config/credentials.js';
3
- import { discoverStories } from '../../core/storybook.js';
4
3
  import { captureScreenshots, getScreenshotKey, parseScreenshotKey } from '../../core/screenshot.js';
5
4
  import { compareAllScreenshots, DEFAULT_MAX_DIFF_PERCENT } from '../../core/compare.js';
6
5
  import { createStorage } from '../../storage/index.js';
7
6
  import { createReporter } from '../reporter.js';
7
+ import { selectStories } from '../select-stories.js';
8
8
  import { ApiClient } from '../../api/client.js';
9
9
  function parseBrowsers(browserArg) {
10
10
  if (!browserArg) {
@@ -63,21 +63,13 @@ async function runApiMode(reporter, config, apiUrl, apiToken, options) {
63
63
  reporter.info(`Browsers: ${config.browsers.join(', ')}`);
64
64
  reporter.newLine();
65
65
  const client = new ApiClient({ apiUrl, apiToken });
66
- // Apply story filter if provided
67
- if (options.story) {
68
- config.include = [options.story];
69
- }
70
66
  // Screenshots are captured here, not by the server: the worker has no route
71
67
  // to a Storybook running on this machine or on a CI runner.
72
- reporter.startSpinner('Discovering stories...');
73
- const stories = await discoverStories(config);
74
- if (stories.length === 0) {
75
- reporter.failSpinner('No stories found');
76
- reporter.warning('Make sure Storybook is running or the static build exists.');
77
- process.exit(1);
68
+ const stories = await selectStories(reporter, config, options, 'tests');
69
+ if (!stories) {
70
+ return;
78
71
  }
79
72
  const totalTests = stories.length * config.browsers.length;
80
- reporter.succeedSpinner(`Found ${reporter.formatStoryCount(stories.length)} (${totalTests} tests across ${config.browsers.length} browser(s))`);
81
73
  reporter.startSpinner('Capturing screenshots...');
82
74
  const screenshots = await captureScreenshots(config, stories, (completed, total, story, browser) => {
83
75
  reporter.progress(completed, total, `${story.title}/${story.name} (${browser})`);
@@ -163,22 +155,14 @@ async function runLocalMode(reporter, config, options) {
163
155
  }
164
156
  reporter.info(`Browsers: ${config.browsers.join(', ')}`);
165
157
  reporter.newLine();
166
- // Apply story filter if provided
167
- if (options.story) {
168
- config.include = [options.story];
169
- }
170
158
  // Create storage
171
159
  const storage = createStorage(config.storage);
172
160
  // Discover stories
173
- reporter.startSpinner('Discovering stories...');
174
- const stories = await discoverStories(config);
175
- if (stories.length === 0) {
176
- reporter.failSpinner('No stories found');
177
- reporter.warning('Make sure Storybook is running or the static build exists.');
178
- process.exit(1);
161
+ const stories = await selectStories(reporter, config, options, 'tests');
162
+ if (!stories) {
163
+ return;
179
164
  }
180
165
  const totalTests = stories.length * config.browsers.length;
181
- reporter.succeedSpinner(`Found ${reporter.formatStoryCount(stories.length)} (${totalTests} tests across ${config.browsers.length} browser(s))`);
182
166
  // Capture screenshots
183
167
  reporter.startSpinner('Capturing screenshots...');
184
168
  const screenshots = await captureScreenshots(config, stories, (completed, total, story, browser) => {
@@ -205,18 +189,18 @@ async function runLocalMode(reporter, config, options) {
205
189
  reportLocalResult(result.story, result.comparison);
206
190
  }
207
191
  reporter.reportSummary(summary, config.maxDiffPercent ?? DEFAULT_MAX_DIFF_PERCENT);
208
- // Exit with appropriate code
209
- if (options.ci) {
210
- // In CI mode, fail on any diffs or errors
211
- if (summary.failed > 0 || summary.errors > 0 || summary.newStories > 0) {
212
- process.exit(1);
213
- }
192
+ // A failed comparison exits non-zero whether or not --ci was passed.
193
+ //
194
+ // It used to exit 0 without --ci, which meant any pipeline that forgot the
195
+ // flag went green with visual regressions in it - the tool reporting success
196
+ // having caught something and said nothing. --ci still adds strictness, but
197
+ // only about *new* stories: locally a story with no baseline yet is normal,
198
+ // in a pipeline it means the run was judged against an incomplete set.
199
+ if (summary.failed > 0 || summary.errors > 0) {
200
+ process.exit(1);
214
201
  }
215
- else {
216
- // In normal mode, only fail on errors
217
- if (summary.errors > 0) {
218
- process.exit(1);
219
- }
202
+ if (options.ci && summary.newStories > 0) {
203
+ process.exit(1);
220
204
  }
221
205
  }
222
206
  function reportLocalResult(story, comparison) {
@@ -306,16 +290,13 @@ function reportApiResults(reporter, testRun, options) {
306
290
  else {
307
291
  console.log('\x1b[32mAll visual regression tests passed!\x1b[0m');
308
292
  }
309
- // Exit with appropriate code
310
- if (options.ci) {
311
- if (testRun.failedStories > 0 || testRun.errorStories > 0 || testRun.newStories > 0) {
312
- process.exit(1);
313
- }
293
+ // Same rule as local mode: a failure is a failure regardless of --ci. See the
294
+ // note there for why this is not gated on the flag.
295
+ if (testRun.failedStories > 0 || testRun.errorStories > 0) {
296
+ process.exit(1);
314
297
  }
315
- else {
316
- if (testRun.errorStories > 0) {
317
- process.exit(1);
318
- }
298
+ if (options.ci && testRun.newStories > 0) {
299
+ process.exit(1);
319
300
  }
320
301
  }
321
302
  function buildSummary(stories, browsers, results) {
@@ -0,0 +1,11 @@
1
+ import { type StorySelectionOptions } from '../select-stories.js';
2
+ export interface UpdateOptions extends StorySelectionOptions {
3
+ config?: string;
4
+ browser?: string;
5
+ storybookUrl?: string;
6
+ verbose?: boolean;
7
+ dryRun?: boolean;
8
+ local?: boolean;
9
+ }
10
+ export declare function updateCommand(options?: UpdateOptions): Promise<void>;
11
+ //# sourceMappingURL=update.d.ts.map
@@ -1,9 +1,10 @@
1
1
  import { loadConfig } from '../../config/loader.js';
2
2
  import { loadCredentials } from '../../config/credentials.js';
3
- import { discoverStories, getStoryKey } from '../../core/storybook.js';
3
+ import { getStoryKey } from '../../core/storybook.js';
4
4
  import { captureScreenshots, getScreenshotKey } from '../../core/screenshot.js';
5
5
  import { createStorage } from '../../storage/index.js';
6
6
  import { createReporter } from '../reporter.js';
7
+ import { selectStories } from '../select-stories.js';
7
8
  import { ApiClient } from '../../api/client.js';
8
9
  function parseBrowsers(browserArg) {
9
10
  if (!browserArg) {
@@ -66,20 +67,12 @@ async function runApiMode(reporter, config, apiUrl, apiToken, options) {
66
67
  reporter.info(`Browsers: ${config.browsers.join(', ')}`);
67
68
  reporter.newLine();
68
69
  const client = new ApiClient({ apiUrl, apiToken });
69
- // Apply story filter if provided
70
- if (options.story) {
71
- config.include = [options.story];
72
- }
73
70
  // Discover stories
74
- reporter.startSpinner('Discovering stories...');
75
- const stories = await discoverStories(config);
76
- if (stories.length === 0) {
77
- reporter.failSpinner('No stories found');
78
- reporter.warning('Make sure Storybook is running or the static build exists.');
79
- process.exit(1);
71
+ const stories = await selectStories(reporter, config, options, 'baselines');
72
+ if (!stories) {
73
+ return;
80
74
  }
81
75
  const totalTests = stories.length * config.browsers.length;
82
- reporter.succeedSpinner(`Found ${reporter.formatStoryCount(stories.length)} (${totalTests} baselines across ${config.browsers.length} browser(s))`);
83
76
  // Capture screenshots
84
77
  reporter.startSpinner('Capturing screenshots...');
85
78
  const screenshots = await captureScreenshots(config, stories, (completed, total, story, browser) => {
@@ -153,22 +146,14 @@ async function runLocalMode(reporter, config, options) {
153
146
  }
154
147
  reporter.info(`Browsers: ${config.browsers.join(', ')}`);
155
148
  reporter.newLine();
156
- // Apply story filter if provided
157
- if (options.story) {
158
- config.include = [options.story];
159
- }
160
149
  // Create storage
161
150
  const storage = createStorage(config.storage);
162
151
  // Discover stories
163
- reporter.startSpinner('Discovering stories...');
164
- const stories = await discoverStories(config);
165
- if (stories.length === 0) {
166
- reporter.failSpinner('No stories found');
167
- reporter.warning('Make sure Storybook is running or the static build exists.');
168
- process.exit(1);
152
+ const stories = await selectStories(reporter, config, options, 'baselines');
153
+ if (!stories) {
154
+ return;
169
155
  }
170
156
  const totalTests = stories.length * config.browsers.length;
171
- reporter.succeedSpinner(`Found ${reporter.formatStoryCount(stories.length)} (${totalTests} baselines across ${config.browsers.length} browser(s))`);
172
157
  // Capture screenshots
173
158
  reporter.startSpinner('Capturing screenshots...');
174
159
  const screenshots = await captureScreenshots(config, stories, (completed, total, story, browser) => {
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ export {};
3
+ //# sourceMappingURL=index.d.ts.map
package/dist/cli/index.js CHANGED
@@ -5,6 +5,7 @@ import { updateCommand } from './commands/update.js';
5
5
  import { initCommand } from './commands/init.js';
6
6
  import { loginCommand } from './commands/login.js';
7
7
  import { logoutCommand } from './commands/logout.js';
8
+ import { collectPatterns } from './select-stories.js';
8
9
  const program = new Command();
9
10
  program
10
11
  .name('storysnap')
@@ -24,7 +25,7 @@ program
24
25
  program
25
26
  .command('login')
26
27
  .description('Authenticate with StorySnap API and store credentials')
27
- .option('-u, --api-url <url>', 'API URL (default: https://api.storysnap.dev)')
28
+ .option('-u, --api-url <url>', 'StorySnap server URL, without /api (default: https://api.storysnap.dev)')
28
29
  .option('-t, --token <token>', 'API token (will prompt if not provided)')
29
30
  .option('-v, --verbose', 'Verbose output')
30
31
  .action(async (options) => {
@@ -47,7 +48,9 @@ program
47
48
  .command('test')
48
49
  .description('Run visual regression tests')
49
50
  .option('-c, --config <path>', 'Path to config file')
50
- .option('-s, --story <pattern>', 'Filter stories by pattern (supports * wildcards)')
51
+ .option('-s, --story <pattern>', 'Only stories matching a pattern (* wildcards; repeat or comma-separate for several)', collectPatterns)
52
+ .option('-x, --exclude <pattern>', 'Skip stories matching a pattern (* wildcards; repeat or comma-separate for several)', collectPatterns)
53
+ .option('--changed [ref]', 'Only stories whose files changed since branching off <ref> (default: main, then origin/main)')
51
54
  .option('-b, --browser <browsers>', 'Browsers to test (chromium,firefox,webkit)')
52
55
  .option('--storybook-url <url>', 'Storybook URL, overriding the config file')
53
56
  .option('--branch <branch>', 'Branch name to record on the test run (API mode)')
@@ -59,6 +62,8 @@ program
59
62
  await testCommand({
60
63
  config: options.config,
61
64
  story: options.story,
65
+ exclude: options.exclude,
66
+ changed: options.changed,
62
67
  browser: options.browser,
63
68
  storybookUrl: options.storybookUrl,
64
69
  branch: options.branch,
@@ -72,7 +77,9 @@ program
72
77
  .command('update')
73
78
  .description('Update baseline screenshots')
74
79
  .option('-c, --config <path>', 'Path to config file')
75
- .option('-s, --story <pattern>', 'Filter stories by pattern (supports * wildcards)')
80
+ .option('-s, --story <pattern>', 'Only stories matching a pattern (* wildcards; repeat or comma-separate for several)', collectPatterns)
81
+ .option('-x, --exclude <pattern>', 'Skip stories matching a pattern (* wildcards; repeat or comma-separate for several)', collectPatterns)
82
+ .option('--changed [ref]', 'Only stories whose files changed since branching off <ref> (default: main, then origin/main)')
76
83
  .option('-b, --browser <browsers>', 'Browsers to test (chromium,firefox,webkit)')
77
84
  .option('--storybook-url <url>', 'Storybook URL, overriding the config file')
78
85
  .option('-v, --verbose', 'Verbose output')
@@ -82,6 +89,8 @@ program
82
89
  await updateCommand({
83
90
  config: options.config,
84
91
  story: options.story,
92
+ exclude: options.exclude,
93
+ changed: options.changed,
85
94
  browser: options.browser,
86
95
  storybookUrl: options.storybookUrl,
87
96
  verbose: options.verbose,
@@ -0,0 +1,28 @@
1
+ import type { TestSummary, ComparisonResult, Story } from '@storysnap/shared';
2
+ export declare class Reporter {
3
+ private spinner;
4
+ private verbose;
5
+ constructor(options?: {
6
+ verbose?: boolean;
7
+ });
8
+ startSpinner(text: string): void;
9
+ updateSpinner(text: string): void;
10
+ succeedSpinner(text?: string): void;
11
+ failSpinner(text?: string): void;
12
+ stopSpinner(): void;
13
+ info(message: string): void;
14
+ success(message: string): void;
15
+ warning(message: string): void;
16
+ error(message: string): void;
17
+ newLine(): void;
18
+ header(title: string): void;
19
+ reportResult(story: Story, result: ComparisonResult): void;
20
+ reportSummary(summary: TestSummary, maxDiffPercent?: number): void;
21
+ reportUpdateSummary(updated: number, total: number): void;
22
+ formatStoryCount(count: number): string;
23
+ progress(current: number, total: number, message: string): void;
24
+ }
25
+ export declare function createReporter(options?: {
26
+ verbose?: boolean;
27
+ }): Reporter;
28
+ //# sourceMappingURL=reporter.d.ts.map
@@ -0,0 +1,25 @@
1
+ import type { Story, StorySnapConfig } from '@storysnap/shared';
2
+ import type { Reporter } from './reporter.js';
3
+ export interface StorySelectionOptions {
4
+ /** --story patterns. They narrow the config's include list rather than replacing it. */
5
+ story?: string[];
6
+ /** --exclude patterns, applied on top of the config's exclude list. */
7
+ exclude?: string[];
8
+ /** --changed: true for the default ref, or the ref that was named. */
9
+ changed?: string | boolean;
10
+ }
11
+ /**
12
+ * Commander collector for options that may be repeated or comma-separated,
13
+ * e.g. `--story "Button*" --story "Form/*"` or `--story "Button*,Form/*"`.
14
+ */
15
+ export declare function collectPatterns(value: string, previous?: string[]): string[];
16
+ /**
17
+ * Discovers stories and narrows them by the command-line filters, reporting the
18
+ * result on the spinner. `unit` names what each story-browser pair produces.
19
+ *
20
+ * Returns null when --changed leaves nothing to test, which is a normal outcome
21
+ * for a change that touches no stories. An empty result from the patterns is
22
+ * a mistake instead, so that exits like an empty Storybook does.
23
+ */
24
+ export declare function selectStories(reporter: Reporter, config: StorySnapConfig, options: StorySelectionOptions, unit: 'tests' | 'baselines'): Promise<Story[] | null>;
25
+ //# sourceMappingURL=select-stories.d.ts.map
@@ -0,0 +1,57 @@
1
+ import { discoverStories, filterStories } from '../core/storybook.js';
2
+ import { getChangedFiles, filterChangedStories } from '../core/changed.js';
3
+ /**
4
+ * Commander collector for options that may be repeated or comma-separated,
5
+ * e.g. `--story "Button*" --story "Form/*"` or `--story "Button*,Form/*"`.
6
+ */
7
+ export function collectPatterns(value, previous = []) {
8
+ return previous.concat(value
9
+ .split(',')
10
+ .map((pattern) => pattern.trim())
11
+ .filter(Boolean));
12
+ }
13
+ /**
14
+ * Discovers stories and narrows them by the command-line filters, reporting the
15
+ * result on the spinner. `unit` names what each story-browser pair produces.
16
+ *
17
+ * Returns null when --changed leaves nothing to test, which is a normal outcome
18
+ * for a change that touches no stories. An empty result from the patterns is
19
+ * a mistake instead, so that exits like an empty Storybook does.
20
+ */
21
+ export async function selectStories(reporter, config, options, unit) {
22
+ reporter.startSpinner('Discovering stories...');
23
+ const discovered = await discoverStories(config);
24
+ if (discovered.length === 0) {
25
+ reporter.failSpinner('No stories found');
26
+ reporter.warning('Make sure Storybook is running or the static build exists.');
27
+ process.exit(1);
28
+ }
29
+ let stories = filterStories(discovered, options.story, options.exclude);
30
+ if (stories.length === 0) {
31
+ reporter.failSpinner('No stories match the --story/--exclude filters');
32
+ reporter.info(`Patterns are matched against story IDs, titles and names, e.g. "button--primary" or "Components/Button/*".`);
33
+ process.exit(1);
34
+ }
35
+ let changedSuffix = '';
36
+ if (options.changed) {
37
+ reporter.updateSpinner('Finding changed files...');
38
+ const { ref, files } = await getChangedFiles(typeof options.changed === 'string' ? options.changed : undefined);
39
+ const result = filterChangedStories(stories, files);
40
+ if (result.stories.length === 0) {
41
+ reporter.succeedSpinner(`No stories affected by changes since ${ref} - nothing to do`);
42
+ return null;
43
+ }
44
+ if (result.unknown > 0) {
45
+ reporter.warning(`${reporter.formatStoryCount(result.unknown)} have no file path in the Storybook index, so --changed included them`);
46
+ }
47
+ stories = result.stories;
48
+ changedSuffix = ` changed since ${ref}`;
49
+ }
50
+ const total = stories.length * config.browsers.length;
51
+ const counted = stories.length === discovered.length
52
+ ? `Found ${reporter.formatStoryCount(stories.length)}`
53
+ : `Selected ${stories.length} of ${reporter.formatStoryCount(discovered.length)}${changedSuffix}`;
54
+ reporter.succeedSpinner(`${counted} (${total} ${unit} across ${config.browsers.length} browser(s))`);
55
+ return stories;
56
+ }
57
+ //# sourceMappingURL=select-stories.js.map
@@ -0,0 +1,9 @@
1
+ export interface Credentials {
2
+ apiUrl: string;
3
+ apiToken: string;
4
+ }
5
+ export declare function saveCredentials(credentials: Credentials): Promise<void>;
6
+ export declare function loadCredentials(): Promise<Credentials | null>;
7
+ export declare function deleteCredentials(): Promise<boolean>;
8
+ export declare function getCredentialsPath(): string;
9
+ //# sourceMappingURL=credentials.d.ts.map
@@ -0,0 +1,12 @@
1
+ import { type Config } from './schema.js';
2
+ export declare function findConfigFile(cwd?: string): Promise<string | null>;
3
+ export declare function loadConfig(configPath?: string, cwd?: string): Promise<Config>;
4
+ export declare function getDefaultConfig(): string;
5
+ /**
6
+ * The TypeScript template as plain JavaScript, typed through JSDoc so editors
7
+ * still check it. The import stays type-only, so the config runs without
8
+ * @storysnap/cli being resolvable from it - under npx, for instance.
9
+ */
10
+ export declare function getDefaultConfigJs(): string;
11
+ export declare function getDefaultConfigJson(): string;
12
+ //# sourceMappingURL=loader.d.ts.map
@@ -58,13 +58,25 @@ const config: StorySnapConfig = {
58
58
  storybookUrl: 'http://localhost:6006',
59
59
  // storybookStaticDir: './storybook-static',
60
60
 
61
- // Storage configuration
62
- storage: {
63
- type: 's3',
64
- bucket: 'my-snapshots',
65
- region: 'us-east-1',
66
- prefix: 'storysnap/',
67
- },
61
+ // Where baselines live depends on the mode the CLI runs in:
62
+ //
63
+ // - API mode: used when an API URL and token are available, from
64
+ // "storysnap login", STORYSNAP_API_URL/STORYSNAP_API_TOKEN, or apiUrl and
65
+ // apiToken here. The server stores everything and the storage setting
66
+ // below is ignored. Runs show up in the dashboard.
67
+ // - Local mode: used otherwise, or with --local. Baselines are written to
68
+ // .storysnap/baselines unless you set storage yourself, for example:
69
+ //
70
+ // storage: {
71
+ // type: 's3',
72
+ // bucket: 'my-snapshots',
73
+ // region: 'us-east-1',
74
+ // prefix: 'storysnap/',
75
+ // // For S3-compatible storage such as MinIO:
76
+ // // endpoint: 'http://localhost:9000',
77
+ // // accessKeyId: '...',
78
+ // // secretAccessKey: '...',
79
+ // },
68
80
 
69
81
  // Screenshot settings
70
82
  viewport: { width: 1280, height: 720 },
@@ -84,15 +96,19 @@ const config: StorySnapConfig = {
84
96
  export default config;
85
97
  `;
86
98
  }
99
+ /**
100
+ * The TypeScript template as plain JavaScript, typed through JSDoc so editors
101
+ * still check it. The import stays type-only, so the config runs without
102
+ * @storysnap/cli being resolvable from it - under npx, for instance.
103
+ */
104
+ export function getDefaultConfigJs() {
105
+ return getDefaultConfig()
106
+ .replace("import type { StorySnapConfig } from '@storysnap/cli';\n\nconst config: StorySnapConfig = ", "/** @type {import('@storysnap/cli').StorySnapConfig} */\nexport default ")
107
+ .replace(/\n+export default config;\n$/, '\n');
108
+ }
87
109
  export function getDefaultConfigJson() {
88
110
  return JSON.stringify({
89
111
  storybookUrl: 'http://localhost:6006',
90
- storage: {
91
- type: 's3',
92
- bucket: 'my-snapshots',
93
- region: 'us-east-1',
94
- prefix: 'storysnap/',
95
- },
96
112
  viewport: { width: 1280, height: 720 },
97
113
  threshold: 0.1,
98
114
  maxDiffPercent: 0.1,
@@ -0,0 +1,182 @@
1
+ import { z } from 'zod';
2
+ declare const browserSchema: z.ZodEnum<["chromium", "firefox", "webkit"]>;
3
+ export type Browser = z.infer<typeof browserSchema>;
4
+ export declare const configSchema: z.ZodEffects<z.ZodObject<{
5
+ storybookUrl: z.ZodOptional<z.ZodString>;
6
+ storybookStaticDir: z.ZodOptional<z.ZodString>;
7
+ storage: z.ZodDefault<z.ZodDiscriminatedUnion<"type", [z.ZodObject<{
8
+ type: z.ZodLiteral<"s3">;
9
+ bucket: z.ZodString;
10
+ region: z.ZodString;
11
+ prefix: z.ZodOptional<z.ZodString>;
12
+ endpoint: z.ZodOptional<z.ZodString>;
13
+ accessKeyId: z.ZodOptional<z.ZodString>;
14
+ secretAccessKey: z.ZodOptional<z.ZodString>;
15
+ }, "strip", z.ZodTypeAny, {
16
+ type: "s3";
17
+ bucket: string;
18
+ region: string;
19
+ prefix?: string | undefined;
20
+ endpoint?: string | undefined;
21
+ accessKeyId?: string | undefined;
22
+ secretAccessKey?: string | undefined;
23
+ }, {
24
+ type: "s3";
25
+ bucket: string;
26
+ region: string;
27
+ prefix?: string | undefined;
28
+ endpoint?: string | undefined;
29
+ accessKeyId?: string | undefined;
30
+ secretAccessKey?: string | undefined;
31
+ }>, z.ZodObject<{
32
+ type: z.ZodLiteral<"local">;
33
+ directory: z.ZodString;
34
+ }, "strip", z.ZodTypeAny, {
35
+ type: "local";
36
+ directory: string;
37
+ }, {
38
+ type: "local";
39
+ directory: string;
40
+ }>]>>;
41
+ viewport: z.ZodDefault<z.ZodObject<{
42
+ width: z.ZodDefault<z.ZodNumber>;
43
+ height: z.ZodDefault<z.ZodNumber>;
44
+ }, "strip", z.ZodTypeAny, {
45
+ width: number;
46
+ height: number;
47
+ }, {
48
+ width?: number | undefined;
49
+ height?: number | undefined;
50
+ }>>;
51
+ browsers: z.ZodDefault<z.ZodArray<z.ZodEnum<["chromium", "firefox", "webkit"]>, "many">>;
52
+ threshold: z.ZodOptional<z.ZodNumber>;
53
+ maxDiffPercent: z.ZodOptional<z.ZodNumber>;
54
+ localSnapshotsDir: z.ZodOptional<z.ZodString>;
55
+ include: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
56
+ exclude: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
57
+ waitForSelector: z.ZodDefault<z.ZodString>;
58
+ waitTimeout: z.ZodDefault<z.ZodNumber>;
59
+ apiUrl: z.ZodOptional<z.ZodString>;
60
+ apiToken: z.ZodOptional<z.ZodString>;
61
+ }, "strip", z.ZodTypeAny, {
62
+ storage: {
63
+ type: "s3";
64
+ bucket: string;
65
+ region: string;
66
+ prefix?: string | undefined;
67
+ endpoint?: string | undefined;
68
+ accessKeyId?: string | undefined;
69
+ secretAccessKey?: string | undefined;
70
+ } | {
71
+ type: "local";
72
+ directory: string;
73
+ };
74
+ viewport: {
75
+ width: number;
76
+ height: number;
77
+ };
78
+ browsers: ("chromium" | "firefox" | "webkit")[];
79
+ waitForSelector: string;
80
+ waitTimeout: number;
81
+ storybookUrl?: string | undefined;
82
+ storybookStaticDir?: string | undefined;
83
+ threshold?: number | undefined;
84
+ maxDiffPercent?: number | undefined;
85
+ localSnapshotsDir?: string | undefined;
86
+ include?: string[] | undefined;
87
+ exclude?: string[] | undefined;
88
+ apiUrl?: string | undefined;
89
+ apiToken?: string | undefined;
90
+ }, {
91
+ storybookUrl?: string | undefined;
92
+ storybookStaticDir?: string | undefined;
93
+ storage?: {
94
+ type: "s3";
95
+ bucket: string;
96
+ region: string;
97
+ prefix?: string | undefined;
98
+ endpoint?: string | undefined;
99
+ accessKeyId?: string | undefined;
100
+ secretAccessKey?: string | undefined;
101
+ } | {
102
+ type: "local";
103
+ directory: string;
104
+ } | undefined;
105
+ viewport?: {
106
+ width?: number | undefined;
107
+ height?: number | undefined;
108
+ } | undefined;
109
+ browsers?: ("chromium" | "firefox" | "webkit")[] | undefined;
110
+ threshold?: number | undefined;
111
+ maxDiffPercent?: number | undefined;
112
+ localSnapshotsDir?: string | undefined;
113
+ include?: string[] | undefined;
114
+ exclude?: string[] | undefined;
115
+ waitForSelector?: string | undefined;
116
+ waitTimeout?: number | undefined;
117
+ apiUrl?: string | undefined;
118
+ apiToken?: string | undefined;
119
+ }>, {
120
+ storage: {
121
+ type: "s3";
122
+ bucket: string;
123
+ region: string;
124
+ prefix?: string | undefined;
125
+ endpoint?: string | undefined;
126
+ accessKeyId?: string | undefined;
127
+ secretAccessKey?: string | undefined;
128
+ } | {
129
+ type: "local";
130
+ directory: string;
131
+ };
132
+ viewport: {
133
+ width: number;
134
+ height: number;
135
+ };
136
+ browsers: ("chromium" | "firefox" | "webkit")[];
137
+ waitForSelector: string;
138
+ waitTimeout: number;
139
+ storybookUrl?: string | undefined;
140
+ storybookStaticDir?: string | undefined;
141
+ threshold?: number | undefined;
142
+ maxDiffPercent?: number | undefined;
143
+ localSnapshotsDir?: string | undefined;
144
+ include?: string[] | undefined;
145
+ exclude?: string[] | undefined;
146
+ apiUrl?: string | undefined;
147
+ apiToken?: string | undefined;
148
+ }, {
149
+ storybookUrl?: string | undefined;
150
+ storybookStaticDir?: string | undefined;
151
+ storage?: {
152
+ type: "s3";
153
+ bucket: string;
154
+ region: string;
155
+ prefix?: string | undefined;
156
+ endpoint?: string | undefined;
157
+ accessKeyId?: string | undefined;
158
+ secretAccessKey?: string | undefined;
159
+ } | {
160
+ type: "local";
161
+ directory: string;
162
+ } | undefined;
163
+ viewport?: {
164
+ width?: number | undefined;
165
+ height?: number | undefined;
166
+ } | undefined;
167
+ browsers?: ("chromium" | "firefox" | "webkit")[] | undefined;
168
+ threshold?: number | undefined;
169
+ maxDiffPercent?: number | undefined;
170
+ localSnapshotsDir?: string | undefined;
171
+ include?: string[] | undefined;
172
+ exclude?: string[] | undefined;
173
+ waitForSelector?: string | undefined;
174
+ waitTimeout?: number | undefined;
175
+ apiUrl?: string | undefined;
176
+ apiToken?: string | undefined;
177
+ }>;
178
+ export type ConfigInput = z.input<typeof configSchema>;
179
+ export type Config = z.output<typeof configSchema>;
180
+ export declare function validateConfig(input: unknown): Config;
181
+ export {};
182
+ //# sourceMappingURL=schema.d.ts.map
@@ -0,0 +1,26 @@
1
+ import type { Story } from '@storysnap/shared';
2
+ /**
3
+ * Files that differ from the point where HEAD branched off `ref`: committed,
4
+ * staged, unstaged and untracked. Comparing against the merge base rather than
5
+ * `ref` itself keeps commits that landed on `ref` since then out of the list.
6
+ *
7
+ * Paths are relative to `cwd`, which matches Storybook's importPath as long as
8
+ * the CLI runs from the directory Storybook runs from.
9
+ */
10
+ export declare function getChangedFiles(ref?: string, cwd?: string): Promise<{
11
+ ref: string;
12
+ files: string[];
13
+ }>;
14
+ /**
15
+ * Keeps the stories whose story file, or a file next to it sharing its name,
16
+ * is among `changedFiles`. That catches edits to the component a story file
17
+ * covers, but not to anything it imports from further away.
18
+ *
19
+ * Stories the index gives no file path for are kept, since there is no way to
20
+ * tell whether they changed; `unknown` counts them.
21
+ */
22
+ export declare function filterChangedStories(stories: Story[], changedFiles: string[]): {
23
+ stories: Story[];
24
+ unknown: number;
25
+ };
26
+ //# sourceMappingURL=changed.d.ts.map
@@ -0,0 +1,78 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { posix } from 'node:path';
3
+ import { promisify } from 'node:util';
4
+ const execFileAsync = promisify(execFile);
5
+ /** Used by `--changed` with no ref. CI checkouts often only have the remote one. */
6
+ const DEFAULT_REFS = ['main', 'origin/main'];
7
+ async function git(args, cwd) {
8
+ const { stdout } = await execFileAsync('git', args, { cwd, maxBuffer: 64 * 1024 * 1024 });
9
+ return stdout;
10
+ }
11
+ /** Parses `-z` output, which leaves unusual file names unquoted. */
12
+ function splitNul(output) {
13
+ return output.split('\0').filter(Boolean);
14
+ }
15
+ async function findMergeBase(refs, cwd) {
16
+ for (const ref of refs) {
17
+ try {
18
+ const base = (await git(['merge-base', ref, 'HEAD'], cwd)).trim();
19
+ return { ref, base };
20
+ }
21
+ catch {
22
+ // Try the next candidate
23
+ }
24
+ }
25
+ const tried = refs.map((ref) => `"${ref}"`).join(' or ');
26
+ throw new Error(`Could not compare against ${tried}. Make sure this is a git repository and the ref exists - ` +
27
+ 'CI checkouts are often shallow, so fetch it first (e.g. "git fetch origin main") ' +
28
+ 'or name one explicitly with --changed <ref>.');
29
+ }
30
+ /**
31
+ * Files that differ from the point where HEAD branched off `ref`: committed,
32
+ * staged, unstaged and untracked. Comparing against the merge base rather than
33
+ * `ref` itself keeps commits that landed on `ref` since then out of the list.
34
+ *
35
+ * Paths are relative to `cwd`, which matches Storybook's importPath as long as
36
+ * the CLI runs from the directory Storybook runs from.
37
+ */
38
+ export async function getChangedFiles(ref, cwd = process.cwd()) {
39
+ const { ref: resolvedRef, base } = await findMergeBase(ref ? [ref] : DEFAULT_REFS, cwd);
40
+ const [tracked, untracked] = await Promise.all([
41
+ git(['diff', '--name-only', '--relative', '-z', base], cwd),
42
+ git(['ls-files', '--others', '--exclude-standard', '-z'], cwd),
43
+ ]);
44
+ return { ref: resolvedRef, files: [...splitNul(tracked), ...splitNul(untracked)] };
45
+ }
46
+ function normalizePath(path) {
47
+ return path.replace(/\\/g, '/').replace(/^\.\//, '');
48
+ }
49
+ /**
50
+ * Groups a file with its siblings by directory and the name before the first
51
+ * dot, so Button.stories.tsx, Button.tsx and Button.module.css share a key.
52
+ */
53
+ function siblingKey(path) {
54
+ const normalized = normalizePath(path);
55
+ const name = posix.basename(normalized).split('.')[0];
56
+ return `${posix.dirname(normalized)}/${name}`;
57
+ }
58
+ /**
59
+ * Keeps the stories whose story file, or a file next to it sharing its name,
60
+ * is among `changedFiles`. That catches edits to the component a story file
61
+ * covers, but not to anything it imports from further away.
62
+ *
63
+ * Stories the index gives no file path for are kept, since there is no way to
64
+ * tell whether they changed; `unknown` counts them.
65
+ */
66
+ export function filterChangedStories(stories, changedFiles) {
67
+ const changed = new Set(changedFiles.map(siblingKey));
68
+ let unknown = 0;
69
+ const selected = stories.filter((story) => {
70
+ if (!story.componentPath) {
71
+ unknown++;
72
+ return true;
73
+ }
74
+ return changed.has(siblingKey(story.componentPath));
75
+ });
76
+ return { stories: selected, unknown };
77
+ }
78
+ //# sourceMappingURL=changed.js.map
@@ -0,0 +1,23 @@
1
+ import type { Screenshot, ComparisonResult, StorageProvider } from '@storysnap/shared';
2
+ /**
3
+ * Local-mode fallbacks. In API mode the equivalent defaults live on the
4
+ * `projects` row so they can be changed without editing a config file; there is
5
+ * no server here to ask, so the same numbers are repeated.
6
+ */
7
+ export declare const DEFAULT_THRESHOLD = 0.1;
8
+ export declare const DEFAULT_MAX_DIFF_PERCENT = 0.1;
9
+ export interface CompareOptions {
10
+ /** pixelmatch per-pixel colour sensitivity (0-1). Smaller is more sensitive. */
11
+ threshold?: number;
12
+ /**
13
+ * How much of the image may differ before the story fails, as a percentage.
14
+ * Must match the rule the worker applies, or local and cloud runs would
15
+ * reach different verdicts about the same screenshots.
16
+ */
17
+ maxDiffPercent?: number;
18
+ storage: StorageProvider;
19
+ localSnapshotsDir?: string;
20
+ }
21
+ export declare function compareScreenshot(screenshot: Screenshot, options: CompareOptions): Promise<ComparisonResult>;
22
+ export declare function compareAllScreenshots(screenshots: Map<string, Screenshot>, options: CompareOptions, onProgress?: (completed: number, total: number, key: string) => void): Promise<Map<string, ComparisonResult>>;
23
+ //# sourceMappingURL=compare.d.ts.map
@@ -0,0 +1,19 @@
1
+ import type { Story, Screenshot, StorySnapConfig, Browser } from '@storysnap/shared';
2
+ export declare class ScreenshotEngine {
3
+ private browsers;
4
+ private config;
5
+ private baseUrl;
6
+ constructor(config: StorySnapConfig);
7
+ initialize(): Promise<void>;
8
+ close(): Promise<void>;
9
+ captureStory(story: Story, browserName: Browser): Promise<Screenshot>;
10
+ captureStories(stories: Story[], onProgress?: (completed: number, total: number, story: Story, browser: Browser) => void): Promise<Map<string, Screenshot>>;
11
+ private waitForStability;
12
+ }
13
+ export declare function getScreenshotKey(storyId: string, browser: Browser): string;
14
+ export declare function parseScreenshotKey(key: string): {
15
+ storyId: string;
16
+ browser: Browser;
17
+ };
18
+ export declare function captureScreenshots(config: StorySnapConfig, stories: Story[], onProgress?: (completed: number, total: number, story: Story, browser: Browser) => void): Promise<Map<string, Screenshot>>;
19
+ //# sourceMappingURL=screenshot.d.ts.map
@@ -0,0 +1,6 @@
1
+ import type { Story, StorySnapConfig, Browser } from '@storysnap/shared';
2
+ export declare function discoverStories(config: StorySnapConfig): Promise<Story[]>;
3
+ export declare function filterStories(stories: Story[], include?: string[], exclude?: string[]): Story[];
4
+ export declare function getStoryUrl(baseUrl: string, storyId: string): string;
5
+ export declare function getStoryKey(storyId: string, browser?: Browser): string;
6
+ //# sourceMappingURL=storybook.d.ts.map
@@ -85,7 +85,7 @@ function parseIndex(index) {
85
85
  }
86
86
  return stories;
87
87
  }
88
- function filterStories(stories, include, exclude) {
88
+ export function filterStories(stories, include, exclude) {
89
89
  let filtered = stories;
90
90
  if (include && include.length > 0) {
91
91
  filtered = filtered.filter((story) => include.some((pattern) => matchPattern(story, pattern)));
@@ -0,0 +1,2 @@
1
+ export type { Story, Viewport, S3StorageConfig, LocalStorageConfig, StorageConfig, StorySnapConfig, Screenshot, ComparisonResult, StoryTestResult, TestSummary, StorageProvider, } from '@storysnap/shared';
2
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1,10 @@
1
+ import type { ConfigInput } from './config/schema.js';
2
+ export type { Browser } from './config/schema.js';
3
+ /**
4
+ * The shape of `storysnap.config.ts`. This is the input the config loader
5
+ * accepts, so settings with defaults are optional.
6
+ */
7
+ export type StorySnapConfig = ConfigInput;
8
+ /** Types a config object without changing it. */
9
+ export declare function defineConfig(config: StorySnapConfig): StorySnapConfig;
10
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,12 @@
1
+ // The package's library entry, for config files. Kept apart from cli/index.ts,
2
+ // which parses argv as soon as it is loaded - importing that from a config file
3
+ // would run the CLI.
4
+ //
5
+ // Only types and side-effect-free helpers belong here. Nothing exported may
6
+ // reference @storysnap/shared: it is a devDependency, so consumers' type
7
+ // checkers cannot resolve it.
8
+ /** Types a config object without changing it. */
9
+ export function defineConfig(config) {
10
+ return config;
11
+ }
12
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,5 @@
1
+ import type { StorageConfig, StorageProvider } from '@storysnap/shared';
2
+ export declare function createStorage(config: StorageConfig): StorageProvider;
3
+ export { S3Storage } from './s3.js';
4
+ export { LocalStorage, ensureDir } from './local.js';
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,13 @@
1
+ import type { StorageProvider, LocalStorageConfig } from '@storysnap/shared';
2
+ export declare class LocalStorage implements StorageProvider {
3
+ private directory;
4
+ constructor(config: LocalStorageConfig);
5
+ private getPath;
6
+ upload(key: string, data: Buffer): Promise<void>;
7
+ download(key: string): Promise<Buffer | null>;
8
+ exists(key: string): Promise<boolean>;
9
+ list(prefix?: string): Promise<string[]>;
10
+ delete(key: string): Promise<void>;
11
+ }
12
+ export declare function ensureDir(dir: string): Promise<void>;
13
+ //# sourceMappingURL=local.d.ts.map
@@ -0,0 +1,14 @@
1
+ import type { StorageProvider, S3StorageConfig } from '@storysnap/shared';
2
+ export declare class S3Storage implements StorageProvider {
3
+ private client;
4
+ private bucket;
5
+ private prefix;
6
+ constructor(config: S3StorageConfig);
7
+ private getKey;
8
+ upload(key: string, data: Buffer): Promise<void>;
9
+ download(key: string): Promise<Buffer | null>;
10
+ exists(key: string): Promise<boolean>;
11
+ list(prefix?: string): Promise<string[]>;
12
+ delete(key: string): Promise<void>;
13
+ }
14
+ //# sourceMappingURL=s3.d.ts.map
package/package.json CHANGED
@@ -1,9 +1,17 @@
1
1
  {
2
2
  "name": "@storysnap/cli",
3
- "version": "1.0.0",
3
+ "version": "1.2.0",
4
4
  "description": "Visual regression testing for Storybook - capture screenshots, detect changes, and maintain baselines",
5
5
  "type": "module",
6
- "main": "dist/cli/index.js",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ },
13
+ "./package.json": "./package.json"
14
+ },
7
15
  "bin": {
8
16
  "storysnap": "./dist/cli/index.js"
9
17
  },
@@ -12,7 +20,6 @@
12
20
  "!dist/**/*.test.js",
13
21
  "!dist/**/*.test.d.ts",
14
22
  "!dist/**/*.map",
15
- "!dist/**/*.d.ts",
16
23
  "!dist/**/*.d.ts.map",
17
24
  "README.md",
18
25
  "LICENSE"