'use strict';

var promises = require('fs/promises');
var common = require('storybook/internal/common');
var coreServer = require('storybook/internal/core-server');
var telemetry = require('storybook/internal/telemetry');
var tsDedent = require('ts-dedent');
var buffer = require('buffer');
var path = require('path');
var childProcess = require('child_process');
var process6 = require('process');
var url = require('url');
var os = require('os');
var fs = require('fs');
var promises$1 = require('timers/promises');
var util = require('util');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var path__default = /*#__PURE__*/_interopDefault(path);
var childProcess__default = /*#__PURE__*/_interopDefault(childProcess);
var process6__default = /*#__PURE__*/_interopDefault(process6);
var os__default = /*#__PURE__*/_interopDefault(os);

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 require_windows=__commonJS({"../../node_modules/isexe/windows.js"(exports,module){module.exports=isexe;isexe.sync=sync;var fs=__require("fs");function checkPathExt(path4,options){var pathext=options.pathExt!==void 0?options.pathExt:process.env.PATHEXT;if(!pathext||(pathext=pathext.split(";"),pathext.indexOf("")!==-1))return !0;for(var i=0;i<pathext.length;i++){var p=pathext[i].toLowerCase();if(p&&path4.substr(-p.length).toLowerCase()===p)return !0}return !1}function checkStat(stat,path4,options){return !stat.isSymbolicLink()&&!stat.isFile()?!1:checkPathExt(path4,options)}function isexe(path4,options,cb){fs.stat(path4,function(er,stat){cb(er,er?!1:checkStat(stat,path4,options));});}function sync(path4,options){return checkStat(fs.statSync(path4),path4,options)}}});var require_mode=__commonJS({"../../node_modules/isexe/mode.js"(exports,module){module.exports=isexe;isexe.sync=sync;var fs=__require("fs");function isexe(path4,options,cb){fs.stat(path4,function(er,stat){cb(er,er?!1:checkStat(stat,options));});}function sync(path4,options){return checkStat(fs.statSync(path4),options)}function checkStat(stat,options){return stat.isFile()&&checkMode(stat,options)}function checkMode(stat,options){var mod=stat.mode,uid=stat.uid,gid=stat.gid,myUid=options.uid!==void 0?options.uid:process.getuid&&process.getuid(),myGid=options.gid!==void 0?options.gid:process.getgid&&process.getgid(),u=parseInt("100",8),g=parseInt("010",8),o=parseInt("001",8),ug=u|g,ret=mod&o||mod&g&&gid===myGid||mod&u&&uid===myUid||mod&ug&&myUid===0;return ret}}});var require_isexe=__commonJS({"../../node_modules/isexe/index.js"(exports,module){__require("fs");var core;process.platform==="win32"||global.TESTING_WINDOWS?core=require_windows():core=require_mode();module.exports=isexe;isexe.sync=sync;function isexe(path4,options,cb){if(typeof options=="function"&&(cb=options,options={}),!cb){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(resolve2,reject){isexe(path4,options||{},function(er,is){er?reject(er):resolve2(is);});})}core(path4,options||{},function(er,is){er&&(er.code==="EACCES"||options&&options.ignoreErrors)&&(er=null,is=!1),cb(er,is);});}function sync(path4,options){try{return core.sync(path4,options||{})}catch(er){if(options&&options.ignoreErrors||er.code==="EACCES")return !1;throw er}}}});var require_which=__commonJS({"../../node_modules/which/which.js"(exports,module){var isWindows=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",path4=__require("path"),COLON=isWindows?";":":",isexe=require_isexe(),getNotFoundError=cmd=>Object.assign(new Error(`not found: ${cmd}`),{code:"ENOENT"}),getPathInfo=(cmd,opt)=>{let colon=opt.colon||COLON,pathEnv=cmd.match(/\//)||isWindows&&cmd.match(/\\/)?[""]:[...isWindows?[process.cwd()]:[],...(opt.path||process.env.PATH||"").split(colon)],pathExtExe=isWindows?opt.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",pathExt=isWindows?pathExtExe.split(colon):[""];return isWindows&&cmd.indexOf(".")!==-1&&pathExt[0]!==""&&pathExt.unshift(""),{pathEnv,pathExt,pathExtExe}},which=(cmd,opt,cb)=>{typeof opt=="function"&&(cb=opt,opt={}),opt||(opt={});let{pathEnv,pathExt,pathExtExe}=getPathInfo(cmd,opt),found=[],step=i=>new Promise((resolve2,reject)=>{if(i===pathEnv.length)return opt.all&&found.length?resolve2(found):reject(getNotFoundError(cmd));let ppRaw=pathEnv[i],pathPart=/^".*"$/.test(ppRaw)?ppRaw.slice(1,-1):ppRaw,pCmd=path4.join(pathPart,cmd),p=!pathPart&&/^\.[\\\/]/.test(cmd)?cmd.slice(0,2)+pCmd:pCmd;resolve2(subStep(p,i,0));}),subStep=(p,i,ii)=>new Promise((resolve2,reject)=>{if(ii===pathExt.length)return resolve2(step(i+1));let ext=pathExt[ii];isexe(p+ext,{pathExt:pathExtExe},(er,is)=>{if(!er&&is)if(opt.all)found.push(p+ext);else return resolve2(p+ext);return resolve2(subStep(p,i,ii+1))});});return cb?step(0).then(res=>cb(null,res),cb):step(0)},whichSync=(cmd,opt)=>{opt=opt||{};let{pathEnv,pathExt,pathExtExe}=getPathInfo(cmd,opt),found=[];for(let i=0;i<pathEnv.length;i++){let ppRaw=pathEnv[i],pathPart=/^".*"$/.test(ppRaw)?ppRaw.slice(1,-1):ppRaw,pCmd=path4.join(pathPart,cmd),p=!pathPart&&/^\.[\\\/]/.test(cmd)?cmd.slice(0,2)+pCmd:pCmd;for(let j=0;j<pathExt.length;j++){let cur=p+pathExt[j];try{if(isexe.sync(cur,{pathExt:pathExtExe}))if(opt.all)found.push(cur);else return cur}catch{}}}if(opt.all&&found.length)return found;if(opt.nothrow)return null;throw getNotFoundError(cmd)};module.exports=which;which.sync=whichSync;}});var require_path_key=__commonJS({"../../node_modules/path-key/index.js"(exports,module){var pathKey2=(options={})=>{let environment=options.env||process.env;return (options.platform||process.platform)!=="win32"?"PATH":Object.keys(environment).reverse().find(key=>key.toUpperCase()==="PATH")||"Path"};module.exports=pathKey2;module.exports.default=pathKey2;}});var require_resolveCommand=__commonJS({"../../node_modules/cross-spawn/lib/util/resolveCommand.js"(exports,module){var path4=__require("path"),which=require_which(),getPathKey=require_path_key();function resolveCommandAttempt(parsed,withoutPathExt){let env=parsed.options.env||process.env,cwd=process.cwd(),hasCustomCwd=parsed.options.cwd!=null,shouldSwitchCwd=hasCustomCwd&&process.chdir!==void 0&&!process.chdir.disabled;if(shouldSwitchCwd)try{process.chdir(parsed.options.cwd);}catch{}let resolved;try{resolved=which.sync(parsed.command,{path:env[getPathKey({env})],pathExt:withoutPathExt?path4.delimiter:void 0});}catch{}finally{shouldSwitchCwd&&process.chdir(cwd);}return resolved&&(resolved=path4.resolve(hasCustomCwd?parsed.options.cwd:"",resolved)),resolved}function resolveCommand(parsed){return resolveCommandAttempt(parsed)||resolveCommandAttempt(parsed,!0)}module.exports=resolveCommand;}});var require_escape=__commonJS({"../../node_modules/cross-spawn/lib/util/escape.js"(exports,module){var metaCharsRegExp=/([()\][%!^"`<>&|;, *?])/g;function escapeCommand(arg){return arg=arg.replace(metaCharsRegExp,"^$1"),arg}function escapeArgument(arg,doubleEscapeMetaChars){return arg=`${arg}`,arg=arg.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),arg=arg.replace(/(?=(\\+?)?)\1$/,"$1$1"),arg=`"${arg}"`,arg=arg.replace(metaCharsRegExp,"^$1"),doubleEscapeMetaChars&&(arg=arg.replace(metaCharsRegExp,"^$1")),arg}module.exports.command=escapeCommand;module.exports.argument=escapeArgument;}});var require_shebang_regex=__commonJS({"../../node_modules/shebang-regex/index.js"(exports,module){module.exports=/^#!(.*)/;}});var require_shebang_command=__commonJS({"../../node_modules/shebang-command/index.js"(exports,module){var shebangRegex=require_shebang_regex();module.exports=(string="")=>{let match=string.match(shebangRegex);if(!match)return null;let[path4,argument]=match[0].replace(/#! ?/,"").split(" "),binary=path4.split("/").pop();return binary==="env"?argument:argument?`${binary} ${argument}`:binary};}});var require_readShebang=__commonJS({"../../node_modules/cross-spawn/lib/util/readShebang.js"(exports,module){var fs=__require("fs"),shebangCommand=require_shebang_command();function readShebang(command){let buffer=Buffer.alloc(150),fd;try{fd=fs.openSync(command,"r"),fs.readSync(fd,buffer,0,150,0),fs.closeSync(fd);}catch{}return shebangCommand(buffer.toString())}module.exports=readShebang;}});var require_parse=__commonJS({"../../node_modules/cross-spawn/lib/parse.js"(exports,module){var path4=__require("path"),resolveCommand=require_resolveCommand(),escape=require_escape(),readShebang=require_readShebang(),isWin=process.platform==="win32",isExecutableRegExp=/\.(?:com|exe)$/i,isCmdShimRegExp=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function detectShebang(parsed){parsed.file=resolveCommand(parsed);let shebang=parsed.file&&readShebang(parsed.file);return shebang?(parsed.args.unshift(parsed.file),parsed.command=shebang,resolveCommand(parsed)):parsed.file}function parseNonShell(parsed){if(!isWin)return parsed;let commandFile=detectShebang(parsed),needsShell=!isExecutableRegExp.test(commandFile);if(parsed.options.forceShell||needsShell){let needsDoubleEscapeMetaChars=isCmdShimRegExp.test(commandFile);parsed.command=path4.normalize(parsed.command),parsed.command=escape.command(parsed.command),parsed.args=parsed.args.map(arg=>escape.argument(arg,needsDoubleEscapeMetaChars));let shellCommand=[parsed.command].concat(parsed.args).join(" ");parsed.args=["/d","/s","/c",`"${shellCommand}"`],parsed.command=process.env.comspec||"cmd.exe",parsed.options.windowsVerbatimArguments=!0;}return parsed}function parse2(command,args,options){args&&!Array.isArray(args)&&(options=args,args=null),args=args?args.slice(0):[],options=Object.assign({},options);let parsed={command,args,options,file:void 0,original:{command,args}};return options.shell?parsed:parseNonShell(parsed)}module.exports=parse2;}});var require_enoent=__commonJS({"../../node_modules/cross-spawn/lib/enoent.js"(exports,module){var isWin=process.platform==="win32";function notFoundError(original,syscall){return Object.assign(new Error(`${syscall} ${original.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${syscall} ${original.command}`,path:original.command,spawnargs:original.args})}function hookChildProcess(cp,parsed){if(!isWin)return;let originalEmit=cp.emit;cp.emit=function(name,arg1){if(name==="exit"){let err=verifyENOENT(arg1,parsed);if(err)return originalEmit.call(cp,"error",err)}return originalEmit.apply(cp,arguments)};}function verifyENOENT(status,parsed){return isWin&&status===1&&!parsed.file?notFoundError(parsed.original,"spawn"):null}function verifyENOENTSync(status,parsed){return isWin&&status===1&&!parsed.file?notFoundError(parsed.original,"spawnSync"):null}module.exports={hookChildProcess,verifyENOENT,verifyENOENTSync,notFoundError};}});var require_cross_spawn=__commonJS({"../../node_modules/cross-spawn/index.js"(exports,module){var cp=__require("child_process"),parse2=require_parse(),enoent=require_enoent();function spawn(command,args,options){let parsed=parse2(command,args,options),spawned=cp.spawn(parsed.command,parsed.args,parsed.options);return enoent.hookChildProcess(spawned,parsed),spawned}function spawnSync(command,args,options){let parsed=parse2(command,args,options),result=cp.spawnSync(parsed.command,parsed.args,parsed.options);return result.error=result.error||enoent.verifyENOENTSync(result.status,parsed),result}module.exports=spawn;module.exports.spawn=spawn;module.exports.sync=spawnSync;module.exports._parse=parse2;module.exports._enoent=enoent;}});var require_merge_stream=__commonJS({"../../node_modules/merge-stream/index.js"(exports,module){var{PassThrough}=__require("stream");module.exports=function(){var sources=[],output=new PassThrough({objectMode:!0});return output.setMaxListeners(0),output.add=add,output.isEmpty=isEmpty,output.on("unpipe",remove),Array.prototype.slice.call(arguments).forEach(add),output;function add(source){return Array.isArray(source)?(source.forEach(add),this):(sources.push(source),source.once("end",remove.bind(null,source)),source.once("error",output.emit.bind(output,"error")),source.pipe(output,{end:!1}),this)}function isEmpty(){return sources.length==0}function remove(source){sources=sources.filter(function(it){return it!==source}),!sources.length&&output.readable&&output.end();}};}});function noop(){}function getSymbols(object){return Object.getOwnPropertySymbols(object).filter(symbol=>Object.prototype.propertyIsEnumerable.call(object,symbol))}function getTag(value){return value==null?value===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(value)}var regexpTag="[object RegExp]",stringTag="[object String]",numberTag="[object Number]",booleanTag="[object Boolean]",argumentsTag="[object Arguments]",symbolTag="[object Symbol]",dateTag="[object Date]",mapTag="[object Map]",setTag="[object Set]",arrayTag="[object Array]",functionTag="[object Function]",arrayBufferTag="[object ArrayBuffer]",objectTag="[object Object]",errorTag="[object Error]",dataViewTag="[object DataView]",uint8ArrayTag="[object Uint8Array]",uint8ClampedArrayTag="[object Uint8ClampedArray]",uint16ArrayTag="[object Uint16Array]",uint32ArrayTag="[object Uint32Array]",bigUint64ArrayTag="[object BigUint64Array]",int8ArrayTag="[object Int8Array]",int16ArrayTag="[object Int16Array]",int32ArrayTag="[object Int32Array]",bigInt64ArrayTag="[object BigInt64Array]",float32ArrayTag="[object Float32Array]",float64ArrayTag="[object Float64Array]";function isPlainObject(value){if(!value||typeof value!="object")return !1;let proto=Object.getPrototypeOf(value);return proto===null||proto===Object.prototype||Object.getPrototypeOf(proto)===null?Object.prototype.toString.call(value)==="[object Object]":!1}function eq(value,other){return value===other||Number.isNaN(value)&&Number.isNaN(other)}function isEqualWith(a,b,areValuesEqual){return isEqualWithImpl(a,b,void 0,void 0,void 0,void 0,areValuesEqual)}function isEqualWithImpl(a,b,property,aParent,bParent,stack,areValuesEqual){let result=areValuesEqual(a,b,property,aParent,bParent,stack);if(result!==void 0)return result;if(typeof a==typeof b)switch(typeof a){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return a===b;case"number":return a===b||Object.is(a,b);case"function":return a===b;case"object":return areObjectsEqual(a,b,stack,areValuesEqual)}return areObjectsEqual(a,b,stack,areValuesEqual)}function areObjectsEqual(a,b,stack,areValuesEqual){if(Object.is(a,b))return !0;let aTag=getTag(a),bTag=getTag(b);if(aTag===argumentsTag&&(aTag=objectTag),bTag===argumentsTag&&(bTag=objectTag),aTag!==bTag)return !1;switch(aTag){case stringTag:return a.toString()===b.toString();case numberTag:{let x=a.valueOf(),y=b.valueOf();return eq(x,y)}case booleanTag:case dateTag:case symbolTag:return Object.is(a.valueOf(),b.valueOf());case regexpTag:return a.source===b.source&&a.flags===b.flags;case functionTag:return a===b}stack=stack??new Map;let aStack=stack.get(a),bStack=stack.get(b);if(aStack!=null&&bStack!=null)return aStack===b;stack.set(a,b),stack.set(b,a);try{switch(aTag){case mapTag:{if(a.size!==b.size)return !1;for(let[key,value]of a.entries())if(!b.has(key)||!isEqualWithImpl(value,b.get(key),key,a,b,stack,areValuesEqual))return !1;return !0}case setTag:{if(a.size!==b.size)return !1;let aValues=Array.from(a.values()),bValues=Array.from(b.values());for(let i=0;i<aValues.length;i++){let aValue=aValues[i],index=bValues.findIndex(bValue=>isEqualWithImpl(aValue,bValue,void 0,a,b,stack,areValuesEqual));if(index===-1)return !1;bValues.splice(index,1);}return !0}case arrayTag:case uint8ArrayTag:case uint8ClampedArrayTag:case uint16ArrayTag:case uint32ArrayTag:case bigUint64ArrayTag:case int8ArrayTag:case int16ArrayTag:case int32ArrayTag:case bigInt64ArrayTag:case float32ArrayTag:case float64ArrayTag:{if(typeof Buffer<"u"&&Buffer.isBuffer(a)!==Buffer.isBuffer(b)||a.length!==b.length)return !1;for(let i=0;i<a.length;i++)if(!isEqualWithImpl(a[i],b[i],i,a,b,stack,areValuesEqual))return !1;return !0}case arrayBufferTag:return a.byteLength!==b.byteLength?!1:areObjectsEqual(new Uint8Array(a),new Uint8Array(b),stack,areValuesEqual);case dataViewTag:return a.byteLength!==b.byteLength||a.byteOffset!==b.byteOffset?!1:areObjectsEqual(new Uint8Array(a),new Uint8Array(b),stack,areValuesEqual);case errorTag:return a.name===b.name&&a.message===b.message;case objectTag:{if(!(areObjectsEqual(a.constructor,b.constructor,stack,areValuesEqual)||isPlainObject(a)&&isPlainObject(b)))return !1;let aKeys=[...Object.keys(a),...getSymbols(a)],bKeys=[...Object.keys(b),...getSymbols(b)];if(aKeys.length!==bKeys.length)return !1;for(let i=0;i<aKeys.length;i++){let propKey=aKeys[i],aProp=a[propKey];if(!Object.hasOwn(b,propKey))return !1;let bProp=b[propKey];if(!isEqualWithImpl(aProp,bProp,propKey,a,b,stack,areValuesEqual))return !1}return !0}default:return !1}}finally{stack.delete(a),stack.delete(b);}}function isEqual(a,b){return isEqualWith(a,b,noop)}var import_picocolors2=__toESM(require_picocolors());var ADDON_ID2="storybook/test",STORYBOOK_ADDON_TEST_CHANNEL="STORYBOOK_ADDON_TEST_CHANNEL";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}}};var STORE_CHANNEL_EVENT_NAME=`UNIVERSAL_STORE:${storeOptions.id}`,STATUS_STORE_CHANNEL_EVENT_NAME="UNIVERSAL_STORE:storybook/status",TEST_PROVIDER_STORE_CHANNEL_EVENT_NAME="UNIVERSAL_STORE:storybook/test-provider";var import_picocolors=__toESM(require_picocolors());var log=message=>{console.log(`${import_picocolors.default.magenta(ADDON_ID2)}: ${message.toString().trim()}`);};var import_cross_spawn=__toESM(require_cross_spawn(),1);function stripFinalNewline(input){let LF=typeof input=="string"?`
`:10,CR=typeof input=="string"?"\r":13;return input[input.length-1]===LF&&(input=input.slice(0,-1)),input[input.length-1]===CR&&(input=input.slice(0,-1)),input}function pathKey(options={}){let{env=process.env,platform=process.platform}=options;return platform!=="win32"?"PATH":Object.keys(env).reverse().find(key=>key.toUpperCase()==="PATH")||"Path"}var npmRunPath=({cwd=process6__default.default.cwd(),path:pathOption=process6__default.default.env[pathKey()],preferLocal=!0,execPath=process6__default.default.execPath,addExecPath=!0}={})=>{let cwdString=cwd instanceof URL?url.fileURLToPath(cwd):cwd,cwdPath=path__default.default.resolve(cwdString),result=[];return preferLocal&&applyPreferLocal(result,cwdPath),addExecPath&&applyExecPath(result,execPath,cwdPath),[...result,pathOption].join(path__default.default.delimiter)},applyPreferLocal=(result,cwdPath)=>{let previous;for(;previous!==cwdPath;)result.push(path__default.default.join(cwdPath,"node_modules/.bin")),previous=cwdPath,cwdPath=path__default.default.resolve(cwdPath,"..");},applyExecPath=(result,execPath,cwdPath)=>{let execPathString=execPath instanceof URL?url.fileURLToPath(execPath):execPath;result.push(path__default.default.resolve(cwdPath,execPathString,".."));},npmRunPathEnv=({env=process6__default.default.env,...options}={})=>{env={...env};let pathName=pathKey({env});return options.path=env[pathName],env[pathName]=npmRunPath(options),env};var copyProperty=(to,from,property,ignoreNonConfigurable)=>{if(property==="length"||property==="prototype"||property==="arguments"||property==="caller")return;let toDescriptor=Object.getOwnPropertyDescriptor(to,property),fromDescriptor=Object.getOwnPropertyDescriptor(from,property);!canCopyProperty(toDescriptor,fromDescriptor)&&ignoreNonConfigurable||Object.defineProperty(to,property,fromDescriptor);},canCopyProperty=function(toDescriptor,fromDescriptor){return toDescriptor===void 0||toDescriptor.configurable||toDescriptor.writable===fromDescriptor.writable&&toDescriptor.enumerable===fromDescriptor.enumerable&&toDescriptor.configurable===fromDescriptor.configurable&&(toDescriptor.writable||toDescriptor.value===fromDescriptor.value)},changePrototype=(to,from)=>{let fromPrototype=Object.getPrototypeOf(from);fromPrototype!==Object.getPrototypeOf(to)&&Object.setPrototypeOf(to,fromPrototype);},wrappedToString=(withName,fromBody)=>`/* Wrapped ${withName}*/
${fromBody}`,toStringDescriptor=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),toStringName=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),changeToString=(to,from,name)=>{let withName=name===""?"":`with ${name.trim()}() `,newToString=wrappedToString.bind(null,withName,from.toString());Object.defineProperty(newToString,"name",toStringName),Object.defineProperty(to,"toString",{...toStringDescriptor,value:newToString});};function mimicFunction(to,from,{ignoreNonConfigurable=!1}={}){let{name}=to;for(let property of Reflect.ownKeys(from))copyProperty(to,from,property,ignoreNonConfigurable);return changePrototype(to,from),changeToString(to,from,name),to}var calledFunctions=new WeakMap,onetime=(function_,options={})=>{if(typeof function_!="function")throw new TypeError("Expected a function");let returnValue,callCount=0,functionName=function_.displayName||function_.name||"<anonymous>",onetime2=function(...arguments_){if(calledFunctions.set(onetime2,++callCount),callCount===1)returnValue=function_.apply(this,arguments_),function_=null;else if(options.throw===!0)throw new Error(`Function \`${functionName}\` can only be called once`);return returnValue};return mimicFunction(onetime2,function_),calledFunctions.set(onetime2,callCount),onetime2};onetime.callCount=function_=>{if(!calledFunctions.has(function_))throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`);return calledFunctions.get(function_)};var onetime_default=onetime;var getRealtimeSignals=()=>{let length=SIGRTMAX-SIGRTMIN+1;return Array.from({length},getRealtimeSignal)},getRealtimeSignal=(value,index)=>({name:`SIGRT${index+1}`,number:SIGRTMIN+index,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),SIGRTMIN=34,SIGRTMAX=64;var SIGNALS=[{name:"SIGHUP",number:1,action:"terminate",description:"Terminal closed",standard:"posix"},{name:"SIGINT",number:2,action:"terminate",description:"User interruption with CTRL-C",standard:"ansi"},{name:"SIGQUIT",number:3,action:"core",description:"User interruption with CTRL-\\",standard:"posix"},{name:"SIGILL",number:4,action:"core",description:"Invalid machine instruction",standard:"ansi"},{name:"SIGTRAP",number:5,action:"core",description:"Debugger breakpoint",standard:"posix"},{name:"SIGABRT",number:6,action:"core",description:"Aborted",standard:"ansi"},{name:"SIGIOT",number:6,action:"core",description:"Aborted",standard:"bsd"},{name:"SIGBUS",number:7,action:"core",description:"Bus error due to misaligned, non-existing address or paging error",standard:"bsd"},{name:"SIGEMT",number:7,action:"terminate",description:"Command should be emulated but is not implemented",standard:"other"},{name:"SIGFPE",number:8,action:"core",description:"Floating point arithmetic error",standard:"ansi"},{name:"SIGKILL",number:9,action:"terminate",description:"Forced termination",standard:"posix",forced:!0},{name:"SIGUSR1",number:10,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGSEGV",number:11,action:"core",description:"Segmentation fault",standard:"ansi"},{name:"SIGUSR2",number:12,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGPIPE",number:13,action:"terminate",description:"Broken pipe or socket",standard:"posix"},{name:"SIGALRM",number:14,action:"terminate",description:"Timeout or timer",standard:"posix"},{name:"SIGTERM",number:15,action:"terminate",description:"Termination",standard:"ansi"},{name:"SIGSTKFLT",number:16,action:"terminate",description:"Stack is empty or overflowed",standard:"other"},{name:"SIGCHLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"posix"},{name:"SIGCLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"other"},{name:"SIGCONT",number:18,action:"unpause",description:"Unpaused",standard:"posix",forced:!0},{name:"SIGSTOP",number:19,action:"pause",description:"Paused",standard:"posix",forced:!0},{name:"SIGTSTP",number:20,action:"pause",description:'Paused using CTRL-Z or "suspend"',standard:"posix"},{name:"SIGTTIN",number:21,action:"pause",description:"Background process cannot read terminal input",standard:"posix"},{name:"SIGBREAK",number:21,action:"terminate",description:"User interruption with CTRL-BREAK",standard:"other"},{name:"SIGTTOU",number:22,action:"pause",description:"Background process cannot write to terminal output",standard:"posix"},{name:"SIGURG",number:23,action:"ignore",description:"Socket received out-of-band data",standard:"bsd"},{name:"SIGXCPU",number:24,action:"core",description:"Process timed out",standard:"bsd"},{name:"SIGXFSZ",number:25,action:"core",description:"File too big",standard:"bsd"},{name:"SIGVTALRM",number:26,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGPROF",number:27,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGWINCH",number:28,action:"ignore",description:"Terminal window size changed",standard:"bsd"},{name:"SIGIO",number:29,action:"terminate",description:"I/O is available",standard:"other"},{name:"SIGPOLL",number:29,action:"terminate",description:"Watched event",standard:"other"},{name:"SIGINFO",number:29,action:"ignore",description:"Request for process information",standard:"other"},{name:"SIGPWR",number:30,action:"terminate",description:"Device running out of power",standard:"systemv"},{name:"SIGSYS",number:31,action:"core",description:"Invalid system call",standard:"other"},{name:"SIGUNUSED",number:31,action:"terminate",description:"Invalid system call",standard:"other"}];var getSignals=()=>{let realtimeSignals=getRealtimeSignals();return [...SIGNALS,...realtimeSignals].map(normalizeSignal)},normalizeSignal=({name,number:defaultNumber,description,action,forced=!1,standard})=>{let{signals:{[name]:constantSignal}}=os.constants,supported=constantSignal!==void 0;return {name,number:supported?constantSignal:defaultNumber,description,supported,action,forced,standard}};var getSignalsByName=()=>{let signals2=getSignals();return Object.fromEntries(signals2.map(getSignalByName))},getSignalByName=({name,number,description,supported,action,forced,standard})=>[name,{name,number,description,supported,action,forced,standard}],signalsByName=getSignalsByName(),getSignalsByNumber=()=>{let signals2=getSignals(),length=65,signalsA=Array.from({length},(value,number)=>getSignalByNumber(number,signals2));return Object.assign({},...signalsA)},getSignalByNumber=(number,signals2)=>{let signal=findSignalByNumber(number,signals2);if(signal===void 0)return {};let{name,description,supported,action,forced,standard}=signal;return {[number]:{name,number,description,supported,action,forced,standard}}},findSignalByNumber=(number,signals2)=>{let signal=signals2.find(({name})=>os.constants.signals[name]===number);return signal!==void 0?signal:signals2.find(signalA=>signalA.number===number)};getSignalsByNumber();var getErrorPrefix=({timedOut,timeout,errorCode,signal,signalDescription,exitCode,isCanceled})=>timedOut?`timed out after ${timeout} milliseconds`:isCanceled?"was canceled":errorCode!==void 0?`failed with ${errorCode}`:signal!==void 0?`was killed with ${signal} (${signalDescription})`:exitCode!==void 0?`failed with exit code ${exitCode}`:"failed",makeError=({stdout,stderr,all,error,signal,exitCode,command,escapedCommand,timedOut,isCanceled,killed,parsed:{options:{timeout,cwd=process6__default.default.cwd()}}})=>{exitCode=exitCode===null?void 0:exitCode,signal=signal===null?void 0:signal;let signalDescription=signal===void 0?void 0:signalsByName[signal].description,errorCode=error&&error.code,execaMessage=`Command ${getErrorPrefix({timedOut,timeout,errorCode,signal,signalDescription,exitCode,isCanceled})}: ${command}`,isError=Object.prototype.toString.call(error)==="[object Error]",shortMessage=isError?`${execaMessage}
${error.message}`:execaMessage,message=[shortMessage,stderr,stdout].filter(Boolean).join(`
`);return isError?(error.originalMessage=error.message,error.message=message):error=new Error(message),error.shortMessage=shortMessage,error.command=command,error.escapedCommand=escapedCommand,error.exitCode=exitCode,error.signal=signal,error.signalDescription=signalDescription,error.stdout=stdout,error.stderr=stderr,error.cwd=cwd,all!==void 0&&(error.all=all),"bufferedData"in error&&delete error.bufferedData,error.failed=!0,error.timedOut=!!timedOut,error.isCanceled=isCanceled,error.killed=killed&&!timedOut,error};var aliases=["stdin","stdout","stderr"],hasAlias=options=>aliases.some(alias=>options[alias]!==void 0),normalizeStdio=options=>{if(!options)return;let{stdio}=options;if(stdio===void 0)return aliases.map(alias=>options[alias]);if(hasAlias(options))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${aliases.map(alias=>`\`${alias}\``).join(", ")}`);if(typeof stdio=="string")return stdio;if(!Array.isArray(stdio))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``);let length=Math.max(stdio.length,aliases.length);return Array.from({length},(value,index)=>stdio[index])},normalizeStdioNode=options=>{let stdio=normalizeStdio(options);return stdio==="ipc"?"ipc":stdio===void 0||typeof stdio=="string"?[stdio,stdio,stdio,"ipc"]:stdio.includes("ipc")?stdio:[...stdio,"ipc"]};var signals=[];signals.push("SIGHUP","SIGINT","SIGTERM");process.platform!=="win32"&&signals.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&signals.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var processOk=process7=>!!process7&&typeof process7=="object"&&typeof process7.removeListener=="function"&&typeof process7.emit=="function"&&typeof process7.reallyExit=="function"&&typeof process7.listeners=="function"&&typeof process7.kill=="function"&&typeof process7.pid=="number"&&typeof process7.on=="function",kExitEmitter=Symbol.for("signal-exit emitter"),global2=globalThis,ObjectDefineProperty=Object.defineProperty.bind(Object),Emitter=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(global2[kExitEmitter])return global2[kExitEmitter];ObjectDefineProperty(global2,kExitEmitter,{value:this,writable:!1,enumerable:!1,configurable:!1});}on(ev,fn){this.listeners[ev].push(fn);}removeListener(ev,fn){let list=this.listeners[ev],i=list.indexOf(fn);i!==-1&&(i===0&&list.length===1?list.length=0:list.splice(i,1));}emit(ev,code,signal){if(this.emitted[ev])return !1;this.emitted[ev]=!0;let ret=!1;for(let fn of this.listeners[ev])ret=fn(code,signal)===!0||ret;return ev==="exit"&&(ret=this.emit("afterExit",code,signal)||ret),ret}},SignalExitBase=class{},signalExitWrap=handler=>({onExit(cb,opts){return handler.onExit(cb,opts)},load(){return handler.load()},unload(){return handler.unload()}}),SignalExitFallback=class extends SignalExitBase{onExit(){return ()=>{}}load(){}unload(){}},SignalExit=class extends SignalExitBase{#hupSig=process4.platform==="win32"?"SIGINT":"SIGHUP";#emitter=new Emitter;#process;#originalProcessEmit;#originalProcessReallyExit;#sigListeners={};#loaded=!1;constructor(process7){super(),this.#process=process7,this.#sigListeners={};for(let sig of signals)this.#sigListeners[sig]=()=>{let listeners=this.#process.listeners(sig),{count}=this.#emitter,p=process7;if(typeof p.__signal_exit_emitter__=="object"&&typeof p.__signal_exit_emitter__.count=="number"&&(count+=p.__signal_exit_emitter__.count),listeners.length===count){this.unload();let ret=this.#emitter.emit("exit",null,sig),s=sig==="SIGHUP"?this.#hupSig:sig;ret||process7.kill(process7.pid,s);}};this.#originalProcessReallyExit=process7.reallyExit,this.#originalProcessEmit=process7.emit;}onExit(cb,opts){if(!processOk(this.#process))return ()=>{};this.#loaded===!1&&this.load();let ev=opts?.alwaysLast?"afterExit":"exit";return this.#emitter.on(ev,cb),()=>{this.#emitter.removeListener(ev,cb),this.#emitter.listeners.exit.length===0&&this.#emitter.listeners.afterExit.length===0&&this.unload();}}load(){if(!this.#loaded){this.#loaded=!0,this.#emitter.count+=1;for(let sig of signals)try{let fn=this.#sigListeners[sig];fn&&this.#process.on(sig,fn);}catch{}this.#process.emit=(ev,...a)=>this.#processEmit(ev,...a),this.#process.reallyExit=code=>this.#processReallyExit(code);}}unload(){this.#loaded&&(this.#loaded=!1,signals.forEach(sig=>{let listener=this.#sigListeners[sig];if(!listener)throw new Error("Listener not defined for signal: "+sig);try{this.#process.removeListener(sig,listener);}catch{}}),this.#process.emit=this.#originalProcessEmit,this.#process.reallyExit=this.#originalProcessReallyExit,this.#emitter.count-=1);}#processReallyExit(code){return processOk(this.#process)?(this.#process.exitCode=code||0,this.#emitter.emit("exit",this.#process.exitCode,null),this.#originalProcessReallyExit.call(this.#process,this.#process.exitCode)):0}#processEmit(ev,...args){let og=this.#originalProcessEmit;if(ev==="exit"&&processOk(this.#process)){typeof args[0]=="number"&&(this.#process.exitCode=args[0]);let ret=og.call(this.#process,ev,...args);return this.#emitter.emit("exit",this.#process.exitCode,null),ret}else return og.call(this.#process,ev,...args)}},process4=globalThis.process,{onExit,load,unload}=signalExitWrap(processOk(process4)?new SignalExit(process4):new SignalExitFallback);var DEFAULT_FORCE_KILL_TIMEOUT=1e3*5,spawnedKill=(kill,signal="SIGTERM",options={})=>{let killResult=kill(signal);return setKillTimeout(kill,signal,options,killResult),killResult},setKillTimeout=(kill,signal,options,killResult)=>{if(!shouldForceKill(signal,options,killResult))return;let timeout=getForceKillAfterTimeout(options),t=setTimeout(()=>{kill("SIGKILL");},timeout);t.unref&&t.unref();},shouldForceKill=(signal,{forceKillAfterTimeout},killResult)=>isSigterm(signal)&&forceKillAfterTimeout!==!1&&killResult,isSigterm=signal=>signal===os__default.default.constants.signals.SIGTERM||typeof signal=="string"&&signal.toUpperCase()==="SIGTERM",getForceKillAfterTimeout=({forceKillAfterTimeout=!0})=>{if(forceKillAfterTimeout===!0)return DEFAULT_FORCE_KILL_TIMEOUT;if(!Number.isFinite(forceKillAfterTimeout)||forceKillAfterTimeout<0)throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${forceKillAfterTimeout}\` (${typeof forceKillAfterTimeout})`);return forceKillAfterTimeout},spawnedCancel=(spawned,context)=>{spawned.kill()&&(context.isCanceled=!0);},timeoutKill=(spawned,signal,reject)=>{spawned.kill(signal),reject(Object.assign(new Error("Timed out"),{timedOut:!0,signal}));},setupTimeout=(spawned,{timeout,killSignal="SIGTERM"},spawnedPromise)=>{if(timeout===0||timeout===void 0)return spawnedPromise;let timeoutId,timeoutPromise=new Promise((resolve2,reject)=>{timeoutId=setTimeout(()=>{timeoutKill(spawned,killSignal,reject);},timeout);}),safeSpawnedPromise=spawnedPromise.finally(()=>{clearTimeout(timeoutId);});return Promise.race([timeoutPromise,safeSpawnedPromise])},validateTimeout=({timeout})=>{if(timeout!==void 0&&(!Number.isFinite(timeout)||timeout<0))throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`)},setExitHandler=async(spawned,{cleanup,detached},timedPromise)=>{if(!cleanup||detached)return timedPromise;let removeExitHandler=onExit(()=>{spawned.kill();});return timedPromise.finally(()=>{removeExitHandler();})};function isStream(stream){return stream!==null&&typeof stream=="object"&&typeof stream.pipe=="function"}function isWritableStream(stream){return isStream(stream)&&stream.writable!==!1&&typeof stream._write=="function"&&typeof stream._writableState=="object"}var isExecaChildProcess=target=>target instanceof childProcess.ChildProcess&&typeof target.then=="function",pipeToTarget=(spawned,streamName,target)=>{if(typeof target=="string")return spawned[streamName].pipe(fs.createWriteStream(target)),spawned;if(isWritableStream(target))return spawned[streamName].pipe(target),spawned;if(!isExecaChildProcess(target))throw new TypeError("The second argument must be a string, a stream or an Execa child process.");if(!isWritableStream(target.stdin))throw new TypeError("The target child process's stdin must be available.");return spawned[streamName].pipe(target.stdin),target},addPipeMethods=spawned=>{spawned.stdout!==null&&(spawned.pipeStdout=pipeToTarget.bind(void 0,spawned,"stdout")),spawned.stderr!==null&&(spawned.pipeStderr=pipeToTarget.bind(void 0,spawned,"stderr")),spawned.all!==void 0&&(spawned.pipeAll=pipeToTarget.bind(void 0,spawned,"all"));};var getStreamContents=async(stream,{init,convertChunk,getSize,truncateChunk,addChunk,getFinalChunk,finalize},{maxBuffer=Number.POSITIVE_INFINITY}={})=>{if(!isAsyncIterable(stream))throw new Error("The first argument must be a Readable, a ReadableStream, or an async iterable.");let state=init();state.length=0;try{for await(let chunk of stream){let chunkType=getChunkType(chunk),convertedChunk=convertChunk[chunkType](chunk,state);appendChunk({convertedChunk,state,getSize,truncateChunk,addChunk,maxBuffer});}return appendFinalChunk({state,convertChunk,getSize,truncateChunk,addChunk,getFinalChunk,maxBuffer}),finalize(state)}catch(error){throw error.bufferedData=finalize(state),error}},appendFinalChunk=({state,getSize,truncateChunk,addChunk,getFinalChunk,maxBuffer})=>{let convertedChunk=getFinalChunk(state);convertedChunk!==void 0&&appendChunk({convertedChunk,state,getSize,truncateChunk,addChunk,maxBuffer});},appendChunk=({convertedChunk,state,getSize,truncateChunk,addChunk,maxBuffer})=>{let chunkSize=getSize(convertedChunk),newLength=state.length+chunkSize;if(newLength<=maxBuffer){addNewChunk(convertedChunk,state,addChunk,newLength);return}let truncatedChunk=truncateChunk(convertedChunk,maxBuffer-state.length);throw truncatedChunk!==void 0&&addNewChunk(truncatedChunk,state,addChunk,maxBuffer),new MaxBufferError},addNewChunk=(convertedChunk,state,addChunk,newLength)=>{state.contents=addChunk(convertedChunk,state,newLength),state.length=newLength;},isAsyncIterable=stream=>typeof stream=="object"&&stream!==null&&typeof stream[Symbol.asyncIterator]=="function",getChunkType=chunk=>{let typeOfChunk=typeof chunk;if(typeOfChunk==="string")return "string";if(typeOfChunk!=="object"||chunk===null)return "others";if(globalThis.Buffer?.isBuffer(chunk))return "buffer";let prototypeName=objectToString.call(chunk);return prototypeName==="[object ArrayBuffer]"?"arrayBuffer":prototypeName==="[object DataView]"?"dataView":Number.isInteger(chunk.byteLength)&&Number.isInteger(chunk.byteOffset)&&objectToString.call(chunk.buffer)==="[object ArrayBuffer]"?"typedArray":"others"},{toString:objectToString}=Object.prototype,MaxBufferError=class extends Error{name="MaxBufferError";constructor(){super("maxBuffer exceeded");}};var identity=value=>value,noop2=()=>{},getContentsProp=({contents})=>contents,throwObjectStream=chunk=>{throw new Error(`Streams in object mode are not supported: ${String(chunk)}`)},getLengthProp=convertedChunk=>convertedChunk.length;async function getStreamAsArrayBuffer(stream,options){return getStreamContents(stream,arrayBufferMethods,options)}var initArrayBuffer=()=>({contents:new ArrayBuffer(0)}),useTextEncoder=chunk=>textEncoder.encode(chunk),textEncoder=new TextEncoder,useUint8Array=chunk=>new Uint8Array(chunk),useUint8ArrayWithOffset=chunk=>new Uint8Array(chunk.buffer,chunk.byteOffset,chunk.byteLength),truncateArrayBufferChunk=(convertedChunk,chunkSize)=>convertedChunk.slice(0,chunkSize),addArrayBufferChunk=(convertedChunk,{contents,length:previousLength},length)=>{let newContents=hasArrayBufferResize()?resizeArrayBuffer(contents,length):resizeArrayBufferSlow(contents,length);return new Uint8Array(newContents).set(convertedChunk,previousLength),newContents},resizeArrayBufferSlow=(contents,length)=>{if(length<=contents.byteLength)return contents;let arrayBuffer=new ArrayBuffer(getNewContentsLength(length));return new Uint8Array(arrayBuffer).set(new Uint8Array(contents),0),arrayBuffer},resizeArrayBuffer=(contents,length)=>{if(length<=contents.maxByteLength)return contents.resize(length),contents;let arrayBuffer=new ArrayBuffer(length,{maxByteLength:getNewContentsLength(length)});return new Uint8Array(arrayBuffer).set(new Uint8Array(contents),0),arrayBuffer},getNewContentsLength=length=>SCALE_FACTOR**Math.ceil(Math.log(length)/Math.log(SCALE_FACTOR)),SCALE_FACTOR=2,finalizeArrayBuffer=({contents,length})=>hasArrayBufferResize()?contents:contents.slice(0,length),hasArrayBufferResize=()=>"resize"in ArrayBuffer.prototype,arrayBufferMethods={init:initArrayBuffer,convertChunk:{string:useTextEncoder,buffer:useUint8Array,arrayBuffer:useUint8Array,dataView:useUint8ArrayWithOffset,typedArray:useUint8ArrayWithOffset,others:throwObjectStream},getSize:getLengthProp,truncateChunk:truncateArrayBufferChunk,addChunk:addArrayBufferChunk,getFinalChunk:noop2,finalize:finalizeArrayBuffer};async function getStreamAsBuffer(stream,options){if(!("Buffer"in globalThis))throw new Error("getStreamAsBuffer() is only supported in Node.js");try{return arrayBufferToNodeBuffer(await getStreamAsArrayBuffer(stream,options))}catch(error){throw error.bufferedData!==void 0&&(error.bufferedData=arrayBufferToNodeBuffer(error.bufferedData)),error}}var arrayBufferToNodeBuffer=arrayBuffer=>globalThis.Buffer.from(arrayBuffer);async function getStreamAsString(stream,options){return getStreamContents(stream,stringMethods,options)}var initString=()=>({contents:"",textDecoder:new TextDecoder}),useTextDecoder=(chunk,{textDecoder})=>textDecoder.decode(chunk,{stream:!0}),addStringChunk=(convertedChunk,{contents})=>contents+convertedChunk,truncateStringChunk=(convertedChunk,chunkSize)=>convertedChunk.slice(0,chunkSize),getFinalStringChunk=({textDecoder})=>{let finalChunk=textDecoder.decode();return finalChunk===""?void 0:finalChunk},stringMethods={init:initString,convertChunk:{string:identity,buffer:useTextDecoder,arrayBuffer:useTextDecoder,dataView:useTextDecoder,typedArray:useTextDecoder,others:throwObjectStream},getSize:getLengthProp,truncateChunk:truncateStringChunk,addChunk:addStringChunk,getFinalChunk:getFinalStringChunk,finalize:getContentsProp};var import_merge_stream=__toESM(require_merge_stream(),1),validateInputOptions=input=>{if(input!==void 0)throw new TypeError("The `input` and `inputFile` options cannot be both set.")},getInput=({input,inputFile})=>typeof inputFile!="string"?input:(validateInputOptions(input),fs.createReadStream(inputFile)),handleInput=(spawned,options)=>{let input=getInput(options);input!==void 0&&(isStream(input)?input.pipe(spawned.stdin):spawned.stdin.end(input));},makeAllStream=(spawned,{all})=>{if(!all||!spawned.stdout&&!spawned.stderr)return;let mixed=(0, import_merge_stream.default)();return spawned.stdout&&mixed.add(spawned.stdout),spawned.stderr&&mixed.add(spawned.stderr),mixed},getBufferedData=async(stream,streamPromise)=>{if(!(!stream||streamPromise===void 0)){await promises$1.setTimeout(0),stream.destroy();try{return await streamPromise}catch(error){return error.bufferedData}}},getStreamPromise=(stream,{encoding,buffer,maxBuffer})=>{if(!(!stream||!buffer))return encoding==="utf8"||encoding==="utf-8"?getStreamAsString(stream,{maxBuffer}):encoding===null||encoding==="buffer"?getStreamAsBuffer(stream,{maxBuffer}):applyEncoding(stream,maxBuffer,encoding)},applyEncoding=async(stream,maxBuffer,encoding)=>(await getStreamAsBuffer(stream,{maxBuffer})).toString(encoding),getSpawnedResult=async({stdout,stderr,all},{encoding,buffer,maxBuffer},processDone)=>{let stdoutPromise=getStreamPromise(stdout,{encoding,buffer,maxBuffer}),stderrPromise=getStreamPromise(stderr,{encoding,buffer,maxBuffer}),allPromise=getStreamPromise(all,{encoding,buffer,maxBuffer:maxBuffer*2});try{return await Promise.all([processDone,stdoutPromise,stderrPromise,allPromise])}catch(error){return Promise.all([{error,signal:error.signal,timedOut:error.timedOut},getBufferedData(stdout,stdoutPromise),getBufferedData(stderr,stderrPromise),getBufferedData(all,allPromise)])}};var nativePromisePrototype=(async()=>{})().constructor.prototype,descriptors=["then","catch","finally"].map(property=>[property,Reflect.getOwnPropertyDescriptor(nativePromisePrototype,property)]),mergePromise=(spawned,promise)=>{for(let[property,descriptor]of descriptors){let value=typeof promise=="function"?(...args)=>Reflect.apply(descriptor.value,promise(),args):descriptor.value.bind(promise);Reflect.defineProperty(spawned,property,{...descriptor,value});}},getSpawnedPromise=spawned=>new Promise((resolve2,reject)=>{spawned.on("exit",(exitCode,signal)=>{resolve2({exitCode,signal});}),spawned.on("error",error=>{reject(error);}),spawned.stdin&&spawned.stdin.on("error",error=>{reject(error);});});var normalizeArgs=(file,args=[])=>Array.isArray(args)?[file,...args]:[file],NO_ESCAPE_REGEXP=/^[\w.-]+$/,escapeArg=arg=>typeof arg!="string"||NO_ESCAPE_REGEXP.test(arg)?arg:`"${arg.replaceAll('"','\\"')}"`,joinCommand=(file,args)=>normalizeArgs(file,args).join(" "),getEscapedCommand=(file,args)=>normalizeArgs(file,args).map(arg=>escapeArg(arg)).join(" ");var verboseDefault=util.debuglog("execa").enabled,padField=(field,padding)=>String(field).padStart(padding,"0"),getTimestamp=()=>{let date=new Date;return `${padField(date.getHours(),2)}:${padField(date.getMinutes(),2)}:${padField(date.getSeconds(),2)}.${padField(date.getMilliseconds(),3)}`},logCommand=(escapedCommand,{verbose})=>{verbose&&process6__default.default.stderr.write(`[${getTimestamp()}] ${escapedCommand}
`);};var DEFAULT_MAX_BUFFER=1e3*1e3*100,getEnv=({env:envOption,extendEnv,preferLocal,localDir,execPath})=>{let env=extendEnv?{...process6__default.default.env,...envOption}:envOption;return preferLocal?npmRunPathEnv({env,cwd:localDir,execPath}):env},handleArguments=(file,args,options={})=>{let parsed=import_cross_spawn.default._parse(file,args,options);return file=parsed.command,args=parsed.args,options=parsed.options,options={maxBuffer:DEFAULT_MAX_BUFFER,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:options.cwd||process6__default.default.cwd(),execPath:process6__default.default.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:verboseDefault,...options},options.env=getEnv(options),options.stdio=normalizeStdio(options),process6__default.default.platform==="win32"&&path__default.default.basename(file,".exe")==="cmd"&&args.unshift("/q"),{file,args,options,parsed}},handleOutput=(options,value,error)=>typeof value!="string"&&!buffer.Buffer.isBuffer(value)?error===void 0?void 0:"":options.stripFinalNewline?stripFinalNewline(value):value;function execa(file,args,options){let parsed=handleArguments(file,args,options),command=joinCommand(file,args),escapedCommand=getEscapedCommand(file,args);logCommand(escapedCommand,parsed.options),validateTimeout(parsed.options);let spawned;try{spawned=childProcess__default.default.spawn(parsed.file,parsed.args,parsed.options);}catch(error){let dummySpawned=new childProcess__default.default.ChildProcess,errorPromise=Promise.reject(makeError({error,stdout:"",stderr:"",all:"",command,escapedCommand,parsed,timedOut:!1,isCanceled:!1,killed:!1}));return mergePromise(dummySpawned,errorPromise),dummySpawned}let spawnedPromise=getSpawnedPromise(spawned),timedPromise=setupTimeout(spawned,parsed.options,spawnedPromise),processDone=setExitHandler(spawned,parsed.options,timedPromise),context={isCanceled:!1};spawned.kill=spawnedKill.bind(null,spawned.kill.bind(spawned)),spawned.cancel=spawnedCancel.bind(null,spawned,context);let handlePromiseOnce=onetime_default(async()=>{let[{error,exitCode,signal,timedOut},stdoutResult,stderrResult,allResult]=await getSpawnedResult(spawned,parsed.options,processDone),stdout=handleOutput(parsed.options,stdoutResult),stderr=handleOutput(parsed.options,stderrResult),all=handleOutput(parsed.options,allResult);if(error||exitCode!==0||signal!==null){let returnedError=makeError({error,exitCode,signal,stdout,stderr,all,command,escapedCommand,parsed,timedOut,isCanceled:(parsed.options.signal?parsed.options.signal.aborted:!1),killed:spawned.killed});if(!parsed.options.reject)return returnedError;throw returnedError}return {command,escapedCommand,exitCode:0,stdout,stderr,all,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}});return handleInput(spawned,parsed.options),spawned.all=makeAllStream(spawned,parsed.options),addPipeMethods(spawned),mergePromise(spawned,handlePromiseOnce),spawned}function execaNode(scriptPath,args,options={}){args&&!Array.isArray(args)&&typeof args=="object"&&(options=args,args=[]);let stdio=normalizeStdioNode(options),defaultExecArgv=process6__default.default.execArgv.filter(arg=>!arg.startsWith("--inspect")),{nodePath=process6__default.default.execPath,nodeOptions=defaultExecArgv}=options;return execa(nodePath,[...nodeOptions,scriptPath,...Array.isArray(args)?args:[]],{...options,stdin:void 0,stdout:void 0,stderr:void 0,stdio,shell:!1})}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]:$/;var 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 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)};var MAX_START_TIME=3e4,vitestModulePath=join(__dirname,"node","vitest.mjs"),eventQueue=[],child,ready=!1,unsubscribeStore,unsubscribeStatusStore,unsubscribeTestProviderStore,forwardUniversalStoreEvent=storeEventName=>(event,eventInfo)=>{child?.send({type:storeEventName,args:[{event,eventInfo}],from:"server"});},bootTestRunner=async({channel,store,options})=>{let stderr=[],killChild=()=>{unsubscribeStore?.(),unsubscribeStatusStore?.(),unsubscribeTestProviderStore?.(),child?.kill(),child=null;};store.subscribe("FATAL_ERROR",killChild);let exit=(code=0)=>{killChild(),eventQueue.length=0,process.exit(code);};process.on("exit",exit),process.on("SIGINT",()=>exit(0)),process.on("SIGTERM",()=>exit(0));let startChildProcess=()=>new Promise((resolve2,reject)=>{child=execaNode(vitestModulePath,{env:{VITEST:"true",TEST:"true",VITEST_CHILD_PROCESS:"true",NODE_ENV:process.env.NODE_ENV??"test",STORYBOOK_CONFIG_DIR:normalize(options.configDir)},extendEnv:!0}),stderr=[],child.stdout?.on("data",log),child.stderr?.on("data",data=>{data.toString().match(/^\u001B\[33m/)||(log(data),stderr.push(data.toString()));}),unsubscribeStore=store.subscribe(forwardUniversalStoreEvent(STORE_CHANNEL_EVENT_NAME)),unsubscribeStatusStore=coreServer.internal_universalStatusStore.subscribe(forwardUniversalStoreEvent(STATUS_STORE_CHANNEL_EVENT_NAME)),unsubscribeTestProviderStore=coreServer.internal_universalTestProviderStore.subscribe(forwardUniversalStoreEvent(TEST_PROVIDER_STORE_CHANNEL_EVENT_NAME)),child.on("message",event=>{if(event.type==="ready"){for(;eventQueue.length;){let{type,args}=eventQueue.shift();child?.send({type,args,from:"server"});}resolve2();}else event.type==="uncaught-error"?(store.send({type:"FATAL_ERROR",payload:event.payload}),reject()):channel.emit(event.type,...event.args);});}),timeout=new Promise((_,reject)=>setTimeout(reject,MAX_START_TIME,new Error(`Aborting test runner process because it took longer than ${MAX_START_TIME/1e3} seconds to start.`)));await Promise.race([startChildProcess(),timeout]).catch(error=>{throw store.send({type:"FATAL_ERROR",payload:{message:"Failed to start test runner process",error:{message:error.message,name:error.name,stack:error.stack,cause:error.cause}}}),eventQueue.length=0,error});},runTestRunner=async({channel,store,initEvent,initArgs,options})=>{!ready&&initEvent&&eventQueue.push({type:initEvent,args:initArgs}),child||(ready=!1,await bootTestRunner({channel,store,options}),ready=!0);};var experimental_serverChannel=async(channel,options)=>{let core=await options.presets.apply("core"),previewPath=common.loadPreviewOrConfigFile({configDir:options.configDir}),previewAnnotations=await options.presets.apply("previewAnnotations",[],options),builderName=typeof core?.builder=="string"?core.builder:core?.builder?.name,framework=await common.getFrameworkName(options);if(!builderName?.includes("vite"))return framework.includes("nextjs")&&log(tsDedent.dedent`
        You're using ${framework}, which is a Webpack-based builder. In order to use Storybook Test, with your project, you need to use '@storybook/nextjs-vite', a high performance Vite-based equivalent.

        Information on how to upgrade here: ${import_picocolors2.default.yellow("https://storybook.js.org/docs/get-started/frameworks/nextjs?ref=upgrade#with-vite")}\n
      `),channel;let fsCache=common.createFileSystemCache({basePath:common.resolvePathInStorybookCache(ADDON_ID2.replace("/","-")),ns:"storybook",ttl:14*24*60*60*1e3}),cachedState=await fsCache.get("state",{config:storeOptions.initialState.config}),selectCachedState=s=>({config:s.config}),store=coreServer.experimental_UniversalStore.create({...storeOptions,initialState:{...storeOptions.initialState,previewAnnotations:(previewAnnotations??[]).concat(previewPath??[]),...selectCachedState(cachedState)},leader:!0});store.onStateChange((state,previousState)=>{isEqual(selectCachedState(state),selectCachedState(previousState))||fsCache.set("state",selectCachedState(state));});let testProviderStore=coreServer.experimental_getTestProviderStore(ADDON_ID2);if(store.subscribe("TRIGGER_RUN",(event,eventInfo)=>{testProviderStore.setState("test-provider-state:running"),store.setState(s=>({...s,fatalError:void 0})),runTestRunner({channel,store,initEvent:STORE_CHANNEL_EVENT_NAME,initArgs:[{event,eventInfo}],options});}),store.subscribe("TOGGLE_WATCHING",(event,eventInfo)=>{store.setState(s=>({...s,watching:event.payload.to,currentRun:{...s.currentRun,...event.payload.to&&{coverageSummary:void 0}}})),event.payload.to&&runTestRunner({channel,store,initEvent:STORE_CHANNEL_EVENT_NAME,initArgs:[{event,eventInfo}],options});}),store.subscribe("FATAL_ERROR",event=>{let{message,error}=event.payload,name=error.name||"Error";log(`${name}: ${message}`),error.stack&&log(error.stack);function logErrorWithCauses(err){err&&(log(`Caused by: ${err.name??"Error"}: ${err.message}`),err.stack&&log(err.stack),err.cause&&logErrorWithCauses(err.cause));}error.cause&&logErrorWithCauses(error.cause),store.setState(s=>({...s,fatalError:{message,error}})),testProviderStore.setState("test-provider-state:crashed");}),testProviderStore.onClearAll(()=>{store.setState(s=>({...s,currentRun:{...s.currentRun,coverageSummary:void 0,unhandledErrors:[]}}));}),!core.disableTelemetry){let enableCrashReports=core.enableCrashReports||options.enableCrashReports;channel.on(STORYBOOK_ADDON_TEST_CHANNEL,event=>{telemetry.telemetry("addon-test",{...event,payload:{...event.payload,storyId:telemetry.oneWayHash(event.payload.storyId)}});}),store.subscribe("TOGGLE_WATCHING",async event=>{await telemetry.telemetry("addon-test",{watchMode:event.payload.to});}),store.subscribe("TEST_RUN_COMPLETED",async event=>{let{unhandledErrors,startedAt,finishedAt,...currentRun}=event.payload;await telemetry.telemetry("addon-test",{...currentRun,duration:(finishedAt??0)-(startedAt??0),unhandledErrorCount:unhandledErrors.length,...enableCrashReports&&unhandledErrors.length>0&&{unhandledErrors:unhandledErrors.map(error=>{let{stacks,...errorWithoutStacks}=error;return telemetry.sanitizeError(errorWithoutStacks)})}});}),enableCrashReports&&store.subscribe("FATAL_ERROR",async event=>{await telemetry.telemetry("addon-test",{fatalError:telemetry.cleanPaths(event.payload.error.message)});});}return channel},staticDirs=async(values=[],options)=>{if(options.configType==="PRODUCTION")return values;let coverageDirectory=common.resolvePathInStorybookCache(COVERAGE_DIRECTORY);return await promises.mkdir(coverageDirectory,{recursive:!0}),[{from:coverageDirectory,to:"/coverage"},...values]};

exports.experimental_serverChannel = experimental_serverChannel;
exports.staticDirs = staticDirs;
