@storybook/addon-vitest 0.0.0-pr-32020-sha-d6522800 → 0.0.0-pr-31819-sha-dabbbfde

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.
Files changed (42) hide show
  1. package/dist/_browser-chunks/chunk-A47P2DCZ.js +11 -0
  2. package/dist/_browser-chunks/chunk-VMSW5DPM.js +60 -0
  3. package/dist/_node-chunks/chunk-C4NXJJA3.js +324 -0
  4. package/dist/_node-chunks/chunk-CIKGVIS6.js +223 -0
  5. package/dist/_node-chunks/chunk-FMQIQP6D.js +96 -0
  6. package/dist/_node-chunks/chunk-KVKHJ5OL.js +46 -0
  7. package/dist/_node-chunks/chunk-N3OFRDD3.js +80 -0
  8. package/dist/_node-chunks/chunk-VFT2PRGV.js +5002 -0
  9. package/dist/_node-chunks/chunk-W26ZMSD3.js +143 -0
  10. package/dist/_node-chunks/chunk-XWQZZ2C3.js +1586 -0
  11. package/dist/index.js +9 -6
  12. package/dist/manager.js +5571 -8
  13. package/dist/node/coverage-reporter.js +1395 -4
  14. package/dist/node/vitest.js +564 -17
  15. package/dist/postinstall.js +1162 -93
  16. package/dist/preset.js +268 -32
  17. package/dist/vitest-plugin/global-setup.js +146 -6
  18. package/dist/vitest-plugin/index.js +2589 -43
  19. package/dist/vitest-plugin/setup-file.js +28 -9
  20. package/dist/vitest-plugin/test-utils.js +68 -8
  21. package/package.json +17 -89
  22. package/static/coverage-reporter.cjs +10 -0
  23. package/dist/chunk-55WZLVGN.mjs +0 -11
  24. package/dist/chunk-JKRQGT2U.mjs +0 -10
  25. package/dist/index.mjs +0 -5
  26. package/dist/node/coverage-reporter.d.ts +0 -184
  27. package/dist/node/coverage-reporter.mjs +0 -12
  28. package/dist/node/vitest.d.ts +0 -2
  29. package/dist/node/vitest.mjs +0 -19
  30. package/dist/vitest-plugin/global-setup.d.ts +0 -6
  31. package/dist/vitest-plugin/global-setup.mjs +0 -13
  32. package/dist/vitest-plugin/index.mjs +0 -28
  33. package/dist/vitest-plugin/setup-file.d.ts +0 -14
  34. package/dist/vitest-plugin/setup-file.mjs +0 -9
  35. package/dist/vitest-plugin/test-utils.d.ts +0 -20
  36. package/dist/vitest-plugin/test-utils.mjs +0 -8
  37. package/manager.js +0 -1
  38. package/manager.mjs +0 -1
  39. package/postinstall.js +0 -1
  40. package/postinstall.mjs +0 -1
  41. package/preset.js +0 -1
  42. package/preset.mjs +0 -1
@@ -1,22 +1,569 @@
1
- 'use strict';
1
+ import CJS_COMPAT_NODE_URL from 'node:url';
2
+ import CJS_COMPAT_NODE_PATH from 'node:path';
3
+ import CJS_COMPAT_NODE_MODULE from "node:module";
2
4
 
3
- var module$1 = require('module');
4
- var process3 = require('process');
5
- var channels = require('storybook/internal/channels');
6
- var fs = require('fs');
7
- var common = require('storybook/internal/common');
8
- var path2 = require('path');
9
- var url = require('url');
5
+ const __filename = CJS_COMPAT_NODE_URL.fileURLToPath(import.meta.url);
6
+ const __dirname = CJS_COMPAT_NODE_PATH.dirname(__filename);
7
+ const require = CJS_COMPAT_NODE_MODULE.createRequire(import.meta.url);
8
+ // ------------------------------------------------------------
9
+ // end of CJS compatibility banner, injected by Storybook's esbuild configuration
10
+ // ------------------------------------------------------------
11
+ import {
12
+ a as O,
13
+ c as I
14
+ } from "../_node-chunks/chunk-VFT2PRGV.js";
15
+ import {
16
+ b as N,
17
+ c as G
18
+ } from "../_node-chunks/chunk-CIKGVIS6.js";
19
+ import {
20
+ a as k,
21
+ d as x,
22
+ f as y,
23
+ j as T,
24
+ k as v,
25
+ m as F
26
+ } from "../_node-chunks/chunk-FMQIQP6D.js";
27
+ import "../_node-chunks/chunk-N3OFRDD3.js";
28
+ import {
29
+ b as j,
30
+ c as P,
31
+ f as V,
32
+ g as A
33
+ } from "../_node-chunks/chunk-W26ZMSD3.js";
34
+ import {
35
+ a as c
36
+ } from "../_node-chunks/chunk-KVKHJ5OL.js";
10
37
 
11
- var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
12
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
38
+ // src/node/vitest.ts
39
+ import S from "node:process";
40
+ import { Channel as H } from "storybook/internal/channels";
41
+ import {
42
+ experimental_UniversalStore as X,
43
+ experimental_getStatusStore as q,
44
+ experimental_getTestProviderStore as J
45
+ } from "storybook/internal/core-server";
13
46
 
14
- var process3__default = /*#__PURE__*/_interopDefault(process3);
15
- var path2__default = /*#__PURE__*/_interopDefault(path2);
47
+ // src/node/vitest-manager.ts
48
+ import { existsSync as W } from "node:fs";
49
+ import { getProjectRoot as Y, resolvePathInStorybookCache as $ } from "storybook/internal/common";
16
50
 
17
- var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty;var __require=(x=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(x,{get:(a,b)=>(typeof require<"u"?require:a)[b]}):x)(function(x){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});var __commonJS=(cb,mod)=>function(){return mod||(0, cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod));var require_picocolors=__commonJS({"../../node_modules/picocolors/picocolors.js"(exports,module){var p=process||{},argv=p.argv||[],env=p.env||{},isColorSupported=!(env.NO_COLOR||argv.includes("--no-color"))&&(!!env.FORCE_COLOR||argv.includes("--color")||p.platform==="win32"||(p.stdout||{}).isTTY&&env.TERM!=="dumb"||!!env.CI),formatter=(open,close,replace=open)=>input=>{let string=""+input,index=string.indexOf(close,open.length);return ~index?open+replaceClose(string,close,replace,index)+close:open+string+close},replaceClose=(string,close,replace,index)=>{let result="",cursor=0;do result+=string.substring(cursor,index)+replace,cursor=index+close.length,index=string.indexOf(close,cursor);while(~index);return result+string.substring(cursor)},createColors=(enabled=isColorSupported)=>{let f=enabled?formatter:()=>String;return {isColorSupported:enabled,reset:f("\x1B[0m","\x1B[0m"),bold:f("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:f("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:f("\x1B[3m","\x1B[23m"),underline:f("\x1B[4m","\x1B[24m"),inverse:f("\x1B[7m","\x1B[27m"),hidden:f("\x1B[8m","\x1B[28m"),strikethrough:f("\x1B[9m","\x1B[29m"),black:f("\x1B[30m","\x1B[39m"),red:f("\x1B[31m","\x1B[39m"),green:f("\x1B[32m","\x1B[39m"),yellow:f("\x1B[33m","\x1B[39m"),blue:f("\x1B[34m","\x1B[39m"),magenta:f("\x1B[35m","\x1B[39m"),cyan:f("\x1B[36m","\x1B[39m"),white:f("\x1B[37m","\x1B[39m"),gray:f("\x1B[90m","\x1B[39m"),bgBlack:f("\x1B[40m","\x1B[49m"),bgRed:f("\x1B[41m","\x1B[49m"),bgGreen:f("\x1B[42m","\x1B[49m"),bgYellow:f("\x1B[43m","\x1B[49m"),bgBlue:f("\x1B[44m","\x1B[49m"),bgMagenta:f("\x1B[45m","\x1B[49m"),bgCyan:f("\x1B[46m","\x1B[49m"),bgWhite:f("\x1B[47m","\x1B[49m"),blackBright:f("\x1B[90m","\x1B[39m"),redBright:f("\x1B[91m","\x1B[39m"),greenBright:f("\x1B[92m","\x1B[39m"),yellowBright:f("\x1B[93m","\x1B[39m"),blueBright:f("\x1B[94m","\x1B[39m"),magentaBright:f("\x1B[95m","\x1B[39m"),cyanBright:f("\x1B[96m","\x1B[39m"),whiteBright:f("\x1B[97m","\x1B[39m"),bgBlackBright:f("\x1B[100m","\x1B[49m"),bgRedBright:f("\x1B[101m","\x1B[49m"),bgGreenBright:f("\x1B[102m","\x1B[49m"),bgYellowBright:f("\x1B[103m","\x1B[49m"),bgBlueBright:f("\x1B[104m","\x1B[49m"),bgMagentaBright:f("\x1B[105m","\x1B[49m"),bgCyanBright:f("\x1B[106m","\x1B[49m"),bgWhiteBright:f("\x1B[107m","\x1B[49m")}};module.exports=createColors();module.exports.createColors=createColors;}});var ADDON_ID2="storybook/test";var COVERAGE_DIRECTORY="coverage";var storeOptions={id:ADDON_ID2,initialState:{config:{coverage:!1,a11y:!1},watching:!1,cancelling:!1,fatalError:void 0,indexUrl:void 0,previewAnnotations:[],currentRun:{triggeredBy:void 0,config:{coverage:!1,a11y:!1},componentTestCount:{success:0,error:0},a11yCount:{success:0,warning:0,error:0},storyIds:void 0,totalTestCount:void 0,startedAt:void 0,finishedAt:void 0,unhandledErrors:[],coverageSummary:void 0}}};`UNIVERSAL_STORE:${storeOptions.id}`;var STATUS_TYPE_ID_COMPONENT_TEST="storybook/component-test",STATUS_TYPE_ID_A11Y="storybook/a11y";function debounce(func,debounceMs,{signal,edges}={}){let pendingThis,pendingArgs=null,leading=edges!=null&&edges.includes("leading"),trailing=edges==null||edges.includes("trailing"),invoke=()=>{pendingArgs!==null&&(func.apply(pendingThis,pendingArgs),pendingThis=void 0,pendingArgs=null);},onTimerEnd=()=>{trailing&&invoke(),cancel();},timeoutId=null,schedule=()=>{timeoutId!=null&&clearTimeout(timeoutId),timeoutId=setTimeout(()=>{timeoutId=null,onTimerEnd();},debounceMs);},cancelTimer=()=>{timeoutId!==null&&(clearTimeout(timeoutId),timeoutId=null);},cancel=()=>{cancelTimer(),pendingThis=void 0,pendingArgs=null;},flush=()=>{cancelTimer(),invoke();},debounced=function(...args){if(signal?.aborted)return;pendingThis=this,pendingArgs=args;let isFirstCall=timeoutId==null;schedule(),leading&&isFirstCall&&invoke();};return debounced.schedule=schedule,debounced.cancel=cancel,debounced.flush=flush,signal?.addEventListener("abort",cancel,{once:!0}),debounced}function throttle(func,throttleMs,{signal,edges=["leading","trailing"]}={}){let pendingAt=null,debounced=debounce(func,throttleMs,{signal,edges}),throttled=function(...args){pendingAt==null?pendingAt=Date.now():Date.now()-pendingAt>=throttleMs&&(pendingAt=Date.now(),debounced.cancel()),debounced(...args);};return throttled.cancel=debounced.cancel,throttled.flush=debounced.flush,throttled}function errorToErrorLike(error){return {message:error.message,name:error.name,stack:error.stack?.replace(error.message,""),cause:error.cause&&error.cause instanceof Error?errorToErrorLike(error.cause):void 0}}var Node=class{value;next;constructor(value){this.value=value;}},Queue=class{#head;#tail;#size;constructor(){this.clear();}enqueue(value){let node=new Node(value);this.#head?(this.#tail.next=node,this.#tail=node):(this.#head=node,this.#tail=node),this.#size++;}dequeue(){let current=this.#head;if(current)return this.#head=this.#head.next,this.#size--,current.value}peek(){if(this.#head)return this.#head.value}clear(){this.#head=void 0,this.#tail=void 0,this.#size=0;}get size(){return this.#size}*[Symbol.iterator](){let current=this.#head;for(;current;)yield current.value,current=current.next;}*drain(){for(;this.#head;)yield this.dequeue();}};function pLimit(concurrency){if(!((Number.isInteger(concurrency)||concurrency===Number.POSITIVE_INFINITY)&&concurrency>0))throw new TypeError("Expected `concurrency` to be a number from 1 and up");let queue=new Queue,activeCount=0,next=()=>{activeCount--,queue.size>0&&queue.dequeue()();},run=async(fn,resolve2,args)=>{activeCount++;let result=(async()=>fn(...args))();resolve2(result);try{await result;}catch{}next();},enqueue=(fn,resolve2,args)=>{queue.enqueue(run.bind(void 0,fn,resolve2,args)),(async()=>(await Promise.resolve(),activeCount<concurrency&&queue.size>0&&queue.dequeue()()))();},generator=(fn,...args)=>new Promise(resolve2=>{enqueue(fn,resolve2,args);});return Object.defineProperties(generator,{activeCount:{get:()=>activeCount},pendingCount:{get:()=>queue.size},clearQueue:{value:()=>{queue.clear();}}}),generator}var EndError=class extends Error{constructor(value){super(),this.value=value;}},testElement=async(element,tester)=>tester(await element),finder=async element=>{let values=await Promise.all(element);if(values[1]===!0)throw new EndError(values[0]);return !1};async function pLocate(iterable,tester,{concurrency=Number.POSITIVE_INFINITY,preserveOrder=!0}={}){let limit=pLimit(concurrency),items=[...iterable].map(element=>[element,limit(testElement,element,tester)]),checkLimit=pLimit(preserveOrder?1:Number.POSITIVE_INFINITY);try{await Promise.all(items.map(element=>checkLimit(finder,element)));}catch(error){if(error instanceof EndError)return error.value;throw error}}var typeMappings={directory:"isDirectory",file:"isFile"};function checkType(type){if(!Object.hasOwnProperty.call(typeMappings,type))throw new Error(`Invalid type specified: ${type}`)}var matchType=(type,stat)=>stat[typeMappings[type]](),toPath=urlOrPath=>urlOrPath instanceof URL?url.fileURLToPath(urlOrPath):urlOrPath;async function locatePath(paths,{cwd:cwd2=process3__default.default.cwd(),type="file",allowSymlinks=!0,concurrency,preserveOrder}={}){checkType(type),cwd2=toPath(cwd2);let statFunction=allowSymlinks?fs.promises.stat:fs.promises.lstat;return pLocate(paths,async path_=>{try{let stat=await statFunction(path2__default.default.resolve(cwd2,path_));return matchType(type,stat)}catch{return !1}},{concurrency,preserveOrder})}function toPath2(urlOrPath){return urlOrPath instanceof URL?url.fileURLToPath(urlOrPath):urlOrPath}var findUpStop=Symbol("findUpStop");async function findUpMultiple(name,options={}){let directory=path2__default.default.resolve(toPath2(options.cwd)??""),{root}=path2__default.default.parse(directory),stopAt=path2__default.default.resolve(directory,toPath2(options.stopAt??root)),limit=options.limit??Number.POSITIVE_INFINITY,paths=[name].flat(),runMatcher=async locateOptions=>{if(typeof name!="function")return locatePath(paths,locateOptions);let foundPath=await name(locateOptions.cwd);return typeof foundPath=="string"?locatePath([foundPath],locateOptions):foundPath},matches=[];for(;;){let foundPath=await runMatcher({...options,cwd:directory});if(foundPath===findUpStop||(foundPath&&matches.push(path2__default.default.resolve(directory,foundPath)),directory===stopAt||matches.length>=limit))break;directory=path2__default.default.dirname(directory);}return matches}async function findUp(name,options={}){return (await findUpMultiple(name,{...options,limit:1}))[0]}var _DRIVE_LETTER_START_RE=/^[A-Za-z]:\//;function normalizeWindowsPath(input=""){return input&&input.replace(/\\/g,"/").replace(_DRIVE_LETTER_START_RE,r=>r.toUpperCase())}var _UNC_REGEX=/^[/\\]{2}/,_IS_ABSOLUTE_RE=/^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/,_DRIVE_LETTER_RE=/^[A-Za-z]:$/,_ROOT_FOLDER_RE=/^\/([A-Za-z]:)?$/,sep="/",delimiter=":",normalize=function(path4){if(path4.length===0)return ".";path4=normalizeWindowsPath(path4);let isUNCPath=path4.match(_UNC_REGEX),isPathAbsolute=isAbsolute(path4),trailingSeparator=path4[path4.length-1]==="/";return path4=normalizeString(path4,!isPathAbsolute),path4.length===0?isPathAbsolute?"/":trailingSeparator?"./":".":(trailingSeparator&&(path4+="/"),_DRIVE_LETTER_RE.test(path4)&&(path4+="/"),isUNCPath?isPathAbsolute?`//${path4}`:`//./${path4}`:isPathAbsolute&&!isAbsolute(path4)?`/${path4}`:path4)},join=function(...arguments_){if(arguments_.length===0)return ".";let joined;for(let argument of arguments_)argument&&argument.length>0&&(joined===void 0?joined=argument:joined+=`/${argument}`);return joined===void 0?".":normalize(joined.replace(/\/\/+/g,"/"))};function cwd(){return typeof process<"u"&&typeof process.cwd=="function"?process.cwd().replace(/\\/g,"/"):"/"}var resolve=function(...arguments_){arguments_=arguments_.map(argument=>normalizeWindowsPath(argument));let resolvedPath="",resolvedAbsolute=!1;for(let index=arguments_.length-1;index>=-1&&!resolvedAbsolute;index--){let path4=index>=0?arguments_[index]:cwd();!path4||path4.length===0||(resolvedPath=`${path4}/${resolvedPath}`,resolvedAbsolute=isAbsolute(path4));}return resolvedPath=normalizeString(resolvedPath,!resolvedAbsolute),resolvedAbsolute&&!isAbsolute(resolvedPath)?`/${resolvedPath}`:resolvedPath.length>0?resolvedPath:"."};function normalizeString(path4,allowAboveRoot){let res="",lastSegmentLength=0,lastSlash=-1,dots=0,char=null;for(let index=0;index<=path4.length;++index){if(index<path4.length)char=path4[index];else {if(char==="/")break;char="/";}if(char==="/"){if(!(lastSlash===index-1||dots===1))if(dots===2){if(res.length<2||lastSegmentLength!==2||res[res.length-1]!=="."||res[res.length-2]!=="."){if(res.length>2){let lastSlashIndex=res.lastIndexOf("/");lastSlashIndex===-1?(res="",lastSegmentLength=0):(res=res.slice(0,lastSlashIndex),lastSegmentLength=res.length-1-res.lastIndexOf("/")),lastSlash=index,dots=0;continue}else if(res.length>0){res="",lastSegmentLength=0,lastSlash=index,dots=0;continue}}allowAboveRoot&&(res+=res.length>0?"/..":"..",lastSegmentLength=2);}else res.length>0?res+=`/${path4.slice(lastSlash+1,index)}`:res=path4.slice(lastSlash+1,index),lastSegmentLength=index-lastSlash-1;lastSlash=index,dots=0;}else char==="."&&dots!==-1?++dots:dots=-1;}return res}var isAbsolute=function(p){return _IS_ABSOLUTE_RE.test(p)},toNamespacedPath=function(p){return normalizeWindowsPath(p)},_EXTNAME_RE=/.(\.[^./]+)$/,extname=function(p){let match=_EXTNAME_RE.exec(normalizeWindowsPath(p));return match&&match[1]||""},relative=function(from,to){let _from=resolve(from).replace(_ROOT_FOLDER_RE,"$1").split("/"),_to=resolve(to).replace(_ROOT_FOLDER_RE,"$1").split("/");if(_to[0][1]===":"&&_from[0][1]===":"&&_from[0]!==_to[0])return _to.join("/");let _fromCopy=[..._from];for(let segment of _fromCopy){if(_to[0]!==segment)break;_from.shift(),_to.shift();}return [..._from.map(()=>".."),..._to].join("/")},dirname=function(p){let segments=normalizeWindowsPath(p).replace(/\/$/,"").split("/").slice(0,-1);return segments.length===1&&_DRIVE_LETTER_RE.test(segments[0])&&(segments[0]+="/"),segments.join("/")||(isAbsolute(p)?"/":".")},format=function(p){let segments=[p.root,p.dir,p.base??p.name+p.ext].filter(Boolean);return normalizeWindowsPath(p.root?resolve(...segments):segments.join("/"))},basename=function(p,extension){let lastSegment=normalizeWindowsPath(p).split("/").pop();return extension&&lastSegment.endsWith(extension)?lastSegment.slice(0,-extension.length):lastSegment},parse=function(p){let root=normalizeWindowsPath(p).split("/").shift()||"/",base=basename(p),extension=extname(base);return {root,dir:dirname(p),base,ext:extension,name:base.slice(0,base.length-extension.length)}},path3={__proto__:null,basename,delimiter,dirname,extname,format,isAbsolute,join,normalize,normalizeString,parse,relative,resolve,sep,toNamespacedPath};function slash(path4){return path4.startsWith("\\\\?\\")?path4:path4.replace(/\\/g,"/")}var import_picocolors=__toESM(require_picocolors());var log=message=>{console.log(`${import_picocolors.default.magenta(ADDON_ID2)}: ${message.toString().trim()}`);};var StorybookReporter=class{constructor(testManager){this.testManager=testManager;}onInit(ctx){this.ctx=ctx;}onTestCaseResult(testCase){let{storyId,reports}=testCase.meta(),testResult=testCase.result();this.testManager.onTestCaseResult({storyId,testResult,reports});}async onTestRunEnd(testModules,unhandledErrors){let totalTestCount=testModules.flatMap(t=>Array.from(t.children.allTests("passed")).concat(Array.from(t.children.allTests("failed")))).length,testModulesErrors=testModules.flatMap(t=>t.errors()),serializedErrors=unhandledErrors.concat(testModulesErrors).map(e=>({...e,name:e.name,message:e.message,stack:e.stack?.replace(e.message,""),cause:e.cause}));this.testManager.onTestRunEnd({totalTestCount,unhandledErrors:serializedErrors}),this.clearVitestState();}async clearVitestState(){this.ctx.state.filesMap.clear(),this.ctx.state.pathsSet.clear(),this.ctx.state.idMap.clear(),this.ctx.state.errorsSet.clear(),this.ctx.state.processTimeoutCauses.clear();}};var VITEST_CONFIG_FILE_EXTENSIONS=["mts","mjs","cts","cjs","ts","tsx","js","jsx"],VITEST_WORKSPACE_FILE_EXTENSION=["ts","js","json"],packageDir=dirname(__require.resolve("@storybook/addon-vitest/package.json"));process.env.VITEST_STORYBOOK="true";var VitestManager=class{constructor(testManager){this.testManager=testManager;this.vitest=null;this.vitestStartupCounter=0;this.vitestRestartPromise=null;this.runningPromise=null;}async startVitest({coverage}){let{createVitest}=await import('vitest/node'),storybookCoverageReporter=[join(packageDir,"dist/node/coverage-reporter.js"),{testManager:this.testManager,coverageOptions:this.vitest?.config?.coverage}],coverageOptions=coverage?{enabled:!0,clean:!0,cleanOnRerun:!0,reportOnFailure:!0,reporter:[["html",{}],storybookCoverageReporter],reportsDirectory:common.resolvePathInStorybookCache(COVERAGE_DIRECTORY)}:{enabled:!1},vitestWorkspaceConfig=await findUp([...VITEST_WORKSPACE_FILE_EXTENSION.map(ext=>`vitest.workspace.${ext}`),...VITEST_CONFIG_FILE_EXTENSIONS.map(ext=>`vitest.config.${ext}`)],{stopAt:common.getProjectRoot()}),projectName="storybook:"+process.env.STORYBOOK_CONFIG_DIR;try{this.vitest=await createVitest("test",{root:vitestWorkspaceConfig?dirname(vitestWorkspaceConfig):process.cwd(),watch:!0,passWithNoTests:!1,project:[projectName],reporters:["default",new StorybookReporter(this.testManager)],coverage:coverageOptions});}catch(err){let originalMessage=String(err.message);if(originalMessage.includes("Found multiple projects")){let custom=["Storybook was unable to start the test run because you have multiple Vitest projects (or browsers) in headed mode.","Please set `headless: true` in your Storybook vitest config.\n\n"].join(`
18
- `);originalMessage.startsWith(custom)||(err.message=`${custom}${originalMessage}`);}throw err}this.vitest&&this.vitest.onCancel(()=>{});try{await this.vitest.init();}catch(e){let message="Failed to initialize Vitest",isV8=e.message?.includes("@vitest/coverage-v8"),isIstanbul=e.message?.includes("@vitest/coverage-istanbul");(e.message?.includes("Failed to load url")&&(isIstanbul||isV8)||e instanceof TypeError&&e?.message==="Cannot read properties of undefined (reading 'name')")&&(message+=`
51
+ // ../../node_modules/slash/index.js
52
+ function M(d) {
53
+ return d.startsWith("\\\\?\\") ? d : d.replace(/\\/g, "/");
54
+ }
55
+ c(M, "slash");
19
56
 
20
- Please install the @vitest/${isIstanbul?"coverage-istanbul":"coverage-v8"} package to collect coverage
21
- `),this.testManager.reportFatalError(message,e);return}await this.setupWatchers();}async restartVitest({coverage}){return await this.vitestRestartPromise,this.vitestRestartPromise=new Promise(async(resolve2,reject)=>{try{await this.runningPromise,await this.vitest?.close(),await this.startVitest({coverage}),resolve2();}catch(e){reject(e);}finally{this.vitestRestartPromise=null;}}),this.vitestRestartPromise}resetGlobalTestNamePattern(){this.vitest?.setGlobalTestNamePattern("");}updateLastChanged(filepath){this.vitest.getModuleProjects(filepath).forEach(({server,browser})=>{server&&server.moduleGraph.getModulesByFile(filepath)?.forEach(mod=>server.moduleGraph.invalidateModule(mod)),browser&&browser.vite.moduleGraph.getModulesByFile(filepath)?.forEach(mod=>browser.vite.moduleGraph.invalidateModule(mod));});}async fetchStories(requestStoryIds){let indexUrl=this.testManager.store.getState().indexUrl;if(!indexUrl)throw new Error("Tried to fetch stories to test, but the index URL was not set in the store yet.");try{let index=await Promise.race([fetch(indexUrl).then(res=>res.json()),new Promise((_,reject)=>setTimeout(reject,3e3,new Error("Request took too long")))]);return (requestStoryIds||Object.keys(index.entries)).map(id=>index.entries[id]).filter(story=>story.type==="story")}catch(e){return log("Failed to fetch story index: "+e.message),[]}}filterTestSpecifications(testSpecifications,stories){let filteredTestSpecifications=[],filteredStoryIds=[],storiesByImportPath={};for(let story of stories){let absoluteImportPath=path3.join(process.cwd(),story.importPath);storiesByImportPath[absoluteImportPath]||(storiesByImportPath[absoluteImportPath]=[]),storiesByImportPath[absoluteImportPath].push(story);}for(let testSpecification of testSpecifications){let{env={}}=testSpecification.project.config,include=env.__VITEST_INCLUDE_TAGS__?.split(",").filter(Boolean)??["test"],exclude=env.__VITEST_EXCLUDE_TAGS__?.split(",").filter(Boolean)??[],skip=env.__VITEST_SKIP_TAGS__?.split(",").filter(Boolean)??[],filteredStories=(storiesByImportPath[testSpecification.moduleId]??[]).filter(story=>!(include.length&&!include.some(tag=>story.tags?.includes(tag))||exclude.some(tag=>story.tags?.includes(tag))));filteredStories.length&&(this.testManager.store.getState().watching||this.updateLastChanged(testSpecification.moduleId),filteredTestSpecifications.push(testSpecification),filteredStoryIds.push(...filteredStories.filter(story=>!skip.some(tag=>story.tags?.includes(tag))).map(story=>story.id)));}return {filteredTestSpecifications,filteredStoryIds}}async runTests(runPayload){let{watching,config}=this.testManager.store.getState(),coverageShouldBeEnabled=config.coverage&&!watching&&(runPayload?.storyIds?.length??0)===0,currentCoverage=this.vitest?.config.coverage?.enabled;this.vitest?currentCoverage!==coverageShouldBeEnabled?await this.restartVitest({coverage:coverageShouldBeEnabled}):await this.vitestRestartPromise:await this.startVitest({coverage:coverageShouldBeEnabled}),this.resetGlobalTestNamePattern(),await this.cancelCurrentRun();let testSpecifications=await this.getStorybookTestSpecifications(),stories=await this.fetchStories(runPayload?.storyIds);if(runPayload.storyIds?.length===1){let storyName=stories[0].name,regex=new RegExp(`^${storyName.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`);this.vitest.setGlobalTestNamePattern(regex);}let{filteredTestSpecifications,filteredStoryIds}=this.filterTestSpecifications(testSpecifications,stories);this.testManager.store.setState(s=>({...s,currentRun:{...s.currentRun,totalTestCount:filteredStoryIds.length}})),await this.vitest.runTestSpecifications(filteredTestSpecifications,!0),this.resetGlobalTestNamePattern();}async cancelCurrentRun(){await this.vitest?.cancelCurrentRun("keyboard-input"),await this.runningPromise;}async getStorybookTestSpecifications(){return (await this.vitest?.globTestSpecifications()??[]).filter(workspaceSpec=>this.isStorybookProject(workspaceSpec.project))??[]}async runAffectedTestsAfterChange(changedFilePath,event){let id=slash(changedFilePath);if(this.vitest?.logger.clearHighlightCache(id),this.updateLastChanged(id),event==="add"&&this.vitest?.projects.find(this.isStorybookProject.bind(this))?.matchesTestGlob(id),!this.testManager.store.getState().watching||!this.vitest)return;this.resetGlobalTestNamePattern();let storybookProject=this.vitest.projects.find(p=>this.isStorybookProject(p)),previewAnnotationSpecifications=this.testManager.store.getState().previewAnnotations.map(previewAnnotation=>({project:storybookProject??this.vitest.projects[0],moduleId:typeof previewAnnotation=="string"?previewAnnotation:previewAnnotation.absolute})),setupFilesSpecifications=this.vitest.projects.flatMap(project=>project.config.setupFiles.map(setupFile=>({project,moduleId:setupFile}))),syntheticGlobalTestSpecifications=previewAnnotationSpecifications.concat(setupFilesSpecifications),testSpecifications=await this.getStorybookTestSpecifications(),allStories=await this.fetchStories(),affectsGlobalFiles=!1,affectedTestSpecifications=(await Promise.all(syntheticGlobalTestSpecifications.concat(testSpecifications).map(async testSpecification=>{let dependencies=await this.getTestDependencies(testSpecification);if(changedFilePath===testSpecification.moduleId||dependencies.has(changedFilePath))return syntheticGlobalTestSpecifications.includes(testSpecification)&&(affectsGlobalFiles=!0),testSpecification}))).filter(Boolean),testSpecificationsToRun=affectsGlobalFiles?testSpecifications:affectedTestSpecifications;if(!testSpecificationsToRun.length)return;let{filteredTestSpecifications,filteredStoryIds}=this.filterTestSpecifications(testSpecificationsToRun,allStories);await this.testManager.runTestsWithState({storyIds:filteredStoryIds,triggeredBy:"watch",callback:async()=>{this.testManager.store.setState(s=>({...s,currentRun:{...s.currentRun,totalTestCount:filteredStoryIds.length}})),await this.vitest.cancelCurrentRun("keyboard-input"),await this.runningPromise,await this.vitest.runTestSpecifications(filteredTestSpecifications,!1);}});}async getTestDependencies(spec){let deps=new Set,addImports=async(project,filepath)=>{if(deps.has(filepath))return;deps.add(filepath);let transformed=project.vite.moduleGraph.getModuleById(filepath)?.ssrTransformResult||await project.vite.transformRequest(filepath,{ssr:!0});if(!transformed)return;let dependencies=[...transformed.deps??[],...transformed.dynamicDeps??[]];await Promise.all(dependencies.map(async dep=>{let fsPath=dep.startsWith("/@fs/")?dep.slice(process.platform==="win32"?5:4):join(project.config.root,dep);!fsPath.includes("node_modules")&&!deps.has(fsPath)&&fs.existsSync(fsPath)&&await addImports(project,fsPath);}));};return await addImports(spec.project,spec.moduleId),deps.delete(spec.moduleId),deps}async registerVitestConfigListener(){this.vitest.vite.watcher.on("change",async file=>{if(normalize(file)===this.vitest?.vite?.config.configFile){log("Restarting Vitest due to config change");let{watching,config}=this.testManager.store.getState();await this.restartVitest({coverage:config.coverage&&!watching});}});}async setupWatchers(){this.resetGlobalTestNamePattern(),this.vitest.vite.watcher.removeAllListeners("change"),this.vitest.vite.watcher.removeAllListeners("add"),this.vitest.vite.watcher.on("change",file=>this.runAffectedTestsAfterChange(file,"change")),this.vitest.vite.watcher.on("add",file=>{this.runAffectedTestsAfterChange(file,"add");}),this.registerVitestConfigListener();}isStorybookProject(project){return !!project.config.env?.__STORYBOOK_URL__}};var testStateToStatusValueMap={pending:"status-value:pending",passed:"status-value:success",warning:"status-value:warning",failed:"status-value:error",skipped:"status-value:unknown"},TestManager=class _TestManager{constructor(options){this.batchedTestCaseResults=[];this.throttledFlushTestCaseResults=throttle(()=>{let testCaseResultsToFlush=this.batchedTestCaseResults;this.batchedTestCaseResults=[],this.store.setState(s=>{let{success:ctSuccess,error:ctError}=s.currentRun.componentTestCount,{success:a11ySuccess,warning:a11yWarning,error:a11yError}=s.currentRun.a11yCount;testCaseResultsToFlush.forEach(({testResult,reports})=>{testResult.state==="passed"?ctSuccess++:testResult.state==="failed"&&ctError++,reports?.filter(r=>r.type==="a11y").forEach(report=>{report.status==="passed"?a11ySuccess++:report.status==="warning"?a11yWarning++:report.status==="failed"&&a11yError++;});});let finishedTestCount=ctSuccess+ctError;return {...s,currentRun:{...s.currentRun,componentTestCount:{success:ctSuccess,error:ctError},a11yCount:{success:a11ySuccess,warning:a11yWarning,error:a11yError},totalTestCount:finishedTestCount>(s.currentRun.totalTestCount??0)?finishedTestCount:s.currentRun.totalTestCount}}});let componentTestStatuses=testCaseResultsToFlush.map(({storyId,testResult})=>({storyId,typeId:STATUS_TYPE_ID_COMPONENT_TEST,value:testStateToStatusValueMap[testResult.state],title:"Component tests",description:testResult.errors?.map(error=>error.stack||error.message).join(`
22
- `)??"",sidebarContextMenu:!1}));this.componentTestStatusStore.set(componentTestStatuses);let a11yStatuses=testCaseResultsToFlush.flatMap(({storyId,reports})=>reports?.filter(r=>r.type==="a11y").map(a11yReport=>({storyId,typeId:STATUS_TYPE_ID_A11Y,value:testStateToStatusValueMap[a11yReport.status],title:"Accessibility tests",description:"",sidebarContextMenu:!1}))).filter(a11yStatus=>a11yStatus!==void 0);a11yStatuses.length>0&&this.a11yStatusStore.set(a11yStatuses);},500);this.store=options.store,this.componentTestStatusStore=options.componentTestStatusStore,this.a11yStatusStore=options.a11yStatusStore,this.testProviderStore=options.testProviderStore,this.onReady=options.onReady,this.storybookOptions=options.storybookOptions,this.vitestManager=new VitestManager(this),this.store.subscribe("TRIGGER_RUN",this.handleTriggerRunEvent.bind(this)),this.store.subscribe("CANCEL_RUN",this.handleCancelEvent.bind(this)),this.store.untilReady().then(()=>this.vitestManager.startVitest({coverage:this.store.getState().config.coverage})).then(()=>this.onReady?.()).catch(e=>{this.reportFatalError("Failed to start Vitest",e);});}async handleTriggerRunEvent(event){await this.runTestsWithState({storyIds:event.payload.storyIds,triggeredBy:event.payload.triggeredBy,callback:async()=>{try{await this.vitestManager.vitestRestartPromise,await this.vitestManager.runTests(event.payload);}catch(err){throw this.reportFatalError("Failed to run tests",err),err}}});}async handleCancelEvent(){try{this.store.setState(s=>({...s,cancelling:!0})),await this.vitestManager.cancelCurrentRun();}catch(err){this.reportFatalError("Failed to cancel tests",err);}finally{this.store.setState(s=>({...s,cancelling:!1}));}}async runTestsWithState({storyIds,triggeredBy,callback}){this.componentTestStatusStore.unset(storyIds),this.a11yStatusStore.unset(storyIds),this.store.setState(s=>({...s,currentRun:{...storeOptions.initialState.currentRun,triggeredBy,startedAt:Date.now(),storyIds,config:s.config}})),process.env.VITEST_STORYBOOK_CONFIG=JSON.stringify(this.store.getState().config),await this.testProviderStore.runWithState(async()=>{if(await callback(),this.store.send({type:"TEST_RUN_COMPLETED",payload:this.store.getState().currentRun}),this.store.getState().currentRun.unhandledErrors.length>0)throw new Error("Tests completed but there are unhandled errors")});}onTestModuleCollected(collectedTestCount){this.store.setState(s=>({...s,currentRun:{...s.currentRun,totalTestCount:(s.currentRun.totalTestCount??0)+collectedTestCount}}));}onTestCaseResult(result){let{storyId,testResult,reports}=result;storyId&&(this.batchedTestCaseResults.push({storyId,testResult,reports}),this.throttledFlushTestCaseResults());}onTestRunEnd(endResult){this.throttledFlushTestCaseResults.flush(),this.store.setState(s=>({...s,currentRun:{...s.currentRun,totalTestCount:endResult.totalTestCount,unhandledErrors:endResult.unhandledErrors,finishedAt:Date.now()}}));}onCoverageCollected(coverageSummary){this.store.setState(s=>({...s,currentRun:{...s.currentRun,coverageSummary}}));}async reportFatalError(message,error){await this.store.untilReady(),this.store.send({type:"FATAL_ERROR",payload:{message,error:errorToErrorLike(error)}});}static async start(options){return new Promise(resolve2=>{let testManager=new _TestManager({...options,onReady:()=>{resolve2(testManager),options.onReady?.();}});})}};var require2=module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('out.js', document.baseURI).href))),{experimental_UniversalStore:UniversalStore,experimental_getStatusStore:getStatusStore,experimental_getTestProviderStore:getTestProviderStore}=require2("storybook/internal/core-server"),channel=new channels.Channel({async:!0,transport:{send:event=>{process3__default.default.send?.(event);},setHandler:handler=>{process3__default.default.on("message",handler);}}});UniversalStore.__prepare(channel,UniversalStore.Environment.SERVER);var store=UniversalStore.create(storeOptions);new TestManager({store,componentTestStatusStore:getStatusStore(STATUS_TYPE_ID_COMPONENT_TEST),a11yStatusStore:getStatusStore(STATUS_TYPE_ID_A11Y),testProviderStore:getTestProviderStore(ADDON_ID2),onReady:()=>{process3__default.default.send?.({type:"ready"});},storybookOptions:{configDir:process3__default.default.env.STORYBOOK_CONFIG_DIR||""}});var exit=(code=0)=>{channel?.removeAllListeners(),process3__default.default.exit(code);},createUnhandledErrorHandler=message=>async error=>{try{let payload={message,error:{message:error.message,name:error.name,stack:error.stack,cause:error.cause}};process3__default.default.send?.({type:"uncaught-error",payload});}finally{exit(1);}};process3__default.default.on("uncaughtException",createUnhandledErrorHandler("Uncaught exception in the test runner process"));process3__default.default.on("unhandledRejection",createUnhandledErrorHandler("Unhandled rejection in the test runner process"));process3__default.default.on("exit",exit);process3__default.default.on("SIGINT",()=>exit(0));process3__default.default.on("SIGTERM",()=>exit(0));
57
+ // src/node/reporter.ts
58
+ var R = class {
59
+ constructor(t) {
60
+ this.testManager = t;
61
+ }
62
+ static {
63
+ c(this, "StorybookReporter");
64
+ }
65
+ onInit(t) {
66
+ this.ctx = t;
67
+ }
68
+ onTestCaseResult(t) {
69
+ let { storyId: e, reports: o } = t.meta(), s = t.result();
70
+ this.testManager.onTestCaseResult({
71
+ storyId: e,
72
+ testResult: s,
73
+ reports: o
74
+ });
75
+ }
76
+ async onTestRunEnd(t, e) {
77
+ let o = t.flatMap(
78
+ (r) => Array.from(r.children.allTests("passed")).concat(Array.from(r.children.allTests("failed")))
79
+ ).length, s = t.flatMap((r) => r.errors()), a = e.concat(s).map((r) => ({
80
+ ...r,
81
+ name: r.name,
82
+ message: r.message,
83
+ stack: r.stack?.replace(r.message, ""),
84
+ cause: r.cause
85
+ }));
86
+ this.testManager.onTestRunEnd({
87
+ totalTestCount: o,
88
+ unhandledErrors: a
89
+ }), this.clearVitestState();
90
+ }
91
+ // TODO: Clearing the whole internal state of Vitest might be too aggressive
92
+ async clearVitestState() {
93
+ this.ctx.state.filesMap.clear(), this.ctx.state.pathsSet.clear(), this.ctx.state.idMap.clear(), this.ctx.state.errorsSet.clear(), this.ctx.state.processTimeoutCauses.clear();
94
+ }
95
+ };
96
+
97
+ // src/node/vitest-manager.ts
98
+ var K = ["mts", "mjs", "cts", "cjs", "ts", "tsx", "js", "jsx"], z = ["ts", "js", "json"];
99
+ process.env.VITEST_STORYBOOK = "true";
100
+ var E = class {
101
+ constructor(t) {
102
+ this.testManager = t;
103
+ this.vitest = null;
104
+ this.vitestStartupCounter = 0;
105
+ this.vitestRestartPromise = null;
106
+ this.runningPromise = null;
107
+ }
108
+ static {
109
+ c(this, "VitestManager");
110
+ }
111
+ async startVitest({ coverage: t }) {
112
+ let { createVitest: e } = await import("vitest/node"), o = [
113
+ P(F("@storybook/addon-vitest"), "static/coverage-reporter.cjs"),
114
+ {
115
+ testManager: this.testManager,
116
+ coverageOptions: this.vitest?.config?.coverage
117
+ }
118
+ ], s = t ? {
119
+ enabled: !0,
120
+ clean: !0,
121
+ cleanOnRerun: !0,
122
+ reportOnFailure: !0,
123
+ reporter: [["html", {}], o],
124
+ reportsDirectory: $(x)
125
+ } : { enabled: !1 }, a = await G(
126
+ [
127
+ ...z.map((i) => `vitest.workspace.${i}`),
128
+ ...K.map((i) => `vitest.config.${i}`)
129
+ ],
130
+ { stopAt: Y() }
131
+ ), r = "storybook:" + process.env.STORYBOOK_CONFIG_DIR;
132
+ try {
133
+ this.vitest = await e("test", {
134
+ root: a ? V(a) : process.cwd(),
135
+ watch: !0,
136
+ passWithNoTests: !1,
137
+ project: [r],
138
+ // TODO:
139
+ // Do we want to enable Vite's default reporter?
140
+ // The output in the terminal might be too spamy and it might be better to
141
+ // find a way to just show errors and warnings for example
142
+ // Otherwise it might be hard for the user to discover Storybook related logs
143
+ reporters: ["default", new R(this.testManager)],
144
+ coverage: s
145
+ });
146
+ } catch (i) {
147
+ let n = String(i.message);
148
+ if (n.includes("Found multiple projects")) {
149
+ let l = [
150
+ "Storybook was unable to start the test run because you have multiple Vitest projects (or browsers) in headed mode.",
151
+ "Please set `headless: true` in your Storybook vitest config.\n\n"
152
+ ].join(`
153
+ `);
154
+ n.startsWith(l) || (i.message = `${l}${n}`);
155
+ }
156
+ throw i;
157
+ }
158
+ this.vitest && this.vitest.onCancel(() => {
159
+ });
160
+ try {
161
+ await this.vitest.init();
162
+ } catch (i) {
163
+ let n = "Failed to initialize Vitest", l = i.message?.includes("@vitest/coverage-v8"), u = i.message?.includes("@vitest/coverage-istanbul");
164
+ (i.message?.includes("Failed to load url") && (u || l) || // Vitest will sometimes not throw the correct missing-package-detection error, so we have to check for this as well
165
+ i instanceof TypeError && i?.message === "Cannot read properties of undefined (reading 'name')") && (n += `
166
+
167
+ Please install the @vitest/${u ? "coverage-istanbul" : "coverage-v8"} package to collect coverage
168
+ `), this.testManager.reportFatalError(n, i);
169
+ return;
170
+ }
171
+ await this.setupWatchers();
172
+ }
173
+ async restartVitest({ coverage: t }) {
174
+ return await this.vitestRestartPromise, this.vitestRestartPromise = new Promise(async (e, o) => {
175
+ try {
176
+ await this.runningPromise, await this.vitest?.close(), await this.startVitest({ coverage: t }), e();
177
+ } catch (s) {
178
+ o(s);
179
+ } finally {
180
+ this.vitestRestartPromise = null;
181
+ }
182
+ }), this.vitestRestartPromise;
183
+ }
184
+ resetGlobalTestNamePattern() {
185
+ this.vitest?.setGlobalTestNamePattern("");
186
+ }
187
+ updateLastChanged(t) {
188
+ this.vitest.getModuleProjects(t).forEach(({ server: o, browser: s }) => {
189
+ o && o.moduleGraph.getModulesByFile(t)?.forEach((r) => o.moduleGraph.invalidateModule(r)), s && s.vite.moduleGraph.getModulesByFile(t)?.forEach((r) => s.vite.moduleGraph.invalidateModule(r));
190
+ });
191
+ }
192
+ async fetchStories(t) {
193
+ let e = this.testManager.store.getState().indexUrl;
194
+ if (!e)
195
+ throw new Error(
196
+ "Tried to fetch stories to test, but the index URL was not set in the store yet."
197
+ );
198
+ try {
199
+ let o = await Promise.race([
200
+ fetch(e).then((a) => a.json()),
201
+ new Promise((a, r) => setTimeout(r, 3e3, new Error("Request took too long")))
202
+ ]);
203
+ return (t || Object.keys(o.entries)).map((a) => o.entries[a]).filter((a) => a.type === "story");
204
+ } catch (o) {
205
+ return I("Failed to fetch story index: " + o.message), [];
206
+ }
207
+ }
208
+ filterTestSpecifications(t, e) {
209
+ let o = [], s = [], a = {};
210
+ for (let r of e) {
211
+ let i = A.join(process.cwd(), r.importPath);
212
+ a[i] || (a[i] = []), a[i].push(r);
213
+ }
214
+ for (let r of t) {
215
+ let { env: i = {} } = r.project.config, n = i.__VITEST_INCLUDE_TAGS__?.split(",").filter(Boolean) ?? ["test"], l = i.__VITEST_EXCLUDE_TAGS__?.split(",").filter(Boolean) ?? [], u = i.__VITEST_SKIP_TAGS__?.split(",").filter(Boolean) ?? [], f = (a[r.moduleId] ?? []).filter((h) => !(n.length && !n.some((m) => h.tags?.includes(m)) || l.some((m) => h.tags?.includes(m))));
216
+ f.length && (this.testManager.store.getState().watching || this.updateLastChanged(r.moduleId), o.push(r), s.push(
217
+ ...f.filter((h) => !u.some((m) => h.tags?.includes(m))).map((h) => h.id)
218
+ ));
219
+ }
220
+ return { filteredTestSpecifications: o, filteredStoryIds: s };
221
+ }
222
+ async runTests(t) {
223
+ let { watching: e, config: o } = this.testManager.store.getState(), s = o.coverage && !e && (t?.storyIds?.length ?? 0) === 0, a = this.vitest?.config.coverage?.enabled;
224
+ this.vitest ? a !== s ? await this.restartVitest({ coverage: s }) : await this.vitestRestartPromise : await this.startVitest({ coverage: s }), this.resetGlobalTestNamePattern(), await this.cancelCurrentRun();
225
+ let r = await this.getStorybookTestSpecifications(), i = await this.fetchStories(t?.storyIds);
226
+ if (t.storyIds?.length === 1) {
227
+ let g = i[0].name, f = new RegExp(`^${g.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}$`);
228
+ this.vitest.setGlobalTestNamePattern(f);
229
+ }
230
+ let { filteredTestSpecifications: l, filteredStoryIds: u } = this.filterTestSpecifications(
231
+ r,
232
+ i
233
+ );
234
+ this.testManager.store.setState((g) => ({
235
+ ...g,
236
+ currentRun: {
237
+ ...g.currentRun,
238
+ totalTestCount: u.length
239
+ }
240
+ })), await this.vitest.runTestSpecifications(l, !0), this.resetGlobalTestNamePattern();
241
+ }
242
+ async cancelCurrentRun() {
243
+ await this.vitest?.cancelCurrentRun("keyboard-input"), await this.runningPromise;
244
+ }
245
+ async getStorybookTestSpecifications() {
246
+ return (await this.vitest?.globTestSpecifications() ?? []).filter(
247
+ (e) => this.isStorybookProject(e.project)
248
+ ) ?? [];
249
+ }
250
+ async runAffectedTestsAfterChange(t, e) {
251
+ let o = M(t);
252
+ if (this.vitest?.logger.clearHighlightCache(o), this.updateLastChanged(o), e === "add" && this.vitest?.projects.find(this.isStorybookProject.bind(this))?.matchesTestGlob(o), !this.testManager.store.getState().watching || !this.vitest)
253
+ return;
254
+ this.resetGlobalTestNamePattern();
255
+ let s = this.vitest.projects.find((p) => this.isStorybookProject(p)), a = this.testManager.store.getState().previewAnnotations.map((p) => ({
256
+ project: s ?? this.vitest.projects[0],
257
+ moduleId: typeof p == "string" ? p : p.absolute
258
+ })), r = this.vitest.projects.flatMap(
259
+ (p) => p.config.setupFiles.map((b) => ({
260
+ project: p,
261
+ moduleId: b
262
+ }))
263
+ ), i = a.concat(r), n = await this.getStorybookTestSpecifications(), l = await this.fetchStories(), u = !1, g = (await Promise.all(
264
+ i.concat(n).map(async (p) => {
265
+ let b = await this.getTestDependencies(p);
266
+ if (t === p.moduleId || b.has(t))
267
+ return i.includes(p) && (u = !0), p;
268
+ })
269
+ )).filter(Boolean), f = u ? n : g;
270
+ if (!f.length)
271
+ return;
272
+ let { filteredTestSpecifications: h, filteredStoryIds: m } = this.filterTestSpecifications(
273
+ f,
274
+ l
275
+ );
276
+ await this.testManager.runTestsWithState({
277
+ storyIds: m,
278
+ triggeredBy: "watch",
279
+ callback: /* @__PURE__ */ c(async () => {
280
+ this.testManager.store.setState((p) => ({
281
+ ...p,
282
+ currentRun: {
283
+ ...p.currentRun,
284
+ totalTestCount: m.length
285
+ }
286
+ })), await this.vitest.cancelCurrentRun("keyboard-input"), await this.runningPromise, await this.vitest.runTestSpecifications(h, !1);
287
+ }, "callback")
288
+ });
289
+ }
290
+ // This is an adaptation of Vitest's own implementation
291
+ // see https://github.com/vitest-dev/vitest/blob/14409088166152c920ce7fa4ad4c0ba57149b869/packages/vitest/src/node/specifications.ts#L171-L198
292
+ async getTestDependencies(t) {
293
+ let e = /* @__PURE__ */ new Set(), o = /* @__PURE__ */ c(async (s, a) => {
294
+ if (e.has(a))
295
+ return;
296
+ e.add(a);
297
+ let i = s.vite.moduleGraph.getModuleById(a)?.ssrTransformResult || await s.vite.transformRequest(a, { ssr: !0 });
298
+ if (!i)
299
+ return;
300
+ let n = [...i.deps ?? [], ...i.dynamicDeps ?? []];
301
+ await Promise.all(
302
+ n.map(async (l) => {
303
+ let u = l.startsWith("/@fs/") ? l.slice(process.platform === "win32" ? 5 : 4) : P(s.config.root, l);
304
+ !u.includes("node_modules") && !e.has(u) && W(u) && await o(s, u);
305
+ })
306
+ );
307
+ }, "addImports");
308
+ return await o(t.project, t.moduleId), e.delete(t.moduleId), e;
309
+ }
310
+ async registerVitestConfigListener() {
311
+ this.vitest.vite.watcher.on("change", async (t) => {
312
+ if (j(t) === this.vitest?.vite?.config.configFile) {
313
+ I("Restarting Vitest due to config change");
314
+ let { watching: o, config: s } = this.testManager.store.getState();
315
+ await this.restartVitest({ coverage: s.coverage && !o });
316
+ }
317
+ });
318
+ }
319
+ async setupWatchers() {
320
+ this.resetGlobalTestNamePattern(), this.vitest.vite.watcher.removeAllListeners("change"), this.vitest.vite.watcher.removeAllListeners("add"), this.vitest.vite.watcher.on(
321
+ "change",
322
+ (t) => this.runAffectedTestsAfterChange(t, "change")
323
+ ), this.vitest.vite.watcher.on("add", (t) => {
324
+ this.runAffectedTestsAfterChange(t, "add");
325
+ }), this.registerVitestConfigListener();
326
+ }
327
+ isStorybookProject(t) {
328
+ return !!t.config.env?.__STORYBOOK_URL__;
329
+ }
330
+ };
331
+
332
+ // src/node/test-manager.ts
333
+ var B = {
334
+ pending: "status-value:pending",
335
+ passed: "status-value:success",
336
+ warning: "status-value:warning",
337
+ failed: "status-value:error",
338
+ skipped: "status-value:unknown"
339
+ }, w = class d {
340
+ constructor(t) {
341
+ this.batchedTestCaseResults = [];
342
+ /**
343
+ * Throttled function to process batched test case results.
344
+ *
345
+ * This function:
346
+ *
347
+ * 1. Takes all batched test case results and clears the batch
348
+ * 2. Updates the store state with new test counts (component tests and a11y tests)
349
+ * 3. Adjusts the totalTestCount if more tests were run than initially anticipated
350
+ * 4. Creates status objects for component tests and updates the component test status store
351
+ * 5. Creates status objects for a11y tests (if any) and updates the a11y status store
352
+ *
353
+ * The throttling (500ms) is necessary as the channel would otherwise get overwhelmed with events,
354
+ * eventually causing the manager and dev server to lose connection.
355
+ */
356
+ this.throttledFlushTestCaseResults = O(() => {
357
+ let t = this.batchedTestCaseResults;
358
+ this.batchedTestCaseResults = [], this.store.setState((s) => {
359
+ let { success: a, error: r } = s.currentRun.componentTestCount, { success: i, warning: n, error: l } = s.currentRun.a11yCount;
360
+ t.forEach(({ testResult: g, reports: f }) => {
361
+ g.state === "passed" ? a++ : g.state === "failed" && r++, f?.filter((h) => h.type === "a11y").forEach((h) => {
362
+ h.status === "passed" ? i++ : h.status === "warning" ? n++ : h.status === "failed" && l++;
363
+ });
364
+ });
365
+ let u = a + r;
366
+ return {
367
+ ...s,
368
+ currentRun: {
369
+ ...s.currentRun,
370
+ componentTestCount: { success: a, error: r },
371
+ a11yCount: { success: i, warning: n, error: l },
372
+ // in some cases successes and errors can exceed the anticipated totalTestCount
373
+ // e.g. when testing more tests than the stories we know about upfront
374
+ // in those cases, we set the totalTestCount to the sum of successes and errors
375
+ totalTestCount: u > (s.currentRun.totalTestCount ?? 0) ? u : s.currentRun.totalTestCount
376
+ }
377
+ };
378
+ });
379
+ let e = t.map(({ storyId: s, testResult: a }) => ({
380
+ storyId: s,
381
+ typeId: T,
382
+ value: B[a.state],
383
+ title: "Component tests",
384
+ description: a.errors?.map((r) => r.stack || r.message).join(`
385
+ `) ?? "",
386
+ sidebarContextMenu: !1
387
+ }));
388
+ this.componentTestStatusStore.set(e);
389
+ let o = t.flatMap(
390
+ ({ storyId: s, reports: a }) => a?.filter((r) => r.type === "a11y").map((r) => ({
391
+ storyId: s,
392
+ typeId: v,
393
+ value: B[r.status],
394
+ title: "Accessibility tests",
395
+ description: "",
396
+ sidebarContextMenu: !1
397
+ }))
398
+ ).filter((s) => s !== void 0);
399
+ o.length > 0 && this.a11yStatusStore.set(o);
400
+ }, 500);
401
+ this.store = t.store, this.componentTestStatusStore = t.componentTestStatusStore, this.a11yStatusStore = t.a11yStatusStore, this.testProviderStore = t.testProviderStore, this.onReady = t.onReady, this.storybookOptions = t.storybookOptions, this.vitestManager = new E(this), this.store.subscribe("TRIGGER_RUN", this.handleTriggerRunEvent.bind(this)), this.store.subscribe("CANCEL_RUN", this.handleCancelEvent.bind(this)), this.store.untilReady().then(() => this.vitestManager.startVitest({ coverage: this.store.getState().config.coverage })).then(() => this.onReady?.()).catch((e) => {
402
+ this.reportFatalError("Failed to start Vitest", e);
403
+ });
404
+ }
405
+ static {
406
+ c(this, "TestManager");
407
+ }
408
+ async handleTriggerRunEvent(t) {
409
+ await this.runTestsWithState({
410
+ storyIds: t.payload.storyIds,
411
+ triggeredBy: t.payload.triggeredBy,
412
+ callback: /* @__PURE__ */ c(async () => {
413
+ try {
414
+ await this.vitestManager.vitestRestartPromise, await this.vitestManager.runTests(t.payload);
415
+ } catch (e) {
416
+ throw this.reportFatalError("Failed to run tests", e), e;
417
+ }
418
+ }, "callback")
419
+ });
420
+ }
421
+ async handleCancelEvent() {
422
+ try {
423
+ this.store.setState((t) => ({
424
+ ...t,
425
+ cancelling: !0
426
+ })), await this.vitestManager.cancelCurrentRun();
427
+ } catch (t) {
428
+ this.reportFatalError("Failed to cancel tests", t);
429
+ } finally {
430
+ this.store.setState((t) => ({
431
+ ...t,
432
+ cancelling: !1
433
+ }));
434
+ }
435
+ }
436
+ async runTestsWithState({
437
+ storyIds: t,
438
+ triggeredBy: e,
439
+ callback: o
440
+ }) {
441
+ this.componentTestStatusStore.unset(t), this.a11yStatusStore.unset(t), this.store.setState((s) => ({
442
+ ...s,
443
+ currentRun: {
444
+ ...y.initialState.currentRun,
445
+ triggeredBy: e,
446
+ startedAt: Date.now(),
447
+ storyIds: t,
448
+ config: s.config
449
+ }
450
+ })), process.env.VITEST_STORYBOOK_CONFIG = JSON.stringify(this.store.getState().config), await this.testProviderStore.runWithState(async () => {
451
+ if (await o(), this.store.send({
452
+ type: "TEST_RUN_COMPLETED",
453
+ payload: this.store.getState().currentRun
454
+ }), this.store.getState().currentRun.unhandledErrors.length > 0)
455
+ throw new Error("Tests completed but there are unhandled errors");
456
+ });
457
+ }
458
+ onTestModuleCollected(t) {
459
+ this.store.setState((e) => ({
460
+ ...e,
461
+ currentRun: {
462
+ ...e.currentRun,
463
+ totalTestCount: (e.currentRun.totalTestCount ?? 0) + t
464
+ }
465
+ }));
466
+ }
467
+ onTestCaseResult(t) {
468
+ let { storyId: e, testResult: o, reports: s } = t;
469
+ e && (this.batchedTestCaseResults.push({ storyId: e, testResult: o, reports: s }), this.throttledFlushTestCaseResults());
470
+ }
471
+ onTestRunEnd(t) {
472
+ this.throttledFlushTestCaseResults.flush(), this.store.setState((e) => ({
473
+ ...e,
474
+ currentRun: {
475
+ ...e.currentRun,
476
+ // when the test run is finished, we can set the totalTestCount to the actual number of tests run
477
+ // this number can be lower than the total number of tests we anticipated upfront
478
+ // e.g. when some tests where skipped without us knowing about it upfront
479
+ totalTestCount: t.totalTestCount,
480
+ unhandledErrors: t.unhandledErrors,
481
+ finishedAt: Date.now()
482
+ }
483
+ }));
484
+ }
485
+ onCoverageCollected(t) {
486
+ this.store.setState((e) => ({
487
+ ...e,
488
+ currentRun: { ...e.currentRun, coverageSummary: t }
489
+ }));
490
+ }
491
+ async reportFatalError(t, e) {
492
+ await this.store.untilReady(), this.store.send({
493
+ type: "FATAL_ERROR",
494
+ payload: {
495
+ message: t,
496
+ error: N(e)
497
+ }
498
+ });
499
+ }
500
+ static async start(t) {
501
+ return new Promise((e) => {
502
+ let o = new d({
503
+ ...t,
504
+ onReady: /* @__PURE__ */ c(() => {
505
+ e(o), t.onReady?.();
506
+ }, "onReady")
507
+ });
508
+ });
509
+ }
510
+ };
511
+
512
+ // src/node/vitest.ts
513
+ var _ = X, L = q, Q = J, D = new H({
514
+ async: !0,
515
+ transport: {
516
+ send: /* @__PURE__ */ c((d) => {
517
+ S.send?.(d);
518
+ }, "send"),
519
+ setHandler: /* @__PURE__ */ c((d) => {
520
+ S.on("message", d);
521
+ }, "setHandler")
522
+ }
523
+ });
524
+ _.__prepare(D, _.Environment.SERVER);
525
+ var Z = _.create(y);
526
+ new w({
527
+ store: Z,
528
+ componentTestStatusStore: L(T),
529
+ a11yStatusStore: L(v),
530
+ testProviderStore: Q(k),
531
+ onReady: /* @__PURE__ */ c(() => {
532
+ S.send?.({ type: "ready" });
533
+ }, "onReady"),
534
+ storybookOptions: {
535
+ configDir: S.env.STORYBOOK_CONFIG_DIR || ""
536
+ }
537
+ });
538
+ var C = /* @__PURE__ */ c((d = 0) => {
539
+ D?.removeAllListeners(), S.exit(d);
540
+ }, "exit"), U = /* @__PURE__ */ c((d) => async (t) => {
541
+ try {
542
+ let e = {
543
+ message: d,
544
+ error: {
545
+ message: t.message,
546
+ name: t.name,
547
+ stack: t.stack,
548
+ cause: t.cause
549
+ }
550
+ };
551
+ S.send?.({
552
+ type: "uncaught-error",
553
+ payload: e
554
+ });
555
+ } finally {
556
+ C(1);
557
+ }
558
+ }, "createUnhandledErrorHandler");
559
+ S.on(
560
+ "uncaughtException",
561
+ U("Uncaught exception in the test runner process")
562
+ );
563
+ S.on(
564
+ "unhandledRejection",
565
+ U("Unhandled rejection in the test runner process")
566
+ );
567
+ S.on("exit", C);
568
+ S.on("SIGINT", () => C(0));
569
+ S.on("SIGTERM", () => C(0));