@storybook/nextjs 9.2.0-alpha.3 → 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.
Files changed (85) hide show
  1. package/README.md +3 -1
  2. package/dist/_browser-chunks/chunk-I5RFHXDS.js +40 -0
  3. package/dist/_browser-chunks/chunk-JOMP7DUK.js +261 -0
  4. package/dist/_browser-chunks/chunk-L5NVL7MD.js +37 -0
  5. package/dist/_browser-chunks/react-18-G7Q4PNHD.js +71 -0
  6. package/dist/_node-chunks/chunk-24UYJEDD.js +74 -0
  7. package/dist/_node-chunks/chunk-EZEBG77A.js +88 -0
  8. package/dist/_node-chunks/chunk-WCSGFZKZ.js +17 -0
  9. package/dist/_node-chunks/chunk-YMVPQWBH.js +167 -0
  10. package/dist/_node-chunks/configureNextFont-HBRWHAUG.js +36 -0
  11. package/dist/_node-chunks/loader-KXTZ5PJ5.js +51 -0
  12. package/dist/_node-chunks/loader-Z4IXWF5M.js +64 -0
  13. package/dist/_node-chunks/utils-4LRBHVQD.js +31 -0
  14. package/dist/_node-chunks/webpack-6HAXGE7X.js +38 -0
  15. package/dist/_node-chunks/webpack-AGNCA7HZ.js +77 -0
  16. package/dist/_node-chunks/webpack-CXSD35E6.js +30 -0
  17. package/dist/_node-chunks/webpack-EWT6TRQB.js +26 -0
  18. package/dist/_node-chunks/webpack-K2R3GUFU.js +29 -0
  19. package/dist/_node-chunks/webpack-PD7PIB6X.js +43 -0
  20. package/dist/_node-chunks/webpack-QFTZE3CE.js +27 -0
  21. package/dist/_node-chunks/webpack-SWQY6JJY.js +107 -0
  22. package/dist/compatibility/draft-mode.compat.js +7 -1
  23. package/dist/export-mocks/cache/index.d.ts +309 -1
  24. package/dist/export-mocks/cache/index.js +22 -1
  25. package/dist/export-mocks/headers/index.d.ts +309 -1
  26. package/dist/export-mocks/headers/index.js +77 -1
  27. package/dist/export-mocks/index.js +20 -1
  28. package/dist/export-mocks/navigation/index.js +88 -1
  29. package/dist/export-mocks/router/index.d.ts +2 -2
  30. package/dist/export-mocks/router/index.js +97 -1
  31. package/dist/font/webpack/loader/storybook-nextjs-font-loader.js +201 -14
  32. package/dist/image-context.js +8 -1
  33. package/dist/images/next-image.js +35 -1
  34. package/dist/images/next-legacy-image.js +21 -1
  35. package/dist/index.d.ts +53 -8
  36. package/dist/index.js +20237 -45
  37. package/dist/next-image-loader-stub.js +33 -1
  38. package/dist/node/index.d.ts +27 -6
  39. package/dist/node/index.js +23 -1
  40. package/dist/preset.js +830 -1
  41. package/dist/preview.d.ts +3 -18
  42. package/dist/preview.d.tsx +18 -0
  43. package/dist/preview.js +11 -1
  44. package/dist/rsc/server-only.js +7 -1
  45. package/dist/swc/next-swc-loader-patch.js +136 -1
  46. package/package.json +41 -122
  47. package/preset.js +1 -1
  48. package/template/cli/js/Configure.mdx +11 -11
  49. package/template/cli/ts/Configure.mdx +11 -11
  50. package/dist/chunk-2TZKD6A5.mjs +0 -20
  51. package/dist/chunk-ETFXNGLC.mjs +0 -3
  52. package/dist/chunk-L66KIASX.mjs +0 -3
  53. package/dist/chunk-NQ32RFK2.mjs +0 -6
  54. package/dist/compatibility/draft-mode.compat.d.ts +0 -1
  55. package/dist/compatibility/draft-mode.compat.mjs +0 -2
  56. package/dist/export-mocks/cache/index.mjs +0 -10
  57. package/dist/export-mocks/headers/index.mjs +0 -12
  58. package/dist/export-mocks/index.d.ts +0 -7
  59. package/dist/export-mocks/index.mjs +0 -11
  60. package/dist/export-mocks/navigation/index.mjs +0 -11
  61. package/dist/export-mocks/router/index.mjs +0 -10
  62. package/dist/font/webpack/loader/storybook-nextjs-font-loader.d.ts +0 -3
  63. package/dist/font/webpack/loader/storybook-nextjs-font-loader.mjs +0 -56
  64. package/dist/image-context.d.ts +0 -13
  65. package/dist/image-context.mjs +0 -6
  66. package/dist/images/decorator.d.ts +0 -6
  67. package/dist/images/decorator.js +0 -1
  68. package/dist/images/decorator.mjs +0 -2
  69. package/dist/images/next-image.d.ts +0 -28
  70. package/dist/images/next-image.mjs +0 -9
  71. package/dist/images/next-legacy-image.d.ts +0 -6
  72. package/dist/images/next-legacy-image.mjs +0 -9
  73. package/dist/index.d-ff220430.d.ts +0 -310
  74. package/dist/index.mjs +0 -58
  75. package/dist/next-image-loader-stub.d.ts +0 -10
  76. package/dist/next-image-loader-stub.mjs +0 -7
  77. package/dist/node/index.mjs +0 -5
  78. package/dist/preset.d.ts +0 -14
  79. package/dist/preview.mjs +0 -3
  80. package/dist/react-18-WSPZ3BUV.mjs +0 -7
  81. package/dist/rsc/server-only.d.ts +0 -3
  82. package/dist/rsc/server-only.mjs +0 -5
  83. package/dist/swc/next-swc-loader-patch.d.ts +0 -21
  84. package/dist/swc/next-swc-loader-patch.mjs +0 -8
  85. package/dist/types-f6ea2c09.d.ts +0 -54
package/dist/preset.js CHANGED
@@ -1 +1,830 @@
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 __esm=(fn,res)=>function(){return fn&&(res=(0,fn[__getOwnPropNames(fn)[0]])(fn=0)),res};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 jsx_pragma_exports={};__export(jsx_pragma_exports,{default:()=>jsxPragma});function jsxPragma({types:t}){return{inherits:import_plugin_syntax_jsx.default,visitor:{JSXElement(_path,state){state.set("jsx",!0)},JSXFragment(_path,state){state.set("jsx",!0)},Program:{exit(path2,state){if(state.get("jsx")){let pragma=t.identifier(state.opts.pragma),importAs=pragma,existingBinding=state.opts.reuseImport!==!1&&state.opts.importAs&&path2.scope.getBinding(state.opts.importAs);if(state.opts.property){state.opts.importAs?importAs=t.identifier(state.opts.importAs):importAs=path2.scope.generateUidIdentifier("pragma");let mapping3=t.variableDeclaration("var",[t.variableDeclarator(pragma,t.memberExpression(importAs,t.identifier(state.opts.property)))]),newPath;existingBinding&&t.isVariableDeclarator(existingBinding.path.node)&&t.isCallExpression(existingBinding.path.node.init)&&t.isIdentifier(existingBinding.path.node.init.callee)&&existingBinding.path.node.init.callee.name==="require"?[newPath]=existingBinding.path.parentPath.insertAfter(mapping3):[newPath]=path2.unshiftContainer("body",mapping3);for(let declar of newPath.get("declarations")){let kind=["var","let","const"].find(k=>newPath.node.kind===k)||"const";path2.scope.registerBinding(kind,declar)}}if(!existingBinding){let importSpecifier=t.importDeclaration([state.opts.import?t.importSpecifier(importAs,t.identifier(state.opts.import)):state.opts.importNamespace?t.importNamespaceSpecifier(importAs):t.importDefaultSpecifier(importAs)],t.stringLiteral(state.opts.module||"react")),[newPath]=path2.unshiftContainer("body",importSpecifier);for(let specifier of newPath.get("specifiers"))path2.scope.registerBinding("module",specifier)}}}}}}}var import_plugin_syntax_jsx,init_jsx_pragma=__esm({"src/babel/plugins/jsx-pragma.ts"(){"use strict";import_plugin_syntax_jsx=__toESM(require("next/dist/compiled/babel/plugin-syntax-jsx"))}});var optimize_hook_destructuring_exports={};__export(optimize_hook_destructuring_exports,{default:()=>optimizeHookDestructuring});function optimizeHookDestructuring({types:t}){let visitor={CallExpression(path2,state){let{onlyBuiltIns}=state.opts,libs=state.opts.lib&&(state.opts.lib===!0?["react","preact/hooks"]:[].concat(state.opts.lib));if(!t.isVariableDeclarator(path2.parent)||!t.isArrayPattern(path2.parent.id))return;let hookName=path2.node.callee.name;if(libs){let binding=path2.scope.getBinding(hookName);if(!binding||binding.kind!=="module")return;let specifier=binding.path.parent.source.value;if(!libs.some(lib=>lib===specifier))return}(onlyBuiltIns?isBuiltInHook:isHook).test(hookName)&&(path2.parent.id=t.objectPattern(path2.parent.id.elements.reduce((patterns,element,i)=>element===null?patterns:patterns.concat(t.objectProperty(t.numericLiteral(i),element)),[])))}};return{name:"optimize-hook-destructuring",visitor:{Program(path2,state){path2.traverse(visitor,state)}}}}var isHook,isBuiltInHook,init_optimize_hook_destructuring=__esm({"src/babel/plugins/optimize-hook-destructuring.ts"(){"use strict";isHook=/^use[A-Z]/,isBuiltInHook=/^use(Callback|Context|DebugValue|Effect|ImperativeHandle|LayoutEffect|Memo|Reducer|Ref|State)$/}});var react_loadable_plugin_exports={};__export(react_loadable_plugin_exports,{default:()=>react_loadable_plugin_default});function react_loadable_plugin_default({types:t}){return{visitor:{ImportDeclaration(path2,state){if(path2.node.source.value!=="next/dynamic")return;let defaultSpecifier=path2.get("specifiers").find(specifier=>specifier.isImportDefaultSpecifier());if(!defaultSpecifier)return;let bindingName=defaultSpecifier.node.local.name,binding=path2.scope.getBinding(bindingName);binding&&binding.referencePaths.forEach(refPath=>{let callExpression=refPath.parentPath;if(callExpression.isMemberExpression()&&callExpression.node.computed===!1){let property=callExpression.get("property");!Array.isArray(property)&&property.isIdentifier({name:"Map"})&&(callExpression=callExpression.parentPath)}if(!callExpression.isCallExpression())return;let callExpression_=callExpression,args=callExpression_.get("arguments");if(args.length>2)throw callExpression_.buildCodeFrameError("next/dynamic only accepts 2 arguments");if(!args[0])return;let loader,options;if(args[0].isObjectExpression()?options=args[0]:(args[1]||callExpression_.node.arguments.push(t.objectExpression([])),args=callExpression_.get("arguments"),loader=args[0],options=args[1]),!options.isObjectExpression())return;let properties=options.get("properties"),propertiesMap={};if(properties.forEach(property=>{let key=property.get("key");propertiesMap[key.node.name]=property}),propertiesMap.loadableGenerated||(propertiesMap.loader&&(loader=propertiesMap.loader.get("value")),propertiesMap.modules&&(loader=propertiesMap.modules.get("value")),!loader||Array.isArray(loader)))return;let dynamicImports=[],dynamicKeys=[];if(propertiesMap.ssr){let ssr=propertiesMap.ssr.get("value"),nodePath=Array.isArray(ssr)?void 0:ssr;nodePath&&nodePath.node.type==="BooleanLiteral"&&nodePath.node.value===!1&&loader&&state.file.opts.caller?.isServer&&loader.replaceWith(t.arrowFunctionExpression([],t.nullLiteral(),!0))}if(loader.traverse({Import(importPath){let importArguments=importPath.parentPath.get("arguments");if(!Array.isArray(importArguments))return;let{node}=importArguments[0];dynamicImports.push(node),dynamicKeys.push(t.binaryExpression("+",t.stringLiteral(`${state.file.opts.caller?.pagesDir?(0,import_node_path.relative)(state.file.opts.caller.pagesDir,state.file.opts.filename):state.file.opts.filename} -> `),node))}}),!!dynamicImports.length&&(options.node.properties.push(t.objectProperty(t.identifier("loadableGenerated"),t.objectExpression(state.file.opts.caller?.isDev||state.file.opts.caller?.isServer?[t.objectProperty(t.identifier("modules"),t.arrayExpression(dynamicKeys))]:[t.objectProperty(t.identifier("webpack"),t.arrowFunctionExpression([],t.arrayExpression(dynamicImports.map(dynamicImport=>t.callExpression(t.memberExpression(t.identifier("require"),t.identifier("resolveWeak")),[dynamicImport])))))]))),loader.isCallExpression())){let arrowFunction=t.arrowFunctionExpression([],loader.node);loader.replaceWith(arrowFunction)}})}}}}var import_node_path,init_react_loadable_plugin=__esm({"src/babel/plugins/react-loadable-plugin.ts"(){"use strict";import_node_path=require("path")}});var amp_attributes_exports={};__export(amp_attributes_exports,{default:()=>AmpAttributePatcher});function AmpAttributePatcher(){return{visitor:{JSXOpeningElement(path2){let openingElement=path2.node,{name,attributes}=openingElement;if(name&&name.type==="JSXIdentifier"&&name.name.startsWith("amp-"))for(let attribute of attributes)attribute.type==="JSXAttribute"&&attribute.name.name==="className"&&(attribute.name.name="class")}}}}var init_amp_attributes=__esm({"src/babel/plugins/amp-attributes.ts"(){"use strict"}});var utils_exports={};__export(utils_exports,{addScopedAlias:()=>addScopedAlias,configureRuntimeNextjsVersionResolution:()=>configureRuntimeNextjsVersionResolution,getNextjsVersion:()=>getNextjsVersion,getNodeModulesExcludeRegex:()=>getNodeModulesExcludeRegex,resolveNextConfig:()=>resolveNextConfig,scopedResolve:()=>scopedResolve,setAlias:()=>setAlias});function setAlias(baseConfig,name,alias){baseConfig.resolve??={},baseConfig.resolve.alias??={};let aliasConfig=baseConfig.resolve.alias;Array.isArray(aliasConfig)?aliasConfig.push({name,alias}):aliasConfig[name]=alias}function getNodeModulesExcludeRegex(transpilePackages){if(!transpilePackages||transpilePackages.length===0)return/node_modules/;let escaped=transpilePackages.map(pkg=>pkg.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|");return new RegExp(`node_modules/(?!(${escaped})/)`)}var import_node_path3,import_common,import_constants,import_config,import_webpack,configureRuntimeNextjsVersionResolution,getNextjsVersion,resolveNextConfig,addScopedAlias,scopedResolve,init_utils=__esm({"src/utils.ts"(){"use strict";import_node_path3=require("path"),import_common=require("storybook/internal/common"),import_constants=require("next/constants"),import_config=__toESM(require("next/dist/server/config")),import_webpack=require("webpack"),configureRuntimeNextjsVersionResolution=baseConfig=>{baseConfig.plugins?.push(new import_webpack.DefinePlugin({"process.env.__NEXT_VERSION":JSON.stringify(getNextjsVersion())}))},getNextjsVersion=()=>require(scopedResolve("next/package.json")).version,resolveNextConfig=async({nextConfigPath})=>{let dir=nextConfigPath?(0,import_node_path3.dirname)(nextConfigPath):(0,import_common.getProjectRoot)();return(0,import_config.default)(import_constants.PHASE_DEVELOPMENT_SERVER,dir,void 0)};addScopedAlias=(baseConfig,name,alias)=>{let scopedAlias=scopedResolve(`${alias??name}`);setAlias(baseConfig,name,scopedAlias)},scopedResolve=id=>{let scopedModulePath=require.resolve(id),idWithNativePathSep=id.replace(/\//g,import_node_path3.sep);if(scopedModulePath.endsWith(idWithNativePathSep))return scopedModulePath;let beginningOfMainScriptPath=scopedModulePath.lastIndexOf(idWithNativePathSep)+id.length;return scopedModulePath.substring(0,beginningOfMainScriptPath)}}});var configureNextFont_exports={};__export(configureNextFont_exports,{configureNextFont:()=>configureNextFont});function configureNextFont(baseConfig,isSWC){let fontLoaderPath=require.resolve("@storybook/nextjs/font/webpack/loader/storybook-nextjs-font-loader");isSWC?baseConfig.module?.rules?.push({test:/next(\\|\/|\\\\).*(\\|\/|\\\\)target\.css$/,loader:fontLoaderPath}):baseConfig.resolveLoader={...baseConfig.resolveLoader,alias:{...baseConfig.resolveLoader?.alias,"storybook-nextjs-font-loader":fontLoaderPath}}}var init_configureNextFont=__esm({"src/font/webpack/configureNextFont.ts"(){"use strict"}});var webpack_exports={};__export(webpack_exports,{configureImports:()=>configureImports});var import_tsconfig_paths,import_tsconfig_paths_webpack_plugin,configureImports,init_webpack=__esm({"src/imports/webpack.ts"(){"use strict";import_tsconfig_paths=require("tsconfig-paths"),import_tsconfig_paths_webpack_plugin=__toESM(require("tsconfig-paths-webpack-plugin")),configureImports=({baseConfig,configDir})=>{let configLoadResult=(0,import_tsconfig_paths.loadConfig)(configDir);configLoadResult.resultType!=="failed"&&(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 webpack_exports2={};__export(webpack_exports2,{configureCss:()=>configureCss});var import_file_resolve,import_getCssModuleLocalIdent,import_semver,configureCss,getImportAndUrlCssLoaderOptions,getUrlResolver,getImportResolver,isCssLoaderV6,init_webpack2=__esm({"src/css/webpack.ts"(){"use strict";import_file_resolve=require("next/dist/build/webpack/config/blocks/css/loaders/file-resolve"),import_getCssModuleLocalIdent=require("next/dist/build/webpack/config/blocks/css/loaders/getCssModuleLocalIdent"),import_semver=__toESM(require("semver"));init_utils();configureCss=(baseConfig,nextConfig)=>{let rules=baseConfig.module?.rules;rules?.forEach((rule,i)=>{rule&&typeof rule!="string"&&rule.test instanceof RegExp&&rule.test.test("test.css")&&(rules[i]={test:/\.css$/,use:[require.resolve("style-loader"),{loader:require.resolve("css-loader"),options:{importLoaders:1,...getImportAndUrlCssLoaderOptions(nextConfig),modules:{auto:!0,getLocalIdent:import_getCssModuleLocalIdent.getCssModuleLocalIdent}}},require.resolve("postcss-loader")],exclude:/next(\\|\/|\\\\).*(\\|\/|\\\\)target\.css$/})}),rules?.push({test:/\.(scss|sass)$/,use:[require.resolve("style-loader"),{loader:require.resolve("css-loader"),options:{importLoaders:3,...getImportAndUrlCssLoaderOptions(nextConfig),modules:{auto:!0,getLocalIdent:import_getCssModuleLocalIdent.getCssModuleLocalIdent}}},require.resolve("postcss-loader"),require.resolve("resolve-url-loader"),{loader:require.resolve("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)=>(0,import_file_resolve.cssFileResolve)(url,resourcePath,nextConfig.experimental?.urlImports),getImportResolver=nextConfig=>(url,_,resourcePath)=>(0,import_file_resolve.cssFileResolve)(typeof url=="string"?url:url.url,resourcePath,nextConfig.experimental?.urlImports),isCssLoaderV6=()=>{try{let cssLoaderVersion=require(scopedResolve("css-loader/package.json")).version;return import_semver.default.gte(cssLoaderVersion,"6.0.0")}catch{return!1}}}});var webpack_exports3={};__export(webpack_exports3,{configureImages:()=>configureImages});var import_node_path4,import_semver2,configureImages,fallbackFilename,configureImageDefaults,configureStaticImageImport,init_webpack3=__esm({"src/images/webpack.ts"(){"use strict";import_node_path4=require("path"),import_semver2=__toESM(require("semver"));init_utils();configureImages=(baseConfig,nextConfig)=>{configureStaticImageImport(baseConfig,nextConfig),configureImageDefaults(baseConfig)},fallbackFilename="static/media/[path][name][ext]",configureImageDefaults=baseConfig=>{let version=getNextjsVersion(),resolve=baseConfig.resolve??{};resolve.alias={...resolve.alias,"sb-original/next/image":require.resolve("next/image"),"next/image":(0,import_node_path4.resolve)(__dirname,"./images/next-image")},import_semver2.default.satisfies(version,">=13.0.0")&&(resolve.alias={...resolve.alias,"sb-original/next/legacy/image":require.resolve("next/legacy/image"),"next/legacy/image":(0,import_node_path4.resolve)(__dirname,"./images/next-legacy-image")})},configureStaticImageImport=(baseConfig,nextConfig)=>{let version=getNextjsVersion(),rules=baseConfig.module?.rules,assetRule=rules?.find(rule=>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??fallbackFilename,nextConfig}}]}),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??fallbackFilename}}))}}});var webpack_exports4={};__export(webpack_exports4,{configureStyledJsx:()=>configureStyledJsx});var configureStyledJsx,init_webpack4=__esm({"src/styledJsx/webpack.ts"(){"use strict";init_utils();configureStyledJsx=baseConfig=>{addScopedAlias(baseConfig,"styled-jsx")}}});var webpack_exports5={};__export(webpack_exports5,{configureNodePolyfills:()=>configureNodePolyfills});var import_node_polyfill_webpack_plugin,configureNodePolyfills,init_webpack5=__esm({"src/nodePolyfills/webpack.ts"(){"use strict";import_node_polyfill_webpack_plugin=__toESM(require("node-polyfill-webpack-plugin")),configureNodePolyfills=baseConfig=>(baseConfig.plugins=[...baseConfig.plugins||[],new import_node_polyfill_webpack_plugin.default],baseConfig.resolve={...baseConfig.resolve,fallback:{fs:!1}},baseConfig)}});var import_semver3,mapping,getCompatibilityAliases,configureCompatibilityAliases,init_compatibility_map=__esm({"src/compatibility/compatibility-map.ts"(){"use strict";import_semver3=__toESM(require("semver"));init_utils();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=>{import_semver3.default.intersects(version,key)&&Object.assign(result,mapping[key])}),result},configureCompatibilityAliases=baseConfig=>{let aliases=getCompatibilityAliases();Object.entries(aliases).forEach(([name,alias])=>{typeof alias=="string"?addScopedAlias(baseConfig,name,alias):setAlias(baseConfig,name,alias)})}}});var import_node_path5,mapping2,getPackageAliases,configureNextExportMocks,init_webpack6=__esm({"src/export-mocks/webpack.ts"(){"use strict";import_node_path5=require("path");init_compatibility_map();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=(0,import_node_path5.dirname)(require.resolve("@storybook/nextjs/package.json")),getFullPath=path2=>path2.startsWith("next")?path2:(0,import_node_path5.join)(packageLocation,path2.replace("@storybook/nextjs",""));return Object.fromEntries(Object.entries(mapping2).map(([originalPath,aliasedPath])=>[originalPath,typeof aliasedPath=="string"?getFullPath(`${aliasedPath}.${extension}`):aliasedPath]))},configureNextExportMocks=baseConfig=>{let resolve=baseConfig.resolve??{};resolve.alias={...resolve.alias,...getPackageAliases({useESM:!0})}}}});var webpack_exports6={};__export(webpack_exports6,{configureAliases:()=>configureAliases});var import_path,configureAliases,init_webpack7=__esm({"src/aliases/webpack.ts"(){"use strict";import_path=__toESM(require("path"));init_compatibility_map();init_webpack6();configureAliases=baseConfig=>{configureNextExportMocks(baseConfig),configureCompatibilityAliases(baseConfig),baseConfig.resolve={...baseConfig.resolve??{},alias:{...baseConfig.resolve?.alias??{},"@opentelemetry/api":"next/dist/compiled/@opentelemetry/api",next:import_path.default.dirname(require.resolve("next/package.json"))}},baseConfig.ignoreWarnings=[...baseConfig.ignoreWarnings??[],warning=>warning.message.includes("export 'draftMode'")&&warning.message.includes("next/dist/server/request/headers")]}}});var webpack_exports7={};__export(webpack_exports7,{configureFastRefresh:()=>configureFastRefresh});var import_react_refresh_webpack_plugin,configureFastRefresh,init_webpack8=__esm({"src/fastRefresh/webpack.ts"(){"use strict";import_react_refresh_webpack_plugin=__toESM(require("@pmmmwh/react-refresh-webpack-plugin")),configureFastRefresh=baseConfig=>{baseConfig.plugins=[...baseConfig.plugins??[],new import_react_refresh_webpack_plugin.default({overlay:!1})]}}});var webpack_exports8={};__export(webpack_exports8,{configureRSC:()=>configureRSC});var configureRSC,init_webpack9=__esm({"src/rsc/webpack.ts"(){"use strict";configureRSC=baseConfig=>{let resolve=baseConfig.resolve??{};resolve.alias={...resolve.alias,"server-only$":require.resolve("./rsc/server-only.js")}}}});var loader_exports={};__export(loader_exports,{configureSWCLoader:()=>configureSWCLoader});var import_node_path6,import_common2,import_builder_webpack5,import_load_jsconfig,configureSWCLoader,init_loader=__esm({"src/swc/loader.ts"(){"use strict";import_node_path6=require("path"),import_common2=require("storybook/internal/common"),import_builder_webpack5=require("@storybook/builder-webpack5"),import_load_jsconfig=__toESM(require("next/dist/build/load-jsconfig"));init_utils();configureSWCLoader=async(baseConfig,options,nextConfig)=>{let isDevelopment=options.configType!=="PRODUCTION",{virtualModules}=await(0,import_builder_webpack5.getVirtualModules)(options),projectRoot=(0,import_common2.getProjectRoot)(),{jsConfig}=await(0,import_load_jsconfig.default)(projectRoot,nextConfig),rawRule=baseConfig.module?.rules?.find(rule=>typeof rule=="object"&&rule?.resourceQuery?.toString()==="/raw/");rawRule&&typeof rawRule=="object"&&(rawRule.exclude=/^__barrel_optimize__/);let transpilePackages=nextConfig.transpilePackages??[];baseConfig.module?.rules?.push({test:/\.((c|m)?(j|t)sx?)$/,include:[projectRoot],exclude:[getNodeModulesExcludeRegex(transpilePackages),...Object.keys(virtualModules)],use:{loader:require.resolve("./swc/next-swc-loader-patch.js"),options:{isServer:!1,rootDir:projectRoot,pagesDir:`${projectRoot}/pages`,appDir:`${projectRoot}/apps`,hasReactRefresh:isDevelopment,jsConfig,nextConfig,supportedBrowsers:require("next/dist/build/utils").getSupportedBrowsers(projectRoot,isDevelopment),swcCacheDir:(0,import_node_path6.join)(projectRoot,nextConfig?.distDir??".next","cache","swc"),bundleTarget:"default"}}})}}});var loader_exports2={};__export(loader_exports2,{configureBabelLoader:()=>configureBabelLoader});var import_common3,import_builder_webpack52,configureBabelLoader,init_loader2=__esm({"src/babel/loader.ts"(){"use strict";import_common3=require("storybook/internal/common"),import_builder_webpack52=require("@storybook/builder-webpack5");init_utils();configureBabelLoader=async(baseConfig,options,nextConfig)=>{let{virtualModules}=await(0,import_builder_webpack52.getVirtualModules)(options),babelOptions=await options.presets.apply("babel",{},options),typescriptOptions=await options.presets.apply("typescript",{},options);baseConfig.module.rules=[...baseConfig.module.rules,{test:typescriptOptions.skipCompiler?/\.((c|m)?jsx?)$/:/\.((c|m)?(j|t)sx?)$/,use:[{loader:require.resolve("babel-loader"),options:{cacheDirectory:(0,import_common3.resolvePathInStorybookCache)("babel"),...babelOptions}}],include:[(0,import_common3.getProjectRoot)()],exclude:[getNodeModulesExcludeRegex(nextConfig.transpilePackages??[]),...Object.keys(virtualModules)]}]}}});var preset_exports={};__export(preset_exports,{addons:()=>addons,babel:()=>babel,core:()=>core,previewAnnotations:()=>previewAnnotations,webpackFinal:()=>webpackFinal});module.exports=__toCommonJS(preset_exports);var import_node_fs=require("fs"),import_node_path7=require("path"),import_common4=require("storybook/internal/common"),import_node_logger=require("storybook/internal/node-logger"),import_core=require("@babel/core"),import_semver4=__toESM(require("semver"));var import_node_path2=require("path"),isLoadIntentTest=process.env.NODE_ENV==="test",isLoadIntentDevelopment=process.env.NODE_ENV==="development";function styledJsxOptions(options){return options=options||{},options.styleModule="styled-jsx/style",Array.isArray(options.plugins)&&(options.plugins=options.plugins.map(plugin=>{if(Array.isArray(plugin)){let[name,pluginOptions]=plugin;return[require.resolve(name),pluginOptions]}return require.resolve(plugin)})),options}function supportsStaticESM(caller){return!!caller?.supportsStaticESM}var preset_default=(api,options={})=>{let supportsESM=api.caller(supportsStaticESM),isServer=api.caller(caller=>!!caller&&caller.isServer),isCallerDevelopment=api.caller(caller=>caller?.isDev),isTest=isCallerDevelopment==null&&isLoadIntentTest,isDevelopment=isCallerDevelopment===!0||isCallerDevelopment==null&&isLoadIntentDevelopment,isBabelLoader=api.caller(caller=>!!caller&&(caller.name==="babel-loader"||caller.name==="next-babel-turbo-loader")),useJsxRuntime=options["preset-react"]?.runtime==="automatic"||!!api.caller(caller=>!!caller&&caller.hasJsxRuntime)&&options["preset-react"]?.runtime!=="classic",presetEnvConfig={modules:"auto",exclude:["transform-typeof-symbol"],bugfixes:!0,targets:{chrome:100,safari:15,firefox:91},...options["preset-env"]};return(isServer||isTest)&&(!presetEnvConfig.targets||!(typeof presetEnvConfig.targets=="object"&&"node"in presetEnvConfig.targets))&&(presetEnvConfig.targets={node:process.versions.node}),{sourceType:"unambiguous",presets:[[require("@babel/preset-env"),presetEnvConfig],[require("@babel/preset-react"),{development:isDevelopment||isTest,...useJsxRuntime?{runtime:"automatic"}:{pragma:"__jsx"},...options["preset-react"]}],[require("@babel/preset-typescript"),{allowNamespaces:!0,...options["preset-typescript"]}]],plugins:[isDevelopment&&require.resolve("react-refresh/babel"),!useJsxRuntime&&[(init_jsx_pragma(),__toCommonJS(jsx_pragma_exports)),{module:"react",importAs:"React",pragma:"__jsx",property:"createElement"}],[(init_optimize_hook_destructuring(),__toCommonJS(optimize_hook_destructuring_exports)),{lib:!0}],require("@babel/plugin-syntax-dynamic-import"),require("@babel/plugin-syntax-import-assertions"),(init_react_loadable_plugin(),__toCommonJS(react_loadable_plugin_exports)),[require("@babel/plugin-transform-class-properties"),options["class-properties"]||{}],[require("@babel/plugin-transform-object-rest-spread"),{useBuiltIns:!0}],!isServer&&[require("@babel/plugin-transform-runtime"),{corejs:!1,helpers:!0,regenerator:!0,useESModules:supportsESM&&presetEnvConfig.modules!=="commonjs",absoluteRuntime:isBabelLoader?(0,import_node_path2.dirname)(require.resolve("@babel/runtime/package.json")):void 0,...options["transform-runtime"]}],[isTest&&options["styled-jsx"]&&options["styled-jsx"]["babel-test"]?require("styled-jsx/babel-test"):require("styled-jsx/babel"),styledJsxOptions(options["styled-jsx"])],(init_amp_attributes(),__toCommonJS(amp_attributes_exports)),isServer&&require("@babel/plugin-syntax-bigint"),require("@babel/plugin-transform-numeric-separator"),require("@babel/plugin-transform-export-namespace-from")].filter(Boolean)}};init_utils();var tryResolve=path2=>{try{return require.resolve(path2)}catch{return!1}},configureConfig=async({baseConfig,nextConfigPath})=>{let nextConfig=await resolveNextConfig({nextConfigPath});return addScopedAlias(baseConfig,"next/config"),baseConfig.resolve?.alias?.["react-dom"]&&delete baseConfig.resolve.alias?.["react-dom"],tryResolve("next/dist/compiled/react")&&addScopedAlias(baseConfig,"react","next/dist/compiled/react"),tryResolve("next/dist/compiled/react-dom/cjs/react-dom-test-utils.production.js")&&addScopedAlias(baseConfig,"react-dom/test-utils","next/dist/compiled/react-dom/cjs/react-dom-test-utils.production.js"),tryResolve("next/dist/compiled/react-dom")&&(addScopedAlias(baseConfig,"react-dom$","next/dist/compiled/react-dom"),addScopedAlias(baseConfig,"react-dom/client","next/dist/compiled/react-dom/client"),addScopedAlias(baseConfig,"react-dom/server","next/dist/compiled/react-dom/server")),await setupRuntimeConfig(baseConfig,nextConfig),nextConfig},setupRuntimeConfig=async(baseConfig,nextConfig)=>{let definePluginConfig={"process.env.__NEXT_RUNTIME_CONFIG":JSON.stringify({serverRuntimeConfig:{},publicRuntimeConfig:nextConfig.publicRuntimeConfig})},newNextLinkBehavior=nextConfig.experimental?.newNextLinkBehavior;definePluginConfig["process.env.__NEXT_NEW_LINK_BEHAVIOR"]=newNextLinkBehavior,baseConfig.plugins?.push(new(await import("webpack")).default.DefinePlugin(definePluginConfig))};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&&declaration.init.callee.name!==specifier.local.name)&&(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 specifier.type==="ImportSpecifier"&&specifier.imported&&specifier.imported.type==="Identifier"&&declaration.init.callee.name!==specifier.imported.name&&(functionName=specifier.imported.name),{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"||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"||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)}}}}}var addons=[(0,import_node_path7.dirname)(require.resolve((0,import_node_path7.join)("@storybook/preset-react-webpack","package.json")))],core=async(config,options)=>{let framework=await options.presets.apply("framework");return await configureConfig({baseConfig:{},nextConfigPath:typeof framework=="string"?void 0:framework.options.nextConfigPath}),{...config,builder:{name:(0,import_node_path7.dirname)(require.resolve((0,import_node_path7.join)("@storybook/builder-webpack5","package.json"))),options:{...typeof framework=="string"?{}:framework.options.builder||{}}},renderer:(0,import_node_path7.dirname)(require.resolve((0,import_node_path7.join)("@storybook/react","package.json")))}},previewAnnotations=(entry=[])=>{let nextDir=(0,import_node_path7.dirname)(require.resolve("@storybook/nextjs/package.json"));return[...entry,(0,import_node_path7.join)(nextDir,"dist/preview.mjs")]},babel=async baseConfig=>{let options=(0,import_core.loadPartialConfig)({...baseConfig,filename:`${(0,import_common4.getProjectRoot)()}/__fake__.js`})?.options,isPresetConfigItem=preset=>typeof preset=="object"&&preset!==null&&"file"in preset,isNextBabelConfig=preset=>Array.isArray(preset)&&preset[0]==="next/babel"||preset==="next/babel"||isPresetConfigItem(preset)&&preset.file?.request==="next/babel",hasNextBabelConfig=options?.presets?.find(isNextBabelConfig),presets=options?.presets?.filter(preset=>!(isPresetConfigItem(preset)&&preset.file?.request===require.resolve("@babel/preset-react")||isNextBabelConfig(preset)))??[];hasNextBabelConfig?Array.isArray(hasNextBabelConfig)&&hasNextBabelConfig[1]?presets.push([preset_default,hasNextBabelConfig[1]]):isPresetConfigItem(hasNextBabelConfig)&&hasNextBabelConfig.file?.request==="next/babel"?presets.push([preset_default,hasNextBabelConfig.options]):presets.push(preset_default):presets.push(preset_default);let plugins=[...options?.plugins??[],TransformFontImports];return{...options,plugins,presets,babelrc:!1,configFile:!1,overrides:[...options?.overrides??[],{include:/(story|stories)\.[cm]?[jt]sx?$/,presets:[["next/dist/compiled/babel/preset-env",{bugfixes:!0,targets:{chrome:100,safari:15,firefox:91}}]]}]}},webpackFinal=async(baseConfig,options)=>{let{nextConfigPath}=await options.presets.apply("frameworkOptions"),nextConfig=await configureConfig({baseConfig,nextConfigPath}),{configureNextFont:configureNextFont2}=await Promise.resolve().then(()=>(init_configureNextFont(),configureNextFont_exports)),{configureRuntimeNextjsVersionResolution:configureRuntimeNextjsVersionResolution2,getNextjsVersion:getNextjsVersion2}=await Promise.resolve().then(()=>(init_utils(),utils_exports)),{configureImports:configureImports2}=await Promise.resolve().then(()=>(init_webpack(),webpack_exports)),{configureCss:configureCss2}=await Promise.resolve().then(()=>(init_webpack2(),webpack_exports2)),{configureImages:configureImages2}=await Promise.resolve().then(()=>(init_webpack3(),webpack_exports3)),{configureStyledJsx:configureStyledJsx2}=await Promise.resolve().then(()=>(init_webpack4(),webpack_exports4)),{configureNodePolyfills:configureNodePolyfills2}=await Promise.resolve().then(()=>(init_webpack5(),webpack_exports5)),{configureAliases:configureAliases2}=await Promise.resolve().then(()=>(init_webpack7(),webpack_exports6)),{configureFastRefresh:configureFastRefresh2}=await Promise.resolve().then(()=>(init_webpack8(),webpack_exports7)),{configureRSC:configureRSC2}=await Promise.resolve().then(()=>(init_webpack9(),webpack_exports8)),{configureSWCLoader:configureSWCLoader2}=await Promise.resolve().then(()=>(init_loader(),loader_exports)),{configureBabelLoader:configureBabelLoader2}=await Promise.resolve().then(()=>(init_loader2(),loader_exports2)),babelRCPath=(0,import_node_path7.join)((0,import_common4.getProjectRoot)(),".babelrc"),babelConfigPath=(0,import_node_path7.join)((0,import_common4.getProjectRoot)(),"babel.config.js"),hasBabelConfig=(0,import_node_fs.existsSync)(babelRCPath)||(0,import_node_fs.existsSync)(babelConfigPath),nextjsVersion=getNextjsVersion2(),isDevelopment=options.configType!=="PRODUCTION",useSWC=import_semver4.default.gte(nextjsVersion,"14.0.0")&&(nextConfig.experimental?.forceSwcTransforms||!hasBabelConfig);return configureNextFont2(baseConfig,useSWC),configureRuntimeNextjsVersionResolution2(baseConfig),configureImports2({baseConfig,configDir:options.configDir}),configureCss2(baseConfig,nextConfig),configureImages2(baseConfig,nextConfig),configureStyledJsx2(baseConfig),configureNodePolyfills2(baseConfig),configureAliases2(baseConfig),isDevelopment&&configureFastRefresh2(baseConfig),options.features?.experimentalRSC&&configureRSC2(baseConfig),useSWC?(import_node_logger.logger.info("=> Using SWC as compiler"),await configureSWCLoader2(baseConfig,options,nextConfig)):(import_node_logger.logger.info("=> Using Babel as compiler"),await configureBabelLoader2(baseConfig,options,nextConfig)),baseConfig};0&&(module.exports={addons,babel,core,previewAnnotations,webpackFinal});
1
+ import CJS_COMPAT_NODE_URL_e3twfmexlgl from 'node:url';
2
+ import CJS_COMPAT_NODE_PATH_e3twfmexlgl from 'node:path';
3
+ import CJS_COMPAT_NODE_MODULE_e3twfmexlgl from "node:module";
4
+
5
+ var __filename = CJS_COMPAT_NODE_URL_e3twfmexlgl.fileURLToPath(import.meta.url);
6
+ var __dirname = CJS_COMPAT_NODE_PATH_e3twfmexlgl.dirname(__filename);
7
+ var require = CJS_COMPAT_NODE_MODULE_e3twfmexlgl.createRequire(import.meta.url);
8
+
9
+ // ------------------------------------------------------------
10
+ // end of CJS compatibility banner, injected by Storybook's esbuild configuration
11
+ // ------------------------------------------------------------
12
+ import {
13
+ addScopedAlias,
14
+ resolveNextConfig
15
+ } from "./_node-chunks/chunk-EZEBG77A.js";
16
+ import "./_node-chunks/chunk-YMVPQWBH.js";
17
+ import {
18
+ __name
19
+ } from "./_node-chunks/chunk-WCSGFZKZ.js";
20
+
21
+ // src/preset.ts
22
+ import { existsSync } from "node:fs";
23
+ import { join } from "node:path";
24
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
25
+ import { getProjectRoot } from "storybook/internal/common";
26
+ import { logger } from "storybook/internal/node-logger";
27
+ import { loadPartialConfig } from "@babel/core";
28
+ import semver from "semver";
29
+
30
+ // src/babel/preset.ts
31
+ import { createRequire } from "node:module";
32
+ import { dirname } from "node:path";
33
+
34
+ // src/babel/plugins/amp-attributes.ts
35
+ function AmpAttributePatcher() {
36
+ return {
37
+ visitor: {
38
+ JSXOpeningElement(path) {
39
+ const openingElement = path.node;
40
+ const { name, attributes } = openingElement;
41
+ if (!(name && name.type === "JSXIdentifier")) {
42
+ return;
43
+ }
44
+ if (!name.name.startsWith("amp-")) {
45
+ return;
46
+ }
47
+ for (const attribute of attributes) {
48
+ if (attribute.type !== "JSXAttribute") {
49
+ continue;
50
+ }
51
+ if (attribute.name.name === "className") {
52
+ attribute.name.name = "class";
53
+ }
54
+ }
55
+ }
56
+ }
57
+ };
58
+ }
59
+ __name(AmpAttributePatcher, "AmpAttributePatcher");
60
+
61
+ // src/babel/plugins/jsx-pragma.ts
62
+ import jsx from "next/dist/compiled/babel/plugin-syntax-jsx.js";
63
+ function jsxPragma({ types: t }) {
64
+ return {
65
+ inherits: jsx,
66
+ visitor: {
67
+ JSXElement(_path, state) {
68
+ state.set("jsx", true);
69
+ },
70
+ // Fragment syntax is still JSX since it compiles to createElement(),
71
+ // but JSXFragment is not a JSXElement
72
+ JSXFragment(_path, state) {
73
+ state.set("jsx", true);
74
+ },
75
+ Program: {
76
+ exit(path, state) {
77
+ if (state.get("jsx")) {
78
+ const pragma = t.identifier(state.opts.pragma);
79
+ let importAs = pragma;
80
+ const existingBinding = state.opts.reuseImport !== false && state.opts.importAs && path.scope.getBinding(state.opts.importAs);
81
+ if (state.opts.property) {
82
+ if (state.opts.importAs) {
83
+ importAs = t.identifier(state.opts.importAs);
84
+ } else {
85
+ importAs = path.scope.generateUidIdentifier("pragma");
86
+ }
87
+ const mapping = t.variableDeclaration("var", [
88
+ t.variableDeclarator(
89
+ pragma,
90
+ t.memberExpression(importAs, t.identifier(state.opts.property))
91
+ )
92
+ ]);
93
+ let newPath;
94
+ if (existingBinding && t.isVariableDeclarator(existingBinding.path.node) && t.isCallExpression(existingBinding.path.node.init) && t.isIdentifier(existingBinding.path.node.init.callee) && existingBinding.path.node.init.callee.name === "require") {
95
+ [newPath] = existingBinding.path.parentPath.insertAfter(mapping);
96
+ } else {
97
+ [newPath] = path.unshiftContainer("body", mapping);
98
+ }
99
+ for (const declar of newPath.get("declarations")) {
100
+ const kind = ["var", "let", "const"].find((k) => newPath.node.kind === k) || "const";
101
+ path.scope.registerBinding(kind, declar);
102
+ }
103
+ }
104
+ if (!existingBinding) {
105
+ const importSpecifier = t.importDeclaration(
106
+ [
107
+ state.opts.import ? (
108
+ // import { $import as _pragma } from '$module'
109
+ t.importSpecifier(importAs, t.identifier(state.opts.import))
110
+ ) : state.opts.importNamespace ? t.importNamespaceSpecifier(importAs) : (
111
+ // import _pragma from '$module'
112
+ t.importDefaultSpecifier(importAs)
113
+ )
114
+ ],
115
+ t.stringLiteral(state.opts.module || "react")
116
+ );
117
+ const [newPath] = path.unshiftContainer("body", importSpecifier);
118
+ for (const specifier of newPath.get("specifiers")) {
119
+ path.scope.registerBinding("module", specifier);
120
+ }
121
+ }
122
+ }
123
+ }
124
+ }
125
+ }
126
+ };
127
+ }
128
+ __name(jsxPragma, "jsxPragma");
129
+
130
+ // src/babel/plugins/optimize-hook-destructuring.ts
131
+ var isHook = /^use[A-Z]/;
132
+ var isBuiltInHook = /^use(Callback|Context|DebugValue|Effect|ImperativeHandle|LayoutEffect|Memo|Reducer|Ref|State)$/;
133
+ function optimizeHookDestructuring({
134
+ types: t
135
+ }) {
136
+ const visitor = {
137
+ CallExpression(path, state) {
138
+ const { onlyBuiltIns } = state.opts;
139
+ const libs = state.opts.lib && (state.opts.lib === true ? ["react", "preact/hooks"] : [].concat(state.opts.lib));
140
+ if (!t.isVariableDeclarator(path.parent)) {
141
+ return;
142
+ }
143
+ if (!t.isArrayPattern(path.parent.id)) {
144
+ return;
145
+ }
146
+ const hookName = path.node.callee.name;
147
+ if (libs) {
148
+ const binding = path.scope.getBinding(hookName);
149
+ if (!binding || binding.kind !== "module") {
150
+ return;
151
+ }
152
+ const specifier = binding.path.parent.source.value;
153
+ if (!libs.some((lib) => lib === specifier)) {
154
+ return;
155
+ }
156
+ }
157
+ if (!(onlyBuiltIns ? isBuiltInHook : isHook).test(hookName)) {
158
+ return;
159
+ }
160
+ path.parent.id = t.objectPattern(
161
+ path.parent.id.elements.reduce((patterns, element, i) => {
162
+ if (element === null) {
163
+ return patterns;
164
+ }
165
+ return patterns.concat(t.objectProperty(t.numericLiteral(i), element));
166
+ }, [])
167
+ );
168
+ }
169
+ };
170
+ return {
171
+ name: "optimize-hook-destructuring",
172
+ visitor: {
173
+ // this is a workaround to run before preset-env destroys destructured assignments
174
+ Program(path, state) {
175
+ path.traverse(visitor, state);
176
+ }
177
+ }
178
+ };
179
+ }
180
+ __name(optimizeHookDestructuring, "optimizeHookDestructuring");
181
+
182
+ // src/babel/plugins/react-loadable-plugin.ts
183
+ import { relative as relativePath } from "node:path";
184
+ function react_loadable_plugin_default({ types: t }) {
185
+ return {
186
+ visitor: {
187
+ ImportDeclaration(path, state) {
188
+ const source = path.node.source.value;
189
+ if (source !== "next/dynamic") {
190
+ return;
191
+ }
192
+ const defaultSpecifier = path.get("specifiers").find((specifier) => {
193
+ return specifier.isImportDefaultSpecifier();
194
+ });
195
+ if (!defaultSpecifier) {
196
+ return;
197
+ }
198
+ const bindingName = defaultSpecifier.node.local.name;
199
+ const binding = path.scope.getBinding(bindingName);
200
+ if (!binding) {
201
+ return;
202
+ }
203
+ binding.referencePaths.forEach((refPath) => {
204
+ let callExpression = refPath.parentPath;
205
+ if (callExpression.isMemberExpression() && callExpression.node.computed === false) {
206
+ const property = callExpression.get("property");
207
+ if (!Array.isArray(property) && property.isIdentifier({ name: "Map" })) {
208
+ callExpression = callExpression.parentPath;
209
+ }
210
+ }
211
+ if (!callExpression.isCallExpression()) {
212
+ return;
213
+ }
214
+ const callExpression_ = callExpression;
215
+ let args = callExpression_.get("arguments");
216
+ if (args.length > 2) {
217
+ throw callExpression_.buildCodeFrameError("next/dynamic only accepts 2 arguments");
218
+ }
219
+ if (!args[0]) {
220
+ return;
221
+ }
222
+ let loader;
223
+ let options;
224
+ if (args[0].isObjectExpression()) {
225
+ options = args[0];
226
+ } else {
227
+ if (!args[1]) {
228
+ callExpression_.node.arguments.push(t.objectExpression([]));
229
+ }
230
+ args = callExpression_.get("arguments");
231
+ loader = args[0];
232
+ options = args[1];
233
+ }
234
+ if (!options.isObjectExpression()) {
235
+ return;
236
+ }
237
+ const options_ = options;
238
+ const properties = options_.get("properties");
239
+ const propertiesMap = {};
240
+ properties.forEach((property) => {
241
+ const key = property.get("key");
242
+ propertiesMap[key.node.name] = property;
243
+ });
244
+ if (propertiesMap.loadableGenerated) {
245
+ return;
246
+ }
247
+ if (propertiesMap.loader) {
248
+ loader = propertiesMap.loader.get("value");
249
+ }
250
+ if (propertiesMap.modules) {
251
+ loader = propertiesMap.modules.get("value");
252
+ }
253
+ if (!loader || Array.isArray(loader)) {
254
+ return;
255
+ }
256
+ const dynamicImports = [];
257
+ const dynamicKeys = [];
258
+ if (propertiesMap.ssr) {
259
+ const ssr = propertiesMap.ssr.get("value");
260
+ const nodePath = Array.isArray(ssr) ? void 0 : ssr;
261
+ if (nodePath) {
262
+ const nonSSR = nodePath.node.type === "BooleanLiteral" && nodePath.node.value === false;
263
+ if (nonSSR && loader && state.file.opts.caller?.isServer) {
264
+ loader.replaceWith(t.arrowFunctionExpression([], t.nullLiteral(), true));
265
+ }
266
+ }
267
+ }
268
+ loader.traverse({
269
+ Import(importPath) {
270
+ const importArguments = importPath.parentPath.get("arguments");
271
+ if (!Array.isArray(importArguments)) {
272
+ return;
273
+ }
274
+ const { node } = importArguments[0];
275
+ dynamicImports.push(node);
276
+ dynamicKeys.push(
277
+ t.binaryExpression(
278
+ "+",
279
+ t.stringLiteral(
280
+ `${state.file.opts.caller?.pagesDir ? relativePath(state.file.opts.caller.pagesDir, state.file.opts.filename) : state.file.opts.filename} -> `
281
+ ),
282
+ node
283
+ )
284
+ );
285
+ }
286
+ });
287
+ if (!dynamicImports.length) {
288
+ return;
289
+ }
290
+ options.node.properties.push(
291
+ t.objectProperty(
292
+ t.identifier("loadableGenerated"),
293
+ t.objectExpression(
294
+ state.file.opts.caller?.isDev || state.file.opts.caller?.isServer ? [t.objectProperty(t.identifier("modules"), t.arrayExpression(dynamicKeys))] : [
295
+ t.objectProperty(
296
+ t.identifier("webpack"),
297
+ t.arrowFunctionExpression(
298
+ [],
299
+ t.arrayExpression(
300
+ dynamicImports.map((dynamicImport) => {
301
+ return t.callExpression(
302
+ t.memberExpression(
303
+ t.identifier("require"),
304
+ t.identifier("resolveWeak")
305
+ ),
306
+ [dynamicImport]
307
+ );
308
+ })
309
+ )
310
+ )
311
+ )
312
+ ]
313
+ )
314
+ )
315
+ );
316
+ if (loader.isCallExpression()) {
317
+ const arrowFunction = t.arrowFunctionExpression([], loader.node);
318
+ loader.replaceWith(arrowFunction);
319
+ }
320
+ });
321
+ }
322
+ }
323
+ };
324
+ }
325
+ __name(react_loadable_plugin_default, "default");
326
+
327
+ // src/babel/preset.ts
328
+ var isLoadIntentTest = process.env.NODE_ENV === "test";
329
+ var isLoadIntentDevelopment = process.env.NODE_ENV === "development";
330
+ var require2 = createRequire(import.meta.url);
331
+ function styledJsxOptions(options) {
332
+ options = options || {};
333
+ options.styleModule = "styled-jsx/style";
334
+ if (!Array.isArray(options.plugins)) {
335
+ return options;
336
+ }
337
+ options.plugins = options.plugins.map((plugin) => {
338
+ if (Array.isArray(plugin)) {
339
+ const [name, pluginOptions] = plugin;
340
+ return [require2.resolve(name), pluginOptions];
341
+ }
342
+ return require2.resolve(plugin);
343
+ });
344
+ return options;
345
+ }
346
+ __name(styledJsxOptions, "styledJsxOptions");
347
+ function supportsStaticESM(caller) {
348
+ return !!caller?.supportsStaticESM;
349
+ }
350
+ __name(supportsStaticESM, "supportsStaticESM");
351
+ var preset_default = /* @__PURE__ */ __name((api, options = {}) => {
352
+ const supportsESM = api.caller(supportsStaticESM);
353
+ const isServer = api.caller((caller) => !!caller && caller.isServer);
354
+ const isCallerDevelopment = api.caller((caller) => caller?.isDev);
355
+ const isTest = isCallerDevelopment == null && isLoadIntentTest;
356
+ const isDevelopment = isCallerDevelopment === true || isCallerDevelopment == null && isLoadIntentDevelopment;
357
+ const isBabelLoader = api.caller(
358
+ (caller) => !!caller && (caller.name === "babel-loader" || caller.name === "next-babel-turbo-loader")
359
+ );
360
+ const useJsxRuntime = options["preset-react"]?.runtime === "automatic" || Boolean(api.caller((caller) => !!caller && caller.hasJsxRuntime)) && options["preset-react"]?.runtime !== "classic";
361
+ const presetEnvConfig = {
362
+ // In the test environment `modules` is often needed to be set to true, babel figures that out by itself using the `'auto'` option
363
+ // In production/development this option is set to `false` so that webpack can handle import/export with tree-shaking
364
+ modules: "auto",
365
+ exclude: ["transform-typeof-symbol"],
366
+ bugfixes: true,
367
+ targets: {
368
+ chrome: 100,
369
+ safari: 15,
370
+ firefox: 91
371
+ },
372
+ ...options["preset-env"]
373
+ };
374
+ if ((isServer || isTest) && (!presetEnvConfig.targets || !(typeof presetEnvConfig.targets === "object" && "node" in presetEnvConfig.targets))) {
375
+ presetEnvConfig.targets = {
376
+ // Targets the current process' version of Node. This requires apps be
377
+ // built and deployed on the same version of Node.
378
+ // This is the same as using "current" but explicit
379
+ node: process.versions.node
380
+ };
381
+ }
382
+ return {
383
+ sourceType: "unambiguous",
384
+ presets: [
385
+ [require2("@babel/preset-env"), presetEnvConfig],
386
+ [
387
+ require2("@babel/preset-react"),
388
+ {
389
+ // This adds @babel/plugin-transform-react-jsx-source and
390
+ // @babel/plugin-transform-react-jsx-self automatically in development
391
+ development: isDevelopment || isTest,
392
+ ...useJsxRuntime ? { runtime: "automatic" } : { pragma: "__jsx" },
393
+ ...options["preset-react"]
394
+ }
395
+ ],
396
+ [
397
+ require2("@babel/preset-typescript"),
398
+ { allowNamespaces: true, ...options["preset-typescript"] }
399
+ ]
400
+ ],
401
+ plugins: [
402
+ isDevelopment && require2.resolve("react-refresh/babel"),
403
+ !useJsxRuntime && [
404
+ jsxPragma,
405
+ {
406
+ // This produces the following injected import for modules containing JSX:
407
+ // import React from 'react';
408
+ // var __jsx = React.createElement;
409
+ module: "react",
410
+ importAs: "React",
411
+ pragma: "__jsx",
412
+ property: "createElement"
413
+ }
414
+ ],
415
+ [
416
+ optimizeHookDestructuring,
417
+ {
418
+ // only optimize hook functions imported from React/Preact
419
+ lib: true
420
+ }
421
+ ],
422
+ require2("@babel/plugin-syntax-dynamic-import"),
423
+ require2("@babel/plugin-syntax-import-assertions"),
424
+ react_loadable_plugin_default,
425
+ [require2("@babel/plugin-transform-class-properties"), options["class-properties"] || {}],
426
+ [
427
+ require2("@babel/plugin-transform-object-rest-spread"),
428
+ {
429
+ useBuiltIns: true
430
+ }
431
+ ],
432
+ !isServer && [
433
+ require2("@babel/plugin-transform-runtime"),
434
+ {
435
+ corejs: false,
436
+ helpers: true,
437
+ regenerator: true,
438
+ useESModules: supportsESM && presetEnvConfig.modules !== "commonjs",
439
+ absoluteRuntime: isBabelLoader ? dirname(require2.resolve("@babel/runtime/package.json")) : void 0,
440
+ ...options["transform-runtime"]
441
+ }
442
+ ],
443
+ [
444
+ isTest && options["styled-jsx"] && options["styled-jsx"]["babel-test"] ? require2("styled-jsx/babel-test") : require2("styled-jsx/babel"),
445
+ styledJsxOptions(options["styled-jsx"])
446
+ ],
447
+ AmpAttributePatcher,
448
+ isServer && require2("@babel/plugin-syntax-bigint"),
449
+ // Always compile numeric separator because the resulting number is
450
+ // smaller.
451
+ require2("@babel/plugin-transform-numeric-separator"),
452
+ require2("@babel/plugin-transform-export-namespace-from")
453
+ ].filter(Boolean)
454
+ };
455
+ }, "default");
456
+
457
+ // src/config/webpack.ts
458
+ import { fileURLToPath } from "node:url";
459
+ var tryResolve = /* @__PURE__ */ __name((path) => {
460
+ try {
461
+ return fileURLToPath(import.meta.resolve(path)) || false;
462
+ } catch (err) {
463
+ return false;
464
+ }
465
+ }, "tryResolve");
466
+ var configureConfig = /* @__PURE__ */ __name(async ({
467
+ baseConfig,
468
+ nextConfigPath
469
+ }) => {
470
+ const nextConfig = await resolveNextConfig({ nextConfigPath });
471
+ addScopedAlias(baseConfig, "next/config");
472
+ if (baseConfig.resolve?.alias?.["react-dom"]) {
473
+ delete baseConfig.resolve.alias?.["react-dom"];
474
+ }
475
+ if (tryResolve("next/dist/compiled/react")) {
476
+ addScopedAlias(baseConfig, "react", "next/dist/compiled/react");
477
+ }
478
+ if (tryResolve("next/dist/compiled/react-dom/cjs/react-dom-test-utils.production.js")) {
479
+ addScopedAlias(
480
+ baseConfig,
481
+ "react-dom/test-utils",
482
+ "next/dist/compiled/react-dom/cjs/react-dom-test-utils.production.js"
483
+ );
484
+ }
485
+ if (tryResolve("next/dist/compiled/react-dom")) {
486
+ addScopedAlias(baseConfig, "react-dom$", "next/dist/compiled/react-dom");
487
+ addScopedAlias(baseConfig, "react-dom/client", "next/dist/compiled/react-dom/client");
488
+ addScopedAlias(baseConfig, "react-dom/server", "next/dist/compiled/react-dom/server");
489
+ }
490
+ await setupRuntimeConfig(baseConfig, nextConfig);
491
+ return nextConfig;
492
+ }, "configureConfig");
493
+ var setupRuntimeConfig = /* @__PURE__ */ __name(async (baseConfig, nextConfig) => {
494
+ const definePluginConfig = {
495
+ // this mimics what nextjs does client side
496
+ // https://github.com/vercel/next.js/blob/57702cb2a9a9dba4b552e0007c16449cf36cfb44/packages/next/client/index.tsx#L101
497
+ "process.env.__NEXT_RUNTIME_CONFIG": JSON.stringify({
498
+ serverRuntimeConfig: {},
499
+ publicRuntimeConfig: nextConfig.publicRuntimeConfig
500
+ })
501
+ };
502
+ const newNextLinkBehavior = nextConfig.experimental?.newNextLinkBehavior;
503
+ definePluginConfig["process.env.__NEXT_NEW_LINK_BEHAVIOR"] = newNextLinkBehavior;
504
+ baseConfig.plugins?.push(new (await import("webpack")).default.DefinePlugin(definePluginConfig));
505
+ }, "setupRuntimeConfig");
506
+
507
+ // src/font/babel/helpers.ts
508
+ function convertNodeToJSON(types, node) {
509
+ if (types.isBooleanLiteral(node) || types.isStringLiteral(node) || types.isNumericLiteral(node)) {
510
+ return node.value;
511
+ }
512
+ if (node.name === "undefined" && !node.value) {
513
+ return void 0;
514
+ }
515
+ if (types.isNullLiteral(node)) {
516
+ return null;
517
+ }
518
+ if (types.isObjectExpression(node)) {
519
+ return computeProps(types, node.properties);
520
+ }
521
+ if (types.isArrayExpression(node)) {
522
+ return node.elements.reduce(
523
+ (acc, element) => [
524
+ ...acc,
525
+ ...element?.type === "SpreadElement" ? convertNodeToJSON(types, element.argument) : [convertNodeToJSON(types, element)]
526
+ ],
527
+ []
528
+ );
529
+ }
530
+ return {};
531
+ }
532
+ __name(convertNodeToJSON, "convertNodeToJSON");
533
+ function computeProps(types, props) {
534
+ return props.reduce((acc, prop) => {
535
+ if (prop.type === "SpreadElement") {
536
+ return {
537
+ ...acc,
538
+ ...convertNodeToJSON(types, prop.argument)
539
+ };
540
+ }
541
+ if (prop.type !== "ObjectMethod") {
542
+ const val = convertNodeToJSON(types, prop.value);
543
+ if (val !== void 0 && types.isIdentifier(prop.key)) {
544
+ return {
545
+ ...acc,
546
+ [prop.key.name]: val
547
+ };
548
+ }
549
+ }
550
+ return acc;
551
+ }, {});
552
+ }
553
+ __name(computeProps, "computeProps");
554
+ function isDefined(value) {
555
+ return value !== void 0;
556
+ }
557
+ __name(isDefined, "isDefined");
558
+ function removeTransformedVariableDeclarations(path, types, metas) {
559
+ path.parentPath.traverse({
560
+ ExportNamedDeclaration(declaratorPath) {
561
+ if (!declaratorPath.parentPath?.isProgram()) {
562
+ return;
563
+ }
564
+ metas.forEach((meta) => {
565
+ if (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) {
566
+ declaratorPath.replaceWith(
567
+ types.exportNamedDeclaration(null, [
568
+ types.exportSpecifier(
569
+ types.identifier(meta.identifierName),
570
+ types.identifier(meta.identifierName)
571
+ )
572
+ ])
573
+ );
574
+ }
575
+ });
576
+ },
577
+ VariableDeclarator(declaratorPath) {
578
+ if (!declaratorPath.parentPath.parentPath?.isProgram()) {
579
+ return;
580
+ }
581
+ if (metas.some(
582
+ (meta) => types.isIdentifier(declaratorPath.node.id) && meta.identifierName === declaratorPath.node.id.name
583
+ )) {
584
+ declaratorPath.remove();
585
+ }
586
+ }
587
+ });
588
+ }
589
+ __name(removeTransformedVariableDeclarations, "removeTransformedVariableDeclarations");
590
+ function replaceImportWithParameterImport(path, types, source, metas, filename) {
591
+ path.replaceWithMultiple([
592
+ ...metas.map((meta) => {
593
+ return types.importDeclaration(
594
+ [types.importDefaultSpecifier(types.identifier(meta.identifierName))],
595
+ types.stringLiteral(
596
+ `storybook-nextjs-font-loader?${JSON.stringify({
597
+ source: source.value,
598
+ props: meta.properties,
599
+ fontFamily: meta.functionName,
600
+ filename
601
+ })}!${source.value}`
602
+ )
603
+ );
604
+ })
605
+ ]);
606
+ }
607
+ __name(replaceImportWithParameterImport, "replaceImportWithParameterImport");
608
+ function getVariableMetasBySpecifier(program, types, specifier) {
609
+ return program.node.body.map((statement) => {
610
+ if (!types.isVariableDeclaration(statement) && !types.isExportNamedDeclaration(statement)) {
611
+ return void 0;
612
+ }
613
+ const exportedNamedDeclaration = !types.isVariableDeclaration(statement) && types.isVariableDeclaration(statement.declaration) && statement.declaration.declarations.length === 1 ? statement.declaration.declarations[0] : null;
614
+ const declaration = types.isVariableDeclaration(statement) ? statement.declarations[0] : exportedNamedDeclaration;
615
+ if (!declaration) {
616
+ return void 0;
617
+ }
618
+ if (!types.isIdentifier(declaration.id)) {
619
+ return void 0;
620
+ }
621
+ if (!types.isCallExpression(declaration.init)) {
622
+ return void 0;
623
+ }
624
+ if (!types.isIdentifier(declaration.init.callee)) {
625
+ return void 0;
626
+ }
627
+ if ((specifier.type !== "ImportSpecifier" || specifier.imported.type !== "Identifier" || declaration.init.callee.name !== specifier.imported.name && declaration.init.callee.name !== specifier.local.name) && (specifier.type !== "ImportDefaultSpecifier" || declaration.init.callee.name !== specifier.local.name)) {
628
+ return void 0;
629
+ }
630
+ const options = declaration.init.arguments[0];
631
+ if (!types.isObjectExpression(options)) {
632
+ throw program.buildCodeFrameError(
633
+ "Please pass an options object to the call expression of next/font functions"
634
+ );
635
+ }
636
+ options.properties.forEach((property) => {
637
+ if (types.isSpreadElement(property)) {
638
+ throw program.buildCodeFrameError(
639
+ "Please do not use spread elements in the options object in next/font function calls"
640
+ );
641
+ }
642
+ });
643
+ const identifierName = declaration.id.name;
644
+ const properties = convertNodeToJSON(types, options);
645
+ let functionName = declaration.init.callee.name;
646
+ if (specifier.type === "ImportSpecifier" && specifier.imported && specifier.imported.type === "Identifier" && declaration.init.callee.name !== specifier.imported.name) {
647
+ functionName = specifier.imported.name;
648
+ }
649
+ return { identifierName, properties, functionName };
650
+ }).filter(isDefined);
651
+ }
652
+ __name(getVariableMetasBySpecifier, "getVariableMetasBySpecifier");
653
+
654
+ // src/font/babel/index.ts
655
+ function TransformFontImports({ types }) {
656
+ return {
657
+ name: "storybook-nextjs-font-imports",
658
+ visitor: {
659
+ ImportDeclaration(path, state) {
660
+ const { node } = path;
661
+ const { source } = node;
662
+ const { filename = "" } = state;
663
+ if (source.value === "next/font/local" || source.value === "@next/font/local") {
664
+ const { specifiers } = node;
665
+ const specifier = specifiers[0];
666
+ if (!path.parentPath.isProgram()) {
667
+ return;
668
+ }
669
+ const program = path.parentPath;
670
+ const variableMetas = getVariableMetasBySpecifier(program, types, specifier);
671
+ removeTransformedVariableDeclarations(path, types, variableMetas);
672
+ replaceImportWithParameterImport(path, types, source, variableMetas, filename);
673
+ }
674
+ if (source.value === "next/font/google" || source.value === "@next/font/google") {
675
+ const { specifiers } = node;
676
+ const variableMetas = specifiers.flatMap((specifier) => {
677
+ if (!path.parentPath.isProgram()) {
678
+ return [];
679
+ }
680
+ const program = path.parentPath;
681
+ return getVariableMetasBySpecifier(program, types, specifier);
682
+ }).filter(isDefined);
683
+ removeTransformedVariableDeclarations(path, types, variableMetas);
684
+ replaceImportWithParameterImport(path, types, source, variableMetas, filename);
685
+ }
686
+ }
687
+ }
688
+ };
689
+ }
690
+ __name(TransformFontImports, "TransformFontImports");
691
+
692
+ // src/preset.ts
693
+ var addons = [
694
+ fileURLToPath2(import.meta.resolve("@storybook/preset-react-webpack"))
695
+ ];
696
+ var core = /* @__PURE__ */ __name(async (config, options) => {
697
+ const framework = await options.presets.apply("framework");
698
+ await configureConfig({
699
+ // Pass in a dummy webpack config object for now, since we don't want to
700
+ // modify the real one yet. We pass in the real one in webpackFinal.
701
+ baseConfig: {},
702
+ nextConfigPath: typeof framework === "string" ? void 0 : framework.options.nextConfigPath
703
+ });
704
+ return {
705
+ ...config,
706
+ builder: {
707
+ name: fileURLToPath2(import.meta.resolve("@storybook/builder-webpack5")),
708
+ options: {
709
+ ...typeof framework === "string" ? {} : framework.options.builder || {}
710
+ }
711
+ },
712
+ renderer: fileURLToPath2(import.meta.resolve("@storybook/react/preset"))
713
+ };
714
+ }, "core");
715
+ var previewAnnotations = /* @__PURE__ */ __name((entry = []) => {
716
+ const result = [...entry, fileURLToPath2(import.meta.resolve("@storybook/nextjs/preview"))];
717
+ return result;
718
+ }, "previewAnnotations");
719
+ var babel = /* @__PURE__ */ __name(async (baseConfig) => {
720
+ const configPartial = loadPartialConfig({
721
+ ...baseConfig,
722
+ filename: `${getProjectRoot()}/__fake__.js`
723
+ });
724
+ const options = configPartial?.options;
725
+ const isPresetConfigItem = /* @__PURE__ */ __name((preset) => {
726
+ return typeof preset === "object" && preset !== null && "file" in preset;
727
+ }, "isPresetConfigItem");
728
+ const isNextBabelConfig = /* @__PURE__ */ __name((preset) => Array.isArray(preset) && preset[0] === "next/babel" || preset === "next/babel" || isPresetConfigItem(preset) && preset.file?.request === "next/babel", "isNextBabelConfig");
729
+ const hasNextBabelConfig = options?.presets?.find(isNextBabelConfig);
730
+ const presets = options?.presets?.filter(
731
+ (preset) => !(isPresetConfigItem(preset) && preset.file?.request === fileURLToPath2(import.meta.resolve("@babel/preset-react")) || isNextBabelConfig(preset))
732
+ ) ?? [];
733
+ if (hasNextBabelConfig) {
734
+ if (Array.isArray(hasNextBabelConfig) && hasNextBabelConfig[1]) {
735
+ presets.push([preset_default, hasNextBabelConfig[1]]);
736
+ } else if (isPresetConfigItem(hasNextBabelConfig) && hasNextBabelConfig.file?.request === "next/babel") {
737
+ presets.push([preset_default, hasNextBabelConfig.options]);
738
+ } else {
739
+ presets.push(preset_default);
740
+ }
741
+ } else {
742
+ presets.push(preset_default);
743
+ }
744
+ const plugins = [...options?.plugins ?? [], TransformFontImports];
745
+ return {
746
+ ...options,
747
+ plugins,
748
+ presets,
749
+ babelrc: false,
750
+ configFile: false,
751
+ overrides: [
752
+ ...options?.overrides ?? [],
753
+ // We need to re-apply the default storybook babel override from:
754
+ // https://github.com/storybookjs/storybook/blob/next/code/core/src/core-server/presets/common-preset.ts
755
+ // Because it get lost in the loadPartialConfig call above.
756
+ // See https://github.com/storybookjs/storybook/issues/28467
757
+ {
758
+ include: /(story|stories)\.[cm]?[jt]sx?$/,
759
+ presets: [
760
+ [
761
+ "next/dist/compiled/babel/preset-env",
762
+ {
763
+ bugfixes: true,
764
+ targets: {
765
+ chrome: 100,
766
+ safari: 15,
767
+ firefox: 91
768
+ }
769
+ }
770
+ ]
771
+ ]
772
+ }
773
+ ]
774
+ };
775
+ }, "babel");
776
+ var webpackFinal = /* @__PURE__ */ __name(async (baseConfig, options) => {
777
+ const { nextConfigPath } = await options.presets.apply("frameworkOptions");
778
+ const nextConfig = await configureConfig({
779
+ baseConfig,
780
+ nextConfigPath
781
+ });
782
+ const { configureNextFont } = await import("./_node-chunks/configureNextFont-HBRWHAUG.js");
783
+ const { configureRuntimeNextjsVersionResolution, getNextjsVersion } = await import("./_node-chunks/utils-4LRBHVQD.js");
784
+ const { configureImports } = await import("./_node-chunks/webpack-6HAXGE7X.js");
785
+ const { configureCss } = await import("./_node-chunks/webpack-SWQY6JJY.js");
786
+ const { configureImages } = await import("./_node-chunks/webpack-AGNCA7HZ.js");
787
+ const { configureStyledJsx } = await import("./_node-chunks/webpack-EWT6TRQB.js");
788
+ const { configureNodePolyfills } = await import("./_node-chunks/webpack-CXSD35E6.js");
789
+ const { configureAliases } = await import("./_node-chunks/webpack-PD7PIB6X.js");
790
+ const { configureFastRefresh } = await import("./_node-chunks/webpack-K2R3GUFU.js");
791
+ const { configureRSC } = await import("./_node-chunks/webpack-QFTZE3CE.js");
792
+ const { configureSWCLoader } = await import("./_node-chunks/loader-Z4IXWF5M.js");
793
+ const { configureBabelLoader } = await import("./_node-chunks/loader-KXTZ5PJ5.js");
794
+ const babelRCPath = join(getProjectRoot(), ".babelrc");
795
+ const babelConfigPath = join(getProjectRoot(), "babel.config.js");
796
+ const hasBabelConfig = existsSync(babelRCPath) || existsSync(babelConfigPath);
797
+ const nextjsVersion = getNextjsVersion();
798
+ const isDevelopment = options.configType !== "PRODUCTION";
799
+ const isNext14orNewer = semver.gte(nextjsVersion, "14.0.0");
800
+ const useSWC = isNext14orNewer && (nextConfig.experimental?.forceSwcTransforms || !hasBabelConfig);
801
+ configureNextFont(baseConfig, useSWC);
802
+ configureRuntimeNextjsVersionResolution(baseConfig);
803
+ configureImports({ baseConfig, configDir: options.configDir });
804
+ configureCss(baseConfig, nextConfig);
805
+ configureImages(baseConfig, nextConfig);
806
+ configureStyledJsx(baseConfig);
807
+ configureNodePolyfills(baseConfig);
808
+ configureAliases(baseConfig);
809
+ if (isDevelopment) {
810
+ configureFastRefresh(baseConfig);
811
+ }
812
+ if (options.features?.experimentalRSC) {
813
+ configureRSC(baseConfig);
814
+ }
815
+ if (useSWC) {
816
+ logger.info("=> Using SWC as compiler");
817
+ await configureSWCLoader(baseConfig, options, nextConfig);
818
+ } else {
819
+ logger.info("=> Using Babel as compiler");
820
+ await configureBabelLoader(baseConfig, options, nextConfig);
821
+ }
822
+ return baseConfig;
823
+ }, "webpackFinal");
824
+ export {
825
+ addons,
826
+ babel,
827
+ core,
828
+ previewAnnotations,
829
+ webpackFinal
830
+ };