@wtfalch/design-check 0.0.0-stage → 0.1.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/README.md CHANGED
@@ -1,3 +1,64 @@
1
- # Temporary Holding Version
1
+ # @wtfalch/design-check
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The design check: compares an app's named states with the frozen design frames.
4
+
5
+ ## `design-check`
6
+
7
+ ```bash
8
+ design-check [playwright arguments]
9
+ ```
10
+
11
+ Runs the app's design check inside the Playwright container, with the app folder
12
+ mounted at the same path (in a pnpm workspace, the workspace root is mounted, so the
13
+ `node_modules` symlinks stay valid). Every argument is passed to `playwright test`;
14
+ a leading `--` is dropped. Variables named `DESIGN_*` are passed into the container.
15
+
16
+ It refuses to start when the installed `@playwright/test` is not the version in the
17
+ image tag.
18
+
19
+ Three paths are fixed:
20
+
21
+ - the app folder is the current directory;
22
+ - the image is named in `tests/design/design-image.json` (`{ "image": "mcr.microsoft.com/playwright:v1.64.1-noble" }`);
23
+ - the Playwright config is `playwright.design.config.ts` in the app folder.
24
+
25
+ `@playwright/test` is a peer dependency: the app installs it itself, because the
26
+ container runs `node_modules/@playwright/test/cli.js` from the app.
27
+
28
+ The image is the app's choice: stills are only equal inside the image that made them.
29
+
30
+ ## The two files an app writes
31
+
32
+ `playwright.design.config.ts`:
33
+
34
+ ```ts
35
+ import { defineDesignConfig } from '@wtfalch/design-check'
36
+
37
+ export default defineDesignConfig() // or defineDesignConfig({ baseURL: 'http://localhost:3301' })
38
+ ```
39
+
40
+ The base address is `DESIGN_BASE_URL` when set, else the `baseURL` option, else
41
+ `http://localhost:3301`. The config uses the `Desktop Chrome` device, so frozen stills
42
+ stay equal to the ones made elsewhere.
43
+
44
+ `tests/design/check.spec.ts`:
45
+
46
+ ```ts
47
+ import { registerFrozenSpecs } from '@wtfalch/design-check'
48
+ import { openState } from './open-state'
49
+
50
+ registerFrozenSpecs({ openState })
51
+ ```
52
+
53
+ It registers, from the current directory (states in `design/states`, stills in
54
+ `design/frozen`, the image in `tests/design/design-image.json`):
55
+
56
+ - one test `frame <feature> <id>` per frozen frame, which opens the frame's state through
57
+ `openState(page, state, { theme, width, height })`, compares it with the still and then
58
+ compares each of the frame's motions (which reopen the state on a fresh page);
59
+ - `no frozen design` when nothing is frozen;
60
+ - `frozen design loads`, failing, when the frozen folder, the states or the image cannot be read;
61
+ - `freeze`, which runs only when `DESIGN_FREEZE` names a request file.
62
+
63
+ An `openState` should: install the clock at `CLOCK_START`, open the page, run the state's
64
+ `prepare`, `fontsLoaded`, `freezeClock`, `fontsLoaded`.
@@ -0,0 +1,6 @@
1
+ /**
2
+ * The arguments Chromium starts with, in the freeze and in the design check.
3
+ * Grey text smoothing everywhere: colour smoothing depends on how a page's
4
+ * layers are built, so a matching page and its still would differ on glyph edges.
5
+ */
6
+ export declare const CHROMIUM_ARGS: readonly string[];
@@ -0,0 +1,6 @@
1
+ /**
2
+ * The arguments Chromium starts with, in the freeze and in the design check.
3
+ * Grey text smoothing everywhere: colour smoothing depends on how a page's
4
+ * layers are built, so a matching page and its still would differ on glyph edges.
5
+ */
6
+ export const CHROMIUM_ARGS = ['--disable-lcd-text'];
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,40 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * The `design-check` bin: runs the app's design check in the Playwright image named in
4
+ * `tests/design/design-image.json`, with the current directory as the app folder.
5
+ * No "run only when executed directly" guard: the bin is a symlink and such a
6
+ * guard fails through it.
7
+ */
8
+ import { spawnSync } from 'node:child_process';
9
+ import path from 'node:path';
10
+ import { checkPinned, dockerArgs, dropLeadingDashes, mountRoot } from './docker.js';
11
+ import { readDesignImage } from './manifest.js';
12
+ import { usage } from './usage.js';
13
+ const argv = process.argv.slice(2);
14
+ if (argv[0] === '--help') {
15
+ process.stdout.write(usage());
16
+ process.exit(0);
17
+ }
18
+ const cwd = process.cwd();
19
+ let image;
20
+ try {
21
+ image = readDesignImage(path.join(cwd, 'tests/design/design-image.json'));
22
+ checkPinned(cwd, image);
23
+ }
24
+ catch (error) {
25
+ process.stderr.write(`design-check: ${error instanceof Error ? error.message : String(error)}\n`);
26
+ process.exit(1);
27
+ }
28
+ const result = spawnSync('docker', dockerArgs({
29
+ root: mountRoot(cwd),
30
+ cwd,
31
+ image,
32
+ env: process.env,
33
+ args: dropLeadingDashes(argv),
34
+ tty: Boolean(process.stdin.isTTY),
35
+ }), { stdio: 'inherit' });
36
+ if (result.error) {
37
+ process.stderr.write(`could not run docker: ${result.error.message}\n`);
38
+ process.exit(1);
39
+ }
40
+ process.exit(result.status ?? 1);
@@ -0,0 +1,20 @@
1
+ import { type BrowserContext, type Page } from '@playwright/test';
2
+ import type { Manifest } from './manifest.js';
3
+ type Frame = Manifest['frames'][number];
4
+ export interface CompareOptions {
5
+ /** Runs on the page before the photograph; only the self-test passes it. */
6
+ before?: (page: Page) => Promise<void>;
7
+ }
8
+ /**
9
+ * Aborts every http: or https: request to a host outside this machine, so the
10
+ * photograph does not wait on the network. file: and data: pass.
11
+ */
12
+ export declare function blockOutside(context: BrowserContext): Promise<void>;
13
+ /**
14
+ * Photographs the page's viewport and compares it with the frame's still, pixel
15
+ * by pixel. Throws `Frame <id>: <message>`; the message holds the differing pixel count.
16
+ */
17
+ export declare function compareFrame(page: Page, folder: string, frame: Frame, tolerance: Manifest['tolerance'], options?: CompareOptions): Promise<void>;
18
+ /** Compares a photograph with the still at `segments` (relative to the repository). Throws `<label>: <message>`. */
19
+ export declare function compareImage(buffer: Buffer, segments: string[], tolerance: Manifest['tolerance'], label: string): void;
20
+ export {};
@@ -0,0 +1,38 @@
1
+ import path from 'node:path';
2
+ import { expect } from '@playwright/test';
3
+ import { repoRoot } from './repo.js';
4
+ const LOCAL_HOSTS = new Set(['localhost', '127.0.0.1']);
5
+ /**
6
+ * Aborts every http: or https: request to a host outside this machine, so the
7
+ * photograph does not wait on the network. file: and data: pass.
8
+ */
9
+ export async function blockOutside(context) {
10
+ await context.route((url) => (url.protocol === 'http:' || url.protocol === 'https:') && !LOCAL_HOSTS.has(url.hostname), (route) => route.abort());
11
+ }
12
+ /**
13
+ * Photographs the page's viewport and compares it with the frame's still, pixel
14
+ * by pixel. Throws `Frame <id>: <message>`; the message holds the differing pixel count.
15
+ */
16
+ export async function compareFrame(page, folder, frame, tolerance, options = {}) {
17
+ await options.before?.(page);
18
+ const buffer = await page.screenshot({
19
+ animations: 'disabled',
20
+ caret: 'hide',
21
+ scale: 'css',
22
+ type: 'png',
23
+ });
24
+ const stillPath = path.relative(repoRoot(), path.resolve(folder, frame.still));
25
+ compareImage(buffer, stillPath.split(path.sep), tolerance, `Frame ${frame.id}`);
26
+ }
27
+ /** Compares a photograph with the still at `segments` (relative to the repository). Throws `<label>: <message>`. */
28
+ export function compareImage(buffer, segments, tolerance, label) {
29
+ try {
30
+ expect(buffer).toMatchSnapshot(segments, {
31
+ threshold: tolerance.threshold,
32
+ maxDiffPixels: tolerance.maxDiffPixels,
33
+ });
34
+ }
35
+ catch (error) {
36
+ throw new Error(`${label}: ${error instanceof Error ? error.message : String(error)}`);
37
+ }
38
+ }
@@ -0,0 +1,17 @@
1
+ /** Options of {@link defineDesignConfig}. */
2
+ export interface DesignConfigOptions {
3
+ /** The base address when `DESIGN_BASE_URL` is not set; defaults to `http://localhost:3301`. */
4
+ baseURL?: string;
5
+ }
6
+ /**
7
+ * The Playwright config of an app's design check: opens the app's named, fixed
8
+ * states (`design/states/`) and compares them with the frozen stills. The base
9
+ * address is `DESIGN_BASE_URL` when set, else `options.baseURL`, else
10
+ * `http://localhost:3301`.
11
+ *
12
+ * It uses `devices['Desktop Chrome']`, which the repository's CLAUDE.md forbids
13
+ * for the gallery suite (a spoofed user-agent changes React Aria's press
14
+ * handling). Here the descriptor is the point: frozen stills were made with it,
15
+ * so stills made with it stay equal.
16
+ */
17
+ export declare function defineDesignConfig(options?: DesignConfigOptions): import("@playwright/test").PlaywrightTestConfig<{}, {}>;
package/dist/config.js ADDED
@@ -0,0 +1,44 @@
1
+ import { defineConfig, devices } from '@playwright/test';
2
+ import { CHROMIUM_ARGS } from './browser.js';
3
+ /**
4
+ * The Playwright config of an app's design check: opens the app's named, fixed
5
+ * states (`design/states/`) and compares them with the frozen stills. The base
6
+ * address is `DESIGN_BASE_URL` when set, else `options.baseURL`, else
7
+ * `http://localhost:3301`.
8
+ *
9
+ * It uses `devices['Desktop Chrome']`, which the repository's CLAUDE.md forbids
10
+ * for the gallery suite (a spoofed user-agent changes React Aria's press
11
+ * handling). Here the descriptor is the point: frozen stills were made with it,
12
+ * so stills made with it stay equal.
13
+ */
14
+ export function defineDesignConfig(options = {}) {
15
+ return defineConfig({
16
+ testDir: './tests/design',
17
+ testMatch: '**/*.spec.ts',
18
+ reporter: 'list',
19
+ // The reference is passed as a path relative to the repository, so the same call
20
+ // reads design/frozen/... for real frames and the fixture for the self-test.
21
+ // 'none': a missing still fails and nothing is written under design/frozen/.
22
+ snapshotDir: '.',
23
+ snapshotPathTemplate: '{snapshotDir}/{arg}{ext}',
24
+ updateSnapshots: 'none',
25
+ outputDir: 'test-results/design',
26
+ // One server, one demo organisation: the specs take turns.
27
+ workers: 1,
28
+ // `next dev` compiles each route on its first visit.
29
+ timeout: 120_000,
30
+ expect: { timeout: 30_000 },
31
+ use: {
32
+ baseURL: process.env.DESIGN_BASE_URL ?? options.baseURL ?? 'http://localhost:3301',
33
+ },
34
+ projects: [
35
+ {
36
+ name: 'chromium',
37
+ use: {
38
+ ...devices['Desktop Chrome'],
39
+ launchOptions: { args: [...CHROMIUM_ARGS] },
40
+ },
41
+ },
42
+ ],
43
+ });
44
+ }
@@ -0,0 +1,14 @@
1
+ import { type Manifest } from './manifest.js';
2
+ export interface FrozenFrame {
3
+ folder: string;
4
+ frame: Manifest['frames'][number];
5
+ tolerance: Manifest['tolerance'];
6
+ }
7
+ /** Every frame of every manifest under `root`; `message` says so when there are none. */
8
+ export declare function describeFrozen(root: string, env: {
9
+ states: string[];
10
+ image: string;
11
+ }): {
12
+ frames: FrozenFrame[];
13
+ message: string;
14
+ };
@@ -0,0 +1,15 @@
1
+ import path from 'node:path';
2
+ import { installedVersion, loadFrozen } from './manifest.js';
3
+ /** Every frame of every manifest under `root`; `message` says so when there are none. */
4
+ export function describeFrozen(root, env) {
5
+ const frames = loadFrozen(root, {
6
+ states: env.states,
7
+ image: env.image,
8
+ installed: installedVersion,
9
+ }).flatMap((m) => m.frames.map((frame) => ({
10
+ folder: path.join(root, m.feature),
11
+ frame,
12
+ tolerance: m.tolerance,
13
+ })));
14
+ return { frames, message: frames.length === 0 ? 'no frozen design' : '' };
15
+ }
@@ -0,0 +1,21 @@
1
+ export interface DockerArgsOptions {
2
+ /** The folder mounted into the container, at the same path. */
3
+ root: string;
4
+ /** The working folder inside the container: the app folder. */
5
+ cwd: string;
6
+ image: string;
7
+ env: Record<string, string | undefined>;
8
+ args: string[];
9
+ tty: boolean;
10
+ }
11
+ /** pnpm passes a literal `--` on to the script; Playwright would read it as a file name. */
12
+ export declare function dropLeadingDashes(args: string[]): string[];
13
+ /** The `docker run` arguments that run the design check in the pinned image. */
14
+ export declare function dockerArgs({ root, cwd, image, env, args, tty }: DockerArgsOptions): string[];
15
+ /**
16
+ * The nearest folder at or above `cwd` that holds a `pnpm-workspace.yaml`, else `cwd`.
17
+ * A workspace's `node_modules` symlinks point above the app, so the mount must reach them.
18
+ */
19
+ export declare function mountRoot(cwd: string): string;
20
+ /** Throws unless the installed `@playwright/test` is the version in the image tag. */
21
+ export declare function checkPinned(cwd: string, image: string): void;
package/dist/docker.js ADDED
@@ -0,0 +1,67 @@
1
+ /** The pieces of `design-check` that run an app's design check in its pinned Playwright image. */
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ /** pnpm passes a literal `--` on to the script; Playwright would read it as a file name. */
5
+ export function dropLeadingDashes(args) {
6
+ return args[0] === '--' ? args.slice(1) : args;
7
+ }
8
+ /** The `docker run` arguments that run the design check in the pinned image. */
9
+ export function dockerArgs({ root, cwd, image, env, args, tty }) {
10
+ const passed = Object.keys(env)
11
+ .filter((name) => name.startsWith('DESIGN_'))
12
+ .sort()
13
+ .flatMap((name) => ['-e', name]);
14
+ return [
15
+ 'run',
16
+ '--rm',
17
+ ...(tty ? ['-t'] : []),
18
+ '--network',
19
+ 'host',
20
+ '-v',
21
+ `${root}:${root}`,
22
+ '-w',
23
+ cwd,
24
+ '-e',
25
+ 'CI=1',
26
+ '-e',
27
+ 'PLAYWRIGHT_BROWSERS_PATH=/ms-playwright',
28
+ ...passed,
29
+ image,
30
+ 'node',
31
+ 'node_modules/@playwright/test/cli.js',
32
+ 'test',
33
+ '--config',
34
+ 'playwright.design.config.ts',
35
+ ...args,
36
+ ];
37
+ }
38
+ /**
39
+ * The nearest folder at or above `cwd` that holds a `pnpm-workspace.yaml`, else `cwd`.
40
+ * A workspace's `node_modules` symlinks point above the app, so the mount must reach them.
41
+ */
42
+ export function mountRoot(cwd) {
43
+ let dir = path.resolve(cwd);
44
+ for (;;) {
45
+ if (existsSync(path.join(dir, 'pnpm-workspace.yaml')))
46
+ return dir;
47
+ const parent = path.dirname(dir);
48
+ if (parent === dir)
49
+ return path.resolve(cwd);
50
+ dir = parent;
51
+ }
52
+ }
53
+ /** Throws unless the installed `@playwright/test` is the version in the image tag. */
54
+ export function checkPinned(cwd, image) {
55
+ const tagVersion = /:v(\d+\.\d+\.\d+)-/.exec(image)?.[1];
56
+ if (!tagVersion) {
57
+ throw new Error(`tests/design/design-image.json: the image ${image} has no version in its tag`);
58
+ }
59
+ const file = path.join(cwd, 'node_modules/@playwright/test/package.json');
60
+ if (!existsSync(file)) {
61
+ throw new Error(`@playwright/test is not installed: ${file} not found`);
62
+ }
63
+ const { version } = JSON.parse(readFileSync(file, 'utf8'));
64
+ if (version !== tagVersion) {
65
+ throw new Error(`@playwright/test ${String(version)} is installed, the image ${image} is for ${tagVersion}`);
66
+ }
67
+ }
@@ -0,0 +1,15 @@
1
+ export interface FreezeOptions {
2
+ /** Where `<feature>/` is made; defaults to `<repo>/design/frozen`. */
3
+ root?: string;
4
+ /** The state names that have a file. */
5
+ states: string[];
6
+ /** The image the stills are made in; written to the manifest. */
7
+ image: string;
8
+ installed?: (pkg: string) => string | null;
9
+ now?: () => Date;
10
+ }
11
+ export declare class FreezeError extends Error {
12
+ constructor(field: string, message: string);
13
+ }
14
+ /** Freezes the boards named in the request file into `<root>/<feature>/`; never overwrites. */
15
+ export declare function freezeFeature(requestPath: string, options: FreezeOptions): Promise<void>;
package/dist/freeze.js ADDED
@@ -0,0 +1,153 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { chromium } from '@playwright/test';
5
+ import { z } from 'zod';
6
+ import { CHROMIUM_ARGS } from './browser.js';
7
+ import { blockOutside } from './compare.js';
8
+ import { installedVersion, verifyManifest } from './manifest.js';
9
+ import { repoRoot } from './repo.js';
10
+ const request = z
11
+ .object({
12
+ feature: z.string().regex(/^[a-z0-9-]+$/, 'must be lowercase letters, digits and hyphens'),
13
+ source: z
14
+ .object({
15
+ artifact: z.string().min(1),
16
+ version: z.string().min(1),
17
+ folder: z.string().min(1),
18
+ })
19
+ .strict(),
20
+ frames: z
21
+ .array(z
22
+ .object({
23
+ board: z.string().min(1),
24
+ surface: z.string().min(1),
25
+ state: z.string().min(1),
26
+ theme: z.string().min(1),
27
+ width: z.number().int().positive(),
28
+ height: z.number().int().positive(),
29
+ })
30
+ .strict())
31
+ .min(1),
32
+ })
33
+ .strict();
34
+ export class FreezeError extends Error {
35
+ constructor(field, message) {
36
+ super(`${field}: ${message}`);
37
+ this.name = 'FreezeError';
38
+ }
39
+ }
40
+ const sha256 = (data) => createHash('sha256').update(data).digest('hex');
41
+ /** Freezes the boards named in the request file into `<root>/<feature>/`; never overwrites. */
42
+ export async function freezeFeature(requestPath, options) {
43
+ const REPO = repoRoot();
44
+ const root = options.root ?? path.join(REPO, 'design/frozen');
45
+ const { states, image } = options;
46
+ const installed = options.installed ?? installedVersion;
47
+ const now = options.now ?? (() => new Date());
48
+ const parsed = request.safeParse(JSON.parse(readFileSync(requestPath, 'utf8')));
49
+ if (!parsed.success) {
50
+ const issue = parsed.error.issues[0];
51
+ const keys = issue.code === 'unrecognized_keys' ? `: ${issue.keys.join(', ')}` : '';
52
+ throw new FreezeError(issue.path.join('.') || '(root)', `${issue.message}${keys}`);
53
+ }
54
+ const req = parsed.data;
55
+ const sourceDir = path.resolve(REPO, req.source.folder);
56
+ const inside = path.relative(REPO, sourceDir);
57
+ if (inside === '..' || inside.startsWith(`..${path.sep}`) || path.isAbsolute(inside)) {
58
+ throw new FreezeError('source.folder', `${req.source.folder} is outside the repository`);
59
+ }
60
+ const ids = new Set();
61
+ const planned = req.frames.map((f, i) => {
62
+ const at = `frames.${i}`;
63
+ if (f.board !== path.basename(f.board) || f.board === '..' || f.board === '.') {
64
+ throw new FreezeError(`${at}.board`, `${f.board} must be a file name`);
65
+ }
66
+ const file = path.join(sourceDir, f.board);
67
+ if (!existsSync(file)) {
68
+ throw new FreezeError(`${at}.board`, `${f.board} is not in ${req.source.folder}`);
69
+ }
70
+ const theme = /data-theme="([^"]*)"/.exec(readFileSync(file, 'utf8'))?.[1];
71
+ if (theme !== f.theme) {
72
+ throw new FreezeError(`${at}.theme`, `${f.board} has data-theme ${theme}, not ${f.theme}`);
73
+ }
74
+ if (!states.includes(f.state)) {
75
+ throw new FreezeError(`${at}.state`, `${f.state} has no file under design/states`);
76
+ }
77
+ const id = `${f.state.replaceAll('/', '--')}--${f.theme}--${f.width}`;
78
+ if (ids.has(id))
79
+ throw new FreezeError(`${at}.state`, `duplicate frame id ${id}: another frame has the same state, theme and width`);
80
+ ids.add(id);
81
+ return { ...f, id, file };
82
+ });
83
+ const folder = path.join(root, req.feature);
84
+ if (existsSync(path.join(folder, 'manifest.json'))) {
85
+ throw new FreezeError('feature', `${req.feature} is already frozen; delete its folder to freeze again`);
86
+ }
87
+ const made = !existsSync(folder);
88
+ let browser;
89
+ try {
90
+ mkdirSync(path.join(folder, 'frames'), { recursive: true });
91
+ mkdirSync(path.join(folder, 'stills'), { recursive: true });
92
+ browser = await chromium.launch({ args: [...CHROMIUM_ARGS] });
93
+ const frames = [];
94
+ for (const f of planned) {
95
+ const context = await browser.newContext({ viewport: { width: f.width, height: f.height } });
96
+ await blockOutside(context);
97
+ const page = await context.newPage();
98
+ await page.goto(`file://${f.file}`);
99
+ await page.evaluate(() => document.fonts.ready);
100
+ const still = await page.screenshot({
101
+ animations: 'disabled',
102
+ caret: 'hide',
103
+ scale: 'css',
104
+ type: 'png',
105
+ });
106
+ await context.close();
107
+ const frameData = readFileSync(f.file);
108
+ writeFileSync(path.join(folder, 'frames', f.board), frameData);
109
+ writeFileSync(path.join(folder, 'stills', `${f.id}.png`), still);
110
+ frames.push({
111
+ id: f.id,
112
+ frame: `frames/${f.board}`,
113
+ frameSha256: sha256(frameData),
114
+ surface: f.surface,
115
+ state: f.state,
116
+ theme: f.theme,
117
+ width: f.width,
118
+ height: f.height,
119
+ still: `stills/${f.id}.png`,
120
+ stillSha256: sha256(still),
121
+ custom: [],
122
+ motion: [],
123
+ });
124
+ }
125
+ const library = {};
126
+ for (const pkg of ['@wtfalch/design', '@wtfalch/house']) {
127
+ const version = installed(pkg);
128
+ if (version === null)
129
+ throw new FreezeError('library', `${pkg} is not installed`);
130
+ library[pkg] = version;
131
+ }
132
+ const manifest = {
133
+ v: 1,
134
+ feature: req.feature,
135
+ source: { artifact: req.source.artifact, version: req.source.version },
136
+ frozenAt: now().toISOString(),
137
+ image,
138
+ library,
139
+ tolerance: { threshold: 0.02, maxDiffPixels: 0 },
140
+ frames,
141
+ };
142
+ verifyManifest(folder, manifest, { states, installed, image });
143
+ writeFileSync(path.join(folder, 'manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`);
144
+ }
145
+ catch (error) {
146
+ if (made)
147
+ rmSync(folder, { recursive: true, force: true });
148
+ throw error;
149
+ }
150
+ finally {
151
+ await browser?.close();
152
+ }
153
+ }
@@ -0,0 +1,20 @@
1
+ /** The library entry of `@wtfalch/design-check`. */
2
+ export { checkPinned, dockerArgs, dropLeadingDashes, mountRoot } from './docker.js';
3
+ export type { DockerArgsOptions } from './docker.js';
4
+ export { blockOutside, compareFrame, compareImage } from './compare.js';
5
+ export type { CompareOptions } from './compare.js';
6
+ export { FreezeError, freezeFeature } from './freeze.js';
7
+ export type { FreezeOptions } from './freeze.js';
8
+ export { describeFrozen } from './describe-frozen.js';
9
+ export type { FrozenFrame } from './describe-frozen.js';
10
+ export { ManifestError, installedVersion, loadFrozen, readDesignImage, readManifest, verifyManifest, } from './manifest.js';
11
+ export type { FrozenEnv, Manifest } from './manifest.js';
12
+ export { compareMotion, photographAt, sameEasing, start } from './motion.js';
13
+ export type { OpenFrame } from './motion.js';
14
+ export { CLOCK_START, FROZEN_AT, fontsLoaded, freezeClock, knownStates } from './open-state.js';
15
+ export type { DesignState, OpenState, OpenStateOptions } from './open-state.js';
16
+ export { CHROMIUM_ARGS } from './browser.js';
17
+ export { defineDesignConfig } from './config.js';
18
+ export type { DesignConfigOptions } from './config.js';
19
+ export { registerFrozenSpecs } from './register.js';
20
+ export type { FrozenSpecsOptions } from './register.js';
package/dist/index.js ADDED
@@ -0,0 +1,11 @@
1
+ /** The library entry of `@wtfalch/design-check`. */
2
+ export { checkPinned, dockerArgs, dropLeadingDashes, mountRoot } from './docker.js';
3
+ export { blockOutside, compareFrame, compareImage } from './compare.js';
4
+ export { FreezeError, freezeFeature } from './freeze.js';
5
+ export { describeFrozen } from './describe-frozen.js';
6
+ export { ManifestError, installedVersion, loadFrozen, readDesignImage, readManifest, verifyManifest, } from './manifest.js';
7
+ export { compareMotion, photographAt, sameEasing, start } from './motion.js';
8
+ export { CLOCK_START, FROZEN_AT, fontsLoaded, freezeClock, knownStates } from './open-state.js';
9
+ export { CHROMIUM_ARGS } from './browser.js';
10
+ export { defineDesignConfig } from './config.js';
11
+ export { registerFrozenSpecs } from './register.js';
@@ -0,0 +1,72 @@
1
+ import { z } from 'zod';
2
+ /** Reads the image name from `design-image.json`; `scripts/design-check.mjs` reads the same file. */
3
+ export declare function readDesignImage(file: string): string;
4
+ export declare class ManifestError extends Error {
5
+ constructor(where: string, message: string);
6
+ }
7
+ export interface FrozenEnv {
8
+ image: string;
9
+ states: string[];
10
+ installed: (pkg: string) => string | null;
11
+ }
12
+ /** The version of `pkg` in this repo's node_modules, or null when it is not installed. */
13
+ export declare function installedVersion(pkg: string): string | null;
14
+ declare const schema: z.ZodObject<{
15
+ v: z.ZodLiteral<1>;
16
+ feature: z.ZodString;
17
+ source: z.ZodObject<{
18
+ artifact: z.ZodString;
19
+ version: z.ZodString;
20
+ }, z.core.$strict>;
21
+ frozenAt: z.ZodString;
22
+ image: z.ZodString;
23
+ library: z.ZodRecord<z.ZodString, z.ZodString>;
24
+ tolerance: z.ZodObject<{
25
+ threshold: z.ZodNumber;
26
+ maxDiffPixels: z.ZodNumber;
27
+ }, z.core.$strict>;
28
+ frames: z.ZodArray<z.ZodObject<{
29
+ id: z.ZodString;
30
+ frame: z.ZodString;
31
+ frameSha256: z.ZodString;
32
+ surface: z.ZodString;
33
+ state: z.ZodString;
34
+ theme: z.ZodString;
35
+ width: z.ZodNumber;
36
+ height: z.ZodNumber;
37
+ still: z.ZodString;
38
+ stillSha256: z.ZodString;
39
+ custom: z.ZodArray<z.ZodObject<{
40
+ name: z.ZodString;
41
+ why: z.ZodString;
42
+ }, z.core.$strict>>;
43
+ motion: z.ZodArray<z.ZodObject<{
44
+ id: z.ZodString;
45
+ trigger: z.ZodObject<{
46
+ action: z.ZodEnum<{
47
+ click: "click";
48
+ hover: "hover";
49
+ focus: "focus";
50
+ load: "load";
51
+ }>;
52
+ name: z.ZodString;
53
+ }, z.core.$strict>;
54
+ moments: z.ZodArray<z.ZodNumber>;
55
+ values: z.ZodArray<z.ZodObject<{
56
+ property: z.ZodString;
57
+ duration: z.ZodString;
58
+ delay: z.ZodString;
59
+ easing: z.ZodString;
60
+ }, z.core.$strict>>;
61
+ stills: z.ZodArray<z.ZodString>;
62
+ }, z.core.$strict>>;
63
+ }, z.core.$strict>>;
64
+ }, z.core.$strict>;
65
+ export type Manifest = z.infer<typeof schema>;
66
+ /** Reads `<folder>/manifest.json` and checks its shape. */
67
+ export declare function readManifest(folder: string): Manifest;
68
+ /** Refuses a manifest that does not match the image, the installed library, or the files on disk. */
69
+ export declare function verifyManifest(folder: string, manifest: Manifest, env: FrozenEnv): void;
70
+ /** The verified manifests of every `<root>/<feature>/manifest.json`, sorted by folder name. */
71
+ export declare function loadFrozen(root: string, env: FrozenEnv): Manifest[];
72
+ export {};
@@ -0,0 +1,168 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { existsSync, readFileSync, readdirSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { z } from 'zod';
5
+ import { repoRoot } from './repo.js';
6
+ /** Reads the image name from `design-image.json`; `scripts/design-check.mjs` reads the same file. */
7
+ export function readDesignImage(file) {
8
+ const { image } = JSON.parse(readFileSync(file, 'utf8'));
9
+ if (typeof image !== 'string' || image.length === 0) {
10
+ throw new Error('design-image.json: image must be a non-empty string');
11
+ }
12
+ return image;
13
+ }
14
+ export class ManifestError extends Error {
15
+ constructor(where, message) {
16
+ super(`${where}: ${message}`);
17
+ this.name = 'ManifestError';
18
+ }
19
+ }
20
+ /** The version of `pkg` in this repo's node_modules, or null when it is not installed. */
21
+ export function installedVersion(pkg) {
22
+ const file = path.join(repoRoot(), 'node_modules', pkg, 'package.json');
23
+ if (!existsSync(file))
24
+ return null;
25
+ return JSON.parse(readFileSync(file, 'utf8')).version;
26
+ }
27
+ // A path inside the frozen folder: relative, no `..`.
28
+ const insidePath = z
29
+ .string()
30
+ .refine((p) => p.length > 0 &&
31
+ !path.posix.isAbsolute(p) &&
32
+ !path.win32.isAbsolute(p) &&
33
+ !p.split(/[\\/]/).includes('..'), { message: 'must be a relative path inside the folder' });
34
+ const motion = z
35
+ .object({
36
+ id: z.string().min(1),
37
+ trigger: z
38
+ .object({ action: z.enum(['click', 'hover', 'focus', 'load']), name: z.string() })
39
+ .strict(),
40
+ moments: z.array(z.number().int().nonnegative()),
41
+ values: z.array(z
42
+ .object({
43
+ property: z.string(),
44
+ duration: z.string(),
45
+ delay: z.string(),
46
+ easing: z.string(),
47
+ })
48
+ .strict()),
49
+ stills: z.array(insidePath),
50
+ })
51
+ .strict()
52
+ .refine((m) => m.moments.length === m.stills.length, {
53
+ path: ['moments'],
54
+ message: 'moments and stills must have the same length',
55
+ });
56
+ const frame = z
57
+ .object({
58
+ id: z.string().min(1),
59
+ frame: insidePath,
60
+ frameSha256: z.string(),
61
+ surface: z.string(),
62
+ state: z.string(),
63
+ theme: z.string(),
64
+ width: z.number().int().positive(),
65
+ height: z.number().int().positive(),
66
+ still: insidePath,
67
+ stillSha256: z.string(),
68
+ custom: z.array(z.object({ name: z.string(), why: z.string() }).strict()),
69
+ motion: z.array(motion),
70
+ })
71
+ .strict();
72
+ const schema = z
73
+ .object({
74
+ v: z.literal(1),
75
+ feature: z.string(),
76
+ source: z.object({ artifact: z.string(), version: z.string() }).strict(),
77
+ frozenAt: z.string(),
78
+ image: z.string(),
79
+ library: z.record(z.string(), z.string()),
80
+ tolerance: z
81
+ .object({
82
+ threshold: z.number().min(0).max(0.02),
83
+ maxDiffPixels: z.number().min(0).max(0),
84
+ })
85
+ .strict(),
86
+ frames: z.array(frame),
87
+ })
88
+ .strict()
89
+ .superRefine((m, ctx) => {
90
+ const seen = new Set();
91
+ m.frames.forEach((f, i) => {
92
+ if (seen.has(f.id)) {
93
+ ctx.addIssue({
94
+ code: 'custom',
95
+ path: ['frames', i, 'id'],
96
+ message: `duplicate frame id ${f.id}`,
97
+ });
98
+ }
99
+ seen.add(f.id);
100
+ });
101
+ });
102
+ /** Reads `<folder>/manifest.json` and checks its shape. */
103
+ export function readManifest(folder) {
104
+ const raw = JSON.parse(readFileSync(path.join(folder, 'manifest.json'), 'utf8'));
105
+ const parsed = schema.safeParse(raw);
106
+ if (parsed.success)
107
+ return parsed.data;
108
+ const issue = parsed.error.issues[0];
109
+ const at = issue.path;
110
+ const frames = raw.frames;
111
+ const id = at[0] === 'frames' && typeof at[1] === 'number' ? frames?.[at[1]]?.id : undefined;
112
+ const field = at.join('.') || '(root)';
113
+ throw new ManifestError(typeof id === 'string' ? id : 'manifest', `${field}: ${issue.message}`);
114
+ }
115
+ const sha256 = (file) => createHash('sha256').update(readFileSync(file)).digest('hex');
116
+ /** Refuses a manifest that does not match the image, the installed library, or the files on disk. */
117
+ export function verifyManifest(folder, manifest, env) {
118
+ if (manifest.image !== env.image) {
119
+ throw new ManifestError('manifest', `image ${manifest.image} differs from ${env.image}`);
120
+ }
121
+ for (const [pkg, version] of Object.entries(manifest.library)) {
122
+ const have = env.installed(pkg);
123
+ if (have === null)
124
+ throw new ManifestError('manifest', `library ${pkg} is not installed`);
125
+ if (have !== version) {
126
+ throw new ManifestError('manifest', `library ${pkg} is ${have}, the manifest has ${version}`);
127
+ }
128
+ }
129
+ for (const f of manifest.frames) {
130
+ if (!env.states.includes(f.state)) {
131
+ throw new ManifestError(f.id, `state ${f.state} has no entry in design/states`);
132
+ }
133
+ const frameFile = path.join(folder, f.frame);
134
+ if (!existsSync(frameFile))
135
+ throw new ManifestError(f.id, `frame is missing: ${f.frame}`);
136
+ if (sha256(frameFile) !== f.frameSha256) {
137
+ throw new ManifestError(f.id, `frameSha256 differs from ${f.frame}`);
138
+ }
139
+ const stillFile = path.join(folder, f.still);
140
+ if (!existsSync(stillFile))
141
+ throw new ManifestError(f.id, `still is missing: ${f.still}`);
142
+ if (sha256(stillFile) !== f.stillSha256) {
143
+ throw new ManifestError(f.id, `stillSha256 differs from ${f.still}`);
144
+ }
145
+ for (const m of f.motion) {
146
+ for (const s of m.stills) {
147
+ if (!existsSync(path.join(folder, s))) {
148
+ throw new ManifestError(f.id, `motion ${m.id} still is missing: ${s}`);
149
+ }
150
+ }
151
+ }
152
+ }
153
+ }
154
+ /** The verified manifests of every `<root>/<feature>/manifest.json`, sorted by folder name. */
155
+ export function loadFrozen(root, env) {
156
+ if (!existsSync(root))
157
+ return [];
158
+ return readdirSync(root, { withFileTypes: true })
159
+ .filter((e) => e.isDirectory() && existsSync(path.join(root, e.name, 'manifest.json')))
160
+ .map((e) => e.name)
161
+ .sort()
162
+ .map((name) => {
163
+ const folder = path.join(root, name);
164
+ const manifest = readManifest(folder);
165
+ verifyManifest(folder, manifest, env);
166
+ return manifest;
167
+ });
168
+ }
@@ -0,0 +1,27 @@
1
+ import type { Page } from '@playwright/test';
2
+ import type { Manifest } from './manifest.js';
3
+ type Frame = Manifest['frames'][number];
4
+ type Motion = Frame['motion'][number];
5
+ interface Started {
6
+ property: string;
7
+ duration: number;
8
+ delay: number;
9
+ easing: string;
10
+ }
11
+ /** Opens the frame's state again on a fresh page. */
12
+ export type OpenFrame = (page: Page) => Promise<void>;
13
+ /**
14
+ * Opens the page, holds every animation at its start, runs the trigger and
15
+ * returns the transitions it started. A string is the reason nothing can be compared.
16
+ */
17
+ export declare function start(page: Page, open: OpenFrame, motion: Motion, reduced?: boolean): Promise<Started[] | string>;
18
+ /** Sets every animation to `ms` (capped at its end), held, and photographs the viewport. */
19
+ export declare function photographAt(page: Page, ms: number): Promise<Buffer>;
20
+ export declare const sameEasing: (a: string, b: string) => boolean;
21
+ /**
22
+ * Compares one motion with the frozen design: the transitions it starts, its
23
+ * stills at each moment, and its behaviour under reduced motion. Throws
24
+ * `Frame <id>, motion <motion id>: <reason>`.
25
+ */
26
+ export declare function compareMotion(page: Page, folder: string, frame: Frame, motion: Motion, tolerance: Manifest['tolerance'], open: OpenFrame): Promise<void>;
27
+ export {};
package/dist/motion.js ADDED
@@ -0,0 +1,134 @@
1
+ import path from 'node:path';
2
+ import { compareImage } from './compare.js';
3
+ import { repoRoot } from './repo.js';
4
+ const ROLES = ['button', 'link', 'checkbox', 'switch', 'tab', 'menuitem', 'radio'];
5
+ /** "150ms", "0.15s" or "0s" as milliseconds. */
6
+ function toMs(text) {
7
+ const m = /^(-?[\d.]+)(ms|s)$/.exec(text.trim());
8
+ if (!m)
9
+ throw new Error(`cannot read the time ${JSON.stringify(text)}`);
10
+ return Number(m[1]) * (m[2] === 's' ? 1000 : 1);
11
+ }
12
+ async function findTrigger(page, name) {
13
+ const found = [];
14
+ for (const role of ROLES) {
15
+ const loc = page.getByRole(role, { name, exact: true });
16
+ for (let i = 0; i < (await loc.count()); i++)
17
+ found.push(loc.nth(i));
18
+ }
19
+ if (found.length !== 1)
20
+ return `trigger matches ${found.length} elements`;
21
+ return found[0];
22
+ }
23
+ /**
24
+ * Opens the page, holds every animation at its start, runs the trigger and
25
+ * returns the transitions it started. A string is the reason nothing can be compared.
26
+ */
27
+ export async function start(page, open, motion, reduced = false) {
28
+ await open(page);
29
+ await page.emulateMedia({ reducedMotion: reduced ? 'reduce' : 'no-preference' });
30
+ const trigger = await findTrigger(page, motion.trigger.name);
31
+ if (typeof trigger === 'string')
32
+ return trigger;
33
+ const cdp = await page.context().newCDPSession(page);
34
+ await cdp.send('Animation.enable');
35
+ await cdp.send('Animation.setPlaybackRate', { playbackRate: 0 });
36
+ if (motion.trigger.action === 'click')
37
+ await trigger.click();
38
+ else if (motion.trigger.action === 'hover')
39
+ await trigger.hover();
40
+ else
41
+ await trigger.focus();
42
+ return page.evaluate(() => document
43
+ .getAnimations()
44
+ .filter((a) => a instanceof CSSTransition)
45
+ .map((a) => {
46
+ const t = a.effect?.getComputedTiming();
47
+ return {
48
+ property: a.transitionProperty,
49
+ duration: Number(t?.duration),
50
+ delay: Number(t?.delay),
51
+ easing: a.effect?.getTiming().easing ?? '',
52
+ };
53
+ }));
54
+ }
55
+ /** Sets every animation to `ms` (capped at its end), held, and photographs the viewport. */
56
+ export async function photographAt(page, ms) {
57
+ await page.evaluate((at) => {
58
+ for (const a of document.getAnimations()) {
59
+ a.pause();
60
+ const t = a.effect?.getComputedTiming();
61
+ a.currentTime = Math.min(at, Number(t?.delay) + Number(t?.duration));
62
+ }
63
+ }, ms);
64
+ return page.screenshot({ animations: 'allow', caret: 'hide', scale: 'css', type: 'png' });
65
+ }
66
+ const EASING_KEYWORDS = {
67
+ ease: 'cubic-bezier(0.25,0.1,0.25,1)',
68
+ 'ease-in': 'cubic-bezier(0.42,0,1,1)',
69
+ 'ease-out': 'cubic-bezier(0,0,0.58,1)',
70
+ 'ease-in-out': 'cubic-bezier(0.42,0,0.58,1)',
71
+ };
72
+ const canonicalEasing = (e) => {
73
+ const bare = e.replace(/\s+/g, '');
74
+ return EASING_KEYWORDS[bare] ?? bare;
75
+ };
76
+ export const sameEasing = (a, b) => canonicalEasing(a) === canonicalEasing(b);
77
+ /**
78
+ * Compares one motion with the frozen design: the transitions it starts, its
79
+ * stills at each moment, and its behaviour under reduced motion. Throws
80
+ * `Frame <id>, motion <motion id>: <reason>`.
81
+ */
82
+ export async function compareMotion(page, folder, frame, motion, tolerance, open) {
83
+ const label = `Frame ${frame.id}, motion ${motion.id}`;
84
+ const fail = (reason) => {
85
+ throw new Error(`${label}: ${reason}`);
86
+ };
87
+ if (motion.trigger.action === 'load')
88
+ fail('trigger load is not compared yet');
89
+ const started = await start(page, open, motion);
90
+ if (typeof started === 'string')
91
+ return fail(started);
92
+ if (started.length === 0)
93
+ fail('the trigger starts no transition');
94
+ // values-equal: sets, by property.
95
+ for (const want of motion.values) {
96
+ const got = started.find((s) => s.property === want.property);
97
+ if (!got)
98
+ fail(`property ${want.property} is in the design, the trigger does not start it`);
99
+ else {
100
+ const problems = [];
101
+ if (got.duration !== toMs(want.duration))
102
+ problems.push(`duration ${want.duration} in the design, ${got.duration}ms on the page`);
103
+ if (got.delay !== toMs(want.delay))
104
+ problems.push(`delay ${want.delay} in the design, ${got.delay}ms on the page`);
105
+ if (!sameEasing(got.easing, want.easing))
106
+ problems.push(`easing ${want.easing} in the design, ${got.easing} on the page`);
107
+ if (problems.length > 0)
108
+ fail(`property ${want.property}: ${problems.join('; ')}`);
109
+ }
110
+ }
111
+ for (const got of started) {
112
+ if (!motion.values.some((v) => v.property === got.property)) {
113
+ fail(`property ${got.property} is started by the trigger, the design does not list it`);
114
+ }
115
+ }
116
+ // stills-equal: a fresh page, every animation held and set to each moment.
117
+ const held = await start(page, open, motion);
118
+ if (typeof held === 'string')
119
+ return fail(held);
120
+ if (held.length === 0)
121
+ fail('the trigger starts no transition');
122
+ for (const [i, moment] of motion.moments.entries()) {
123
+ const buffer = await photographAt(page, moment);
124
+ const stillPath = path.relative(repoRoot(), path.resolve(folder, motion.stills[i]));
125
+ compareImage(buffer, stillPath.split(path.sep), tolerance, `${label}, at ${moment} ms`);
126
+ }
127
+ // reduced-motion: a fresh page, the trigger starts nothing longer than 0.
128
+ const reduced = await start(page, open, motion, true);
129
+ if (typeof reduced === 'string')
130
+ return fail(reduced);
131
+ const long = reduced.find((s) => s.duration > 0);
132
+ if (long)
133
+ fail(`reduced motion: property ${long.property} still runs ${long.duration}ms`);
134
+ }
@@ -0,0 +1,29 @@
1
+ import type { Page } from '@playwright/test';
2
+ export declare const CLOCK_START = "2026-01-01T00:00:00Z";
3
+ export declare const FROZEN_AT = "2026-01-01T00:00:02Z";
4
+ /**
5
+ * On a slow machine the page's clock can already be past FROZEN_AT, and pauseAt only moves
6
+ * forward. Pause at whichever is later (a second ahead, as the clock runs while we ask), then set
7
+ * the time back without running timers.
8
+ */
9
+ export declare function freezeClock(page: Page): Promise<void>;
10
+ /** One state of a screen: `path` is the page to open, `prepare` does what the state needs once it has loaded. */
11
+ export interface DesignState<Context = string> {
12
+ path: (context: Context) => string;
13
+ prepare?: (page: Page) => Promise<void>;
14
+ }
15
+ export interface OpenStateOptions {
16
+ theme: string;
17
+ width: number;
18
+ height: number;
19
+ }
20
+ /** Opens a named state of a screen with a fixed theme, viewport and clock. */
21
+ export type OpenState = (page: Page, name: string, options: OpenStateOptions) => Promise<void>;
22
+ /** Every `<surface>/<state>` that has a file under `dir`. */
23
+ export declare function knownStates(dir: string): string[];
24
+ /**
25
+ * Settled means the fonts the screen asks for are loaded. `fonts.ready` can resolve before a face
26
+ * the layout asks for late has started loading, so look until three looks in a row, 100 ms apart
27
+ * on this side of the page (the page's own timers may be held), find nothing loading.
28
+ */
29
+ export declare function fontsLoaded(page: Page): Promise<void>;
@@ -0,0 +1,37 @@
1
+ import { readFileSync, readdirSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ export const CLOCK_START = '2026-01-01T00:00:00Z';
4
+ export const FROZEN_AT = '2026-01-01T00:00:02Z';
5
+ /**
6
+ * On a slow machine the page's clock can already be past FROZEN_AT, and pauseAt only moves
7
+ * forward. Pause at whichever is later (a second ahead, as the clock runs while we ask), then set
8
+ * the time back without running timers.
9
+ */
10
+ export async function freezeClock(page) {
11
+ const pageNow = await page.evaluate(() => Date.now());
12
+ await page.clock.pauseAt(new Date(Math.max(pageNow + 1000, Date.parse(FROZEN_AT))));
13
+ await page.clock.setSystemTime(new Date(FROZEN_AT));
14
+ }
15
+ /** Every `<surface>/<state>` that has a file under `dir`. */
16
+ export function knownStates(dir) {
17
+ return readdirSync(dir, { recursive: true, encoding: 'utf8' })
18
+ .filter((entry) => entry.endsWith('.ts'))
19
+ .filter((entry) => /^\s*export\s+default\b/m.test(readFileSync(path.join(dir, entry), 'utf8')))
20
+ .map((entry) => entry.slice(0, -'.ts'.length).split(path.sep).join('/'))
21
+ .sort();
22
+ }
23
+ /**
24
+ * Settled means the fonts the screen asks for are loaded. `fonts.ready` can resolve before a face
25
+ * the layout asks for late has started loading, so look until three looks in a row, 100 ms apart
26
+ * on this side of the page (the page's own timers may be held), find nothing loading.
27
+ */
28
+ export async function fontsLoaded(page) {
29
+ let quiet = 0;
30
+ for (let look = 0; look < 100 && quiet < 3; look++) {
31
+ await page.evaluate(() => document.fonts.ready);
32
+ quiet = (await page.evaluate(() => document.fonts.status)) === 'loaded' ? quiet + 1 : 0;
33
+ await page.waitForTimeout(100);
34
+ }
35
+ if (quiet < 3)
36
+ throw new Error('Fonts were still loading after 10 seconds');
37
+ }
@@ -0,0 +1,19 @@
1
+ import { type OpenState } from './open-state.js';
2
+ /** Options of {@link registerFrozenSpecs}. */
3
+ export interface FrozenSpecsOptions {
4
+ /** Opens a named state of the app; for motion it reopens the state on a fresh page. */
5
+ openState: OpenState;
6
+ }
7
+ /**
8
+ * Registers the app's design check, from the current directory: one test per
9
+ * frozen frame (and its motion) in `design/frozen`, opened through
10
+ * `openState` and compared with the frozen still; `no frozen design` when
11
+ * nothing is frozen; `frozen design loads` failing when the folder cannot be
12
+ * read; and a `freeze` test that runs only when `DESIGN_FREEZE` names a request
13
+ * file. States are read from `design/states`, the image from
14
+ * `tests/design/design-image.json`.
15
+ *
16
+ * It calls `test(...)` while the spec file loads, so the package and the app
17
+ * must share one `@playwright/test`, which the peer dependency gives.
18
+ */
19
+ export declare function registerFrozenSpecs({ openState }: FrozenSpecsOptions): void;
@@ -0,0 +1,70 @@
1
+ import path from 'node:path';
2
+ import { test } from '@playwright/test';
3
+ import { blockOutside, compareFrame } from './compare.js';
4
+ import { describeFrozen } from './describe-frozen.js';
5
+ import { freezeFeature } from './freeze.js';
6
+ import { readDesignImage } from './manifest.js';
7
+ import { compareMotion } from './motion.js';
8
+ import { knownStates } from './open-state.js';
9
+ import { repoRoot } from './repo.js';
10
+ /**
11
+ * Registers the app's design check, from the current directory: one test per
12
+ * frozen frame (and its motion) in `design/frozen`, opened through
13
+ * `openState` and compared with the frozen still; `no frozen design` when
14
+ * nothing is frozen; `frozen design loads` failing when the folder cannot be
15
+ * read; and a `freeze` test that runs only when `DESIGN_FREEZE` names a request
16
+ * file. States are read from `design/states`, the image from
17
+ * `tests/design/design-image.json`.
18
+ *
19
+ * It calls `test(...)` while the spec file loads, so the package and the app
20
+ * must share one `@playwright/test`, which the peer dependency gives.
21
+ */
22
+ export function registerFrozenSpecs({ openState }) {
23
+ const repo = repoRoot();
24
+ const root = path.join(repo, 'design/frozen');
25
+ const states = () => knownStates(path.join(repo, 'design/states'));
26
+ const image = () => readDesignImage(path.join(repo, 'tests/design/design-image.json'));
27
+ let described;
28
+ let failure;
29
+ try {
30
+ described = describeFrozen(root, { states: states(), image: image() });
31
+ }
32
+ catch (error) {
33
+ failure = error instanceof Error ? error : new Error(String(error));
34
+ }
35
+ if (failure) {
36
+ const error = failure;
37
+ test('frozen design loads', () => {
38
+ throw error;
39
+ });
40
+ }
41
+ else if (described && described.frames.length === 0) {
42
+ const { message } = described;
43
+ test('no frozen design', () => {
44
+ console.log(message);
45
+ });
46
+ }
47
+ else {
48
+ for (const { folder, frame, tolerance } of described?.frames ?? []) {
49
+ test(`frame ${path.basename(folder)} ${frame.id}`, async ({ page, context }) => {
50
+ await blockOutside(context);
51
+ const open = (p) => openState(p, frame.state, {
52
+ theme: frame.theme,
53
+ width: frame.width,
54
+ height: frame.height,
55
+ });
56
+ await open(page);
57
+ await compareFrame(page, folder, frame, tolerance);
58
+ for (const motion of frame.motion) {
59
+ await compareMotion(page, folder, frame, motion, tolerance, open);
60
+ }
61
+ });
62
+ }
63
+ }
64
+ // The command: DESIGN_FREEZE=design/freeze/<feature>.json design-check --grep freeze
65
+ test('freeze', async () => {
66
+ const request = process.env.DESIGN_FREEZE;
67
+ test.skip(!request, 'set DESIGN_FREEZE to a request file');
68
+ await freezeFeature(path.resolve(request), { root, states: states(), image: image() });
69
+ });
70
+ }
package/dist/repo.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ /** The repository the check runs in: the current directory, where the CLI is started. */
2
+ export declare function repoRoot(): string;
package/dist/repo.js ADDED
@@ -0,0 +1,4 @@
1
+ /** The repository the check runs in: the current directory, where the CLI is started. */
2
+ export function repoRoot() {
3
+ return process.cwd();
4
+ }
@@ -0,0 +1,2 @@
1
+ /** The text `design-check --help` prints. */
2
+ export declare function usage(): string;
package/dist/usage.js ADDED
@@ -0,0 +1,13 @@
1
+ /** The text `design-check --help` prints. */
2
+ export function usage() {
3
+ return [
4
+ 'Usage: design-check [playwright arguments]',
5
+ '',
6
+ "Runs the app's design check in the Playwright image named in",
7
+ 'tests/design/design-image.json, with the current directory as the app folder.',
8
+ 'Every argument is passed to `playwright test`.',
9
+ '',
10
+ ' --help print this text',
11
+ '',
12
+ ].join('\n');
13
+ }
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "@wtfalch/design-check",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "The design check: compares an app's named states with the frozen design frames.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/wtfalch/design",
9
+ "directory": "packages/design-check"
10
+ },
11
+ "type": "module",
12
+ "files": ["dist"],
13
+ "publishConfig": {
14
+ "access": "public"
15
+ },
16
+ "main": "./dist/index.js",
17
+ "types": "./dist/index.d.ts",
18
+ "exports": {
19
+ ".": {
20
+ "types": "./dist/index.d.ts",
21
+ "default": "./dist/index.js"
22
+ }
23
+ },
24
+ "bin": {
25
+ "design-check": "./dist/cli.js"
26
+ },
27
+ "sideEffects": false,
28
+ "engines": {
29
+ "node": ">=22.0.0"
30
+ },
31
+ "scripts": {
32
+ "build": "rm -rf dist && tsc -p tsconfig.build.json",
33
+ "prepack": "pnpm build",
34
+ "typecheck": "tsc --noEmit",
35
+ "test": "playwright test"
36
+ },
37
+ "dependencies": {
38
+ "zod": "4.6.2"
39
+ },
40
+ "peerDependencies": {
41
+ "@playwright/test": ">=1.62.1 <2"
42
+ },
43
+ "devDependencies": {
44
+ "@playwright/test": "1.62.1",
45
+ "@types/node": "^22",
46
+ "typescript": "^5.9.0"
47
+ }
48
+ }