@storybook/react-vite
Version:
Storybook for React and Vite: Develop, document, and test UI components in isolation
218 lines (211 loc) • 7.21 kB
JavaScript
import CJS_COMPAT_NODE_URL_xkh8kf5refo from 'node:url';
import CJS_COMPAT_NODE_PATH_xkh8kf5refo from 'node:path';
import CJS_COMPAT_NODE_MODULE_xkh8kf5refo from "node:module";
var __filename = CJS_COMPAT_NODE_URL_xkh8kf5refo.fileURLToPath(import.meta.url);
var __dirname = CJS_COMPAT_NODE_PATH_xkh8kf5refo.dirname(__filename);
var require = CJS_COMPAT_NODE_MODULE_xkh8kf5refo.createRequire(import.meta.url);
// ------------------------------------------------------------
// end of CJS compatibility banner, injected by Storybook's esbuild configuration
// ------------------------------------------------------------
import {
__name
} from "./chunk-B77K422O.js";
// 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;
var actualNameHandler = /* @__PURE__ */ __name(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", "");
}
}, "actualNameHandler");
var 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";
}
static {
__name(this, "ReactDocgenResolveError");
}
};
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: []
});
}
}
__name(defaultLookupModule, "defaultLookupModule");
// src/plugins/react-docgen.ts
var defaultHandlers = Object.values(docgenHandlers).map((handler) => handler);
var defaultResolver = new docgenResolver.FindExportedDefinitionsResolver();
var handlers = [...defaultHandlers, actualNameHandler_default];
async function reactDocgen({
include = /\.(mjs|tsx?|jsx?)$/,
exclude = [/node_modules\/.*/]
} = {}) {
const cwd = process.cwd();
const filter = createFilter(include, exclude);
const tsconfigPath = find.up("tsconfig.json", { cwd, last: getProjectRoot() });
const tsconfig = TsconfigPaths.loadConfig(tsconfigPath);
let matchPath;
if (tsconfig.resultType === "success") {
logger.info("Using tsconfig paths for react-docgen");
matchPath = TsconfigPaths.createMatchPath(tsconfig.absoluteBaseUrl, tsconfig.paths, [
"browser",
"module",
"main"
]);
}
return {
name: "storybook:react-docgen-plugin",
enforce: "pre",
async transform(src, id) {
if (!filter(relative(cwd, id))) {
return;
}
try {
const docgenResults = parse(src, {
resolver: defaultResolver,
handlers,
importer: getReactDocgenImporter(matchPath),
filename: id
});
const s = new MagicString(src);
docgenResults.forEach((info) => {
const { actualName, definedInFile, ...docgenInfo } = info;
if (actualName && definedInFile == id) {
const docNode = JSON.stringify(docgenInfo);
s.append(`;${actualName}.__docgenInfo=${docNode}`);
}
});
return {
code: s.toString(),
map: s.generateMap({ hires: true, source: id })
};
} catch (e) {
if (e.code === ERROR_CODES.MISSING_DEFINITION) {
return;
}
throw e;
}
}
};
}
__name(reactDocgen, "reactDocgen");
function getReactDocgenImporter(matchPath) {
return makeFsImporter((filename, basedir) => {
const mappedFilenameByPaths = (() => {
if (matchPath) {
const match = matchPath(filename);
return match || filename;
} else {
return filename;
}
})();
const result = defaultLookupModule(mappedFilenameByPaths, basedir);
if (result.includes(`${sep}react-native${sep}index.js`)) {
const replaced = result.replace(
`${sep}react-native${sep}index.js`,
`${sep}react-native-web${sep}dist${sep}index.js`
);
if (existsSync(replaced)) {
if (RESOLVE_EXTENSIONS.find((ext) => result.endsWith(ext))) {
return replaced;
}
}
}
if (RESOLVE_EXTENSIONS.find((ext) => result.endsWith(ext))) {
return result;
}
throw new ReactDocgenResolveError(filename);
});
}
__name(getReactDocgenImporter, "getReactDocgenImporter");
export {
getReactDocgenImporter,
reactDocgen
};