@storybook/nextjs 9.2.0-alpha.2 → 10.0.0-beta.0
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/README.md +3 -1
- package/dist/_browser-chunks/chunk-I5RFHXDS.js +40 -0
- package/dist/_browser-chunks/chunk-JOMP7DUK.js +261 -0
- package/dist/_browser-chunks/chunk-L5NVL7MD.js +37 -0
- package/dist/_browser-chunks/react-18-G7Q4PNHD.js +71 -0
- package/dist/_node-chunks/chunk-24UYJEDD.js +74 -0
- package/dist/_node-chunks/chunk-EZEBG77A.js +88 -0
- package/dist/_node-chunks/chunk-WCSGFZKZ.js +17 -0
- package/dist/_node-chunks/chunk-YMVPQWBH.js +167 -0
- package/dist/_node-chunks/configureNextFont-HBRWHAUG.js +36 -0
- package/dist/_node-chunks/loader-KXTZ5PJ5.js +51 -0
- package/dist/_node-chunks/loader-Z4IXWF5M.js +64 -0
- package/dist/_node-chunks/utils-4LRBHVQD.js +31 -0
- package/dist/_node-chunks/webpack-6HAXGE7X.js +38 -0
- package/dist/_node-chunks/webpack-AGNCA7HZ.js +77 -0
- package/dist/_node-chunks/webpack-CXSD35E6.js +30 -0
- package/dist/_node-chunks/webpack-EWT6TRQB.js +26 -0
- package/dist/_node-chunks/webpack-K2R3GUFU.js +29 -0
- package/dist/_node-chunks/webpack-PD7PIB6X.js +43 -0
- package/dist/_node-chunks/webpack-QFTZE3CE.js +27 -0
- package/dist/_node-chunks/webpack-SWQY6JJY.js +107 -0
- package/dist/compatibility/draft-mode.compat.js +7 -1
- package/dist/export-mocks/cache/index.d.ts +309 -1
- package/dist/export-mocks/cache/index.js +22 -1
- package/dist/export-mocks/headers/index.d.ts +309 -1
- package/dist/export-mocks/headers/index.js +77 -1
- package/dist/export-mocks/index.js +20 -1
- package/dist/export-mocks/navigation/index.d.ts +8 -1
- package/dist/export-mocks/navigation/index.js +88 -1
- package/dist/export-mocks/router/index.d.ts +2 -2
- package/dist/export-mocks/router/index.js +97 -1
- package/dist/font/webpack/loader/storybook-nextjs-font-loader.js +201 -14
- package/dist/image-context.js +8 -1
- package/dist/images/next-image.js +35 -1
- package/dist/images/next-legacy-image.js +21 -1
- package/dist/index.d.ts +53 -8
- package/dist/index.js +20237 -45
- package/dist/next-image-loader-stub.js +33 -1
- package/dist/node/index.d.ts +27 -6
- package/dist/node/index.js +23 -1
- package/dist/preset.js +830 -1
- package/dist/preview.d.ts +3 -18
- package/dist/preview.d.tsx +18 -0
- package/dist/preview.js +11 -1
- package/dist/rsc/server-only.js +7 -1
- package/dist/swc/next-swc-loader-patch.js +136 -1
- package/package.json +41 -122
- package/preset.js +1 -1
- package/template/cli/js/Configure.mdx +11 -11
- package/template/cli/ts/Configure.mdx +11 -11
- package/dist/chunk-2TZKD6A5.mjs +0 -20
- package/dist/chunk-ETFXNGLC.mjs +0 -3
- package/dist/chunk-L66KIASX.mjs +0 -3
- package/dist/chunk-NQ32RFK2.mjs +0 -6
- package/dist/compatibility/draft-mode.compat.d.ts +0 -1
- package/dist/compatibility/draft-mode.compat.mjs +0 -2
- package/dist/export-mocks/cache/index.mjs +0 -10
- package/dist/export-mocks/headers/index.mjs +0 -12
- package/dist/export-mocks/index.d.ts +0 -7
- package/dist/export-mocks/index.mjs +0 -11
- package/dist/export-mocks/navigation/index.mjs +0 -11
- package/dist/export-mocks/router/index.mjs +0 -10
- package/dist/font/webpack/loader/storybook-nextjs-font-loader.d.ts +0 -3
- package/dist/font/webpack/loader/storybook-nextjs-font-loader.mjs +0 -56
- package/dist/image-context.d.ts +0 -13
- package/dist/image-context.mjs +0 -6
- package/dist/images/decorator.d.ts +0 -6
- package/dist/images/decorator.js +0 -1
- package/dist/images/decorator.mjs +0 -2
- package/dist/images/next-image.d.ts +0 -28
- package/dist/images/next-image.mjs +0 -9
- package/dist/images/next-legacy-image.d.ts +0 -6
- package/dist/images/next-legacy-image.mjs +0 -9
- package/dist/index.d-ff220430.d.ts +0 -310
- package/dist/index.mjs +0 -58
- package/dist/next-image-loader-stub.d.ts +0 -10
- package/dist/next-image-loader-stub.mjs +0 -7
- package/dist/node/index.mjs +0 -5
- package/dist/preset.d.ts +0 -14
- package/dist/preview.mjs +0 -3
- package/dist/react-18-WSPZ3BUV.mjs +0 -7
- package/dist/rsc/server-only.d.ts +0 -3
- package/dist/rsc/server-only.mjs +0 -5
- package/dist/swc/next-swc-loader-patch.d.ts +0 -21
- package/dist/swc/next-swc-loader-patch.mjs +0 -8
- package/dist/types-f6ea2c09.d.ts +0 -54
package/dist/chunk-2TZKD6A5.mjs
DELETED
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
import { ImageDecorator } from './chunk-NQ32RFK2.mjs';
|
|
2
|
-
import { __export } from './chunk-L66KIASX.mjs';
|
|
3
|
-
import { createNavigation, getRouter } from '@storybook/nextjs/navigation.mock';
|
|
4
|
-
import { createRouter, getRouter as getRouter$1 } from '@storybook/nextjs/router.mock';
|
|
5
|
-
import { isNextRouterError } from 'next/dist/client/components/is-next-router-error';
|
|
6
|
-
import { setConfig } from 'next/config';
|
|
7
|
-
import * as React3 from 'react';
|
|
8
|
-
import React3__default, { useMemo } from 'react';
|
|
9
|
-
import initHeadManager from 'next/dist/client/head-manager';
|
|
10
|
-
import { HeadManagerContext } from 'next/dist/shared/lib/head-manager-context.shared-runtime';
|
|
11
|
-
import { RedirectBoundary } from 'next/dist/client/components/redirect-boundary';
|
|
12
|
-
import { GlobalLayoutRouterContext, AppRouterContext, LayoutRouterContext } from 'next/dist/shared/lib/app-router-context.shared-runtime';
|
|
13
|
-
import { PathParamsContext, PathnameContext, SearchParamsContext } from 'next/dist/shared/lib/hooks-client-context.shared-runtime';
|
|
14
|
-
import 'next/dist/shared/lib/segment';
|
|
15
|
-
import { RouterContext } from 'next/dist/shared/lib/router-context.shared-runtime';
|
|
16
|
-
import { StyleRegistry } from 'styled-jsx';
|
|
17
|
-
|
|
18
|
-
var preview_exports={};__export(preview_exports,{decorators:()=>decorators,loaders:()=>loaders,parameters:()=>parameters});setConfig(process.env.__NEXT_RUNTIME_CONFIG);var HeadManagerProvider=({children})=>{let headManager=useMemo(initHeadManager,[]);return headManager.getIsSsr=()=>!1,React3__default.createElement(HeadManagerContext.Provider,{value:headManager},children)},head_manager_provider_default=HeadManagerProvider;var HeadManagerDecorator=Story=>React3.createElement(head_manager_provider_default,null,React3.createElement(Story,null));var getParallelRoutes=segmentsList=>{let segment=segmentsList.shift();return segment?[segment,{children:getParallelRoutes(segmentsList)}]:[]},AppRouterProvider=({children,routeParams})=>{let{pathname,query,segments=[]}=routeParams,tree=[pathname,{children:getParallelRoutes([...segments])}],pathParams=useMemo(()=>{let params={},currentSegments=routeParams.segments;if(currentSegments){if(Array.isArray(currentSegments)){for(let segmentEntry of currentSegments)if(Array.isArray(segmentEntry)&&segmentEntry.length===2&&typeof segmentEntry[0]=="string"){let key=segmentEntry[0],value=segmentEntry[1];params[key]=value;}}else if(typeof currentSegments=="object"&&!Array.isArray(currentSegments)){let segmentObject=currentSegments;for(let key in segmentObject)Object.prototype.hasOwnProperty.call(segmentObject,key)&&(params[key]=segmentObject[key]);}}return params},[routeParams.segments]),newLazyCacheNode={lazyData:null,rsc:null,prefetchRsc:null,head:null,prefetchHead:null,parallelRoutes:new Map,loading:null};return React3__default.createElement(PathParamsContext.Provider,{value:pathParams},React3__default.createElement(PathnameContext.Provider,{value:pathname},React3__default.createElement(SearchParamsContext.Provider,{value:new URLSearchParams(query)},React3__default.createElement(GlobalLayoutRouterContext.Provider,{value:{changeByServerResponse(){},buildId:"storybook",tree,focusAndScrollRef:{apply:!1,hashFragment:null,segmentPaths:[tree],onlyHashChange:!1},nextUrl:pathname}},React3__default.createElement(AppRouterContext.Provider,{value:getRouter()},React3__default.createElement(LayoutRouterContext.Provider,{value:{childNodes:new Map,tree,parentTree:tree,parentCacheNode:newLazyCacheNode,url:pathname,loading:null}},children))))))};var PageRouterProvider=({children})=>React3__default.createElement(RouterContext.Provider,{value:getRouter$1()},children);var defaultRouterParams={pathname:"/",query:{}},RouterDecorator=(Story,{parameters:parameters2})=>parameters2.nextjs?.appDirectory??!1?AppRouterProvider?React3.createElement(AppRouterProvider,{routeParams:{...defaultRouterParams,...parameters2.nextjs?.navigation}},React3.createElement(RedirectBoundary,null,React3.createElement(Story,null))):null:React3.createElement(PageRouterProvider,null,React3.createElement(Story,null));var StyledJsxDecorator=Story=>React3.createElement(StyleRegistry,null,React3.createElement(Story,null));function addNextHeadCount(){let meta=document.createElement("meta");meta.name="next-head-count",meta.content="0",document.head.appendChild(meta);}function isAsyncClientComponentError(error){return typeof error=="string"&&(error.includes("Only Server Components can be async at the moment.")||error.includes("A component was suspended by an uncached promise.")||error.includes("async/await is not yet supported in Client Components"))}addNextHeadCount();var origConsoleError=globalThis.console.error;globalThis.console.error=(...args)=>{let error=args[0];isNextRouterError(error)||isAsyncClientComponentError(error)||origConsoleError.apply(globalThis.console,args);};globalThis.addEventListener("error",ev=>{if(isNextRouterError(ev.error)||isAsyncClientComponentError(ev.error)){ev.preventDefault();return}});var decorators=[StyledJsxDecorator,ImageDecorator,RouterDecorator,HeadManagerDecorator],loaders=async({globals,parameters:parameters2})=>{let{router,appDirectory}=parameters2.nextjs??{};appDirectory?createNavigation(router):createRouter({locale:globals.locale,...router});},parameters={docs:{source:{excludeDecorators:!0}},react:{rootOptions:{onCaughtError(error){isNextRouterError(error)||console.error(error);}}}};
|
|
19
|
-
|
|
20
|
-
export { decorators, loaders, parameters, preview_exports };
|
package/dist/chunk-ETFXNGLC.mjs
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
var defaultLoader=({src,width,quality=75})=>{let missingValues=[];if(src||missingValues.push("src"),width||missingValues.push("width"),missingValues.length>0)throw new Error(`Next Image Optimization requires ${missingValues.join(", ")} to be provided. Make sure you pass them as props to the \`next/image\` component. Received: ${JSON.stringify({src,width,quality})}`);let url=new URL(src,window.location.href);return !url.searchParams.has("w")&&!url.searchParams.has("q")&&(url.searchParams.set("w",width.toString()),url.searchParams.set("q",quality.toString())),!src.startsWith("http://")&&!src.startsWith("https://")?url.toString().slice(url.origin.length):url.toString()};
|
|
2
|
-
|
|
3
|
-
export { defaultLoader };
|
package/dist/chunk-L66KIASX.mjs
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
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 __esm=(fn,res)=>function(){return fn&&(res=(0, fn[__getOwnPropNames(fn)[0]])(fn=0)),res};var __commonJS=(cb,mod)=>function(){return mod||(0, cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0});},__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)),__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);
|
|
2
|
-
|
|
3
|
-
export { __commonJS, __esm, __export, __require, __toCommonJS, __toESM };
|
package/dist/chunk-NQ32RFK2.mjs
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import * as React from 'react';
|
|
2
|
-
import { ImageContext as ImageContext$1 } from '@storybook/nextjs/dist/image-context';
|
|
3
|
-
|
|
4
|
-
var ImageContext=ImageContext$1,ImageDecorator=(Story,{parameters})=>parameters.nextjs?.image?React.createElement(ImageContext.Provider,{value:parameters.nextjs.image},React.createElement(Story,null)):React.createElement(Story,null);
|
|
5
|
-
|
|
6
|
-
export { ImageDecorator };
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export { draftMode } from 'next/dist/client/components/headers';
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import '../../chunk-L66KIASX.mjs';
|
|
2
|
-
import { unstable_cache } from 'next/dist/server/web/spec-extension/unstable-cache';
|
|
3
|
-
export { unstable_cache } from 'next/dist/server/web/spec-extension/unstable-cache';
|
|
4
|
-
import { unstable_noStore } from 'next/dist/server/web/spec-extension/unstable-no-store';
|
|
5
|
-
export { unstable_noStore } from 'next/dist/server/web/spec-extension/unstable-no-store';
|
|
6
|
-
import { fn } from 'storybook/test';
|
|
7
|
-
|
|
8
|
-
var revalidatePath=fn().mockName("next/cache::revalidatePath"),revalidateTag=fn().mockName("next/cache::revalidateTag"),cacheExports={unstable_cache,revalidateTag,revalidatePath,unstable_noStore},cache_default=cacheExports;
|
|
9
|
-
|
|
10
|
-
export { cache_default as default, revalidatePath, revalidateTag };
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
import '../../chunk-L66KIASX.mjs';
|
|
2
|
-
import { draftMode } from 'next/dist/server/request/draft-mode';
|
|
3
|
-
import * as headers3 from 'next/dist/server/request/headers';
|
|
4
|
-
export * from 'next/dist/server/request/headers';
|
|
5
|
-
import { fn } from 'storybook/test';
|
|
6
|
-
import { HeadersAdapter } from 'next/dist/server/web/spec-extension/adapters/headers';
|
|
7
|
-
import { headers as headers$1 } from '@storybook/nextjs/headers.mock';
|
|
8
|
-
import { RequestCookies } from 'next/dist/compiled/@edge-runtime/cookies';
|
|
9
|
-
|
|
10
|
-
var HeadersAdapterMock=class extends HeadersAdapter{constructor(){super({});this.append=fn(super.append.bind(this)).mockName("next/headers::headers().append");this.delete=fn(super.delete.bind(this)).mockName("next/headers::headers().delete");this.get=fn(super.get.bind(this)).mockName("next/headers::headers().get");this.has=fn(super.has.bind(this)).mockName("next/headers::headers().has");this.set=fn(super.set.bind(this)).mockName("next/headers::headers().set");this.forEach=fn(super.forEach.bind(this)).mockName("next/headers::headers().forEach");this.entries=fn(super.entries.bind(this)).mockName("next/headers::headers().entries");this.keys=fn(super.keys.bind(this)).mockName("next/headers::headers().keys");this.values=fn(super.values.bind(this)).mockName("next/headers::headers().values");}},headersAdapterMock,headers=()=>(headersAdapterMock||(headersAdapterMock=new HeadersAdapterMock),headersAdapterMock);headers.mockRestore=()=>{headersAdapterMock=new HeadersAdapterMock;};var RequestCookiesMock=class extends RequestCookies{constructor(){super(...arguments);this.get=fn(super.get.bind(this)).mockName("next/headers::cookies().get");this.getAll=fn(super.getAll.bind(this)).mockName("next/headers::cookies().getAll");this.has=fn(super.has.bind(this)).mockName("next/headers::cookies().has");this.set=fn(super.set.bind(this)).mockName("next/headers::cookies().set");this.delete=fn(super.delete.bind(this)).mockName("next/headers::cookies().delete");}},requestCookiesMock,cookies=fn(()=>(requestCookiesMock||(requestCookiesMock=new RequestCookiesMock(headers$1())),requestCookiesMock)).mockName("next/headers::cookies()"),originalRestore=cookies.mockRestore.bind(null);cookies.mockRestore=()=>{originalRestore(),headers$1.mockRestore(),requestCookiesMock=new RequestCookiesMock(headers$1());};var draftMode2=fn(draftMode??headers3.draftMode).mockName("draftMode");
|
|
11
|
-
|
|
12
|
-
export { cookies, draftMode2 as draftMode, headers };
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import { __require } from '../chunk-L66KIASX.mjs';
|
|
2
|
-
import { dirname, sep, join } from 'node:path';
|
|
3
|
-
import semver from 'semver';
|
|
4
|
-
import 'storybook/internal/common';
|
|
5
|
-
import 'next/constants';
|
|
6
|
-
import 'next/dist/server/config';
|
|
7
|
-
import 'webpack';
|
|
8
|
-
|
|
9
|
-
var getNextjsVersion=()=>__require(scopedResolve("next/package.json")).version;var scopedResolve=id=>{let scopedModulePath=__require.resolve(id),idWithNativePathSep=id.replace(/\//g,sep);if(scopedModulePath.endsWith(idWithNativePathSep))return scopedModulePath;let beginningOfMainScriptPath=scopedModulePath.lastIndexOf(idWithNativePathSep)+id.length;return scopedModulePath.substring(0,beginningOfMainScriptPath)};var mapping={"<15.0.0":{"next/dist/server/request/headers":"next/dist/client/components/headers","next/dist/server/request/draft-mode":"@storybook/nextjs/dist/compatibility/draft-mode.compat"}},getCompatibilityAliases=()=>{let version=getNextjsVersion(),result={};return Object.keys(mapping).forEach(key=>{semver.intersects(version,key)&&Object.assign(result,mapping[key]);}),result};var mapping2={"next/headers":"/dist/export-mocks/headers/index","@storybook/nextjs/headers.mock":"/dist/export-mocks/headers/index","next/navigation":"/dist/export-mocks/navigation/index","@storybook/nextjs/navigation.mock":"/dist/export-mocks/navigation/index","next/router":"/dist/export-mocks/router/index","@storybook/nextjs/router.mock":"/dist/export-mocks/router/index","next/cache":"/dist/export-mocks/cache/index","@storybook/nextjs/cache.mock":"/dist/export-mocks/cache/index",...getCompatibilityAliases()},getPackageAliases=({useESM=!1}={})=>{let extension=useESM?"mjs":"js",packageLocation=dirname(__require.resolve("@storybook/nextjs/package.json")),getFullPath=path=>path.startsWith("next")?path:join(packageLocation,path.replace("@storybook/nextjs",""));return Object.fromEntries(Object.entries(mapping2).map(([originalPath,aliasedPath])=>[originalPath,typeof aliasedPath=="string"?getFullPath(`${aliasedPath}.${extension}`):aliasedPath]))};
|
|
10
|
-
|
|
11
|
-
export { getPackageAliases };
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import '../../chunk-L66KIASX.mjs';
|
|
2
|
-
import { NextjsRouterMocksNotAvailable } from 'storybook/internal/preview-errors';
|
|
3
|
-
import * as actual from 'next/dist/client/components/navigation';
|
|
4
|
-
export * from 'next/dist/client/components/navigation';
|
|
5
|
-
import { getRedirectError } from 'next/dist/client/components/redirect';
|
|
6
|
-
import { RedirectStatusCode } from 'next/dist/client/components/redirect-status-code';
|
|
7
|
-
import { fn } from 'storybook/test';
|
|
8
|
-
|
|
9
|
-
var navigationAPI,createNavigation=overrides=>{let navigationActions={push:fn().mockName("next/navigation::useRouter().push"),replace:fn().mockName("next/navigation::useRouter().replace"),forward:fn().mockName("next/navigation::useRouter().forward"),back:fn().mockName("next/navigation::useRouter().back"),prefetch:fn().mockName("next/navigation::useRouter().prefetch"),refresh:fn().mockName("next/navigation::useRouter().refresh")};return overrides&&Object.keys(navigationActions).forEach(key=>{key in overrides&&(navigationActions[key]=fn((...args)=>overrides[key](...args)).mockName(`useRouter().${key}`));}),navigationAPI=navigationActions,navigationAPI},getRouter=()=>{if(!navigationAPI)throw new NextjsRouterMocksNotAvailable({importType:"next/navigation"});return navigationAPI},redirect=fn((url,type=actual.RedirectType.push)=>{throw getRedirectError(url,type,RedirectStatusCode.SeeOther)}).mockName("next/navigation::redirect"),permanentRedirect=fn((url,type=actual.RedirectType.push)=>{throw getRedirectError(url,type,RedirectStatusCode.SeeOther)}).mockName("next/navigation::permanentRedirect"),useSearchParams2=fn(actual.useSearchParams).mockName("next/navigation::useSearchParams"),usePathname2=fn(actual.usePathname).mockName("next/navigation::usePathname"),useSelectedLayoutSegment2=fn(actual.useSelectedLayoutSegment).mockName("next/navigation::useSelectedLayoutSegment"),useSelectedLayoutSegments2=fn(actual.useSelectedLayoutSegments).mockName("next/navigation::useSelectedLayoutSegments"),useRouter2=fn(actual.useRouter).mockName("next/navigation::useRouter"),useServerInsertedHTML2=fn(actual.useServerInsertedHTML).mockName("next/navigation::useServerInsertedHTML"),notFound2=fn(actual.notFound).mockName("next/navigation::notFound"),useParams2=fn(actual.useParams).mockName("next/navigation::useParams");
|
|
10
|
-
|
|
11
|
-
export { createNavigation, getRouter, notFound2 as notFound, permanentRedirect, redirect, useParams2 as useParams, usePathname2 as usePathname, useRouter2 as useRouter, useSearchParams2 as useSearchParams, useSelectedLayoutSegment2 as useSelectedLayoutSegment, useSelectedLayoutSegments2 as useSelectedLayoutSegments, useServerInsertedHTML2 as useServerInsertedHTML };
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import '../../chunk-L66KIASX.mjs';
|
|
2
|
-
import { NextjsRouterMocksNotAvailable } from 'storybook/internal/preview-errors';
|
|
3
|
-
import * as singletonRouter from 'next/dist/client/router';
|
|
4
|
-
import singletonRouter__default from 'next/dist/client/router';
|
|
5
|
-
export * from 'next/dist/client/router';
|
|
6
|
-
import { fn } from 'storybook/test';
|
|
7
|
-
|
|
8
|
-
var defaultRouterState={route:"/",asPath:"/",basePath:"/",pathname:"/",query:{},isFallback:!1,isLocaleDomain:!1,isReady:!0,isPreview:!1},routerAPI,createRouter=overrides=>{let routerActions={push:fn((..._args)=>Promise.resolve(!0)).mockName("next/router::useRouter().push"),replace:fn((..._args)=>Promise.resolve(!0)).mockName("next/router::useRouter().replace"),reload:fn((..._args)=>{}).mockName("next/router::useRouter().reload"),back:fn((..._args)=>{}).mockName("next/router::useRouter().back"),forward:fn(()=>{}).mockName("next/router::useRouter().forward"),prefetch:fn((..._args)=>Promise.resolve()).mockName("next/router::useRouter().prefetch"),beforePopState:fn((..._args)=>{}).mockName("next/router::useRouter().beforePopState")},routerEvents={on:fn((..._args)=>{}).mockName("next/router::useRouter().events.on"),off:fn((..._args)=>{}).mockName("next/router::useRouter().events.off"),emit:fn((..._args)=>{}).mockName("next/router::useRouter().events.emit")};return overrides&&Object.keys(routerActions).forEach(key=>{key in overrides&&(routerActions[key]=fn((...args)=>overrides[key](...args)).mockName(`useRouter().${key}`));}),overrides?.events&&Object.keys(routerEvents).forEach(key=>{key in routerEvents&&(routerEvents[key]=fn((...args)=>overrides.events[key](...args)).mockName(`useRouter().events.${key}`));}),routerAPI={...defaultRouterState,...overrides,...routerActions,events:routerEvents},singletonRouter__default.router=routerAPI,singletonRouter__default.readyCallbacks.forEach(cb=>cb()),singletonRouter__default.readyCallbacks=[],routerAPI},getRouter=()=>{if(!routerAPI)throw new NextjsRouterMocksNotAvailable({importType:"next/router"});return routerAPI},router_default=singletonRouter__default,useRouter2=fn(singletonRouter.useRouter).mockName("next/router::useRouter"),withRouter2=fn(singletonRouter.withRouter).mockName("next/router::withRouter");
|
|
9
|
-
|
|
10
|
-
export { createRouter, router_default as default, getRouter, useRouter2 as useRouter, withRouter2 as withRouter };
|
|
@@ -1,56 +0,0 @@
|
|
|
1
|
-
import '../../../chunk-L66KIASX.mjs';
|
|
2
|
-
import { dirname, join, sep } from 'node:path';
|
|
3
|
-
import { GoogleFontsDownloadError, GoogleFontsLoadingError } from 'storybook/internal/server-errors';
|
|
4
|
-
import { fetchCSSFromGoogleFonts } from 'next/dist/compiled/@next/font/dist/google/fetch-css-from-google-fonts';
|
|
5
|
-
import { getFontAxes } from 'next/dist/compiled/@next/font/dist/google/get-font-axes';
|
|
6
|
-
import { getGoogleFontsUrl } from 'next/dist/compiled/@next/font/dist/google/get-google-fonts-url';
|
|
7
|
-
import { validateGoogleFontFunctionCall } from 'next/dist/compiled/@next/font/dist/google/validate-google-font-function-call';
|
|
8
|
-
import loaderUtils from 'next/dist/compiled/loader-utils3';
|
|
9
|
-
import { getProjectRoot } from 'storybook/internal/common';
|
|
10
|
-
import { validateLocalFontFunctionCall } from 'next/dist/compiled/@next/font/dist/local/validate-local-font-function-call';
|
|
11
|
-
|
|
12
|
-
var cssCache=new Map;async function getFontFaceDeclarations(options){let{fontFamily,weights,styles,selectedVariableAxes,display,variable}=validateGoogleFontFunctionCall(options.fontFamily,options.props),fontAxes=getFontAxes(fontFamily,weights,styles,selectedVariableAxes),url=getGoogleFontsUrl(fontFamily,fontAxes,display);try{let hasCachedCSS=cssCache.has(url),fontFaceCSS=hasCachedCSS?cssCache.get(url):await fetchCSSFromGoogleFonts(url,fontFamily,!0).catch(()=>null);if(hasCachedCSS?cssCache.delete(url):cssCache.set(url,fontFaceCSS),fontFaceCSS===null)throw new GoogleFontsDownloadError({fontFamily,url});return {id:loaderUtils.getHashDigest(url,"md5","hex",6),fontFamily,fontFaceCSS,weights,styles,variable}}catch(error){throw new GoogleFontsLoadingError({error,url})}}async function getFontFaceDeclarations2(options,rootContext,swcMode){let localFontSrc=options.props.src,parentFolder=swcMode?dirname(join(getProjectRoot(),options.filename)).replace(rootContext,""):dirname(options.filename).replace(rootContext,""),{weight,style,variable,declarations=[]}=validateLocalFontFunctionCall("",options.props),id=`font-${loaderUtils.getHashDigest(Buffer.from(JSON.stringify(localFontSrc)),"md5","hex",6)}`,fontDeclarations=declarations.map(({prop,value})=>`${prop}: ${value};`).join(`
|
|
13
|
-
`);return {id,fontFamily:id,fontFaceCSS:(()=>{if(typeof localFontSrc=="string"){let localFontPath=join(parentFolder,localFontSrc).replaceAll("\\","/");return `@font-face {
|
|
14
|
-
font-family: ${id};
|
|
15
|
-
src: url(.${localFontPath});
|
|
16
|
-
${fontDeclarations}
|
|
17
|
-
}`}return localFontSrc.map(font=>{let localFontPath=join(parentFolder,font.path).replaceAll("\\","/");return `@font-face {
|
|
18
|
-
font-family: ${id};
|
|
19
|
-
src: url(.${localFontPath});
|
|
20
|
-
${font.weight?`font-weight: ${font.weight};`:""}
|
|
21
|
-
${font.style?`font-style: ${font.style};`:""}
|
|
22
|
-
${fontDeclarations}
|
|
23
|
-
}`}).join("")})(),weights:weight?[weight]:[],styles:style?[style]:[],variable}}function getCSSMeta(options){let className=getClassName(options),style=getStylesObj(options),variableClassName=`__variable_${className}`,classNamesCSS=`
|
|
24
|
-
.${className} {
|
|
25
|
-
font-family: ${options.fontFamily};
|
|
26
|
-
${isNextCSSPropertyValid(options.styles)?`font-style: ${options.styles[0]};`:""}
|
|
27
|
-
${isNextCSSPropertyValid(options.weights)?`font-weight: ${options.weights[0]};`:""}
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
${options.variable?`.${variableClassName} { ${options.variable}: '${options.fontFamily}'; }`:""}
|
|
31
|
-
`,fontFaceCSS=`${changeFontDisplayToSwap(options.fontFaceCSS)}`;return {className,fontFaceCSS,classNamesCSS,style,...options.variable?{variableClassName}:{}}}function getClassName({styles,weights,fontFamily}){let font=fontFamily.replaceAll(" ","-").toLowerCase(),style=isNextCSSPropertyValid(styles)?styles[0]:null,weight=isNextCSSPropertyValid(weights)?weights[0]:null;return `${font}${style?`-${style}`:""}${weight?`-${weight}`:""}`}function getStylesObj({styles,weights,fontFamily}){return {fontFamily,...isNextCSSPropertyValid(styles)?{fontStyle:styles[0]}:{},...isNextCSSPropertyValid(weights)?{fontWeight:weights[0]}:{}}}function isNextCSSPropertyValid(prop){return prop.length===1&&prop[0]!=="variable"}function changeFontDisplayToSwap(css){return css.replaceAll("font-display: optional;","font-display: block;")}function setFontDeclarationsInHead({id,fontFaceCSS,classNamesCSS}){return `
|
|
32
|
-
if (!document.getElementById('id-${id}')) {
|
|
33
|
-
const fontDeclarations = \`${fontFaceCSS}\`;
|
|
34
|
-
const style = document.createElement('style');
|
|
35
|
-
style.setAttribute('id', 'font-face-${id}');
|
|
36
|
-
style.innerHTML = fontDeclarations;
|
|
37
|
-
document.head.appendChild(style);
|
|
38
|
-
|
|
39
|
-
const classNamesCSS = \`${classNamesCSS}\`;
|
|
40
|
-
const classNamesStyle = document.createElement('style');
|
|
41
|
-
classNamesStyle.setAttribute('id', 'classnames-${id}');
|
|
42
|
-
classNamesStyle.innerHTML = classNamesCSS;
|
|
43
|
-
document.head.appendChild(classNamesStyle);
|
|
44
|
-
|
|
45
|
-
}
|
|
46
|
-
`}async function storybookNextjsFontLoader(){let loaderOptions=this.getOptions(),swcMode=!1,options;if(Object.keys(loaderOptions).length>0)options=loaderOptions;else {let importQuery=JSON.parse(this.resourceQuery.slice(1));swcMode=!0,options={filename:importQuery.path,fontFamily:importQuery.import,props:importQuery.arguments[0],source:this.context.replace(this.rootContext,"")};}let rootCtx=this.rootContext,fontFaceDeclaration,pathSep=sep;if((options.source.endsWith(`next${pathSep}font${pathSep}google`)||options.source.endsWith(`@next${pathSep}font${pathSep}google`))&&(fontFaceDeclaration=await getFontFaceDeclarations(options)),(options.source.endsWith(`next${pathSep}font${pathSep}local`)||options.source.endsWith(`@next${pathSep}font${pathSep}local`))&&(fontFaceDeclaration=await getFontFaceDeclarations2(options,rootCtx,swcMode)),typeof fontFaceDeclaration<"u"){let cssMeta=getCSSMeta(fontFaceDeclaration);return `
|
|
47
|
-
${setFontDeclarationsInHead({fontFaceCSS:cssMeta.fontFaceCSS,id:fontFaceDeclaration.id,classNamesCSS:cssMeta.classNamesCSS})}
|
|
48
|
-
|
|
49
|
-
module.exports = {
|
|
50
|
-
className: "${cssMeta.className}",
|
|
51
|
-
style: ${JSON.stringify(cssMeta.style)}
|
|
52
|
-
${cssMeta.variableClassName?`, variable: "${cssMeta.variableClassName}"`:""}
|
|
53
|
-
}
|
|
54
|
-
`}return "module.exports = {}"}
|
|
55
|
-
|
|
56
|
-
export { storybookNextjsFontLoader as default };
|
package/dist/image-context.d.ts
DELETED
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
import * as React from 'react';
|
|
2
|
-
import { ImageProps, StaticImageData } from 'next/image';
|
|
3
|
-
import { ImageProps as ImageProps$1 } from 'next/legacy/image';
|
|
4
|
-
|
|
5
|
-
interface StaticRequire {
|
|
6
|
-
default: StaticImageData;
|
|
7
|
-
}
|
|
8
|
-
declare type StaticImport = StaticRequire | StaticImageData;
|
|
9
|
-
declare const ImageContext: React.Context<Partial<Omit<ImageProps, "src"> & {
|
|
10
|
-
src: string | StaticImport;
|
|
11
|
-
}> & Omit<ImageProps$1, "src">>;
|
|
12
|
-
|
|
13
|
-
export { ImageContext };
|
package/dist/image-context.mjs
DELETED
package/dist/images/decorator.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";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 __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__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)),__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var decorator_exports={};__export(decorator_exports,{ImageDecorator:()=>ImageDecorator});module.exports=__toCommonJS(decorator_exports);var React=__toESM(require("react")),import_image_context=require("@storybook/nextjs/dist/image-context"),ImageContext=import_image_context.ImageContext,ImageDecorator=(Story,{parameters})=>parameters.nextjs?.image?React.createElement(ImageContext.Provider,{value:parameters.nextjs.image},React.createElement(Story,null)):React.createElement(Story,null);0&&(module.exports={ImageDecorator});
|
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
import * as next_dist_shared_lib_get_img_props from 'next/dist/shared/lib/get-img-props';
|
|
2
|
-
import React__default from 'react';
|
|
3
|
-
import * as _NextImage from 'next/image';
|
|
4
|
-
|
|
5
|
-
declare const MockedNextImage: React__default.ForwardRefExoticComponent<Omit<React__default.DetailedHTMLProps<React__default.ImgHTMLAttributes<HTMLImageElement>, HTMLImageElement>, "src" | "srcSet" | "ref" | "alt" | "width" | "height" | "loading"> & {
|
|
6
|
-
src: string | next_dist_shared_lib_get_img_props.StaticImport;
|
|
7
|
-
alt: string;
|
|
8
|
-
width?: number | `${number}`;
|
|
9
|
-
height?: number | `${number}`;
|
|
10
|
-
fill?: boolean;
|
|
11
|
-
loader?: _NextImage.ImageLoader;
|
|
12
|
-
quality?: number | `${number}`;
|
|
13
|
-
priority?: boolean;
|
|
14
|
-
loading?: "lazy" | "eager" | undefined;
|
|
15
|
-
placeholder?: next_dist_shared_lib_get_img_props.PlaceholderValue;
|
|
16
|
-
blurDataURL?: string;
|
|
17
|
-
unoptimized?: boolean;
|
|
18
|
-
overrideSrc?: string;
|
|
19
|
-
onLoadingComplete?: next_dist_shared_lib_get_img_props.OnLoadingComplete;
|
|
20
|
-
layout?: string;
|
|
21
|
-
objectFit?: string;
|
|
22
|
-
objectPosition?: string;
|
|
23
|
-
lazyBoundary?: string;
|
|
24
|
-
lazyRoot?: string;
|
|
25
|
-
} & React__default.RefAttributes<HTMLImageElement>>;
|
|
26
|
-
declare const getImageProps: (props: _NextImage.ImageProps) => any;
|
|
27
|
-
|
|
28
|
-
export { MockedNextImage as default, getImageProps };
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import { defaultLoader } from '../chunk-ETFXNGLC.mjs';
|
|
2
|
-
import '../chunk-L66KIASX.mjs';
|
|
3
|
-
import React from 'react';
|
|
4
|
-
import { ImageContext as ImageContext$1 } from '@storybook/nextjs/dist/image-context';
|
|
5
|
-
import * as NextImageNamespace from 'sb-original/next/image';
|
|
6
|
-
|
|
7
|
-
var OriginalNextImage=NextImageNamespace.default,{getImageProps:originalGetImageProps}=NextImageNamespace,ImageContext=ImageContext$1,MockedNextImage=React.forwardRef(({loader,...props},ref)=>{let imageParameters=React.useContext(ImageContext);return React.createElement(OriginalNextImage,{ref,...imageParameters,...props,loader:loader??defaultLoader})});MockedNextImage.displayName="NextImage";var getImageProps=props=>originalGetImageProps?.({loader:defaultLoader,...props}),next_image_default=MockedNextImage;
|
|
8
|
-
|
|
9
|
-
export { next_image_default as default, getImageProps };
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import { defaultLoader } from '../chunk-ETFXNGLC.mjs';
|
|
2
|
-
import '../chunk-L66KIASX.mjs';
|
|
3
|
-
import React from 'react';
|
|
4
|
-
import { ImageContext as ImageContext$1 } from '@storybook/nextjs/dist/image-context';
|
|
5
|
-
import OriginalNextLegacyImage from 'sb-original/next/legacy/image';
|
|
6
|
-
|
|
7
|
-
var ImageContext=ImageContext$1;function NextLegacyImage({loader,...props}){let imageParameters=React.useContext(ImageContext);return React.createElement(OriginalNextLegacyImage,{...imageParameters,...props,loader:loader??defaultLoader})}var next_legacy_image_default=NextLegacyImage;
|
|
8
|
-
|
|
9
|
-
export { next_legacy_image_default as default };
|
|
@@ -1,310 +0,0 @@
|
|
|
1
|
-
interface MockResultReturn<T> {
|
|
2
|
-
type: "return";
|
|
3
|
-
/**
|
|
4
|
-
* The value that was returned from the function. If function returned a Promise, then this will be a resolved value.
|
|
5
|
-
*/
|
|
6
|
-
value: T;
|
|
7
|
-
}
|
|
8
|
-
interface MockResultIncomplete {
|
|
9
|
-
type: "incomplete";
|
|
10
|
-
value: undefined;
|
|
11
|
-
}
|
|
12
|
-
interface MockResultThrow {
|
|
13
|
-
type: "throw";
|
|
14
|
-
/**
|
|
15
|
-
* An error that was thrown during function execution.
|
|
16
|
-
*/
|
|
17
|
-
value: any;
|
|
18
|
-
}
|
|
19
|
-
interface MockSettledResultFulfilled<T> {
|
|
20
|
-
type: "fulfilled";
|
|
21
|
-
value: T;
|
|
22
|
-
}
|
|
23
|
-
interface MockSettledResultRejected {
|
|
24
|
-
type: "rejected";
|
|
25
|
-
value: any;
|
|
26
|
-
}
|
|
27
|
-
type MockResult<T> = MockResultReturn<T> | MockResultThrow | MockResultIncomplete;
|
|
28
|
-
type MockSettledResult<T> = MockSettledResultFulfilled<T> | MockSettledResultRejected;
|
|
29
|
-
interface MockContext<T extends Procedure> {
|
|
30
|
-
/**
|
|
31
|
-
* This is an array containing all arguments for each call. One item of the array is the arguments of that call.
|
|
32
|
-
*
|
|
33
|
-
* @see https://vitest.dev/api/mock#mock-calls
|
|
34
|
-
* @example
|
|
35
|
-
* const fn = vi.fn()
|
|
36
|
-
*
|
|
37
|
-
* fn('arg1', 'arg2')
|
|
38
|
-
* fn('arg3')
|
|
39
|
-
*
|
|
40
|
-
* fn.mock.calls === [
|
|
41
|
-
* ['arg1', 'arg2'], // first call
|
|
42
|
-
* ['arg3'], // second call
|
|
43
|
-
* ]
|
|
44
|
-
*/
|
|
45
|
-
calls: Parameters<T>[];
|
|
46
|
-
/**
|
|
47
|
-
* This is an array containing all instances that were instantiated when mock was called with a `new` keyword. Note that this is an actual context (`this`) of the function, not a return value.
|
|
48
|
-
* @see https://vitest.dev/api/mock#mock-instances
|
|
49
|
-
*/
|
|
50
|
-
instances: ReturnType<T>[];
|
|
51
|
-
/**
|
|
52
|
-
* An array of `this` values that were used during each call to the mock function.
|
|
53
|
-
* @see https://vitest.dev/api/mock#mock-contexts
|
|
54
|
-
*/
|
|
55
|
-
contexts: ThisParameterType<T>[];
|
|
56
|
-
/**
|
|
57
|
-
* The order of mock's execution. This returns an array of numbers which are shared between all defined mocks.
|
|
58
|
-
*
|
|
59
|
-
* @see https://vitest.dev/api/mock#mock-invocationcallorder
|
|
60
|
-
* @example
|
|
61
|
-
* const fn1 = vi.fn()
|
|
62
|
-
* const fn2 = vi.fn()
|
|
63
|
-
*
|
|
64
|
-
* fn1()
|
|
65
|
-
* fn2()
|
|
66
|
-
* fn1()
|
|
67
|
-
*
|
|
68
|
-
* fn1.mock.invocationCallOrder === [1, 3]
|
|
69
|
-
* fn2.mock.invocationCallOrder === [2]
|
|
70
|
-
*/
|
|
71
|
-
invocationCallOrder: number[];
|
|
72
|
-
/**
|
|
73
|
-
* This is an array containing all values that were `returned` from the function.
|
|
74
|
-
*
|
|
75
|
-
* The `value` property contains the returned value or thrown error. If the function returned a `Promise`, then `result` will always be `'return'` even if the promise was rejected.
|
|
76
|
-
*
|
|
77
|
-
* @see https://vitest.dev/api/mock#mock-results
|
|
78
|
-
* @example
|
|
79
|
-
* const fn = vi.fn()
|
|
80
|
-
* .mockReturnValueOnce('result')
|
|
81
|
-
* .mockImplementationOnce(() => { throw new Error('thrown error') })
|
|
82
|
-
*
|
|
83
|
-
* const result = fn()
|
|
84
|
-
*
|
|
85
|
-
* try {
|
|
86
|
-
* fn()
|
|
87
|
-
* }
|
|
88
|
-
* catch {}
|
|
89
|
-
*
|
|
90
|
-
* fn.mock.results === [
|
|
91
|
-
* {
|
|
92
|
-
* type: 'return',
|
|
93
|
-
* value: 'result',
|
|
94
|
-
* },
|
|
95
|
-
* {
|
|
96
|
-
* type: 'throw',
|
|
97
|
-
* value: Error,
|
|
98
|
-
* },
|
|
99
|
-
* ]
|
|
100
|
-
*/
|
|
101
|
-
results: MockResult<ReturnType<T>>[];
|
|
102
|
-
/**
|
|
103
|
-
* An array containing all values that were `resolved` or `rejected` from the function.
|
|
104
|
-
*
|
|
105
|
-
* This array will be empty if the function was never resolved or rejected.
|
|
106
|
-
*
|
|
107
|
-
* @see https://vitest.dev/api/mock#mock-settledresults
|
|
108
|
-
* @example
|
|
109
|
-
* const fn = vi.fn().mockResolvedValueOnce('result')
|
|
110
|
-
*
|
|
111
|
-
* const result = fn()
|
|
112
|
-
*
|
|
113
|
-
* fn.mock.settledResults === []
|
|
114
|
-
* fn.mock.results === [
|
|
115
|
-
* {
|
|
116
|
-
* type: 'return',
|
|
117
|
-
* value: Promise<'result'>,
|
|
118
|
-
* },
|
|
119
|
-
* ]
|
|
120
|
-
*
|
|
121
|
-
* await result
|
|
122
|
-
*
|
|
123
|
-
* fn.mock.settledResults === [
|
|
124
|
-
* {
|
|
125
|
-
* type: 'fulfilled',
|
|
126
|
-
* value: 'result',
|
|
127
|
-
* },
|
|
128
|
-
* ]
|
|
129
|
-
*/
|
|
130
|
-
settledResults: MockSettledResult<Awaited<ReturnType<T>>>[];
|
|
131
|
-
/**
|
|
132
|
-
* This contains the arguments of the last call. If spy wasn't called, will return `undefined`.
|
|
133
|
-
* @see https://vitest.dev/api/mock#mock-lastcall
|
|
134
|
-
*/
|
|
135
|
-
lastCall: Parameters<T> | undefined;
|
|
136
|
-
}
|
|
137
|
-
type Procedure = (...args: any[]) => any;
|
|
138
|
-
// pick a single function type from function overloads, unions, etc...
|
|
139
|
-
type NormalizedProcedure<T extends Procedure> = (...args: Parameters<T>) => ReturnType<T>;
|
|
140
|
-
/*
|
|
141
|
-
cf. https://typescript-eslint.io/rules/method-signature-style/
|
|
142
|
-
|
|
143
|
-
Typescript assignability is different between
|
|
144
|
-
{ foo: (f: T) => U } (this is "method-signature-style")
|
|
145
|
-
and
|
|
146
|
-
{ foo(f: T): U }
|
|
147
|
-
|
|
148
|
-
Jest uses the latter for `MockInstance.mockImplementation` etc... and it allows assignment such as:
|
|
149
|
-
const boolFn: Jest.Mock<() => boolean> = jest.fn<() => true>(() => true)
|
|
150
|
-
*/
|
|
151
|
-
/* eslint-disable ts/method-signature-style */
|
|
152
|
-
interface MockInstance<T extends Procedure = Procedure> extends Disposable {
|
|
153
|
-
/**
|
|
154
|
-
* Use it to return the name assigned to the mock with the `.mockName(name)` method. By default, it will return `vi.fn()`.
|
|
155
|
-
* @see https://vitest.dev/api/mock#getmockname
|
|
156
|
-
*/
|
|
157
|
-
getMockName(): string;
|
|
158
|
-
/**
|
|
159
|
-
* Sets the internal mock name. This is useful for identifying the mock when an assertion fails.
|
|
160
|
-
* @see https://vitest.dev/api/mock#mockname
|
|
161
|
-
*/
|
|
162
|
-
mockName(name: string): this;
|
|
163
|
-
/**
|
|
164
|
-
* Current context of the mock. It stores information about all invocation calls, instances, and results.
|
|
165
|
-
*/
|
|
166
|
-
mock: MockContext<T>;
|
|
167
|
-
/**
|
|
168
|
-
* Clears all information about every call. After calling it, all properties on `.mock` will return to their initial state. This method does not reset implementations. It is useful for cleaning up mocks between different assertions.
|
|
169
|
-
*
|
|
170
|
-
* To automatically call this method before each test, enable the [`clearMocks`](https://vitest.dev/config/#clearmocks) setting in the configuration.
|
|
171
|
-
* @see https://vitest.dev/api/mock#mockclear
|
|
172
|
-
*/
|
|
173
|
-
mockClear(): this;
|
|
174
|
-
/**
|
|
175
|
-
* Does what `mockClear` does and resets inner implementation to the original function. This also resets all "once" implementations.
|
|
176
|
-
*
|
|
177
|
-
* Note that resetting a mock from `vi.fn()` will set implementation to an empty function that returns `undefined`.
|
|
178
|
-
* Resetting a mock from `vi.fn(impl)` will set implementation to `impl`. It is useful for completely resetting a mock to its default state.
|
|
179
|
-
*
|
|
180
|
-
* To automatically call this method before each test, enable the [`mockReset`](https://vitest.dev/config/#mockreset) setting in the configuration.
|
|
181
|
-
* @see https://vitest.dev/api/mock#mockreset
|
|
182
|
-
*/
|
|
183
|
-
mockReset(): this;
|
|
184
|
-
/**
|
|
185
|
-
* Does what `mockReset` does and restores original descriptors of spied-on objects.
|
|
186
|
-
*
|
|
187
|
-
* Note that restoring mock from `vi.fn()` will set implementation to an empty function that returns `undefined`. Restoring a `vi.fn(impl)` will restore implementation to `impl`.
|
|
188
|
-
* @see https://vitest.dev/api/mock#mockrestore
|
|
189
|
-
*/
|
|
190
|
-
mockRestore(): void;
|
|
191
|
-
/**
|
|
192
|
-
* Returns current permanent mock implementation if there is one.
|
|
193
|
-
*
|
|
194
|
-
* If mock was created with `vi.fn`, it will consider passed down method as a mock implementation.
|
|
195
|
-
*
|
|
196
|
-
* If mock was created with `vi.spyOn`, it will return `undefined` unless a custom implementation was provided.
|
|
197
|
-
*/
|
|
198
|
-
getMockImplementation(): NormalizedProcedure<T> | undefined;
|
|
199
|
-
/**
|
|
200
|
-
* Accepts a function to be used as the mock implementation. TypeScript expects the arguments and return type to match those of the original function.
|
|
201
|
-
* @see https://vitest.dev/api/mock#mockimplementation
|
|
202
|
-
* @example
|
|
203
|
-
* const increment = vi.fn().mockImplementation(count => count + 1);
|
|
204
|
-
* expect(increment(3)).toBe(4);
|
|
205
|
-
*/
|
|
206
|
-
mockImplementation(fn: NormalizedProcedure<T>): this;
|
|
207
|
-
/**
|
|
208
|
-
* Accepts a function to be used as the mock implementation. TypeScript expects the arguments and return type to match those of the original function. This method can be chained to produce different results for multiple function calls.
|
|
209
|
-
*
|
|
210
|
-
* When the mocked function runs out of implementations, it will invoke the default implementation set with `vi.fn(() => defaultValue)` or `.mockImplementation(() => defaultValue)` if they were called.
|
|
211
|
-
* @see https://vitest.dev/api/mock#mockimplementationonce
|
|
212
|
-
* @example
|
|
213
|
-
* const fn = vi.fn(count => count).mockImplementationOnce(count => count + 1);
|
|
214
|
-
* expect(fn(3)).toBe(4);
|
|
215
|
-
* expect(fn(3)).toBe(3);
|
|
216
|
-
*/
|
|
217
|
-
mockImplementationOnce(fn: NormalizedProcedure<T>): this;
|
|
218
|
-
/**
|
|
219
|
-
* Overrides the original mock implementation temporarily while the callback is being executed.
|
|
220
|
-
*
|
|
221
|
-
* Note that this method takes precedence over the [`mockImplementationOnce`](https://vitest.dev/api/mock#mockimplementationonce).
|
|
222
|
-
* @see https://vitest.dev/api/mock#withimplementation
|
|
223
|
-
* @example
|
|
224
|
-
* const myMockFn = vi.fn(() => 'original')
|
|
225
|
-
*
|
|
226
|
-
* myMockFn.withImplementation(() => 'temp', () => {
|
|
227
|
-
* myMockFn() // 'temp'
|
|
228
|
-
* })
|
|
229
|
-
*
|
|
230
|
-
* myMockFn() // 'original'
|
|
231
|
-
*/
|
|
232
|
-
withImplementation<T2>(fn: NormalizedProcedure<T>, cb: () => T2): T2 extends Promise<unknown> ? Promise<this> : this;
|
|
233
|
-
/**
|
|
234
|
-
* Use this if you need to return the `this` context from the method without invoking the actual implementation.
|
|
235
|
-
* @see https://vitest.dev/api/mock#mockreturnthis
|
|
236
|
-
*/
|
|
237
|
-
mockReturnThis(): this;
|
|
238
|
-
/**
|
|
239
|
-
* Accepts a value that will be returned whenever the mock function is called. TypeScript will only accept values that match the return type of the original function.
|
|
240
|
-
* @see https://vitest.dev/api/mock#mockreturnvalue
|
|
241
|
-
* @example
|
|
242
|
-
* const mock = vi.fn()
|
|
243
|
-
* mock.mockReturnValue(42)
|
|
244
|
-
* mock() // 42
|
|
245
|
-
* mock.mockReturnValue(43)
|
|
246
|
-
* mock() // 43
|
|
247
|
-
*/
|
|
248
|
-
mockReturnValue(value: ReturnType<T>): this;
|
|
249
|
-
/**
|
|
250
|
-
* Accepts a value that will be returned whenever the mock function is called. TypeScript will only accept values that match the return type of the original function.
|
|
251
|
-
*
|
|
252
|
-
* When the mocked function runs out of implementations, it will invoke the default implementation set with `vi.fn(() => defaultValue)` or `.mockImplementation(() => defaultValue)` if they were called.
|
|
253
|
-
* @example
|
|
254
|
-
* const myMockFn = vi
|
|
255
|
-
* .fn()
|
|
256
|
-
* .mockReturnValue('default')
|
|
257
|
-
* .mockReturnValueOnce('first call')
|
|
258
|
-
* .mockReturnValueOnce('second call')
|
|
259
|
-
*
|
|
260
|
-
* // 'first call', 'second call', 'default'
|
|
261
|
-
* console.log(myMockFn(), myMockFn(), myMockFn())
|
|
262
|
-
*/
|
|
263
|
-
mockReturnValueOnce(value: ReturnType<T>): this;
|
|
264
|
-
/**
|
|
265
|
-
* Accepts a value that will be resolved when the async function is called. TypeScript will only accept values that match the return type of the original function.
|
|
266
|
-
* @example
|
|
267
|
-
* const asyncMock = vi.fn().mockResolvedValue(42)
|
|
268
|
-
* asyncMock() // Promise<42>
|
|
269
|
-
*/
|
|
270
|
-
mockResolvedValue(value: Awaited<ReturnType<T>>): this;
|
|
271
|
-
/**
|
|
272
|
-
* Accepts a value that will be resolved during the next function call. TypeScript will only accept values that match the return type of the original function. If chained, each consecutive call will resolve the specified value.
|
|
273
|
-
* @example
|
|
274
|
-
* const myMockFn = vi
|
|
275
|
-
* .fn()
|
|
276
|
-
* .mockResolvedValue('default')
|
|
277
|
-
* .mockResolvedValueOnce('first call')
|
|
278
|
-
* .mockResolvedValueOnce('second call')
|
|
279
|
-
*
|
|
280
|
-
* // Promise<'first call'>, Promise<'second call'>, Promise<'default'>
|
|
281
|
-
* console.log(myMockFn(), myMockFn(), myMockFn())
|
|
282
|
-
*/
|
|
283
|
-
mockResolvedValueOnce(value: Awaited<ReturnType<T>>): this;
|
|
284
|
-
/**
|
|
285
|
-
* Accepts an error that will be rejected when async function is called.
|
|
286
|
-
* @example
|
|
287
|
-
* const asyncMock = vi.fn().mockRejectedValue(new Error('Async error'))
|
|
288
|
-
* await asyncMock() // throws Error<'Async error'>
|
|
289
|
-
*/
|
|
290
|
-
mockRejectedValue(error: unknown): this;
|
|
291
|
-
/**
|
|
292
|
-
* Accepts a value that will be rejected during the next function call. If chained, each consecutive call will reject the specified value.
|
|
293
|
-
* @example
|
|
294
|
-
* const asyncMock = vi
|
|
295
|
-
* .fn()
|
|
296
|
-
* .mockResolvedValueOnce('first call')
|
|
297
|
-
* .mockRejectedValueOnce(new Error('Async error'))
|
|
298
|
-
*
|
|
299
|
-
* await asyncMock() // first call
|
|
300
|
-
* await asyncMock() // throws Error<'Async error'>
|
|
301
|
-
*/
|
|
302
|
-
mockRejectedValueOnce(error: unknown): this;
|
|
303
|
-
}
|
|
304
|
-
/* eslint-enable ts/method-signature-style */
|
|
305
|
-
interface Mock<T extends Procedure = Procedure> extends MockInstance<T> {
|
|
306
|
-
new (...args: Parameters<T>): ReturnType<T>;
|
|
307
|
-
(...args: Parameters<T>): ReturnType<T>;
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
export { Mock as M };
|