@storybook/react-vite
Version:
Storybook for React and Vite: Develop, document, and test UI components in isolation
177 lines (170 loc) • 6.6 kB
JavaScript
import CJS_COMPAT_NODE_URL_l8ikm81v3xk from 'node:url';
import CJS_COMPAT_NODE_PATH_l8ikm81v3xk from 'node:path';
import CJS_COMPAT_NODE_MODULE_l8ikm81v3xk from "node:module";
var __filename = CJS_COMPAT_NODE_URL_l8ikm81v3xk.fileURLToPath(import.meta.url);
var __dirname = CJS_COMPAT_NODE_PATH_l8ikm81v3xk.dirname(__filename);
var require = CJS_COMPAT_NODE_MODULE_l8ikm81v3xk.createRequire(import.meta.url);
// ------------------------------------------------------------
// end of CJS compatibility banner, injected by Storybook's esbuild configuration
// ------------------------------------------------------------
// src/plugins/react-docgen.ts
import { existsSync } from "node:fs";
import { relative, sep } from "node:path";
import { getProjectRoot } from "storybook/internal/common";
import { logger } from "storybook/internal/node-logger";
import { createFilter } from "@rollup/pluginutils";
import * as find from "empathic/find";
import MagicString from "magic-string";
import {
ERROR_CODES,
builtinHandlers as docgenHandlers,
builtinResolvers as docgenResolver,
makeFsImporter,
parse
} from "react-docgen";
import * as TsconfigPaths from "tsconfig-paths";
// src/plugins/docgen-handlers/actualNameHandler.ts
import { utils } from "react-docgen";
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", "");
}
}, actualNameHandler_default = actualNameHandler;
// src/plugins/docgen-resolver.ts
import { extname } from "node:path";
import resolve from "resolve";
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";
}
}, 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) {
let resolveOptions = {
basedir,
extensions: RESOLVE_EXTENSIONS,
// we do not need to check core modules as we cannot import them anyway
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,
// we already know that there is an extension at this point, so no need to check other extensions
extensions: []
});
}
}
// src/plugins/react-docgen.ts
var defaultHandlers = Object.values(docgenHandlers).map((handler) => handler), defaultResolver = new docgenResolver.FindExportedDefinitionsResolver(), handlers = [...defaultHandlers, actualNameHandler_default];
async function reactDocgen({
include = /\.(mjs|tsx?|jsx?)$/,
exclude = [/node_modules\/.*/]
} = {}) {
let cwd = process.cwd(), filter = createFilter(include, exclude), tsconfigPath = find.up("tsconfig.json", { cwd, last: getProjectRoot() }), tsconfig = TsconfigPaths.loadConfig(tsconfigPath), matchPath;
return tsconfig.resultType === "success" && (logger.debug("Using tsconfig paths for react-docgen"), matchPath = TsconfigPaths.createMatchPath(tsconfig.absoluteBaseUrl, tsconfig.paths, [
"browser",
"module",
"main"
])), {
name: "storybook:react-docgen-plugin",
enforce: "pre",
async transform(src, id) {
if (filter(relative(cwd, id)))
try {
let docgenResults = parse(src, {
resolver: defaultResolver,
handlers,
importer: getReactDocgenImporter(matchPath),
filename: id
}), s = new MagicString(src);
return docgenResults.forEach((info) => {
let { actualName, definedInFile, ...docgenInfo } = info;
if (actualName && definedInFile == id) {
let docNode = JSON.stringify(docgenInfo);
s.append(`;${actualName}.__docgenInfo=${docNode}`);
}
}), {
code: s.toString(),
map: s.generateMap({ hires: !0, source: id })
};
} catch (e) {
if (e.code === ERROR_CODES.MISSING_DEFINITION)
return;
throw e;
}
}
};
}
function getReactDocgenImporter(matchPath) {
return makeFsImporter((filename, basedir) => {
let mappedFilenameByPaths = matchPath && matchPath(filename) || filename, result = defaultLookupModule(mappedFilenameByPaths, basedir);
if (result.includes(`${sep}react-native${sep}index.js`)) {
let replaced = result.replace(
`${sep}react-native${sep}index.js`,
`${sep}react-native-web${sep}dist${sep}index.js`
);
if (existsSync(replaced) && RESOLVE_EXTENSIONS.find((ext) => result.endsWith(ext)))
return replaced;
}
if (RESOLVE_EXTENSIONS.find((ext) => result.endsWith(ext)))
return result;
throw new ReactDocgenResolveError(filename);
});
}
export {
getReactDocgenImporter,
reactDocgen
};