@storybook/preset-react-webpack
Version:
Storybook for React: Develop React Component in isolation with Hot Reloading
14 lines (11 loc) • 4.4 kB
JavaScript
import '../chunk-MXFP7CYD.mjs';
import { getProjectRoot } from 'storybook/internal/common';
import { logger } from 'storybook/internal/node-logger';
import { findUp } from 'find-up';
import MagicString from 'magic-string';
import { builtinHandlers, builtinResolvers, parse, ERROR_CODES, makeFsImporter, utils } from 'react-docgen';
import * as TsconfigPaths from 'tsconfig-paths';
import { extname } from 'node:path';
import resolve from 'resolve';
var ReactDocgenResolveError=class extends Error{constructor(filename){super(`'${filename}' was ignored by react-docgen.`);this.code="MODULE_NOT_FOUND";}},RESOLVE_EXTENSIONS=[".js",".cts",".mts",".ctsx",".mtsx",".ts",".tsx",".mjs",".cjs",".mts",".cts",".jsx"];function defaultLookupModule(filename,basedir){let resolveOptions={basedir,extensions:RESOLVE_EXTENSIONS,includeCoreModules:!1};try{return resolve.sync(filename,resolveOptions)}catch(error){let ext=extname(filename),newFilename;switch(ext){case".js":case".mjs":case".cjs":newFilename=`${filename.slice(0,-2)}ts`;break;case".jsx":newFilename=`${filename.slice(0,-3)}tsx`;break;default:throw error}return resolve.sync(newFilename,{...resolveOptions,extensions:[]})}}var{getNameOrValue,isReactForwardRefCall}=utils,actualNameHandler=function(documentation,componentDefinition){if(documentation.set("definedInFile",componentDefinition.hub.file.opts.filename),(componentDefinition.isClassDeclaration()||componentDefinition.isFunctionDeclaration())&&componentDefinition.has("id"))documentation.set("actualName",getNameOrValue(componentDefinition.get("id")));else if(componentDefinition.isArrowFunctionExpression()||componentDefinition.isFunctionExpression()||isReactForwardRefCall(componentDefinition)){let currentPath=componentDefinition;for(;currentPath.parentPath;){if(currentPath.parentPath.isVariableDeclarator()){documentation.set("actualName",getNameOrValue(currentPath.parentPath.get("id")));return}if(currentPath.parentPath.isAssignmentExpression()){let leftPath=currentPath.parentPath.get("left");if(leftPath.isIdentifier()||leftPath.isLiteral()){documentation.set("actualName",getNameOrValue(leftPath));return}}currentPath=currentPath.parentPath;}documentation.set("actualName","");}},defaultHandlers=Object.values(builtinHandlers).map(handler=>handler),defaultResolver=new builtinResolvers.FindExportedDefinitionsResolver,handlers=[...defaultHandlers,actualNameHandler],tsconfigPathsInitialized=!1,matchPath;async function reactDocgenLoader(source,map){let callback=this.async(),options=this.getOptions()||{},{debug=!1}=options;if(!tsconfigPathsInitialized){let tsconfigPath=await findUp("tsconfig.json",{cwd:process.cwd(),stopAt:getProjectRoot()}),tsconfig=TsconfigPaths.loadConfig(tsconfigPath);tsconfig.resultType==="success"&&(logger.info("Using tsconfig paths for react-docgen"),matchPath=TsconfigPaths.createMatchPath(tsconfig.absoluteBaseUrl,tsconfig.paths,["browser","module","main"])),tsconfigPathsInitialized=!0;}try{let docgenResults=parse(source,{filename:this.resourcePath,resolver:defaultResolver,handlers,importer:getReactDocgenImporter(matchPath),babelOptions:{babelrc:!1,configFile:!1}}),magicString=new MagicString(source);docgenResults.forEach(info=>{let{actualName,definedInFile,...docgenInfo}=info;if(actualName&&definedInFile==this.resourcePath){let docNode=JSON.stringify(docgenInfo);magicString.append(`;${actualName}.__docgenInfo=${docNode}`);}}),callback(null,magicString.toString(),map??magicString.generateMap({hires:!0,source:this.resourcePath,includeContent:!0}));}catch(error){error.code===ERROR_CODES.MISSING_DEFINITION||(debug?(logger.warn(`Failed to parse ${this.resourcePath} with react-docgen. Please use the below error message and the content of the file which causes the error to report the issue to the maintainers of react-docgen. https://github.com/reactjs/react-docgen`),logger.error(error)):logger.warn(`Failed to parse ${this.resourcePath} with react-docgen. Rerun Storybook with --loglevel=debug to get more info.`)),callback(null,source);}}function getReactDocgenImporter(matchingPath){return makeFsImporter((filename,basedir)=>{let mappedFilenameByPaths=matchingPath&&matchingPath(filename)||filename,result=defaultLookupModule(mappedFilenameByPaths,basedir);if(RESOLVE_EXTENSIONS.find(ext=>result.endsWith(ext)))return result;throw new ReactDocgenResolveError(filename)})}
export { reactDocgenLoader as default, getReactDocgenImporter };