@recursica/adapter-tester 4.0.0 → 5.0.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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mantineSourceOfTruth-DE7XOgea.js","sources":["../src/harness/mantineSourceOfTruth.ts"],"sourcesContent":["import { mkdirSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n/**\n * Generates a small, throwaway Storybook project that installs\n * `@recursica/mantine-adapter` 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\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/mantine-adapter. Defaults to \"latest\". */\n mantineAdapterVersion?: string;\n /** npm version/range for @recursica/storybook-template. Defaults to \"latest\". */\n storybookTemplateVersion?: 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/mantine-adapter 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// mantine-adapter'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/mantine-adapter\": options.mantineAdapterVersion,\n \"@recursica/storybook-template\": options.storybookTemplateVersion,\n \"@recursica/official-release\": \"latest\",\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/mantine-adapter/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\nconst PREVIEW_TSX = `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/official-release/recursica_variables_scoped.css\";\nimport recursicaTokens from \"@recursica/official-release/recursica_tokens.json\";\nimport recursicaBrand from \"@recursica/official-release/recursica_brand.json\";\nimport recursicaUIKit from \"@recursica/official-release/recursica_ui-kit.json\";\n\nconst basePreview = createPreviewConfig({\n defaultTheme: \"light\",\n recursicaTokensJsonPath: recursicaTokens,\n recursicaBrandJsonPath: recursicaBrand,\n recursicaUIKitJsonPath: recursicaUIKit,\n});\n\n// Mirrors mantine-adapter'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 (mantine-adapter'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/** 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 } = options;\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\"), PREVIEW_TSX);\n writeFileSync(join(dir, \".gitignore\"), \"node_modules\\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/mantine-adapter/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.\n const command = `npm install @recursica/mantine-adapter@${mantineAdapterVersion} @recursica/storybook-template@${storybookTemplateVersion} --no-audit --no-fund && 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":["MANTINE_CORE_RANGE","STORYBOOK_RANGE","REACT_RANGE","DEFAULT_ADDON_DEPENDENCIES","WORKAROUND_DEPENDENCIES","harnessPackageJson","options","MAIN_TS","PREVIEW_TSX","scaffoldMantineSourceOfTruthHarness","dir","mantineAdapterVersion","storybookTemplateVersion","mkdirSync","join","writeFileSync","mantineSourceOfTruthWebServer"],"mappings":";;AAoDA,MAAMA,IAAqB,UACrBC,IAAkB,WAClBC,IAAc,WAOdC,IAA6B;AAAA,EACjC,yBAAyBF;AAAA,EACzB,yBAAyBA;AAAA,EACzB,uBAAuB;AACzB,GAOMG,IAA0B;AAAA,EAC9B,kBAAkB;AACpB;AAEA,SAASC,EAAmBC,GAGzB;AACD,SAAO;AAAA,IACL,MAAM;AAAA,IACN,SAAS;AAAA,IACT,MAAM;AAAA,IACN,SAAS;AAAA;AAAA;AAAA;AAAA,MAIP,WAAW;AAAA,IAAA;AAAA,IAEb,cAAc;AAAA,MACZ,8BAA8BA,EAAQ;AAAA,MACtC,iCAAiCA,EAAQ;AAAA,MACzC,+BAA+B;AAAA,MAC/B,6BAA6B;AAAA,MAC7B,iBAAiBN;AAAA,MACjB,kBAAkBA;AAAA,MAClB,OAAOE;AAAA,MACP,aAAaA;AAAA,MACb,WAAWD;AAAA,MACX,yBAAyBA;AAAA,MACzB,GAAGE;AAAA,MACH,GAAGC;AAAA,IAAA;AAAA,EACL;AAEJ;AAEA,MAAMG,IAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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AAQ,IAAI;AAAA,IAClC,WAAWI,EAAKJ,GAAK,gBAAgB;AAAA,IACrC,SAAS,MAAM;AAAA,EAAA;AAEnB;"}
@@ -1,4 +1,4 @@
1
- "use strict";const t=require("node:fs"),o=require("node:path"),c="^8.0.0",s="^10.3.3",d="^19.0.0",p={"@storybook/addon-docs":s,"@storybook/addon-a11y":s,"storybook-dark-mode":"^5.0.0"},u={"react-markdown":"^10.1.0"};function m(e){return{name:"adapter-tester-mantine-source-of-truth-harness",private:!0,type:"module",scripts:{storybook:`storybook dev -p ${e.port}`},dependencies:{"@recursica/mantine-adapter":e.mantineAdapterVersion,"@recursica/storybook-template":e.storybookTemplateVersion,"@recursica/official-release":"latest","@recursica/adapter-common":"latest","@mantine/core":c,"@mantine/dates":c,react:d,"react-dom":d,storybook:s,"@storybook/react-vite":s,...p,...u}}}const f=`import { createMainConfig } from "@recursica/storybook-template/main";
1
+ "use strict";const o=require("node:fs"),t=require("node:path"),n="^8.0.0",s="^10.3.3",c="^19.0.0",l={"@storybook/addon-docs":s,"@storybook/addon-a11y":s,"storybook-dark-mode":"^5.0.0"},p={"react-markdown":"^10.1.0"};function u(r){return{name:"adapter-tester-mantine-source-of-truth-harness",private:!0,type:"module",scripts:{storybook:"storybook dev"},dependencies:{"@recursica/mantine-adapter":r.mantineAdapterVersion,"@recursica/storybook-template":r.storybookTemplateVersion,"@recursica/official-release":"latest","@recursica/adapter-common":"latest","@mantine/core":n,"@mantine/dates":n,react:c,"react-dom":c,storybook:s,"@storybook/react-vite":s,...l,...p}}}const m=`import { createMainConfig } from "@recursica/storybook-template/main";
2
2
 
3
3
  const config = createMainConfig({
4
4
  stories: [
@@ -17,7 +17,7 @@ const config = createMainConfig({
17
17
  config.typescript = { ...config.typescript, reactDocgen: false };
18
18
 
19
19
  export default config;
20
- `,y=`import type { Preview } from "@storybook/react-vite";
20
+ `,f=`import type { Preview } from "@storybook/react-vite";
21
21
  import { createPreviewConfig } from "@recursica/storybook-template/preview";
22
22
  import { MantineProvider } from "@mantine/core";
23
23
  import { Layer } from "@recursica/adapter-common";
@@ -69,7 +69,7 @@ const preview: Preview = {
69
69
  };
70
70
 
71
71
  export default preview;
72
- `;function l(e){const{dir:r,port:a,mantineAdapterVersion:i="latest",storybookTemplateVersion:n="latest"}=e;return t.mkdirSync(o.join(r,".storybook"),{recursive:!0}),t.writeFileSync(o.join(r,"package.json"),JSON.stringify(m({mantineAdapterVersion:i,storybookTemplateVersion:n,port:a}),null,2)+`
73
- `),t.writeFileSync(o.join(r,".storybook/main.ts"),f),t.writeFileSync(o.join(r,".storybook/preview.tsx"),y),t.writeFileSync(o.join(r,".gitignore"),`node_modules
74
- `),r}function h(e){const r=l(e),{mantineAdapterVersion:a="latest",storybookTemplateVersion:i="latest"}=e;return{command:`npm install @recursica/mantine-adapter@${a} @recursica/storybook-template@${i} --no-audit --no-fund && npm run storybook`,port:e.port,cwd:r,reuseExistingServer:!process.env.CI,timeout:180*1e3}}exports.mantineSourceOfTruthWebServer=h;exports.scaffoldMantineSourceOfTruthHarness=l;
75
- //# sourceMappingURL=mantineSourceOfTruth-BUb5MZy0.cjs.map
72
+ `;function d(r){const{dir:e,mantineAdapterVersion:a="latest",storybookTemplateVersion:i="latest"}=r;return o.mkdirSync(t.join(e,".storybook"),{recursive:!0}),o.writeFileSync(t.join(e,"package.json"),JSON.stringify(u({mantineAdapterVersion:a,storybookTemplateVersion:i}),null,2)+`
73
+ `),o.writeFileSync(t.join(e,".storybook/main.ts"),m),o.writeFileSync(t.join(e,".storybook/preview.tsx"),f),o.writeFileSync(t.join(e,".gitignore"),`node_modules
74
+ `),e}function y(r){const e=d(r),{mantineAdapterVersion:a="latest",storybookTemplateVersion:i="latest"}=r;return{command:`npm install @recursica/mantine-adapter@${a} @recursica/storybook-template@${i} --no-audit --no-fund && npm run storybook`,port:r.port,cwd:e,reuseExistingServer:!process.env.CI,cacheFile:t.join(e,"last-port.json"),timeout:180*1e3}}exports.mantineSourceOfTruthWebServer=y;exports.scaffoldMantineSourceOfTruthHarness=d;
75
+ //# sourceMappingURL=mantineSourceOfTruth-Dpe4mlmF.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mantineSourceOfTruth-Dpe4mlmF.cjs","sources":["../src/harness/mantineSourceOfTruth.ts"],"sourcesContent":["import { mkdirSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n/**\n * Generates a small, throwaway Storybook project that installs\n * `@recursica/mantine-adapter` 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\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/mantine-adapter. Defaults to \"latest\". */\n mantineAdapterVersion?: string;\n /** npm version/range for @recursica/storybook-template. Defaults to \"latest\". */\n storybookTemplateVersion?: 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/mantine-adapter 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// mantine-adapter'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/mantine-adapter\": options.mantineAdapterVersion,\n \"@recursica/storybook-template\": options.storybookTemplateVersion,\n \"@recursica/official-release\": \"latest\",\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/mantine-adapter/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\nconst PREVIEW_TSX = `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/official-release/recursica_variables_scoped.css\";\nimport recursicaTokens from \"@recursica/official-release/recursica_tokens.json\";\nimport recursicaBrand from \"@recursica/official-release/recursica_brand.json\";\nimport recursicaUIKit from \"@recursica/official-release/recursica_ui-kit.json\";\n\nconst basePreview = createPreviewConfig({\n defaultTheme: \"light\",\n recursicaTokensJsonPath: recursicaTokens,\n recursicaBrandJsonPath: recursicaBrand,\n recursicaUIKitJsonPath: recursicaUIKit,\n});\n\n// Mirrors mantine-adapter'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 (mantine-adapter'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/** 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 } = options;\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\"), PREVIEW_TSX);\n writeFileSync(join(dir, \".gitignore\"), \"node_modules\\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/mantine-adapter/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.\n const command = `npm install @recursica/mantine-adapter@${mantineAdapterVersion} @recursica/storybook-template@${storybookTemplateVersion} --no-audit --no-fund && 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":["MANTINE_CORE_RANGE","STORYBOOK_RANGE","REACT_RANGE","DEFAULT_ADDON_DEPENDENCIES","WORKAROUND_DEPENDENCIES","harnessPackageJson","options","MAIN_TS","PREVIEW_TSX","scaffoldMantineSourceOfTruthHarness","dir","mantineAdapterVersion","storybookTemplateVersion","mkdirSync","join","writeFileSync","mantineSourceOfTruthWebServer"],"mappings":"+DAoDMA,EAAqB,SACrBC,EAAkB,UAClBC,EAAc,UAOdC,EAA6B,CACjC,wBAAyBF,EACzB,wBAAyBA,EACzB,sBAAuB,QACzB,EAOMG,EAA0B,CAC9B,iBAAkB,SACpB,EAEA,SAASC,EAAmBC,EAGzB,CACD,MAAO,CACL,KAAM,iDACN,QAAS,GACT,KAAM,SACN,QAAS,CAIP,UAAW,eAAA,EAEb,aAAc,CACZ,6BAA8BA,EAAQ,sBACtC,gCAAiCA,EAAQ,yBACzC,8BAA+B,SAC/B,4BAA6B,SAC7B,gBAAiBN,EACjB,iBAAkBA,EAClB,MAAOE,EACP,YAAaA,EACb,UAAWD,EACX,wBAAyBA,EACzB,GAAGE,EACH,GAAGC,CAAA,CACL,CAEJ,CAEA,MAAMG,EAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAqBVC,EAAc;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAuDb,SAASC,EACdH,EACQ,CACR,KAAM,CACJ,IAAAI,EACA,sBAAAC,EAAwB,SACxB,yBAAAC,EAA2B,QAAA,EACzBN,EAEJO,OAAAA,EAAAA,UAAUC,EAAAA,KAAKJ,EAAK,YAAY,EAAG,CAAE,UAAW,GAAM,EACtDK,EAAAA,cACED,EAAAA,KAAKJ,EAAK,cAAc,EACxB,KAAK,UACHL,EAAmB,CACjB,sBAAAM,EACA,yBAAAC,CAAA,CACD,EACD,KACA,CAAA,EACE;AAAA,CAAA,EAENG,EAAAA,cAAcD,EAAAA,KAAKJ,EAAK,oBAAoB,EAAGH,CAAO,EACtDQ,EAAAA,cAAcD,EAAAA,KAAKJ,EAAK,wBAAwB,EAAGF,CAAW,EAC9DO,EAAAA,cAAcD,EAAAA,KAAKJ,EAAK,YAAY,EAAG;AAAA,CAAgB,EAEhDA,CACT,CAMO,SAASM,EACdV,EACwB,CACxB,MAAMI,EAAMD,EAAoCH,CAAO,EACjD,CACJ,sBAAAK,EAAwB,SACxB,yBAAAC,EAA2B,QAAA,EACzBN,EAYJ,MAAO,CACL,QAHc,0CAA0CK,CAAqB,kCAAkCC,CAAwB,6CAIvI,KAAMN,EAAQ,KACd,IAAKI,EACL,oBAAqB,CAAC,QAAQ,IAAI,GAClC,UAAWI,EAAAA,KAAKJ,EAAK,gBAAgB,EACrC,QAAS,IAAM,GAAA,CAEnB"}
@@ -0,0 +1,39 @@
1
+ import { ChildProcess } from 'node:child_process';
2
+ import { HarnessWebServerConfig } from './harness/mantineSourceOfTruth.js';
3
+ /**
4
+ * Boots a target's Storybook and discovers the real port it ends up on,
5
+ * instead of pinning one via `-p`/`--port`. Storybook silently falls back to
6
+ * an OS-assigned port whenever its default/configured one is taken (this is
7
+ * what caused the flaky `webServer` timeouts noted in mui-adapter), so the
8
+ * only reliable source of truth is the URL it prints in its own startup
9
+ * banner. Used by both the automated/headless run (cli.ts) and Dev Mode
10
+ * (devServer.ts) — neither pins a port anymore.
11
+ */
12
+ export interface LaunchTarget {
13
+ /** Human-readable name used in log lines. */
14
+ name: string;
15
+ command: string;
16
+ cwd: string;
17
+ /** Reuse an already-running instance (detected via the last-known-port
18
+ * cache) instead of spawning a new one. Mirrors the old `reuseExistingServer`
19
+ * behavior, which used to just probe the one fixed configured port. */
20
+ reuseExistingServer: boolean;
21
+ /** File the discovered port is cached in between runs, so a later
22
+ * `reuseExistingServer` run knows where to look. One per target. */
23
+ cacheFile: string;
24
+ timeoutMs?: number;
25
+ }
26
+ export interface DiscoveredServer {
27
+ url: string;
28
+ port: number;
29
+ /** The process we spawned, or `null` if an already-running instance was
30
+ * reused — callers should only kill what they started. */
31
+ process: ChildProcess | null;
32
+ }
33
+ /** Adapts a resolved `HarnessWebServerConfig` into a `LaunchTarget`. */
34
+ export declare function toLaunchTarget(name: string, server: HarnessWebServerConfig): LaunchTarget;
35
+ /** Reuses an already-running Storybook if `reuseExistingServer` is set and
36
+ * the last-known-port cache points at something still listening; otherwise
37
+ * spawns `target.command` fresh and detects the real port from its output. */
38
+ export declare function launchAndDetectStorybook(target: LaunchTarget): Promise<DiscoveredServer>;
39
+ //# sourceMappingURL=portDiscovery.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"portDiscovery.d.ts","sourceRoot":"","sources":["../src/portDiscovery.ts"],"names":[],"mappings":"AAAA,OAAO,EAAS,KAAK,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAI9D,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,mCAAmC,CAAC;AAEhF;;;;;;;;GAQG;AAEH,MAAM,WAAW,YAAY;IAC3B,6CAA6C;IAC7C,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,GAAG,EAAE,MAAM,CAAC;IACZ;;2EAEuE;IACvE,mBAAmB,EAAE,OAAO,CAAC;IAC7B;wEACoE;IACpE,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,gBAAgB;IAC/B,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,MAAM,CAAC;IACb;8DAC0D;IAC1D,OAAO,EAAE,YAAY,GAAG,IAAI,CAAC;CAC9B;AAgHD,wEAAwE;AACxE,wBAAgB,cAAc,CAC5B,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,sBAAsB,GAC7B,YAAY,CASd;AAED;;8EAE8E;AAC9E,wBAAsB,wBAAwB,CAC5C,MAAM,EAAE,YAAY,GACnB,OAAO,CAAC,gBAAgB,CAAC,CAgB3B"}
@@ -6,6 +6,30 @@ interface StorybookEntry {
6
6
  name: string;
7
7
  title: string;
8
8
  }
9
+ /** Everything a generated Playwright spec needs to register the golden-image
10
+ * suite itself. Split out from the actual `test.describe`/`test` calls so
11
+ * those calls execute in the spec file that imports this, not in this
12
+ * library file — otherwise Playwright's HTML report groups every story under
13
+ * this file's own (sourcemapped) path instead of a stable spec name. */
14
+ export interface VisualRegressionPlan {
15
+ /** `config`'s own (non-source-of-truth) target name, for the suite title. */
16
+ ownTargetName: string;
17
+ /** Suite title suffix describing which check mode is running. */
18
+ suiteLabel: string;
19
+ /** Stories to check, already filtered and sorted by id. */
20
+ stories: StorybookEntry[];
21
+ /** Story ids the source-of-truth adapter has a golden for but this
22
+ * project's own Storybook doesn't — empty outside `checkMode: "divergence"`
23
+ * or when `sourceOfTruthGolden` didn't resolve. Excludes ids covered by a
24
+ * `stories.<id>.exclude` entry: an intentional gap, not a sync failure. */
25
+ missingFromSourceOfTruth: string[];
26
+ /** Golden-checks one story. Call this from inside a `test(story.id, ...)`
27
+ * body — safe to run concurrently across Playwright workers, since each
28
+ * call only ever reads/writes its own story's manifest entry (locked at
29
+ * the point it writes it back, so concurrent workers never race each
30
+ * other's entries — see `updateManifestEntry`). */
31
+ checkStory: (story: StorybookEntry, browser: Browser, testInfo: TestInfo) => Promise<void>;
32
+ }
9
33
  /** Everything a generated Playwright spec needs to register the golden-image
10
34
  * suite itself. Split out from the actual `test.describe`/`test` calls so
11
35
  * those calls execute in the spec file that imports this, not in this
@@ -38,10 +62,10 @@ export interface VisualRegressionPlan {
38
62
  * No golden yet for a story is not a failure — one is captured from this
39
63
  * run instead (same as `--update-golden`, scoped to just that story), in
40
64
  * either mode.
41
- * 2. **Source-of-truth divergence (`checkMode: "divergence"`; soft flag,
42
- * never fails the run):** this project's own golden vs the
43
- * source-of-truth's golden (`config`'s `sourceOfTruthGolden`). Skipped
44
- * entirely when `config.isSourceOfTruthAdapter` is true — the
65
+ * 2. **Source-of-truth divergence (`checkMode: "divergence"`; hard fail):**
66
+ * this project's own golden vs the source-of-truth's golden (`config`'s
67
+ * `sourceOfTruthGolden`). Skipped entirely when
68
+ * `config.isSourceOfTruthAdapter` is true — the
45
69
  * source-of-truth adapter has nothing above it to diverge from — and
46
70
  * skipped per-story when neither side has a baseline yet. A
47
71
  * once-flagged divergence stays quiet after `--approve-divergence`,
@@ -1 +1 @@
1
- {"version":3,"file":"runVisualRegression.d.ts","sourceRoot":"","sources":["../../src/testing/runVisualRegression.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAE1D,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAcxD,UAAU,cAAc;IACtB,IAAI,EAAE,MAAM,CAAC;IACb,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;CACf;AAkED;;;;wEAIwE;AACxE,MAAM,WAAW,oBAAoB;IACnC,6EAA6E;IAC7E,aAAa,EAAE,MAAM,CAAC;IACtB,iEAAiE;IACjE,UAAU,EAAE,MAAM,CAAC;IACnB,2DAA2D;IAC3D,OAAO,EAAE,cAAc,EAAE,CAAC;IAC1B;;;;uDAImD;IACnD,UAAU,EAAE,CACV,KAAK,EAAE,cAAc,EACrB,OAAO,EAAE,OAAO,EAChB,QAAQ,EAAE,QAAQ,KACf,OAAO,CAAC,IAAI,CAAC,CAAC;CACpB;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAsB,2BAA2B,CAC/C,MAAM,EAAE,mBAAmB,GAC1B,OAAO,CAAC,oBAAoB,CAAC,CA6L/B"}
1
+ {"version":3,"file":"runVisualRegression.d.ts","sourceRoot":"","sources":["../../src/testing/runVisualRegression.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAE1D,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAcxD,UAAU,cAAc;IACtB,IAAI,EAAE,MAAM,CAAC;IACb,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;CACf;AAmED;;;;wEAIwE;AACxE,MAAM,WAAW,oBAAoB;IACnC,6EAA6E;IAC7E,aAAa,EAAE,MAAM,CAAC;IACtB,iEAAiE;IACjE,UAAU,EAAE,MAAM,CAAC;IACnB,2DAA2D;IAC3D,OAAO,EAAE,cAAc,EAAE,CAAC;IAC1B;;;+EAG2E;IAC3E,wBAAwB,EAAE,MAAM,EAAE,CAAC;IACnC;;;;uDAImD;IACnD,UAAU,EAAE,CACV,KAAK,EAAE,cAAc,EACrB,OAAO,EAAE,OAAO,EAChB,QAAQ,EAAE,QAAQ,KACf,OAAO,CAAC,IAAI,CAAC,CAAC;CACpB;AAED;;;;wEAIwE;AACxE,MAAM,WAAW,oBAAoB;IACnC,6EAA6E;IAC7E,aAAa,EAAE,MAAM,CAAC;IACtB,iEAAiE;IACjE,UAAU,EAAE,MAAM,CAAC;IACnB,2DAA2D;IAC3D,OAAO,EAAE,cAAc,EAAE,CAAC;IAC1B;;;;uDAImD;IACnD,UAAU,EAAE,CACV,KAAK,EAAE,cAAc,EACrB,OAAO,EAAE,OAAO,EAChB,QAAQ,EAAE,QAAQ,KACf,OAAO,CAAC,IAAI,CAAC,CAAC;CACpB;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAsB,2BAA2B,CAC/C,MAAM,EAAE,mBAAmB,GAC1B,OAAO,CAAC,oBAAoB,CAAC,CA2P/B"}
package/dist/testing.cjs CHANGED
@@ -1,5 +1,6 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const D=require("@playwright/test"),s=require("node:fs"),R=require("pixelmatch"),x=require("pngjs"),O=require("node:path"),G=require("./index-C6uYPRmx.cjs");function I(e,t){const n=x.PNG.sync.read(e),r=x.PNG.sync.read(t);if(n.width!==r.width||n.height!==r.height)return{diffPixels:1/0,diffImage:null};const i=new x.PNG({width:n.width,height:n.height});return{diffPixels:R(n.data,r.data,i.data,n.width,n.height,{threshold:.1}),diffImage:x.PNG.sync.write(i)}}const U="http://json-schema.org/draft-07/schema#",K="https://github.com/borderux/recursica/tree/main/packages/adapter-tester/src/golden/manifest.schema.json",V="test/golden/manifest.json",J="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.",W="object",X={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."}}},H={$schema:U,$id:K,title:V,description:J,type:W,additionalProperties:X},z=G.index,N=new G.ajvExports.Ajv({allErrors:!0,strict:!0});z(N);const F=N.compile(H);function E(e,t){if(F(e))return;const n=(F.errors??[]).map(r=>{var c;const i=(c=r.params)!=null&&c.additionalProperty?` '${r.params.additionalProperty}'`:"";return` - ${r.instancePath||"root"} ${r.message}${i}`}).join(`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const L=require("@playwright/test"),i=require("node:fs"),H=require("pixelmatch"),b=require("pngjs"),P=require("node:path"),R=require("./index-C6uYPRmx.cjs");function _(e,t){const n=b.PNG.sync.read(e),r=b.PNG.sync.read(t);if(n.width!==r.width||n.height!==r.height)return{diffPixels:1/0,diffImage:null};const o=new b.PNG({width:n.width,height:n.height});return{diffPixels:H(n.data,r.data,o.data,n.width,n.height,{threshold:.1}),diffImage:b.PNG.sync.write(o)}}const z="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:z,$id:Y,title:Q,description:Z,type:ee,additionalProperties:te},ne=R.index,J=new R.ajvExports.Ajv({allErrors:!0,strict:!0});ne(J);const q=J.compile(re);function N(e,t){if(q(e))return;const n=(q.errors??[]).map(r=>{var a;const o=(a=r.params)!=null&&a.additionalProperty?` '${r.params.additionalProperty}'`:"";return` - ${r.instancePath||"root"} ${r.message}${o}`}).join(`
2
2
  `);throw new Error(`Invalid ${t}:
3
- ${n}`)}function b(e){return O.join(e,"manifest.json")}function C(e){return O.join(e,"manifest.json.lock")}function T(e,t){return O.join(e,`${t}.png`)}function $(e){const t=b(e);if(!s.existsSync(t))return{};const n=JSON.parse(s.readFileSync(t,"utf8"));return E(n,t),n}function Y(e,t){const n=b(e);E(t,n);const r={};for(const c of Object.keys(t).sort())r[c]=t[c];s.mkdirSync(e,{recursive:!0});const i=`${n}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;s.writeFileSync(i,JSON.stringify(r,null,2)+`
4
- `),s.renameSync(i,n)}const Q=25,Z=15e3;function ee(e){return new Promise(t=>setTimeout(t,e))}async function te(e){s.mkdirSync(e,{recursive:!0});const t=C(e),n=Date.now()+Z;for(;;)try{s.closeSync(s.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 ee(Q)}}function re(e){s.rmSync(C(e),{force:!0})}async function L(e,t,n){await te(e);try{const r=$(e),i=n(r[t]);return i===void 0?delete r[t]:r[t]=i,Y(e,r),i}finally{re(e)}}function ne(e,t,n){s.mkdirSync(e,{recursive:!0}),s.writeFileSync(T(e,t),n)}async function ie(e,t){const n=$(e),r=Object.keys(n).filter(i=>!t.has(i));for(const i of r){const c=T(e,i);s.existsSync(c)&&s.unlinkSync(c),await L(e,i,()=>{})}return r}const se="borderux/recursica";async function oe(e,t){var c,u;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(),i=((c=r["dist-tags"])==null?void 0:c[t])??((u=r.versions)!=null&&u[t]?t:void 0);if(!i)throw new Error(`${e} has no version or dist-tag "${t}" on the npm registry.`);return i}function ae(e){return`packages/${e.split("/").pop()}`}async function ce(e){if(e.type==="local")return s.existsSync(b(e.dir))?{manifest:$(e.dir),async readImage(d){const f=T(e.dir,d);return s.existsSync(f)?s.readFileSync(f):null}}:(console.warn(`No golden baseline found yet at ${e.dir} — source-of-truth divergence check skipped for this run.`),null);let t;try{t=await oe(e.packageName,e.versionSpec)}catch(a){return console.warn(`Could not resolve ${e.packageName}@${e.versionSpec} — source-of-truth divergence check skipped for this run.`,a),null}const n=O.join(e.cacheDir,t),r=`${e.packageName}@${t}`,i=`https://raw.githubusercontent.com/${se}/${r}/${ae(e.packageName)}/test/golden`;let c;const u=b(n);if(s.existsSync(u))c=$(n);else{let a;try{a=await fetch(`${i}/manifest.json`)}catch(h){return console.warn(`Could not reach GitHub to fetch ${r}'s golden baseline — source-of-truth divergence check skipped for this run.`,h),null}if(!a.ok)return console.warn(`No golden baseline published for ${r} — source-of-truth divergence check skipped for this run.`),null;const d=await a.text(),f=JSON.parse(d);E(f,`${i}/manifest.json`),s.mkdirSync(n,{recursive:!0}),s.writeFileSync(u,d),c=f}return{manifest:c,async readImage(a){const d=T(n,a);if(s.existsSync(d))return s.readFileSync(d);const f=await fetch(`${i}/${a}.png`);if(!f.ok)return null;const h=Buffer.from(await f.arrayBuffer());return s.mkdirSync(n,{recursive:!0}),s.writeFileSync(d,h),h}}}const de=["Theme","Tokens","Introduction"];function _(e,t){return e===t||e.startsWith(t)}async function ue(e,t,n){let r;try{const i=await fetch(`${e.url}/index.json`);if(!i.ok)throw new Error(`Failed to fetch Storybook index: ${i.statusText}`);const u=(await i.json()).entries||{};r=Object.values(u).filter(a=>a.type==="story"&&!t.some(d=>a.title===d||a.title.startsWith(`${d}/`))&&!n.some(d=>_(a.id,d))),r.sort((a,d)=>a.id.localeCompare(d.id))}catch(i){throw console.error("Failed to load Storybook index from",`${e.url}/index.json`,i),new Error(`Storybook target "${e.name}" is not responsive or index.json is missing. Please ensure its Storybook is running.`)}return r}function fe(e,t,n){let r;for(const i of Object.keys(t))_(e,i)&&(!r||i.length>r.length)&&(r=i);return r!==void 0?t[r]:n}async function he(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??de,r=e.stories??{},i=Object.keys(r).filter(o=>r[o].exclude),c=Object.fromEntries(Object.entries(r).filter(([,o])=>o.threshold!==void 0).map(([o,y])=>[o,y.threshold])),u=e.goldenDir,a=e.goldenMode,d=e.checkMode,f=await ue(t,n,i);if(a==="update-golden"){const o=await ie(u,new Set(f.map(y=>y.id)));o.length>0&&console.warn(`Pruned ${o.length} orphaned golden(s) no longer in Storybook: ${o.join(", ")}`)}const h=d!=="divergence"||e.isSourceOfTruthAdapter||!e.sourceOfTruthGolden?null:await ce(e.sourceOfTruthGolden),B=d==="divergence"?"Source-of-Truth Divergence Check":"Own-Drift Golden Image Check";return{ownTargetName:t.name,suiteLabel:B,stories:f,checkStory:async(o,y,l)=>{const v=await y.newPage();await v.setViewportSize({width:800,height:600}),await v.goto(`${t.url}/iframe.html?id=${o.id}&viewMode=story`,{waitUntil:"networkidle"}),await v.waitForSelector("#storybook-root"),await v.waitForTimeout(300);const P=await v.screenshot(),j=T(u,o.id),p=$(u)[o.id],q=a!=="check"||!p||!s.existsSync(j);let w;if(q)ne(u,o.id,P),w=p!=null&&p.sourceOfTruthCreatedAt?{createdAt:new Date().toISOString(),sourceOfTruthCreatedAt:p.sourceOfTruthCreatedAt}:{createdAt:new Date().toISOString()},p||l.annotations.push({type:"golden-created",description:`No golden existed yet for "${o.id}" — captured one from this run.`});else if(w=p,d==="own"){const g=s.readFileSync(j),{diffPixels:m,diffImage:S}=I(P,g),k=fe(o.id,c,e.diffThresholdPixels);m>=k&&(await l.attach("expected",{body:g,contentType:"image/png"}),await l.attach("actual",{body:P,contentType:"image/png"}),S&&await l.attach("diff",{body:S,contentType:"image/png"})),D.expect.soft(m,`"${o.id}" has drifted from its own golden image (${m} mismatched pixels, threshold ${k})`).toBeLessThan(k)}if(h){const g=h.manifest[o.id],m=g?await h.readImage(o.id):null;if(g&&m)if(a==="approve-divergence")w={...w,sourceOfTruthCreatedAt:g.createdAt};else{const S=s.readFileSync(j),{diffPixels:k,diffImage:A}=I(S,m),M=w.sourceOfTruthCreatedAt;k===0||M!==void 0&&M>=g.createdAt||(await l.attach("expected",{body:m,contentType:"image/png"}),await l.attach("actual",{body:S,contentType:"image/png"}),A&&await l.attach("diff",{body:A,contentType:"image/png"}),l.annotations.push({type:"source-of-truth-divergence",description:`"${o.id}" differs from the source of truth's golden and hasn't been reviewed — run with --approve-divergence if this is intentional, or fix the adapter styling.`}))}}await L(u,o.id,()=>w)}}}exports.resolveVisualRegressionPlan=he;
3
+ ${n}`)}function j(e){return P.join(e,"manifest.json")}function U(e){return P.join(e,"manifest.json.lock")}function k(e,t){return P.join(e,`${t}.png`)}function x(e){const t=j(e);if(!i.existsSync(t))return{};const n=JSON.parse(i.readFileSync(t,"utf8"));return N(n,t),n}function se(e,t){const n=j(e);N(t,n);const r={};for(const a of Object.keys(t).sort())r[a]=t[a];i.mkdirSync(e,{recursive:!0});const o=`${n}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;i.writeFileSync(o,JSON.stringify(r,null,2)+`
4
+ `),i.renameSync(o,n)}const oe=25,ie=15e3;function ae(e){return new Promise(t=>setTimeout(t,e))}async function ce(e){i.mkdirSync(e,{recursive:!0});const t=U(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(oe)}}function de(e){i.rmSync(U(e),{force:!0})}async function K(e,t,n){await ce(e);try{const r=x(e),o=n(r[t]);return o===void 0?delete r[t]:r[t]=o,se(e,r),o}finally{de(e)}}function ue(e,t,n){i.mkdirSync(e,{recursive:!0}),i.writeFileSync(k(e,t),n)}async function he(e,t){const n=x(e),r=Object.keys(n).filter(o=>!t.has(o));for(const o of r){const a=k(e,o);i.existsSync(a)&&i.unlinkSync(a),await K(e,o,()=>{})}return r}const le="borderux/recursica";async function fe(e,t){var a,u;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(),o=((a=r["dist-tags"])==null?void 0:a[t])??((u=r.versions)!=null&&u[t]?t:void 0);if(!o)throw new Error(`${e} has no version or dist-tag "${t}" on the npm registry.`);return o}function pe(e){return`packages/${e.split("/").pop()}`}async function ge(e){if(e.type==="local")return i.existsSync(j(e.dir))?{manifest:x(e.dir),async readImage(h){const d=k(e.dir,h);return i.existsSync(d)?i.readFileSync(d):null}}:(console.warn(`No golden baseline found yet at ${e.dir} — source-of-truth divergence check skipped for this run.`),null);let t;try{t=await fe(e.packageName,e.versionSpec)}catch(c){return console.warn(`Could not resolve ${e.packageName}@${e.versionSpec} — source-of-truth divergence check skipped for this run.`,c),null}const n=P.join(e.cacheDir,t),r=`${e.packageName}@${t}`,o=`https://raw.githubusercontent.com/${le}/${r}/${pe(e.packageName)}/test/golden`;let a;const u=j(n);if(i.existsSync(u))a=x(n);else{let c;try{c=await fetch(`${o}/manifest.json`)}catch(p){return console.warn(`Could not reach GitHub to fetch ${r}'s golden baseline — source-of-truth divergence check skipped for this run.`,p),null}if(!c.ok)return console.warn(`No golden baseline published for ${r} — source-of-truth divergence check skipped for this run.`),null;const h=await c.text(),d=JSON.parse(h);N(d,`${o}/manifest.json`),i.mkdirSync(n,{recursive:!0}),i.writeFileSync(u,h),a=d}return{manifest:a,async readImage(c){const h=k(n,c);if(i.existsSync(h))return i.readFileSync(h);const d=await fetch(`${o}/${c}.png`);if(!d.ok)return null;const p=Buffer.from(await d.arrayBuffer());return i.mkdirSync(n,{recursive:!0}),i.writeFileSync(h,p),p}}}const me=["Theme","Tokens","Introduction"];function I(e,t){return e===t||e.startsWith(t)}async function we(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 a=(await r.json()).entries||{};n=Object.values(a).filter(u=>u.type==="story"&&!t.some(c=>u.title===c||u.title.startsWith(`${c}/`))),n.sort((u,c)=>u.id.localeCompare(c.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 D(e,t,n){let r;for(const o of Object.keys(t))I(e,o)&&(!r||o.length>r.length)&&(r=o);return r!==void 0?t[r]:n}async function ye(e){const t=e.isSourceOfTruthAdapter?e.targets[0]:e.targets.find(s=>!s.sourceOfTruth);if(!t)throw new Error("adapter-tester config has no non-sourceOfTruth target to run the golden check against.");const n=e.excludeTitlePrefixes??me,r=e.stories??{},o=Object.keys(r).filter(s=>r[s].exclude),a=Object.fromEntries(Object.entries(r).filter(([,s])=>s.goldenThreshold!==void 0).map(([s,l])=>[s,l.goldenThreshold])),u=Object.fromEntries(Object.entries(r).filter(([,s])=>s.sourceOfTruthThreshold!==void 0).map(([s,l])=>[s,l.sourceOfTruthThreshold])),c=e.goldenDir,h=e.goldenMode,d=e.checkMode,p=await we(t,n),E=p.filter(s=>!o.some(l=>I(s.id,l)));if(h==="update-golden"){const s=await he(c,new Set(E.map(l=>l.id)));s.length>0&&console.warn(`Pruned ${s.length} orphaned golden(s) no longer in Storybook: ${s.join(", ")}`)}const g=d!=="divergence"||e.isSourceOfTruthAdapter||!e.sourceOfTruthGolden?null:await ge(e.sourceOfTruthGolden),V=new Set(p.map(s=>s.id)),T=g?Object.keys(g.manifest).filter(s=>!V.has(s)&&!o.some(l=>I(s,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"?"this project's golden vs source-of-truth's golden":"live render vs this project's own golden"})`,`[adapter-tester] goldenMode: "${h}"`,`[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?g?`[adapter-tester] sourceOfTruthGolden: resolved, ${Object.keys(g.manifest).length} golden(s) available (config: ${JSON.stringify(e.sourceOfTruthGolden)})`:`[adapter-tester] sourceOfTruthGolden: unavailable — no baseline found or unreachable (config: ${JSON.stringify(e.sourceOfTruthGolden)}); divergence check will skip every story`:"[adapter-tester] sourceOfTruthGolden: skipped — no sourceOfTruthGolden configured":'[adapter-tester] sourceOfTruthGolden: not used in "own" checkMode',`[adapter-tester] stories: ${E.length} to check (excluded: ${o.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
+ `));const W=d==="divergence"?"Source-of-Truth Divergence Check":"Own-Drift Golden Image Check";return{ownTargetName:t.name,suiteLabel:W,stories:E,missingFromSourceOfTruth:T,checkStory:async(s,l,f)=>{const S=await l.newPage();await S.setViewportSize({width:800,height:600}),await S.goto(`${t.url}/iframe.html?id=${s.id}&viewMode=story`,{waitUntil:"networkidle"}),await S.waitForSelector("#storybook-root"),await S.waitForTimeout(300);const G=await S.screenshot(),A=k(c,s.id),m=x(c)[s.id],X=h!=="check"||!m||!i.existsSync(A);let $;if(X)ue(c,s.id,G),$=m!=null&&m.sourceOfTruthCreatedAt?{createdAt:new Date().toISOString(),sourceOfTruthCreatedAt:m.sourceOfTruthCreatedAt}:{createdAt:new Date().toISOString()},m||f.annotations.push({type:"golden-created",description:`No golden existed yet for "${s.id}" — captured one from this run.`});else if($=m,d==="own"){const w=i.readFileSync(A),{diffPixels:y,diffImage:O}=_(G,w),v=D(s.id,a,e.goldenThresholdPixels);y>=v&&(await f.attach("expected",{body:w,contentType:"image/png"}),await f.attach("actual",{body:G,contentType:"image/png"}),O&&await f.attach("diff",{body:O,contentType:"image/png"})),L.expect.soft(y,`"${s.id}" has drifted from its own golden image (${y} mismatched pixels, threshold ${v})`).toBeLessThan(v)}if(g){const w=g.manifest[s.id],y=w?await g.readImage(s.id):null;if(w&&y)if(h==="approve-divergence")$={...$,sourceOfTruthCreatedAt:w.createdAt};else{const O=i.readFileSync(A),{diffPixels:v,diffImage:F}=_(O,y),M=D(s.id,u,e.sourceOfTruthThresholdPixels),C=$.sourceOfTruthCreatedAt,B=v<M||C!==void 0&&C>=w.createdAt;B||(await f.attach("expected",{body:y,contentType:"image/png"}),await f.attach("actual",{body:O,contentType:"image/png"}),F&&await f.attach("diff",{body:F,contentType:"image/png"}),f.annotations.push({type:"source-of-truth-divergence",description:`"${s.id}" differs from the source of truth's golden by ${v} mismatched pixels (threshold ${M}) and hasn't been reviewed — run with --approve-divergence if this is intentional, or fix the adapter styling.`})),L.expect.soft(B,`"${s.id}" differs from the source of truth's golden by ${v} mismatched pixels (threshold ${M}) and hasn't been reviewed — run with --approve-divergence if this is intentional, or fix the adapter styling.`).toBe(!0)}}await K(c,s.id,()=>$)}}}exports.resolveVisualRegressionPlan=ye;
5
6
  //# sourceMappingURL=testing.cjs.map
@@ -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\nconst GITHUB_REPO = \"borderux/recursica\";\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// This monorepo's packages all live at `packages/<unscoped-name>` — mirrors\n// the same convention `mantineSourceOfTruthHarness` and every existing\n// `packages/*/package.json`'s `repository.directory` field already assume.\nfunction packageDirectory(packageName: string): string {\n return `packages/${packageName.split(\"/\").pop()}`;\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 * Returns `null` — degrading the divergence check to a skip, not a failure —\n * when no golden baseline exists yet for this version, or the registry/repo\n * is unreachable.\n */\nexport async function resolveSourceOfTruthGolden(\n location: SourceOfTruthGoldenLocation,\n): Promise<SourceOfTruthGolden | null> {\n if (location.type === \"local\") {\n if (!existsSync(manifestPath(location.dir))) {\n console.warn(\n `No golden baseline found yet at ${location.dir} — source-of-truth divergence check skipped for this run.`,\n );\n return null;\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 console.warn(\n `Could not resolve ${location.packageName}@${location.versionSpec} — source-of-truth divergence check skipped for this run.`,\n error,\n );\n return null;\n }\n\n const cacheDir = join(location.cacheDir, version);\n const tag = `${location.packageName}@${version}`;\n const rawBase = `https://raw.githubusercontent.com/${GITHUB_REPO}/${tag}/${packageDirectory(location.packageName)}/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 console.warn(\n `Could not reach GitHub to fetch ${tag}'s golden baseline — source-of-truth divergence check skipped for this run.`,\n error,\n );\n return null;\n }\n if (!response.ok) {\n console.warn(\n `No golden baseline published for ${tag} — source-of-truth divergence check skipped for this run.`,\n );\n return null;\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\nasync function fetchStories(\n target: { name: string; url: string },\n excludeTitlePrefixes: string[],\n excludeStoryIds: 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 !excludeStoryIds.some((prefix) => matchesPrefix(entry.id, prefix)),\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 * `diffThresholdPixels` when nothing matches. */\nfunction resolveThreshold(\n storyId: string,\n storyThresholds: Record<string, number>,\n diffThresholdPixels: 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 : diffThresholdPixels;\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 of\n * which boots the source-of-truth adapter's own Storybook — the divergence\n * check below compares stored golden files, not live pages:\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\"`; soft flag,\n * never fails the run):** this project's own golden vs the\n * source-of-truth's golden (`config`'s `sourceOfTruthGolden`). Skipped\n * entirely when `config.isSourceOfTruthAdapter` is true — the\n * source-of-truth adapter has nothing above it to diverge from — and\n * skipped per-story when neither side has a baseline yet. A\n * 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 storyThresholds = Object.fromEntries(\n Object.entries(storyOverrides)\n .filter(([, override]) => override.threshold !== undefined)\n .map(([id, override]) => [id, override.threshold!]),\n );\n const goldenDir = config.goldenDir;\n const goldenMode = config.goldenMode;\n const checkMode = config.checkMode;\n\n const stories = await fetchStories(\n ownTarget,\n excludeTitlePrefixes,\n excludeStoryIds,\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 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 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.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 storyThresholds,\n config.diffThresholdPixels,\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 const ownImage = readFileSync(imagePath);\n const { diffPixels, diffImage } = diffPngBuffers(\n ownImage,\n sourceOfTruthImage,\n );\n const approvedAt = currentEntry.sourceOfTruthCreatedAt;\n const isKnownDivergence =\n diffPixels === 0 ||\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: ownImage,\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 and hasn't been reviewed — run with --approve-divergence if this is intentional, or fix the adapter styling.`,\n });\n }\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","packageDirectory","resolveSourceOfTruthGolden","location","version","cacheDir","tag","rawBase","cachedManifestPath","text","parsed","cachedImagePath","DEFAULT_EXCLUDE_TITLE_PREFIXES","matchesPrefix","prefix","fetchStories","target","excludeTitlePrefixes","excludeStoryIds","stories","entries","entry","resolveThreshold","storyThresholds","diffThresholdPixels","bestMatch","resolveVisualRegressionPlan","config","ownTarget","storyOverrides","override","goldenMode","checkMode","prunedStoryIds","story","sourceOfTruthGolden","suiteLabel","browser","testInfo","page","liveBuffer","capturingNewGolden","currentEntry","goldenBuffer","diffPixels","diffImage","threshold","expect","sourceOfTruthEntry","sourceOfTruthImage","ownImage","approvedAt"],"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,MA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GACNX,EACAI,EAAO,mBAAA,EAELiB,GAAcE,IAChB,MAAMR,EAAS,OAAO,WAAY,CAChC,KAAMK,EACN,YAAa,WAAA,CACd,EACD,MAAML,EAAS,OAAO,SAAU,CAC9B,KAAME,EACN,YAAa,WAAA,CACd,EACGK,GACF,MAAMP,EAAS,OAAO,OAAQ,CAC5B,KAAMO,EACN,YAAa,WAAA,CACd,GAGLE,EAAAA,OACG,KACCH,EACA,IAAIV,EAAM,EAAE,4CAA4CU,CAAU,iCAAiCE,CAAS,GAAA,EAE7G,aAAaA,CAAS,CAC3B,CAGF,GAAIX,EAAqB,CACvB,MAAMa,EAAqBb,EAAoB,SAASD,EAAM,EAAE,EAC1De,EAAqBD,EACvB,MAAMb,EAAoB,UAAUD,EAAM,EAAE,EAC5C,KAEJ,GAAIc,GAAsBC,EACxB,GAAIlB,IAAe,qBACjBW,EAAe,CACb,GAAGA,EACH,uBAAwBM,EAAmB,SAAA,MAExC,CACL,MAAME,EAAWvF,EAAAA,aAAa6B,CAAS,EACjC,CAAE,WAAAoD,EAAY,UAAAC,CAAA,EAAc/G,EAChCoH,EACAD,CAAA,EAEIE,EAAaT,EAAa,uBAE9BE,IAAe,GACdO,IAAe,QACdA,GAAcH,EAAmB,YAEnC,MAAMV,EAAS,OAAO,WAAY,CAChC,KAAMW,EACN,YAAa,WAAA,CACd,EACD,MAAMX,EAAS,OAAO,SAAU,CAC9B,KAAMY,EACN,YAAa,WAAA,CACd,EACGL,GACF,MAAMP,EAAS,OAAO,OAAQ,CAC5B,KAAMO,EACN,YAAa,WAAA,CACd,EAEHP,EAAS,YAAY,KAAK,CACxB,KAAM,6BACN,YAAa,IAAIJ,EAAM,EAAE,0JAAA,CAC1B,EAEL,CAEJ,CAKA,MAAMnD,EAAoB3B,EAAW8E,EAAM,GAAI,IAAMQ,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\nconst GITHUB_REPO = \"borderux/recursica\";\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// This monorepo's packages all live at `packages/<unscoped-name>` — mirrors\n// the same convention `mantineSourceOfTruthHarness` and every existing\n// `packages/*/package.json`'s `repository.directory` field already assume.\nfunction packageDirectory(packageName: string): string {\n return `packages/${packageName.split(\"/\").pop()}`;\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 * Returns `null` — degrading the divergence check to a skip, not a failure —\n * when no golden baseline exists yet for this version, or the registry/repo\n * is unreachable.\n */\nexport async function resolveSourceOfTruthGolden(\n location: SourceOfTruthGoldenLocation,\n): Promise<SourceOfTruthGolden | null> {\n if (location.type === \"local\") {\n if (!existsSync(manifestPath(location.dir))) {\n console.warn(\n `No golden baseline found yet at ${location.dir} — source-of-truth divergence check skipped for this run.`,\n );\n return null;\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 console.warn(\n `Could not resolve ${location.packageName}@${location.versionSpec} — source-of-truth divergence check skipped for this run.`,\n error,\n );\n return null;\n }\n\n const cacheDir = join(location.cacheDir, version);\n const tag = `${location.packageName}@${version}`;\n const rawBase = `https://raw.githubusercontent.com/${GITHUB_REPO}/${tag}/${packageDirectory(location.packageName)}/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 console.warn(\n `Could not reach GitHub to fetch ${tag}'s golden baseline — source-of-truth divergence check skipped for this run.`,\n error,\n );\n return null;\n }\n if (!response.ok) {\n console.warn(\n `No golden baseline published for ${tag} — source-of-truth divergence check skipped for this run.`,\n );\n return null;\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 of\n * which boots the source-of-truth adapter's own Storybook — the divergence\n * check below compares stored golden files, not live pages:\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 project's own golden vs the source-of-truth's golden (`config`'s\n * `sourceOfTruthGolden`). Skipped entirely when\n * `config.isSourceOfTruthAdapter` is true — the\n * source-of-truth adapter has nothing above it to diverge from — and\n * skipped per-story when neither side has a baseline yet. A\n * 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\" ? \"this project's golden 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 : sourceOfTruthGolden\n ? `[adapter-tester] sourceOfTruthGolden: resolved, ${Object.keys(sourceOfTruthGolden.manifest).length} golden(s) available (config: ${JSON.stringify(config.sourceOfTruthGolden)})`\n : `[adapter-tester] sourceOfTruthGolden: unavailable — no baseline found or unreachable (config: ${JSON.stringify(config.sourceOfTruthGolden)}); divergence check will skip every story`\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.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 const ownImage = readFileSync(imagePath);\n const { diffPixels, diffImage } = diffPngBuffers(\n ownImage,\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: ownImage,\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","packageDirectory","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","liveBuffer","capturingNewGolden","currentEntry","goldenBuffer","diffPixels","diffImage","threshold","expect","sourceOfTruthEntry","sourceOfTruthImage","ownImage","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,KAAK,MAAME,CAAI,CAAA,CACrD,mrCCzBME,GAAcC,EAAAA,MAGdC,EAAM,IAAIC,EAAAA,WAAAA,IAAI,CAAE,UAAW,GAAM,OAAQ,GAAM,EACrDH,GAAWE,CAAG,EACd,MAAME,EAAWF,EAAI,QAAQG,EAAM,EAO5B,SAASC,EAAuBC,EAAeC,EAAoB,CACxE,GAAIJ,EAASG,CAAI,EAAG,OAEpB,MAAME,GAAUL,EAAS,QAAU,CAAA,GAChC,IAAKM,GAAU,OACd,MAAMC,GAAQC,EAAAF,EAAM,SAAN,MAAAE,EAAc,mBACxB,KAAKF,EAAM,OAAO,kBAAkB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