import { readFile } from 'node:fs/promises' import { join } from 'node:path' import { chromium, errors as playwrightErrors } from 'playwright' import { routeFiles } from './lib/routed-files.mjs' import { withDeadline } from './play-tests/deadline.mjs' import { trackFrameRequests } from './play-tests/frame-requests.mjs' import { reportLine } from './play-tests/report.mjs' import { parseShard, shardOf } from './play-tests/shard.mjs' import { watchScript } from './play-tests/stuck-script.mjs' import { exposeTouchInput } from './play-tests/touch-input.mjs' /** * Runs the play functions of every story tagged "play" in the built Storybook and fails on any thrown error; with * `--shard /`, only that shard's stories (play-tests/shard.mjs). */ const storybookDir = join(import.meta.dirname, '..', 'storybook-static') const index = JSON.parse(await readFile(join(storybookDir, 'index.json'), 'utf8')) const playable = Object.values(index.entries).filter((entry) => entry.type === 'story' && entry.tags.includes('play')) if (playable.length === 0) throw new Error('No stories tagged "play" found in storybook-static/index.json') const stories = shardOf(playable, parseShard(process.argv)) const browser = await chromium.launch() // Headless Chromium hides scrollbars; a story tagged "scrollbars" gets a browser whose scrollbars take room, as they do // on Windows and Linux. const scrollbars = stories.some((story) => story.tags.includes('scrollbars')) ? await chromium.launch({ ignoreDefaultArgs: ['--hide-scrollbars'] }) : undefined // The error a story's play function raised, or undefined when it rendered and played. `progress.step` says what it // waits on and `progress.scriptAt` where the page's script stands (play-tests/stuck-script.mjs), for a story that hangs; // `progress.crashed` that its page crashed, which ends every call waiting on it. const playIn = async (context, story, progress) => { const base = await routeFiles(context, storybookDir) const page = await context.newPage() page.on('crash', () => { progress.crashed = true }) progress.scriptAt = await watchScript(context, page) if (story.tags.includes('touch')) await exposeTouchInput(page) // A "mouse" story clicks with the real mouse, which reaches into frames of other origins as a person's click does. if (story.tags.includes('mouse')) await page.exposeFunction('pbClick', ({ x, y, button }) => page.mouse.click(x, y, { button })) // A "sealed-frames" story fails when a frame inside the page sends a request out (play-tests/frame-requests.mjs). const frameRequests = story.tags.includes('sealed-frames') ? trackFrameRequests(page) : () => [] // Storybook installs its channel by assigning this global; an accessor attaches the listeners in that same assignment, // so no event is sent before they are, and each channel installed after the first gets them too. The last render phase // says where a story that sends no event stopped, such as "playing" for a play function that never ends. await page.addInitScript(() => { window.__sbEvents = [] window.__sbPhase = undefined let installed Object.defineProperty(window, '__STORYBOOK_ADDONS_CHANNEL__', { configurable: true, get: () => installed, set: (channel) => { installed = channel if (!channel) return window.__sbPhase ??= 'channel installed' channel.on('storyRenderPhaseChanged', ({ newPhase }) => { window.__sbPhase = newPhase }) for (const name of ['storyRendered', 'playFunctionThrewException', 'storyThrewException', 'storyErrored', 'storyMissing']) channel.on(name, (payload) => window.__sbEvents.push({ name, payload })) }, }) }) // A story whose file fails to load sends storyMissing with only its id; the cause goes to the console, so a failure // without a message reports the page's console errors and failed requests instead. const logged = [] page.on('console', (message) => message.type() === 'error' && logged.push(message.text())) page.on('requestfailed', (request) => logged.push(`${request.failure()?.errorText} ${request.url()}`)) progress.step = 'opening the page' await page.goto(`${base}/iframe.html?id=${story.id}&viewMode=story`) progress.step = 'waiting for a Storybook event' // A page whose Storybook runtime never loaded sends no event at all; it fails with the page's console errors and failed // requests. const settled = await page.waitForFunction(() => window.__sbEvents?.length > 0, null, { timeout: 30_000 }).catch((error) => { if (error instanceof playwrightErrors.TimeoutError) return undefined throw error }) if (!settled) { progress.step = 'reading the render phase, as Storybook sent no event within 30 s' const phase = await page.evaluate(() => window.__sbPhase ?? 'no channel installed') return { name: 'noStoryEvent', message: [`Storybook sent no event within 30 s (last phase: ${phase})`, ...logged].join('\n ') } } progress.step = 'reading the events Storybook sent' const events = await page.evaluate(() => window.__sbEvents.map((event) => ({ name: event.name, message: String(event.payload?.message ?? event.payload?.description ?? '') }))) const error = events.find((event) => event.name !== 'storyRendered') const requested = frameRequests() if (!error && requested.length > 0) return { name: 'frameRequested', message: `a frame requested ${requested.join(', ')}` } if (!error) return undefined return { ...error, message: error.message || logged.join('\n ') } } // A story's whole time, above the 30 s Storybook gets to send an event; the slowest stories take under 10 s. const storySeconds = 60 // Closing a page takes well under a second. const closeSeconds = 10 // A pause interrupts a running script at once. const pauseSeconds = 5 const timedOut = Symbol('timed out') // A story that has not finished within storySeconds fails, naming what it waited on, and its context closes, so the run // goes on with the next story (play-tests/deadline.mjs). const playStory = async (story) => { // The Storybook viewport toolbar does not apply when an iframe is opened directly, so phone stories get a phone-sized page, // "keyboard" stories the part of an iPhone 17 above its keyboard, which the app shrinks the page to, "wide" stories a // desktop screen wider than a page's centred column beside the sidebar, and "laptop" stories a 1440 px laptop screen. // "touch" stories get a 390 px phone that takes touch input, as an iPhone does. // Times show in the viewer's zone, so every page has the same one, whatever the machine's, and one that is not UTC. const touch = story.tags.includes('touch') const viewport = story.tags.includes('keyboard') ? { width: 402, height: 478 } : touch ? { width: 390, height: 844 } : story.tags.includes('phone') ? { width: 360, height: 740 } : story.tags.includes('wide') ? { width: 1920, height: 1080 } : story.tags.includes('laptop') ? { width: 1440, height: 900 } : { width: 1280, height: 720 } const setUp = (story.tags.includes('scrollbars') ? scrollbars : browser).newContext({ viewport, timezoneId: 'Europe/Amsterdam', ...(touch && { hasTouch: true, isMobile: true }) }) const progress = { step: 'setting up the page' } const played = setUp.then((context) => playIn(context, story, progress)).catch((error) => { if (progress.crashed) return { name: 'pageCrashed', message: `its page crashed while ${progress.step}` } throw error }) const outcome = await withDeadline(played, storySeconds * 1000, timedOut) // Closing the context ends the calls still waiting on its page: they fail as their target closed, which the timeout // below stands for. The close has a deadline of its own, as does everything a story waits on. const close = () => withDeadline(setUp.then((context) => context.close()), closeSeconds * 1000, timedOut) // Where the script of a page that stopped answering stands, before its context closes, which it does even when // reading that fails. Whatever the page does, reading it resolves to a line: a pause, a refused pause, a closed page // or no pause in time (play-tests/stuck-script.mjs). So a rejection here is a bug in the runner, and it stops the run // rather than being swallowed. let scriptAt let closed try { scriptAt = outcome === timedOut && progress.scriptAt ? await progress.scriptAt(pauseSeconds * 1000) : undefined } finally { closed = await close() } if (outcome === timedOut) return { name: 'storyTimedOut', message: [`did not finish within ${storySeconds} s while ${progress.step}`, scriptAt].filter(Boolean).join('; ') } if (closed === timedOut) return { name: 'storyTimedOut', message: `its page did not close within ${closeSeconds} s` } return outcome } // Four pages at a time: a story mostly waits on rendering. Each story's line prints as it finishes // (play-tests/report.mjs). const pages = 4 let next = 0 let failed = 0 await Promise.all(Array.from({ length: pages }, async () => { while (next < stories.length) { const story = stories[next++] const started = performance.now() const error = await playStory(story) console.log(reportLine(story, error, performance.now() - started)) if (error) failed += 1 } })) await browser.close() await scrollbars?.close() if (failed > 0) process.exitCode = 1