@storybook/addon-vitest 0.0.0-pr-31987-sha-a5d24df6 → 0.0.0-pr-32047-sha-2c994900

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.
package/dist/manager.js CHANGED
@@ -5,4 +5,4 @@ import { Modal, ProgressSpinner, Button, IconButton, WithTooltip, TooltipNote, L
5
5
  import { StopAltIcon, SyncIcon, CloseIcon, EyeIcon, PlayHollowIcon, InfoIcon } from '@storybook/icons';
6
6
  import { styled } from 'storybook/theming';
7
7
 
8
- var ADDON_ID="storybook/interactions",PANEL_ID=`${ADDON_ID}/panel`;var ADDON_ID2="storybook/a11y",PANEL_ID2=`${ADDON_ID2}/panel`;var ADDON_ID3="storybook/test",TEST_PROVIDER_ID=`${ADDON_ID3}/test-provider`;var DOCUMENTATION_LINK3="writing-tests/integrations/vitest-addon",DOCUMENTATION_FATAL_ERROR_LINK=`${DOCUMENTATION_LINK3}#what-happens-if-vitest-itself-has-an-error`;var storeOptions={id:ADDON_ID3,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}}},FULL_RUN_TRIGGERS=["global","run-all"];var STATUS_TYPE_ID_COMPONENT_TEST="storybook/component-test",STATUS_TYPE_ID_A11Y="storybook/a11y";var store=experimental_UniversalStore.create({...storeOptions,leader:globalThis.CONFIG_TYPE==="PRODUCTION"}),componentTestStatusStore=experimental_getStatusStore(STATUS_TYPE_ID_COMPONENT_TEST),a11yStatusStore=experimental_getStatusStore(STATUS_TYPE_ID_A11Y),testProviderStore=experimental_getTestProviderStore(ADDON_ID3);var ModalBar=styled.div({display:"flex",justifyContent:"space-between",alignItems:"center",padding:"6px 6px 6px 20px"}),ModalActionBar=styled.div({display:"flex",justifyContent:"space-between",alignItems:"center"}),ModalTitle=styled(Modal.Title)(({theme:{typography}})=>({fontSize:typography.size.s2,fontWeight:typography.weight.bold})),ModalStackTrace=styled.pre(({theme})=>({whiteSpace:"pre-wrap",wordWrap:"break-word",overflow:"auto",maxHeight:"60vh",margin:0,padding:"20px",fontFamily:theme.typography.fonts.mono,fontSize:"12px",borderTop:`1px solid ${theme.appBorderColor}`,borderRadius:0})),TroubleshootLink=styled.a(({theme})=>({color:theme.color.defaultText})),GlobalErrorContext=React3.createContext({isModalOpen:!1,setModalOpen:void 0});function ErrorCause({error}){return error?React3.createElement("div",null,React3.createElement("h4",null,"Caused by: ",error.name||"Error",": ",error.message),error.stack&&React3.createElement("pre",null,error.stack),error.cause&&React3.createElement(ErrorCause,{error:error.cause})):null}function GlobalErrorModal({onRerun,storeState}){let api=useStorybookApi(),{isModalOpen,setModalOpen}=useContext(GlobalErrorContext),handleClose=()=>setModalOpen?.(!1),troubleshootURL=api.getDocsUrl({subpath:DOCUMENTATION_FATAL_ERROR_LINK,versioned:!0,renderer:!0}),{fatalError,currentRun:{unhandledErrors}}=storeState,content=fatalError?React3.createElement(React3.Fragment,null,React3.createElement("p",null,fatalError.error.name||"Error"),fatalError.message&&React3.createElement("p",null,fatalError.message),fatalError.error.message&&React3.createElement("p",null,fatalError.error.message),fatalError.error.stack&&React3.createElement("p",null,fatalError.error.stack),fatalError.error.cause&&React3.createElement(ErrorCause,{error:fatalError.error.cause})):unhandledErrors.length>0?React3.createElement("ol",null,unhandledErrors.map(error=>React3.createElement("li",{key:error.name+error.message},React3.createElement("p",null,error.name,": ",error.message),error.VITEST_TEST_PATH&&React3.createElement("p",null,'This error originated in "',React3.createElement("b",null,error.VITEST_TEST_PATH),`". It doesn't mean the error was thrown inside the file itself, but while it was running.`),error.VITEST_TEST_NAME&&React3.createElement(React3.Fragment,null,React3.createElement("p",null,`The latest test that might've caused the error is "`,React3.createElement("b",null,error.VITEST_TEST_NAME),'". It might mean one of the following:'),React3.createElement("ul",null,React3.createElement("li",null,"The error was thrown, while Vitest was running this test."),React3.createElement("li",null,"If the error occurred after the test had been completed, this was the last documented test before it was thrown."))),error.stacks&&React3.createElement(React3.Fragment,null,React3.createElement("p",null,React3.createElement("b",null,"Stacks:")),React3.createElement("ul",null,error.stacks.map(stack=>React3.createElement("li",{key:stack.file+stack.line+stack.column},stack.file,":",stack.line,":",stack.column," - ",stack.method||"unknown method")))),error.stack&&React3.createElement("p",null,error.stack),error.cause?React3.createElement(ErrorCause,{error:error.cause}):null))):null;return React3.createElement(Modal,{onEscapeKeyDown:handleClose,onInteractOutside:handleClose,open:isModalOpen},React3.createElement(ModalBar,null,React3.createElement(ModalTitle,null,"Storybook Tests error details"),React3.createElement(ModalActionBar,null,React3.createElement(Button,{onClick:onRerun,variant:"ghost"},React3.createElement(SyncIcon,null),"Rerun"),React3.createElement(Button,{variant:"ghost",asChild:!0},React3.createElement("a",{target:"_blank",href:troubleshootURL,rel:"noreferrer"},"Troubleshoot")),React3.createElement(IconButton,{onClick:handleClose,"aria-label":"Close modal"},React3.createElement(CloseIcon,null)))),React3.createElement(ModalStackTrace,null,content,React3.createElement("br",null),React3.createElement("br",null),"Troubleshoot:"," ",React3.createElement(TroubleshootLink,{target:"_blank",href:troubleshootURL},troubleshootURL)))}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 statusValueToStoryIds=(allStatuses,typeId,storyIds)=>{let statusValueToStoryIdsMap={"status-value:pending":[],"status-value:success":[],"status-value:error":[],"status-value:warning":[],"status-value:unknown":[]};return (storyIds?storyIds.map(storyId=>allStatuses[storyId]).filter(Boolean):Object.values(allStatuses)).forEach(statusByTypeId=>{let status=statusByTypeId[typeId];status&&statusValueToStoryIdsMap[status.value].push(status.storyId);}),statusValueToStoryIdsMap},useTestProvider=(api,entryId)=>{let testProviderState=experimental_useTestProviderStore(s=>s[ADDON_ID3]),[storeState,setStoreState]=experimental_useUniversalStore(store),[isSettingsUpdated,setIsSettingsUpdated]=useState(!1),settingsUpdatedTimeoutRef=useRef();useEffect(()=>{let unsubscribe=store.onStateChange((state,previousState)=>{isEqual(state.config,previousState.config)||(testProviderStore.settingsChanged(),setIsSettingsUpdated(!0),clearTimeout(settingsUpdatedTimeoutRef.current),settingsUpdatedTimeoutRef.current=setTimeout(()=>{setIsSettingsUpdated(!1);},1e3));});return ()=>{unsubscribe(),clearTimeout(settingsUpdatedTimeoutRef.current);}},[]);let storyIds=useMemo(()=>entryId?api.findAllLeafStoryIds(entryId):void 0,[entryId,api]),componentTestStatusSelector=useCallback(allStatuses=>statusValueToStoryIds(allStatuses,STATUS_TYPE_ID_COMPONENT_TEST,storyIds),[storyIds]),componentTestStatusValueToStoryIds=experimental_useStatusStore(componentTestStatusSelector),a11yStatusValueToStoryIdsSelector=useCallback(allStatuses=>statusValueToStoryIds(allStatuses,STATUS_TYPE_ID_A11Y,storyIds),[storyIds]),a11yStatusValueToStoryIds=experimental_useStatusStore(a11yStatusValueToStoryIdsSelector);return {storeState,setStoreState,testProviderState,componentTestStatusValueToStoryIds,a11yStatusValueToStoryIds,isSettingsUpdated}};var RelativeTime=({timestamp})=>{let[timeAgo,setTimeAgo]=useState(null);if(useEffect(()=>{if(timestamp){setTimeAgo(Date.now()-timestamp);let interval=setInterval(()=>setTimeAgo(Date.now()-timestamp),1e4);return ()=>clearInterval(interval)}},[timestamp]),timeAgo===null)return null;let seconds=Math.round(timeAgo/1e3);if(seconds<60)return "just now";let minutes=Math.floor(seconds/60);if(minutes<60)return minutes===1?"a minute ago":`${minutes} minutes ago`;let hours=Math.floor(minutes/60);if(hours<24)return hours===1?"an hour ago":`${hours} hours ago`;let days=Math.floor(hours/24);return days===1?"yesterday":`${days} days ago`};var Wrapper=styled.div(({theme})=>({overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis",fontSize:theme.typography.size.s1,color:theme.textMutedColor})),PositiveText=styled.span(({theme})=>({color:theme.color.positiveText}));function Description({entryId,storeState,testProviderState,isSettingsUpdated,...props}){let{setModalOpen}=React3.useContext(GlobalErrorContext),{componentTestCount,totalTestCount,unhandledErrors,finishedAt}=storeState.currentRun,finishedTestCount=componentTestCount.success+componentTestCount.error,description="Not run";if(!entryId&&isSettingsUpdated)description=React3.createElement(PositiveText,null,"Settings updated");else if(testProviderState==="test-provider-state:running")description=(finishedTestCount??0)===0?"Starting...":`Testing... ${finishedTestCount}/${totalTestCount}`;else if(!entryId&&testProviderState==="test-provider-state:crashed")description=setModalOpen?React3.createElement(Link,{isButton:!0,onClick:()=>setModalOpen(!0)},"View full error"):"Crashed";else if(!entryId&&unhandledErrors.length>0){let unhandledErrorDescription=`View ${unhandledErrors.length} unhandled error${unhandledErrors?.length>1?"s":""}`;description=setModalOpen?React3.createElement(Link,{isButton:!0,onClick:()=>setModalOpen(!0)},unhandledErrorDescription):unhandledErrorDescription;}else entryId&&totalTestCount?description=`Ran ${totalTestCount} ${totalTestCount===1?"test":"tests"}`:finishedAt?description=React3.createElement(React3.Fragment,null,"Ran ",totalTestCount," ",totalTestCount===1?"test":"tests"," ",React3.createElement(RelativeTime,{timestamp:finishedAt})):storeState.watching&&(description="Watching for file changes");return React3.createElement(Wrapper,{...props},description)}var TestStatusIcon=styled.div(({percentage})=>({width:percentage?12:6,height:percentage?12:6,margin:percentage?1:4,background:percentage?`conic-gradient(var(--status-color) ${percentage}%, var(--status-background) ${percentage+1}%)`:"var(--status-color)",borderRadius:"50%"}),({isRunning,theme})=>isRunning&&{animation:`${theme.animation.glow} 1.5s ease-in-out infinite`},({status,theme})=>status==="positive"&&{"--status-color":theme.color.positive,"--status-background":`${theme.color.positive}66`},({status,theme})=>status==="warning"&&{"--status-color":theme.color.gold,"--status-background":`${theme.color.gold}66`},({status,theme})=>status==="negative"&&{"--status-color":theme.color.negative,"--status-background":`${theme.color.negative}66`},({status,theme})=>status==="critical"&&{"--status-color":theme.color.defaultText,"--status-background":`${theme.color.defaultText}66`},({status,theme})=>status==="unknown"&&{"--status-color":theme.color.mediumdark,"--status-background":`${theme.color.mediumdark}66`});var Container=styled.div({display:"flex",flexDirection:"column"}),Heading=styled.div({display:"flex",justifyContent:"space-between",padding:"8px 0",gap:12}),Info=styled.div({display:"flex",flexDirection:"column",marginLeft:8,minWidth:0}),Title=styled.div(({crashed,theme})=>({fontSize:theme.typography.size.s1,fontWeight:crashed?"bold":"normal",color:crashed?theme.color.negativeText:theme.color.defaultText})),Actions=styled.div({display:"flex",gap:4}),Extras=styled.div({marginBottom:2}),Muted=styled.span(({theme})=>({color:theme.textMutedColor})),Progress=styled(ProgressSpinner)({margin:4}),Row=styled.div({display:"flex",gap:4}),StopIcon=styled(StopAltIcon)({width:10}),openPanel=({api,panelId,entryId})=>{let story=entryId?api.findAllLeafStoryIds(entryId)[0]:void 0;story&&api.selectStory(story),api.setSelectedPanel(panelId),api.togglePanel(!0);},TestProviderRender=({api,entry,testProviderState,storeState,setStoreState,componentTestStatusValueToStoryIds,a11yStatusValueToStoryIds,isSettingsUpdated,...props})=>{let{config,watching,cancelling,currentRun,fatalError}=storeState,finishedTestCount=currentRun.componentTestCount.success+currentRun.componentTestCount.error,hasA11yAddon=addons.experimental_getRegisteredAddons().includes(ADDON_ID2),isRunning=testProviderState==="test-provider-state:running",isStarting=isRunning&&finishedTestCount===0,[componentTestStatusIcon,componentTestStatusLabel]=fatalError?["critical","Component tests crashed"]:componentTestStatusValueToStoryIds["status-value:error"].length>0?["negative","Component tests failed"]:isRunning?["unknown","Testing in progress"]:componentTestStatusValueToStoryIds["status-value:success"].length>0?["positive","Component tests passed"]:["unknown","Run tests to see results"],[a11yStatusIcon,a11yStatusLabel]=fatalError?["critical","Component tests crashed"]:a11yStatusValueToStoryIds["status-value:error"].length>0?["negative","Accessibility tests failed"]:a11yStatusValueToStoryIds["status-value:warning"].length>0?["warning","Accessibility tests failed"]:isRunning?["unknown","Testing in progress"]:a11yStatusValueToStoryIds["status-value:success"].length>0?["positive","Accessibility tests passed"]:["unknown","Run tests to see accessibility results"];return React3.createElement(Container,{...props},React3.createElement(Heading,null,React3.createElement(Info,null,entry?React3.createElement(Title,{id:"testing-module-title"},"Run component tests"):React3.createElement(Title,{id:"testing-module-title",crashed:testProviderState==="test-provider-state:crashed"||fatalError!==void 0||currentRun.unhandledErrors.length>0},currentRun.unhandledErrors.length===1?"Component tests completed with an error":currentRun.unhandledErrors.length>1?"Component tests completed with errors":fatalError?"Component tests didn\u2019t complete":"Run component tests"),React3.createElement(Description,{id:"testing-module-description",storeState,testProviderState,entryId:entry?.id,isSettingsUpdated})),React3.createElement(Actions,null,!entry&&React3.createElement(WithTooltip,{hasChrome:!1,trigger:"hover",tooltip:React3.createElement(TooltipNote,{note:`${watching?"Disable":"Enable"} watch mode`})},React3.createElement(IconButton,{"aria-label":`${watching?"Disable":"Enable"} watch mode`,size:"medium",active:watching,onClick:()=>store.send({type:"TOGGLE_WATCHING",payload:{to:!watching}}),disabled:isRunning},React3.createElement(EyeIcon,null))),isRunning?React3.createElement(WithTooltip,{hasChrome:!1,trigger:"hover",tooltip:React3.createElement(TooltipNote,{note:cancelling?"Stopping...":"Stop test run"})},React3.createElement(IconButton,{"aria-label":cancelling?"Stopping...":"Stop test run",padding:"none",size:"medium",onClick:()=>store.send({type:"CANCEL_RUN"}),disabled:cancelling||isStarting},React3.createElement(Progress,{percentage:finishedTestCount&&storeState.currentRun.totalTestCount?finishedTestCount/storeState.currentRun.totalTestCount*100:void 0},React3.createElement(StopIcon,null)))):React3.createElement(WithTooltip,{hasChrome:!1,trigger:"hover",tooltip:React3.createElement(TooltipNote,{note:"Start test run"})},React3.createElement(IconButton,{"aria-label":"Start test run",size:"medium",onClick:()=>store.send({type:"TRIGGER_RUN",payload:{storyIds:entry?api.findAllLeafStoryIds(entry.id):void 0,triggeredBy:entry?entry.type:"global"}})},React3.createElement(PlayHollowIcon,null))))),React3.createElement(Extras,null,React3.createElement(Row,null,React3.createElement(ListItem,{as:"label",title:"Interactions",icon:entry?null:React3.createElement(Form.Checkbox,{checked:!0,disabled:!0})}),React3.createElement(WithTooltip,{hasChrome:!1,trigger:"hover",tooltip:React3.createElement(TooltipNote,{note:componentTestStatusLabel})},React3.createElement(IconButton,{size:"medium",disabled:componentTestStatusValueToStoryIds["status-value:error"].length===0&&componentTestStatusValueToStoryIds["status-value:warning"].length===0&&componentTestStatusValueToStoryIds["status-value:success"].length===0,onClick:()=>{openPanel({api,panelId:PANEL_ID,entryId:componentTestStatusValueToStoryIds["status-value:error"][0]??componentTestStatusValueToStoryIds["status-value:warning"][0]??componentTestStatusValueToStoryIds["status-value:success"][0]??entry?.id});}},React3.createElement(TestStatusIcon,{status:componentTestStatusIcon,"aria-label":componentTestStatusLabel,isRunning}),componentTestStatusValueToStoryIds["status-value:error"].length+componentTestStatusValueToStoryIds["status-value:warning"].length||null))),!entry&&React3.createElement(Row,null,React3.createElement(ListItem,{as:"label",title:watching?React3.createElement(Muted,null,"Coverage (unavailable)"):"Coverage",icon:React3.createElement(Form.Checkbox,{checked:config.coverage,disabled:isRunning,onChange:()=>setStoreState(s=>({...s,config:{...s.config,coverage:!config.coverage}}))})}),React3.createElement(WithTooltip,{hasChrome:!1,trigger:"hover",tooltip:React3.createElement(TooltipNote,{note:watching?"Unavailable in watch mode":currentRun.triggeredBy&&!FULL_RUN_TRIGGERS.includes(currentRun.triggeredBy)?"Unavailable when running focused tests":isRunning?"Testing in progress":currentRun.coverageSummary?"View coverage report":fatalError?"Component tests crashed":"Run tests to calculate coverage"})},watching||currentRun.triggeredBy&&!FULL_RUN_TRIGGERS.includes(currentRun.triggeredBy)?React3.createElement(IconButton,{size:"medium",disabled:!0},React3.createElement(InfoIcon,{"aria-label":watching?"Coverage is unavailable in watch mode":"Coverage is unavailable when running focused tests"})):currentRun.coverageSummary?React3.createElement(IconButton,{asChild:!0,size:"medium"},React3.createElement("a",{href:"/coverage/index.html",target:"_blank","aria-label":"Open coverage report"},React3.createElement(TestStatusIcon,{isRunning,percentage:currentRun.coverageSummary.percentage,status:currentRun.coverageSummary.status,"aria-label":`Coverage status: ${currentRun.coverageSummary.status}`}),React3.createElement("span",{"aria-label":`${currentRun.coverageSummary.percentage} percent coverage`},currentRun.coverageSummary.percentage,"%"))):React3.createElement(IconButton,{size:"medium",disabled:!0},React3.createElement(TestStatusIcon,{isRunning,status:fatalError?"critical":"unknown","aria-label":"Coverage status: unknown"})))),hasA11yAddon&&React3.createElement(Row,null,React3.createElement(ListItem,{as:"label",title:"Accessibility",icon:entry?null:React3.createElement(Form.Checkbox,{checked:config.a11y,disabled:isRunning,onChange:()=>setStoreState(s=>({...s,config:{...s.config,a11y:!config.a11y}}))})}),React3.createElement(WithTooltip,{hasChrome:!1,trigger:"hover",tooltip:React3.createElement(TooltipNote,{note:a11yStatusLabel})},React3.createElement(IconButton,{size:"medium",disabled:a11yStatusValueToStoryIds["status-value:error"].length===0&&a11yStatusValueToStoryIds["status-value:warning"].length===0&&a11yStatusValueToStoryIds["status-value:success"].length===0,onClick:()=>{openPanel({api,entryId:a11yStatusValueToStoryIds["status-value:error"][0]??a11yStatusValueToStoryIds["status-value:warning"][0]??a11yStatusValueToStoryIds["status-value:success"][0]??entry?.id,panelId:PANEL_ID2});}},React3.createElement(TestStatusIcon,{status:a11yStatusIcon,"aria-label":a11yStatusLabel,isRunning}),a11yStatusValueToStoryIds["status-value:error"].length+a11yStatusValueToStoryIds["status-value:warning"].length||null)))))};var SidebarContextMenu=({context,api})=>{let{testProviderState,componentTestStatusValueToStoryIds,a11yStatusValueToStoryIds,storeState,setStoreState}=useTestProvider(api,context.id);return React3.createElement(TestProviderRender,{api,entry:context,style:{minWidth:240},testProviderState,componentTestStatusValueToStoryIds,a11yStatusValueToStoryIds,storeState,setStoreState,isSettingsUpdated:!1})};addons.register(ADDON_ID3,api=>{if((globalThis.STORYBOOK_BUILDER||"").includes("vite")){let openPanel2=panelId=>{api.setSelectedPanel(panelId),api.togglePanel(!0);};componentTestStatusStore.onSelect(()=>{openPanel2(PANEL_ID);}),a11yStatusStore.onSelect(()=>{openPanel2(PANEL_ID2);}),testProviderStore.onRunAll(()=>{store.send({type:"TRIGGER_RUN",payload:{triggeredBy:"run-all"}});}),store.untilReady().then(()=>{store.setState(state=>({...state,indexUrl:new URL("index.json",window.location.href).toString()}));}),addons.add(TEST_PROVIDER_ID,{type:Addon_TypesEnum.experimental_TEST_PROVIDER,render:()=>{let[isModalOpen,setModalOpen]=useState(!1),{storeState,setStoreState,testProviderState,componentTestStatusValueToStoryIds,a11yStatusValueToStoryIds,isSettingsUpdated}=useTestProvider(api);return React3.createElement(GlobalErrorContext.Provider,{value:{isModalOpen,setModalOpen}},React3.createElement(TestProviderRender,{api,storeState,setStoreState,isSettingsUpdated,testProviderState,componentTestStatusValueToStoryIds,a11yStatusValueToStoryIds}),React3.createElement(GlobalErrorModal,{storeState,onRerun:()=>{setModalOpen(!1),store.send({type:"TRIGGER_RUN",payload:{triggeredBy:"global"}});}}))},sidebarContextMenu:({context})=>context.type==="docs"||context.type==="story"&&!context.tags.includes("test")?null:React3.createElement(SidebarContextMenu,{context,api})});}});
8
+ var ADDON_ID="storybook/interactions",PANEL_ID=`${ADDON_ID}/panel`;var ADDON_ID2="storybook/a11y",PANEL_ID2=`${ADDON_ID2}/panel`;var ADDON_ID3="storybook/test",TEST_PROVIDER_ID=`${ADDON_ID3}/test-provider`;var DOCUMENTATION_LINK3="writing-tests/integrations/vitest-addon",DOCUMENTATION_FATAL_ERROR_LINK=`${DOCUMENTATION_LINK3}#what-happens-if-vitest-itself-has-an-error`;var storeOptions={id:ADDON_ID3,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}}},FULL_RUN_TRIGGERS=["global","run-all"];var STATUS_TYPE_ID_COMPONENT_TEST="storybook/component-test",STATUS_TYPE_ID_A11Y="storybook/a11y";var store=experimental_UniversalStore.create({...storeOptions,leader:globalThis.CONFIG_TYPE==="PRODUCTION"}),componentTestStatusStore=experimental_getStatusStore(STATUS_TYPE_ID_COMPONENT_TEST),a11yStatusStore=experimental_getStatusStore(STATUS_TYPE_ID_A11Y),testProviderStore=experimental_getTestProviderStore(ADDON_ID3);var ModalBar=styled.div({display:"flex",justifyContent:"space-between",alignItems:"center",padding:"6px 6px 6px 20px"}),ModalActionBar=styled.div({display:"flex",justifyContent:"space-between",alignItems:"center"}),ModalTitle=styled(Modal.Title)(({theme:{typography}})=>({fontSize:typography.size.s2,fontWeight:typography.weight.bold})),ModalStackTrace=styled.pre(({theme})=>({whiteSpace:"pre-wrap",wordWrap:"break-word",overflow:"auto",maxHeight:"60vh",margin:0,padding:"20px",fontFamily:theme.typography.fonts.mono,fontSize:"12px",borderTop:`1px solid ${theme.appBorderColor}`,borderRadius:0})),TroubleshootLink=styled.a(({theme})=>({color:theme.color.defaultText})),GlobalErrorContext=React3.createContext({isModalOpen:!1,setModalOpen:void 0});function ErrorCause({error}){return error?React3.createElement("div",null,React3.createElement("h4",null,"Caused by: ",error.name||"Error",": ",error.message),error.stack&&React3.createElement("pre",null,error.stack),error.cause&&React3.createElement(ErrorCause,{error:error.cause})):null}function GlobalErrorModal({onRerun,storeState}){let api=useStorybookApi(),{isModalOpen,setModalOpen}=useContext(GlobalErrorContext),handleClose=()=>setModalOpen?.(!1),troubleshootURL=api.getDocsUrl({subpath:DOCUMENTATION_FATAL_ERROR_LINK,versioned:!0,renderer:!0}),{fatalError,currentRun:{unhandledErrors}}=storeState,content=fatalError?React3.createElement(React3.Fragment,null,React3.createElement("p",null,fatalError.error.name||"Error"),fatalError.message&&React3.createElement("p",null,fatalError.message),fatalError.error.message&&React3.createElement("p",null,fatalError.error.message),fatalError.error.stack&&React3.createElement("p",null,fatalError.error.stack),fatalError.error.cause&&React3.createElement(ErrorCause,{error:fatalError.error.cause})):unhandledErrors.length>0?React3.createElement("ol",null,unhandledErrors.map(error=>React3.createElement("li",{key:error.name+error.message},React3.createElement("p",null,error.name,": ",error.message),error.VITEST_TEST_PATH&&React3.createElement("p",null,'This error originated in "',React3.createElement("b",null,error.VITEST_TEST_PATH),`". It doesn't mean the error was thrown inside the file itself, but while it was running.`),error.VITEST_TEST_NAME&&React3.createElement(React3.Fragment,null,React3.createElement("p",null,`The latest test that might've caused the error is "`,React3.createElement("b",null,error.VITEST_TEST_NAME),'". It might mean one of the following:'),React3.createElement("ul",null,React3.createElement("li",null,"The error was thrown, while Vitest was running this test."),React3.createElement("li",null,"If the error occurred after the test had been completed, this was the last documented test before it was thrown."))),error.stacks&&React3.createElement(React3.Fragment,null,React3.createElement("p",null,React3.createElement("b",null,"Stacks:")),React3.createElement("ul",null,error.stacks.map(stack=>React3.createElement("li",{key:stack.file+stack.line+stack.column},stack.file,":",stack.line,":",stack.column," - ",stack.method||"unknown method")))),error.stack&&React3.createElement("p",null,error.stack),error.cause?React3.createElement(ErrorCause,{error:error.cause}):null))):null;return React3.createElement(Modal,{onEscapeKeyDown:handleClose,onInteractOutside:handleClose,open:isModalOpen},React3.createElement(ModalBar,null,React3.createElement(ModalTitle,null,"Storybook Tests error details"),React3.createElement(ModalActionBar,null,React3.createElement(Button,{onClick:onRerun,variant:"ghost"},React3.createElement(SyncIcon,null),"Rerun"),React3.createElement(Button,{variant:"ghost",asChild:!0},React3.createElement("a",{target:"_blank",href:troubleshootURL,rel:"noreferrer"},"Troubleshoot")),React3.createElement(IconButton,{onClick:handleClose,"aria-label":"Close modal"},React3.createElement(CloseIcon,null)))),React3.createElement(ModalStackTrace,null,content,React3.createElement("br",null),React3.createElement("br",null),"Troubleshoot:"," ",React3.createElement(TroubleshootLink,{target:"_blank",href:troubleshootURL},troubleshootURL)))}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 statusValueToStoryIds=(allStatuses,typeId,storyIds)=>{let statusValueToStoryIdsMap={"status-value:pending":[],"status-value:success":[],"status-value:error":[],"status-value:warning":[],"status-value:unknown":[]};return (storyIds?storyIds.map(storyId=>allStatuses[storyId]).filter(Boolean):Object.values(allStatuses)).forEach(statusByTypeId=>{let status=statusByTypeId[typeId];status&&statusValueToStoryIdsMap[status.value].push(status.storyId);}),statusValueToStoryIdsMap},useTestProvider=(api,entryId)=>{let testProviderState=experimental_useTestProviderStore(s=>s[ADDON_ID3]),[storeState,setStoreState]=experimental_useUniversalStore(store),[isSettingsUpdated,setIsSettingsUpdated]=useState(!1),settingsUpdatedTimeoutRef=useRef();useEffect(()=>{let unsubscribe=store.onStateChange((state,previousState)=>{isEqual(state.config,previousState.config)||(testProviderStore.settingsChanged(),setIsSettingsUpdated(!0),clearTimeout(settingsUpdatedTimeoutRef.current),settingsUpdatedTimeoutRef.current=setTimeout(()=>{setIsSettingsUpdated(!1);},1e3));});return ()=>{unsubscribe(),clearTimeout(settingsUpdatedTimeoutRef.current);}},[]);let storyIds=useMemo(()=>entryId?api.findAllLeafStoryIds(entryId):void 0,[entryId,api]),componentTestStatusSelector=useCallback(allStatuses=>statusValueToStoryIds(allStatuses,STATUS_TYPE_ID_COMPONENT_TEST,storyIds),[storyIds]),componentTestStatusValueToStoryIds=experimental_useStatusStore(componentTestStatusSelector),a11yStatusValueToStoryIdsSelector=useCallback(allStatuses=>statusValueToStoryIds(allStatuses,STATUS_TYPE_ID_A11Y,storyIds),[storyIds]),a11yStatusValueToStoryIds=experimental_useStatusStore(a11yStatusValueToStoryIdsSelector);return {storeState,setStoreState,testProviderState,componentTestStatusValueToStoryIds,a11yStatusValueToStoryIds,isSettingsUpdated}};var RelativeTime=({timestamp})=>{let[timeAgo,setTimeAgo]=useState(null);if(useEffect(()=>{if(timestamp){setTimeAgo(Date.now()-timestamp);let interval=setInterval(()=>setTimeAgo(Date.now()-timestamp),1e4);return ()=>clearInterval(interval)}},[timestamp]),timeAgo===null)return null;let seconds=Math.round(timeAgo/1e3);if(seconds<60)return "just now";let minutes=Math.floor(seconds/60);if(minutes<60)return minutes===1?"a minute ago":`${minutes} minutes ago`;let hours=Math.floor(minutes/60);if(hours<24)return hours===1?"an hour ago":`${hours} hours ago`;let days=Math.floor(hours/24);return days===1?"yesterday":`${days} days ago`};var Wrapper=styled.div(({theme})=>({overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis",fontSize:theme.typography.size.s1,color:theme.textMutedColor})),PositiveText=styled.span(({theme})=>({color:theme.color.positiveText}));function Description({entryId,storeState,testProviderState,isSettingsUpdated,...props}){let{setModalOpen}=React3.useContext(GlobalErrorContext),{componentTestCount,totalTestCount,unhandledErrors,finishedAt}=storeState.currentRun,finishedTestCount=componentTestCount.success+componentTestCount.error,description="Not run";if(!entryId&&isSettingsUpdated)description=React3.createElement(PositiveText,null,"Settings updated");else if(testProviderState==="test-provider-state:running")description=(finishedTestCount??0)===0?"Starting...":`Testing... ${finishedTestCount}/${totalTestCount}`;else if(!entryId&&testProviderState==="test-provider-state:crashed")description=setModalOpen?React3.createElement(Link,{isButton:!0,onClick:()=>setModalOpen(!0)},"View full error"):"Crashed";else if(!entryId&&unhandledErrors.length>0){let unhandledErrorDescription=`View ${unhandledErrors.length} unhandled error${unhandledErrors?.length>1?"s":""}`;description=setModalOpen?React3.createElement(Link,{isButton:!0,onClick:()=>setModalOpen(!0)},unhandledErrorDescription):unhandledErrorDescription;}else entryId&&totalTestCount?description=`Ran ${totalTestCount} ${totalTestCount===1?"test":"tests"}`:finishedAt?description=React3.createElement(React3.Fragment,null,"Ran ",totalTestCount," ",totalTestCount===1?"test":"tests"," ",React3.createElement(RelativeTime,{timestamp:finishedAt})):storeState.watching&&(description="Watching for file changes");return React3.createElement(Wrapper,{...props},description)}var TestStatusIcon=styled.div(({percentage})=>({width:percentage?12:6,height:percentage?12:6,margin:percentage?1:4,background:percentage?`conic-gradient(var(--status-color) ${percentage}%, var(--status-background) ${percentage+1}%)`:"var(--status-color)",borderRadius:"50%"}),({isRunning,theme})=>isRunning&&{animation:`${theme.animation.glow} 1.5s ease-in-out infinite`},({status,theme})=>status==="positive"&&{"--status-color":theme.color.positive,"--status-background":`${theme.color.positive}66`},({status,theme})=>status==="warning"&&{"--status-color":theme.color.gold,"--status-background":`${theme.color.gold}66`},({status,theme})=>status==="negative"&&{"--status-color":theme.color.negative,"--status-background":`${theme.color.negative}66`},({status,theme})=>status==="critical"&&{"--status-color":theme.color.defaultText,"--status-background":`${theme.color.defaultText}66`},({status,theme})=>status==="unknown"&&{"--status-color":theme.color.mediumdark,"--status-background":`${theme.color.mediumdark}66`});var Container=styled.div({display:"flex",flexDirection:"column"}),Heading=styled.div({display:"flex",justifyContent:"space-between",padding:"8px 0",gap:12}),Info=styled.div({display:"flex",flexDirection:"column",marginLeft:8,minWidth:0}),Title=styled.div(({crashed,theme})=>({fontSize:theme.typography.size.s1,fontWeight:crashed?"bold":"normal",color:crashed?theme.color.negativeText:theme.color.defaultText})),Actions=styled.div({display:"flex",gap:4}),Extras=styled.div({marginBottom:2}),Muted=styled.span(({theme})=>({color:theme.textMutedColor})),Progress=styled(ProgressSpinner)({margin:4}),Row=styled.div({display:"flex",gap:4}),StopIcon=styled(StopAltIcon)({width:10}),openPanel=({api,panelId,entryId})=>{let story=entryId?api.findAllLeafStoryIds(entryId)[0]:void 0;story&&api.selectStory(story),api.setSelectedPanel(panelId),api.togglePanel(!0);},TestProviderRender=({api,entry,testProviderState,storeState,setStoreState,componentTestStatusValueToStoryIds,a11yStatusValueToStoryIds,isSettingsUpdated,...props})=>{let{config,watching,cancelling,currentRun,fatalError}=storeState,finishedTestCount=currentRun.componentTestCount.success+currentRun.componentTestCount.error,hasA11yAddon=addons.experimental_getRegisteredAddons().includes(ADDON_ID2),isRunning=testProviderState==="test-provider-state:running",isStarting=isRunning&&finishedTestCount===0,[componentTestStatusIcon,componentTestStatusLabel]=fatalError?["critical","Component tests crashed"]:componentTestStatusValueToStoryIds["status-value:error"].length>0?["negative","Component tests failed"]:isRunning?["unknown","Testing in progress"]:componentTestStatusValueToStoryIds["status-value:success"].length>0?["positive","Component tests passed"]:["unknown","Run tests to see results"],[a11yStatusIcon,a11yStatusLabel]=fatalError?["critical","Component tests crashed"]:a11yStatusValueToStoryIds["status-value:error"].length>0?["negative","Accessibility tests failed"]:a11yStatusValueToStoryIds["status-value:warning"].length>0?["warning","Accessibility tests failed"]:isRunning?["unknown","Testing in progress"]:a11yStatusValueToStoryIds["status-value:success"].length>0?["positive","Accessibility tests passed"]:["unknown","Run tests to see accessibility results"];return React3.createElement(Container,{...props},React3.createElement(Heading,null,React3.createElement(Info,null,entry?React3.createElement(Title,{id:"testing-module-title"},"Run component tests"):React3.createElement(Title,{id:"testing-module-title",crashed:testProviderState==="test-provider-state:crashed"||fatalError!==void 0||currentRun.unhandledErrors.length>0},currentRun.unhandledErrors.length===1?"Component tests completed with an error":currentRun.unhandledErrors.length>1?"Component tests completed with errors":fatalError?"Component tests didn\u2019t complete":"Run component tests"),React3.createElement(Description,{id:"testing-module-description",storeState,testProviderState,entryId:entry?.id,isSettingsUpdated})),React3.createElement(Actions,null,!entry&&React3.createElement(WithTooltip,{hasChrome:!1,trigger:"hover",tooltip:React3.createElement(TooltipNote,{note:`${watching?"Disable":"Enable"} watch mode`})},React3.createElement(IconButton,{"aria-label":`${watching?"Disable":"Enable"} watch mode`,size:"medium",active:watching,onClick:()=>store.send({type:"TOGGLE_WATCHING",payload:{to:!watching}}),disabled:isRunning},React3.createElement(EyeIcon,null))),isRunning?React3.createElement(WithTooltip,{hasChrome:!1,trigger:"hover",tooltip:React3.createElement(TooltipNote,{note:cancelling?"Stopping...":"Stop test run"})},React3.createElement(IconButton,{"aria-label":cancelling?"Stopping...":"Stop test run",padding:"none",size:"medium",onClick:()=>store.send({type:"CANCEL_RUN"}),disabled:cancelling||isStarting},React3.createElement(Progress,{percentage:finishedTestCount&&storeState.currentRun.totalTestCount?finishedTestCount/storeState.currentRun.totalTestCount*100:void 0},React3.createElement(StopIcon,null)))):React3.createElement(WithTooltip,{hasChrome:!1,trigger:"hover",tooltip:React3.createElement(TooltipNote,{note:"Start test run"})},React3.createElement(IconButton,{"aria-label":"Start test run",size:"medium",onClick:()=>store.send({type:"TRIGGER_RUN",payload:{storyIds:entry?api.findAllLeafStoryIds(entry.id):void 0,triggeredBy:entry?entry.type:"global"}})},React3.createElement(PlayHollowIcon,null))))),React3.createElement(Extras,null,React3.createElement(Row,null,React3.createElement(ListItem,{as:"label",title:"Interactions",icon:entry?null:React3.createElement(Form.Checkbox,{checked:!0,disabled:!0})}),React3.createElement(WithTooltip,{hasChrome:!1,trigger:"hover",tooltip:React3.createElement(TooltipNote,{note:componentTestStatusLabel})},React3.createElement(IconButton,{size:"medium",disabled:componentTestStatusValueToStoryIds["status-value:error"].length===0&&componentTestStatusValueToStoryIds["status-value:warning"].length===0&&componentTestStatusValueToStoryIds["status-value:success"].length===0,onClick:()=>{openPanel({api,panelId:PANEL_ID,entryId:componentTestStatusValueToStoryIds["status-value:error"][0]??componentTestStatusValueToStoryIds["status-value:warning"][0]??componentTestStatusValueToStoryIds["status-value:success"][0]??entry?.id});}},React3.createElement(TestStatusIcon,{status:componentTestStatusIcon,"aria-label":componentTestStatusLabel,isRunning}),componentTestStatusValueToStoryIds["status-value:error"].length+componentTestStatusValueToStoryIds["status-value:warning"].length||null))),!entry&&React3.createElement(Row,null,React3.createElement(ListItem,{as:"label",title:watching?React3.createElement(Muted,null,"Coverage (unavailable)"):"Coverage",icon:React3.createElement(Form.Checkbox,{checked:config.coverage,disabled:isRunning,onChange:()=>setStoreState(s=>({...s,config:{...s.config,coverage:!config.coverage}}))})}),React3.createElement(WithTooltip,{hasChrome:!1,trigger:"hover",tooltip:React3.createElement(TooltipNote,{note:watching?"Unavailable in watch mode":currentRun.triggeredBy&&!FULL_RUN_TRIGGERS.includes(currentRun.triggeredBy)?"Unavailable when running focused tests":isRunning?"Testing in progress":currentRun.coverageSummary?"View coverage report":fatalError?"Component tests crashed":"Run tests to calculate coverage"})},watching||currentRun.triggeredBy&&!FULL_RUN_TRIGGERS.includes(currentRun.triggeredBy)?React3.createElement(IconButton,{size:"medium",disabled:!0},React3.createElement(InfoIcon,{"aria-label":watching?"Coverage is unavailable in watch mode":"Coverage is unavailable when running focused tests"})):currentRun.coverageSummary?React3.createElement(IconButton,{asChild:!0,size:"medium"},React3.createElement("a",{href:"/coverage/index.html",target:"_blank","aria-label":"Open coverage report"},React3.createElement(TestStatusIcon,{isRunning,percentage:currentRun.coverageSummary.percentage,status:currentRun.coverageSummary.status,"aria-label":`Coverage status: ${currentRun.coverageSummary.status}`}),React3.createElement("span",{"aria-label":`${currentRun.coverageSummary.percentage} percent coverage`},currentRun.coverageSummary.percentage,"%"))):React3.createElement(IconButton,{size:"medium",disabled:!0},React3.createElement(TestStatusIcon,{isRunning,status:fatalError?"critical":"unknown","aria-label":"Coverage status: unknown"})))),hasA11yAddon&&React3.createElement(Row,null,React3.createElement(ListItem,{as:"label",title:"Accessibility",icon:entry?null:React3.createElement(Form.Checkbox,{checked:config.a11y,disabled:isRunning,onChange:()=>setStoreState(s=>({...s,config:{...s.config,a11y:!config.a11y}}))})}),React3.createElement(WithTooltip,{hasChrome:!1,trigger:"hover",tooltip:React3.createElement(TooltipNote,{note:a11yStatusLabel})},React3.createElement(IconButton,{size:"medium",disabled:a11yStatusValueToStoryIds["status-value:error"].length===0&&a11yStatusValueToStoryIds["status-value:warning"].length===0&&a11yStatusValueToStoryIds["status-value:success"].length===0,onClick:()=>{openPanel({api,entryId:a11yStatusValueToStoryIds["status-value:error"][0]??a11yStatusValueToStoryIds["status-value:warning"][0]??a11yStatusValueToStoryIds["status-value:success"][0]??entry?.id,panelId:PANEL_ID2});}},React3.createElement(TestStatusIcon,{status:a11yStatusIcon,"aria-label":a11yStatusLabel,isRunning}),a11yStatusValueToStoryIds["status-value:error"].length+a11yStatusValueToStoryIds["status-value:warning"].length||null)))))};var SidebarContextMenu=({context,api})=>{let{testProviderState,componentTestStatusValueToStoryIds,a11yStatusValueToStoryIds,storeState,setStoreState}=useTestProvider(api,context.id);return React3.createElement(TestProviderRender,{api,entry:context,style:{minWidth:240},testProviderState,componentTestStatusValueToStoryIds,a11yStatusValueToStoryIds,storeState,setStoreState,isSettingsUpdated:!1})};addons.register(ADDON_ID3,api=>{let openPanel2=panelId=>{api.setSelectedPanel(panelId),api.togglePanel(!0);};componentTestStatusStore.onSelect(()=>{openPanel2(PANEL_ID);}),a11yStatusStore.onSelect(()=>{openPanel2(PANEL_ID2);}),testProviderStore.onRunAll(()=>{store.send({type:"TRIGGER_RUN",payload:{triggeredBy:"run-all"}});}),store.untilReady().then(()=>{store.setState(state=>({...state,indexUrl:new URL("index.json",window.location.href).toString()}));}),addons.add(TEST_PROVIDER_ID,{type:Addon_TypesEnum.experimental_TEST_PROVIDER,render:()=>{let[isModalOpen,setModalOpen]=useState(!1),{storeState,setStoreState,testProviderState,componentTestStatusValueToStoryIds,a11yStatusValueToStoryIds,isSettingsUpdated}=useTestProvider(api);return React3.createElement(GlobalErrorContext.Provider,{value:{isModalOpen,setModalOpen}},React3.createElement(TestProviderRender,{api,storeState,setStoreState,isSettingsUpdated,testProviderState,componentTestStatusValueToStoryIds,a11yStatusValueToStoryIds}),React3.createElement(GlobalErrorModal,{storeState,onRerun:()=>{setModalOpen(!1),store.send({type:"TRIGGER_RUN",payload:{triggeredBy:"global"}});}}))},sidebarContextMenu:({context})=>context.type==="docs"||context.type==="story"&&!context.tags.includes("test")?null:React3.createElement(SidebarContextMenu,{context,api})});});
@@ -49,7 +49,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
49
49
  ${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:error2,signal,exitCode,command,escapedCommand,timedOut,isCanceled,killed,parsed:{options:{timeout,cwd:cwd2=process2__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=error2&&error2.code,execaMessage=`Command ${getErrorPrefix({timedOut,timeout,errorCode,signal,signalDescription,exitCode,isCanceled})}: ${command}`,isError=Object.prototype.toString.call(error2)==="[object Error]",shortMessage=isError?`${execaMessage}
50
50
  ${error2.message}`:execaMessage,message=[shortMessage,stderr,stdout].filter(Boolean).join(`
51
51
  `);return isError?(error2.originalMessage=error2.message,error2.message=message):error2=new Error(message),error2.shortMessage=shortMessage,error2.command=command,error2.escapedCommand=escapedCommand,error2.exitCode=exitCode,error2.signal=signal,error2.signalDescription=signalDescription,error2.stdout=stdout,error2.stderr=stderr,error2.cwd=cwd2,all!==void 0&&(error2.all=all),"bufferedData"in error2&&delete error2.bufferedData,error2.failed=!0,error2.timedOut=!!timedOut,error2.isCanceled=isCanceled,error2.killed=killed&&!timedOut,error2};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])};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=process8=>!!process8&&typeof process8=="object"&&typeof process8.removeListener=="function"&&typeof process8.emit=="function"&&typeof process8.reallyExit=="function"&&typeof process8.listeners=="function"&&typeof process8.kill=="function"&&typeof process8.pid=="number"&&typeof process8.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(process8){super(),this.#process=process8,this.#sigListeners={};for(let sig of signals)this.#sigListeners[sig]=()=>{let listeners=this.#process.listeners(sig),{count}=this.#emitter,p=process8;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||process8.kill(process8.pid,s);}};this.#originalProcessReallyExit=process8.reallyExit,this.#originalProcessEmit=process8.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(error2){throw error2.bufferedData=finalize(state),error2}},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,noop=()=>{},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:noop,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(error2){throw error2.bufferedData!==void 0&&(error2.bufferedData=arrayBufferToNodeBuffer(error2.bufferedData)),error2}}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.setTimeout(0),stream.destroy();try{return await streamPromise}catch(error2){return error2.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(error2){return Promise.all([{error:error2,signal:error2.signal,timedOut:error2.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",error2=>{reject(error2);}),spawned.stdin&&spawned.stdin.on("error",error2=>{reject(error2);});});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&&process2__default.default.stderr.write(`[${getTimestamp()}] ${escapedCommand}
52
- `);};var DEFAULT_MAX_BUFFER=1e3*1e3*100,getEnv=({env:envOption,extendEnv,preferLocal,localDir,execPath})=>{let env=extendEnv?{...process2__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||process2__default.default.cwd(),execPath:process2__default.default.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:verboseDefault,...options},options.env=getEnv(options),options.stdio=normalizeStdio(options),process2__default.default.platform==="win32"&&path__default.default.basename(file,".exe")==="cmd"&&args.unshift("/q"),{file,args,options,parsed}},handleOutput=(options,value,error2)=>typeof value!="string"&&!buffer.Buffer.isBuffer(value)?error2===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(error2){let dummySpawned=new childProcess__default.default.ChildProcess,errorPromise=Promise.reject(makeError({error:error2,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:error2,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(error2||exitCode!==0||signal!==null){let returnedError=makeError({error:error2,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}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(error2){if(error2 instanceof EndError)return error2.value;throw error2}}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=process2__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(path__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=path__default.default.resolve(toPath2(options.cwd)??""),{root}=path__default.default.parse(directory),stopAt=path__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(path__default.default.resolve(directory,foundPath)),directory===stopAt||matches.length>=limit))break;directory=path__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]:)?$/;var normalize=function(path6){if(path6.length===0)return ".";path6=normalizeWindowsPath(path6);let isUNCPath=path6.match(_UNC_REGEX),isPathAbsolute=isAbsolute(path6),trailingSeparator=path6[path6.length-1]==="/";return path6=normalizeString(path6,!isPathAbsolute),path6.length===0?isPathAbsolute?"/":trailingSeparator?"./":".":(trailingSeparator&&(path6+="/"),_DRIVE_LETTER_RE.test(path6)&&(path6+="/"),isUNCPath?isPathAbsolute?`//${path6}`:`//./${path6}`:isPathAbsolute&&!isAbsolute(path6)?`/${path6}`:path6)},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 path6=index>=0?arguments_[index]:cwd();!path6||path6.length===0||(resolvedPath=`${path6}/${resolvedPath}`,resolvedAbsolute=isAbsolute(path6));}return resolvedPath=normalizeString(resolvedPath,!resolvedAbsolute),resolvedAbsolute&&!isAbsolute(resolvedPath)?`/${resolvedPath}`:resolvedPath.length>0?resolvedPath:"."};function normalizeString(path6,allowAboveRoot){let res="",lastSegmentLength=0,lastSlash=-1,dots=0,char=null;for(let index=0;index<=path6.length;++index){if(index<path6.length)char=path6[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+=`/${path6.slice(lastSlash+1,index)}`:res=path6.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 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)?"/":".")};var import_semver=__toESM(require_semver2());var DOCUMENTATION_LINK2="writing-tests/integrations/vitest-addon";var SUPPORTED_FRAMEWORKS=["@storybook/nextjs","@storybook/nextjs-vite","@storybook/react-vite","@storybook/svelte-vite","@storybook/vue3-vite","@storybook/html-vite","@storybook/web-components-vite","@storybook/sveltekit","@storybook/react-native-web-vite"];var fancy=process.platform!=="win32"||process.env.CI||process.env.TERM==="xterm-256color",step=nodeLogger.colors.gray("\u203A");nodeLogger.colors.blue(fancy?"\u2139":"i");nodeLogger.colors.green(fancy?"\u2714":"\u221A");nodeLogger.colors.orange(fancy?"\u26A0":"\u203C");nodeLogger.colors.red(fancy?"\u2716":"\xD7");var baseOptions={borderStyle:"round",padding:1},print=(message,options)=>{nodeLogger.logger.line(1),nodeLogger.logger.logBox(message,{...baseOptions,...options});},printInfo=(title,message,options)=>print(message,{borderColor:"blue",title,...options}),printWarning=(title,message,options)=>print(message,{borderColor:"yellow",title,...options}),printError=(title,message,options)=>print(message,{borderColor:"red",title,...options}),printSuccess=(title,message,options)=>print(message,{borderColor:"green",title,...options});var loadTemplate=async(name,replacements)=>{let template=await fs4__namespace.readFile(join(dirname(__require.resolve("@storybook/addon-vitest/package.json")),"templates",name),"utf8");return Object.entries(replacements).forEach(([key,value])=>template=template.replace(key,value)),template},mergeProperties=(source,target)=>{for(let sourceProp of source)if(sourceProp.type==="ObjectProperty"){let targetProp=target.find(p=>sourceProp.key.type==="Identifier"&&p.type==="ObjectProperty"&&p.key.type==="Identifier"&&p.key.name===sourceProp.key.name);targetProp&&targetProp.type==="ObjectProperty"?sourceProp.value.type==="ObjectExpression"&&targetProp.value.type==="ObjectExpression"?mergeProperties(sourceProp.value.properties,targetProp.value.properties):sourceProp.value.type==="ArrayExpression"&&targetProp.value.type==="ArrayExpression"?targetProp.value.elements.push(...sourceProp.value.elements):targetProp.value=sourceProp.value:target.push(sourceProp);}},updateConfigFile=(source,target)=>{let updated=!1;for(let sourceNode of source.program.body)if(sourceNode.type==="ImportDeclaration"){if(!target.program.body.some(targetNode=>targetNode.type===sourceNode.type&&targetNode.specifiers.some(s=>s.local.name===sourceNode.specifiers[0].local.name))){let lastImport=target.program.body.findLastIndex(n=>n.type==="ImportDeclaration");target.program.body.splice(lastImport+1,0,sourceNode);}}else if(sourceNode.type==="VariableDeclaration"){if(!target.program.body.some(targetNode=>targetNode.type===sourceNode.type&&targetNode.declarations.some(d=>"name"in d.id&&"name"in sourceNode.declarations[0].id&&d.id.name===sourceNode.declarations[0].id.name))){let lastImport=target.program.body.findLastIndex(n=>n.type==="ImportDeclaration");target.program.body.splice(lastImport+1,0,sourceNode);}}else if(sourceNode.type==="ExportDefaultDeclaration"){let exportDefault=target.program.body.find(n=>n.type==="ExportDefaultDeclaration");if(exportDefault&&sourceNode.declaration.type==="CallExpression"&&sourceNode.declaration.arguments.length>0&&sourceNode.declaration.arguments[0].type==="ObjectExpression"){let{properties}=sourceNode.declaration.arguments[0];exportDefault.declaration.type==="ObjectExpression"?(mergeProperties(properties,exportDefault.declaration.properties),updated=!0):exportDefault.declaration.type==="CallExpression"&&exportDefault.declaration.callee.type==="Identifier"&&exportDefault.declaration.callee.name==="defineConfig"&&exportDefault.declaration.arguments[0]?.type==="ObjectExpression"&&(mergeProperties(properties,exportDefault.declaration.arguments[0].properties),updated=!0);}}return updated},updateWorkspaceFile=(source,target)=>{let updated=!1;for(let sourceNode of source.program.body)if(sourceNode.type==="ImportDeclaration"){if(!target.program.body.some(targetNode=>targetNode.type===sourceNode.type&&targetNode.source.value===sourceNode.source.value&&targetNode.specifiers.some(s=>s.local.name===sourceNode.specifiers[0].local.name))){let lastImport=target.program.body.findLastIndex(n=>n.type==="ImportDeclaration");target.program.body.splice(lastImport+1,0,sourceNode);}}else if(sourceNode.type==="VariableDeclaration"){if(!target.program.body.some(targetNode=>targetNode.type===sourceNode.type&&targetNode.declarations.some(d=>"name"in d.id&&"name"in sourceNode.declarations[0].id&&d.id.name===sourceNode.declarations[0].id.name))){let lastImport=target.program.body.findLastIndex(n=>n.type==="ImportDeclaration");target.program.body.splice(lastImport+1,0,sourceNode);}}else if(sourceNode.type==="ExportDefaultDeclaration"){let exportDefault=target.program.body.find(n=>n.type==="ExportDefaultDeclaration");if(exportDefault&&sourceNode.declaration.type==="CallExpression"&&sourceNode.declaration.arguments.length>0&&sourceNode.declaration.arguments[0].type==="ArrayExpression"&&sourceNode.declaration.arguments[0].elements.length>0){let{elements}=sourceNode.declaration.arguments[0];exportDefault.declaration.type==="ArrayExpression"?(exportDefault.declaration.elements.push(...elements),updated=!0):exportDefault.declaration.type==="CallExpression"&&exportDefault.declaration.callee.type==="Identifier"&&exportDefault.declaration.callee.name==="defineWorkspace"&&exportDefault.declaration.arguments[0]?.type==="ArrayExpression"&&(exportDefault.declaration.arguments[0].elements.push(...elements),updated=!0);}}return updated};function getAddonNames(mainConfig){return (mainConfig.addons||[]).map(addon=>{let name="";return typeof addon=="string"?name=addon:typeof addon=="object"&&(name=addon.name),name}).filter(item=>item!=null)}var ADDON_NAME="@storybook/addon-vitest",EXTENSIONS=[".ts",".tsx",".js",".jsx",".cts",".mts",".cjs",".mjs"],addonA11yName="@storybook/addon-a11y",hasErrors=!1,logErrors=(...args)=>{hasErrors=!0,printError(...args);},findFile=async(basename2,extensions=EXTENSIONS)=>findUp(extensions.map(ext=>basename2+ext),{stopAt:common.getProjectRoot()});async function postInstall(options){printSuccess("\u{1F44B} Howdy!",tsDedent.dedent`
52
+ `);};var DEFAULT_MAX_BUFFER=1e3*1e3*100,getEnv=({env:envOption,extendEnv,preferLocal,localDir,execPath})=>{let env=extendEnv?{...process2__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||process2__default.default.cwd(),execPath:process2__default.default.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,verbose:verboseDefault,...options},options.env=getEnv(options),options.stdio=normalizeStdio(options),process2__default.default.platform==="win32"&&path__default.default.basename(file,".exe")==="cmd"&&args.unshift("/q"),{file,args,options,parsed}},handleOutput=(options,value,error2)=>typeof value!="string"&&!buffer.Buffer.isBuffer(value)?error2===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(error2){let dummySpawned=new childProcess__default.default.ChildProcess,errorPromise=Promise.reject(makeError({error:error2,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:error2,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(error2||exitCode!==0||signal!==null){let returnedError=makeError({error:error2,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}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(error2){if(error2 instanceof EndError)return error2.value;throw error2}}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=process2__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(path__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=path__default.default.resolve(toPath2(options.cwd)??""),{root}=path__default.default.parse(directory),stopAt=path__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(path__default.default.resolve(directory,foundPath)),directory===stopAt||matches.length>=limit))break;directory=path__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]:)?$/;var normalize=function(path6){if(path6.length===0)return ".";path6=normalizeWindowsPath(path6);let isUNCPath=path6.match(_UNC_REGEX),isPathAbsolute=isAbsolute(path6),trailingSeparator=path6[path6.length-1]==="/";return path6=normalizeString(path6,!isPathAbsolute),path6.length===0?isPathAbsolute?"/":trailingSeparator?"./":".":(trailingSeparator&&(path6+="/"),_DRIVE_LETTER_RE.test(path6)&&(path6+="/"),isUNCPath?isPathAbsolute?`//${path6}`:`//./${path6}`:isPathAbsolute&&!isAbsolute(path6)?`/${path6}`:path6)},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 path6=index>=0?arguments_[index]:cwd();!path6||path6.length===0||(resolvedPath=`${path6}/${resolvedPath}`,resolvedAbsolute=isAbsolute(path6));}return resolvedPath=normalizeString(resolvedPath,!resolvedAbsolute),resolvedAbsolute&&!isAbsolute(resolvedPath)?`/${resolvedPath}`:resolvedPath.length>0?resolvedPath:"."};function normalizeString(path6,allowAboveRoot){let res="",lastSegmentLength=0,lastSlash=-1,dots=0,char=null;for(let index=0;index<=path6.length;++index){if(index<path6.length)char=path6[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+=`/${path6.slice(lastSlash+1,index)}`:res=path6.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 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)?"/":".")};var import_semver=__toESM(require_semver2());var DOCUMENTATION_LINK2="writing-tests/integrations/vitest-addon";var SUPPORTED_FRAMEWORKS=["@storybook/angular","@storybook/nextjs","@storybook/nextjs-vite","@storybook/react-vite","@storybook/react-webpack5","@storybook/svelte-vite","@storybook/vue3-vite","@storybook/html-vite","@storybook/web-components-vite","@storybook/sveltekit","@storybook/react-native-web-vite"];var fancy=process.platform!=="win32"||process.env.CI||process.env.TERM==="xterm-256color",step=nodeLogger.colors.gray("\u203A");nodeLogger.colors.blue(fancy?"\u2139":"i");nodeLogger.colors.green(fancy?"\u2714":"\u221A");nodeLogger.colors.orange(fancy?"\u26A0":"\u203C");nodeLogger.colors.red(fancy?"\u2716":"\xD7");var baseOptions={borderStyle:"round",padding:1},print=(message,options)=>{nodeLogger.logger.line(1),nodeLogger.logger.logBox(message,{...baseOptions,...options});},printInfo=(title,message,options)=>print(message,{borderColor:"blue",title,...options}),printWarning=(title,message,options)=>print(message,{borderColor:"yellow",title,...options}),printError=(title,message,options)=>print(message,{borderColor:"red",title,...options}),printSuccess=(title,message,options)=>print(message,{borderColor:"green",title,...options});var loadTemplate=async(name,replacements)=>{let template=await fs4__namespace.readFile(join(dirname(__require.resolve("@storybook/addon-vitest/package.json")),"templates",name),"utf8");return Object.entries(replacements).forEach(([key,value])=>template=template.replace(key,value)),template},mergeProperties=(source,target)=>{for(let sourceProp of source)if(sourceProp.type==="ObjectProperty"){let targetProp=target.find(p=>sourceProp.key.type==="Identifier"&&p.type==="ObjectProperty"&&p.key.type==="Identifier"&&p.key.name===sourceProp.key.name);targetProp&&targetProp.type==="ObjectProperty"?sourceProp.value.type==="ObjectExpression"&&targetProp.value.type==="ObjectExpression"?mergeProperties(sourceProp.value.properties,targetProp.value.properties):sourceProp.value.type==="ArrayExpression"&&targetProp.value.type==="ArrayExpression"?targetProp.value.elements.push(...sourceProp.value.elements):targetProp.value=sourceProp.value:target.push(sourceProp);}},updateConfigFile=(source,target)=>{let updated=!1;for(let sourceNode of source.program.body)if(sourceNode.type==="ImportDeclaration"){if(!target.program.body.some(targetNode=>targetNode.type===sourceNode.type&&targetNode.specifiers.some(s=>s.local.name===sourceNode.specifiers[0].local.name))){let lastImport=target.program.body.findLastIndex(n=>n.type==="ImportDeclaration");target.program.body.splice(lastImport+1,0,sourceNode);}}else if(sourceNode.type==="VariableDeclaration"){if(!target.program.body.some(targetNode=>targetNode.type===sourceNode.type&&targetNode.declarations.some(d=>"name"in d.id&&"name"in sourceNode.declarations[0].id&&d.id.name===sourceNode.declarations[0].id.name))){let lastImport=target.program.body.findLastIndex(n=>n.type==="ImportDeclaration");target.program.body.splice(lastImport+1,0,sourceNode);}}else if(sourceNode.type==="ExportDefaultDeclaration"){let exportDefault=target.program.body.find(n=>n.type==="ExportDefaultDeclaration");if(exportDefault&&sourceNode.declaration.type==="CallExpression"&&sourceNode.declaration.arguments.length>0&&sourceNode.declaration.arguments[0].type==="ObjectExpression"){let{properties}=sourceNode.declaration.arguments[0];exportDefault.declaration.type==="ObjectExpression"?(mergeProperties(properties,exportDefault.declaration.properties),updated=!0):exportDefault.declaration.type==="CallExpression"&&exportDefault.declaration.callee.type==="Identifier"&&exportDefault.declaration.callee.name==="defineConfig"&&exportDefault.declaration.arguments[0]?.type==="ObjectExpression"&&(mergeProperties(properties,exportDefault.declaration.arguments[0].properties),updated=!0);}}return updated},updateWorkspaceFile=(source,target)=>{let updated=!1;for(let sourceNode of source.program.body)if(sourceNode.type==="ImportDeclaration"){if(!target.program.body.some(targetNode=>targetNode.type===sourceNode.type&&targetNode.source.value===sourceNode.source.value&&targetNode.specifiers.some(s=>s.local.name===sourceNode.specifiers[0].local.name))){let lastImport=target.program.body.findLastIndex(n=>n.type==="ImportDeclaration");target.program.body.splice(lastImport+1,0,sourceNode);}}else if(sourceNode.type==="VariableDeclaration"){if(!target.program.body.some(targetNode=>targetNode.type===sourceNode.type&&targetNode.declarations.some(d=>"name"in d.id&&"name"in sourceNode.declarations[0].id&&d.id.name===sourceNode.declarations[0].id.name))){let lastImport=target.program.body.findLastIndex(n=>n.type==="ImportDeclaration");target.program.body.splice(lastImport+1,0,sourceNode);}}else if(sourceNode.type==="ExportDefaultDeclaration"){let exportDefault=target.program.body.find(n=>n.type==="ExportDefaultDeclaration");if(exportDefault&&sourceNode.declaration.type==="CallExpression"&&sourceNode.declaration.arguments.length>0&&sourceNode.declaration.arguments[0].type==="ArrayExpression"&&sourceNode.declaration.arguments[0].elements.length>0){let{elements}=sourceNode.declaration.arguments[0];exportDefault.declaration.type==="ArrayExpression"?(exportDefault.declaration.elements.push(...elements),updated=!0):exportDefault.declaration.type==="CallExpression"&&exportDefault.declaration.callee.type==="Identifier"&&exportDefault.declaration.callee.name==="defineWorkspace"&&exportDefault.declaration.arguments[0]?.type==="ArrayExpression"&&(exportDefault.declaration.arguments[0].elements.push(...elements),updated=!0);}}return updated};function getAddonNames(mainConfig){return (mainConfig.addons||[]).map(addon=>{let name="";return typeof addon=="string"?name=addon:typeof addon=="object"&&(name=addon.name),name}).filter(item=>item!=null)}var ADDON_NAME="@storybook/addon-vitest",EXTENSIONS=[".ts",".tsx",".js",".jsx",".cts",".mts",".cjs",".mjs"],addonA11yName="@storybook/addon-a11y",hasErrors=!1,logErrors=(...args)=>{hasErrors=!0,printError(...args);},findFile=async(basename2,extensions=EXTENSIONS)=>findUp(extensions.map(ext=>basename2+ext),{stopAt:common.getProjectRoot()});async function postInstall(options){printSuccess("\u{1F44B} Howdy!",tsDedent.dedent`
53
53
  I'm the installation helper for ${ADDON_NAME}
54
54
 
55
55
  Hold on for a moment while I look at your project and get it set up...
@@ -58,7 +58,7 @@ ${error2.message}`:execaMessage,message=[shortMessage,stderr,stdout].filter(Bool
58
58
  https://storybook.js.org/docs/next/${DOCUMENTATION_LINK2}#install-and-set-up
59
59
 
60
60
  Do you want to migrate?
61
- `,initial:!0})).migrateToNextjsVite&&(await packageManager.addDependencies({type:"devDependencies",skipInstall:!0},["@storybook/nextjs-vite"]),await packageManager.removeDependencies(["@storybook/nextjs"]),babel.traverse(config._ast,{StringLiteral(path6){path6.node.value==="@storybook/nextjs"&&(path6.node.value="@storybook/nextjs-vite");}}),await csfTools.writeConfig(config,mainJsPath),info2.frameworkPackageName="@storybook/nextjs-vite",info2.builderPackageName="@storybook/builder-vite",await common.scanAndTransformFiles({promptMessage:"Enter a glob to scan for all @storybook/nextjs imports to substitute with @storybook/nextjs-vite:",force:options.yes,dryRun:!1,transformFn:(files,options2,dryRun)=>common.transformImportFiles(files,options2,dryRun),transformOptions:{"@storybook/nextjs":"@storybook/nextjs-vite"}}));let annotationsImport=SUPPORTED_FRAMEWORKS.includes(info2.frameworkPackageName)?info2.frameworkPackageName==="@storybook/nextjs"?"@storybook/nextjs-vite":info2.frameworkPackageName:null,isRendererSupported=!!annotationsImport,result=await(async()=>{let reasons=[];hasCustomWebpackConfig&&reasons.push("\u2022 The addon can not be used with a custom Webpack configuration."),info2.frameworkPackageName!=="@storybook/nextjs"&&info2.builderPackageName!=="@storybook/builder-vite"&&reasons.push("\u2022 The addon can only be used with a Vite-based Storybook framework or Next.js."),isRendererSupported||reasons.push(tsDedent.dedent`
61
+ `,initial:!0})).migrateToNextjsVite&&(await packageManager.addDependencies({type:"devDependencies",skipInstall:!0},["@storybook/nextjs-vite"]),await packageManager.removeDependencies(["@storybook/nextjs"]),babel.traverse(config._ast,{StringLiteral(path6){path6.node.value==="@storybook/nextjs"&&(path6.node.value="@storybook/nextjs-vite");}}),await csfTools.writeConfig(config,mainJsPath),info2.frameworkPackageName="@storybook/nextjs-vite",info2.builderPackageName="@storybook/builder-vite",await common.scanAndTransformFiles({promptMessage:"Enter a glob to scan for all @storybook/nextjs imports to substitute with @storybook/nextjs-vite:",force:options.yes,dryRun:!1,transformFn:(files,options2,dryRun)=>common.transformImportFiles(files,options2,dryRun),transformOptions:{"@storybook/nextjs":"@storybook/nextjs-vite"}}));let annotationsImport=SUPPORTED_FRAMEWORKS.includes(info2.frameworkPackageName)?info2.frameworkPackageName==="@storybook/nextjs"?"@storybook/nextjs-vite":info2.frameworkPackageName:null,isRendererSupported=!!annotationsImport,result=await(async()=>{let reasons=[];isRendererSupported||reasons.push(tsDedent.dedent`
62
62
  • The addon cannot yet be used with ${info2.frameworkPackageName}
63
63
  `),coercedVitestVersion&&!(0, import_semver.satisfies)(coercedVitestVersion,">=3.0.0")&&reasons.push(tsDedent.dedent`
64
64
  • The addon requires Vitest 3.0.0 or higher. You are currently using ${vitestVersionSpecifier}.
package/dist/preset.js CHANGED
@@ -4,7 +4,6 @@ var promises = require('fs/promises');
4
4
  var common = require('storybook/internal/common');
5
5
  var coreServer = require('storybook/internal/core-server');
6
6
  var telemetry = require('storybook/internal/telemetry');
7
- var tsDedent = require('ts-dedent');
8
7
  var buffer = require('buffer');
9
8
  var path = require('path');
10
9
  var childProcess = require('child_process');
@@ -22,16 +21,12 @@ var childProcess__default = /*#__PURE__*/_interopDefault(childProcess);
22
21
  var process6__default = /*#__PURE__*/_interopDefault(process6);
23
22
  var os__default = /*#__PURE__*/_interopDefault(os);
24
23
 
25
- 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"?`
24
+ 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 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"?`
26
25
  `: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}*/
27
26
  ${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}
28
27
  ${error.message}`:execaMessage,message=[shortMessage,stderr,stdout].filter(Boolean).join(`
29
28
  `);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}
30
- `);};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`
31
- 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.
32
-
33
- Information on how to upgrade here: ${import_picocolors2.default.yellow("https://storybook.js.org/docs/get-started/frameworks/nextjs#with-vite")}\n
34
- `),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]};
29
+ `);};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),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]};
35
30
 
36
31
  exports.experimental_serverChannel = experimental_serverChannel;
37
32
  exports.staticDirs = staticDirs;
@@ -1,6 +1,12 @@
1
1
  import { Plugin } from 'vitest/config';
2
2
 
3
3
  type UserOptions = {
4
+ /**
5
+ * Whether to use Playwright to run the tests.
6
+ *
7
+ * @default false
8
+ */
9
+ usePlaywright?: boolean;
4
10
  /**
5
11
  * The directory where the Storybook configuration is located, relative to the vitest
6
12
  * configuration file. If not provided, the plugin will use '.storybook' in the current working