@storybook/addon-vitest 0.0.0-pr-32905-sha-03386401 → 0.0.0-pr-32717-sha-77751994

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.
@@ -1,33 +1,29 @@
1
- import CJS_COMPAT_NODE_URL_65os5sh7j3n from 'node:url';
2
- import CJS_COMPAT_NODE_PATH_65os5sh7j3n from 'node:path';
3
- import CJS_COMPAT_NODE_MODULE_65os5sh7j3n from "node:module";
1
+ import CJS_COMPAT_NODE_URL_41ip4wg3fbb from 'node:url';
2
+ import CJS_COMPAT_NODE_PATH_41ip4wg3fbb from 'node:path';
3
+ import CJS_COMPAT_NODE_MODULE_41ip4wg3fbb from "node:module";
4
4
 
5
- var __filename = CJS_COMPAT_NODE_URL_65os5sh7j3n.fileURLToPath(import.meta.url);
6
- var __dirname = CJS_COMPAT_NODE_PATH_65os5sh7j3n.dirname(__filename);
7
- var require = CJS_COMPAT_NODE_MODULE_65os5sh7j3n.createRequire(import.meta.url);
5
+ var __filename = CJS_COMPAT_NODE_URL_41ip4wg3fbb.fileURLToPath(import.meta.url);
6
+ var __dirname = CJS_COMPAT_NODE_PATH_41ip4wg3fbb.dirname(__filename);
7
+ var require = CJS_COMPAT_NODE_MODULE_41ip4wg3fbb.createRequire(import.meta.url);
8
8
 
9
9
  // ------------------------------------------------------------
10
10
  // end of CJS compatibility banner, injected by Storybook's esbuild configuration
11
11
  // ------------------------------------------------------------
12
12
  import {
13
- execa,
14
13
  resolvePackageDir
15
- } from "./_node-chunks/chunk-XWLWNIP6.js";
14
+ } from "./_node-chunks/chunk-HEOEWXF6.js";
16
15
  import {
17
- any,
18
- getAddonNames,
19
- up
20
- } from "./_node-chunks/chunk-RUDA5N3P.js";
16
+ any
17
+ } from "./_node-chunks/chunk-THQKN44K.js";
21
18
  import {
22
- DOCUMENTATION_LINK,
23
- SUPPORTED_FRAMEWORKS
24
- } from "./_node-chunks/chunk-DZV25OSU.js";
19
+ DOCUMENTATION_LINK
20
+ } from "./_node-chunks/chunk-VVCT3VD2.js";
25
21
  import {
26
22
  dirname,
27
23
  join,
28
24
  relative,
29
25
  resolve
30
- } from "./_node-chunks/chunk-JXPTXSYX.js";
26
+ } from "./_node-chunks/chunk-RKUPODUD.js";
31
27
  import {
32
28
  require_compare,
33
29
  require_constants,
@@ -37,12 +33,12 @@ import {
37
33
  require_parse_options,
38
34
  require_re,
39
35
  require_semver
40
- } from "./_node-chunks/chunk-KP25QVKF.js";
36
+ } from "./_node-chunks/chunk-PSGKZP6M.js";
41
37
  import {
42
38
  __commonJS,
43
39
  __name,
44
40
  __toESM
45
- } from "./_node-chunks/chunk-E2P6GXK6.js";
41
+ } from "./_node-chunks/chunk-S7YRH6YW.js";
46
42
 
47
43
  // ../../node_modules/semver/functions/parse.js
48
44
  var require_parse = __commonJS({
@@ -364,7 +360,7 @@ var require_coerce = __commonJS({
364
360
  var SemVer = require_semver();
365
361
  var parse = require_parse();
366
362
  var { safeRe: re, t } = require_re();
367
- var coerce2 = /* @__PURE__ */ __name((version, options) => {
363
+ var coerce = /* @__PURE__ */ __name((version, options) => {
368
364
  if (version instanceof SemVer) {
369
365
  return version;
370
366
  }
@@ -399,7 +395,7 @@ var require_coerce = __commonJS({
399
395
  const build = options.includePrerelease && match[6] ? `+${match[6]}` : "";
400
396
  return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options);
401
397
  }, "coerce");
402
- module.exports = coerce2;
398
+ module.exports = coerce;
403
399
  }
404
400
  });
405
401
 
@@ -1444,7 +1440,7 @@ var require_semver2 = __commonJS({
1444
1440
  var gte = require_gte();
1445
1441
  var lte = require_lte();
1446
1442
  var cmp = require_cmp();
1447
- var coerce2 = require_coerce();
1443
+ var coerce = require_coerce();
1448
1444
  var Comparator = require_comparator();
1449
1445
  var Range = require_range();
1450
1446
  var satisfies2 = require_satisfies();
@@ -1482,7 +1478,7 @@ var require_semver2 = __commonJS({
1482
1478
  gte,
1483
1479
  lte,
1484
1480
  cmp,
1485
- coerce: coerce2,
1481
+ coerce,
1486
1482
  Comparator,
1487
1483
  Range,
1488
1484
  satisfies: satisfies2,
@@ -1513,56 +1509,23 @@ var require_semver2 = __commonJS({
1513
1509
  import { existsSync } from "node:fs";
1514
1510
  import * as fs2 from "node:fs/promises";
1515
1511
  import { writeFile } from "node:fs/promises";
1516
- import { isAbsolute, posix, sep } from "node:path";
1517
- import { fileURLToPath, pathToFileURL } from "node:url";
1518
- import { babelParse, generate, traverse } from "storybook/internal/babel";
1512
+ import { babelParse, generate } from "storybook/internal/babel";
1513
+ import { AddonVitestService } from "storybook/internal/cli";
1519
1514
  import {
1520
1515
  JsPackageManagerFactory,
1521
1516
  formatFileContent,
1522
- getInterpretedFile,
1523
1517
  getProjectRoot,
1524
- isCI as isCI2,
1525
- loadMainConfig,
1526
- scanAndTransformFiles,
1527
- transformImportFiles
1518
+ getStorybookInfo
1528
1519
  } from "storybook/internal/common";
1529
- import { experimental_loadStorybook } from "storybook/internal/core-server";
1530
- import { readConfig, writeConfig } from "storybook/internal/csf-tools";
1531
- import { logger as logger2 } from "storybook/internal/node-logger";
1532
-
1533
- // ../../node_modules/empathic/package.mjs
1534
- function up2(options) {
1535
- return up("package.json", options);
1536
- }
1537
- __name(up2, "up");
1538
-
1539
- // src/postinstall.ts
1520
+ import { CLI_COLORS } from "storybook/internal/node-logger";
1521
+ import {
1522
+ AddonVitestPostinstallError,
1523
+ AddonVitestPostinstallPrerequisiteCheckError
1524
+ } from "storybook/internal/server-errors";
1525
+ import { SupportedFramework } from "storybook/internal/types";
1540
1526
  var import_semver = __toESM(require_semver2(), 1);
1541
- import prompts from "prompts";
1542
1527
  import { dedent } from "ts-dedent";
1543
1528
 
1544
- // src/postinstall-logger.ts
1545
- import { isCI } from "storybook/internal/common";
1546
- import { colors, logger } from "storybook/internal/node-logger";
1547
- var fancy = process.platform !== "win32" || isCI() || process.env.TERM === "xterm-256color";
1548
- var step = colors.gray("\u203A");
1549
- var info = colors.blue(fancy ? "\u2139" : "i");
1550
- var success = colors.green(fancy ? "\u2714" : "\u221A");
1551
- var warning = colors.orange(fancy ? "\u26A0" : "\u203C");
1552
- var error = colors.red(fancy ? "\u2716" : "\xD7");
1553
- var baseOptions = {
1554
- borderStyle: "round",
1555
- padding: 1
1556
- };
1557
- var print = /* @__PURE__ */ __name((message, options) => {
1558
- logger.line(1);
1559
- logger.logBox(message, { ...baseOptions, ...options });
1560
- }, "print");
1561
- var printInfo = /* @__PURE__ */ __name((title, message, options) => print(message, { borderColor: "blue", title, ...options }), "printInfo");
1562
- var printWarning = /* @__PURE__ */ __name((title, message, options) => print(message, { borderColor: "yellow", title, ...options }), "printWarning");
1563
- var printError = /* @__PURE__ */ __name((title, message, options) => print(message, { borderColor: "red", title, ...options }), "printError");
1564
- var printSuccess = /* @__PURE__ */ __name((title, message, options) => print(message, { borderColor: "green", title, ...options }), "printSuccess");
1565
-
1566
1529
  // src/updateVitestFile.ts
1567
1530
  import * as fs from "node:fs/promises";
1568
1531
  var loadTemplate = /* @__PURE__ */ __name(async (name, replacements) => {
@@ -1771,274 +1734,133 @@ var updateWorkspaceFile = /* @__PURE__ */ __name((source, target) => {
1771
1734
  var ADDON_NAME = "@storybook/addon-vitest";
1772
1735
  var EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".cts", ".mts", ".cjs", ".mjs"];
1773
1736
  var addonA11yName = "@storybook/addon-a11y";
1774
- var hasErrors = false;
1775
- function nameMatches(name, pattern) {
1776
- if (name === pattern) {
1777
- return true;
1778
- }
1779
- if (name.includes(`${pattern}${sep}`)) {
1780
- return true;
1781
- }
1782
- if (name.includes(`${pattern}${posix.sep}`)) {
1783
- return true;
1784
- }
1785
- return false;
1786
- }
1787
- __name(nameMatches, "nameMatches");
1788
- var logErrors = /* @__PURE__ */ __name((...args) => {
1789
- hasErrors = true;
1790
- printError(...args);
1791
- }, "logErrors");
1792
- var findFile = /* @__PURE__ */ __name((basename, extensions = EXTENSIONS) => any(
1793
- extensions.map((ext) => basename + ext),
1794
- { last: getProjectRoot() }
1795
- ), "findFile");
1796
1737
  async function postInstall(options) {
1797
- printSuccess(
1798
- "\u{1F44B} Howdy!",
1799
- dedent`
1800
- I'm the installation helper for ${ADDON_NAME}
1801
-
1802
- Hold on for a moment while I look at your project and get it set up...
1803
- `
1804
- );
1738
+ const errors = [];
1739
+ const { logger, prompt } = options;
1805
1740
  const packageManager = JsPackageManagerFactory.getPackageManager({
1806
1741
  force: options.packageManager
1807
1742
  });
1743
+ const findFile = /* @__PURE__ */ __name((basename, extensions = EXTENSIONS) => any(
1744
+ extensions.map((ext) => basename + ext),
1745
+ { last: getProjectRoot(), cwd: options.configDir }
1746
+ ), "findFile");
1808
1747
  const vitestVersionSpecifier = await packageManager.getInstalledVersion("vitest");
1809
- const coercedVitestVersion = vitestVersionSpecifier ? (0, import_semver.coerce)(vitestVersionSpecifier) : null;
1810
1748
  const isVitest3_2To4 = vitestVersionSpecifier ? (0, import_semver.satisfies)(vitestVersionSpecifier, ">=3.2.0 <4.0.0") : false;
1811
1749
  const isVitest4OrNewer = vitestVersionSpecifier ? (0, import_semver.satisfies)(vitestVersionSpecifier, ">=4.0.0") : true;
1812
- const info2 = await getStorybookInfo(options);
1750
+ const info = await getStorybookInfo(options.configDir);
1813
1751
  const allDeps = packageManager.getAllDependencies();
1814
- const dependencies = [
1815
- "vitest",
1816
- "playwright",
1817
- isVitest4OrNewer ? "@vitest/browser-playwright" : "@vitest/browser"
1818
- ];
1819
- const uniqueDependencies = dependencies.filter((p) => !allDeps[p]);
1820
- const mainJsPath = getInterpretedFile(resolve(options.configDir, "main"));
1821
- const config = await readConfig(mainJsPath);
1822
- const hasCustomWebpackConfig = !!config.getFieldNode(["webpackFinal"]);
1823
- const isInteractive = process.stdout.isTTY && !isCI2();
1824
- if (nameMatches(info2.frameworkPackageName, "@storybook/nextjs") && !hasCustomWebpackConfig) {
1825
- const out = options.yes || !isInteractive ? { migrateToNextjsVite: !!options.yes } : await prompts({
1826
- type: "confirm",
1827
- name: "migrateToNextjsVite",
1828
- message: dedent`
1829
- The addon requires the use of @storybook/nextjs-vite to work with Next.js.
1830
- https://storybook.js.org/docs/next/${DOCUMENTATION_LINK}#install-and-set-up
1752
+ const addonVitestService = new AddonVitestService();
1753
+ const compatibilityResult = await addonVitestService.validateCompatibility({
1754
+ packageManager,
1755
+ framework: info.framework,
1756
+ builder: info.builder
1757
+ });
1758
+ let result = null;
1759
+ if (!compatibilityResult.compatible && compatibilityResult.reasons) {
1760
+ const reasons = compatibilityResult.reasons.map((r) => `\u2022 ${CLI_COLORS.error(r)}`);
1761
+ reasons.unshift(dedent`
1762
+ Automated setup failed
1763
+ We have found incompatibilities due to the following package incompatibilities:
1764
+ `);
1765
+ reasons.push(
1766
+ dedent`
1767
+ You can fix these issues and rerun the command to reinstall. If you wish to roll back the installation, remove ${ADDON_NAME} from the "addons" array
1768
+ in your main Storybook config file and remove the dependency from your package.json file.
1831
1769
 
1832
- Do you want to migrate?
1833
- `,
1834
- initial: true
1770
+ Please check the documentation for more information about its requirements and installation:
1771
+ https://storybook.js.org/docs/next/${DOCUMENTATION_LINK}
1772
+ `
1773
+ );
1774
+ result = reasons.map((r) => r.trim()).join("\n\n");
1775
+ }
1776
+ if (result) {
1777
+ logger.error(result);
1778
+ throw new AddonVitestPostinstallPrerequisiteCheckError({
1779
+ reasons: compatibilityResult.reasons
1835
1780
  });
1836
- if (out.migrateToNextjsVite) {
1837
- await packageManager.addDependencies({ type: "devDependencies", skipInstall: true }, [
1838
- "@storybook/nextjs-vite"
1839
- ]);
1840
- await packageManager.removeDependencies(["@storybook/nextjs"]);
1841
- traverse(config._ast, {
1842
- StringLiteral(path) {
1843
- if (path.node.value === "@storybook/nextjs") {
1844
- path.node.value = "@storybook/nextjs-vite";
1845
- }
1846
- }
1847
- });
1848
- await writeConfig(config, mainJsPath);
1849
- info2.frameworkPackageName = "@storybook/nextjs-vite";
1850
- info2.builderPackageName = "@storybook/builder-vite";
1851
- await scanAndTransformFiles({
1852
- promptMessage: "Enter a glob to scan for all @storybook/nextjs imports to substitute with @storybook/nextjs-vite:",
1853
- force: options.yes,
1854
- dryRun: false,
1855
- transformFn: /* @__PURE__ */ __name((files, options2, dryRun) => transformImportFiles(files, options2, dryRun), "transformFn"),
1856
- transformOptions: {
1857
- "@storybook/nextjs": "@storybook/nextjs-vite"
1858
- }
1859
- });
1860
- }
1861
1781
  }
1862
- const annotationsImport = SUPPORTED_FRAMEWORKS.find(
1863
- (f) => nameMatches(info2.frameworkPackageName, f)
1864
- ) ? info2.frameworkPackageName === "@storybook/nextjs" ? "@storybook/nextjs-vite" : info2.frameworkPackageName : null;
1865
- const isRendererSupported = !!annotationsImport;
1866
- const prerequisiteCheck = /* @__PURE__ */ __name(async () => {
1867
- const reasons = [];
1868
- if (hasCustomWebpackConfig) {
1869
- reasons.push("\u2022 The addon can not be used with a custom Webpack configuration.");
1870
- }
1871
- if (!nameMatches(info2.frameworkPackageName, "@storybook/nextjs") && !nameMatches(info2.builderPackageName, "@storybook/builder-vite")) {
1872
- reasons.push(
1873
- "\u2022 The addon can only be used with a Vite-based Storybook framework or Next.js."
1874
- );
1875
- }
1876
- if (!isRendererSupported) {
1877
- reasons.push(dedent`
1878
- • The addon cannot yet be used with ${info2.frameworkPackageName}
1879
- `);
1880
- }
1881
- if (coercedVitestVersion && !(0, import_semver.satisfies)(coercedVitestVersion, ">=3.0.0")) {
1882
- reasons.push(dedent`
1883
- • The addon requires Vitest 3.0.0 or higher. You are currently using ${vitestVersionSpecifier}.
1884
- Please update all of your Vitest dependencies and try again.
1885
- `);
1886
- }
1887
- const mswVersionSpecifier = await packageManager.getInstalledVersion("msw");
1888
- const coercedMswVersion = mswVersionSpecifier ? (0, import_semver.coerce)(mswVersionSpecifier) : null;
1889
- if (coercedMswVersion && !(0, import_semver.satisfies)(coercedMswVersion, ">=2.0.0")) {
1890
- reasons.push(dedent`
1891
- • The addon uses Vitest behind the scenes, which supports only version 2 and above of MSW. However, we have detected version ${coercedMswVersion.version} in this project.
1892
- Please update the 'msw' package and try again.
1893
- `);
1894
- }
1895
- if (nameMatches(info2.frameworkPackageName, "@storybook/nextjs")) {
1896
- const nextVersion = await packageManager.getInstalledVersion("next");
1897
- if (!nextVersion) {
1898
- reasons.push(dedent`
1899
- • You are using @storybook/nextjs without having "next" installed.
1900
- Please install "next" or use a different Storybook framework integration and try again.
1901
- `);
1782
+ if (!options.skipDependencyManagement) {
1783
+ const versionedDependencies = await addonVitestService.collectDependencies(packageManager);
1784
+ if (info.framework === SupportedFramework.NEXTJS) {
1785
+ const allDeps2 = packageManager.getAllDependencies();
1786
+ if (!allDeps2["@storybook/nextjs-vite"]) {
1902
1787
  }
1903
1788
  }
1904
- if (reasons.length > 0) {
1905
- reasons.unshift(
1906
- `@storybook/addon-vitest's automated setup failed due to the following package incompatibilities:`
1907
- );
1908
- reasons.push("--------------------------------");
1909
- reasons.push(
1789
+ const v8Version = await packageManager.getInstalledVersion("@vitest/coverage-v8");
1790
+ const istanbulVersion = await packageManager.getInstalledVersion("@vitest/coverage-istanbul");
1791
+ if (!v8Version && !istanbulVersion) {
1792
+ logger.step(
1910
1793
  dedent`
1911
- You can fix these issues and rerun the command to reinstall. If you wish to roll back the installation, remove ${ADDON_NAME} from the "addons" array
1912
- in your main Storybook config file and remove the dependency from your package.json file.
1794
+ You don't seem to have a coverage reporter installed. Vitest needs either V8 or Istanbul to generate coverage reports.
1795
+
1796
+ Adding "@vitest/coverage-v8" to enable coverage reporting.
1797
+ Read more about Vitest coverage providers at https://vitest.dev/guide/coverage.html#coverage-providers
1913
1798
  `
1914
1799
  );
1915
- if (!isRendererSupported) {
1916
- reasons.push(
1917
- dedent`
1918
- Please check the documentation for more information about its requirements and installation:
1919
- https://storybook.js.org/docs/next/${DOCUMENTATION_LINK}
1920
- `
1921
- );
1922
- } else {
1923
- reasons.push(
1924
- dedent`
1925
- Fear not, however, you can follow the manual installation process instead at:
1926
- https://storybook.js.org/docs/next/${DOCUMENTATION_LINK}#manual-setup
1927
- `
1928
- );
1929
- }
1930
- return reasons.map((r) => r.trim()).join("\n\n");
1931
1800
  }
1932
- return null;
1933
- }, "prerequisiteCheck");
1934
- const result = await prerequisiteCheck();
1935
- if (result) {
1936
- logErrors("\u26D4\uFE0F Sorry!", result);
1937
- logger2.line(1);
1938
- return;
1939
- }
1940
- if (info2.frameworkPackageName === "@storybook/nextjs") {
1941
- printInfo(
1942
- "\u{1F37F} Just so you know...",
1943
- dedent`
1944
- It looks like you're using Next.js.
1945
-
1946
- Adding "@storybook/nextjs-vite/vite-plugin" so you can use it with Vitest.
1947
-
1948
- More info about the plugin at https://github.com/storybookjs/vite-plugin-storybook-nextjs
1949
- `
1950
- );
1951
- try {
1952
- const storybookVersion = await packageManager.getInstalledVersion("storybook");
1953
- uniqueDependencies.push(`@storybook/nextjs-vite@^${storybookVersion}`);
1954
- } catch (e) {
1955
- console.error("Failed to install @storybook/nextjs-vite. Please install it manually");
1801
+ if (versionedDependencies.length > 0) {
1802
+ logger.step("Adding dependencies to your package.json");
1803
+ logger.log(" " + versionedDependencies.join(", "));
1804
+ await packageManager.addDependencies(
1805
+ { type: "devDependencies", skipInstall: true },
1806
+ versionedDependencies
1807
+ );
1956
1808
  }
1957
- }
1958
- const v8Version = await packageManager.getInstalledVersion("@vitest/coverage-v8");
1959
- const istanbulVersion = await packageManager.getInstalledVersion("@vitest/coverage-istanbul");
1960
- if (!v8Version && !istanbulVersion) {
1961
- printInfo(
1962
- "\u{1F648} Let me cover this for you",
1963
- dedent`
1964
- You don't seem to have a coverage reporter installed. Vitest needs either V8 or Istanbul to generate coverage reports.
1965
-
1966
- Adding "@vitest/coverage-v8" to enable coverage reporting.
1967
- Read more about Vitest coverage providers at https://vitest.dev/guide/coverage.html#coverage-providers
1968
- `
1969
- );
1970
- uniqueDependencies.push(`@vitest/coverage-v8`);
1971
- }
1972
- const versionedDependencies = uniqueDependencies.map((p) => {
1973
- if (p.includes("vitest")) {
1974
- return vitestVersionSpecifier ? `${p}@${vitestVersionSpecifier}` : p;
1809
+ if (!options.skipInstall) {
1810
+ await packageManager.installDependencies();
1975
1811
  }
1976
- return p;
1977
- });
1978
- if (versionedDependencies.length > 0) {
1979
- await packageManager.addDependencies(
1980
- { type: "devDependencies", skipInstall: true },
1981
- versionedDependencies
1982
- );
1983
- logger2.line(1);
1984
- logger2.plain(`${step} Installing dependencies:`);
1985
- logger2.plain(" " + versionedDependencies.join(", "));
1986
1812
  }
1987
- await packageManager.installDependencies();
1988
- logger2.line(1);
1989
- if (options.skipInstall) {
1990
- logger2.plain("Skipping Playwright installation, please run this command manually:");
1991
- logger2.plain(" npx playwright install chromium --with-deps");
1992
- } else {
1993
- logger2.plain(`${step} Configuring Playwright with Chromium (this might take some time):`);
1994
- logger2.plain(" npx playwright install chromium --with-deps");
1995
- try {
1996
- await packageManager.executeCommand({
1997
- command: "npx",
1998
- args: ["playwright", "install", "chromium", "--with-deps"]
1813
+ if (!options.skipDependencyManagement) {
1814
+ if (!options.skipInstall) {
1815
+ const playwrightErrors = await addonVitestService.installPlaywright(packageManager, {
1816
+ yes: options.yes
1999
1817
  });
2000
- } catch (e) {
2001
- console.error("Failed to install Playwright. Please install it manually");
1818
+ errors.push(...playwrightErrors);
1819
+ } else {
1820
+ logger.warn(dedent`
1821
+ Playwright browser binaries installation skipped. Please run the following command manually later:
1822
+ ${CLI_COLORS.cta("npx playwright install chromium --with-deps")}
1823
+ `);
2002
1824
  }
2003
1825
  }
2004
1826
  const fileExtension = allDeps.typescript || findFile("tsconfig", [...EXTENSIONS, ".json"]) ? "ts" : "js";
2005
1827
  const vitestSetupFile = resolve(options.configDir, `vitest.setup.${fileExtension}`);
2006
1828
  if (existsSync(vitestSetupFile)) {
2007
- logErrors(
2008
- "\u{1F6A8} Oh no!",
2009
- dedent`
2010
- Found an existing Vitest setup file:
2011
- ${vitestSetupFile}
2012
-
2013
- Please refer to the documentation to complete the setup manually:
2014
- https://storybook.js.org/docs/next/${DOCUMENTATION_LINK}#manual-setup
2015
- `
1829
+ const errorMessage = dedent`
1830
+ Found an existing Vitest setup file:
1831
+ ${vitestSetupFile}
1832
+ Please refer to the documentation to complete the setup manually:
1833
+ https://storybook.js.org/docs/next/${DOCUMENTATION_LINK}#manual-setup
1834
+ `;
1835
+ logger.line();
1836
+ logger.error(`${errorMessage}
1837
+ `);
1838
+ errors.push("Found existing Vitest setup file");
1839
+ } else {
1840
+ logger.step(`Creating a Vitest setup file for Storybook:`);
1841
+ logger.log(`${vitestSetupFile}
1842
+ `);
1843
+ const previewExists = EXTENSIONS.map((ext) => resolve(options.configDir, `preview${ext}`)).some(
1844
+ existsSync
2016
1845
  );
2017
- logger2.line(1);
2018
- return;
2019
- }
2020
- logger2.line(1);
2021
- logger2.plain(`${step} Creating a Vitest setup file for Storybook:`);
2022
- logger2.plain(` ${vitestSetupFile}`);
2023
- const previewExists = EXTENSIONS.map((ext) => resolve(options.configDir, `preview${ext}`)).some(
2024
- existsSync
2025
- );
2026
- const imports = [`import { setProjectAnnotations } from '${annotationsImport}';`];
2027
- const projectAnnotations = [];
2028
- if (previewExists) {
2029
- imports.push(`import * as projectAnnotations from './preview';`);
2030
- projectAnnotations.push("projectAnnotations");
2031
- }
2032
- await writeFile(
2033
- vitestSetupFile,
2034
- dedent`
1846
+ const annotationsImport = info.frameworkPackage;
1847
+ const imports = [`import { setProjectAnnotations } from '${annotationsImport}';`];
1848
+ const projectAnnotations = [];
1849
+ if (previewExists) {
1850
+ imports.push(`import * as projectAnnotations from './preview';`);
1851
+ projectAnnotations.push("projectAnnotations");
1852
+ }
1853
+ await writeFile(
1854
+ vitestSetupFile,
1855
+ dedent`
2035
1856
  ${imports.join("\n")}
2036
1857
 
2037
1858
  // This is an important step to apply the right configuration when testing your stories.
2038
1859
  // More info at: https://storybook.js.org/docs/api/portable-stories/portable-stories-vitest#setprojectannotations
2039
1860
  setProjectAnnotations([${projectAnnotations.join(", ")}]);
2040
1861
  `
2041
- );
1862
+ );
1863
+ }
2042
1864
  const vitestWorkspaceFile = findFile("vitest.workspace", [".ts", ".js", ".json"]);
2043
1865
  const viteConfigFile = findFile("vite.config");
2044
1866
  const vitestConfigFile = findFile("vitest.config");
@@ -2070,14 +1892,12 @@ async function postInstall(options) {
2070
1892
  const target = babelParse(workspaceFile);
2071
1893
  const updated = updateWorkspaceFile(source, target);
2072
1894
  if (updated) {
2073
- logger2.line(1);
2074
- logger2.plain(`${step} Updating your Vitest workspace file:`);
2075
- logger2.plain(` ${vitestWorkspaceFile}`);
1895
+ logger.step(`Updating your Vitest workspace file...`);
1896
+ logger.log(`${vitestWorkspaceFile}`);
2076
1897
  const formattedContent = await formatFileContent(vitestWorkspaceFile, generate(target).code);
2077
1898
  await writeFile(vitestWorkspaceFile, formattedContent);
2078
1899
  } else {
2079
- logErrors(
2080
- "\u{1F6A8} Oh no!",
1900
+ logger.error(
2081
1901
  dedent`
2082
1902
  Could not update existing Vitest workspace file:
2083
1903
  ${vitestWorkspaceFile}
@@ -2089,8 +1909,7 @@ async function postInstall(options) {
2089
1909
  https://storybook.js.org/docs/next/${DOCUMENTATION_LINK}#manual-setup
2090
1910
  `
2091
1911
  );
2092
- logger2.line(1);
2093
- return;
1912
+ errors.push("Unable to update existing Vitest workspace file");
2094
1913
  }
2095
1914
  } else if (rootConfig) {
2096
1915
  let target, updated;
@@ -2109,9 +1928,8 @@ async function postInstall(options) {
2109
1928
  updated = updateConfigFile(source, target);
2110
1929
  }
2111
1930
  if (target && updated) {
2112
- logger2.line(1);
2113
- logger2.plain(`${step} Updating your ${vitestConfigFile ? "Vitest" : "Vite"} config file:`);
2114
- logger2.plain(` ${rootConfig}`);
1931
+ logger.step(`Updating your ${vitestConfigFile ? "Vitest" : "Vite"} config file:`);
1932
+ logger.log(` ${rootConfig}`);
2115
1933
  const formattedContent = await formatFileContent(rootConfig, generate(target).code);
2116
1934
  const shouldAddReference = !configFileHasTypeReference && !vitestConfigFile;
2117
1935
  await writeFile(
@@ -2119,139 +1937,90 @@ async function postInstall(options) {
2119
1937
  shouldAddReference ? '/// <reference types="vitest/config" />\n' + formattedContent : formattedContent
2120
1938
  );
2121
1939
  } else {
2122
- logErrors(
2123
- "\u{1F6A8} Oh no!",
2124
- dedent`
1940
+ logger.error(dedent`
2125
1941
  We were unable to update your existing ${vitestConfigFile ? "Vitest" : "Vite"} config file.
2126
1942
 
2127
1943
  Please refer to the documentation to complete the setup manually:
2128
1944
  https://storybook.js.org/docs/writing-tests/integrations/vitest-addon#manual-setup
2129
- `
2130
- );
1945
+ `);
1946
+ errors.push("Unable to update existing Vitest config file");
2131
1947
  }
2132
1948
  } else {
2133
- const newConfigFile = resolve(`vitest.config.${fileExtension}`);
1949
+ const parentDir = dirname(options.configDir);
1950
+ const newConfigFile = resolve(parentDir, `vitest.config.${fileExtension}`);
2134
1951
  const configTemplate = await loadTemplate(getTemplateName(), {
2135
1952
  CONFIG_DIR: options.configDir,
2136
1953
  SETUP_FILE: relative(dirname(newConfigFile), vitestSetupFile)
2137
1954
  });
2138
- logger2.line(1);
2139
- logger2.plain(`${step} Creating a Vitest config file:`);
2140
- logger2.plain(` ${newConfigFile}`);
1955
+ logger.step(`Creating a Vitest config file:`);
1956
+ logger.log(`${newConfigFile}`);
2141
1957
  const formattedContent = await formatFileContent(newConfigFile, configTemplate);
2142
1958
  await writeFile(newConfigFile, formattedContent);
2143
1959
  }
2144
- const a11yAddon = info2.addons.find((addon) => addon.includes(addonA11yName));
1960
+ const a11yAddon = info.addons.find((addon) => addon.includes(addonA11yName));
2145
1961
  if (a11yAddon) {
2146
1962
  try {
2147
- logger2.plain(`${step} Setting up ${addonA11yName} for @storybook/addon-vitest:`);
2148
- await execa(
2149
- "storybook",
2150
- [
2151
- "automigrate",
2152
- "addon-a11y-addon-test",
2153
- "--loglevel",
2154
- "silent",
2155
- "--yes",
2156
- "--skip-doctor",
2157
- ...options.packageManager ? ["--package-manager", options.packageManager] : [],
2158
- ...options.skipInstall ? ["--skip-install"] : [],
2159
- ...options.configDir !== ".storybook" ? ["--config-dir", `"${options.configDir}"`] : []
2160
- ],
1963
+ const command = ["automigrate", "addon-a11y-addon-test"];
1964
+ command.push("--loglevel", "silent");
1965
+ command.push("--yes", "--skip-doctor");
1966
+ if (options.packageManager) {
1967
+ command.push("--package-manager", options.packageManager);
1968
+ }
1969
+ if (options.skipInstall) {
1970
+ command.push("--skip-install");
1971
+ }
1972
+ if (options.configDir !== ".storybook") {
1973
+ command.push("--config-dir", `"${options.configDir}"`);
1974
+ }
1975
+ const remoteCommand = packageManager.getRemoteRunCommand("storybook", command);
1976
+ const [cmd, ...args] = remoteCommand.split(" ");
1977
+ await prompt.executeTask(
1978
+ // TODO: Remove stdio: 'ignore' once we have a way to log the output of the command properly
1979
+ () => packageManager.executeCommand({ command: cmd, args, stdio: "ignore" }),
2161
1980
  {
2162
- stdio: "inherit"
1981
+ intro: "Setting up a11y addon for @storybook/addon-vitest",
1982
+ error: "Failed to setup a11y addon for @storybook/addon-vitest",
1983
+ success: "a11y addon setup successfully"
2163
1984
  }
2164
1985
  );
2165
1986
  } catch (e) {
2166
- logErrors(
2167
- "\u{1F6A8} Oh no!",
2168
- dedent`
2169
- We have detected that you have ${addonA11yName} installed but could not automatically set it up for @storybook/addon-vitest:
2170
-
2171
- ${e instanceof Error ? e.message : String(e)}
2172
-
1987
+ logger.line();
1988
+ logger.error(dedent`
1989
+ Could not automatically set up ${addonA11yName} for @storybook/addon-vitest.
2173
1990
  Please refer to the documentation to complete the setup manually:
2174
1991
  https://storybook.js.org/docs/writing-tests/accessibility-testing#test-addon-integration
2175
- `
1992
+ `);
1993
+ errors.push(
1994
+ "The @storybook/addon-a11y couldn't be set up for the Vitest addon" + (e instanceof Error ? e.stack : String(e))
2176
1995
  );
2177
1996
  }
2178
1997
  }
2179
1998
  const runCommand = rootConfig ? `npx vitest --project=storybook` : `npx vitest`;
2180
- if (!hasErrors) {
2181
- printSuccess(
2182
- "\u{1F389} All done!",
2183
- dedent`
1999
+ logger.line();
2000
+ if (errors.length === 0) {
2001
+ logger.step(CLI_COLORS.success("@storybook/addon-vitest setup completed successfully"));
2002
+ logger.log(dedent`
2184
2003
  @storybook/addon-vitest is now configured and you're ready to run your tests!
2185
-
2186
2004
  Here are a couple of tips to get you started:
2187
- • You can run tests with "${runCommand}"
2188
- When using the Vitest extension in your editor, all of your stories will be shown as tests!
2189
-
2005
+
2006
+ You can run tests with "${CLI_COLORS.cta(runCommand)}"
2007
+ • Vitest IDE extension shows all stories as tests in your editor!
2008
+
2190
2009
  Check the documentation for more information about its features and options at:
2191
2010
  https://storybook.js.org/docs/next/${DOCUMENTATION_LINK}
2192
- `
2193
- );
2011
+ `);
2194
2012
  } else {
2195
- printWarning(
2196
- "\u26A0\uFE0F Done, but with errors!",
2013
+ logger.warn(
2197
2014
  dedent`
2198
- @storybook/addon-vitest was installed successfully, but there were some errors during the setup process.
2199
-
2200
- Please refer to the documentation to complete the setup manually and check the errors above:
2015
+ Done, but with errors!
2016
+ @storybook/addon-vitest was installed successfully, but there were some errors during the setup process. Please refer to the documentation to complete the setup manually and check the errors above:
2201
2017
  https://storybook.js.org/docs/next/${DOCUMENTATION_LINK}#manual-setup
2202
2018
  `
2203
2019
  );
2020
+ throw new AddonVitestPostinstallError({ errors });
2204
2021
  }
2205
- logger2.line(1);
2206
2022
  }
2207
2023
  __name(postInstall, "postInstall");
2208
- async function getPackageNameFromPath(input) {
2209
- const path = input.startsWith("file://") ? fileURLToPath(input) : input;
2210
- if (!isAbsolute(path)) {
2211
- return path;
2212
- }
2213
- const packageJsonPath = up2({ cwd: path });
2214
- if (!packageJsonPath) {
2215
- throw new Error(`Could not find package.json in path: ${path}`);
2216
- }
2217
- const { default: packageJson } = await import(pathToFileURL(packageJsonPath).href, {
2218
- with: { type: "json" }
2219
- });
2220
- return packageJson.name;
2221
- }
2222
- __name(getPackageNameFromPath, "getPackageNameFromPath");
2223
- async function getStorybookInfo({ configDir, packageManager: pkgMgr }) {
2224
- const packageManager = JsPackageManagerFactory.getPackageManager({ force: pkgMgr, configDir });
2225
- const { packageJson } = packageManager.primaryPackageJson;
2226
- const config = await loadMainConfig({ configDir });
2227
- const { presets } = await experimental_loadStorybook({
2228
- configDir,
2229
- packageJson
2230
- });
2231
- const framework = await presets.apply("framework", {});
2232
- const core = await presets.apply("core", {});
2233
- const { builder, renderer } = core;
2234
- if (!builder) {
2235
- throw new Error("Could not detect your Storybook builder.");
2236
- }
2237
- const frameworkPackageName = await getPackageNameFromPath(
2238
- typeof framework === "string" ? framework : framework.name
2239
- );
2240
- const builderPackageName = await getPackageNameFromPath(
2241
- typeof builder === "string" ? builder : builder.name
2242
- );
2243
- let rendererPackageName;
2244
- if (renderer) {
2245
- rendererPackageName = await getPackageNameFromPath(renderer);
2246
- }
2247
- return {
2248
- frameworkPackageName,
2249
- builderPackageName,
2250
- rendererPackageName,
2251
- addons: getAddonNames(config)
2252
- };
2253
- }
2254
- __name(getStorybookInfo, "getStorybookInfo");
2255
2024
  export {
2256
2025
  postInstall as default
2257
2026
  };