@cappa/plugin-storybook 0.8.0 → 0.8.1

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/dist/index.cjs DELETED
@@ -1,423 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/index.cjs.ts
31
- var index_cjs_exports = {};
32
- __export(index_cjs_exports, {
33
- cappaPluginStorybook: () => cappaPluginStorybook,
34
- previewAnnotations: () => previewAnnotations
35
- });
36
- module.exports = __toCommonJS(index_cjs_exports);
37
-
38
- // src/cappa/plugin.ts
39
- var import_logger = require("@cappa/logger");
40
-
41
- // src/cappa/storybook-url.ts
42
- function encodePairs(obj) {
43
- if (!obj || !Object.keys(obj).length) return "";
44
- return Object.entries(obj).filter(([, v]) => v !== void 0).map(([k, v]) => {
45
- const val = typeof v === "string" ? encodeURIComponent(v) : typeof v === "number" || typeof v === "boolean" ? String(v) : encodeURIComponent(JSON.stringify(v));
46
- return `${encodeURIComponent(k)}:${val}`;
47
- }).join(";");
48
- }
49
- function buildStorybookIframeUrl({
50
- baseUrl,
51
- storyId,
52
- viewMode = "story",
53
- args,
54
- globals,
55
- query,
56
- fullscreen = true,
57
- singleStory = true
58
- }) {
59
- const u = new URL("/iframe.html", baseUrl);
60
- u.searchParams.set("id", storyId);
61
- u.searchParams.set("viewMode", viewMode);
62
- const argPairs = encodePairs(args);
63
- if (argPairs) u.searchParams.set("args", argPairs);
64
- const globalPairs = encodePairs(globals);
65
- if (globalPairs) u.searchParams.set("globals", globalPairs);
66
- if (fullscreen) u.searchParams.set("full", "1");
67
- if (singleStory) u.searchParams.set("singleStory", "true");
68
- if (query) {
69
- for (const [k, v] of Object.entries(query)) {
70
- if (v === void 0) continue;
71
- u.searchParams.set(k, String(v));
72
- }
73
- }
74
- return u.toString();
75
- }
76
-
77
- // src/cappa/util.ts
78
- var freezeUI = async (page) => {
79
- await page.addStyleTag({
80
- content: `
81
- *, *::before, *::after {
82
- -moz-animation: none !important;
83
- -moz-transition: none !important;
84
- transition: none !important;
85
- animation: none !important;
86
- }
87
- *, input, textarea { caret-color: transparent !important }
88
- *:focus { outline: none !important }
89
- *:focus-visible { outline: none !important }
90
- *:focus-within { outline: none !important }
91
- * { text-rendering: optimizeLegibility !important }
92
- ::-webkit-scrollbar { display: none !important }
93
- html { scroll-behavior: auto !important }
94
- svg, svg * {
95
- shape-rendering: crispEdges !important;
96
- text-rendering: geometricPrecision !important;
97
- vector-effect: non-scaling-stroke !important;
98
- }
99
- img { image-rendering: crisp-edges !important }
100
- `
101
- });
102
- };
103
- var waitForVisualIdle = async (page) => {
104
- await page.waitForLoadState("load");
105
- await page.evaluate(async () => {
106
- await document.fonts?.ready?.catch(() => {
107
- });
108
- const imgs = Array.from(document.images).filter((i) => !i.complete);
109
- await Promise.all(
110
- imgs.map(
111
- (i) => new Promise((res) => {
112
- i.onload = i.onerror = () => res(null);
113
- })
114
- )
115
- );
116
- });
117
- await page.evaluate(
118
- ({ minIdleMs }) => new Promise((resolve) => {
119
- let timer = null;
120
- let last = performance.now();
121
- const done = () => {
122
- if (timer) cancelAnimationFrame(timer);
123
- resolve();
124
- };
125
- const mo = new MutationObserver(() => {
126
- last = performance.now();
127
- });
128
- mo.observe(document, {
129
- attributes: true,
130
- childList: true,
131
- subtree: true,
132
- characterData: true
133
- });
134
- const tick = () => {
135
- if (performance.now() - last >= minIdleMs) {
136
- mo.disconnect();
137
- done();
138
- } else {
139
- timer = requestAnimationFrame(tick);
140
- }
141
- };
142
- requestAnimationFrame(() => requestAnimationFrame(tick));
143
- }),
144
- { minIdleMs: 100 }
145
- );
146
- };
147
- var buildFilename = (story) => {
148
- return `${story.title.replace(/[^a-zA-Z0-9/]/g, "")}/${story.name.replace(/[^a-zA-Z0-9]/g, "")}.png`;
149
- };
150
-
151
- // src/cappa/plugin.ts
152
- async function waitForPlayFunctionCompletion(page, storyName) {
153
- const logger = (0, import_logger.getLogger)();
154
- try {
155
- const hasPlayFunction = await page.evaluate(
156
- () => window.__cappa_has_play_function === true
157
- );
158
- if (!hasPlayFunction) {
159
- return;
160
- }
161
- logger.debug(
162
- `Waiting for play function to complete for story: ${storyName}`
163
- );
164
- await page.waitForFunction(() => window.playAfterEach === true, {
165
- timeout: 1e4
166
- });
167
- logger.debug(`Play function completed for story: ${storyName}`);
168
- await page.evaluate(() => {
169
- window.playAfterEach = false;
170
- window.__cappa_has_play_function = false;
171
- });
172
- } catch {
173
- await page.evaluate(() => {
174
- window.playAfterEach = false;
175
- window.__cappa_has_play_function = false;
176
- });
177
- }
178
- }
179
- function toFilterContext(story) {
180
- return {
181
- id: story.id,
182
- title: story.title,
183
- name: story.name,
184
- filePath: `${story.title}/${story.name}`
185
- };
186
- }
187
- function createLatch() {
188
- let resolve;
189
- const p = new Promise((r) => {
190
- resolve = r;
191
- });
192
- return { p, resolve };
193
- }
194
- var cappaPluginStorybook = (options) => {
195
- return {
196
- name: "StorybookPlugin",
197
- description: "Takes screenshots of Storybook stories with configurable options",
198
- discover: async (screenshotTool) => {
199
- if (!options) {
200
- throw new Error("Storybook plugin options are required");
201
- }
202
- if (!options.storybookUrl) {
203
- throw new Error("storybookUrl is required");
204
- }
205
- const logger = (0, import_logger.getLogger)();
206
- const {
207
- storybookUrl,
208
- includeStories,
209
- excludeStories,
210
- storybook: defaultStorybookOptions
211
- } = options;
212
- const storiesUrl = `${storybookUrl}/index.json`;
213
- logger.debug(`Fetching stories from: ${storiesUrl}`);
214
- const timeout = screenshotTool.connectionTimeout;
215
- let response;
216
- try {
217
- response = await fetch(storiesUrl, {
218
- signal: AbortSignal.timeout(timeout)
219
- });
220
- } catch (error) {
221
- if (error instanceof DOMException && error.name === "TimeoutError") {
222
- throw new Error(
223
- `Connection to Storybook at ${storybookUrl} timed out after ${timeout}ms. Make sure Storybook is running and accessible.`
224
- );
225
- }
226
- throw new Error(
227
- `Failed to connect to Storybook at ${storybookUrl}. Make sure Storybook is running and accessible. Error: ${error.message}`
228
- );
229
- }
230
- if (!response.ok) {
231
- throw new Error(
232
- `Failed to fetch stories: ${response.status} ${response.statusText}`
233
- );
234
- }
235
- const data = await response.json();
236
- const stories = Object.values(data.entries);
237
- let filteredStories = stories;
238
- if (includeStories) {
239
- filteredStories = filteredStories.filter(
240
- (story) => includeStories(toFilterContext(story))
241
- );
242
- }
243
- if (excludeStories) {
244
- filteredStories = filteredStories.filter(
245
- (story) => !excludeStories(toFilterContext(story))
246
- );
247
- }
248
- filteredStories = filteredStories.filter(
249
- (story) => story.type === "story"
250
- );
251
- logger.start(`Found ${filteredStories.length} stories to screenshot...`);
252
- return filteredStories.map((story) => ({
253
- id: story.id,
254
- url: buildStorybookIframeUrl({
255
- baseUrl: storybookUrl,
256
- storyId: story.id,
257
- viewMode: defaultStorybookOptions?.viewMode,
258
- args: defaultStorybookOptions?.args,
259
- globals: defaultStorybookOptions?.globals,
260
- query: defaultStorybookOptions?.query,
261
- fullscreen: defaultStorybookOptions?.fullscreen,
262
- singleStory: defaultStorybookOptions?.singleStory
263
- }),
264
- data: {
265
- story
266
- }
267
- }));
268
- },
269
- initPage: async (page, screenshotTool) => {
270
- const logger = (0, import_logger.getLogger)();
271
- const { logConsoleEvents = true } = screenshotTool;
272
- const latchMap = /* @__PURE__ */ new Map();
273
- await page.exposeFunction(
274
- "__cappa_parameters",
275
- async (id, payload) => {
276
- latchMap.get(id)?.resolve?.(payload);
277
- }
278
- );
279
- if (logConsoleEvents) {
280
- page.on("console", (message) => {
281
- logger.debug("console", message.text());
282
- });
283
- }
284
- page.on("pageerror", (error) => {
285
- logger.debug("pageerror", error);
286
- });
287
- return { latchMap };
288
- },
289
- // Phase 2: Execute single story
290
- execute: async (task, page, screenshotTool, context) => {
291
- const { url, data } = task;
292
- const { story } = data;
293
- const logger = (0, import_logger.getLogger)();
294
- const { storybook: defaultStorybookOptions } = options || {};
295
- try {
296
- const currentLatch = createLatch();
297
- context.latchMap.set(story.id, currentLatch);
298
- const captureStart = performance.now();
299
- await page.goto(url, { timeout: screenshotTool.connectionTimeout });
300
- const storyParameters = await context.latchMap.get(story.id)?.p;
301
- context.latchMap.delete(story.id);
302
- const variantParameters = storyParameters?.variants ?? [];
303
- if (storyParameters?.skip) {
304
- logger.warn(`Skipping story ${story.title} - ${story.name}`);
305
- return {
306
- storyId: story.id,
307
- storyName: `${story.title} - ${story.name}`,
308
- skipped: true
309
- };
310
- }
311
- if (storyParameters && Object.keys(storyParameters).length > 0) {
312
- logger.debug("Taking screenshot with options", storyParameters);
313
- }
314
- const resolvedViewport = storyParameters?.viewport ?? screenshotTool.viewport;
315
- await page.setViewportSize(resolvedViewport);
316
- await freezeUI(page);
317
- await waitForVisualIdle(page);
318
- await waitForPlayFunctionCompletion(
319
- page,
320
- `${story.title} - ${story.name}`
321
- );
322
- const toLocatorMask = (mask) => mask?.map((selector) => page.locator(selector));
323
- const filename = buildFilename(story);
324
- const variantsWithUrls = [];
325
- const variantExtrasEntries = [];
326
- for (const variant of variantParameters) {
327
- const variantFilename = variant.filename || screenshotTool.getVariantFilename(filename, {
328
- id: variant.id,
329
- label: variant.label,
330
- filename: variant.filename
331
- });
332
- const mergedArgs = {
333
- ...defaultStorybookOptions?.args,
334
- ...variant.options?.args
335
- };
336
- variantsWithUrls.push({
337
- id: variant.id,
338
- label: variant.label,
339
- filename: variantFilename,
340
- url: buildStorybookIframeUrl({
341
- baseUrl: options?.storybookUrl || "",
342
- storyId: story.id,
343
- viewMode: defaultStorybookOptions?.viewMode,
344
- args: mergedArgs,
345
- globals: defaultStorybookOptions?.globals,
346
- query: defaultStorybookOptions?.query,
347
- fullscreen: defaultStorybookOptions?.fullscreen,
348
- singleStory: defaultStorybookOptions?.singleStory
349
- }),
350
- options: variant.options ? {
351
- ...variant.options,
352
- mask: toLocatorMask(variant.options.mask)
353
- } : void 0
354
- });
355
- variantExtrasEntries.push([
356
- variant.id,
357
- {
358
- saveDiffImage: true,
359
- diffImageFilename: variantFilename,
360
- diff: variant.options?.diff
361
- }
362
- ]);
363
- }
364
- const baseOptions = {
365
- fullPage: storyParameters?.fullPage,
366
- delay: storyParameters?.delay,
367
- omitBackground: storyParameters?.omitBackground,
368
- skip: storyParameters?.skip,
369
- viewport: storyParameters?.viewport ?? screenshotTool.viewport,
370
- mask: toLocatorMask(storyParameters?.mask)
371
- };
372
- const variantFilenameMap = /* @__PURE__ */ new Map();
373
- for (const variant of variantsWithUrls) {
374
- const variantFilename = variant.filename;
375
- if (!variantFilename) continue;
376
- variantFilenameMap.set(variant.id, variantFilename);
377
- }
378
- const captureExtras = {
379
- saveDiffImage: true,
380
- diffImageFilename: filename,
381
- diff: storyParameters?.diff,
382
- variants: variantExtrasEntries.length ? Object.fromEntries(variantExtrasEntries) : void 0,
383
- skipBaseNavigation: true,
384
- waitForStability: waitForVisualIdle,
385
- captureStart
386
- };
387
- const captureResult = await screenshotTool.captureWithVariants(
388
- page,
389
- filename,
390
- url,
391
- baseOptions,
392
- variantsWithUrls,
393
- captureExtras
394
- );
395
- return {
396
- storyId: story.id,
397
- storyName: `${story.title} - ${story.name}`,
398
- filepath: captureResult.base.filepath,
399
- success: captureResult.base.skipped ? void 0 : captureResult.base.comparisonResult ? captureResult.base.comparisonResult.passed : Boolean(captureResult.base.filepath),
400
- skipped: captureResult.base.skipped
401
- };
402
- } catch (error) {
403
- logger.error(
404
- `Error taking screenshot of story ${story.title} - ${story.name}:`,
405
- error.message
406
- );
407
- return {
408
- storyId: story.id,
409
- storyName: `${story.title} - ${story.name}`,
410
- error: error?.message ?? "Unknown error"
411
- };
412
- }
413
- }
414
- };
415
- };
416
-
417
- // src/index.cjs.ts
418
- var previewAnnotations = [require.resolve("./preview.js")];
419
- // Annotate the CommonJS export names for ESM import in node:
420
- 0 && (module.exports = {
421
- cappaPluginStorybook,
422
- previewAnnotations
423
- });
@@ -1,81 +0,0 @@
1
- import { DiffOptions, Plugin } from '@cappa/core';
2
-
3
- interface StorybookRenderOptions {
4
- viewMode?: "story" | "docs";
5
- args?: Record<string, unknown>;
6
- globals?: Record<string, string | number | boolean>;
7
- query?: Record<string, string | number | boolean>;
8
- fullscreen?: boolean;
9
- singleStory?: boolean;
10
- }
11
- type DiffOptionsStorybook = DiffOptions;
12
- interface ScreenshotVariantOverrideStorybook {
13
- fullPage?: boolean;
14
- delay?: number;
15
- skip?: boolean;
16
- mask?: string[];
17
- omitBackground?: boolean;
18
- viewport?: {
19
- width: number;
20
- height: number;
21
- };
22
- args?: Record<string, unknown>;
23
- /**
24
- * Optional diff settings override applied when comparing this screenshot.
25
- * Supports both pixel (default) and gmsd algorithms.
26
- */
27
- diff?: DiffOptionsStorybook;
28
- }
29
- interface ScreenshotVariantOptionsStorybook {
30
- id: string;
31
- label?: string;
32
- filename?: string;
33
- options?: ScreenshotVariantOverrideStorybook;
34
- }
35
- interface ScreenshotOptionsStorybook extends ScreenshotVariantOverrideStorybook {
36
- variants?: ScreenshotVariantOptionsStorybook[];
37
- }
38
-
39
- /**
40
- * Context passed to includeStories and excludeStories predicate functions.
41
- * Use these fields to decide which stories to include or exclude.
42
- */
43
- interface StoryFilterContext {
44
- id: string;
45
- title: string;
46
- name: string;
47
- /** Full story path: `${title}/${name}` (e.g. "Button/Primary") */
48
- filePath: string;
49
- }
50
- interface StorybookPluginOptions {
51
- storybookUrl: string;
52
- /**
53
- * Optional predicate to include stories. If provided, only stories for which
54
- * it returns true are included. Example: (s) => s.id === 'button--primary'
55
- * or (s) => s.title === 'Button'.
56
- */
57
- includeStories?: (story: StoryFilterContext) => boolean;
58
- /**
59
- * Optional predicate to exclude stories. If provided, stories for which it
60
- * returns true are excluded (applied after includeStories). Example:
61
- * (s) => s.title === 'Input'.
62
- */
63
- excludeStories?: (story: StoryFilterContext) => boolean;
64
- defaultViewport?: {
65
- width: number;
66
- height: number;
67
- };
68
- waitForSelector?: string;
69
- waitForTimeout?: number;
70
- storybook?: StorybookRenderOptions;
71
- }
72
- /**
73
- * Storybook Plugin for Cappa
74
- * Fetches stories from a running Storybook server and takes screenshots of each story.
75
- * Supports includeStories and excludeStories predicate functions for filtering.
76
- */
77
- declare const cappaPluginStorybook: Plugin<StorybookPluginOptions>;
78
-
79
- declare const previewAnnotations: string[];
80
-
81
- export { type ScreenshotOptionsStorybook as CappaStorybookOptions, type StoryFilterContext, type StorybookPluginOptions, cappaPluginStorybook, previewAnnotations };