@storybook/nextjs 7.0.0-beta.4 β†’ 7.0.0-beta.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/README.md +119 -11
  2. package/dist/app-router-provider-LIUPULW3.mjs +1 -0
  3. package/dist/chunk-4MG4OZFL.mjs +1 -0
  4. package/dist/font/webpack/loader/storybook-nextjs-font-loader.d.ts +3 -0
  5. package/dist/font/webpack/loader/storybook-nextjs-font-loader.js +40 -0
  6. package/dist/font/webpack/loader/storybook-nextjs-font-loader.mjs +40 -0
  7. package/dist/index.d.ts +0 -1
  8. package/dist/index.js +1 -1
  9. package/dist/index.mjs +0 -1
  10. package/dist/next-image-loader-stub.js +1 -1
  11. package/dist/next-image-loader-stub.mjs +1 -1
  12. package/dist/preset.d.ts +13 -11
  13. package/dist/preset.js +1 -5
  14. package/dist/preset.mjs +1 -5
  15. package/dist/preview.js +6 -6
  16. package/dist/preview.mjs +2 -2
  17. package/package.json +17 -13
  18. package/template/cli/js/Button.stories.js +1 -1
  19. package/template/cli/js/Header.stories.js +2 -2
  20. package/template/cli/js/Introduction.mdx +1 -1
  21. package/template/cli/ts-legacy/Button.stories.ts +1 -1
  22. package/template/cli/ts-legacy/Header.stories.ts +2 -2
  23. package/template/cli/ts-legacy/Introduction.stories.mdx +1 -1
  24. package/template/cli/ts-legacy/Page.tsx +1 -1
  25. package/template/stories/Image.stories.jsx +1 -1
  26. package/template/stories_12-js/ImageFuture.stories.jsx +1 -1
  27. package/template/stories_default-js/Font.jsx +64 -0
  28. package/template/stories_default-js/Font.stories.jsx +23 -0
  29. package/template/stories_default-js/Head.stories.jsx +34 -0
  30. package/template/stories_default-js/ImageLegacy.stories.jsx +1 -1
  31. package/template/stories_default-js/Navigation.stories.jsx +22 -1
  32. package/template/stories_default-js/fonts/OFL.txt +93 -0
  33. package/template/stories_default-js/fonts/RubikStorm-Regular.ttf +0 -0
  34. package/dist/app-router-provider-5WPYJFG6.mjs +0 -1
  35. package/dist/chunk-LAHENP5R.mjs +0 -1
package/README.md CHANGED
@@ -7,19 +7,31 @@
7
7
  - [Getting Started](#getting-started)
8
8
  - [In a project without Storybook](#in-a-project-without-storybook)
9
9
  - [In a project with Storybook](#in-a-project-with-storybook)
10
+ - [Automatic migration](#automatic-migration)
11
+ - [Manual migration](#manual-migration)
10
12
  - [Documentation](#documentation)
11
13
  - [Options](#options)
12
14
  - [Next.js's Image Component](#nextjss-image-component)
13
15
  - [Local Images](#local-images)
14
16
  - [Remote Images](#remote-images)
15
- - [Optimization](#optimization)
16
17
  - [AVIF](#avif)
18
+ - [Next.js Font Optimization](#nextjs-font-optimization)
19
+ - [@next/font/google](#nextfontgoogle)
20
+ - [@next/font/local](#nextfontlocal)
21
+ - [Not supported features of @next/font](#not-supported-features-of-nextfont)
17
22
  - [Next.js Routing](#nextjs-routing)
18
23
  - [Overriding defaults](#overriding-defaults)
19
24
  - [Global Defaults](#global-defaults)
20
25
  - [Default Router](#default-router)
21
26
  - [Actions Integration Caveats](#actions-integration-caveats)
22
27
  - [Next.js Navigation](#nextjs-navigation)
28
+ - [Set `nextjs.appDirectory` to `true`](#set-nextjsappdirectory-to-true)
29
+ - [Overriding defaults](#overriding-defaults-1)
30
+ - [Global Defaults](#global-defaults-1)
31
+ - [`useSelectedLayoutSegment` and `useSelectedLayoutSegments` hook](#useselectedlayoutsegment-and-useselectedlayoutsegments-hook)
32
+ - [Default Navigation Context](#default-navigation-context)
33
+ - [Actions Integration Caveats](#actions-integration-caveats-1)
34
+ - [Next.js Head](#nextjs-head)
23
35
  - [Sass/Scss](#sassscss)
24
36
  - [Css/Sass/Scss Modules](#csssassscss-modules)
25
37
  - [Styled JSX](#styled-jsx)
@@ -30,17 +42,21 @@
30
42
  - [Typescript](#typescript)
31
43
  - [Notes for Yarn v2 and v3 users](#notes-for-yarn-v2-and-v3-users)
32
44
  - [FAQ](#faq)
33
- - [Stories for pages](#stories-for-pages-components-which-fetch-data)
45
+ - [Stories for pages/components which fetch data](#stories-for-pagescomponents-which-fetch-data)
34
46
  - [Statically imported images won't load](#statically-imported-images-wont-load)
35
- - [Module not found: Error: Can't resolve [package name]](#module-not-found-error-cant-resolve-package-name)
47
+ - [Module not found: Error: Can't resolve \[package name\]](#module-not-found-error-cant-resolve-package-name)
36
48
  - [Acknowledgements](#acknowledgements)
37
49
 
38
50
  ## Supported Features
39
51
 
40
52
  πŸ‘‰ [Next.js's Image Component](#nextjss-image-component)
41
53
 
54
+ πŸ‘‰ [Next.js Font Optimization](#nextjs-font-optimization)
55
+
42
56
  πŸ‘‰ [Next.js Routing (next/router)](#nextjs-routing)
43
57
 
58
+ πŸ‘‰ [Next.js Head (next/head)](#nextjs-head)
59
+
44
60
  πŸ‘‰ [Next.js Navigation (next/navigation)](#nextjs-navigation)
45
61
 
46
62
  πŸ‘‰ [Sass/Scss](#sassscss)
@@ -84,17 +100,23 @@ This framework is designed to work with Storybook 7. If you’re not already usi
84
100
  npx storybook@next upgrade --prerelease
85
101
  ```
86
102
 
103
+ #### Automatic migration
104
+
105
+ When running the `upgrade` command above, you should get a prompt asking you to migrate to `@storybook/nextjs`, which should handle everything for you. In case that auto-migration does not work for your project, refer to the manual migration below.
106
+
107
+ #### Manual migration
108
+
87
109
  Install the framework:
88
110
 
89
111
  ```bash
90
- yarn install -D @storybook/nextjs@next
112
+ yarn add --dev @storybook/nextjs@next
91
113
  ```
92
114
 
93
115
  Update your `main.js` to change the framework property:
94
116
 
95
117
  ```js
96
118
  // .storybook/main.js
97
- module.exports = {
119
+ export default {
98
120
  // ...
99
121
  framework: {
100
122
  // name: '@storybook/react-webpack5', // Remove this
@@ -108,7 +130,7 @@ If you were using Storybook plugins to integrate with Next.js, those are no long
108
130
 
109
131
  ```js
110
132
  // .storybook/main.js
111
- module.exports = {
133
+ export default {
112
134
  // ...
113
135
  addons: [
114
136
  // ...
@@ -129,9 +151,9 @@ For example:
129
151
 
130
152
  ```js
131
153
  // .storybook/main.js
132
- const path = require('path');
154
+ import * as path from 'path';
133
155
 
134
- module.exports = {
156
+ export default {
135
157
  // ...
136
158
  framework: {
137
159
  name: '@storybook/nextjs',
@@ -196,6 +218,54 @@ export default function Home() {
196
218
 
197
219
  This format is not supported by this framework yet. Feel free to [open up an issue](https://github.com/storybookjs/storybook/issues) if this is something you want to see.
198
220
 
221
+ ### Next.js Font Optimization
222
+
223
+ [@next/font](https://nextjs.org/docs/basic-features/font-optimization) is partially supported in Storybook. The packages `@next/font/google` and `@next/font/local` are supported.
224
+
225
+ #### @next/font/google
226
+
227
+ You don't have to do anything. `@next/font/google` is supported out of the box.
228
+
229
+ #### @next/font/local
230
+
231
+ For local fonts you have to define the [src](https://nextjs.org/docs/api-reference/next/font#src) property.
232
+ The path is relative to the directory where the font loader function is called.
233
+
234
+ If the following component defines your localFont like this:
235
+
236
+ ```js
237
+ // src/components/MyComponent.js
238
+ import localFont from '@next/font/local';
239
+
240
+ const localRubikStorm = localFont({ src: './fonts/RubikStorm-Regular.ttf' });
241
+ ```
242
+
243
+ You have to tell Storybook where the `fonts` directory is located. The `from` value is relative to the `.storybook` directory. The `to` value is relative to the execution context of Storybook. Very likely it is the root of your project.
244
+
245
+ ```js
246
+ // .storybook/main.js
247
+ export default {
248
+ ...
249
+ "staticDirs": [
250
+ {
251
+ from: '../src/components/fonts',
252
+ to: 'src/components/fonts'
253
+ }
254
+ ],
255
+ }
256
+ ```
257
+
258
+ #### Not supported features of @next/font
259
+
260
+ The following features are not supported (yet). Support for these features might be planned for the future:
261
+
262
+ - [Support font loaders configuration in next.config.js](https://nextjs.org/docs/basic-features/font-optimization#specifying-a-subset)
263
+ - [fallback](https://nextjs.org/docs/api-reference/next/font#fallback) option
264
+ - [adjustFontFallback](https://nextjs.org/docs/api-reference/next/font#adjustfontfallback) option
265
+ - [declarations](https://nextjs.org/docs/api-reference/next/font#declarations) option
266
+ - [preload](https://nextjs.org/docs/api-reference/next/font#preload) option gets ignored. Storybook handles Font loading its own way.
267
+ - [display](https://nextjs.org/docs/api-reference/next/font#display) option gets ignored. All fonts are loaded with display set to "block" to make Storybook load the font properly.
268
+
199
269
  ### Next.js Routing
200
270
 
201
271
  [Next.js's router](https://nextjs.org/docs/routing/introduction) is automatically stubbed for you so that when the router is interacted with, all of its interactions are automatically logged to the Actions ctions panel if you have the [Storybook actions addon](https://storybook.js.org/docs/react/essentials/actions).
@@ -428,6 +498,40 @@ export const parameters = {
428
498
  };
429
499
  ```
430
500
 
501
+ #### `useSelectedLayoutSegment` and `useSelectedLayoutSegments` hook
502
+
503
+ The `useSelectedLayoutSegment` and `useSelectedLayoutSegments` hooks are supported in Storybook. You have to set the `nextjs.navigation.segments` parameter to return the segments you want to use.
504
+
505
+ ```js
506
+ // SomeComponentThatUsesTheNavigation.stories.js
507
+ import SomeComponentThatUsesTheNavigation from './SomeComponentThatUsesTheNavigation';
508
+
509
+ export default {
510
+ component: SomeComponentThatUsesTheNavigation,
511
+ parameters: {
512
+ nextjs: {
513
+ appDirectory: true,
514
+ navigation: {
515
+ segments: ['dashboard', 'analytics']
516
+ },
517
+ },
518
+ },
519
+ };
520
+
521
+ export const Example = {};
522
+
523
+ // SomeComponentThatUsesTheNavigation.js
524
+ import { useSelectedLayoutSegment, useSelectedLayoutSegments } from 'next/navigation';
525
+
526
+ export default function SomeComponentThatUsesTheNavigation() {
527
+ const segment = useSelectedLayoutSegment(); // dashboard
528
+ const segments = useSelectedLayoutSegments(); // ["dashboard", "analytics"]
529
+ ...
530
+ }
531
+ ```
532
+
533
+ The default value of `nextjs.navigation.segments` is `[]` if not set.
534
+
431
535
  #### Default Navigation Context
432
536
 
433
537
  The default values on the stubbed navigation context are as follows:
@@ -498,6 +602,10 @@ export const parameters = {
498
602
  };
499
603
  ```
500
604
 
605
+ ### Next.js Head
606
+
607
+ [next/head](https://nextjs.org/docs/api-reference/next/head) is supported out of the box. You can use it in your stories like you would in your Next.js application. Please keep in mind, that the Head children are placed into the head element of the iframe that Storybook uses to render your stories.
608
+
501
609
  ### Sass/Scss
502
610
 
503
611
  [Global sass/scss stylesheets](https://nextjs.org/docs/basic-features/built-in-css-support#sass-support) are supported without any additional configuration as well. Just import them into [preview.js](https://storybook.js.org/docs/react/configure/overview#configure-story-rendering)
@@ -510,9 +618,9 @@ This will automatically include any of your [custom sass configurations](https:/
510
618
 
511
619
  ```js
512
620
  // next.config.js
513
- const path = require('path');
621
+ import * as path from 'path';
514
622
 
515
- module.exports = {
623
+ export default {
516
624
  // Any options here are included in Sass compilation for your stories
517
625
  sassOptions: {
518
626
  includePaths: [path.join(__dirname, 'styles')],
@@ -676,7 +784,7 @@ Below is an example of how to add svgr support to Storybook with this framework.
676
784
 
677
785
  ```js
678
786
  // .storybook/main.js
679
- module.exports = {
787
+ export default {
680
788
  // ...
681
789
  webpackFinal: async (config) => {
682
790
  // This modifies the existing image rule to exclude .svg files
@@ -0,0 +1 @@
1
+ import"./chunk-4MG4OZFL.mjs";import React from"react";import{AppRouterContext,LayoutRouterContext}from"next/dist/shared/lib/app-router-context";import{PathnameContext,SearchParamsContext}from"next/dist/shared/lib/hooks-client-context";var getParallelRoutes=segmentsList=>{let segment=segmentsList.shift();return segment?[segment,{children:getParallelRoutes(segmentsList)}]:[]},AppRouterProvider=({children,action,routeParams})=>{let{pathname,query,segments=[],...restRouteParams}=routeParams;return React.createElement(AppRouterContext.Provider,{value:{push(...args){action("nextNavigation.push")(...args)},replace(...args){action("nextNavigation.replace")(...args)},forward(...args){action("nextNavigation.forward")(...args)},back(...args){action("nextNavigation.back")(...args)},prefetch(...args){action("nextNavigation.prefetch")(...args)},refresh:()=>{action("nextNavigation.refresh")()},...restRouteParams}},React.createElement(SearchParamsContext.Provider,{value:new URLSearchParams(query)},React.createElement(LayoutRouterContext.Provider,{value:{childNodes:new Map,tree:[pathname,{children:getParallelRoutes([...segments])}],url:pathname}},React.createElement(PathnameContext.Provider,{value:pathname},children))))},app_router_provider_default=AppRouterProvider;export{app_router_provider_default as default};
@@ -0,0 +1 @@
1
+ var __getOwnPropNames=Object.getOwnPropertyNames;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 new 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};export{__require,__commonJS};
@@ -0,0 +1,3 @@
1
+ declare function storybookNextjsFontLoader(this: any): Promise<string>;
2
+
3
+ export { storybookNextjsFontLoader as default };
@@ -0,0 +1,40 @@
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 storybook_nextjs_font_loader_exports={};__export(storybook_nextjs_font_loader_exports,{default:()=>storybookNextjsFontLoader});module.exports=__toCommonJS(storybook_nextjs_font_loader_exports);var import_loader_utils3=__toESM(require("next/dist/compiled/loader-utils3")),import_utils=require("@next/font/dist/google/utils"),cssCache=new Map;async function getFontFaceDeclarations(options){let{fontFamily,weights,styles,selectedVariableAxes,display,variable}=(0,import_utils.validateData)(options.fontFamily,[options.props],null),fontAxes=(0,import_utils.getFontAxes)(fontFamily,weights,styles,selectedVariableAxes),url=(0,import_utils.getUrl)(fontFamily,fontAxes,display);try{let hasCachedCSS=cssCache.has(url),fontFaceCSS=hasCachedCSS?cssCache.get(url):await(0,import_utils.fetchCSSFromGoogleFonts)(url,fontFamily).catch(()=>null);if(hasCachedCSS?cssCache.delete(url):cssCache.set(url,fontFaceCSS),fontFaceCSS===null)throw Error(`Failed to fetch \`${fontFamily}\` from Google Fonts.`);return{id:import_loader_utils3.default.getHashDigest(url,"md5","hex",6),fontFamily,fontFaceCSS,weights,styles,variable}}catch{throw new Error("Google Fonts couldn't be loaded.")}}var import_loader_utils32=__toESM(require("next/dist/compiled/loader-utils3")),import_utils2=require("@next/font/dist/local/utils"),import_path=__toESM(require("path"));async function getFontFaceDeclarations2(options,rootContext){let localFontSrc=options.props.src,parentFolder=options.filename.split("/").slice(0,-1).join("/").replace(rootContext,""),{weight,style,variable}=(0,import_utils2.validateData)("",options.props),id=`font-${import_loader_utils32.default.getHashDigest(Buffer.from(JSON.stringify(localFontSrc)),"md5","hex",6)}`;return{id,fontFamily:id,fontFaceCSS:(()=>{if(typeof localFontSrc=="string"){let localFontPath=import_path.default.join(parentFolder,localFontSrc);return`@font-face {
2
+ font-family: ${id};
3
+ src: url(${localFontPath});
4
+ }`}return localFontSrc.map(font=>{let localFontPath=import_path.default.join(parentFolder,font.path);return`@font-face {
5
+ font-family: ${id};
6
+ src: url(${localFontPath});
7
+ ${font.weight?`font-weight: ${font.weight};`:""}
8
+ ${font.style?`font-style: ${font.style};`:""}
9
+ }`}).join("")})(),weights:weight?[weight]:[],styles:style?[style]:[],variable}}function getCSSMeta(options){let className=getClassName(options),style=getStylesObj(options),variableClassName=`__variable_${className}`,classNamesCSS=`
10
+ .${className} {
11
+ font-family: ${options.fontFamily};
12
+ ${isNextCSSPropertyValid(options.styles)?`font-style: ${options.styles[0]};`:""}
13
+ ${isNextCSSPropertyValid(options.weights)?`font-weight: ${options.weights[0]};`:""}
14
+ }
15
+
16
+ ${options.variable?`.${variableClassName} { ${options.variable}: '${options.fontFamily}'; }`:""}
17
+ `,fontFaceCSS=`${changeFontDisplayToSwap(options.fontFaceCSS)}`;return{className,fontFaceCSS,classNamesCSS,style,...options.variable?{variableClassName}:{}}}function getClassName({styles,weights,fontFamily}){let font=fontFamily.replace(" ","-").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`
18
+ if (!document.getElementById('id-${id}')) {
19
+ const fontDeclarations = \`${fontFaceCSS}\`;
20
+ const style = document.createElement('style');
21
+ style.setAttribute('id', 'font-face-${id}');
22
+ style.innerHTML = fontDeclarations;
23
+ document.head.appendChild(style);
24
+
25
+ const classNamesCSS = \`${classNamesCSS}\`;
26
+ const classNamesStyle = document.createElement('style');
27
+ classNamesStyle.setAttribute('id', 'classnames-${id}');
28
+ classNamesStyle.innerHTML = classNamesCSS;
29
+ document.head.appendChild(classNamesStyle);
30
+
31
+ }
32
+ `}async function storybookNextjsFontLoader(){let options=this.getOptions(),rootCtx=this.rootContext,fontFaceDeclaration;if(options.source==="@next/font/google"&&(fontFaceDeclaration=await getFontFaceDeclarations(options)),options.source==="@next/font/local"&&(fontFaceDeclaration=await getFontFaceDeclarations2(options,rootCtx)),typeof fontFaceDeclaration<"u"){let cssMeta=getCSSMeta(fontFaceDeclaration);return`
33
+ ${setFontDeclarationsInHead({fontFaceCSS:cssMeta.fontFaceCSS,id:fontFaceDeclaration.id,classNamesCSS:cssMeta.classNamesCSS})}
34
+
35
+ module.exports = {
36
+ className: "${cssMeta.className}",
37
+ style: ${JSON.stringify(cssMeta.style)}
38
+ ${cssMeta.variableClassName?`, variable: "${cssMeta.variableClassName}"`:""}
39
+ }
40
+ `}return"module.exports = {}"}0&&(module.exports={});
@@ -0,0 +1,40 @@
1
+ import"../../../chunk-4MG4OZFL.mjs";import loaderUtils from"next/dist/compiled/loader-utils3";import{fetchCSSFromGoogleFonts,getFontAxes,getUrl,validateData}from"@next/font/dist/google/utils";var cssCache=new Map;async function getFontFaceDeclarations(options){let{fontFamily,weights,styles,selectedVariableAxes,display,variable}=validateData(options.fontFamily,[options.props],null),fontAxes=getFontAxes(fontFamily,weights,styles,selectedVariableAxes),url=getUrl(fontFamily,fontAxes,display);try{let hasCachedCSS=cssCache.has(url),fontFaceCSS=hasCachedCSS?cssCache.get(url):await fetchCSSFromGoogleFonts(url,fontFamily).catch(()=>null);if(hasCachedCSS?cssCache.delete(url):cssCache.set(url,fontFaceCSS),fontFaceCSS===null)throw Error(`Failed to fetch \`${fontFamily}\` from Google Fonts.`);return{id:loaderUtils.getHashDigest(url,"md5","hex",6),fontFamily,fontFaceCSS,weights,styles,variable}}catch{throw new Error("Google Fonts couldn't be loaded.")}}import loaderUtils2 from"next/dist/compiled/loader-utils3";import{validateData as validateData2}from"@next/font/dist/local/utils";import path from"path";async function getFontFaceDeclarations2(options,rootContext){let localFontSrc=options.props.src,parentFolder=options.filename.split("/").slice(0,-1).join("/").replace(rootContext,""),{weight,style,variable}=validateData2("",options.props),id=`font-${loaderUtils2.getHashDigest(Buffer.from(JSON.stringify(localFontSrc)),"md5","hex",6)}`;return{id,fontFamily:id,fontFaceCSS:(()=>{if(typeof localFontSrc=="string"){let localFontPath=path.join(parentFolder,localFontSrc);return`@font-face {
2
+ font-family: ${id};
3
+ src: url(${localFontPath});
4
+ }`}return localFontSrc.map(font=>{let localFontPath=path.join(parentFolder,font.path);return`@font-face {
5
+ font-family: ${id};
6
+ src: url(${localFontPath});
7
+ ${font.weight?`font-weight: ${font.weight};`:""}
8
+ ${font.style?`font-style: ${font.style};`:""}
9
+ }`}).join("")})(),weights:weight?[weight]:[],styles:style?[style]:[],variable}}function getCSSMeta(options){let className=getClassName(options),style=getStylesObj(options),variableClassName=`__variable_${className}`,classNamesCSS=`
10
+ .${className} {
11
+ font-family: ${options.fontFamily};
12
+ ${isNextCSSPropertyValid(options.styles)?`font-style: ${options.styles[0]};`:""}
13
+ ${isNextCSSPropertyValid(options.weights)?`font-weight: ${options.weights[0]};`:""}
14
+ }
15
+
16
+ ${options.variable?`.${variableClassName} { ${options.variable}: '${options.fontFamily}'; }`:""}
17
+ `,fontFaceCSS=`${changeFontDisplayToSwap(options.fontFaceCSS)}`;return{className,fontFaceCSS,classNamesCSS,style,...options.variable?{variableClassName}:{}}}function getClassName({styles,weights,fontFamily}){let font=fontFamily.replace(" ","-").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`
18
+ if (!document.getElementById('id-${id}')) {
19
+ const fontDeclarations = \`${fontFaceCSS}\`;
20
+ const style = document.createElement('style');
21
+ style.setAttribute('id', 'font-face-${id}');
22
+ style.innerHTML = fontDeclarations;
23
+ document.head.appendChild(style);
24
+
25
+ const classNamesCSS = \`${classNamesCSS}\`;
26
+ const classNamesStyle = document.createElement('style');
27
+ classNamesStyle.setAttribute('id', 'classnames-${id}');
28
+ classNamesStyle.innerHTML = classNamesCSS;
29
+ document.head.appendChild(classNamesStyle);
30
+
31
+ }
32
+ `}async function storybookNextjsFontLoader(){let options=this.getOptions(),rootCtx=this.rootContext,fontFaceDeclaration;if(options.source==="@next/font/google"&&(fontFaceDeclaration=await getFontFaceDeclarations(options)),options.source==="@next/font/local"&&(fontFaceDeclaration=await getFontFaceDeclarations2(options,rootCtx)),typeof fontFaceDeclaration<"u"){let cssMeta=getCSSMeta(fontFaceDeclaration);return`
33
+ ${setFontDeclarationsInHead({fontFaceCSS:cssMeta.fontFaceCSS,id:fontFaceDeclaration.id,classNamesCSS:cssMeta.classNamesCSS})}
34
+
35
+ module.exports = {
36
+ className: "${cssMeta.className}",
37
+ style: ${JSON.stringify(cssMeta.style)}
38
+ ${cssMeta.variableClassName?`, variable: "${cssMeta.variableClassName}"`:""}
39
+ }
40
+ `}return"module.exports = {}"}export{storybookNextjsFontLoader as default};
package/dist/index.d.ts CHANGED
@@ -1,4 +1,3 @@
1
- export * from '@storybook/react';
2
1
  export { F as FrameworkOptions, S as StorybookConfig } from './types-96e623f7.js';
3
2
  import '@storybook/preset-react-webpack';
4
3
  import '@storybook/builder-webpack5';
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var a=Object.defineProperty;var b=Object.getOwnPropertyDescriptor;var c=Object.getOwnPropertyNames;var d=Object.prototype.hasOwnProperty;var t=(r,o,m,x)=>{if(o&&typeof o=="object"||typeof o=="function")for(let e of c(o))!d.call(r,e)&&e!==m&&a(r,e,{get:()=>o[e],enumerable:!(x=b(o,e))||x.enumerable});return r},p=(r,o,m)=>(t(r,o,"default"),m&&t(m,o,"default"));var g=r=>t(a({},"__esModule",{value:!0}),r);var f={};module.exports=g(f);p(f,require("@storybook/react"),module.exports);
1
+ "use strict";var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;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 __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var src_exports={};module.exports=__toCommonJS(src_exports);
package/dist/index.mjs CHANGED
@@ -1 +0,0 @@
1
- export*from"@storybook/react";
@@ -1 +1 @@
1
- "use strict";var m=Object.create;var a=Object.defineProperty;var c=Object.getOwnPropertyDescriptor;var h=Object.getOwnPropertyNames;var u=Object.getPrototypeOf,d=Object.prototype.hasOwnProperty;var l=(t,e)=>{for(var i in e)a(t,i,{get:e[i],enumerable:!0})},n=(t,e,i,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of h(e))!d.call(t,o)&&o!==i&&a(t,o,{get:()=>e[o],enumerable:!(r=c(e,o))||r.enumerable});return t};var x=(t,e,i)=>(i=t!=null?m(u(t)):{},n(e||!t||!t.__esModule?a(i,"default",{value:t,enumerable:!0}):i,t)),g=t=>n(a({},"__esModule",{value:!0}),t);var w={};l(w,{default:()=>L});module.exports=g(w);var s=require("loader-utils"),f=x(require("image-size")),p=function(t){let{filename:e}=this.getOptions(),i=(0,s.interpolateName)(this,e.replace("[ext]",".[ext]"),{context:this.rootContext,content:t});this.emitFile(i,t);let{width:r,height:o}=(0,f.default)(this.resourcePath);return`export default ${JSON.stringify({src:i,height:o,width:r,blurDataURL:i})};`};p.raw=!0;var L=p;0&&(module.exports={});
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 __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 import_loader_utils=require("loader-utils"),import_image_size=__toESM(require("image-size")),nextImageLoaderStub=function(content){let{filename}=this.getOptions(),outputPath=(0,import_loader_utils.interpolateName)(this,filename.replace("[ext]",".[ext]"),{context:this.rootContext,content});this.emitFile(outputPath,content);let{width,height}=(0,import_image_size.default)(this.resourcePath);return`export default ${JSON.stringify({src:outputPath,height,width,blurDataURL:outputPath})};`};nextImageLoaderStub.raw=!0;module.exports=nextImageLoaderStub;
@@ -1 +1 @@
1
- import"./chunk-LAHENP5R.mjs";import{interpolateName}from"loader-utils";import imageSizeOf from"image-size";var nextImageLoaderStub=function(content){let{filename}=this.getOptions(),outputPath=interpolateName(this,filename.replace("[ext]",".[ext]"),{context:this.rootContext,content});this.emitFile(outputPath,content);let{width,height}=imageSizeOf(this.resourcePath);return`export default ${JSON.stringify({src:outputPath,height,width,blurDataURL:outputPath})};`};nextImageLoaderStub.raw=!0;var next_image_loader_stub_default=nextImageLoaderStub;export{next_image_loader_stub_default as default};
1
+ import{__commonJS}from"./chunk-4MG4OZFL.mjs";import{interpolateName}from"loader-utils";import imageSizeOf from"image-size";var require_next_image_loader_stub=__commonJS({"src/next-image-loader-stub.ts"(exports,module){var nextImageLoaderStub=function(content){let{filename}=this.getOptions(),outputPath=interpolateName(this,filename.replace("[ext]",".[ext]"),{context:this.rootContext,content});this.emitFile(outputPath,content);let{width,height}=imageSizeOf(this.resourcePath);return`export default ${JSON.stringify({src:outputPath,height,width,blurDataURL:outputPath})};`};nextImageLoaderStub.raw=!0;module.exports=nextImageLoaderStub}});export default require_next_image_loader_stub();
package/dist/preset.d.ts CHANGED
@@ -876,20 +876,17 @@ interface CLIOptions {
876
876
  quiet?: boolean;
877
877
  versionUpdates?: boolean;
878
878
  releaseNotes?: boolean;
879
- dll?: boolean;
880
879
  docs?: boolean;
881
- docsDll?: boolean;
882
- uiDll?: boolean;
883
880
  debugWebpack?: boolean;
884
881
  webpackStatsJson?: string | boolean;
885
882
  outputDir?: string;
886
883
  }
887
884
  interface BuilderOptions {
888
885
  configType?: 'DEVELOPMENT' | 'PRODUCTION';
889
- ignorePreview: boolean;
890
- cache: FileSystemCache;
886
+ ignorePreview?: boolean;
887
+ cache?: FileSystemCache;
891
888
  configDir: string;
892
- docsMode: boolean;
889
+ docsMode?: boolean;
893
890
  features?: StorybookConfig['features'];
894
891
  versionCheck?: VersionCheck;
895
892
  releaseNotesData?: ReleaseNotesData;
@@ -935,18 +932,19 @@ type CoreCommon_StorybookRefs = Record<string, {
935
932
  }>;
936
933
  type DocsOptions = {
937
934
  /**
938
- * Should we generate docs entries at all under any circumstances? (i.e. can they be rendered)
935
+ * Should we disable generate docs entries at all under any circumstances? (i.e. can they be rendered)
939
936
  */
940
- enabled?: boolean;
937
+ disable?: boolean;
941
938
  /**
942
939
  * What should we call the generated docs entries?
943
940
  */
944
941
  defaultName?: string;
945
942
  /**
946
- * Should we generate a docs entry per CSF file with the `docsPage` tag?
947
- * Set to 'automatic' to generate an entry irrespective of tag.
943
+ * Should we generate a docs entry per CSF file?
944
+ * Set to 'tag' (the default) to generate an entry for every CSF file with the
945
+ * 'autodocs' tag.
948
946
  */
949
- docsPage?: boolean | 'automatic';
947
+ autodocs?: boolean | 'tag';
950
948
  /**
951
949
  * Only show doc entries in the side bar (usually set with the `--docs` CLI flag)
952
950
  */
@@ -1002,6 +1000,10 @@ interface StorybookConfig {
1002
1000
  * Will be removed in 7.0.
1003
1001
  */
1004
1002
  warnOnLegacyHierarchySeparator?: boolean;
1003
+ /**
1004
+ * Use legacy MDX1, to help smooth migration to 7.0
1005
+ */
1006
+ legacyMdx1?: boolean;
1005
1007
  };
1006
1008
  /**
1007
1009
  * Tells Storybook where to find stories.
package/dist/preset.js CHANGED
@@ -1,5 +1 @@
1
- "use strict";var Z=Object.create;var x=Object.defineProperty;var ee=Object.getOwnPropertyDescriptor;var oe=Object.getOwnPropertyNames;var te=Object.getPrototypeOf,re=Object.prototype.hasOwnProperty;var se=(e,t)=>{for(var o in t)x(e,o,{get:t[o],enumerable:!0})},h=(e,t,o,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of oe(t))!re.call(e,s)&&s!==o&&x(e,s,{get:()=>t[s],enumerable:!(r=ee(t,s))||r.enumerable});return e};var n=(e,t,o)=>(o=e!=null?Z(te(e)):{},h(t||!e||!e.__esModule?x(o,"default",{value:e,enumerable:!0}):o,e)),ie=e=>h(x({},"__esModule",{value:!0}),e);var ye={};se(ye,{addons:()=>me,babel:()=>de,config:()=>ue,core:()=>ge,frameworkOptions:()=>le,webpackFinal:()=>xe});module.exports=ie(ye);var c=require("path"),Q=require("@babel/core"),Y=require("@storybook/core-common");var b=n(require("semver")),V=require("webpack");var k=n(require("path")),R=require("webpack"),j=require("next/constants"),P=n(require("find-up")),E=require("fs-extra"),S=n(require("ts-dedent")),I=require("url"),O=e=>{var t;(t=e.plugins)==null||t.push(new R.DefinePlugin({"process.env.__NEXT_VERSION":JSON.stringify(f())}))},f=()=>require(y("next/package.json")).version,ne=async e=>["mjs","js"].reduce(async(o,r)=>(await o||(o=(0,P.default)(`next.config.${r}`,{cwd:e})),o),Promise.resolve(void 0)),_=async({baseConfig:e={},nextConfigPath:t,configDir:o})=>{let r=t||await ne(o);if(!r||await(0,E.pathExists)(r)===!1)throw new Error(S.default`
2
- Could not find or resolve your Next config file. Please provide the next config file path as a framework option.
3
-
4
- More info: https://github.com/storybookjs/storybook/blob/next/code/frameworks/nextjs/README.md#options
5
- `);let s=await import((0,I.pathToFileURL)(r).href),i=typeof s=="function"?s(j.PHASE_DEVELOPMENT_SERVER,{defaultConfig:e}):s;return i.default||i},p=(e,t,o)=>{e.resolve??={},e.resolve.alias??={};let r=e.resolve.alias,s=y(`${o??t}`);Array.isArray(r)?r.push({name:t,alias:s}):r[t]=s},y=e=>{let t=require.resolve(e,{paths:[k.default.resolve()]}),r=t.lastIndexOf(e.replace(/\//g,k.default.sep))+e.length;return t.substring(0,r)};var A=async({baseConfig:e,nextConfigPath:t,configDir:o})=>{let r=await _({baseConfig:e,nextConfigPath:t,configDir:o});return p(e,"next/config"),pe(e,r),r},W=f(),pe=(e,t)=>{var s,i;let o={"process.env.__NEXT_RUNTIME_CONFIG":JSON.stringify({serverRuntimeConfig:{},publicRuntimeConfig:t.publicRuntimeConfig})},r=(s=t.experimental)==null?void 0:s.newNextLinkBehavior;b.default.gte(W,"13.0.0")&&b.default.lt(W,"13.0.6")&&r!==!1?o["process.env.__NEXT_NEW_LINK_BEHAVIOR"]=!0:o["process.env.__NEXT_NEW_LINK_BEHAVIOR"]=r,(i=e.plugins)==null||i.push(new V.DefinePlugin(o))};var v=require("next/dist/build/webpack/config/blocks/css/loaders/getCssModuleLocalIdent"),w=require("next/dist/build/webpack/config/blocks/css/loaders/file-resolve"),$=n(require("semver"));var q=(e,t)=>{var r,s,i;let o=(r=e.module)==null?void 0:r.rules;o==null||o.forEach((m,l)=>{typeof m!="string"&&m.test instanceof RegExp&&m.test.test("test.css")&&(o[l]={test:/\.css$/,use:["style-loader",{loader:"css-loader",options:{importLoaders:1,...F(t),modules:{auto:!0,getLocalIdent:v.getCssModuleLocalIdent}}},"postcss-loader"]})}),o==null||o.push({test:/\.(scss|sass)$/,use:["style-loader",{loader:"css-loader",options:{importLoaders:3,...F(t),modules:{auto:!0,getLocalIdent:v.getCssModuleLocalIdent}}},"postcss-loader","resolve-url-loader",{loader:"sass-loader",options:{sourceMap:!0,sassOptions:t.sassOptions,additionalData:((s=t.sassOptions)==null?void 0:s.prependData)||((i=t.sassOptions)==null?void 0:i.additionalData)}}]})},F=e=>ae()?{url:{filter:L(e)},import:{filter:T(e)}}:{url:L(e),import:T(e)},L=e=>(t,o)=>{var r;return(0,w.cssFileResolve)(t,o,(r=e.experimental)==null?void 0:r.urlImports)},T=e=>(t,o,r)=>{var s;return(0,w.cssFileResolve)(typeof t=="string"?t:t.url,r,(s=e.experimental)==null?void 0:s.urlImports)},ae=()=>{try{let e=require(y("css-loader/package.json")).version;return $.default.gte(e,"6.0.0")}catch{return!1}};var D=n(require("tsconfig-paths-webpack-plugin")),M=require("tsconfig-paths"),B=e=>{let t=(0,M.loadConfig)();t.resultType==="failed"||!t.baseUrl||(e.resolve??={},e.resolve.plugins??=[],e.resolve.plugins.push(new D.default({configFile:t.configFileAbsolutePath,extensions:[".js",".jsx",".ts",".tsx"]})))};var U=n(require("semver"));var J=e=>{let t=fe();p(e,t)},fe=()=>{let e=f();return U.default.gte(e,"11.1.0")?"next/dist/shared/lib/router-context":"next/dist/next-server/lib/router-context"};var X=n(require("semver"));var H=e=>{let t=f();X.default.gte(t,"12.0.0")?p(e,"styled-jsx"):(p(e,"styled-jsx/babel"),p(e,"styled-jsx/css"),p(e,"styled-jsx/macro"),p(e,"styled-jsx/server"),p(e,"styled-jsx/style"),p(e,"styled-jsx/webpack"))};var K=n(require("semver"));var G=e=>{ce(e),p(e,"next/image")},ce=e=>{var s,i,m;let t=f();if(K.default.lt(t,"11.0.0"))return;let o=(s=e.module)==null?void 0:s.rules,r=o==null?void 0:o.find(l=>typeof l!="string"&&l.test instanceof RegExp&&l.test.test("test.jpg"));!r||(r.test=/\.(apng|eot|otf|ttf|woff|woff2|cur|ani|pdf)(\?.*)?$/,o==null||o.push({test:/\.(png|jpg|jpeg|gif|webp|avif|ico|bmp|svg)$/i,issuer:{not:/\.(css|scss|sass)$/},use:[{loader:require.resolve("@storybook/nextjs/next-image-loader-stub.js"),options:{filename:(i=r.generator)==null?void 0:i.filename}}]}),o==null||o.push({test:/\.(png|jpg|jpeg|gif|webp|avif|ico|bmp|svg)$/i,issuer:/\.(css|scss|sass)$/,type:"asset/resource",generator:{filename:(m=r.generator)==null?void 0:m.filename}}))};var u=n(require("semver")),d=require("webpack");function z(e){let t=f(),o=u.default.satisfies(t,"~12"),r=u.default.satisfies(t,"~13"),s=u.default.lt(t,"12.2.0"),i=u.default.lt(t,"13.0.0");e.plugins=e.plugins??[],r||e.plugins.push(new d.IgnorePlugin({resourceRegExp:/next\/legacy\/image$/})),(!o||s)&&e.plugins.push(new d.IgnorePlugin({resourceRegExp:/next\/future\/image$/})),i&&e.plugins.push(new d.IgnorePlugin({resourceRegExp:/next\/dist\/shared\/lib\/hooks-client-context$/})),s&&e.plugins.push(new d.IgnorePlugin({resourceRegExp:/next\/dist\/shared\/lib\/app-router-context$/}))}var me=[(0,c.dirname)(require.resolve((0,c.join)("@storybook/preset-react-webpack","package.json"))),(0,c.dirname)(require.resolve((0,c.join)("@storybook/builder-webpack5","package.json")))],C={},le=async(e,t)=>{let o=await t.presets.apply("framework");return typeof o=="string"?{name:o,options:C}:typeof o>"u"?{name:require.resolve("@storybook/nextjs"),options:C}:{name:o.name,options:{...C,...o.options}}},ge=async(e,t)=>{let o=await t.presets.apply("framework");return{...e,builder:{name:(0,c.dirname)(require.resolve((0,c.join)("@storybook/builder-webpack5","package.json"))),options:typeof o=="string"?{}:o.options.builder||{}},renderer:(0,c.dirname)(require.resolve((0,c.join)("@storybook/react","package.json")))}},ue=(e=[])=>[...e,require.resolve("@storybook/nextjs/preview.js")],de=async e=>{var m,l,N;let t=(0,Q.loadPartialConfig)({...e,filename:`${(0,Y.getProjectRoot)()}/__fake__.js`}),o=t==null?void 0:t.options,r=a=>typeof a=="object"&&a!==null&&"file"in a;((m=o==null?void 0:o.presets)==null?void 0:m.find(a=>{var g;return Array.isArray(a)&&a[0]==="next/babel"||a==="next/babel"||r(a)&&((g=a.file)==null?void 0:g.request)==="next/babel"}))||(l=o==null?void 0:o.presets)==null||l.push("next/babel");let i=(N=o==null?void 0:o.presets)==null?void 0:N.filter(a=>{var g;return!(r(a)&&((g=a.file)==null?void 0:g.request)===require.resolve("@babel/preset-react"))});return{...o,presets:i,babelrc:!1,configFile:!1}},xe=async(e,t)=>{let o=await t.presets.apply("frameworkOptions"),{options:{nextConfigPath:r}={}}=o,s=await A({baseConfig:e,nextConfigPath:r,configDir:t.configDir});return z(e),O(e),B(e),q(e,s),G(e),J(e),H(e),e};0&&(module.exports={addons,babel,config,core,frameworkOptions,webpackFinal});
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 preset_exports={};__export(preset_exports,{addons:()=>addons,babel:()=>babel,config:()=>config,core:()=>core,frameworkOptions:()=>frameworkOptions,webpackFinal:()=>webpackFinal});module.exports=__toCommonJS(preset_exports);var import_path2=require("path"),import_core=require("@babel/core"),import_core_common=require("@storybook/core-common");var import_semver=__toESM(require("semver")),import_webpack2=require("webpack");var import_path=__toESM(require("path")),import_webpack=require("webpack"),import_constants=require("next/constants"),import_find_up=__toESM(require("find-up")),import_fs_extra=require("fs-extra"),import_node_url=require("url"),configureRuntimeNextjsVersionResolution=baseConfig=>{var _a;(_a=baseConfig.plugins)==null||_a.push(new import_webpack.DefinePlugin({"process.env.__NEXT_VERSION":JSON.stringify(getNextjsVersion())}))},getNextjsVersion=()=>require(scopedResolve("next/package.json")).version,findNextConfigFile=async configDir=>["mjs","js"].reduce(async(acc,ext)=>(await acc||(acc=(0,import_find_up.default)(`next.config.${ext}`,{cwd:configDir})),acc),Promise.resolve(void 0)),resolveNextConfig=async({baseConfig={},nextConfigPath,configDir})=>{let nextConfigFile=nextConfigPath||await findNextConfigFile(configDir);if(!nextConfigFile||await(0,import_fs_extra.pathExists)(nextConfigFile)===!1)return{};let nextConfigExport=await import((0,import_node_url.pathToFileURL)(nextConfigFile).href),nextConfig=typeof nextConfigExport=="function"?nextConfigExport(import_constants.PHASE_DEVELOPMENT_SERVER,{defaultConfig:baseConfig}):nextConfigExport;return nextConfig.default||nextConfig},addScopedAlias=(baseConfig,name,alias)=>{baseConfig.resolve??={},baseConfig.resolve.alias??={};let aliasConfig=baseConfig.resolve.alias,scopedAlias=scopedResolve(`${alias??name}`);Array.isArray(aliasConfig)?aliasConfig.push({name,alias:scopedAlias}):aliasConfig[name]=scopedAlias},scopedResolve=id=>{let scopedModulePath=require.resolve(id,{paths:[import_path.default.resolve()]}),beginningOfMainScriptPath=scopedModulePath.lastIndexOf(id.replace(/\//g,import_path.default.sep))+id.length;return scopedModulePath.substring(0,beginningOfMainScriptPath)};var configureConfig=async({baseConfig,nextConfigPath,configDir})=>{let nextConfig=await resolveNextConfig({baseConfig,nextConfigPath,configDir});return addScopedAlias(baseConfig,"next/config"),setupRuntimeConfig(baseConfig,nextConfig),nextConfig},version=getNextjsVersion(),setupRuntimeConfig=(baseConfig,nextConfig)=>{var _a,_b;let definePluginConfig={"process.env.__NEXT_RUNTIME_CONFIG":JSON.stringify({serverRuntimeConfig:{},publicRuntimeConfig:nextConfig.publicRuntimeConfig})},newNextLinkBehavior=(_a=nextConfig.experimental)==null?void 0:_a.newNextLinkBehavior;import_semver.default.gte(version,"13.0.0")&&import_semver.default.lt(version,"13.0.6")&&newNextLinkBehavior!==!1?definePluginConfig["process.env.__NEXT_NEW_LINK_BEHAVIOR"]=!0:definePluginConfig["process.env.__NEXT_NEW_LINK_BEHAVIOR"]=newNextLinkBehavior,(_b=baseConfig.plugins)==null||_b.push(new import_webpack2.DefinePlugin(definePluginConfig))};var import_getCssModuleLocalIdent=require("next/dist/build/webpack/config/blocks/css/loaders/getCssModuleLocalIdent"),import_file_resolve=require("next/dist/build/webpack/config/blocks/css/loaders/file-resolve"),import_semver2=__toESM(require("semver"));var configureCss=(baseConfig,nextConfig)=>{var _a,_b,_c;let rules=(_a=baseConfig.module)==null?void 0:_a.rules;rules==null||rules.forEach((rule,i)=>{typeof rule!="string"&&rule.test instanceof RegExp&&rule.test.test("test.css")&&(rules[i]={test:/\.css$/,use:["style-loader",{loader:"css-loader",options:{importLoaders:1,...getImportAndUrlCssLoaderOptions(nextConfig),modules:{auto:!0,getLocalIdent:import_getCssModuleLocalIdent.getCssModuleLocalIdent}}},"postcss-loader"]})}),rules==null||rules.push({test:/\.(scss|sass)$/,use:["style-loader",{loader:"css-loader",options:{importLoaders:3,...getImportAndUrlCssLoaderOptions(nextConfig),modules:{auto:!0,getLocalIdent:import_getCssModuleLocalIdent.getCssModuleLocalIdent}}},"postcss-loader","resolve-url-loader",{loader:"sass-loader",options:{sourceMap:!0,sassOptions:nextConfig.sassOptions,additionalData:((_b=nextConfig.sassOptions)==null?void 0:_b.prependData)||((_c=nextConfig.sassOptions)==null?void 0:_c.additionalData)}}]})},getImportAndUrlCssLoaderOptions=nextConfig=>isCssLoaderV6()?{url:{filter:getUrlResolver(nextConfig)},import:{filter:getImportResolver(nextConfig)}}:{url:getUrlResolver(nextConfig),import:getImportResolver(nextConfig)},getUrlResolver=nextConfig=>(url,resourcePath)=>{var _a;return(0,import_file_resolve.cssFileResolve)(url,resourcePath,(_a=nextConfig.experimental)==null?void 0:_a.urlImports)},getImportResolver=nextConfig=>(url,_,resourcePath)=>{var _a;return(0,import_file_resolve.cssFileResolve)(typeof url=="string"?url:url.url,resourcePath,(_a=nextConfig.experimental)==null?void 0:_a.urlImports)},isCssLoaderV6=()=>{try{let cssLoaderVersion=require(scopedResolve("css-loader/package.json")).version;return import_semver2.default.gte(cssLoaderVersion,"6.0.0")}catch{return!1}};var import_tsconfig_paths_webpack_plugin=__toESM(require("tsconfig-paths-webpack-plugin")),import_tsconfig_paths=require("tsconfig-paths"),configureImports=baseConfig=>{let configLoadResult=(0,import_tsconfig_paths.loadConfig)();configLoadResult.resultType==="failed"||!configLoadResult.baseUrl||(baseConfig.resolve??={},baseConfig.resolve.plugins??=[],baseConfig.resolve.plugins.push(new import_tsconfig_paths_webpack_plugin.default({configFile:configLoadResult.configFileAbsolutePath,extensions:[".js",".jsx",".ts",".tsx"]})))};var import_semver3=__toESM(require("semver"));var configureRouting=baseConfig=>{let routerContextPath=getRouterContextPath();addScopedAlias(baseConfig,routerContextPath)},getRouterContextPath=()=>{let version2=getNextjsVersion();return import_semver3.default.gte(version2,"11.1.0")?"next/dist/shared/lib/router-context":"next/dist/next-server/lib/router-context"};var import_semver4=__toESM(require("semver"));var configureStyledJsx=baseConfig=>{let version2=getNextjsVersion();import_semver4.default.gte(version2,"12.0.0")?addScopedAlias(baseConfig,"styled-jsx"):(addScopedAlias(baseConfig,"styled-jsx/babel"),addScopedAlias(baseConfig,"styled-jsx/css"),addScopedAlias(baseConfig,"styled-jsx/macro"),addScopedAlias(baseConfig,"styled-jsx/server"),addScopedAlias(baseConfig,"styled-jsx/style"),addScopedAlias(baseConfig,"styled-jsx/webpack"))};var import_semver5=__toESM(require("semver"));var configureImages=baseConfig=>{configureStaticImageImport(baseConfig),addScopedAlias(baseConfig,"next/image")},configureStaticImageImport=baseConfig=>{var _a,_b,_c;let version2=getNextjsVersion();if(import_semver5.default.lt(version2,"11.0.0"))return;let rules=(_a=baseConfig.module)==null?void 0:_a.rules,assetRule=rules==null?void 0:rules.find(rule=>typeof rule!="string"&&rule.test instanceof RegExp&&rule.test.test("test.jpg"));assetRule&&(assetRule.test=/\.(apng|eot|otf|ttf|woff|woff2|cur|ani|pdf)(\?.*)?$/,rules==null||rules.push({test:/\.(png|jpg|jpeg|gif|webp|avif|ico|bmp|svg)$/i,issuer:{not:/\.(css|scss|sass)$/},use:[{loader:require.resolve("@storybook/nextjs/next-image-loader-stub.js"),options:{filename:(_b=assetRule.generator)==null?void 0:_b.filename}}]}),rules==null||rules.push({test:/\.(png|jpg|jpeg|gif|webp|avif|ico|bmp|svg)$/i,issuer:/\.(css|scss|sass)$/,type:"asset/resource",generator:{filename:(_c=assetRule.generator)==null?void 0:_c.filename}}))};var import_semver6=__toESM(require("semver")),import_webpack3=require("webpack");function configureNextImport(baseConfig){let nextJSVersion=getNextjsVersion(),isNext12=import_semver6.default.satisfies(nextJSVersion,"~12"),isNext13=import_semver6.default.satisfies(nextJSVersion,"~13"),isNextVersionSmallerThan12dot2=import_semver6.default.lt(nextJSVersion,"12.2.0"),isNextVersionSmallerThan13=import_semver6.default.lt(nextJSVersion,"13.0.0");baseConfig.plugins=baseConfig.plugins??[],isNext13||baseConfig.plugins.push(new import_webpack3.IgnorePlugin({resourceRegExp:/next\/legacy\/image$/})),(!isNext12||isNextVersionSmallerThan12dot2)&&baseConfig.plugins.push(new import_webpack3.IgnorePlugin({resourceRegExp:/next\/future\/image$/})),isNextVersionSmallerThan13&&baseConfig.plugins.push(new import_webpack3.IgnorePlugin({resourceRegExp:/next\/dist\/shared\/lib\/hooks-client-context$/})),isNextVersionSmallerThan12dot2&&baseConfig.plugins.push(new import_webpack3.IgnorePlugin({resourceRegExp:/next\/dist\/shared\/lib\/app-router-context$/}))}function convertNodeToJSON(types,node){if(types.isBooleanLiteral(node)||types.isStringLiteral(node)||types.isNumericLiteral(node))return node.value;if(!(node.name==="undefined"&&!node.value))return types.isNullLiteral(node)?null:types.isObjectExpression(node)?computeProps(types,node.properties):types.isArrayExpression(node)?node.elements.reduce((acc,element)=>[...acc,...(element==null?void 0:element.type)==="SpreadElement"?convertNodeToJSON(types,element.argument):[convertNodeToJSON(types,element)]],[]):{}}function computeProps(types,props){return props.reduce((acc,prop)=>{if(prop.type==="SpreadElement")return{...acc,...convertNodeToJSON(types,prop.argument)};if(prop.type!=="ObjectMethod"){let val=convertNodeToJSON(types,prop.value);if(val!==void 0&&types.isIdentifier(prop.key))return{...acc,[prop.key.name]:val}}return acc},{})}function isDefined(value){return value!==void 0}function removeTransformedVariableDeclarations(path2,types,metas){path2.parentPath.traverse({ExportNamedDeclaration(declaratorPath){var _a;(_a=declaratorPath.parentPath)!=null&&_a.isProgram()&&metas.forEach(meta=>{types.isVariableDeclaration(declaratorPath.node.declaration)&&declaratorPath.node.declaration.declarations.length===1&&types.isVariableDeclarator(declaratorPath.node.declaration.declarations[0])&&types.isIdentifier(declaratorPath.node.declaration.declarations[0].id)&&meta.identifierName===declaratorPath.node.declaration.declarations[0].id.name&&declaratorPath.replaceWith(types.exportNamedDeclaration(null,[types.exportSpecifier(types.identifier(meta.identifierName),types.identifier(meta.identifierName))]))})},VariableDeclarator(declaratorPath){var _a;(_a=declaratorPath.parentPath.parentPath)!=null&&_a.isProgram()&&metas.some(meta=>types.isIdentifier(declaratorPath.node.id)&&meta.identifierName===declaratorPath.node.id.name)&&declaratorPath.remove()}})}function replaceImportWithParamterImport(path2,types,source,metas,filename){path2.replaceWithMultiple([...metas.map(meta=>types.importDeclaration([types.importDefaultSpecifier(types.identifier(meta.identifierName))],types.stringLiteral(`storybook-nextjs-font-loader?${JSON.stringify({source:source.value,props:meta.properties,fontFamily:meta.functionName,filename})}!${source.value}`)))])}function getVariableMetasBySpecifier(program,types,specifier){return program.node.body.map(statement=>{if(!types.isVariableDeclaration(statement)&&!types.isExportNamedDeclaration(statement))return;let exportedNamedDeclaration=!types.isVariableDeclaration(statement)&&types.isVariableDeclaration(statement.declaration)&&statement.declaration.declarations.length===1?statement.declaration.declarations[0]:null,declaration=types.isVariableDeclaration(statement)?statement.declarations[0]:exportedNamedDeclaration;if(!declaration||!types.isIdentifier(declaration.id)||!types.isCallExpression(declaration.init)||(!types.isIdentifier(declaration.init.callee)||specifier.type!=="ImportSpecifier"||specifier.imported.type!=="Identifier"||declaration.init.callee.name!==specifier.imported.name)&&(!types.isIdentifier(declaration.init.callee)||specifier.type!=="ImportDefaultSpecifier"||declaration.init.callee.name!==specifier.local.name))return;let options=declaration.init.arguments[0];if(!types.isObjectExpression(options))throw program.buildCodeFrameError("Please pass an options object to the call expression of @next/font functions");options.properties.forEach(property=>{if(types.isSpreadElement(property))throw program.buildCodeFrameError("Please do not use spread elements in the options object in @next/font function calls")});let identifierName=declaration.id.name,properties=convertNodeToJSON(types,options),functionName=declaration.init.callee.name;return{identifierName,properties,functionName}}).filter(isDefined)}function TransformFontImports({types}){return{name:"storybook-nextjs-font-imports",visitor:{ImportDeclaration(path2,state){let{node}=path2,{source}=node,{filename=""}=state;if(source.value==="@next/font/local"){let{specifiers}=node,specifier=specifiers[0];if(!path2.parentPath.isProgram())return;let program=path2.parentPath,variableMetas=getVariableMetasBySpecifier(program,types,specifier);removeTransformedVariableDeclarations(path2,types,variableMetas),replaceImportWithParamterImport(path2,types,source,variableMetas,filename)}if(source.value==="@next/font/google"){let{specifiers}=node,variableMetas=specifiers.flatMap(specifier=>{if(!path2.parentPath.isProgram())return[];let program=path2.parentPath;return getVariableMetasBySpecifier(program,types,specifier)}).filter(isDefined);removeTransformedVariableDeclarations(path2,types,variableMetas),replaceImportWithParamterImport(path2,types,source,variableMetas,filename)}}}}}function configureNextFont(baseConfig){var _a;baseConfig.plugins=[...baseConfig.plugins||[]],baseConfig.resolveLoader={...baseConfig.resolveLoader,alias:{...(_a=baseConfig.resolveLoader)==null?void 0:_a.alias,"storybook-nextjs-font-loader":require.resolve("./font/webpack/loader/storybook-nextjs-font-loader")}}}var addons=[(0,import_path2.dirname)(require.resolve((0,import_path2.join)("@storybook/preset-react-webpack","package.json"))),(0,import_path2.dirname)(require.resolve((0,import_path2.join)("@storybook/builder-webpack5","package.json")))],defaultFrameworkOptions={},frameworkOptions=async(_,options)=>{let config2=await options.presets.apply("framework");return typeof config2=="string"?{name:config2,options:defaultFrameworkOptions}:typeof config2>"u"?{name:require.resolve("@storybook/nextjs"),options:defaultFrameworkOptions}:{name:config2.name,options:{...defaultFrameworkOptions,...config2.options}}},core=async(config2,options)=>{let framework=await options.presets.apply("framework");return{...config2,builder:{name:(0,import_path2.dirname)(require.resolve((0,import_path2.join)("@storybook/builder-webpack5","package.json"))),options:typeof framework=="string"?{}:framework.options.builder||{}},renderer:(0,import_path2.dirname)(require.resolve((0,import_path2.join)("@storybook/react","package.json")))}},config=(entry=[])=>[...entry,require.resolve("@storybook/nextjs/preview.js")],babel=async baseConfig=>{var _a,_b,_c;let configPartial=(0,import_core.loadPartialConfig)({...baseConfig,filename:`${(0,import_core_common.getProjectRoot)()}/__fake__.js`}),options=configPartial==null?void 0:configPartial.options,isPresetConfigItem=preset=>typeof preset=="object"&&preset!==null&&"file"in preset;((_a=options==null?void 0:options.presets)==null?void 0:_a.find(preset=>{var _a2;return Array.isArray(preset)&&preset[0]==="next/babel"||preset==="next/babel"||isPresetConfigItem(preset)&&((_a2=preset.file)==null?void 0:_a2.request)==="next/babel"}))||(_b=options==null?void 0:options.presets)==null||_b.push("next/babel");let presets=(_c=options==null?void 0:options.presets)==null?void 0:_c.filter(preset=>{var _a2;return!(isPresetConfigItem(preset)&&((_a2=preset.file)==null?void 0:_a2.request)===require.resolve("@babel/preset-react"))}),plugins=[...(options==null?void 0:options.plugins)??[],TransformFontImports];return{...options,plugins,presets,babelrc:!1,configFile:!1}},webpackFinal=async(baseConfig,options)=>{let frameworkOptions2=await options.presets.apply("frameworkOptions"),{options:{nextConfigPath}={}}=frameworkOptions2,nextConfig=await configureConfig({baseConfig,nextConfigPath,configDir:options.configDir});return configureNextFont(baseConfig),configureNextImport(baseConfig),configureRuntimeNextjsVersionResolution(baseConfig),configureImports(baseConfig),configureCss(baseConfig,nextConfig),configureImages(baseConfig),configureRouting(baseConfig),configureStyledJsx(baseConfig),baseConfig};0&&(module.exports={addons,babel,config,core,frameworkOptions,webpackFinal});
package/dist/preset.mjs CHANGED
@@ -1,5 +1 @@
1
- import{__require}from"./chunk-LAHENP5R.mjs";import{dirname,join}from"path";import{loadPartialConfig}from"@babel/core";import{getProjectRoot}from"@storybook/core-common";import semver from"semver";import{DefinePlugin as DefinePlugin2}from"webpack";import path from"path";import{DefinePlugin}from"webpack";import{PHASE_DEVELOPMENT_SERVER}from"next/constants";import findUp from"find-up";import{pathExists}from"fs-extra";import dedent from"ts-dedent";import{pathToFileURL}from"url";var configureRuntimeNextjsVersionResolution=baseConfig=>{baseConfig.plugins?.push(new DefinePlugin({"process.env.__NEXT_VERSION":JSON.stringify(getNextjsVersion())}))},getNextjsVersion=()=>__require(scopedResolve("next/package.json")).version,findNextConfigFile=async configDir=>["mjs","js"].reduce(async(acc,ext)=>(await acc||(acc=findUp(`next.config.${ext}`,{cwd:configDir})),acc),Promise.resolve(void 0)),resolveNextConfig=async({baseConfig={},nextConfigPath,configDir})=>{let nextConfigFile=nextConfigPath||await findNextConfigFile(configDir);if(!nextConfigFile||await pathExists(nextConfigFile)===!1)throw new Error(dedent`
2
- Could not find or resolve your Next config file. Please provide the next config file path as a framework option.
3
-
4
- More info: https://github.com/storybookjs/storybook/blob/next/code/frameworks/nextjs/README.md#options
5
- `);let nextConfigExport=await import(pathToFileURL(nextConfigFile).href),nextConfig=typeof nextConfigExport=="function"?nextConfigExport(PHASE_DEVELOPMENT_SERVER,{defaultConfig:baseConfig}):nextConfigExport;return nextConfig.default||nextConfig},addScopedAlias=(baseConfig,name,alias)=>{baseConfig.resolve??={},baseConfig.resolve.alias??={};let aliasConfig=baseConfig.resolve.alias,scopedAlias=scopedResolve(`${alias??name}`);Array.isArray(aliasConfig)?aliasConfig.push({name,alias:scopedAlias}):aliasConfig[name]=scopedAlias},scopedResolve=id=>{let scopedModulePath=__require.resolve(id,{paths:[path.resolve()]}),beginningOfMainScriptPath=scopedModulePath.lastIndexOf(id.replace(/\//g,path.sep))+id.length;return scopedModulePath.substring(0,beginningOfMainScriptPath)};var configureConfig=async({baseConfig,nextConfigPath,configDir})=>{let nextConfig=await resolveNextConfig({baseConfig,nextConfigPath,configDir});return addScopedAlias(baseConfig,"next/config"),setupRuntimeConfig(baseConfig,nextConfig),nextConfig},version=getNextjsVersion(),setupRuntimeConfig=(baseConfig,nextConfig)=>{let definePluginConfig={"process.env.__NEXT_RUNTIME_CONFIG":JSON.stringify({serverRuntimeConfig:{},publicRuntimeConfig:nextConfig.publicRuntimeConfig})},newNextLinkBehavior=nextConfig.experimental?.newNextLinkBehavior;semver.gte(version,"13.0.0")&&semver.lt(version,"13.0.6")&&newNextLinkBehavior!==!1?definePluginConfig["process.env.__NEXT_NEW_LINK_BEHAVIOR"]=!0:definePluginConfig["process.env.__NEXT_NEW_LINK_BEHAVIOR"]=newNextLinkBehavior,baseConfig.plugins?.push(new DefinePlugin2(definePluginConfig))};import{getCssModuleLocalIdent}from"next/dist/build/webpack/config/blocks/css/loaders/getCssModuleLocalIdent";import{cssFileResolve}from"next/dist/build/webpack/config/blocks/css/loaders/file-resolve";import semver2 from"semver";var configureCss=(baseConfig,nextConfig)=>{let rules=baseConfig.module?.rules;rules?.forEach((rule,i)=>{typeof rule!="string"&&rule.test instanceof RegExp&&rule.test.test("test.css")&&(rules[i]={test:/\.css$/,use:["style-loader",{loader:"css-loader",options:{importLoaders:1,...getImportAndUrlCssLoaderOptions(nextConfig),modules:{auto:!0,getLocalIdent:getCssModuleLocalIdent}}},"postcss-loader"]})}),rules?.push({test:/\.(scss|sass)$/,use:["style-loader",{loader:"css-loader",options:{importLoaders:3,...getImportAndUrlCssLoaderOptions(nextConfig),modules:{auto:!0,getLocalIdent:getCssModuleLocalIdent}}},"postcss-loader","resolve-url-loader",{loader:"sass-loader",options:{sourceMap:!0,sassOptions:nextConfig.sassOptions,additionalData:nextConfig.sassOptions?.prependData||nextConfig.sassOptions?.additionalData}}]})},getImportAndUrlCssLoaderOptions=nextConfig=>isCssLoaderV6()?{url:{filter:getUrlResolver(nextConfig)},import:{filter:getImportResolver(nextConfig)}}:{url:getUrlResolver(nextConfig),import:getImportResolver(nextConfig)},getUrlResolver=nextConfig=>(url,resourcePath)=>cssFileResolve(url,resourcePath,nextConfig.experimental?.urlImports),getImportResolver=nextConfig=>(url,_,resourcePath)=>cssFileResolve(typeof url=="string"?url:url.url,resourcePath,nextConfig.experimental?.urlImports),isCssLoaderV6=()=>{try{let cssLoaderVersion=__require(scopedResolve("css-loader/package.json")).version;return semver2.gte(cssLoaderVersion,"6.0.0")}catch{return!1}};import TsconfigPathsPlugin from"tsconfig-paths-webpack-plugin";import{loadConfig}from"tsconfig-paths";var configureImports=baseConfig=>{let configLoadResult=loadConfig();configLoadResult.resultType==="failed"||!configLoadResult.baseUrl||(baseConfig.resolve??={},baseConfig.resolve.plugins??=[],baseConfig.resolve.plugins.push(new TsconfigPathsPlugin({configFile:configLoadResult.configFileAbsolutePath,extensions:[".js",".jsx",".ts",".tsx"]})))};import semver3 from"semver";var configureRouting=baseConfig=>{let routerContextPath=getRouterContextPath();addScopedAlias(baseConfig,routerContextPath)},getRouterContextPath=()=>{let version2=getNextjsVersion();return semver3.gte(version2,"11.1.0")?"next/dist/shared/lib/router-context":"next/dist/next-server/lib/router-context"};import semver4 from"semver";var configureStyledJsx=baseConfig=>{let version2=getNextjsVersion();semver4.gte(version2,"12.0.0")?addScopedAlias(baseConfig,"styled-jsx"):(addScopedAlias(baseConfig,"styled-jsx/babel"),addScopedAlias(baseConfig,"styled-jsx/css"),addScopedAlias(baseConfig,"styled-jsx/macro"),addScopedAlias(baseConfig,"styled-jsx/server"),addScopedAlias(baseConfig,"styled-jsx/style"),addScopedAlias(baseConfig,"styled-jsx/webpack"))};import semver5 from"semver";var configureImages=baseConfig=>{configureStaticImageImport(baseConfig),addScopedAlias(baseConfig,"next/image")},configureStaticImageImport=baseConfig=>{let version2=getNextjsVersion();if(semver5.lt(version2,"11.0.0"))return;let rules=baseConfig.module?.rules,assetRule=rules?.find(rule=>typeof rule!="string"&&rule.test instanceof RegExp&&rule.test.test("test.jpg"));!assetRule||(assetRule.test=/\.(apng|eot|otf|ttf|woff|woff2|cur|ani|pdf)(\?.*)?$/,rules?.push({test:/\.(png|jpg|jpeg|gif|webp|avif|ico|bmp|svg)$/i,issuer:{not:/\.(css|scss|sass)$/},use:[{loader:__require.resolve("@storybook/nextjs/next-image-loader-stub.js"),options:{filename:assetRule.generator?.filename}}]}),rules?.push({test:/\.(png|jpg|jpeg|gif|webp|avif|ico|bmp|svg)$/i,issuer:/\.(css|scss|sass)$/,type:"asset/resource",generator:{filename:assetRule.generator?.filename}}))};import semver6 from"semver";import{IgnorePlugin}from"webpack";function configureNextImport(baseConfig){let nextJSVersion=getNextjsVersion(),isNext12=semver6.satisfies(nextJSVersion,"~12"),isNext13=semver6.satisfies(nextJSVersion,"~13"),isNextVersionSmallerThan12dot2=semver6.lt(nextJSVersion,"12.2.0"),isNextVersionSmallerThan13=semver6.lt(nextJSVersion,"13.0.0");baseConfig.plugins=baseConfig.plugins??[],isNext13||baseConfig.plugins.push(new IgnorePlugin({resourceRegExp:/next\/legacy\/image$/})),(!isNext12||isNextVersionSmallerThan12dot2)&&baseConfig.plugins.push(new IgnorePlugin({resourceRegExp:/next\/future\/image$/})),isNextVersionSmallerThan13&&baseConfig.plugins.push(new IgnorePlugin({resourceRegExp:/next\/dist\/shared\/lib\/hooks-client-context$/})),isNextVersionSmallerThan12dot2&&baseConfig.plugins.push(new IgnorePlugin({resourceRegExp:/next\/dist\/shared\/lib\/app-router-context$/}))}var addons=[dirname(__require.resolve(join("@storybook/preset-react-webpack","package.json"))),dirname(__require.resolve(join("@storybook/builder-webpack5","package.json")))],defaultFrameworkOptions={},frameworkOptions=async(_,options)=>{let config2=await options.presets.apply("framework");return typeof config2=="string"?{name:config2,options:defaultFrameworkOptions}:typeof config2>"u"?{name:__require.resolve("@storybook/nextjs"),options:defaultFrameworkOptions}:{name:config2.name,options:{...defaultFrameworkOptions,...config2.options}}},core=async(config2,options)=>{let framework=await options.presets.apply("framework");return{...config2,builder:{name:dirname(__require.resolve(join("@storybook/builder-webpack5","package.json"))),options:typeof framework=="string"?{}:framework.options.builder||{}},renderer:dirname(__require.resolve(join("@storybook/react","package.json")))}},config=(entry=[])=>[...entry,__require.resolve("@storybook/nextjs/preview.js")],babel=async baseConfig=>{let options=loadPartialConfig({...baseConfig,filename:`${getProjectRoot()}/__fake__.js`})?.options,isPresetConfigItem=preset=>typeof preset=="object"&&preset!==null&&"file"in preset;options?.presets?.find(preset=>Array.isArray(preset)&&preset[0]==="next/babel"||preset==="next/babel"||isPresetConfigItem(preset)&&preset.file?.request==="next/babel")||options?.presets?.push("next/babel");let presets=options?.presets?.filter(preset=>!(isPresetConfigItem(preset)&&preset.file?.request===__require.resolve("@babel/preset-react")));return{...options,presets,babelrc:!1,configFile:!1}},webpackFinal=async(baseConfig,options)=>{let frameworkOptions2=await options.presets.apply("frameworkOptions"),{options:{nextConfigPath}={}}=frameworkOptions2,nextConfig=await configureConfig({baseConfig,nextConfigPath,configDir:options.configDir});return configureNextImport(baseConfig),configureRuntimeNextjsVersionResolution(baseConfig),configureImports(baseConfig),configureCss(baseConfig,nextConfig),configureImages(baseConfig),configureRouting(baseConfig),configureStyledJsx(baseConfig),baseConfig};export{addons,babel,config,core,frameworkOptions,webpackFinal};
1
+ import{__require}from"./chunk-4MG4OZFL.mjs";import{dirname,join}from"path";import{loadPartialConfig}from"@babel/core";import{getProjectRoot}from"@storybook/core-common";import semver from"semver";import{DefinePlugin as DefinePlugin2}from"webpack";import path from"path";import{DefinePlugin}from"webpack";import{PHASE_DEVELOPMENT_SERVER}from"next/constants";import findUp from"find-up";import{pathExists}from"fs-extra";import{pathToFileURL}from"url";var configureRuntimeNextjsVersionResolution=baseConfig=>{baseConfig.plugins?.push(new DefinePlugin({"process.env.__NEXT_VERSION":JSON.stringify(getNextjsVersion())}))},getNextjsVersion=()=>__require(scopedResolve("next/package.json")).version,findNextConfigFile=async configDir=>["mjs","js"].reduce(async(acc,ext)=>(await acc||(acc=findUp(`next.config.${ext}`,{cwd:configDir})),acc),Promise.resolve(void 0)),resolveNextConfig=async({baseConfig={},nextConfigPath,configDir})=>{let nextConfigFile=nextConfigPath||await findNextConfigFile(configDir);if(!nextConfigFile||await pathExists(nextConfigFile)===!1)return{};let nextConfigExport=await import(pathToFileURL(nextConfigFile).href),nextConfig=typeof nextConfigExport=="function"?nextConfigExport(PHASE_DEVELOPMENT_SERVER,{defaultConfig:baseConfig}):nextConfigExport;return nextConfig.default||nextConfig},addScopedAlias=(baseConfig,name,alias)=>{baseConfig.resolve??={},baseConfig.resolve.alias??={};let aliasConfig=baseConfig.resolve.alias,scopedAlias=scopedResolve(`${alias??name}`);Array.isArray(aliasConfig)?aliasConfig.push({name,alias:scopedAlias}):aliasConfig[name]=scopedAlias},scopedResolve=id=>{let scopedModulePath=__require.resolve(id,{paths:[path.resolve()]}),beginningOfMainScriptPath=scopedModulePath.lastIndexOf(id.replace(/\//g,path.sep))+id.length;return scopedModulePath.substring(0,beginningOfMainScriptPath)};var configureConfig=async({baseConfig,nextConfigPath,configDir})=>{let nextConfig=await resolveNextConfig({baseConfig,nextConfigPath,configDir});return addScopedAlias(baseConfig,"next/config"),setupRuntimeConfig(baseConfig,nextConfig),nextConfig},version=getNextjsVersion(),setupRuntimeConfig=(baseConfig,nextConfig)=>{let definePluginConfig={"process.env.__NEXT_RUNTIME_CONFIG":JSON.stringify({serverRuntimeConfig:{},publicRuntimeConfig:nextConfig.publicRuntimeConfig})},newNextLinkBehavior=nextConfig.experimental?.newNextLinkBehavior;semver.gte(version,"13.0.0")&&semver.lt(version,"13.0.6")&&newNextLinkBehavior!==!1?definePluginConfig["process.env.__NEXT_NEW_LINK_BEHAVIOR"]=!0:definePluginConfig["process.env.__NEXT_NEW_LINK_BEHAVIOR"]=newNextLinkBehavior,baseConfig.plugins?.push(new DefinePlugin2(definePluginConfig))};import{getCssModuleLocalIdent}from"next/dist/build/webpack/config/blocks/css/loaders/getCssModuleLocalIdent";import{cssFileResolve}from"next/dist/build/webpack/config/blocks/css/loaders/file-resolve";import semver2 from"semver";var configureCss=(baseConfig,nextConfig)=>{let rules=baseConfig.module?.rules;rules?.forEach((rule,i)=>{typeof rule!="string"&&rule.test instanceof RegExp&&rule.test.test("test.css")&&(rules[i]={test:/\.css$/,use:["style-loader",{loader:"css-loader",options:{importLoaders:1,...getImportAndUrlCssLoaderOptions(nextConfig),modules:{auto:!0,getLocalIdent:getCssModuleLocalIdent}}},"postcss-loader"]})}),rules?.push({test:/\.(scss|sass)$/,use:["style-loader",{loader:"css-loader",options:{importLoaders:3,...getImportAndUrlCssLoaderOptions(nextConfig),modules:{auto:!0,getLocalIdent:getCssModuleLocalIdent}}},"postcss-loader","resolve-url-loader",{loader:"sass-loader",options:{sourceMap:!0,sassOptions:nextConfig.sassOptions,additionalData:nextConfig.sassOptions?.prependData||nextConfig.sassOptions?.additionalData}}]})},getImportAndUrlCssLoaderOptions=nextConfig=>isCssLoaderV6()?{url:{filter:getUrlResolver(nextConfig)},import:{filter:getImportResolver(nextConfig)}}:{url:getUrlResolver(nextConfig),import:getImportResolver(nextConfig)},getUrlResolver=nextConfig=>(url,resourcePath)=>cssFileResolve(url,resourcePath,nextConfig.experimental?.urlImports),getImportResolver=nextConfig=>(url,_,resourcePath)=>cssFileResolve(typeof url=="string"?url:url.url,resourcePath,nextConfig.experimental?.urlImports),isCssLoaderV6=()=>{try{let cssLoaderVersion=__require(scopedResolve("css-loader/package.json")).version;return semver2.gte(cssLoaderVersion,"6.0.0")}catch{return!1}};import TsconfigPathsPlugin from"tsconfig-paths-webpack-plugin";import{loadConfig}from"tsconfig-paths";var configureImports=baseConfig=>{let configLoadResult=loadConfig();configLoadResult.resultType==="failed"||!configLoadResult.baseUrl||(baseConfig.resolve??={},baseConfig.resolve.plugins??=[],baseConfig.resolve.plugins.push(new TsconfigPathsPlugin({configFile:configLoadResult.configFileAbsolutePath,extensions:[".js",".jsx",".ts",".tsx"]})))};import semver3 from"semver";var configureRouting=baseConfig=>{let routerContextPath=getRouterContextPath();addScopedAlias(baseConfig,routerContextPath)},getRouterContextPath=()=>{let version2=getNextjsVersion();return semver3.gte(version2,"11.1.0")?"next/dist/shared/lib/router-context":"next/dist/next-server/lib/router-context"};import semver4 from"semver";var configureStyledJsx=baseConfig=>{let version2=getNextjsVersion();semver4.gte(version2,"12.0.0")?addScopedAlias(baseConfig,"styled-jsx"):(addScopedAlias(baseConfig,"styled-jsx/babel"),addScopedAlias(baseConfig,"styled-jsx/css"),addScopedAlias(baseConfig,"styled-jsx/macro"),addScopedAlias(baseConfig,"styled-jsx/server"),addScopedAlias(baseConfig,"styled-jsx/style"),addScopedAlias(baseConfig,"styled-jsx/webpack"))};import semver5 from"semver";var configureImages=baseConfig=>{configureStaticImageImport(baseConfig),addScopedAlias(baseConfig,"next/image")},configureStaticImageImport=baseConfig=>{let version2=getNextjsVersion();if(semver5.lt(version2,"11.0.0"))return;let rules=baseConfig.module?.rules,assetRule=rules?.find(rule=>typeof rule!="string"&&rule.test instanceof RegExp&&rule.test.test("test.jpg"));assetRule&&(assetRule.test=/\.(apng|eot|otf|ttf|woff|woff2|cur|ani|pdf)(\?.*)?$/,rules?.push({test:/\.(png|jpg|jpeg|gif|webp|avif|ico|bmp|svg)$/i,issuer:{not:/\.(css|scss|sass)$/},use:[{loader:__require.resolve("@storybook/nextjs/next-image-loader-stub.js"),options:{filename:assetRule.generator?.filename}}]}),rules?.push({test:/\.(png|jpg|jpeg|gif|webp|avif|ico|bmp|svg)$/i,issuer:/\.(css|scss|sass)$/,type:"asset/resource",generator:{filename:assetRule.generator?.filename}}))};import semver6 from"semver";import{IgnorePlugin}from"webpack";function configureNextImport(baseConfig){let nextJSVersion=getNextjsVersion(),isNext12=semver6.satisfies(nextJSVersion,"~12"),isNext13=semver6.satisfies(nextJSVersion,"~13"),isNextVersionSmallerThan12dot2=semver6.lt(nextJSVersion,"12.2.0"),isNextVersionSmallerThan13=semver6.lt(nextJSVersion,"13.0.0");baseConfig.plugins=baseConfig.plugins??[],isNext13||baseConfig.plugins.push(new IgnorePlugin({resourceRegExp:/next\/legacy\/image$/})),(!isNext12||isNextVersionSmallerThan12dot2)&&baseConfig.plugins.push(new IgnorePlugin({resourceRegExp:/next\/future\/image$/})),isNextVersionSmallerThan13&&baseConfig.plugins.push(new IgnorePlugin({resourceRegExp:/next\/dist\/shared\/lib\/hooks-client-context$/})),isNextVersionSmallerThan12dot2&&baseConfig.plugins.push(new IgnorePlugin({resourceRegExp:/next\/dist\/shared\/lib\/app-router-context$/}))}function convertNodeToJSON(types,node){if(types.isBooleanLiteral(node)||types.isStringLiteral(node)||types.isNumericLiteral(node))return node.value;if(!(node.name==="undefined"&&!node.value))return types.isNullLiteral(node)?null:types.isObjectExpression(node)?computeProps(types,node.properties):types.isArrayExpression(node)?node.elements.reduce((acc,element)=>[...acc,...element?.type==="SpreadElement"?convertNodeToJSON(types,element.argument):[convertNodeToJSON(types,element)]],[]):{}}function computeProps(types,props){return props.reduce((acc,prop)=>{if(prop.type==="SpreadElement")return{...acc,...convertNodeToJSON(types,prop.argument)};if(prop.type!=="ObjectMethod"){let val=convertNodeToJSON(types,prop.value);if(val!==void 0&&types.isIdentifier(prop.key))return{...acc,[prop.key.name]:val}}return acc},{})}function isDefined(value){return value!==void 0}function removeTransformedVariableDeclarations(path2,types,metas){path2.parentPath.traverse({ExportNamedDeclaration(declaratorPath){declaratorPath.parentPath?.isProgram()&&metas.forEach(meta=>{types.isVariableDeclaration(declaratorPath.node.declaration)&&declaratorPath.node.declaration.declarations.length===1&&types.isVariableDeclarator(declaratorPath.node.declaration.declarations[0])&&types.isIdentifier(declaratorPath.node.declaration.declarations[0].id)&&meta.identifierName===declaratorPath.node.declaration.declarations[0].id.name&&declaratorPath.replaceWith(types.exportNamedDeclaration(null,[types.exportSpecifier(types.identifier(meta.identifierName),types.identifier(meta.identifierName))]))})},VariableDeclarator(declaratorPath){declaratorPath.parentPath.parentPath?.isProgram()&&metas.some(meta=>types.isIdentifier(declaratorPath.node.id)&&meta.identifierName===declaratorPath.node.id.name)&&declaratorPath.remove()}})}function replaceImportWithParamterImport(path2,types,source,metas,filename){path2.replaceWithMultiple([...metas.map(meta=>types.importDeclaration([types.importDefaultSpecifier(types.identifier(meta.identifierName))],types.stringLiteral(`storybook-nextjs-font-loader?${JSON.stringify({source:source.value,props:meta.properties,fontFamily:meta.functionName,filename})}!${source.value}`)))])}function getVariableMetasBySpecifier(program,types,specifier){return program.node.body.map(statement=>{if(!types.isVariableDeclaration(statement)&&!types.isExportNamedDeclaration(statement))return;let exportedNamedDeclaration=!types.isVariableDeclaration(statement)&&types.isVariableDeclaration(statement.declaration)&&statement.declaration.declarations.length===1?statement.declaration.declarations[0]:null,declaration=types.isVariableDeclaration(statement)?statement.declarations[0]:exportedNamedDeclaration;if(!declaration||!types.isIdentifier(declaration.id)||!types.isCallExpression(declaration.init)||(!types.isIdentifier(declaration.init.callee)||specifier.type!=="ImportSpecifier"||specifier.imported.type!=="Identifier"||declaration.init.callee.name!==specifier.imported.name)&&(!types.isIdentifier(declaration.init.callee)||specifier.type!=="ImportDefaultSpecifier"||declaration.init.callee.name!==specifier.local.name))return;let options=declaration.init.arguments[0];if(!types.isObjectExpression(options))throw program.buildCodeFrameError("Please pass an options object to the call expression of @next/font functions");options.properties.forEach(property=>{if(types.isSpreadElement(property))throw program.buildCodeFrameError("Please do not use spread elements in the options object in @next/font function calls")});let identifierName=declaration.id.name,properties=convertNodeToJSON(types,options),functionName=declaration.init.callee.name;return{identifierName,properties,functionName}}).filter(isDefined)}function TransformFontImports({types}){return{name:"storybook-nextjs-font-imports",visitor:{ImportDeclaration(path2,state){let{node}=path2,{source}=node,{filename=""}=state;if(source.value==="@next/font/local"){let{specifiers}=node,specifier=specifiers[0];if(!path2.parentPath.isProgram())return;let program=path2.parentPath,variableMetas=getVariableMetasBySpecifier(program,types,specifier);removeTransformedVariableDeclarations(path2,types,variableMetas),replaceImportWithParamterImport(path2,types,source,variableMetas,filename)}if(source.value==="@next/font/google"){let{specifiers}=node,variableMetas=specifiers.flatMap(specifier=>{if(!path2.parentPath.isProgram())return[];let program=path2.parentPath;return getVariableMetasBySpecifier(program,types,specifier)}).filter(isDefined);removeTransformedVariableDeclarations(path2,types,variableMetas),replaceImportWithParamterImport(path2,types,source,variableMetas,filename)}}}}}function configureNextFont(baseConfig){baseConfig.plugins=[...baseConfig.plugins||[]],baseConfig.resolveLoader={...baseConfig.resolveLoader,alias:{...baseConfig.resolveLoader?.alias,"storybook-nextjs-font-loader":__require.resolve("./font/webpack/loader/storybook-nextjs-font-loader")}}}var addons=[dirname(__require.resolve(join("@storybook/preset-react-webpack","package.json"))),dirname(__require.resolve(join("@storybook/builder-webpack5","package.json")))],defaultFrameworkOptions={},frameworkOptions=async(_,options)=>{let config2=await options.presets.apply("framework");return typeof config2=="string"?{name:config2,options:defaultFrameworkOptions}:typeof config2>"u"?{name:__require.resolve("@storybook/nextjs"),options:defaultFrameworkOptions}:{name:config2.name,options:{...defaultFrameworkOptions,...config2.options}}},core=async(config2,options)=>{let framework=await options.presets.apply("framework");return{...config2,builder:{name:dirname(__require.resolve(join("@storybook/builder-webpack5","package.json"))),options:typeof framework=="string"?{}:framework.options.builder||{}},renderer:dirname(__require.resolve(join("@storybook/react","package.json")))}},config=(entry=[])=>[...entry,__require.resolve("@storybook/nextjs/preview.js")],babel=async baseConfig=>{let options=loadPartialConfig({...baseConfig,filename:`${getProjectRoot()}/__fake__.js`})?.options,isPresetConfigItem=preset=>typeof preset=="object"&&preset!==null&&"file"in preset;options?.presets?.find(preset=>Array.isArray(preset)&&preset[0]==="next/babel"||preset==="next/babel"||isPresetConfigItem(preset)&&preset.file?.request==="next/babel")||options?.presets?.push("next/babel");let presets=options?.presets?.filter(preset=>!(isPresetConfigItem(preset)&&preset.file?.request===__require.resolve("@babel/preset-react"))),plugins=[...options?.plugins??[],TransformFontImports];return{...options,plugins,presets,babelrc:!1,configFile:!1}},webpackFinal=async(baseConfig,options)=>{let frameworkOptions2=await options.presets.apply("frameworkOptions"),{options:{nextConfigPath}={}}=frameworkOptions2,nextConfig=await configureConfig({baseConfig,nextConfigPath,configDir:options.configDir});return configureNextFont(baseConfig),configureNextImport(baseConfig),configureRuntimeNextjsVersionResolution(baseConfig),configureImports(baseConfig),configureCss(baseConfig,nextConfig),configureImages(baseConfig),configureRouting(baseConfig),configureStyledJsx(baseConfig),baseConfig};export{addons,babel,config,core,frameworkOptions,webpackFinal};