UNPKG

storybook-addon-jsdoc-to-mdx

Version:

Storybook addon that automatically generates MDX documentation from JSDoc comments in your TypeScript and JavaScript files. Supports HTML tags in comments, complex TypeScript types, and integrates seamlessly with Storybook 7.x and 8.x.

66 lines (65 loc) 2.93 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.analyzeFolders = analyzeFolders; exports.analyzeSourceFile = analyzeSourceFile; exports.processNode = processNode; exports.generateMdxContent = generateMdxContent; exports.writeMdxFile = writeMdxFile; const ts_morph_1 = require("ts-morph"); const utils_1 = require("./utils"); const astAnalysis_1 = require("./astAnalysis"); const mdxContent_1 = require("./mdxContent"); const fs_1 = __importDefault(require("fs")); const path_1 = __importDefault(require("path")); function analyzeFolders(folderPaths, extensions) { const project = new ts_morph_1.Project(); folderPaths.forEach((folderPath) => { extensions.forEach((extension) => { project.addSourceFilesAtPaths(path_1.default.join(folderPath, `**/*.${extension}`)); }); }); project.getSourceFiles().forEach((sourceFile) => analyzeSourceFile(sourceFile, folderPaths)); } function analyzeSourceFile(sourceFile, folderPaths) { const baseDir = (0, utils_1.findBasePath)(sourceFile.getFilePath(), folderPaths); const jsDocComments = []; sourceFile.forEachChild((node) => processNode(node, jsDocComments)); if (jsDocComments.length > 0) { const pathName = (0, utils_1.getPathName)(sourceFile.getFilePath(), baseDir); const mdxContent = generateMdxContent(jsDocComments, pathName); const mdxFilePath = getMdxFilePath(sourceFile.getFilePath()); writeMdxFile(mdxFilePath, mdxContent); } } function processNode(node, jsDocComments) { if (ts_morph_1.Node.isJSDocable(node) && node.getJsDocs && typeof node.getJsDocs === "function") { const jsDocs = node.getJsDocs(); if (jsDocs.length > 0) { const nodeName = (0, astAnalysis_1.getFunctionName)(node); const commentText = jsDocs.map((doc) => doc.getFullText().trim()).join("\n"); let nodeCode; if (ts_morph_1.Node.isMethodDeclaration(node) && ts_morph_1.Node.isClassDeclaration(node.getParent())) { nodeCode = node.getParentOrThrow().getText(); } else { nodeCode = node.getText(); } jsDocComments.push({ name: nodeName, type: node.getKindName(), comment: commentText, code: nodeCode }); } } if (node.getKind() === ts_morph_1.SyntaxKind.ClassDeclaration) { node.forEachChild((child) => processNode(child, jsDocComments)); } } function generateMdxContent(jsDocComments, pathName) { return (0, mdxContent_1.createMdxContent)(jsDocComments, pathName); } function writeMdxFile(filePath, content) { fs_1.default.writeFileSync(filePath, content); } function getMdxFilePath(filePath) { return filePath.replace(/\.[^/.]+$/, ".doc.mdx"); }