storybook-react-rsbuild
Version:
Storybook for React and Rsbuild: Develop React components in isolation with Hot Reloading.
196 lines (192 loc) • 6.65 kB
JavaScript
import findUp from 'find-up';
import MagicString from 'magic-string';
import { builtinHandlers, builtinResolvers, parse, ERROR_CODES, makeFsImporter, utils } from 'react-docgen';
import { logger } from 'storybook/internal/node-logger';
import * as TsconfigPaths from 'tsconfig-paths';
import { extname } from 'path';
import resolve from 'resolve';
// src/loaders/react-docgen-loader.ts
var ReactDocgenResolveError = class extends Error {
constructor(filename) {
super(`'${filename}' was ignored by react-docgen.`);
// the magic string that react-docgen uses to check if a module is ignored
this.code = "MODULE_NOT_FOUND";
}
};
var RESOLVE_EXTENSIONS = [
".js",
".cts",
// These were originally not in the code, I added them
".mts",
// These were originally not in the code, I added them
".ctsx",
// These were originally not in the code, I added them
".mtsx",
// These were originally not in the code, I added them
".ts",
".tsx",
".mjs",
".cjs",
".mts",
".cts",
".jsx"
];
function defaultLookupModule(filename, basedir) {
const resolveOptions = {
basedir,
extensions: RESOLVE_EXTENSIONS,
// we do not need to check core modules as we cannot import them anyway
includeCoreModules: false
};
try {
return resolve.sync(filename, resolveOptions);
} catch (error) {
const ext = extname(filename);
let 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,
// we already know that there is an extension at this point, so no need to check other extensions
extensions: []
});
}
}
// src/loaders/react-docgen-loader.ts
var { getNameOrValue, isReactForwardRefCall } = utils;
var actualNameHandler = function actualNameHandler2(documentation, componentDefinition) {
documentation.set("definedInFile", componentDefinition.hub.file.opts.filename);
if ((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;
while (currentPath.parentPath) {
if (currentPath.parentPath.isVariableDeclarator()) {
documentation.set(
"actualName",
getNameOrValue(currentPath.parentPath.get("id"))
);
return;
}
if (currentPath.parentPath.isAssignmentExpression()) {
const leftPath = currentPath.parentPath.get("left");
if (leftPath.isIdentifier() || leftPath.isLiteral()) {
documentation.set("actualName", getNameOrValue(leftPath));
return;
}
}
currentPath = currentPath.parentPath;
}
documentation.set("actualName", "");
}
};
var defaultHandlers = Object.values(builtinHandlers).map((handler) => handler);
var defaultResolver = new builtinResolvers.FindExportedDefinitionsResolver();
var handlers = [...defaultHandlers, actualNameHandler];
var tsconfigPathsInitializeStatus = "uninitialized";
var resolveTsconfigPathsInitialingPromise;
var tsconfigPathsInitialingPromise = new Promise((resolve2) => {
resolveTsconfigPathsInitialingPromise = resolve2;
});
var finishInitialization = () => {
resolveTsconfigPathsInitialingPromise();
tsconfigPathsInitializeStatus = "initialized";
};
var matchPath;
async function reactDocgenLoader(source, map) {
const callback = this.async();
const options = this.getOptions() || {};
const { debug = false } = options;
if (tsconfigPathsInitializeStatus === "uninitialized") {
tsconfigPathsInitializeStatus = "initializing";
const tsconfigPath = await findUp("tsconfig.json", { cwd: process.cwd() });
const tsconfig = TsconfigPaths.loadConfig(tsconfigPath);
if (tsconfig.resultType === "success") {
logger.info("Using tsconfig paths for react-docgen");
matchPath = TsconfigPaths.createMatchPath(
tsconfig.absoluteBaseUrl,
tsconfig.paths,
["browser", "module", "main"]
);
}
finishInitialization();
}
if (tsconfigPathsInitializeStatus === "initializing") {
await tsconfigPathsInitialingPromise;
}
try {
const docgenResults = parse(source, {
filename: this.resourcePath,
resolver: defaultResolver,
handlers,
importer: getReactDocgenImporter(matchPath),
babelOptions: {
babelrc: false,
configFile: false
}
});
const magicString = new MagicString(source);
for (const info of docgenResults) {
const { actualName, definedInFile, ...docgenInfo } = info;
if (actualName && definedInFile === this.resourcePath) {
const docNode = JSON.stringify(docgenInfo);
magicString.append(`;${actualName}.__docgenInfo=${docNode}`);
}
}
callback(
null,
magicString.toString(),
map ?? magicString.generateMap({
hires: true,
source: this.resourcePath,
includeContent: true
})
);
} catch (error) {
if (error.code === ERROR_CODES.MISSING_DEFINITION) {
callback(null, source);
} else {
if (!debug) {
logger.warn(
`Failed to parse ${this.resourcePath} with react-docgen. Rerun Storybook with --loglevel=debug to get more info.`
);
} else {
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);
}
callback(null, source);
}
}
}
function getReactDocgenImporter(matchingPath) {
return makeFsImporter((filename, basedir) => {
const mappedFilenameByPaths = (() => {
if (matchingPath) {
const match = matchingPath(filename);
return match || filename;
}
return filename;
})();
const result = defaultLookupModule(mappedFilenameByPaths, basedir);
if (RESOLVE_EXTENSIONS.find((ext) => result.endsWith(ext))) {
return result;
}
throw new ReactDocgenResolveError(filename);
});
}
export { reactDocgenLoader as default, getReactDocgenImporter };