@recursica/adapter-tester 5.1.3 → 5.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 +1 -1
- package/dist/adapter-tester.schema.json.d.ts +6 -1
- package/dist/cli.cjs +10 -10
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +101 -96
- package/dist/cli.js.map +1 -1
- package/dist/fileConfig.d.ts +10 -3
- package/dist/fileConfig.d.ts.map +1 -1
- package/dist/golden/resolveSourceOfTruthGolden.d.ts.map +1 -1
- package/dist/harness/mantineSourceOfTruth.d.ts +34 -0
- package/dist/harness/mantineSourceOfTruth.d.ts.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/mantineSourceOfTruth-6KZlsQ67.cjs +89 -0
- package/dist/mantineSourceOfTruth-6KZlsQ67.cjs.map +1 -0
- package/dist/{mantineSourceOfTruth-BDJ5mfpd.js → mantineSourceOfTruth-CAKhcVCT.js} +68 -34
- package/dist/mantineSourceOfTruth-CAKhcVCT.js.map +1 -0
- package/dist/portDiscovery.d.ts +1 -1
- package/dist/testing.cjs +1 -1
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.js +22 -22
- package/dist/testing.js.map +1 -1
- package/package.json +1 -1
- package/report-header.txt +1 -1
- package/src/adapter-tester.schema.json +6 -1
- package/dist/mantineSourceOfTruth-BDJ5mfpd.js.map +0 -1
- package/dist/mantineSourceOfTruth-CdRlVrRC.cjs +0 -75
- package/dist/mantineSourceOfTruth-CdRlVrRC.cjs.map +0 -1
|
@@ -1,13 +1,18 @@
|
|
|
1
|
-
import { mkdirSync as
|
|
1
|
+
import { mkdirSync as m, writeFileSync as n } from "node:fs";
|
|
2
2
|
import { join as t } from "node:path";
|
|
3
|
-
const
|
|
3
|
+
const u = [
|
|
4
|
+
"recursica_variables_scoped.css",
|
|
5
|
+
"recursica_tokens.json",
|
|
6
|
+
"recursica_brand.json",
|
|
7
|
+
"recursica_ui-kit.json"
|
|
8
|
+
], d = "^8.0.0", a = "^10.3.3", p = "^19.0.0", l = {
|
|
4
9
|
"@storybook/addon-docs": a,
|
|
5
10
|
"@storybook/addon-a11y": a,
|
|
6
11
|
"storybook-dark-mode": "^5.0.0"
|
|
7
|
-
},
|
|
12
|
+
}, f = {
|
|
8
13
|
"react-markdown": "^10.1.0"
|
|
9
14
|
};
|
|
10
|
-
function
|
|
15
|
+
function y(r) {
|
|
11
16
|
return {
|
|
12
17
|
name: "adapter-tester-mantine-source-of-truth-harness",
|
|
13
18
|
private: !0,
|
|
@@ -21,20 +26,19 @@ function m(r) {
|
|
|
21
26
|
dependencies: {
|
|
22
27
|
"@recursica/adapter-mantine-v8": r.mantineAdapterVersion,
|
|
23
28
|
"@recursica/storybook-template": r.storybookTemplateVersion,
|
|
24
|
-
"@recursica/official-release": "latest",
|
|
25
29
|
"@recursica/adapter-common": "latest",
|
|
26
|
-
"@mantine/core":
|
|
27
|
-
"@mantine/dates":
|
|
28
|
-
react:
|
|
29
|
-
"react-dom":
|
|
30
|
+
"@mantine/core": d,
|
|
31
|
+
"@mantine/dates": d,
|
|
32
|
+
react: p,
|
|
33
|
+
"react-dom": p,
|
|
30
34
|
storybook: a,
|
|
31
35
|
"@storybook/react-vite": a,
|
|
32
|
-
...
|
|
33
|
-
...
|
|
36
|
+
...l,
|
|
37
|
+
...f
|
|
34
38
|
}
|
|
35
39
|
};
|
|
36
40
|
}
|
|
37
|
-
const
|
|
41
|
+
const h = `import { createMainConfig } from "@recursica/storybook-template/main";
|
|
38
42
|
|
|
39
43
|
const config = createMainConfig({
|
|
40
44
|
stories: [
|
|
@@ -53,17 +57,19 @@ const config = createMainConfig({
|
|
|
53
57
|
config.typescript = { ...config.typescript, reactDocgen: false };
|
|
54
58
|
|
|
55
59
|
export default config;
|
|
56
|
-
|
|
60
|
+
`;
|
|
61
|
+
function g() {
|
|
62
|
+
return `import type { Preview } from "@storybook/react-vite";
|
|
57
63
|
import { createPreviewConfig } from "@recursica/storybook-template/preview";
|
|
58
64
|
import { MantineProvider } from "@mantine/core";
|
|
59
65
|
import { Layer } from "@recursica/adapter-common";
|
|
60
66
|
import "@mantine/core/styles.css";
|
|
61
67
|
import "@mantine/dates/styles.css";
|
|
62
68
|
import "@recursica/adapter-common/style.css";
|
|
63
|
-
import "
|
|
64
|
-
import recursicaTokens from "
|
|
65
|
-
import recursicaBrand from "
|
|
66
|
-
import recursicaUIKit from "
|
|
69
|
+
import "../recursica_variables_scoped.css";
|
|
70
|
+
import recursicaTokens from "../recursica_tokens.json";
|
|
71
|
+
import recursicaBrand from "../recursica_brand.json";
|
|
72
|
+
import recursicaUIKit from "../recursica_ui-kit.json";
|
|
67
73
|
|
|
68
74
|
const basePreview = createPreviewConfig({
|
|
69
75
|
defaultTheme: "light",
|
|
@@ -79,7 +85,7 @@ const basePreview = createPreviewConfig({
|
|
|
79
85
|
// dramatically smaller/differently-positioned than the source of truth's (no Layer padding,
|
|
80
86
|
// background, or border-radius at all), which alone can blow past the pixel-diff threshold
|
|
81
87
|
// regardless of whether the actual Recursica tokens match — a false positive, not a real
|
|
82
|
-
// component bug. ColorSchemeWrapper (mantine-
|
|
88
|
+
// component bug. ColorSchemeWrapper (adapter-mantine-v8's dark-mode-toggle sync helper) is
|
|
83
89
|
// intentionally not replicated — it only matters for the interactive dev-mode UI, not automated
|
|
84
90
|
// screenshot diffing, which always runs in a single theme.
|
|
85
91
|
const preview: Preview = {
|
|
@@ -106,33 +112,61 @@ const preview: Preview = {
|
|
|
106
112
|
|
|
107
113
|
export default preview;
|
|
108
114
|
`;
|
|
109
|
-
|
|
115
|
+
}
|
|
116
|
+
function k(r, e, o) {
|
|
117
|
+
const s = r === "target" ? o : t(e, "node_modules/@recursica/adapter-mantine-v8");
|
|
118
|
+
return `import { copyFileSync } from "node:fs";
|
|
119
|
+
import { join } from "node:path";
|
|
120
|
+
|
|
121
|
+
const sourceDir = ${JSON.stringify(s)};
|
|
122
|
+
const destDir = ${JSON.stringify(e)};
|
|
123
|
+
const files = ${JSON.stringify(u, null, 2)};
|
|
124
|
+
|
|
125
|
+
for (const file of files) {
|
|
126
|
+
copyFileSync(join(sourceDir, file), join(destDir, file));
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
console.log(\`[adapter-tester] copied Recursica tokens from \${sourceDir}\`);
|
|
130
|
+
`;
|
|
131
|
+
}
|
|
132
|
+
function v(r) {
|
|
110
133
|
const {
|
|
111
134
|
dir: e,
|
|
112
|
-
mantineAdapterVersion:
|
|
113
|
-
storybookTemplateVersion:
|
|
135
|
+
mantineAdapterVersion: o = "latest",
|
|
136
|
+
storybookTemplateVersion: s = "latest",
|
|
137
|
+
tokensSource: i = "target",
|
|
138
|
+
targetDir: c
|
|
114
139
|
} = r;
|
|
115
|
-
|
|
140
|
+
if (i === "target" && !c)
|
|
141
|
+
throw new Error(
|
|
142
|
+
`mantineSourceOfTruthWebServer: tokensSource "target" (the default) requires targetDir — the target adapter's own repo root, source of its 4 committed Recursica token files.`
|
|
143
|
+
);
|
|
144
|
+
return m(t(e, ".storybook"), { recursive: !0 }), n(
|
|
116
145
|
t(e, "package.json"),
|
|
117
146
|
JSON.stringify(
|
|
118
|
-
|
|
119
|
-
mantineAdapterVersion:
|
|
120
|
-
storybookTemplateVersion:
|
|
147
|
+
y({
|
|
148
|
+
mantineAdapterVersion: o,
|
|
149
|
+
storybookTemplateVersion: s
|
|
121
150
|
}),
|
|
122
151
|
null,
|
|
123
152
|
2
|
|
124
153
|
) + `
|
|
125
154
|
`
|
|
126
|
-
),
|
|
155
|
+
), n(t(e, ".storybook/main.ts"), h), n(t(e, ".storybook/preview.tsx"), g()), n(
|
|
156
|
+
t(e, "copy-tokens.mjs"),
|
|
157
|
+
k(i, e, c)
|
|
158
|
+
), n(t(e, ".gitignore"), `node_modules
|
|
159
|
+
*.json
|
|
160
|
+
*.css
|
|
127
161
|
`), e;
|
|
128
162
|
}
|
|
129
|
-
function
|
|
130
|
-
const e =
|
|
131
|
-
mantineAdapterVersion:
|
|
132
|
-
storybookTemplateVersion:
|
|
163
|
+
function S(r) {
|
|
164
|
+
const e = v(r), {
|
|
165
|
+
mantineAdapterVersion: o = "latest",
|
|
166
|
+
storybookTemplateVersion: s = "latest"
|
|
133
167
|
} = r;
|
|
134
168
|
return {
|
|
135
|
-
command: `npm install @recursica/adapter-mantine-v8@${
|
|
169
|
+
command: `npm install @recursica/adapter-mantine-v8@${o} @recursica/storybook-template@${s} --no-audit --no-fund && node copy-tokens.mjs && npm run storybook`,
|
|
136
170
|
port: r.port,
|
|
137
171
|
cwd: e,
|
|
138
172
|
reuseExistingServer: !process.env.CI,
|
|
@@ -141,7 +175,7 @@ function k(r) {
|
|
|
141
175
|
};
|
|
142
176
|
}
|
|
143
177
|
export {
|
|
144
|
-
|
|
145
|
-
|
|
178
|
+
S as m,
|
|
179
|
+
v as s
|
|
146
180
|
};
|
|
147
|
-
//# sourceMappingURL=mantineSourceOfTruth-
|
|
181
|
+
//# sourceMappingURL=mantineSourceOfTruth-CAKhcVCT.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mantineSourceOfTruth-CAKhcVCT.js","sources":["../src/harness/mantineSourceOfTruth.ts"],"sourcesContent":["import { mkdirSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n/** The 4 Recursica token files every real adapter commits at its own repo root. */\nconst TOKEN_FILES = [\n \"recursica_variables_scoped.css\",\n \"recursica_tokens.json\",\n \"recursica_brand.json\",\n \"recursica_ui-kit.json\",\n];\n\n/**\n * Generates a small, throwaway Storybook project that installs\n * `@recursica/adapter-mantine-v8` as a real npm dependency (not a workspace\n * link) and boots a real Storybook from its published `src/**\\/*.stories.tsx`\n * files, using `@recursica/storybook-template`'s exported factories.\n *\n * This lets any repo — including ones that never checked out the Recursica\n * monorepo — run adapter-tester's visual regression suite against Mantine\n * (Recursica's source-of-truth adapter) as one side of the comparison, while\n * the other side is that repo's own already-running local Storybook.\n *\n * See PROPOSAL-installed-package-harness.md for the verified prototype this\n * is built from, and the three upstream gaps it works around.\n */\n\n/**\n * Which Recursica token snapshot the harness's Mantine components render\n * with:\n *\n * - `\"target\"` (default): the target adapter's own committed\n * `recursica_variables_scoped.css`/`recursica_tokens.json`/\n * `recursica_brand.json`/`recursica_ui-kit.json` (read from `targetDir`,\n * copied into the harness once `npm install` finishes) — makes the\n * divergence check mean exactly \"given the *same* tokens this target\n * adapter is using, does it render the same as Mantine's own components,\"\n * isolating adapter-mapping correctness from any token-snapshot drift\n * between the two repos.\n * - `\"mantine-package\"`: `@recursica/adapter-mantine-v8`'s own bundled\n * token files (whatever it was last published with) — tests against\n * Mantine's own understanding of the tokens instead, which also (as a\n * side effect) flags a target repo whose own committed tokens have gone\n * stale relative to Mantine's.\n *\n * Never `@recursica/official-release` — confirmed live (not a theoretical\n * concern) to be a stale, deprecated, generic token snapshot unrelated to\n * either adapter's real ones: it resolves the brand's primary/secondary\n * fonts to Lexend/Bellota Text, not this design system's actual Dongle/\n * Nunito Sans. An earlier version of this harness imported from it\n * directly — this type/its two real options replace that entirely.\n */\nexport type MantineSourceOfTruthTokensSource = \"target\" | \"mantine-package\";\n\nexport interface MantineSourceOfTruthHarnessOptions {\n /**\n * Directory the harness project is scaffolded into. Regenerated on every\n * call — add it to your .gitignore rather than committing it.\n */\n dir: string;\n /** First-guess port, shown for `--dry-run` visibility only. The harness's\n * Storybook is never pinned to this — see `HarnessWebServerConfig.port`. */\n port: number;\n /** npm version/range for @recursica/adapter-mantine-v8. Defaults to \"latest\". */\n mantineAdapterVersion?: string;\n /** npm version/range for @recursica/storybook-template. Defaults to \"latest\". */\n storybookTemplateVersion?: string;\n /** See `MantineSourceOfTruthTokensSource`. Defaults to `\"target\"`. */\n tokensSource?: MantineSourceOfTruthTokensSource;\n /**\n * The target adapter's own repo root — required when `tokensSource` is\n * `\"target\"` (the default), the source the 4 token files are copied\n * from. Unused (and not required) for `\"mantine-package\"`.\n */\n targetDir?: string;\n}\n\nexport interface HarnessWebServerConfig {\n command: string;\n /** First-guess port, shown for `--dry-run` visibility only — not\n * authoritative. The real port is whatever this Storybook's own startup\n * banner reports once it's actually running (see portDiscovery.ts), since\n * Storybook silently falls back to an OS-assigned port whenever this one\n * is taken. */\n port: number;\n cwd: string;\n reuseExistingServer: boolean;\n /** File the real, detected port is cached in between runs, so a later\n * `reuseExistingServer` run can find this instance again. */\n cacheFile: string;\n timeout: number;\n}\n\n// Peer/dev ranges pinned to what @recursica/adapter-mantine-v8 and\n// @recursica/storybook-template themselves require, so the harness can't\n// drift onto an incompatible Mantine or Storybook major version.\nconst MANTINE_CORE_RANGE = \"^8.0.0\";\nconst STORYBOOK_RANGE = \"^10.3.3\";\nconst REACT_RANGE = \"^19.0.0\";\n\n// storybook-template's createMainConfig() defaults its addons list to these\n// three but doesn't declare them as peerDependencies (proposal gap 2) — a\n// harness that skips installing any of them gets a silent \"could not\n// resolve addon\" warning at boot, then a hard runtime crash later when Vite\n// pre-bundles preview.tsx's dependency graph. Installed explicitly here.\nconst DEFAULT_ADDON_DEPENDENCIES = {\n \"@storybook/addon-docs\": STORYBOOK_RANGE,\n \"@storybook/addon-a11y\": STORYBOOK_RANGE,\n \"storybook-dark-mode\": \"^5.0.0\",\n};\n\n// adapter-mantine-v8's Introduction.stories.tsx (Version.tsx/OverStyling.tsx)\n// needs react-markdown, but it's a devDependency there — Storybook-only,\n// never bundled into dist — so an external `npm install` of the published\n// package won't pull it in. The harness boots a real Storybook against\n// src/, so it must provide this itself. Installed explicitly here.\nconst WORKAROUND_DEPENDENCIES = {\n \"react-markdown\": \"^10.1.0\",\n};\n\nfunction harnessPackageJson(options: {\n mantineAdapterVersion: string;\n storybookTemplateVersion: string;\n}) {\n return {\n name: \"adapter-tester-mantine-source-of-truth-harness\",\n private: true,\n type: \"module\",\n scripts: {\n // No `-p` pin — Storybook silently falls back to an OS-assigned port\n // whenever its default is taken, so the caller detects the real port\n // from this process's own output rather than trusting a fixed one.\n storybook: `storybook dev`,\n },\n dependencies: {\n \"@recursica/adapter-mantine-v8\": options.mantineAdapterVersion,\n \"@recursica/storybook-template\": options.storybookTemplateVersion,\n \"@recursica/adapter-common\": \"latest\",\n \"@mantine/core\": MANTINE_CORE_RANGE,\n \"@mantine/dates\": MANTINE_CORE_RANGE,\n react: REACT_RANGE,\n \"react-dom\": REACT_RANGE,\n storybook: STORYBOOK_RANGE,\n \"@storybook/react-vite\": STORYBOOK_RANGE,\n ...DEFAULT_ADDON_DEPENDENCIES,\n ...WORKAROUND_DEPENDENCIES,\n },\n };\n}\n\nconst MAIN_TS = `import { createMainConfig } from \"@recursica/storybook-template/main\";\n\nconst config = createMainConfig({\n stories: [\n \"../node_modules/@recursica/adapter-mantine-v8/src/**/*.stories.@(js|jsx|mjs|ts|tsx)\",\n ],\n enableCORS: true,\n});\n\n// react-docgen-typescript can't resolve a TS project for a config file living\n// in .storybook/ when the component source it's docgen'ing lives three\n// directories down inside node_modules — it throws \"Cannot read properties\n// of undefined (reading 'fileExists')\", which surfaces as a plain 404 on\n// preview.tsx. Docgen only powers Storybook's Controls/Docs tables, which\n// this harness never renders, so disabling it is a safe workaround (see\n// PROPOSAL-installed-package-harness.md, gap 3).\nconfig.typescript = { ...config.typescript, reactDocgen: false };\n\nexport default config;\n`;\n\n// Both `tokensSource` modes copy the 4 token files into the harness's own\n// root (see `copyTokensScript()`) before Storybook boots, rather than\n// importing a package subpath directly — `@recursica/adapter-mantine-v8`'s\n// own `package.json` `exports` map only lists `\".\"`/`\"./style.css\"`, so a\n// bare `import \"@recursica/adapter-mantine-v8/recursica_tokens.json\"` would\n// fail to resolve under strict ESM exports-map enforcement even though the\n// file physically ships in the package (confirmed by reading that package's\n// real, installed `package.json` directly). Copying sidesteps that\n// entirely, and gives both modes the identical, simple `../recursica_*`\n// relative-import shape a real adapter's own `preview.tsx` already uses.\nfunction previewTsx(): string {\n return `import type { Preview } from \"@storybook/react-vite\";\nimport { createPreviewConfig } from \"@recursica/storybook-template/preview\";\nimport { MantineProvider } from \"@mantine/core\";\nimport { Layer } from \"@recursica/adapter-common\";\nimport \"@mantine/core/styles.css\";\nimport \"@mantine/dates/styles.css\";\nimport \"@recursica/adapter-common/style.css\";\nimport \"../recursica_variables_scoped.css\";\nimport recursicaTokens from \"../recursica_tokens.json\";\nimport recursicaBrand from \"../recursica_brand.json\";\nimport recursicaUIKit from \"../recursica_ui-kit.json\";\n\nconst basePreview = createPreviewConfig({\n defaultTheme: \"light\",\n recursicaTokensJsonPath: recursicaTokens,\n recursicaBrandJsonPath: recursicaBrand,\n recursicaUIKitJsonPath: recursicaUIKit,\n});\n\n// Mirrors adapter-mantine-v8's own .storybook/preview.tsx decorator (every story defaults to\n// withLayer: true, layer: 0, wrapped with 48px padding) — every real adapter's own preview.tsx\n// applies this same wrapping, so a target adapter's story renders inside the same Layer\n// chrome/padding the source-of-truth side does. Without this, target screenshots come out\n// dramatically smaller/differently-positioned than the source of truth's (no Layer padding,\n// background, or border-radius at all), which alone can blow past the pixel-diff threshold\n// regardless of whether the actual Recursica tokens match — a false positive, not a real\n// component bug. ColorSchemeWrapper (adapter-mantine-v8's dark-mode-toggle sync helper) is\n// intentionally not replicated — it only matters for the interactive dev-mode UI, not automated\n// screenshot diffing, which always runs in a single theme.\nconst preview: Preview = {\n ...basePreview,\n decorators: [\n (Story, context) => {\n const { withLayer = true, layer = 0 } = context.args;\n const content = <Story />;\n return (\n <MantineProvider>\n {withLayer ? (\n <Layer layer={layer as 0 | 1 | 2 | 3} style={{ padding: \"48px\" }}>\n {content}\n </Layer>\n ) : (\n content\n )}\n </MantineProvider>\n );\n },\n ...(basePreview.decorators || []),\n ],\n};\n\nexport default preview;\n`;\n}\n\n/**\n * Generates `copy-tokens.mjs` — run as its own step between `npm install`\n * and `npm run storybook` (see `mantineSourceOfTruthWebServer`'s `command`),\n * not inlined into `scaffoldMantineSourceOfTruthHarness` itself: for\n * `\"mantine-package\"` mode, the source files live inside\n * `node_modules/@recursica/adapter-mantine-v8`, which doesn't exist yet at\n * scaffold time (scaffolding runs before `npm install`) — this script only\n * runs once the package is actually on disk. `\"target\"` mode's source files\n * are already on disk at scaffold time, but uses the same after-install\n * timing for one consistent code path rather than two.\n */\nfunction copyTokensScript(\n tokensSource: MantineSourceOfTruthTokensSource,\n dir: string,\n targetDir: string | undefined,\n): string {\n const sourceDir =\n tokensSource === \"target\"\n ? targetDir!\n : join(dir, \"node_modules/@recursica/adapter-mantine-v8\");\n\n return `import { copyFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nconst sourceDir = ${JSON.stringify(sourceDir)};\nconst destDir = ${JSON.stringify(dir)};\nconst files = ${JSON.stringify(TOKEN_FILES, null, 2)};\n\nfor (const file of files) {\n copyFileSync(join(sourceDir, file), join(destDir, file));\n}\n\nconsole.log(\\`[adapter-tester] copied Recursica tokens from \\${sourceDir}\\`);\n`;\n}\n\n/** Writes the harness project's files to `options.dir` without booting it. */\nexport function scaffoldMantineSourceOfTruthHarness(\n options: MantineSourceOfTruthHarnessOptions,\n): string {\n const {\n dir,\n mantineAdapterVersion = \"latest\",\n storybookTemplateVersion = \"latest\",\n tokensSource = \"target\",\n targetDir,\n } = options;\n\n if (tokensSource === \"target\" && !targetDir) {\n throw new Error(\n 'mantineSourceOfTruthWebServer: tokensSource \"target\" (the default) requires targetDir — the target adapter\\'s own repo root, source of its 4 committed Recursica token files.',\n );\n }\n\n mkdirSync(join(dir, \".storybook\"), { recursive: true });\n writeFileSync(\n join(dir, \"package.json\"),\n JSON.stringify(\n harnessPackageJson({\n mantineAdapterVersion,\n storybookTemplateVersion,\n }),\n null,\n 2,\n ) + \"\\n\",\n );\n writeFileSync(join(dir, \".storybook/main.ts\"), MAIN_TS);\n writeFileSync(join(dir, \".storybook/preview.tsx\"), previewTsx());\n writeFileSync(\n join(dir, \"copy-tokens.mjs\"),\n copyTokensScript(tokensSource, dir, targetDir),\n );\n writeFileSync(join(dir, \".gitignore\"), \"node_modules\\n*.json\\n*.css\\n\");\n\n return dir;\n}\n\n/**\n * Scaffolds the harness and returns a Playwright `webServer` entry for it.\n * Spread the result directly into `playwright.config.ts`'s `webServer` array.\n */\nexport function mantineSourceOfTruthWebServer(\n options: MantineSourceOfTruthHarnessOptions,\n): HarnessWebServerConfig {\n const dir = scaffoldMantineSourceOfTruthHarness(options);\n const {\n mantineAdapterVersion = \"latest\",\n storybookTemplateVersion = \"latest\",\n } = options;\n\n // A bare `npm install` is satisfied by a package-lock.json already sitting\n // in `dir` from a prior run and skips re-resolving against the registry\n // entirely — no network call — so a run can silently keep testing against\n // a stale @recursica/adapter-mantine-v8/storybook-template even after a newer\n // version is published. Naming the two version-pinned packages as explicit\n // `pkg@specifier` CLI args instead forces npm to re-check just those two\n // against the registry every run, while the rest of node_modules stays\n // cached. `copy-tokens.mjs` runs after install completes (see its own doc\n // comment for why) and before Storybook boots, so `preview.tsx`'s own\n // `../recursica_*` imports resolve correctly on first render.\n const command = `npm install @recursica/adapter-mantine-v8@${mantineAdapterVersion} @recursica/storybook-template@${storybookTemplateVersion} --no-audit --no-fund && node copy-tokens.mjs && npm run storybook`;\n\n return {\n command,\n port: options.port,\n cwd: dir,\n reuseExistingServer: !process.env.CI,\n cacheFile: join(dir, \"last-port.json\"),\n timeout: 180 * 1000,\n };\n}\n"],"names":["TOKEN_FILES","MANTINE_CORE_RANGE","STORYBOOK_RANGE","REACT_RANGE","DEFAULT_ADDON_DEPENDENCIES","WORKAROUND_DEPENDENCIES","harnessPackageJson","options","MAIN_TS","previewTsx","copyTokensScript","tokensSource","dir","targetDir","sourceDir","join","scaffoldMantineSourceOfTruthHarness","mantineAdapterVersion","storybookTemplateVersion","mkdirSync","writeFileSync","mantineSourceOfTruthWebServer"],"mappings":";;AAIA,MAAMA,IAAc;AAAA,EAClB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAsFMC,IAAqB,UACrBC,IAAkB,WAClBC,IAAc,WAOdC,IAA6B;AAAA,EACjC,yBAAyBF;AAAA,EACzB,yBAAyBA;AAAA,EACzB,uBA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@@ -4,7 +4,7 @@ import { HarnessWebServerConfig } from './harness/mantineSourceOfTruth.js';
|
|
|
4
4
|
* Boots a target's Storybook and discovers the real port it ends up on,
|
|
5
5
|
* instead of pinning one via `-p`/`--port`. Storybook silently falls back to
|
|
6
6
|
* an OS-assigned port whenever its default/configured one is taken (this is
|
|
7
|
-
* what caused the flaky `webServer` timeouts noted in mui-
|
|
7
|
+
* what caused the flaky `webServer` timeouts noted in @recursica/adapter-mui-v7), so the
|
|
8
8
|
* only reliable source of truth is the URL it prints in its own startup
|
|
9
9
|
* banner. Used by both the automated/headless run (cli.ts) and Dev Mode
|
|
10
10
|
* (devServer.ts) — neither pins a port anymore.
|
package/dist/testing.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const L=require("@playwright/test"),i=require("node:fs"),z=require("pixelmatch"),P=require("pngjs"),E=require("node:path"),D=require("./index-C6uYPRmx.cjs");function B(e,t){const n=P.PNG.sync.read(e),r=P.PNG.sync.read(t);if(n.width!==r.width||n.height!==r.height)return{diffPixels:1/0,diffImage:null};const s=new P.PNG({width:n.width,height:n.height});return{diffPixels:z(n.data,r.data,s.data,n.width,n.height,{threshold:.1}),diffImage:P.PNG.sync.write(s)}}const H="http://json-schema.org/draft-07/schema#",Y="https://github.com/borderux/recursica/tree/main/packages/adapter-tester/src/golden/manifest.schema.json",Q="test/golden/manifest.json",Z="Tracks golden (baseline) image metadata for @recursica/adapter-tester's golden-image visual regression checks. One manifest lives alongside its adapter's test/golden/<story-id>.png files, keyed by story id.",ee="object",te={type:"object",additionalProperties:!1,required:["createdAt"],properties:{createdAt:{type:"string",format:"date-time",description:"When this story's own golden PNG was last captured, via --update-golden, --approve-divergence, or first-run auto-create."},sourceOfTruthCreatedAt:{type:"string",format:"date-time",description:"The source-of-truth adapter's (mantine) manifest `createdAt` for this story at the time this adapter's divergence from it was last reviewed via --approve-divergence. Omitted on the source-of-truth adapter's own manifest, and omitted here until the first approval. If mantine's current `createdAt` for this story is newer than this value, the divergence is flagged again for re-review."}}},re={$schema:H,$id:Y,title:Q,description:Z,type:ee,additionalProperties:te},ne=D.index,U=new D.ajvExports.Ajv({allErrors:!0,strict:!0});ne(U);const _=U.compile(re);function C(e,t){if(_(e))return;const n=(_.errors??[]).map(r=>{var c;const s=(c=r.params)!=null&&c.additionalProperty?` '${r.params.additionalProperty}'`:"";return` - ${r.instancePath||"root"} ${r.message}${s}`}).join(`
|
|
2
2
|
`);throw new Error(`Invalid ${t}:
|
|
3
3
|
${n}`)}function j(e){return E.join(e,"manifest.json")}function J(e){return E.join(e,"manifest.json.lock")}function k(e,t){return E.join(e,`${t}.png`)}function b(e){const t=j(e);if(!i.existsSync(t))return{};const n=JSON.parse(i.readFileSync(t,"utf8"));return C(n,t),n}function oe(e,t){const n=j(e);C(t,n);const r={};for(const c of Object.keys(t).sort())r[c]=t[c];i.mkdirSync(e,{recursive:!0});const s=`${n}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;i.writeFileSync(s,JSON.stringify(r,null,2)+`
|
|
4
|
-
`),i.renameSync(s,n)}const se=25,ie=15e3;function ae(e){return new Promise(t=>setTimeout(t,e))}async function ce(e){i.mkdirSync(e,{recursive:!0});const t=J(e),n=Date.now()+ie;for(;;)try{i.closeSync(i.openSync(t,"wx"));return}catch(r){if(r.code!=="EEXIST")throw r;if(Date.now()>=n)throw new Error(`Timed out waiting for the manifest lock at "${t}" — delete it if a previous run crashed while holding it.`);await ae(se)}}function de(e){i.rmSync(J(e),{force:!0})}async function K(e,t,n){await ce(e);try{const r=b(e),s=n(r[t]);return s===void 0?delete r[t]:r[t]=s,oe(e,r),s}finally{de(e)}}function he(e,t,n){i.mkdirSync(e,{recursive:!0}),i.writeFileSync(k(e,t),n)}async function ue(e,t){const n=b(e),r=Object.keys(n).filter(s=>!t.has(s));for(const s of r){const c=k(e,s);i.existsSync(c)&&i.unlinkSync(c),await K(e,s,()=>{})}return r}const q="borderux/recursica-adapter-mantine-v8";async function le(e,t){var c,h;const n=await fetch(`https://registry.npmjs.org/${e}`);if(!n.ok)throw new Error(`Could not reach npm registry for ${e}: ${n.statusText}`);const r=await n.json(),s=((c=r["dist-tags"])==null?void 0:c[t])??((h=r.versions)!=null&&h[t]?t:void 0);if(!s)throw new Error(`${e} has no version or dist-tag "${t}" on the npm registry.`);return s}async function fe(e){if(e.type==="local"){if(!i.existsSync(j(e.dir)))throw new Error(`No golden baseline found at ${e.dir} — the source-of-truth divergence check has nothing to compare against. Capture one there first (--update-golden), or fix sourceOfTruth.dir if it's pointing at the wrong checkout.`);return{manifest:b(e.dir),async readImage(u){const d=k(e.dir,u);return i.existsSync(d)?i.readFileSync(d):null}}}let t;try{t=await le(e.packageName,e.versionSpec)}catch(a){throw new Error(`Could not resolve ${e.packageName}@${e.versionSpec} on the npm registry — the source-of-truth divergence check has nothing to compare against.`,{cause:a})}const n=E.join(e.cacheDir,t),r
|
|
4
|
+
`),i.renameSync(s,n)}const se=25,ie=15e3;function ae(e){return new Promise(t=>setTimeout(t,e))}async function ce(e){i.mkdirSync(e,{recursive:!0});const t=J(e),n=Date.now()+ie;for(;;)try{i.closeSync(i.openSync(t,"wx"));return}catch(r){if(r.code!=="EEXIST")throw r;if(Date.now()>=n)throw new Error(`Timed out waiting for the manifest lock at "${t}" — delete it if a previous run crashed while holding it.`);await ae(se)}}function de(e){i.rmSync(J(e),{force:!0})}async function K(e,t,n){await ce(e);try{const r=b(e),s=n(r[t]);return s===void 0?delete r[t]:r[t]=s,oe(e,r),s}finally{de(e)}}function he(e,t,n){i.mkdirSync(e,{recursive:!0}),i.writeFileSync(k(e,t),n)}async function ue(e,t){const n=b(e),r=Object.keys(n).filter(s=>!t.has(s));for(const s of r){const c=k(e,s);i.existsSync(c)&&i.unlinkSync(c),await K(e,s,()=>{})}return r}const q="borderux/recursica-adapter-mantine-v8";async function le(e,t){var c,h;const n=await fetch(`https://registry.npmjs.org/${e}`);if(!n.ok)throw new Error(`Could not reach npm registry for ${e}: ${n.statusText}`);const r=await n.json(),s=((c=r["dist-tags"])==null?void 0:c[t])??((h=r.versions)!=null&&h[t]?t:void 0);if(!s)throw new Error(`${e} has no version or dist-tag "${t}" on the npm registry.`);return s}async function fe(e){if(e.type==="local"){if(!i.existsSync(j(e.dir)))throw new Error(`No golden baseline found at ${e.dir} — the source-of-truth divergence check has nothing to compare against. Capture one there first (--update-golden), or fix sourceOfTruth.dir if it's pointing at the wrong checkout.`);return{manifest:b(e.dir),async readImage(u){const d=k(e.dir,u);return i.existsSync(d)?i.readFileSync(d):null}}}let t;try{t=await le(e.packageName,e.versionSpec)}catch(a){throw new Error(`Could not resolve ${e.packageName}@${e.versionSpec} on the npm registry — the source-of-truth divergence check has nothing to compare against.`,{cause:a})}const n=E.join(e.cacheDir,t),r=`v${t}`,s=`https://raw.githubusercontent.com/${q}/${r}/test/golden`;let c;const h=j(n);if(i.existsSync(h))c=b(n);else{let a;try{a=await fetch(`${s}/manifest.json`)}catch(m){throw new Error(`Could not reach GitHub to fetch ${r}'s golden baseline (${s}/manifest.json) — the source-of-truth divergence check has nothing to compare against.`,{cause:m})}if(!a.ok)throw new Error(`No golden baseline published for tag "${r}" in ${q} (${s}/manifest.json returned ${a.status}) — the source-of-truth divergence check has nothing to compare against. Confirm that tag exists and its release actually published test/golden/.`);const u=await a.text(),d=JSON.parse(u);C(d,`${s}/manifest.json`),i.mkdirSync(n,{recursive:!0}),i.writeFileSync(h,u),c=d}return{manifest:c,async readImage(a){const u=k(n,a);if(i.existsSync(u))return i.readFileSync(u);const d=await fetch(`${s}/${a}.png`);if(!d.ok)return null;const m=Buffer.from(await d.arrayBuffer());return i.mkdirSync(n,{recursive:!0}),i.writeFileSync(u,m),m}}}const pe=["Theme","Tokens","Introduction"];function M(e,t){return e===t||e.startsWith(t)}async function ge(e,t){let n;try{const r=await fetch(`${e.url}/index.json`);if(!r.ok)throw new Error(`Failed to fetch Storybook index: ${r.statusText}`);const c=(await r.json()).entries||{};n=Object.values(c).filter(h=>h.type==="story"&&!t.some(a=>h.title===a||h.title.startsWith(`${a}/`))),n.sort((h,a)=>h.id.localeCompare(a.id))}catch(r){throw console.error("Failed to load Storybook index from",`${e.url}/index.json`,r),new Error(`Storybook target "${e.name}" is not responsive or index.json is missing. Please ensure its Storybook is running.`)}return n}function R(e,t,n){let r;for(const s of Object.keys(t))M(e,s)&&(!r||s.length>r.length)&&(r=s);return r!==void 0?t[r]:n}async function me(e){const t=e.isSourceOfTruthAdapter?e.targets[0]:e.targets.find(o=>!o.sourceOfTruth);if(!t)throw new Error("adapter-tester config has no non-sourceOfTruth target to run the golden check against.");const n=e.excludeTitlePrefixes??pe,r=e.stories??{},s=Object.keys(r).filter(o=>r[o].exclude),c=Object.fromEntries(Object.entries(r).filter(([,o])=>o.goldenThreshold!==void 0).map(([o,l])=>[o,l.goldenThreshold])),h=Object.fromEntries(Object.entries(r).filter(([,o])=>o.sourceOfTruthThreshold!==void 0).map(([o,l])=>[o,l.sourceOfTruthThreshold])),a=e.goldenDir,u=e.goldenMode,d=e.checkMode,m=await ge(t,n),A=m.filter(o=>!s.some(l=>M(o.id,l)));if(u==="update-golden"){const o=await ue(a,new Set(A.map(l=>l.id)));o.length>0&&console.warn(`Pruned ${o.length} orphaned golden(s) no longer in Storybook: ${o.join(", ")}`)}const v=d!=="divergence"||e.isSourceOfTruthAdapter||!e.sourceOfTruthGolden?null:await fe(e.sourceOfTruthGolden),V=new Set(m.map(o=>o.id)),T=v?Object.keys(v.manifest).filter(o=>!V.has(o)&&!s.some(l=>M(o,l))).sort():[];T.length>0&&console.error(`[adapter-tester] ${T.length} stor(y/ies) exist in the source of truth but are missing here: ${T.join(", ")}. Add the missing story, or mark it \`exclude: true\` under \`stories\` in adapter-tester.config.json if intentional.`),console.log([`[adapter-tester] target: "${t.name}" (${t.url})`,`[adapter-tester] checkMode: "${d}" (${d==="divergence"?"live render vs source-of-truth's golden":"live render vs this project's own golden"})`,`[adapter-tester] goldenMode: "${u}"`,`[adapter-tester] goldenThresholdPixels: ${e.goldenThresholdPixels}`,`[adapter-tester] sourceOfTruthThresholdPixels: ${e.sourceOfTruthThresholdPixels}`,d==="divergence"?e.isSourceOfTruthAdapter?"[adapter-tester] sourceOfTruthGolden: skipped — this is the source-of-truth adapter, nothing to diverge from":e.sourceOfTruthGolden?`[adapter-tester] sourceOfTruthGolden: resolved, ${Object.keys(v.manifest).length} golden(s) available (config: ${JSON.stringify(e.sourceOfTruthGolden)})`:"[adapter-tester] sourceOfTruthGolden: skipped — no sourceOfTruthGolden configured":'[adapter-tester] sourceOfTruthGolden: not used in "own" checkMode',`[adapter-tester] stories: ${A.length} to check (excluded: ${s.length}, title prefixes excluded: ${n.join(", ")||"none"})`,`[adapter-tester] story parity with source of truth: ${T.length===0?"OK":`${T.length} missing (see error above)`}`].join(`
|
|
5
5
|
`));const W=d==="divergence"?"Source-of-Truth Divergence Check":"Own-Drift Golden Image Check";return{ownTargetName:t.name,suiteLabel:W,stories:A,missingFromSourceOfTruth:T,checkStory:async(o,l,g)=>{const w=await l.newPage();await w.setViewportSize({width:800,height:600}),await w.goto(`${t.url}/iframe.html?id=${o.id}&viewMode=story`,{waitUntil:"networkidle"}),await w.waitForSelector("#storybook-root"),await w.addStyleTag({content:"* { -webkit-font-smoothing: antialiased !important; -moz-osx-font-smoothing: grayscale !important; }"}),await w.evaluate(()=>Promise.all(Array.from(document.querySelectorAll('link[rel="stylesheet"]')).map(f=>f.sheet?Promise.resolve():new Promise(p=>{f.addEventListener("load",()=>p(),{once:!0}),f.addEventListener("error",()=>p(),{once:!0})}))).then(()=>document.fonts.ready)),await w.waitForTimeout(300);const O=await w.screenshot(),I=k(a,o.id),y=b(a)[o.id],X=u!=="check"||!y||!i.existsSync(I);let $;if(X)he(a,o.id,O),$=y!=null&&y.sourceOfTruthCreatedAt?{createdAt:new Date().toISOString(),sourceOfTruthCreatedAt:y.sourceOfTruthCreatedAt}:{createdAt:new Date().toISOString()},y||g.annotations.push({type:"golden-created",description:`No golden existed yet for "${o.id}" — captured one from this run.`});else if($=y,d==="own"){const f=i.readFileSync(I),{diffPixels:p,diffImage:S}=B(O,f),x=R(o.id,c,e.goldenThresholdPixels);p>=x&&(await g.attach("expected",{body:f,contentType:"image/png"}),await g.attach("actual",{body:O,contentType:"image/png"}),S&&await g.attach("diff",{body:S,contentType:"image/png"})),L.expect.soft(p,`"${o.id}" has drifted from its own golden image (${p} mismatched pixels, threshold ${x})`).toBeLessThan(x)}if(v){const f=v.manifest[o.id],p=f?await v.readImage(o.id):null;if(f&&p)if(u==="approve-divergence")$={...$,sourceOfTruthCreatedAt:f.createdAt};else{const{diffPixels:S,diffImage:x}=B(O,p),G=R(o.id,h,e.sourceOfTruthThresholdPixels),F=$.sourceOfTruthCreatedAt,N=S<G||F!==void 0&&F>=f.createdAt;N||(await g.attach("expected",{body:p,contentType:"image/png"}),await g.attach("actual",{body:O,contentType:"image/png"}),x&&await g.attach("diff",{body:x,contentType:"image/png"}),g.annotations.push({type:"source-of-truth-divergence",description:`"${o.id}" differs from the source of truth's golden by ${S} mismatched pixels (threshold ${G}) and hasn't been reviewed — run with --approve-divergence if this is intentional, or fix the adapter styling.`})),L.expect.soft(N,`"${o.id}" differs from the source of truth's golden by ${S} mismatched pixels (threshold ${G}) and hasn't been reviewed — run with --approve-divergence if this is intentional, or fix the adapter styling.`).toBe(!0)}}await K(a,o.id,()=>$)}}}exports.resolveVisualRegressionPlan=me;
|
|
6
6
|
//# sourceMappingURL=testing.cjs.map
|
package/dist/testing.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"testing.cjs","sources":["../src/golden/diffPng.ts","../src/golden/validateManifest.ts","../src/golden/manifestStore.ts","../src/golden/resolveSourceOfTruthGolden.ts","../src/testing/runVisualRegression.ts"],"sourcesContent":["import pixelmatch from \"pixelmatch\";\nimport { PNG } from \"pngjs\";\n\nexport interface PngDiffResult {\n /** Mismatched-pixel count, or `Infinity` if the two images aren't even the\n * same dimensions — pixelmatch itself throws on a size mismatch, and a size\n * mismatch is itself a real difference, not something to swallow. */\n diffPixels: number;\n /** Visual highlight of the mismatched pixels, encoded as a PNG buffer.\n * `null` when `diffPixels` is `Infinity` — there's no pixel-aligned diff to\n * render across two different-sized images. */\n diffImage: Buffer | null;\n}\n\n/** Pixel-diffs two PNG buffers. */\nexport function diffPngBuffers(a: Buffer, b: Buffer): PngDiffResult {\n const imgA = PNG.sync.read(a);\n const imgB = PNG.sync.read(b);\n if (imgA.width !== imgB.width || imgA.height !== imgB.height) {\n return { diffPixels: Infinity, diffImage: null };\n }\n const diff = new PNG({ width: imgA.width, height: imgA.height });\n const diffPixels = pixelmatch(\n imgA.data,\n imgB.data,\n diff.data,\n imgA.width,\n imgA.height,\n { threshold: 0.1 },\n );\n return { diffPixels, diffImage: PNG.sync.write(diff) };\n}\n","import { Ajv } from \"ajv\";\nimport * as ajvFormatsModule from \"ajv-formats\";\nimport type { FormatsPlugin } from \"ajv-formats\";\nimport schema from \"./manifest.schema.json\" with { type: \"json\" };\n\n// See validateFileConfig.ts for why `.default` has to be unwrapped by hand.\nconst addFormats = (ajvFormatsModule as unknown as { default: FormatsPlugin })\n .default;\n\nconst ajv = new Ajv({ allErrors: true, strict: true });\naddFormats(ajv);\nconst validate = ajv.compile(schema);\n\n/**\n * Validates a parsed `test/golden/manifest.json` against `manifest.schema.json`.\n * Throws with every violation listed — callers must not silently coerce or\n * drop invalid entries.\n */\nexport function validateGoldenManifest(data: unknown, path: string): void {\n if (validate(data)) return;\n\n const errors = (validate.errors ?? [])\n .map((error) => {\n const extra = error.params?.additionalProperty\n ? ` '${error.params.additionalProperty}'`\n : \"\";\n return ` - ${error.instancePath || \"root\"} ${error.message}${extra}`;\n })\n .join(\"\\n\");\n throw new Error(`Invalid ${path}:\\n${errors}`);\n}\n","import {\n closeSync,\n existsSync,\n mkdirSync,\n openSync,\n readFileSync,\n renameSync,\n rmSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { join } from \"node:path\";\nimport { validateGoldenManifest } from \"./validateManifest.js\";\n\nexport interface GoldenManifestEntry {\n createdAt: string;\n sourceOfTruthCreatedAt?: string;\n}\n\nexport type GoldenManifest = Record<string, GoldenManifestEntry>;\n\nexport function manifestPath(goldenDir: string): string {\n return join(goldenDir, \"manifest.json\");\n}\n\nfunction manifestLockPath(goldenDir: string): string {\n return join(goldenDir, \"manifest.json.lock\");\n}\n\nexport function goldenImagePath(goldenDir: string, storyId: string): string {\n return join(goldenDir, `${storyId}.png`);\n}\n\n/** Returns `{}` if no manifest exists yet — a fresh adapter with no goldens\n * captured is the normal starting state, not an error. */\nexport function loadManifest(goldenDir: string): GoldenManifest {\n const path = manifestPath(goldenDir);\n if (!existsSync(path)) return {};\n const data = JSON.parse(readFileSync(path, \"utf8\"));\n validateGoldenManifest(data, path);\n return data;\n}\n\n/** Validates before writing, and sorts keys so the diff on a reviewed PR is\n * stable regardless of the order stories happened to run in. Writes to a\n * temp file and renames over the real one — `rename` is atomic, so a\n * concurrent `loadManifest` (running in another Playwright worker) never\n * observes a half-written file. */\nexport function saveManifest(\n goldenDir: string,\n manifest: GoldenManifest,\n): void {\n const path = manifestPath(goldenDir);\n validateGoldenManifest(manifest, path);\n const sorted: GoldenManifest = {};\n for (const key of Object.keys(manifest).sort()) {\n sorted[key] = manifest[key]!;\n }\n mkdirSync(goldenDir, { recursive: true });\n const tmpPath = `${path}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;\n writeFileSync(tmpPath, JSON.stringify(sorted, null, 2) + \"\\n\");\n renameSync(tmpPath, path);\n}\n\nconst LOCK_RETRY_MS = 25;\nconst LOCK_TIMEOUT_MS = 15_000;\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/** Exclusive-create the lock file, spin-retrying until it's free. `wx` fails\n * atomically (`EEXIST`) if another worker process already holds it — that's\n * the only signal we need, no third-party lock library required for a\n * same-machine, same-run lock like this. */\nasync function acquireManifestLock(goldenDir: string): Promise<void> {\n mkdirSync(goldenDir, { recursive: true });\n const path = manifestLockPath(goldenDir);\n const deadline = Date.now() + LOCK_TIMEOUT_MS;\n for (;;) {\n try {\n closeSync(openSync(path, \"wx\"));\n return;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"EEXIST\") throw error;\n if (Date.now() >= deadline) {\n throw new Error(\n `Timed out waiting for the manifest lock at \"${path}\" — delete it if a previous run crashed while holding it.`,\n );\n }\n await sleep(LOCK_RETRY_MS);\n }\n }\n}\n\nfunction releaseManifestLock(goldenDir: string): void {\n rmSync(manifestLockPath(goldenDir), { force: true });\n}\n\n/** Runs `updater` against this story's manifest entry under an exclusive\n * lock on `manifest.json`: reloads the manifest fresh, applies `updater`,\n * and saves it back, all before releasing the lock. Concurrent Playwright\n * workers each own a different story, so this is the only section that\n * needs to serialize — everything else about a story (its screenshot, its\n * golden image file, its diff) is independent of every other story. */\nexport async function updateManifestEntry(\n goldenDir: string,\n storyId: string,\n updater: (\n entry: GoldenManifestEntry | undefined,\n ) => GoldenManifestEntry | undefined,\n): Promise<GoldenManifestEntry | undefined> {\n await acquireManifestLock(goldenDir);\n try {\n const manifest = loadManifest(goldenDir);\n const nextEntry = updater(manifest[storyId]);\n if (nextEntry === undefined) {\n delete manifest[storyId];\n } else {\n manifest[storyId] = nextEntry;\n }\n saveManifest(goldenDir, manifest);\n return nextEntry;\n } finally {\n releaseManifestLock(goldenDir);\n }\n}\n\nexport function saveGoldenImage(\n goldenDir: string,\n storyId: string,\n buffer: Buffer,\n): void {\n mkdirSync(goldenDir, { recursive: true });\n writeFileSync(goldenImagePath(goldenDir, storyId), buffer);\n}\n\n/** Removes the golden `.png` + manifest entry for every story id in the\n * manifest that isn't in `currentStoryIds` (e.g. a story renamed or deleted\n * from Storybook) — otherwise those never get cleaned up on their own,\n * since a run only ever adds/updates entries for stories it actually saw.\n * Returns the pruned ids, for the caller to report. Both the file removal\n * and the manifest delete are idempotent, so it's safe for this to run\n * redundantly from more than one Playwright worker. */\nexport async function pruneOrphanedGoldens(\n goldenDir: string,\n currentStoryIds: ReadonlySet<string>,\n): Promise<string[]> {\n const manifest = loadManifest(goldenDir);\n const orphanIds = Object.keys(manifest).filter(\n (id) => !currentStoryIds.has(id),\n );\n for (const id of orphanIds) {\n const imagePath = goldenImagePath(goldenDir, id);\n if (existsSync(imagePath)) unlinkSync(imagePath);\n await updateManifestEntry(goldenDir, id, () => undefined);\n }\n return orphanIds;\n}\n","import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { SourceOfTruthGoldenLocation } from \"../config.js\";\nimport {\n goldenImagePath,\n loadManifest,\n manifestPath,\n type GoldenManifest,\n} from \"./manifestStore.js\";\nimport { validateGoldenManifest } from \"./validateManifest.js\";\n\n// The source-of-truth adapter (Mantine) lives in its own standalone repo, not\n// this monorepo — its golden images are fetched from here, not from borderux/recursica.\nconst GITHUB_REPO = \"borderux/recursica-adapter-mantine-v8\";\n\nexport interface SourceOfTruthGolden {\n manifest: GoldenManifest;\n /** Returns the golden PNG bytes for a story, or `null` if the source of\n * truth has no golden captured for it yet. */\n readImage(storyId: string): Promise<Buffer | null>;\n}\n\nasync function resolveNpmVersion(\n packageName: string,\n versionSpec: string,\n): Promise<string> {\n const response = await fetch(`https://registry.npmjs.org/${packageName}`);\n if (!response.ok) {\n throw new Error(\n `Could not reach npm registry for ${packageName}: ${response.statusText}`,\n );\n }\n const data = (await response.json()) as {\n \"dist-tags\"?: Record<string, string>;\n versions?: Record<string, unknown>;\n };\n const resolved =\n data[\"dist-tags\"]?.[versionSpec] ??\n (data.versions?.[versionSpec] ? versionSpec : undefined);\n if (!resolved) {\n throw new Error(\n `${packageName} has no version or dist-tag \"${versionSpec}\" on the npm registry.`,\n );\n }\n return resolved;\n}\n\n/**\n * Resolves the source-of-truth adapter's golden images for the divergence\n * check. Never boots a Storybook — both location types resolve to plain\n * files, fetched once and cached, not re-diffed per pixel over the wire.\n *\n * `location.type === \"local\"`: a sibling package already checked out (this\n * monorepo's own `sourceOfTruth.type: \"url\"` mode) — read its\n * `test/golden/` directly, including any uncommitted local changes.\n *\n * `location.type === \"npm\"`: no local checkout (the default, standalone-repo\n * mode) — resolve the installed version against the npm registry, then fetch\n * that exact version's `test/golden/` from the public GitHub repo at the\n * matching release tag (changesets tags every release as\n * `<packageName>@<version>`), caching what's downloaded under `cacheDir`.\n *\n * Throws when no golden baseline exists yet for this version, or the\n * registry/repo is unreachable — a divergence check that can't reach its\n * baseline must fail loudly, not degrade to a silent skip that Playwright\n * then reports as a pass.\n */\nexport async function resolveSourceOfTruthGolden(\n location: SourceOfTruthGoldenLocation,\n): Promise<SourceOfTruthGolden> {\n if (location.type === \"local\") {\n if (!existsSync(manifestPath(location.dir))) {\n throw new Error(\n `No golden baseline found at ${location.dir} — the source-of-truth divergence check has nothing to compare against. Capture one there first (--update-golden), or fix sourceOfTruth.dir if it's pointing at the wrong checkout.`,\n );\n }\n const manifest = loadManifest(location.dir);\n return {\n manifest,\n async readImage(storyId) {\n const path = goldenImagePath(location.dir, storyId);\n return existsSync(path) ? readFileSync(path) : null;\n },\n };\n }\n\n let version: string;\n try {\n version = await resolveNpmVersion(\n location.packageName,\n location.versionSpec,\n );\n } catch (error) {\n throw new Error(\n `Could not resolve ${location.packageName}@${location.versionSpec} on the npm registry — the source-of-truth divergence check has nothing to compare against.`,\n { cause: error },\n );\n }\n\n const cacheDir = join(location.cacheDir, version);\n const tag = `${location.packageName}@${version}`;\n // @recursica/adapter-mantine-v8 is a standalone single-package repo (unlike\n // the old @recursica/mantine-adapter, which lived at `packages/<name>`\n // inside this monorepo) — its `test/golden/` sits directly at the repo root.\n const rawBase = `https://raw.githubusercontent.com/${GITHUB_REPO}/${tag}/test/golden`;\n\n let manifest: GoldenManifest;\n const cachedManifestPath = manifestPath(cacheDir);\n if (existsSync(cachedManifestPath)) {\n manifest = loadManifest(cacheDir);\n } else {\n let response: Response;\n try {\n response = await fetch(`${rawBase}/manifest.json`);\n } catch (error) {\n throw new Error(\n `Could not reach GitHub to fetch ${tag}'s golden baseline (${rawBase}/manifest.json) — the source-of-truth divergence check has nothing to compare against.`,\n { cause: error },\n );\n }\n if (!response.ok) {\n throw new Error(\n `No golden baseline published for tag \"${tag}\" in ${GITHUB_REPO} (${rawBase}/manifest.json returned ${response.status}) — the source-of-truth divergence check has nothing to compare against. Confirm that tag exists and its release actually published test/golden/.`,\n );\n }\n const text = await response.text();\n const parsed = JSON.parse(text);\n validateGoldenManifest(parsed, `${rawBase}/manifest.json`);\n mkdirSync(cacheDir, { recursive: true });\n writeFileSync(cachedManifestPath, text);\n manifest = parsed;\n }\n\n return {\n manifest,\n async readImage(storyId) {\n const cachedImagePath = goldenImagePath(cacheDir, storyId);\n if (existsSync(cachedImagePath)) return readFileSync(cachedImagePath);\n const response = await fetch(`${rawBase}/${storyId}.png`);\n if (!response.ok) return null;\n const buffer = Buffer.from(await response.arrayBuffer());\n mkdirSync(cacheDir, { recursive: true });\n writeFileSync(cachedImagePath, buffer);\n return buffer;\n },\n };\n}\n","import { expect } from \"@playwright/test\";\nimport type { Browser, TestInfo } from \"@playwright/test\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport type { AdapterTesterConfig } from \"../config.js\";\nimport { diffPngBuffers } from \"../golden/diffPng.js\";\nimport {\n type GoldenManifestEntry,\n goldenImagePath,\n loadManifest,\n pruneOrphanedGoldens,\n saveGoldenImage,\n updateManifestEntry,\n} from \"../golden/manifestStore.js\";\nimport { resolveSourceOfTruthGolden } from \"../golden/resolveSourceOfTruthGolden.js\";\n\nconst DEFAULT_EXCLUDE_TITLE_PREFIXES = [\"Theme\", \"Tokens\", \"Introduction\"];\n\ninterface StorybookEntry {\n type: string;\n id: string;\n name: string;\n title: string;\n}\n\nfunction matchesPrefix(id: string, prefix: string): boolean {\n return id === prefix || id.startsWith(prefix);\n}\n\n/** Fetches every story `target`'s Storybook currently has, filtered only by\n * `excludeTitlePrefixes` — not `stories.<id>.exclude`, so callers can still\n * tell an excluded story apart from one that's genuinely missing. */\nasync function fetchStories(\n target: { name: string; url: string },\n excludeTitlePrefixes: string[],\n): Promise<StorybookEntry[]> {\n let stories: StorybookEntry[];\n try {\n const response = await fetch(`${target.url}/index.json`);\n if (!response.ok) {\n throw new Error(\n `Failed to fetch Storybook index: ${response.statusText}`,\n );\n }\n const data = (await response.json()) as any;\n const entries = data.entries || {};\n stories = Object.values(entries).filter(\n (entry: any) =>\n entry.type === \"story\" &&\n !excludeTitlePrefixes.some(\n (prefix) =>\n entry.title === prefix || entry.title.startsWith(`${prefix}/`),\n ),\n ) as StorybookEntry[];\n stories.sort((a, b) => a.id.localeCompare(b.id));\n } catch (error) {\n console.error(\n \"Failed to load Storybook index from\",\n `${target.url}/index.json`,\n error,\n );\n throw new Error(\n `Storybook target \"${target.name}\" is not responsive or index.json is missing. Please ensure its Storybook is running.`,\n );\n }\n return stories;\n}\n\n/** Resolves the diff threshold for `storyId`: the longest (most specific)\n * `storyThresholds` key matching by prefix, falling back to\n * `defaultThresholdPixels` when nothing matches. */\nfunction resolveThreshold(\n storyId: string,\n storyThresholds: Record<string, number>,\n defaultThresholdPixels: number,\n): number {\n let bestMatch: string | undefined;\n for (const prefix of Object.keys(storyThresholds)) {\n if (\n matchesPrefix(storyId, prefix) &&\n (!bestMatch || prefix.length > bestMatch.length)\n ) {\n bestMatch = prefix;\n }\n }\n return bestMatch !== undefined\n ? storyThresholds[bestMatch]!\n : defaultThresholdPixels;\n}\n\n/** Everything a generated Playwright spec needs to register the golden-image\n * suite itself. Split out from the actual `test.describe`/`test` calls so\n * those calls execute in the spec file that imports this, not in this\n * library file — otherwise Playwright's HTML report groups every story under\n * this file's own (sourcemapped) path instead of a stable spec name. */\nexport interface VisualRegressionPlan {\n /** `config`'s own (non-source-of-truth) target name, for the suite title. */\n ownTargetName: string;\n /** Suite title suffix describing which check mode is running. */\n suiteLabel: string;\n /** Stories to check, already filtered and sorted by id. */\n stories: StorybookEntry[];\n /** Story ids the source-of-truth adapter has a golden for but this\n * project's own Storybook doesn't — empty outside `checkMode: \"divergence\"`\n * or when `sourceOfTruthGolden` didn't resolve. Excludes ids covered by a\n * `stories.<id>.exclude` entry: an intentional gap, not a sync failure. */\n missingFromSourceOfTruth: string[];\n /** Golden-checks one story. Call this from inside a `test(story.id, ...)`\n * body — safe to run concurrently across Playwright workers, since each\n * call only ever reads/writes its own story's manifest entry (locked at\n * the point it writes it back, so concurrent workers never race each\n * other's entries — see `updateManifestEntry`). */\n checkStory: (\n story: StorybookEntry,\n browser: Browser,\n testInfo: TestInfo,\n ) => Promise<void>;\n}\n\n/** Everything a generated Playwright spec needs to register the golden-image\n * suite itself. Split out from the actual `test.describe`/`test` calls so\n * those calls execute in the spec file that imports this, not in this\n * library file — otherwise Playwright's HTML report groups every story under\n * this file's own (sourcemapped) path instead of a stable spec name. */\nexport interface VisualRegressionPlan {\n /** `config`'s own (non-source-of-truth) target name, for the suite title. */\n ownTargetName: string;\n /** Suite title suffix describing which check mode is running. */\n suiteLabel: string;\n /** Stories to check, already filtered and sorted by id. */\n stories: StorybookEntry[];\n /** Golden-checks one story. Call this from inside a `test(story.id, ...)`\n * body — safe to run concurrently across Playwright workers, since each\n * call only ever reads/writes its own story's manifest entry (locked at\n * the point it writes it back, so concurrent workers never race each\n * other's entries — see `updateManifestEntry`). */\n checkStory: (\n story: StorybookEntry,\n browser: Browser,\n testInfo: TestInfo,\n ) => Promise<void>;\n}\n\n/**\n * Resolves the golden-image plan for `config`'s own target (the one target\n * in `config.targets` not marked `sourceOfTruth`).\n *\n * Two independent checks per story, gated by `config.checkMode`. Neither\n * boots the source-of-truth adapter's own Storybook — its side of both\n * checks is always a stored golden file, never a live page:\n *\n * 1. **Own-drift (`checkMode: \"own\"`, the default; hard fail):** this run's\n * live render vs this project's own stored `test/golden/<story-id>.png`.\n * No golden yet for a story is not a failure — one is captured from this\n * run instead (same as `--update-golden`, scoped to just that story), in\n * either mode.\n * 2. **Source-of-truth divergence (`checkMode: \"divergence\"`; hard fail):**\n * this run's live render vs the source-of-truth's stored golden (`config`'s\n * `sourceOfTruthGolden`) — always fresh, no `--update-golden` step needed\n * first. Skipped entirely when `config.isSourceOfTruthAdapter` is true —\n * the source-of-truth adapter has nothing above it to diverge from — and\n * skipped per-story when the source of truth has no baseline for it yet.\n * A once-flagged divergence stays quiet after `--approve-divergence`,\n * until the source of truth's own golden changes again.\n */\nexport async function resolveVisualRegressionPlan(\n config: AdapterTesterConfig,\n): Promise<VisualRegressionPlan> {\n const ownTarget = config.isSourceOfTruthAdapter\n ? config.targets[0]\n : config.targets.find((target) => !target.sourceOfTruth);\n if (!ownTarget) {\n throw new Error(\n \"adapter-tester config has no non-sourceOfTruth target to run the golden check against.\",\n );\n }\n const excludeTitlePrefixes =\n config.excludeTitlePrefixes ?? DEFAULT_EXCLUDE_TITLE_PREFIXES;\n const storyOverrides = config.stories ?? {};\n const excludeStoryIds = Object.keys(storyOverrides).filter(\n (id) => storyOverrides[id]!.exclude,\n );\n const goldenStoryThresholds = Object.fromEntries(\n Object.entries(storyOverrides)\n .filter(([, override]) => override.goldenThreshold !== undefined)\n .map(([id, override]) => [id, override.goldenThreshold!]),\n );\n const sourceOfTruthStoryThresholds = Object.fromEntries(\n Object.entries(storyOverrides)\n .filter(([, override]) => override.sourceOfTruthThreshold !== undefined)\n .map(([id, override]) => [id, override.sourceOfTruthThreshold!]),\n );\n const goldenDir = config.goldenDir;\n const goldenMode = config.goldenMode;\n const checkMode = config.checkMode;\n\n // Fetched with only excludeTitlePrefixes applied — not excludeStoryIds —\n // so the source-of-truth story-parity check below can tell an excluded\n // story apart from one that's genuinely missing from this Storybook.\n const ownStories = await fetchStories(ownTarget, excludeTitlePrefixes);\n const stories = ownStories.filter(\n (entry) =>\n !excludeStoryIds.some((prefix) => matchesPrefix(entry.id, prefix)),\n );\n\n // `--update-golden` redefines this project's own baseline, so it's also\n // the point a renamed/removed story's now-orphaned golden gets cleaned up\n // — otherwise nothing ever prunes it, since a run only ever adds/updates\n // entries for stories it actually saw in this pass. Uses the full current\n // story list (not narrowed by any `--grep` Playwright itself applies), so\n // this catches every orphan regardless of how the run is scoped.\n if (goldenMode === \"update-golden\") {\n const prunedStoryIds = await pruneOrphanedGoldens(\n goldenDir,\n new Set(stories.map((story) => story.id)),\n );\n if (prunedStoryIds.length > 0) {\n console.warn(\n `Pruned ${prunedStoryIds.length} orphaned golden(s) no longer in Storybook: ${prunedStoryIds.join(\", \")}`,\n );\n }\n }\n\n const sourceOfTruthGolden =\n checkMode !== \"divergence\" ||\n config.isSourceOfTruthAdapter ||\n !config.sourceOfTruthGolden\n ? null\n : await resolveSourceOfTruthGolden(config.sourceOfTruthGolden);\n\n // Checked against `ownStories` (title-prefix-excluded only), not `stories`\n // — a story marked `exclude: true` still counts as \"present\", it's just\n // not diffed. Only a story the source of truth has that this adapter\n // never built at all, and hasn't acknowledged via `exclude`, is missing.\n const ownStoryIds = new Set(ownStories.map((entry) => entry.id));\n const missingFromSourceOfTruth = sourceOfTruthGolden\n ? Object.keys(sourceOfTruthGolden.manifest)\n .filter(\n (id) =>\n !ownStoryIds.has(id) &&\n !excludeStoryIds.some((prefix) => matchesPrefix(id, prefix)),\n )\n .sort()\n : [];\n\n if (missingFromSourceOfTruth.length > 0) {\n console.error(\n `[adapter-tester] ${missingFromSourceOfTruth.length} stor(y/ies) exist in the source of truth but are missing here: ${missingFromSourceOfTruth.join(\", \")}. Add the missing story, or mark it \\`exclude: true\\` under \\`stories\\` in adapter-tester.config.json if intentional.`,\n );\n }\n\n console.log(\n [\n `[adapter-tester] target: \"${ownTarget.name}\" (${ownTarget.url})`,\n `[adapter-tester] checkMode: \"${checkMode}\" (${checkMode === \"divergence\" ? \"live render vs source-of-truth's golden\" : \"live render vs this project's own golden\"})`,\n `[adapter-tester] goldenMode: \"${goldenMode}\"`,\n `[adapter-tester] goldenThresholdPixels: ${config.goldenThresholdPixels}`,\n `[adapter-tester] sourceOfTruthThresholdPixels: ${config.sourceOfTruthThresholdPixels}`,\n checkMode === \"divergence\"\n ? config.isSourceOfTruthAdapter\n ? `[adapter-tester] sourceOfTruthGolden: skipped — this is the source-of-truth adapter, nothing to diverge from`\n : !config.sourceOfTruthGolden\n ? `[adapter-tester] sourceOfTruthGolden: skipped — no sourceOfTruthGolden configured`\n : // Unresolvable-baseline case never reaches here — resolveSourceOfTruthGolden\n // throws instead of returning null, failing the whole run before this\n // logs, rather than letting the divergence check silently no-op.\n `[adapter-tester] sourceOfTruthGolden: resolved, ${Object.keys(sourceOfTruthGolden!.manifest).length} golden(s) available (config: ${JSON.stringify(config.sourceOfTruthGolden)})`\n : `[adapter-tester] sourceOfTruthGolden: not used in \"own\" checkMode`,\n `[adapter-tester] stories: ${stories.length} to check (excluded: ${excludeStoryIds.length}, title prefixes excluded: ${excludeTitlePrefixes.join(\", \") || \"none\"})`,\n `[adapter-tester] story parity with source of truth: ${missingFromSourceOfTruth.length === 0 ? \"OK\" : `${missingFromSourceOfTruth.length} missing (see error above)`}`,\n ].join(\"\\n\"),\n );\n\n const suiteLabel =\n checkMode === \"divergence\"\n ? \"Source-of-Truth Divergence Check\"\n : \"Own-Drift Golden Image Check\";\n\n return {\n ownTargetName: ownTarget.name,\n suiteLabel,\n stories,\n missingFromSourceOfTruth,\n checkStory: async (story, browser, testInfo) => {\n const page = await browser.newPage();\n await page.setViewportSize({ width: 800, height: 600 });\n await page.goto(\n `${ownTarget.url}/iframe.html?id=${story.id}&viewMode=story`,\n { waitUntil: \"networkidle\" },\n );\n await page.waitForSelector(\"#storybook-root\");\n await page.addStyleTag({\n content: `* { -webkit-font-smoothing: antialiased !important; -moz-osx-font-smoothing: grayscale !important; }`,\n });\n // Web fonts (e.g. `withRecursicaFonts`'s Google Fonts `<link>`s, injected\n // from a React effect after this page's `networkidle` already fired) can\n // still be mid-download here. Wait for any `<link>` stylesheet that's\n // still loading to settle — so the browser has parsed its `@font-face`\n // rules and started the actual font-file fetches `document.fonts.ready`\n // below needs to know about — then for the fonts themselves. Without\n // this, the very first golden capture of a newly-introduced font family\n // is a coin flip between the real font and its fallback, depending on\n // how fast the network happens to be.\n await page.evaluate(() =>\n Promise.all(\n Array.from(\n document.querySelectorAll<HTMLLinkElement>(\n 'link[rel=\"stylesheet\"]',\n ),\n ).map((link) =>\n link.sheet\n ? Promise.resolve()\n : new Promise<void>((resolve) => {\n link.addEventListener(\"load\", () => resolve(), {\n once: true,\n });\n link.addEventListener(\"error\", () => resolve(), {\n once: true,\n });\n }),\n ),\n ).then(() => document.fonts.ready),\n );\n await page.waitForTimeout(300);\n const liveBuffer = await page.screenshot();\n\n const imagePath = goldenImagePath(goldenDir, story.id);\n // Only this worker ever touches this story's key, so reading it here\n // (outside the lock `updateManifestEntry` takes at the end) can't\n // race another worker — they're all reading/writing different keys.\n const entry = loadManifest(goldenDir)[story.id];\n const capturingNewGolden =\n goldenMode !== \"check\" || !entry || !existsSync(imagePath);\n\n let currentEntry: GoldenManifestEntry;\n if (capturingNewGolden) {\n saveGoldenImage(goldenDir, story.id, liveBuffer);\n currentEntry = entry?.sourceOfTruthCreatedAt\n ? {\n createdAt: new Date().toISOString(),\n sourceOfTruthCreatedAt: entry.sourceOfTruthCreatedAt,\n }\n : { createdAt: new Date().toISOString() };\n if (!entry) {\n testInfo.annotations.push({\n type: \"golden-created\",\n description: `No golden existed yet for \"${story.id}\" — captured one from this run.`,\n });\n }\n } else {\n currentEntry = entry;\n if (checkMode === \"own\") {\n const goldenBuffer = readFileSync(imagePath);\n const { diffPixels, diffImage } = diffPngBuffers(\n liveBuffer,\n goldenBuffer,\n );\n const threshold = resolveThreshold(\n story.id,\n goldenStoryThresholds,\n config.goldenThresholdPixels,\n );\n if (diffPixels >= threshold) {\n await testInfo.attach(\"expected\", {\n body: goldenBuffer,\n contentType: \"image/png\",\n });\n await testInfo.attach(\"actual\", {\n body: liveBuffer,\n contentType: \"image/png\",\n });\n if (diffImage) {\n await testInfo.attach(\"diff\", {\n body: diffImage,\n contentType: \"image/png\",\n });\n }\n }\n expect\n .soft(\n diffPixels,\n `\"${story.id}\" has drifted from its own golden image (${diffPixels} mismatched pixels, threshold ${threshold})`,\n )\n .toBeLessThan(threshold);\n }\n }\n\n if (sourceOfTruthGolden) {\n const sourceOfTruthEntry = sourceOfTruthGolden.manifest[story.id];\n const sourceOfTruthImage = sourceOfTruthEntry\n ? await sourceOfTruthGolden.readImage(story.id)\n : null;\n\n if (sourceOfTruthEntry && sourceOfTruthImage) {\n if (goldenMode === \"approve-divergence\") {\n currentEntry = {\n ...currentEntry,\n sourceOfTruthCreatedAt: sourceOfTruthEntry.createdAt,\n };\n } else {\n // Always this run's live render, never the stored own-drift\n // golden — divergence should reflect what's on screen right now,\n // not whatever was last captured via --update-golden.\n const { diffPixels, diffImage } = diffPngBuffers(\n liveBuffer,\n sourceOfTruthImage,\n );\n const threshold = resolveThreshold(\n story.id,\n sourceOfTruthStoryThresholds,\n config.sourceOfTruthThresholdPixels,\n );\n const approvedAt = currentEntry.sourceOfTruthCreatedAt;\n const isKnownDivergence =\n diffPixels < threshold ||\n (approvedAt !== undefined &&\n approvedAt >= sourceOfTruthEntry.createdAt);\n if (!isKnownDivergence) {\n await testInfo.attach(\"expected\", {\n body: sourceOfTruthImage,\n contentType: \"image/png\",\n });\n await testInfo.attach(\"actual\", {\n body: liveBuffer,\n contentType: \"image/png\",\n });\n if (diffImage) {\n await testInfo.attach(\"diff\", {\n body: diffImage,\n contentType: \"image/png\",\n });\n }\n testInfo.annotations.push({\n type: \"source-of-truth-divergence\",\n description: `\"${story.id}\" differs from the source of truth's golden by ${diffPixels} mismatched pixels (threshold ${threshold}) and hasn't been reviewed — run with --approve-divergence if this is intentional, or fix the adapter styling.`,\n });\n }\n expect\n .soft(\n isKnownDivergence,\n `\"${story.id}\" differs from the source of truth's golden by ${diffPixels} mismatched pixels (threshold ${threshold}) and hasn't been reviewed — run with --approve-divergence if this is intentional, or fix the adapter styling.`,\n )\n .toBe(true);\n }\n }\n }\n\n // Locked read-modify-write of just this story's entry — see\n // `updateManifestEntry` for why that's enough to make this safe\n // across concurrent Playwright workers.\n await updateManifestEntry(goldenDir, story.id, () => currentEntry);\n },\n };\n}\n"],"names":["diffPngBuffers","a","b","imgA","PNG","imgB","diff","pixelmatch","addFormats","ajvFormatsModule.default","ajv","Ajv","validate","schema","validateGoldenManifest","data","path","errors","error","extra","_a","manifestPath","goldenDir","join","manifestLockPath","goldenImagePath","storyId","loadManifest","existsSync","readFileSync","saveManifest","manifest","sorted","key","mkdirSync","tmpPath","writeFileSync","renameSync","LOCK_RETRY_MS","LOCK_TIMEOUT_MS","sleep","ms","resolve","acquireManifestLock","deadline","closeSync","openSync","releaseManifestLock","rmSync","updateManifestEntry","updater","nextEntry","saveGoldenImage","buffer","pruneOrphanedGoldens","currentStoryIds","orphanIds","id","imagePath","unlinkSync","GITHUB_REPO","resolveNpmVersion","packageName","versionSpec","response","resolved","_b","resolveSourceOfTruthGolden","location","version","cacheDir","tag","rawBase","cachedManifestPath","text","parsed","cachedImagePath","DEFAULT_EXCLUDE_TITLE_PREFIXES","matchesPrefix","prefix","fetchStories","target","excludeTitlePrefixes","stories","entries","entry","resolveThreshold","storyThresholds","defaultThresholdPixels","bestMatch","resolveVisualRegressionPlan","config","ownTarget","storyOverrides","excludeStoryIds","goldenStoryThresholds","override","sourceOfTruthStoryThresholds","goldenMode","checkMode","ownStories","prunedStoryIds","story","sourceOfTruthGolden","ownStoryIds","missingFromSourceOfTruth","suiteLabel","browser","testInfo","page","link","liveBuffer","capturingNewGolden","currentEntry","goldenBuffer","diffPixels","diffImage","threshold","expect","sourceOfTruthEntry","sourceOfTruthImage","approvedAt","isKnownDivergence"],"mappings":"6OAeO,SAASA,EAAeC,EAAWC,EAA0B,CAClE,MAAMC,EAAOC,EAAAA,IAAI,KAAK,KAAKH,CAAC,EACtBI,EAAOD,EAAAA,IAAI,KAAK,KAAKF,CAAC,EAC5B,GAAIC,EAAK,QAAUE,EAAK,OAASF,EAAK,SA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,EAAa,uBAC1BS,EACJP,EAAaE,GACZI,IAAe,QACdA,GAAcF,EAAmB,UAChCG,IACH,MAAMd,EAAS,OAAO,WAAY,CAChC,KAAMY,EACN,YAAa,WAAA,CACd,EACD,MAAMZ,EAAS,OAAO,SAAU,CAC9B,KAAMG,EACN,YAAa,WAAA,CACd,EACGK,GACF,MAAMR,EAAS,OAAO,OAAQ,CAC5B,KAAMQ,EACN,YAAa,WAAA,CACd,EAEHR,EAAS,YAAY,KAAK,CACxB,KAAM,6BACN,YAAa,IAAIN,EAAM,EAAE,kDAAkDa,CAAU,iCAAiCE,CAAS,gHAAA,CAChI,GAEHC,EAAAA,OACG,KACCI,EACA,IAAIpB,EAAM,EAAE,kDAAkDa,CAAU,iCAAiCE,CAAS,gHAAA,EAEnH,KAAK,EAAI,CACd,CAEJ,CAKA,MAAMpE,EAAoB3B,EAAWgF,EAAM,GAAI,IAAMW,CAAY,CACnE,CAAA,CAEJ"}
|
|
1
|
+
{"version":3,"file":"testing.cjs","sources":["../src/golden/diffPng.ts","../src/golden/validateManifest.ts","../src/golden/manifestStore.ts","../src/golden/resolveSourceOfTruthGolden.ts","../src/testing/runVisualRegression.ts"],"sourcesContent":["import pixelmatch from \"pixelmatch\";\nimport { PNG } from \"pngjs\";\n\nexport interface PngDiffResult {\n /** Mismatched-pixel count, or `Infinity` if the two images aren't even the\n * same dimensions — pixelmatch itself throws on a size mismatch, and a size\n * mismatch is itself a real difference, not something to swallow. */\n diffPixels: number;\n /** Visual highlight of the mismatched pixels, encoded as a PNG buffer.\n * `null` when `diffPixels` is `Infinity` — there's no pixel-aligned diff to\n * render across two different-sized images. */\n diffImage: Buffer | null;\n}\n\n/** Pixel-diffs two PNG buffers. */\nexport function diffPngBuffers(a: Buffer, b: Buffer): PngDiffResult {\n const imgA = PNG.sync.read(a);\n const imgB = PNG.sync.read(b);\n if (imgA.width !== imgB.width || imgA.height !== imgB.height) {\n return { diffPixels: Infinity, diffImage: null };\n }\n const diff = new PNG({ width: imgA.width, height: imgA.height });\n const diffPixels = pixelmatch(\n imgA.data,\n imgB.data,\n diff.data,\n imgA.width,\n imgA.height,\n { threshold: 0.1 },\n );\n return { diffPixels, diffImage: PNG.sync.write(diff) };\n}\n","import { Ajv } from \"ajv\";\nimport * as ajvFormatsModule from \"ajv-formats\";\nimport type { FormatsPlugin } from \"ajv-formats\";\nimport schema from \"./manifest.schema.json\" with { type: \"json\" };\n\n// See validateFileConfig.ts for why `.default` has to be unwrapped by hand.\nconst addFormats = (ajvFormatsModule as unknown as { default: FormatsPlugin })\n .default;\n\nconst ajv = new Ajv({ allErrors: true, strict: true });\naddFormats(ajv);\nconst validate = ajv.compile(schema);\n\n/**\n * Validates a parsed `test/golden/manifest.json` against `manifest.schema.json`.\n * Throws with every violation listed — callers must not silently coerce or\n * drop invalid entries.\n */\nexport function validateGoldenManifest(data: unknown, path: string): void {\n if (validate(data)) return;\n\n const errors = (validate.errors ?? [])\n .map((error) => {\n const extra = error.params?.additionalProperty\n ? ` '${error.params.additionalProperty}'`\n : \"\";\n return ` - ${error.instancePath || \"root\"} ${error.message}${extra}`;\n })\n .join(\"\\n\");\n throw new Error(`Invalid ${path}:\\n${errors}`);\n}\n","import {\n closeSync,\n existsSync,\n mkdirSync,\n openSync,\n readFileSync,\n renameSync,\n rmSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { join } from \"node:path\";\nimport { validateGoldenManifest } from \"./validateManifest.js\";\n\nexport interface GoldenManifestEntry {\n createdAt: string;\n sourceOfTruthCreatedAt?: string;\n}\n\nexport type GoldenManifest = Record<string, GoldenManifestEntry>;\n\nexport function manifestPath(goldenDir: string): string {\n return join(goldenDir, \"manifest.json\");\n}\n\nfunction manifestLockPath(goldenDir: string): string {\n return join(goldenDir, \"manifest.json.lock\");\n}\n\nexport function goldenImagePath(goldenDir: string, storyId: string): string {\n return join(goldenDir, `${storyId}.png`);\n}\n\n/** Returns `{}` if no manifest exists yet — a fresh adapter with no goldens\n * captured is the normal starting state, not an error. */\nexport function loadManifest(goldenDir: string): GoldenManifest {\n const path = manifestPath(goldenDir);\n if (!existsSync(path)) return {};\n const data = JSON.parse(readFileSync(path, \"utf8\"));\n validateGoldenManifest(data, path);\n return data;\n}\n\n/** Validates before writing, and sorts keys so the diff on a reviewed PR is\n * stable regardless of the order stories happened to run in. Writes to a\n * temp file and renames over the real one — `rename` is atomic, so a\n * concurrent `loadManifest` (running in another Playwright worker) never\n * observes a half-written file. */\nexport function saveManifest(\n goldenDir: string,\n manifest: GoldenManifest,\n): void {\n const path = manifestPath(goldenDir);\n validateGoldenManifest(manifest, path);\n const sorted: GoldenManifest = {};\n for (const key of Object.keys(manifest).sort()) {\n sorted[key] = manifest[key]!;\n }\n mkdirSync(goldenDir, { recursive: true });\n const tmpPath = `${path}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;\n writeFileSync(tmpPath, JSON.stringify(sorted, null, 2) + \"\\n\");\n renameSync(tmpPath, path);\n}\n\nconst LOCK_RETRY_MS = 25;\nconst LOCK_TIMEOUT_MS = 15_000;\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/** Exclusive-create the lock file, spin-retrying until it's free. `wx` fails\n * atomically (`EEXIST`) if another worker process already holds it — that's\n * the only signal we need, no third-party lock library required for a\n * same-machine, same-run lock like this. */\nasync function acquireManifestLock(goldenDir: string): Promise<void> {\n mkdirSync(goldenDir, { recursive: true });\n const path = manifestLockPath(goldenDir);\n const deadline = Date.now() + LOCK_TIMEOUT_MS;\n for (;;) {\n try {\n closeSync(openSync(path, \"wx\"));\n return;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"EEXIST\") throw error;\n if (Date.now() >= deadline) {\n throw new Error(\n `Timed out waiting for the manifest lock at \"${path}\" — delete it if a previous run crashed while holding it.`,\n );\n }\n await sleep(LOCK_RETRY_MS);\n }\n }\n}\n\nfunction releaseManifestLock(goldenDir: string): void {\n rmSync(manifestLockPath(goldenDir), { force: true });\n}\n\n/** Runs `updater` against this story's manifest entry under an exclusive\n * lock on `manifest.json`: reloads the manifest fresh, applies `updater`,\n * and saves it back, all before releasing the lock. Concurrent Playwright\n * workers each own a different story, so this is the only section that\n * needs to serialize — everything else about a story (its screenshot, its\n * golden image file, its diff) is independent of every other story. */\nexport async function updateManifestEntry(\n goldenDir: string,\n storyId: string,\n updater: (\n entry: GoldenManifestEntry | undefined,\n ) => GoldenManifestEntry | undefined,\n): Promise<GoldenManifestEntry | undefined> {\n await acquireManifestLock(goldenDir);\n try {\n const manifest = loadManifest(goldenDir);\n const nextEntry = updater(manifest[storyId]);\n if (nextEntry === undefined) {\n delete manifest[storyId];\n } else {\n manifest[storyId] = nextEntry;\n }\n saveManifest(goldenDir, manifest);\n return nextEntry;\n } finally {\n releaseManifestLock(goldenDir);\n }\n}\n\nexport function saveGoldenImage(\n goldenDir: string,\n storyId: string,\n buffer: Buffer,\n): void {\n mkdirSync(goldenDir, { recursive: true });\n writeFileSync(goldenImagePath(goldenDir, storyId), buffer);\n}\n\n/** Removes the golden `.png` + manifest entry for every story id in the\n * manifest that isn't in `currentStoryIds` (e.g. a story renamed or deleted\n * from Storybook) — otherwise those never get cleaned up on their own,\n * since a run only ever adds/updates entries for stories it actually saw.\n * Returns the pruned ids, for the caller to report. Both the file removal\n * and the manifest delete are idempotent, so it's safe for this to run\n * redundantly from more than one Playwright worker. */\nexport async function pruneOrphanedGoldens(\n goldenDir: string,\n currentStoryIds: ReadonlySet<string>,\n): Promise<string[]> {\n const manifest = loadManifest(goldenDir);\n const orphanIds = Object.keys(manifest).filter(\n (id) => !currentStoryIds.has(id),\n );\n for (const id of orphanIds) {\n const imagePath = goldenImagePath(goldenDir, id);\n if (existsSync(imagePath)) unlinkSync(imagePath);\n await updateManifestEntry(goldenDir, id, () => undefined);\n }\n return orphanIds;\n}\n","import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { SourceOfTruthGoldenLocation } from \"../config.js\";\nimport {\n goldenImagePath,\n loadManifest,\n manifestPath,\n type GoldenManifest,\n} from \"./manifestStore.js\";\nimport { validateGoldenManifest } from \"./validateManifest.js\";\n\n// The source-of-truth adapter (Mantine) lives in its own standalone repo, not\n// this monorepo — its golden images are fetched from here, not from borderux/recursica.\nconst GITHUB_REPO = \"borderux/recursica-adapter-mantine-v8\";\n\nexport interface SourceOfTruthGolden {\n manifest: GoldenManifest;\n /** Returns the golden PNG bytes for a story, or `null` if the source of\n * truth has no golden captured for it yet. */\n readImage(storyId: string): Promise<Buffer | null>;\n}\n\nasync function resolveNpmVersion(\n packageName: string,\n versionSpec: string,\n): Promise<string> {\n const response = await fetch(`https://registry.npmjs.org/${packageName}`);\n if (!response.ok) {\n throw new Error(\n `Could not reach npm registry for ${packageName}: ${response.statusText}`,\n );\n }\n const data = (await response.json()) as {\n \"dist-tags\"?: Record<string, string>;\n versions?: Record<string, unknown>;\n };\n const resolved =\n data[\"dist-tags\"]?.[versionSpec] ??\n (data.versions?.[versionSpec] ? versionSpec : undefined);\n if (!resolved) {\n throw new Error(\n `${packageName} has no version or dist-tag \"${versionSpec}\" on the npm registry.`,\n );\n }\n return resolved;\n}\n\n/**\n * Resolves the source-of-truth adapter's golden images for the divergence\n * check. Never boots a Storybook — both location types resolve to plain\n * files, fetched once and cached, not re-diffed per pixel over the wire.\n *\n * `location.type === \"local\"`: a sibling package already checked out (this\n * monorepo's own `sourceOfTruth.type: \"url\"` mode) — read its\n * `test/golden/` directly, including any uncommitted local changes.\n *\n * `location.type === \"npm\"`: no local checkout (the default, standalone-repo\n * mode) — resolve the installed version against the npm registry, then fetch\n * that exact version's `test/golden/` from the public GitHub repo at the\n * matching release tag (changesets tags every release as\n * `<packageName>@<version>`), caching what's downloaded under `cacheDir`.\n *\n * Throws when no golden baseline exists yet for this version, or the\n * registry/repo is unreachable — a divergence check that can't reach its\n * baseline must fail loudly, not degrade to a silent skip that Playwright\n * then reports as a pass.\n */\nexport async function resolveSourceOfTruthGolden(\n location: SourceOfTruthGoldenLocation,\n): Promise<SourceOfTruthGolden> {\n if (location.type === \"local\") {\n if (!existsSync(manifestPath(location.dir))) {\n throw new Error(\n `No golden baseline found at ${location.dir} — the source-of-truth divergence check has nothing to compare against. Capture one there first (--update-golden), or fix sourceOfTruth.dir if it's pointing at the wrong checkout.`,\n );\n }\n const manifest = loadManifest(location.dir);\n return {\n manifest,\n async readImage(storyId) {\n const path = goldenImagePath(location.dir, storyId);\n return existsSync(path) ? readFileSync(path) : null;\n },\n };\n }\n\n let version: string;\n try {\n version = await resolveNpmVersion(\n location.packageName,\n location.versionSpec,\n );\n } catch (error) {\n throw new Error(\n `Could not resolve ${location.packageName}@${location.versionSpec} on the npm registry — the source-of-truth divergence check has nothing to compare against.`,\n { cause: error },\n );\n }\n\n const cacheDir = join(location.cacheDir, version);\n // @recursica/adapter-mantine-v8 is a standalone single-package repo (unlike\n // the old @recursica/mantine-adapter, which lived at `packages/<name>`\n // inside this monorepo) — its `test/golden/` sits directly at the repo root.\n // changesets/action tags single-package repos as `v<version>`, not\n // `<packageName>@<version>` (that longer form is only its default for\n // multi-package/monorepo releases) — this repo's release.yml confirms\n // `v<version>` is what actually gets tagged and pushed on every release.\n const tag = `v${version}`;\n const rawBase = `https://raw.githubusercontent.com/${GITHUB_REPO}/${tag}/test/golden`;\n\n let manifest: GoldenManifest;\n const cachedManifestPath = manifestPath(cacheDir);\n if (existsSync(cachedManifestPath)) {\n manifest = loadManifest(cacheDir);\n } else {\n let response: Response;\n try {\n response = await fetch(`${rawBase}/manifest.json`);\n } catch (error) {\n throw new Error(\n `Could not reach GitHub to fetch ${tag}'s golden baseline (${rawBase}/manifest.json) — the source-of-truth divergence check has nothing to compare against.`,\n { cause: error },\n );\n }\n if (!response.ok) {\n throw new Error(\n `No golden baseline published for tag \"${tag}\" in ${GITHUB_REPO} (${rawBase}/manifest.json returned ${response.status}) — the source-of-truth divergence check has nothing to compare against. Confirm that tag exists and its release actually published test/golden/.`,\n );\n }\n const text = await response.text();\n const parsed = JSON.parse(text);\n validateGoldenManifest(parsed, `${rawBase}/manifest.json`);\n mkdirSync(cacheDir, { recursive: true });\n writeFileSync(cachedManifestPath, text);\n manifest = parsed;\n }\n\n return {\n manifest,\n async readImage(storyId) {\n const cachedImagePath = goldenImagePath(cacheDir, storyId);\n if (existsSync(cachedImagePath)) return readFileSync(cachedImagePath);\n const response = await fetch(`${rawBase}/${storyId}.png`);\n if (!response.ok) return null;\n const buffer = Buffer.from(await response.arrayBuffer());\n mkdirSync(cacheDir, { recursive: true });\n writeFileSync(cachedImagePath, buffer);\n return buffer;\n },\n };\n}\n","import { expect } from \"@playwright/test\";\nimport type { Browser, TestInfo } from \"@playwright/test\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport type { AdapterTesterConfig } from \"../config.js\";\nimport { diffPngBuffers } from \"../golden/diffPng.js\";\nimport {\n type GoldenManifestEntry,\n goldenImagePath,\n loadManifest,\n pruneOrphanedGoldens,\n saveGoldenImage,\n updateManifestEntry,\n} from \"../golden/manifestStore.js\";\nimport { resolveSourceOfTruthGolden } from \"../golden/resolveSourceOfTruthGolden.js\";\n\nconst DEFAULT_EXCLUDE_TITLE_PREFIXES = [\"Theme\", \"Tokens\", \"Introduction\"];\n\ninterface StorybookEntry {\n type: string;\n id: string;\n name: string;\n title: string;\n}\n\nfunction matchesPrefix(id: string, prefix: string): boolean {\n return id === prefix || id.startsWith(prefix);\n}\n\n/** Fetches every story `target`'s Storybook currently has, filtered only by\n * `excludeTitlePrefixes` — not `stories.<id>.exclude`, so callers can still\n * tell an excluded story apart from one that's genuinely missing. */\nasync function fetchStories(\n target: { name: string; url: string },\n excludeTitlePrefixes: string[],\n): Promise<StorybookEntry[]> {\n let stories: StorybookEntry[];\n try {\n const response = await fetch(`${target.url}/index.json`);\n if (!response.ok) {\n throw new Error(\n `Failed to fetch Storybook index: ${response.statusText}`,\n );\n }\n const data = (await response.json()) as any;\n const entries = data.entries || {};\n stories = Object.values(entries).filter(\n (entry: any) =>\n entry.type === \"story\" &&\n !excludeTitlePrefixes.some(\n (prefix) =>\n entry.title === prefix || entry.title.startsWith(`${prefix}/`),\n ),\n ) as StorybookEntry[];\n stories.sort((a, b) => a.id.localeCompare(b.id));\n } catch (error) {\n console.error(\n \"Failed to load Storybook index from\",\n `${target.url}/index.json`,\n error,\n );\n throw new Error(\n `Storybook target \"${target.name}\" is not responsive or index.json is missing. Please ensure its Storybook is running.`,\n );\n }\n return stories;\n}\n\n/** Resolves the diff threshold for `storyId`: the longest (most specific)\n * `storyThresholds` key matching by prefix, falling back to\n * `defaultThresholdPixels` when nothing matches. */\nfunction resolveThreshold(\n storyId: string,\n storyThresholds: Record<string, number>,\n defaultThresholdPixels: number,\n): number {\n let bestMatch: string | undefined;\n for (const prefix of Object.keys(storyThresholds)) {\n if (\n matchesPrefix(storyId, prefix) &&\n (!bestMatch || prefix.length > bestMatch.length)\n ) {\n bestMatch = prefix;\n }\n }\n return bestMatch !== undefined\n ? storyThresholds[bestMatch]!\n : defaultThresholdPixels;\n}\n\n/** Everything a generated Playwright spec needs to register the golden-image\n * suite itself. Split out from the actual `test.describe`/`test` calls so\n * those calls execute in the spec file that imports this, not in this\n * library file — otherwise Playwright's HTML report groups every story under\n * this file's own (sourcemapped) path instead of a stable spec name. */\nexport interface VisualRegressionPlan {\n /** `config`'s own (non-source-of-truth) target name, for the suite title. */\n ownTargetName: string;\n /** Suite title suffix describing which check mode is running. */\n suiteLabel: string;\n /** Stories to check, already filtered and sorted by id. */\n stories: StorybookEntry[];\n /** Story ids the source-of-truth adapter has a golden for but this\n * project's own Storybook doesn't — empty outside `checkMode: \"divergence\"`\n * or when `sourceOfTruthGolden` didn't resolve. Excludes ids covered by a\n * `stories.<id>.exclude` entry: an intentional gap, not a sync failure. */\n missingFromSourceOfTruth: string[];\n /** Golden-checks one story. Call this from inside a `test(story.id, ...)`\n * body — safe to run concurrently across Playwright workers, since each\n * call only ever reads/writes its own story's manifest entry (locked at\n * the point it writes it back, so concurrent workers never race each\n * other's entries — see `updateManifestEntry`). */\n checkStory: (\n story: StorybookEntry,\n browser: Browser,\n testInfo: TestInfo,\n ) => Promise<void>;\n}\n\n/** Everything a generated Playwright spec needs to register the golden-image\n * suite itself. Split out from the actual `test.describe`/`test` calls so\n * those calls execute in the spec file that imports this, not in this\n * library file — otherwise Playwright's HTML report groups every story under\n * this file's own (sourcemapped) path instead of a stable spec name. */\nexport interface VisualRegressionPlan {\n /** `config`'s own (non-source-of-truth) target name, for the suite title. */\n ownTargetName: string;\n /** Suite title suffix describing which check mode is running. */\n suiteLabel: string;\n /** Stories to check, already filtered and sorted by id. */\n stories: StorybookEntry[];\n /** Golden-checks one story. Call this from inside a `test(story.id, ...)`\n * body — safe to run concurrently across Playwright workers, since each\n * call only ever reads/writes its own story's manifest entry (locked at\n * the point it writes it back, so concurrent workers never race each\n * other's entries — see `updateManifestEntry`). */\n checkStory: (\n story: StorybookEntry,\n browser: Browser,\n testInfo: TestInfo,\n ) => Promise<void>;\n}\n\n/**\n * Resolves the golden-image plan for `config`'s own target (the one target\n * in `config.targets` not marked `sourceOfTruth`).\n *\n * Two independent checks per story, gated by `config.checkMode`. Neither\n * boots the source-of-truth adapter's own Storybook — its side of both\n * checks is always a stored golden file, never a live page:\n *\n * 1. **Own-drift (`checkMode: \"own\"`, the default; hard fail):** this run's\n * live render vs this project's own stored `test/golden/<story-id>.png`.\n * No golden yet for a story is not a failure — one is captured from this\n * run instead (same as `--update-golden`, scoped to just that story), in\n * either mode.\n * 2. **Source-of-truth divergence (`checkMode: \"divergence\"`; hard fail):**\n * this run's live render vs the source-of-truth's stored golden (`config`'s\n * `sourceOfTruthGolden`) — always fresh, no `--update-golden` step needed\n * first. Skipped entirely when `config.isSourceOfTruthAdapter` is true —\n * the source-of-truth adapter has nothing above it to diverge from — and\n * skipped per-story when the source of truth has no baseline for it yet.\n * A once-flagged divergence stays quiet after `--approve-divergence`,\n * until the source of truth's own golden changes again.\n */\nexport async function resolveVisualRegressionPlan(\n config: AdapterTesterConfig,\n): Promise<VisualRegressionPlan> {\n const ownTarget = config.isSourceOfTruthAdapter\n ? config.targets[0]\n : config.targets.find((target) => !target.sourceOfTruth);\n if (!ownTarget) {\n throw new Error(\n \"adapter-tester config has no non-sourceOfTruth target to run the golden check against.\",\n );\n }\n const excludeTitlePrefixes =\n config.excludeTitlePrefixes ?? DEFAULT_EXCLUDE_TITLE_PREFIXES;\n const storyOverrides = config.stories ?? {};\n const excludeStoryIds = Object.keys(storyOverrides).filter(\n (id) => storyOverrides[id]!.exclude,\n );\n const goldenStoryThresholds = Object.fromEntries(\n Object.entries(storyOverrides)\n .filter(([, override]) => override.goldenThreshold !== undefined)\n .map(([id, override]) => [id, override.goldenThreshold!]),\n );\n const sourceOfTruthStoryThresholds = Object.fromEntries(\n Object.entries(storyOverrides)\n .filter(([, override]) => override.sourceOfTruthThreshold !== undefined)\n .map(([id, override]) => [id, override.sourceOfTruthThreshold!]),\n );\n const goldenDir = config.goldenDir;\n const goldenMode = config.goldenMode;\n const checkMode = config.checkMode;\n\n // Fetched with only excludeTitlePrefixes applied — not excludeStoryIds —\n // so the source-of-truth story-parity check below can tell an excluded\n // story apart from one that's genuinely missing from this Storybook.\n const ownStories = await fetchStories(ownTarget, excludeTitlePrefixes);\n const stories = ownStories.filter(\n (entry) =>\n !excludeStoryIds.some((prefix) => matchesPrefix(entry.id, prefix)),\n );\n\n // `--update-golden` redefines this project's own baseline, so it's also\n // the point a renamed/removed story's now-orphaned golden gets cleaned up\n // — otherwise nothing ever prunes it, since a run only ever adds/updates\n // entries for stories it actually saw in this pass. Uses the full current\n // story list (not narrowed by any `--grep` Playwright itself applies), so\n // this catches every orphan regardless of how the run is scoped.\n if (goldenMode === \"update-golden\") {\n const prunedStoryIds = await pruneOrphanedGoldens(\n goldenDir,\n new Set(stories.map((story) => story.id)),\n );\n if (prunedStoryIds.length > 0) {\n console.warn(\n `Pruned ${prunedStoryIds.length} orphaned golden(s) no longer in Storybook: ${prunedStoryIds.join(\", \")}`,\n );\n }\n }\n\n const sourceOfTruthGolden =\n checkMode !== \"divergence\" ||\n config.isSourceOfTruthAdapter ||\n !config.sourceOfTruthGolden\n ? null\n : await resolveSourceOfTruthGolden(config.sourceOfTruthGolden);\n\n // Checked against `ownStories` (title-prefix-excluded only), not `stories`\n // — a story marked `exclude: true` still counts as \"present\", it's just\n // not diffed. Only a story the source of truth has that this adapter\n // never built at all, and hasn't acknowledged via `exclude`, is missing.\n const ownStoryIds = new Set(ownStories.map((entry) => entry.id));\n const missingFromSourceOfTruth = sourceOfTruthGolden\n ? Object.keys(sourceOfTruthGolden.manifest)\n .filter(\n (id) =>\n !ownStoryIds.has(id) &&\n !excludeStoryIds.some((prefix) => matchesPrefix(id, prefix)),\n )\n .sort()\n : [];\n\n if (missingFromSourceOfTruth.length > 0) {\n console.error(\n `[adapter-tester] ${missingFromSourceOfTruth.length} stor(y/ies) exist in the source of truth but are missing here: ${missingFromSourceOfTruth.join(\", \")}. Add the missing story, or mark it \\`exclude: true\\` under \\`stories\\` in adapter-tester.config.json if intentional.`,\n );\n }\n\n console.log(\n [\n `[adapter-tester] target: \"${ownTarget.name}\" (${ownTarget.url})`,\n `[adapter-tester] checkMode: \"${checkMode}\" (${checkMode === \"divergence\" ? \"live render vs source-of-truth's golden\" : \"live render vs this project's own golden\"})`,\n `[adapter-tester] goldenMode: \"${goldenMode}\"`,\n `[adapter-tester] goldenThresholdPixels: ${config.goldenThresholdPixels}`,\n `[adapter-tester] sourceOfTruthThresholdPixels: ${config.sourceOfTruthThresholdPixels}`,\n checkMode === \"divergence\"\n ? config.isSourceOfTruthAdapter\n ? `[adapter-tester] sourceOfTruthGolden: skipped — this is the source-of-truth adapter, nothing to diverge from`\n : !config.sourceOfTruthGolden\n ? `[adapter-tester] sourceOfTruthGolden: skipped — no sourceOfTruthGolden configured`\n : // Unresolvable-baseline case never reaches here — resolveSourceOfTruthGolden\n // throws instead of returning null, failing the whole run before this\n // logs, rather than letting the divergence check silently no-op.\n `[adapter-tester] sourceOfTruthGolden: resolved, ${Object.keys(sourceOfTruthGolden!.manifest).length} golden(s) available (config: ${JSON.stringify(config.sourceOfTruthGolden)})`\n : `[adapter-tester] sourceOfTruthGolden: not used in \"own\" checkMode`,\n `[adapter-tester] stories: ${stories.length} to check (excluded: ${excludeStoryIds.length}, title prefixes excluded: ${excludeTitlePrefixes.join(\", \") || \"none\"})`,\n `[adapter-tester] story parity with source of truth: ${missingFromSourceOfTruth.length === 0 ? \"OK\" : `${missingFromSourceOfTruth.length} missing (see error above)`}`,\n ].join(\"\\n\"),\n );\n\n const suiteLabel =\n checkMode === \"divergence\"\n ? \"Source-of-Truth Divergence Check\"\n : \"Own-Drift Golden Image Check\";\n\n return {\n ownTargetName: ownTarget.name,\n suiteLabel,\n stories,\n missingFromSourceOfTruth,\n checkStory: async (story, browser, testInfo) => {\n const page = await browser.newPage();\n await page.setViewportSize({ width: 800, height: 600 });\n await page.goto(\n `${ownTarget.url}/iframe.html?id=${story.id}&viewMode=story`,\n { waitUntil: \"networkidle\" },\n );\n await page.waitForSelector(\"#storybook-root\");\n await page.addStyleTag({\n content: `* { -webkit-font-smoothing: antialiased !important; -moz-osx-font-smoothing: grayscale !important; }`,\n });\n // Web fonts (e.g. `withRecursicaFonts`'s Google Fonts `<link>`s, injected\n // from a React effect after this page's `networkidle` already fired) can\n // still be mid-download here. Wait for any `<link>` stylesheet that's\n // still loading to settle — so the browser has parsed its `@font-face`\n // rules and started the actual font-file fetches `document.fonts.ready`\n // below needs to know about — then for the fonts themselves. Without\n // this, the very first golden capture of a newly-introduced font family\n // is a coin flip between the real font and its fallback, depending on\n // how fast the network happens to be.\n await page.evaluate(() =>\n Promise.all(\n Array.from(\n document.querySelectorAll<HTMLLinkElement>(\n 'link[rel=\"stylesheet\"]',\n ),\n ).map((link) =>\n link.sheet\n ? Promise.resolve()\n : new Promise<void>((resolve) => {\n link.addEventListener(\"load\", () => resolve(), {\n once: true,\n });\n link.addEventListener(\"error\", () => resolve(), {\n once: true,\n });\n }),\n ),\n ).then(() => document.fonts.ready),\n );\n await page.waitForTimeout(300);\n const liveBuffer = await page.screenshot();\n\n const imagePath = goldenImagePath(goldenDir, story.id);\n // Only this worker ever touches this story's key, so reading it here\n // (outside the lock `updateManifestEntry` takes at the end) can't\n // race another worker — they're all reading/writing different keys.\n const entry = loadManifest(goldenDir)[story.id];\n const capturingNewGolden =\n goldenMode !== \"check\" || !entry || !existsSync(imagePath);\n\n let currentEntry: GoldenManifestEntry;\n if (capturingNewGolden) {\n saveGoldenImage(goldenDir, story.id, liveBuffer);\n currentEntry = entry?.sourceOfTruthCreatedAt\n ? {\n createdAt: new Date().toISOString(),\n sourceOfTruthCreatedAt: entry.sourceOfTruthCreatedAt,\n }\n : { createdAt: new Date().toISOString() };\n if (!entry) {\n testInfo.annotations.push({\n type: \"golden-created\",\n description: `No golden existed yet for \"${story.id}\" — captured one from this run.`,\n });\n }\n } else {\n currentEntry = entry;\n if (checkMode === \"own\") {\n const goldenBuffer = readFileSync(imagePath);\n const { diffPixels, diffImage } = diffPngBuffers(\n liveBuffer,\n goldenBuffer,\n );\n const threshold = resolveThreshold(\n story.id,\n goldenStoryThresholds,\n config.goldenThresholdPixels,\n );\n if (diffPixels >= threshold) {\n await testInfo.attach(\"expected\", {\n body: goldenBuffer,\n contentType: \"image/png\",\n });\n await testInfo.attach(\"actual\", {\n body: liveBuffer,\n contentType: \"image/png\",\n });\n if (diffImage) {\n await testInfo.attach(\"diff\", {\n body: diffImage,\n contentType: \"image/png\",\n });\n }\n }\n expect\n .soft(\n diffPixels,\n `\"${story.id}\" has drifted from its own golden image (${diffPixels} mismatched pixels, threshold ${threshold})`,\n )\n .toBeLessThan(threshold);\n }\n }\n\n if (sourceOfTruthGolden) {\n const sourceOfTruthEntry = sourceOfTruthGolden.manifest[story.id];\n const sourceOfTruthImage = sourceOfTruthEntry\n ? await sourceOfTruthGolden.readImage(story.id)\n : null;\n\n if (sourceOfTruthEntry && sourceOfTruthImage) {\n if (goldenMode === \"approve-divergence\") {\n currentEntry = {\n ...currentEntry,\n sourceOfTruthCreatedAt: sourceOfTruthEntry.createdAt,\n };\n } else {\n // Always this run's live render, never the stored own-drift\n // golden — divergence should reflect what's on screen right now,\n // not whatever was last captured via --update-golden.\n const { diffPixels, diffImage } = diffPngBuffers(\n liveBuffer,\n sourceOfTruthImage,\n );\n const threshold = resolveThreshold(\n story.id,\n sourceOfTruthStoryThresholds,\n config.sourceOfTruthThresholdPixels,\n );\n const approvedAt = currentEntry.sourceOfTruthCreatedAt;\n const isKnownDivergence =\n diffPixels < threshold ||\n (approvedAt !== undefined &&\n approvedAt >= sourceOfTruthEntry.createdAt);\n if (!isKnownDivergence) {\n await testInfo.attach(\"expected\", {\n body: sourceOfTruthImage,\n contentType: \"image/png\",\n });\n await testInfo.attach(\"actual\", {\n body: liveBuffer,\n contentType: \"image/png\",\n });\n if (diffImage) {\n await testInfo.attach(\"diff\", {\n body: diffImage,\n contentType: \"image/png\",\n });\n }\n testInfo.annotations.push({\n type: \"source-of-truth-divergence\",\n description: `\"${story.id}\" differs from the source of truth's golden by ${diffPixels} mismatched pixels (threshold ${threshold}) and hasn't been reviewed — run with --approve-divergence if this is intentional, or fix the adapter styling.`,\n });\n }\n expect\n .soft(\n isKnownDivergence,\n `\"${story.id}\" differs from the source of truth's golden by ${diffPixels} mismatched pixels (threshold ${threshold}) and hasn't been reviewed — run with --approve-divergence if this is intentional, or fix the adapter styling.`,\n )\n .toBe(true);\n }\n }\n }\n\n // Locked read-modify-write of just this story's entry — see\n // `updateManifestEntry` for why that's enough to make this safe\n // across concurrent Playwright workers.\n await updateManifestEntry(goldenDir, story.id, () => currentEntry);\n },\n };\n}\n"],"names":["diffPngBuffers","a","b","imgA","PNG","imgB","diff","pixelmatch","addFormats","ajvFormatsModule.default","ajv","Ajv","validate","schema","validateGoldenManifest","data","path","errors","error","extra","_a","manifestPath","goldenDir","join","manifestLockPath","goldenImagePath","storyId","loadManifest","existsSync","readFileSync","saveManifest","manifest","sorted","key","mkdirSync","tmpPath","writeFileSync","renameSync","LOCK_RETRY_MS","LOCK_TIMEOUT_MS","sleep","ms","resolve","acquireManifestLock","deadline","closeSync","openSync","releaseManifestLock","rmSync","updateManifestEntry","updater","nextEntry","saveGoldenImage","buffer","pruneOrphanedGoldens","currentStoryIds","orphanIds","id","imagePath","unlinkSync","GITHUB_REPO","resolveNpmVersion","packageName","versionSpec","response","resolved","_b","resolveSourceOfTruthGolden","location","version","cacheDir","tag","rawBase","cachedManifestPath","text","parsed","cachedImagePath","DEFAULT_EXCLUDE_TITLE_PREFIXES","matchesPrefix","prefix","fetchStories","target","excludeTitlePrefixes","stories","entries","entry","resolveThreshold","storyThresholds","defaultThresholdPixels","bestMatch","resolveVisualRegressionPlan","config","ownTarget","storyOverrides","excludeStoryIds","goldenStoryThresholds","override","sourceOfTruthStoryThresholds","goldenMode","checkMode","ownStories","prunedStoryIds","story","sourceOfTruthGolden","ownStoryIds","missingFromSourceOfTruth","suiteLabel","browser","testInfo","page","link","liveBuffer","capturingNewGolden","currentEntry","goldenBuffer","diffPixels","diffImage","threshold","expect","sourceOfTruthEntry","sourceOfTruthImage","approvedAt","isKnownDivergence"],"mappings":"6OAeO,SAASA,EAAeC,EAAWC,EAA0B,CAClE,MAAMC,EAAOC,EAAAA,IAAI,KAAK,KAAKH,CAAC,EACtBI,EAAOD,EAAAA,IAAI,KAAK,KAAKF,CAAC,EAC5B,GAAIC,EAAK,QAAUE,EAAK,OAASF,EAAK,SAAWE,EAAK,OACpD,MAAO,CAAE,WAAY,IAAU,UAAW,IAAA,EAE5C,MAAMC,EAAO,IAAIF,EAAAA,IAAI,CAAE,MAAOD,EAAK,MAAO,OAAQA,EAAK,OAAQ,EAS/D,MAAO,CAAE,WARUI,EACjBJ,EAAK,KACLE,EAAK,KACLC,EAAK,KACLH,EAAK,MACLA,EAAK,OACL,CAAE,UAAW,EAAA,CAAI,EAEE,UAAWC,EAAAA,IAAI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