@storybook/addon-vitest 0.0.0-pr-32874-sha-fd398904 → 0.0.0-pr-32921-sha-16b7aab0

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_x7l8djn52xj from 'node:url';
2
- import CJS_COMPAT_NODE_PATH_x7l8djn52xj from 'node:path';
3
- import CJS_COMPAT_NODE_MODULE_x7l8djn52xj from "node:module";
1
+ import CJS_COMPAT_NODE_URL_6px7swmj8pe from 'node:url';
2
+ import CJS_COMPAT_NODE_PATH_6px7swmj8pe from 'node:path';
3
+ import CJS_COMPAT_NODE_MODULE_6px7swmj8pe from "node:module";
4
4
 
5
- var __filename = CJS_COMPAT_NODE_URL_x7l8djn52xj.fileURLToPath(import.meta.url);
6
- var __dirname = CJS_COMPAT_NODE_PATH_x7l8djn52xj.dirname(__filename);
7
- var require = CJS_COMPAT_NODE_MODULE_x7l8djn52xj.createRequire(import.meta.url);
5
+ var __filename = CJS_COMPAT_NODE_URL_6px7swmj8pe.fileURLToPath(import.meta.url);
6
+ var __dirname = CJS_COMPAT_NODE_PATH_6px7swmj8pe.dirname(__filename);
7
+ var require = CJS_COMPAT_NODE_MODULE_6px7swmj8pe.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-75RHCDJA.js";
14
+ } from "./_node-chunks/chunk-IVUROXNL.js";
16
15
  import {
17
- any,
18
- getAddonNames,
19
- up
20
- } from "./_node-chunks/chunk-ATWWQSYY.js";
16
+ any
17
+ } from "./_node-chunks/chunk-ZJEXRKEJ.js";
21
18
  import {
22
- DOCUMENTATION_LINK,
23
- SUPPORTED_FRAMEWORKS
24
- } from "./_node-chunks/chunk-5EGXS55U.js";
19
+ DOCUMENTATION_LINK
20
+ } from "./_node-chunks/chunk-ITGNSETM.js";
25
21
  import {
26
22
  dirname,
27
23
  join,
28
24
  relative,
29
25
  resolve
30
- } from "./_node-chunks/chunk-ZIYTWRWN.js";
26
+ } from "./_node-chunks/chunk-YT4V4DMB.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-44SFLJBP.js";
36
+ } from "./_node-chunks/chunk-WPTT6UNN.js";
41
37
  import {
42
38
  __commonJS,
43
39
  __name,
44
40
  __toESM
45
- } from "./_node-chunks/chunk-LB44Z253.js";
41
+ } from "./_node-chunks/chunk-XJAFV5RM.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) => {
@@ -1616,10 +1579,7 @@ var updateConfigFile = /* @__PURE__ */ __name((source, target) => {
1616
1579
  } else if (targetExportDefault.declaration.type === "CallExpression" && targetExportDefault.declaration.callee.type === "Identifier" && targetExportDefault.declaration.callee.name === "defineConfig" && targetExportDefault.declaration.arguments[0]?.type === "ObjectExpression") {
1617
1580
  canHandleConfig = true;
1618
1581
  } else if (targetExportDefault.declaration.type === "CallExpression" && targetExportDefault.declaration.callee.type === "Identifier" && targetExportDefault.declaration.callee.name === "mergeConfig" && targetExportDefault.declaration.arguments.length >= 2) {
1619
- const defineConfigNodes = targetExportDefault.declaration.arguments.filter(
1620
- (arg) => arg?.type === "CallExpression" && arg.callee.type === "Identifier" && arg.callee.name === "defineConfig" && arg.arguments[0]?.type === "ObjectExpression"
1621
- );
1622
- canHandleConfig = defineConfigNodes.length > 0;
1582
+ canHandleConfig = true;
1623
1583
  }
1624
1584
  if (!canHandleConfig) {
1625
1585
  return false;
@@ -1652,20 +1612,24 @@ var updateConfigFile = /* @__PURE__ */ __name((source, target) => {
1652
1612
  mergeProperties(properties, exportDefault.declaration.arguments[0].properties);
1653
1613
  updated = true;
1654
1614
  } else if (exportDefault.declaration.type === "CallExpression" && exportDefault.declaration.callee.type === "Identifier" && exportDefault.declaration.callee.name === "mergeConfig" && exportDefault.declaration.arguments.length >= 2) {
1655
- const defineConfigNodes = exportDefault.declaration.arguments.filter(
1656
- (arg) => arg?.type === "CallExpression" && arg.callee.type === "Identifier" && arg.callee.name === "defineConfig" && arg.arguments[0]?.type === "ObjectExpression"
1657
- );
1658
- const defineConfigNodeWithTest = defineConfigNodes.find(
1659
- (node) => node.arguments[0].type === "ObjectExpression" && node.arguments[0].properties.some(
1615
+ const configObjectNodes = [];
1616
+ for (const arg of exportDefault.declaration.arguments) {
1617
+ if (arg?.type === "CallExpression" && arg.callee.type === "Identifier" && arg.callee.name === "defineConfig" && arg.arguments[0]?.type === "ObjectExpression") {
1618
+ configObjectNodes.push(arg.arguments[0]);
1619
+ } else if (arg?.type === "ObjectExpression") {
1620
+ configObjectNodes.push(arg);
1621
+ }
1622
+ }
1623
+ const configObjectWithTest = configObjectNodes.find(
1624
+ (obj) => obj.properties.some(
1660
1625
  (p) => p.type === "ObjectProperty" && p.key.type === "Identifier" && p.key.name === "test"
1661
1626
  )
1662
1627
  );
1663
- const defineConfigNode = defineConfigNodeWithTest || defineConfigNodes[0];
1664
- if (!defineConfigNode) {
1628
+ const targetConfigObject = configObjectWithTest || configObjectNodes[0];
1629
+ if (!targetConfigObject) {
1665
1630
  return false;
1666
1631
  }
1667
- const defineConfigProps = defineConfigNode.arguments[0];
1668
- const existingTestProp = defineConfigProps.properties.find(
1632
+ const existingTestProp = targetConfigObject.properties.find(
1669
1633
  (p) => p.type === "ObjectProperty" && p.key.type === "Identifier" && p.key.name === "test"
1670
1634
  );
1671
1635
  if (existingTestProp && existingTestProp.value.type === "ObjectExpression") {
@@ -1677,6 +1641,16 @@ var updateConfigFile = /* @__PURE__ */ __name((source, target) => {
1677
1641
  (p) => p.type === "ObjectProperty" && p.key.type === "Identifier" && (p.key.name === "workspace" || p.key.name === "projects")
1678
1642
  );
1679
1643
  if (workspaceOrProjectsProp && workspaceOrProjectsProp.value.type === "ArrayExpression") {
1644
+ const coverageProp = existingTestProp.value.properties.find(
1645
+ (p) => p.type === "ObjectProperty" && p.key.type === "Identifier" && p.key.name === "coverage"
1646
+ );
1647
+ const testPropsWithoutCoverage = existingTestProp.value.properties.filter(
1648
+ (p) => p !== coverageProp
1649
+ );
1650
+ const testConfigForProject = {
1651
+ type: "ObjectExpression",
1652
+ properties: testPropsWithoutCoverage
1653
+ };
1680
1654
  const existingTestProject = {
1681
1655
  type: "ObjectExpression",
1682
1656
  properties: [
@@ -1690,25 +1664,28 @@ var updateConfigFile = /* @__PURE__ */ __name((source, target) => {
1690
1664
  {
1691
1665
  type: "ObjectProperty",
1692
1666
  key: { type: "Identifier", name: "test" },
1693
- value: existingTestProp.value,
1667
+ value: testConfigForProject,
1694
1668
  computed: false,
1695
1669
  shorthand: false
1696
1670
  }
1697
1671
  ]
1698
1672
  };
1699
1673
  workspaceOrProjectsProp.value.elements.unshift(existingTestProject);
1700
- defineConfigProps.properties = defineConfigProps.properties.filter(
1674
+ targetConfigObject.properties = targetConfigObject.properties.filter(
1701
1675
  (p) => p !== existingTestProp
1702
1676
  );
1703
- mergeProperties(properties, defineConfigProps.properties);
1677
+ if (coverageProp && templateTestProp.value.type === "ObjectExpression") {
1678
+ templateTestProp.value.properties.unshift(coverageProp);
1679
+ }
1680
+ mergeProperties(properties, targetConfigObject.properties);
1704
1681
  } else {
1705
- mergeProperties(properties, defineConfigProps.properties);
1682
+ mergeProperties(properties, targetConfigObject.properties);
1706
1683
  }
1707
1684
  } else {
1708
- mergeProperties(properties, defineConfigProps.properties);
1685
+ mergeProperties(properties, targetConfigObject.properties);
1709
1686
  }
1710
1687
  } else {
1711
- mergeProperties(properties, defineConfigProps.properties);
1688
+ mergeProperties(properties, targetConfigObject.properties);
1712
1689
  }
1713
1690
  updated = true;
1714
1691
  }
@@ -1757,290 +1734,156 @@ var updateWorkspaceFile = /* @__PURE__ */ __name((source, target) => {
1757
1734
  var ADDON_NAME = "@storybook/addon-vitest";
1758
1735
  var EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".cts", ".mts", ".cjs", ".mjs"];
1759
1736
  var addonA11yName = "@storybook/addon-a11y";
1760
- var hasErrors = false;
1761
- function nameMatches(name, pattern) {
1762
- if (name === pattern) {
1763
- return true;
1764
- }
1765
- if (name.includes(`${pattern}${sep}`)) {
1766
- return true;
1767
- }
1768
- if (name.includes(`${pattern}${posix.sep}`)) {
1769
- return true;
1770
- }
1771
- return false;
1772
- }
1773
- __name(nameMatches, "nameMatches");
1774
- var logErrors = /* @__PURE__ */ __name((...args) => {
1775
- hasErrors = true;
1776
- printError(...args);
1777
- }, "logErrors");
1778
- var findFile = /* @__PURE__ */ __name((basename, extensions = EXTENSIONS) => any(
1779
- extensions.map((ext) => basename + ext),
1780
- { last: getProjectRoot() }
1781
- ), "findFile");
1782
1737
  async function postInstall(options) {
1783
- printSuccess(
1784
- "\u{1F44B} Howdy!",
1785
- dedent`
1786
- I'm the installation helper for ${ADDON_NAME}
1787
-
1788
- Hold on for a moment while I look at your project and get it set up...
1789
- `
1790
- );
1738
+ const errors = [];
1739
+ const { logger, prompt } = options;
1791
1740
  const packageManager = JsPackageManagerFactory.getPackageManager({
1792
1741
  force: options.packageManager
1793
1742
  });
1794
- const info2 = await getStorybookInfo(options);
1795
- const allDeps = packageManager.getAllDependencies();
1796
- const dependencies = ["vitest", "@vitest/browser", "playwright"].filter((p) => !allDeps[p]);
1743
+ const findFile = /* @__PURE__ */ __name((basename, extensions = EXTENSIONS) => any(
1744
+ extensions.map((ext) => basename + ext),
1745
+ { last: getProjectRoot(), cwd: options.configDir }
1746
+ ), "findFile");
1797
1747
  const vitestVersionSpecifier = await packageManager.getInstalledVersion("vitest");
1798
- const coercedVitestVersion = vitestVersionSpecifier ? (0, import_semver.coerce)(vitestVersionSpecifier) : null;
1799
- const isVitest3_2OrNewer = vitestVersionSpecifier ? (0, import_semver.satisfies)(vitestVersionSpecifier, ">=3.2.0") : true;
1800
- const mainJsPath = getInterpretedFile(resolve(options.configDir, "main"));
1801
- const config = await readConfig(mainJsPath);
1802
- const hasCustomWebpackConfig = !!config.getFieldNode(["webpackFinal"]);
1803
- const isInteractive = process.stdout.isTTY && !isCI2();
1804
- if (nameMatches(info2.frameworkPackageName, "@storybook/nextjs") && !hasCustomWebpackConfig) {
1805
- const out = options.yes || !isInteractive ? { migrateToNextjsVite: !!options.yes } : await prompts({
1806
- type: "confirm",
1807
- name: "migrateToNextjsVite",
1808
- message: dedent`
1809
- The addon requires the use of @storybook/nextjs-vite to work with Next.js.
1810
- https://storybook.js.org/docs/next/${DOCUMENTATION_LINK}#install-and-set-up
1748
+ const isVitest3_2To4 = vitestVersionSpecifier ? (0, import_semver.satisfies)(vitestVersionSpecifier, ">=3.2.0 <4.0.0") : false;
1749
+ const isVitest4OrNewer = vitestVersionSpecifier ? (0, import_semver.satisfies)(vitestVersionSpecifier, ">=4.0.0") : true;
1750
+ const info = await getStorybookInfo(options.configDir);
1751
+ const allDeps = packageManager.getAllDependencies();
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.
1811
1769
 
1812
- Do you want to migrate?
1813
- `,
1814
- 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
1815
1780
  });
1816
- if (out.migrateToNextjsVite) {
1817
- await packageManager.addDependencies({ type: "devDependencies", skipInstall: true }, [
1818
- "@storybook/nextjs-vite"
1819
- ]);
1820
- await packageManager.removeDependencies(["@storybook/nextjs"]);
1821
- traverse(config._ast, {
1822
- StringLiteral(path) {
1823
- if (path.node.value === "@storybook/nextjs") {
1824
- path.node.value = "@storybook/nextjs-vite";
1825
- }
1826
- }
1827
- });
1828
- await writeConfig(config, mainJsPath);
1829
- info2.frameworkPackageName = "@storybook/nextjs-vite";
1830
- info2.builderPackageName = "@storybook/builder-vite";
1831
- await scanAndTransformFiles({
1832
- promptMessage: "Enter a glob to scan for all @storybook/nextjs imports to substitute with @storybook/nextjs-vite:",
1833
- force: options.yes,
1834
- dryRun: false,
1835
- transformFn: /* @__PURE__ */ __name((files, options2, dryRun) => transformImportFiles(files, options2, dryRun), "transformFn"),
1836
- transformOptions: {
1837
- "@storybook/nextjs": "@storybook/nextjs-vite"
1838
- }
1839
- });
1840
- }
1841
1781
  }
1842
- const annotationsImport = SUPPORTED_FRAMEWORKS.find(
1843
- (f) => nameMatches(info2.frameworkPackageName, f)
1844
- ) ? info2.frameworkPackageName === "@storybook/nextjs" ? "@storybook/nextjs-vite" : info2.frameworkPackageName : null;
1845
- const isRendererSupported = !!annotationsImport;
1846
- const prerequisiteCheck = /* @__PURE__ */ __name(async () => {
1847
- const reasons = [];
1848
- if (hasCustomWebpackConfig) {
1849
- reasons.push("\u2022 The addon can not be used with a custom Webpack configuration.");
1850
- }
1851
- if (!nameMatches(info2.frameworkPackageName, "@storybook/nextjs") && !nameMatches(info2.builderPackageName, "@storybook/builder-vite")) {
1852
- reasons.push(
1853
- "\u2022 The addon can only be used with a Vite-based Storybook framework or Next.js."
1854
- );
1855
- }
1856
- if (!isRendererSupported) {
1857
- reasons.push(dedent`
1858
- • The addon cannot yet be used with ${info2.frameworkPackageName}
1859
- `);
1860
- }
1861
- if (coercedVitestVersion && !(0, import_semver.satisfies)(coercedVitestVersion, ">=3.0.0")) {
1862
- reasons.push(dedent`
1863
- • The addon requires Vitest 3.0.0 or higher. You are currently using ${vitestVersionSpecifier}.
1864
- Please update all of your Vitest dependencies and try again.
1865
- `);
1866
- }
1867
- const mswVersionSpecifier = await packageManager.getInstalledVersion("msw");
1868
- const coercedMswVersion = mswVersionSpecifier ? (0, import_semver.coerce)(mswVersionSpecifier) : null;
1869
- if (coercedMswVersion && !(0, import_semver.satisfies)(coercedMswVersion, ">=2.0.0")) {
1870
- reasons.push(dedent`
1871
- • 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.
1872
- Please update the 'msw' package and try again.
1873
- `);
1874
- }
1875
- if (nameMatches(info2.frameworkPackageName, "@storybook/nextjs")) {
1876
- const nextVersion = await packageManager.getInstalledVersion("next");
1877
- if (!nextVersion) {
1878
- reasons.push(dedent`
1879
- • You are using @storybook/nextjs without having "next" installed.
1880
- Please install "next" or use a different Storybook framework integration and try again.
1881
- `);
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"]) {
1882
1787
  }
1883
1788
  }
1884
- if (reasons.length > 0) {
1885
- reasons.unshift(
1886
- `@storybook/addon-vitest's automated setup failed due to the following package incompatibilities:`
1887
- );
1888
- reasons.push("--------------------------------");
1889
- 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(
1890
1793
  dedent`
1891
- 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
1892
- 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
1893
1798
  `
1894
1799
  );
1895
- if (!isRendererSupported) {
1896
- reasons.push(
1897
- dedent`
1898
- Please check the documentation for more information about its requirements and installation:
1899
- https://storybook.js.org/docs/next/${DOCUMENTATION_LINK}
1900
- `
1901
- );
1902
- } else {
1903
- reasons.push(
1904
- dedent`
1905
- Fear not, however, you can follow the manual installation process instead at:
1906
- https://storybook.js.org/docs/next/${DOCUMENTATION_LINK}#manual-setup
1907
- `
1908
- );
1909
- }
1910
- return reasons.map((r) => r.trim()).join("\n\n");
1911
1800
  }
1912
- return null;
1913
- }, "prerequisiteCheck");
1914
- const result = await prerequisiteCheck();
1915
- if (result) {
1916
- logErrors("\u26D4\uFE0F Sorry!", result);
1917
- logger2.line(1);
1918
- return;
1919
- }
1920
- if (info2.frameworkPackageName === "@storybook/nextjs") {
1921
- printInfo(
1922
- "\u{1F37F} Just so you know...",
1923
- dedent`
1924
- It looks like you're using Next.js.
1925
-
1926
- Adding "@storybook/nextjs-vite/vite-plugin" so you can use it with Vitest.
1927
-
1928
- More info about the plugin at https://github.com/storybookjs/vite-plugin-storybook-nextjs
1929
- `
1930
- );
1931
- try {
1932
- const storybookVersion = await packageManager.getInstalledVersion("storybook");
1933
- dependencies.push(`@storybook/nextjs-vite@^${storybookVersion}`);
1934
- } catch (e) {
1935
- 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
+ );
1936
1808
  }
1937
- }
1938
- const v8Version = await packageManager.getInstalledVersion("@vitest/coverage-v8");
1939
- const istanbulVersion = await packageManager.getInstalledVersion("@vitest/coverage-istanbul");
1940
- if (!v8Version && !istanbulVersion) {
1941
- printInfo(
1942
- "\u{1F648} Let me cover this for you",
1943
- dedent`
1944
- You don't seem to have a coverage reporter installed. Vitest needs either V8 or Istanbul to generate coverage reports.
1945
-
1946
- Adding "@vitest/coverage-v8" to enable coverage reporting.
1947
- Read more about Vitest coverage providers at https://vitest.dev/guide/coverage.html#coverage-providers
1948
- `
1949
- );
1950
- dependencies.push(`@vitest/coverage-v8`);
1951
- }
1952
- const versionedDependencies = dependencies.map((p) => {
1953
- if (p.includes("vitest")) {
1954
- return vitestVersionSpecifier ? `${p}@${vitestVersionSpecifier}` : p;
1809
+ if (!options.skipInstall) {
1810
+ await packageManager.installDependencies();
1955
1811
  }
1956
- return p;
1957
- });
1958
- if (versionedDependencies.length > 0) {
1959
- await packageManager.addDependencies(
1960
- { type: "devDependencies", skipInstall: true },
1961
- versionedDependencies
1962
- );
1963
- logger2.line(1);
1964
- logger2.plain(`${step} Installing dependencies:`);
1965
- logger2.plain(" " + versionedDependencies.join(", "));
1966
1812
  }
1967
- await packageManager.installDependencies();
1968
- logger2.line(1);
1969
- if (options.skipInstall) {
1970
- logger2.plain("Skipping Playwright installation, please run this command manually:");
1971
- logger2.plain(" npx playwright install chromium --with-deps");
1972
- } else {
1973
- logger2.plain(`${step} Configuring Playwright with Chromium (this might take some time):`);
1974
- logger2.plain(" npx playwright install chromium --with-deps");
1975
- try {
1976
- await packageManager.executeCommand({
1977
- command: "npx",
1978
- 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
1979
1817
  });
1980
- } catch (e) {
1981
- 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
+ `);
1982
1824
  }
1983
1825
  }
1984
1826
  const fileExtension = allDeps.typescript || findFile("tsconfig", [...EXTENSIONS, ".json"]) ? "ts" : "js";
1985
1827
  const vitestSetupFile = resolve(options.configDir, `vitest.setup.${fileExtension}`);
1986
1828
  if (existsSync(vitestSetupFile)) {
1987
- logErrors(
1988
- "\u{1F6A8} Oh no!",
1989
- dedent`
1990
- Found an existing Vitest setup file:
1991
- ${vitestSetupFile}
1992
-
1993
- Please refer to the documentation to complete the setup manually:
1994
- https://storybook.js.org/docs/next/${DOCUMENTATION_LINK}#manual-setup
1995
- `
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
1996
1845
  );
1997
- logger2.line(1);
1998
- return;
1999
- }
2000
- logger2.line(1);
2001
- logger2.plain(`${step} Creating a Vitest setup file for Storybook:`);
2002
- logger2.plain(` ${vitestSetupFile}`);
2003
- const previewExists = EXTENSIONS.map((ext) => resolve(options.configDir, `preview${ext}`)).some(
2004
- existsSync
2005
- );
2006
- const imports = [`import { setProjectAnnotations } from '${annotationsImport}';`];
2007
- const projectAnnotations = [];
2008
- if (previewExists) {
2009
- imports.push(`import * as projectAnnotations from './preview';`);
2010
- projectAnnotations.push("projectAnnotations");
2011
- }
2012
- await writeFile(
2013
- vitestSetupFile,
2014
- 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`
2015
1856
  ${imports.join("\n")}
2016
1857
 
2017
1858
  // This is an important step to apply the right configuration when testing your stories.
2018
1859
  // More info at: https://storybook.js.org/docs/api/portable-stories/portable-stories-vitest#setprojectannotations
2019
1860
  setProjectAnnotations([${projectAnnotations.join(", ")}]);
2020
1861
  `
2021
- );
2022
- const vitestWorkspaceFile = findFile("vitest.workspace", [".ts", ".js", ".json"]) || findFile("vitest.projects", [".ts", ".js", ".json"]);
1862
+ );
1863
+ }
1864
+ const vitestWorkspaceFile = findFile("vitest.workspace", [".ts", ".js", ".json"]);
2023
1865
  const viteConfigFile = findFile("vite.config");
2024
1866
  const vitestConfigFile = findFile("vitest.config");
2025
1867
  const vitestShimFile = findFile("vitest.shims.d");
2026
1868
  const rootConfig = vitestConfigFile || viteConfigFile;
2027
- const browserConfig = `{
2028
- enabled: true,
2029
- headless: true,
2030
- provider: 'playwright',
2031
- instances: [{ browser: 'chromium' }]
2032
- }`;
2033
1869
  if (fileExtension === "ts" && !vitestShimFile) {
2034
1870
  await writeFile(
2035
1871
  "vitest.shims.d.ts",
2036
- '/// <reference types="@vitest/browser/providers/playwright" />'
1872
+ isVitest4OrNewer ? '/// <reference types="@vitest/browser-playwright" />' : '/// <reference types="@vitest/browser/providers/playwright" />'
2037
1873
  );
2038
1874
  }
1875
+ const getTemplateName = /* @__PURE__ */ __name(() => {
1876
+ if (isVitest4OrNewer) {
1877
+ return "vitest.config.4.template.ts";
1878
+ } else if (isVitest3_2To4) {
1879
+ return "vitest.config.3.2.template.ts";
1880
+ }
1881
+ return "vitest.config.template.ts";
1882
+ }, "getTemplateName");
2039
1883
  if (vitestWorkspaceFile) {
2040
1884
  const workspaceTemplate = await loadTemplate("vitest.workspace.template.ts", {
2041
1885
  EXTENDS_WORKSPACE: viteConfigFile ? relative(dirname(vitestWorkspaceFile), viteConfigFile) : "",
2042
1886
  CONFIG_DIR: options.configDir,
2043
- BROWSER_CONFIG: browserConfig,
2044
1887
  SETUP_FILE: relative(dirname(vitestWorkspaceFile), vitestSetupFile)
2045
1888
  }).then((t) => t.replace(`
2046
1889
  'ROOT_CONFIG',`, "").replace(/\s+extends: '',/, ""));
@@ -2049,14 +1892,12 @@ async function postInstall(options) {
2049
1892
  const target = babelParse(workspaceFile);
2050
1893
  const updated = updateWorkspaceFile(source, target);
2051
1894
  if (updated) {
2052
- logger2.line(1);
2053
- logger2.plain(`${step} Updating your Vitest workspace file:`);
2054
- logger2.plain(` ${vitestWorkspaceFile}`);
1895
+ logger.step(`Updating your Vitest workspace file...`);
1896
+ logger.log(`${vitestWorkspaceFile}`);
2055
1897
  const formattedContent = await formatFileContent(vitestWorkspaceFile, generate(target).code);
2056
1898
  await writeFile(vitestWorkspaceFile, formattedContent);
2057
1899
  } else {
2058
- logErrors(
2059
- "\u{1F6A8} Oh no!",
1900
+ logger.error(
2060
1901
  dedent`
2061
1902
  Could not update existing Vitest workspace file:
2062
1903
  ${vitestWorkspaceFile}
@@ -2068,21 +1909,18 @@ async function postInstall(options) {
2068
1909
  https://storybook.js.org/docs/next/${DOCUMENTATION_LINK}#manual-setup
2069
1910
  `
2070
1911
  );
2071
- logger2.line(1);
2072
- return;
1912
+ errors.push("Unable to update existing Vitest workspace file");
2073
1913
  }
2074
1914
  } else if (rootConfig) {
2075
1915
  let target, updated;
2076
1916
  const configFile = await fs2.readFile(rootConfig, "utf8");
2077
- const hasProjectsConfig = configFile.includes("projects:");
2078
1917
  const configFileHasTypeReference = configFile.match(
2079
1918
  /\/\/\/\s*<reference\s+types=["']vitest\/config["']\s*\/>/
2080
1919
  );
2081
- const templateName = hasProjectsConfig || isVitest3_2OrNewer ? "vitest.config.3.2.template.ts" : "vitest.config.template.ts";
1920
+ const templateName = getTemplateName();
2082
1921
  if (templateName) {
2083
1922
  const configTemplate = await loadTemplate(templateName, {
2084
1923
  CONFIG_DIR: options.configDir,
2085
- BROWSER_CONFIG: browserConfig,
2086
1924
  SETUP_FILE: relative(dirname(rootConfig), vitestSetupFile)
2087
1925
  });
2088
1926
  const source = babelParse(configTemplate);
@@ -2090,45 +1928,38 @@ async function postInstall(options) {
2090
1928
  updated = updateConfigFile(source, target);
2091
1929
  }
2092
1930
  if (target && updated) {
2093
- logger2.line(1);
2094
- logger2.plain(`${step} Updating your ${vitestConfigFile ? "Vitest" : "Vite"} config file:`);
2095
- logger2.plain(` ${rootConfig}`);
1931
+ logger.step(`Updating your ${vitestConfigFile ? "Vitest" : "Vite"} config file:`);
1932
+ logger.log(` ${rootConfig}`);
2096
1933
  const formattedContent = await formatFileContent(rootConfig, generate(target).code);
1934
+ const shouldAddReference = !configFileHasTypeReference && !vitestConfigFile;
2097
1935
  await writeFile(
2098
1936
  rootConfig,
2099
- configFileHasTypeReference ? formattedContent : '/// <reference types="vitest/config" />\n' + formattedContent
1937
+ shouldAddReference ? '/// <reference types="vitest/config" />\n' + formattedContent : formattedContent
2100
1938
  );
2101
1939
  } else {
2102
- logErrors(
2103
- "\u{1F6A8} Oh no!",
2104
- dedent`
1940
+ logger.error(dedent`
2105
1941
  We were unable to update your existing ${vitestConfigFile ? "Vitest" : "Vite"} config file.
2106
1942
 
2107
1943
  Please refer to the documentation to complete the setup manually:
2108
1944
  https://storybook.js.org/docs/writing-tests/integrations/vitest-addon#manual-setup
2109
- `
2110
- );
1945
+ `);
1946
+ errors.push("Unable to update existing Vitest config file");
2111
1947
  }
2112
1948
  } else {
2113
- const newConfigFile = resolve(`vitest.config.${fileExtension}`);
2114
- const configTemplate = await loadTemplate(
2115
- isVitest3_2OrNewer ? "vitest.config.3.2.template.ts" : "vitest.config.template.ts",
2116
- {
2117
- CONFIG_DIR: options.configDir,
2118
- BROWSER_CONFIG: browserConfig,
2119
- SETUP_FILE: relative(dirname(newConfigFile), vitestSetupFile)
2120
- }
2121
- );
2122
- logger2.line(1);
2123
- logger2.plain(`${step} Creating a Vitest config file:`);
2124
- logger2.plain(` ${newConfigFile}`);
1949
+ const parentDir = dirname(options.configDir);
1950
+ const newConfigFile = resolve(parentDir, `vitest.config.${fileExtension}`);
1951
+ const configTemplate = await loadTemplate(getTemplateName(), {
1952
+ CONFIG_DIR: options.configDir,
1953
+ SETUP_FILE: relative(dirname(newConfigFile), vitestSetupFile)
1954
+ });
1955
+ logger.step(`Creating a Vitest config file:`);
1956
+ logger.log(`${newConfigFile}`);
2125
1957
  const formattedContent = await formatFileContent(newConfigFile, configTemplate);
2126
1958
  await writeFile(newConfigFile, formattedContent);
2127
1959
  }
2128
- const a11yAddon = info2.addons.find((addon) => addon.includes(addonA11yName));
1960
+ const a11yAddon = info.addons.find((addon) => addon.includes(addonA11yName));
2129
1961
  if (a11yAddon) {
2130
1962
  try {
2131
- logger2.plain(`${step} Setting up ${addonA11yName} for @storybook/addon-vitest:`);
2132
1963
  const command = ["automigrate", "addon-a11y-addon-test"];
2133
1964
  command.push("--loglevel", "silent");
2134
1965
  command.push("--yes", "--skip-doctor");
@@ -2141,99 +1972,53 @@ async function postInstall(options) {
2141
1972
  if (options.configDir !== ".storybook") {
2142
1973
  command.push("--config-dir", `"${options.configDir}"`);
2143
1974
  }
2144
- await execa("storybook", command, {
2145
- stdio: "inherit"
2146
- });
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" }),
1980
+ {
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"
1984
+ }
1985
+ );
2147
1986
  } catch (e) {
2148
- logErrors(
2149
- "\u{1F6A8} Oh no!",
2150
- dedent`
2151
- We have detected that you have ${addonA11yName} installed but could not automatically set it up for @storybook/addon-vitest:
2152
-
2153
- ${e instanceof Error ? e.message : String(e)}
2154
-
1987
+ logger.error(dedent`
1988
+ Could not automatically set up ${addonA11yName} for @storybook/addon-vitest.
2155
1989
  Please refer to the documentation to complete the setup manually:
2156
1990
  https://storybook.js.org/docs/writing-tests/accessibility-testing#test-addon-integration
2157
- `
1991
+ `);
1992
+ errors.push(
1993
+ "The @storybook/addon-a11y couldn't be set up for the Vitest addon" + (e instanceof Error ? e.stack : String(e))
2158
1994
  );
2159
1995
  }
2160
1996
  }
2161
1997
  const runCommand = rootConfig ? `npx vitest --project=storybook` : `npx vitest`;
2162
- if (!hasErrors) {
2163
- printSuccess(
2164
- "\u{1F389} All done!",
2165
- dedent`
1998
+ if (errors.length === 0) {
1999
+ logger.step(CLI_COLORS.success("@storybook/addon-vitest setup completed successfully"));
2000
+ logger.log(dedent`
2166
2001
  @storybook/addon-vitest is now configured and you're ready to run your tests!
2167
-
2168
2002
  Here are a couple of tips to get you started:
2169
- • You can run tests with "${runCommand}"
2170
- When using the Vitest extension in your editor, all of your stories will be shown as tests!
2171
-
2003
+
2004
+ You can run tests with "${CLI_COLORS.cta(runCommand)}"
2005
+ • Vitest IDE extension shows all stories as tests in your editor!
2006
+
2172
2007
  Check the documentation for more information about its features and options at:
2173
2008
  https://storybook.js.org/docs/next/${DOCUMENTATION_LINK}
2174
- `
2175
- );
2009
+ `);
2176
2010
  } else {
2177
- printWarning(
2178
- "\u26A0\uFE0F Done, but with errors!",
2011
+ logger.warn(
2179
2012
  dedent`
2180
- @storybook/addon-vitest was installed successfully, but there were some errors during the setup process.
2181
-
2182
- Please refer to the documentation to complete the setup manually and check the errors above:
2013
+ Done, but with errors!
2014
+ @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:
2183
2015
  https://storybook.js.org/docs/next/${DOCUMENTATION_LINK}#manual-setup
2184
2016
  `
2185
2017
  );
2018
+ throw new AddonVitestPostinstallError({ errors });
2186
2019
  }
2187
- logger2.line(1);
2188
2020
  }
2189
2021
  __name(postInstall, "postInstall");
2190
- async function getPackageNameFromPath(input) {
2191
- const path = input.startsWith("file://") ? fileURLToPath(input) : input;
2192
- if (!isAbsolute(path)) {
2193
- return path;
2194
- }
2195
- const packageJsonPath = up2({ cwd: path });
2196
- if (!packageJsonPath) {
2197
- throw new Error(`Could not find package.json in path: ${path}`);
2198
- }
2199
- const { default: packageJson } = await import(pathToFileURL(packageJsonPath).href, {
2200
- with: { type: "json" }
2201
- });
2202
- return packageJson.name;
2203
- }
2204
- __name(getPackageNameFromPath, "getPackageNameFromPath");
2205
- async function getStorybookInfo({ configDir, packageManager: pkgMgr }) {
2206
- const packageManager = JsPackageManagerFactory.getPackageManager({ force: pkgMgr, configDir });
2207
- const { packageJson } = packageManager.primaryPackageJson;
2208
- const config = await loadMainConfig({ configDir });
2209
- const { presets } = await experimental_loadStorybook({
2210
- configDir,
2211
- packageJson
2212
- });
2213
- const framework = await presets.apply("framework", {});
2214
- const core = await presets.apply("core", {});
2215
- const { builder, renderer } = core;
2216
- if (!builder) {
2217
- throw new Error("Could not detect your Storybook builder.");
2218
- }
2219
- const frameworkPackageName = await getPackageNameFromPath(
2220
- typeof framework === "string" ? framework : framework.name
2221
- );
2222
- const builderPackageName = await getPackageNameFromPath(
2223
- typeof builder === "string" ? builder : builder.name
2224
- );
2225
- let rendererPackageName;
2226
- if (renderer) {
2227
- rendererPackageName = await getPackageNameFromPath(renderer);
2228
- }
2229
- return {
2230
- frameworkPackageName,
2231
- builderPackageName,
2232
- rendererPackageName,
2233
- addons: getAddonNames(config)
2234
- };
2235
- }
2236
- __name(getStorybookInfo, "getStorybookInfo");
2237
2022
  export {
2238
2023
  postInstall as default
2239
2024
  };