UNPKG

dumi

Version:

📖 Documentation Generator of React Component

313 lines (311 loc) • 12.5 kB
var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/assetParsers/block.ts var block_exports = {}; __export(block_exports, { default: () => block_default }); module.exports = __toCommonJS(block_exports); var import_utils = require("../utils"); var import_utils2 = require("@umijs/utils"); var import_assert = __toESM(require("assert")); var import_fs = __toESM(require("fs")); var import_path = __toESM(require("path")); var import_constants = require("../constants"); var MAX_BLOCK_ASSET_CACHE_SIZE = 512; var blockAssetCache = /* @__PURE__ */ new Map(); var MAX_SIDE_EFFECT_IMPORT_CACHE_ENTRIES = 512; var MAX_SIDE_EFFECT_IMPORT_CACHE_CHARACTERS = 1024 * 1024; var sideEffectImportCache = /* @__PURE__ */ new Map(); var sideEffectImportCacheCharacters = 0; function cloneParsedBlockAsset(ret) { var _a; return { asset: JSON.parse(JSON.stringify(ret.asset)), resolveMap: { ...ret.resolveMap }, sideEffectStyles: (_a = ret.sideEffectStyles) == null ? void 0 : _a.slice(), frontmatter: ret.frontmatter ? JSON.parse(JSON.stringify(ret.frontmatter)) : ret.frontmatter }; } function getContentHashFromFile(file) { try { return (0, import_utils.getContentHash)(import_fs.default.readFileSync(file, "utf-8")); } catch { return "missing"; } } function getDepsKey(deps) { return JSON.stringify( Array.from(new Set(deps)).sort().map((file) => `${(0, import_utils2.winPath)(file)}:${getContentHashFromFile(file)}`) ); } function getParseCacheKey(opts) { const entryContent = opts.entryPointCode ?? import_fs.default.readFileSync(opts.fileAbsPath, "utf-8"); return JSON.stringify({ file: (0, import_utils2.winPath)(opts.fileAbsPath), fileLocale: opts.fileLocale, id: opts.id, refAtomIds: opts.refAtomIds, entryHash: (0, import_utils.getContentHash)(entryContent), techStack: opts.techStack.name, runtimeOpts: opts.techStack.runtimeOpts, hasOnBlockLoad: Boolean(opts.techStack.onBlockLoad), hasGenerateMetadata: Boolean(opts.techStack.generateMetadata), hasGenerateSources: Boolean(opts.techStack.generateSources), collectSideEffectStyles: Boolean(opts.collectSideEffectStyles) }); } function getParseDeps(ret, entryFile) { return Object.values(ret.resolveMap).filter( (file) => import_path.default.isAbsolute(file) && file !== entryFile ); } function getCachedBlockAsset(cacheKey) { const cached = blockAssetCache.get(cacheKey); if (cached && cached.depsKey === getDepsKey(cached.deps)) { return cloneParsedBlockAsset(cached.result); } } function setCachedBlockAsset(cacheKey, ret, deps) { if (blockAssetCache.size >= MAX_BLOCK_ASSET_CACHE_SIZE) { const firstKey = blockAssetCache.keys().next().value; if (firstKey) blockAssetCache.delete(firstKey); } blockAssetCache.set(cacheKey, { deps, depsKey: getDepsKey(deps), result: cloneParsedBlockAsset(ret) }); } function getSideEffectImports(code, ext) { const cacheKey = process.env.DUMI_CACHE === "none" ? "" : `${ext}\0${code}`; const cached = cacheKey ? sideEffectImportCache.get(cacheKey) : void 0; if (cached) return cached.imports; const imports = /* @__PURE__ */ Object.create(null); const { parseSync } = require("@swc/core"); try { const program = parseSync( code, ext === ".ts" || ext === ".tsx" ? { syntax: "typescript", tsx: ext === ".tsx", decorators: true } : { syntax: "ecmascript", jsx: ext === ".jsx", decorators: true } ); for (const item of program.body) { if (item.type === "ImportDeclaration") { if (item.typeOnly || item.specifiers.length > 0 && item.specifiers.every( (specifier) => specifier.type === "ImportSpecifier" && specifier.isTypeOnly )) { continue; } const source = item.source.value; imports[source] = imports[source] !== false && item.specifiers.length === 0; } else if ((item.type === "ExportNamedDeclaration" || item.type === "ExportAllDeclaration") && item.source && !(item.type === "ExportNamedDeclaration" && item.typeOnly)) { imports[item.source.value] = false; } } } catch { return {}; } if (cacheKey) { const size = cacheKey.length + Object.keys(imports).reduce((total, source) => total + source.length, 0); if (size <= MAX_SIDE_EFFECT_IMPORT_CACHE_CHARACTERS) { while (sideEffectImportCache.size >= MAX_SIDE_EFFECT_IMPORT_CACHE_ENTRIES || sideEffectImportCacheCharacters + size > MAX_SIDE_EFFECT_IMPORT_CACHE_CHARACTERS) { const first = sideEffectImportCache.entries().next().value; sideEffectImportCache.delete(first[0]); sideEffectImportCacheCharacters -= first[1].size; } sideEffectImportCache.set(cacheKey, { imports, size }); sideEffectImportCacheCharacters += size; } } return imports; } async function parseBlockAsset(opts) { const cacheKey = opts.cacheable ? getParseCacheKey(opts) : ""; const cached = cacheKey ? getCachedBlockAsset(cacheKey) : void 0; if (cached) { return cached; } const asset = { type: "BLOCK", id: opts.id, refAtomIds: opts.refAtomIds, dependencies: {}, entry: "" }; const result = { asset, resolveMap: {}, sideEffectStyles: [], frontmatter: null }; const styleImports = /* @__PURE__ */ new Map(); const { build } = require("@umijs/bundler-utils/compiled/esbuild"); const deferrer = build({ // do not emit file write: false, // enable bundle for trigger onResolve hook, but all deps will be externalized bundle: true, logLevel: "silent", format: "esm", target: "esnext", // esbuild need relative entry path entryPoints: [import_path.default.basename(opts.fileAbsPath)], absWorkingDir: import_path.default.dirname(opts.fileAbsPath), plugins: [ { name: "plugin-dumi-collect-deps", setup: (builder) => { builder.onResolve({ filter: /.*/ }, (args) => { var _a, _b; const resolved = args.kind === "entry-point" ? import_path.default.join(args.resolveDir, args.path) : opts.resolver(args.resolveDir, args.path); (0, import_assert.default)( resolved, `Can't resolve ${args.path} from ${args.resolveDir}` ); if (opts.collectSideEffectStyles && opts.techStack.runtimeOpts && args.kind !== "entry-point" && !/[?#]/.test(args.path) && /\.(css|less|sass|scss|styl)$/i.test(resolved) && !/\.module\.[^.]+$/i.test(resolved)) { const key = args.path.startsWith(".") ? (0, import_utils2.winPath)(resolved) : args.path; styleImports.set( key, styleImports.get(key) !== false && args.kind === "import-statement" && ((_b = (_a = args.pluginData) == null ? void 0 : _a.sideEffectImports) == null ? void 0 : _b[args.path]) === true ); } if (args.kind !== "entry-point" && !args.path.startsWith(".")) { const pkgJsonPath = import_utils2.pkgUp.pkgUpSync({ cwd: resolved }); if (pkgJsonPath) { const pkg = require(pkgJsonPath); asset.dependencies[pkg.name] = { type: "NPM", value: pkg.version }; if (opts.techStack.runtimeOpts) result.resolveMap[args.path] = args.path; } return { path: args.path, external: true }; } return { path: resolved, pluginData: { kind: args.kind, resolveDir: args.resolveDir, source: args.path } }; }); builder.onLoad({ filter: /.*/ }, (args) => { let ext = import_path.default.extname(args.path); const techStack = opts.techStack; const isEntryPoint = args.pluginData.kind === "entry-point"; const filename = `${isEntryPoint ? "index" : (0, import_utils2.winPath)( import_path.default.format({ ...import_path.default.parse(args.pluginData.source), base: "", ext: "" }) )}${ext}`; let entryPointCode = opts.entryPointCode; let contents = void 0; if (techStack.onBlockLoad) { const result2 = techStack.onBlockLoad({ filename, entryPointCode: entryPointCode ?? (entryPointCode = import_fs.default.readFileSync( args.path, "utf-8" )), ...args }); if (result2) { ext = `.${result2.type}`; contents = result2.content; } } let isModule = import_constants.DEFAULT_DEMO_MODULE_EXTENSIONS.includes(ext); let isPlainText = import_constants.DEFAULT_DEMO_PLAIN_TEXT_EXTENSIONS.includes(ext); if (isModule || isPlainText) { asset.dependencies[filename] = { type: "FILE", value: opts.entryPointCode ?? import_fs.default.readFileSync(args.path, "utf-8") }; const file = asset.dependencies[filename]; if (isEntryPoint) { const { code, frontmatter } = (0, import_utils.parseCodeFrontmatter)(file.value); asset.entry = filename; if (frontmatter) { file.value = code; asset.dependencies[filename].value = code; ["description", "title", "snapshot", "keywords"].forEach( (key) => { asset[key] = frontmatter == null ? void 0 : frontmatter[key]; } ); ["description", "title"].forEach((key) => { frontmatter[key] = frontmatter[`${key}.${opts.fileLocale}`] || frontmatter[key]; }); result.frontmatter = frontmatter; } } if (opts.techStack.runtimeOpts && (!isEntryPoint || !opts.entryPointCode)) { result.resolveMap[filename] = args.path; } return { // only continue to load for module files contents: isModule ? contents ?? file.value : "", loader: isModule ? ext.slice(1) : "text", pluginData: { sideEffectImports: opts.collectSideEffectStyles && isModule ? getSideEffectImports(contents ?? file.value, ext) : {} } }; } }); } } ] }); let hasError = false; try { await deferrer; } catch { hasError = true; } if (!hasError) { result.sideEffectStyles = Array.from(styleImports).filter(([, sideEffectOnly]) => sideEffectOnly).map(([key]) => key); } if (!hasError && cacheKey) { setCachedBlockAsset( cacheKey, result, getParseDeps(result, opts.fileAbsPath) ); } return result; } var block_default = parseBlockAsset;