@storybook/addon-vitest 0.0.0-pr-31819-sha-323d0e88 → 0.0.0-pr-31987-sha-64db30c4

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/chunk-55WZLVGN.mjs +11 -0
  2. package/dist/chunk-JKRQGT2U.mjs +10 -0
  3. package/dist/index.js +6 -9
  4. package/dist/index.mjs +5 -0
  5. package/dist/manager.js +8 -5571
  6. package/dist/node/coverage-reporter.d.ts +184 -0
  7. package/dist/node/coverage-reporter.js +4 -1395
  8. package/dist/node/coverage-reporter.mjs +12 -0
  9. package/dist/node/vitest.d.ts +2 -0
  10. package/dist/node/vitest.js +17 -564
  11. package/dist/node/vitest.mjs +19 -0
  12. package/dist/postinstall.js +93 -1163
  13. package/dist/preset.js +32 -268
  14. package/dist/vitest-plugin/global-setup.d.ts +6 -0
  15. package/dist/vitest-plugin/global-setup.js +6 -146
  16. package/dist/vitest-plugin/global-setup.mjs +13 -0
  17. package/dist/vitest-plugin/index.js +43 -2589
  18. package/dist/vitest-plugin/index.mjs +28 -0
  19. package/dist/vitest-plugin/setup-file.d.ts +14 -0
  20. package/dist/vitest-plugin/setup-file.js +9 -28
  21. package/dist/vitest-plugin/setup-file.mjs +9 -0
  22. package/dist/vitest-plugin/test-utils.d.ts +20 -0
  23. package/dist/vitest-plugin/test-utils.js +8 -68
  24. package/dist/vitest-plugin/test-utils.mjs +8 -0
  25. package/manager.js +1 -0
  26. package/manager.mjs +1 -0
  27. package/package.json +89 -17
  28. package/postinstall.js +1 -0
  29. package/postinstall.mjs +1 -0
  30. package/preset.js +1 -0
  31. package/preset.mjs +1 -0
  32. package/dist/_browser-chunks/chunk-A47P2DCZ.js +0 -11
  33. package/dist/_browser-chunks/chunk-VMSW5DPM.js +0 -60
  34. package/dist/_node-chunks/chunk-C4NXJJA3.js +0 -324
  35. package/dist/_node-chunks/chunk-CIKGVIS6.js +0 -223
  36. package/dist/_node-chunks/chunk-FMQIQP6D.js +0 -96
  37. package/dist/_node-chunks/chunk-KVKHJ5OL.js +0 -46
  38. package/dist/_node-chunks/chunk-N3OFRDD3.js +0 -80
  39. package/dist/_node-chunks/chunk-VFT2PRGV.js +0 -5002
  40. package/dist/_node-chunks/chunk-W26ZMSD3.js +0 -143
  41. package/dist/_node-chunks/chunk-XWQZZ2C3.js +0 -1586
  42. package/static/coverage-reporter.cjs +0 -10
@@ -0,0 +1,19 @@
1
+ import ESM_COMPAT_Module, { createRequire } from 'node:module';
2
+ import { fileURLToPath } from 'node:url';
3
+ import path3, { dirname } from 'node:path';
4
+ import { require_picocolors, dirname as dirname$1, join, path, normalize } from '../chunk-55WZLVGN.mjs';
5
+ import { __toESM, __require } from '../chunk-JKRQGT2U.mjs';
6
+ import process3 from 'node:process';
7
+ import { Channel } from 'storybook/internal/channels';
8
+ import { existsSync, promises } from 'node:fs';
9
+ import { resolvePathInStorybookCache, getProjectRoot } from 'storybook/internal/common';
10
+
11
+ const __filename = fileURLToPath(import.meta.url);
12
+ dirname(__filename);
13
+ ESM_COMPAT_Module.createRequire(import.meta.url);
14
+ 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,resolve,args)=>{activeCount++;let result=(async()=>fn(...args))();resolve(result);try{await result;}catch{}next();},enqueue=(fn,resolve,args)=>{queue.enqueue(run.bind(void 0,fn,resolve,args)),(async()=>(await Promise.resolve(),activeCount<concurrency&&queue.size>0&&queue.dequeue()()))();},generator=(fn,...args)=>new Promise(resolve=>{enqueue(fn,resolve,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?fileURLToPath(urlOrPath):urlOrPath;async function locatePath(paths,{cwd=process3.cwd(),type="file",allowSymlinks=!0,concurrency,preserveOrder}={}){checkType(type),cwd=toPath(cwd);let statFunction=allowSymlinks?promises.stat:promises.lstat;return pLocate(paths,async path_=>{try{let stat=await statFunction(path3.resolve(cwd,path_));return matchType(type,stat)}catch{return !1}},{concurrency,preserveOrder})}function toPath2(urlOrPath){return urlOrPath instanceof URL?fileURLToPath(urlOrPath):urlOrPath}var findUpStop=Symbol("findUpStop");async function findUpMultiple(name,options={}){let directory=path3.resolve(toPath2(options.cwd)??""),{root}=path3.parse(directory),stopAt=path3.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(path3.resolve(directory,foundPath)),directory===stopAt||matches.length>=limit))break;directory=path3.dirname(directory);}return matches}async function findUp(name,options={}){return (await findUpMultiple(name,{...options,limit:1}))[0]}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$1(__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: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:getProjectRoot()}),projectName="storybook:"+process.env.STORYBOOK_CONFIG_DIR;try{this.vitest=await createVitest("test",{root:vitestWorkspaceConfig?dirname$1(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(`
15
+ `);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+=`
16
+
17
+ Please install the @vitest/${isIstanbul?"coverage-istanbul":"coverage-v8"} package to collect coverage
18
+ `),this.testManager.reportFatalError(message,e);return}await this.setupWatchers();}async restartVitest({coverage}){return await this.vitestRestartPromise,this.vitestRestartPromise=new Promise(async(resolve,reject)=>{try{await this.runningPromise,await this.vitest?.close(),await this.startVitest({coverage}),resolve();}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=path.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)&&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(`
19
+ `)??"",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(resolve=>{let testManager=new _TestManager({...options,onReady:()=>{resolve(testManager),options.onReady?.();}});})}};var require2=createRequire(import.meta.url),{experimental_UniversalStore:UniversalStore,experimental_getStatusStore:getStatusStore,experimental_getTestProviderStore:getTestProviderStore}=require2("storybook/internal/core-server"),channel=new Channel({async:!0,transport:{send:event=>{process3.send?.(event);},setHandler:handler=>{process3.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.send?.({type:"ready"});},storybookOptions:{configDir:process3.env.STORYBOOK_CONFIG_DIR||""}});var exit=(code=0)=>{channel?.removeAllListeners(),process3.exit(code);},createUnhandledErrorHandler=message=>async error=>{try{let payload={message,error:{message:error.message,name:error.name,stack:error.stack,cause:error.cause}};process3.send?.({type:"uncaught-error",payload});}finally{exit(1);}};process3.on("uncaughtException",createUnhandledErrorHandler("Uncaught exception in the test runner process"));process3.on("unhandledRejection",createUnhandledErrorHandler("Unhandled rejection in the test runner process"));process3.on("exit",exit);process3.on("SIGINT",()=>exit(0));process3.on("SIGTERM",()=>exit(0));