UNPKG

beesbuild

Version:

构建工具链

251 lines (250 loc) 11.6 kB
"use strict"; 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); var stdin_exports = {}; __export(stdin_exports, { rollupStub: () => rollupStub, runBrowserRollupStub: () => runBrowserRollupStub, stubBuild: () => stubBuild, tryResolve: () => tryResolve }); module.exports = __toCommonJS(stdin_exports); var import_path = __toESM(require("path")); var import_chalk_unified = __toESM(require("chalk-unified")); var import_utils = require("@beesbuild/utils"); var import_fs_extra = __toESM(require("fs-extra")); var import_jiti = __toESM(require("jiti")); var import_mlly = require("mlly"); var import_lodash_unified = require("lodash-unified"); var prettier = __toESM(require("prettier")); var import_utils2 = require("../utils.cjs"); var import_variables = require("../variables.cjs"); var import_shebang = require("./plugins/shebang.cjs"); var import_untyped = require("./untyped.cjs"); function tryResolve(id, rootDir = process.cwd()) { const _require = (0, import_jiti.default)(rootDir, { interopDefault: true, esmResolve: true }); try { return _require.resolve(id); } catch (error) { if (error.code !== "MODULE_NOT_FOUND") { import_utils.consola.error(`Error trying import ${id} from ${rootDir}`, error); } return id; } } const stubBuild = async (module2, ctx) => { const rootDir = ctx.options.rootDir; const outDir = ctx.options.outDir || "."; const entryFile = ctx.options.entries.find(({ isEntry }) => isEntry); let entryFilepath = (entryFile == null ? void 0 : entryFile.input) ? import_path.default.resolve(rootDir, entryFile.input) : import_path.default.resolve(rootDir, "src"); const buildConfig = (0, import_lodash_unified.fromPairs)((0, import_utils.getBuildConfig)({ rootDir, outDir, manifest: ctx.pkg, rollup: { emitCJS: true, emitDts: true, emitUmd: true }, entryFile: entryFile == null ? void 0 : entryFile.input })); const { output, ext } = buildConfig[module2]; const dir = import_path.default.resolve(output.path, `index.${ext}`); if ((0, import_fs_extra.existsSync)(dir)) return; const info = (0, import_utils.parseManifest)(entryFilepath); entryFilepath = import_path.default.join(info.dir, info.name); const d = import_path.default.relative(import_path.default.dirname(dir), entryFilepath); const ddir = import_utils.pathExtra.join(d.startsWith(".") ? d : `./${d}`); import_utils.consola.info(`\u3010Start:d\u3011for stub types file: ${d} generated`); import_utils.consola.info(`\u3010Start:dir\u3011for stub types file: ${buildConfig.dts.output.name} generated`); import_utils.consola.info(`\u3010Start:ddir\u3011for stub types file: ${ddir} generated`); const code = []; switch (module2) { case "cjs": code.push(`module.exports = require('${ddir}');`); break; default: code.push(`export * from '${ddir}';`, `export { default } from '${ddir}';`); break; } const codeStr = await prettier.format(code.join("\n"), { parser: "typescript", singleQuote: true }); import_utils.consola.success(import_chalk_unified.default.cyan(`\u3010End\u3011for stub types file: ${dir} generated`)); if (!(0, import_fs_extra.existsSync)(import_path.default.dirname(dir))) { (0, import_fs_extra.mkdirSync)(import_path.default.dirname(dir), { recursive: true }); } (0, import_fs_extra.writeFileSync)(dir, codeStr, "utf8"); return Promise.resolve(); }; const runBrowserRollupStub = async (modules, ctx) => { if (modules.includes("dts")) { let typesProject = ctx.caches[ctx.uid]["typesProject"]; if (!typesProject) { typesProject = (0, import_untyped.createTypesProject)(ctx); ctx.caches[ctx.uid]["typesProject"] = typesProject; const sourceFiles = typesProject.addSourceFiles(); import_utils.consola.warn(sourceFiles.length, "sourceFiles"); } typesProject.typeCheck(true); } return Promise.allSettled(modules.map(module2 => stubBuild(module2, ctx))); }; const rollupStub = async ctx => { var _a, _b; if (((_a = ctx.options) == null ? void 0 : _a.runEnv) === "Browser") { return runBrowserRollupStub(["esm", "cjs", "dts"], ctx); } const rootDir = ctx.options.rootDir; const serializedJitiOptions = _dirname => { const JitiOptions = { ...ctx.options.stubOptions.jiti, alias: { ...(0, import_utils2.resolveAliases)(ctx), ...ctx.options.stubOptions.jiti.alias } }; for (const [key, p] of Object.entries(JitiOptions.alias)) { const pp = import_path.default.join(_dirname, import_path.default.relative(rootDir, p)); JitiOptions.alias[key] = `${pp}/`; } return JSON.stringify(JitiOptions, null, 2); }; const { esm, cjs, dts } = (0, import_utils.handleManifest)(ctx.pkg, ctx.options.rootDir); const entries = ctx.options.entries.filter(entry => entry.builder === "rollup" && entry.isEntry); for (const option of entries) { const { input, name } = option; const outDir = import_path.default.join(ctx.options.outDir, name != null ? name : "dist"); const output = import_path.default.resolve(rootDir, outDir); const resolvedEntry = import_path.default.normalize(tryResolve(input, rootDir) || input); const resolvedEntryWithoutExt = resolvedEntry.slice(0, Math.max(0, resolvedEntry.length - import_path.default.extname(resolvedEntry).length)); const code = await import_fs_extra.default.readFile(resolvedEntry, "utf8"); const shebang = (0, import_shebang.getShebang)(code); let dirname = import_path.default.dirname(output); await import_fs_extra.default.mkdir(dirname, { recursive: true }); const rollup = ctx.options.rollup; let cjsOutput = `${output}.${cjs.ext}`; if (rollup.emitCJS) { if (ctx.pkg.main) { const dir = import_path.default.dirname(import_path.default.resolve(ctx.options.rootDir, cjs.fullPath)); if (dir !== dirname) { dirname = dir; await import_fs_extra.default.mkdir(dirname, { recursive: true }); } cjsOutput = import_path.default.resolve(ctx.options.rootDir, cjs.fullPath); } const _dirname2 = import_path.default.relative(import_path.default.dirname(cjsOutput), rootDir); const cjsPath = import_path.default.join(_dirname2, import_path.default.relative(rootDir, input)); const code2 = [shebang, `const jiti = require('jiti');`, `const path = require('node:path');`, `const cjsPath = path.resolve(__dirname, '${cjsPath}')`, "", `/** @type { import('${cjsPath}') } */`, `const _module = jiti(null, ${serializedJitiOptions(_dirname2)})(cjsPath);`, "", "module.exports = _module;", ""].join("\n"); await import_fs_extra.default.writeFile(cjsOutput, code2); } const namedExports = await (0, import_mlly.resolveModuleExportNames)(resolvedEntry, { extensions: import_variables.DEFAULT_EXTENSIONS }).catch(error => { import_utils.consola.warn(ctx, `Cannot analyze ${resolvedEntry} for exports:${error}`); return []; }); const hasDefaultExport = namedExports.includes("default") || namedExports.length === 0; let esmOutput = `${output}.${esm.ext}`; if (ctx.pkg.module) { const dir = import_path.default.dirname(import_path.default.resolve(ctx.options.rootDir, esm.fullPath)); if (dir !== dirname) { dirname = dir; await import_fs_extra.default.mkdir(dirname, { recursive: true }); } esmOutput = import_path.default.resolve(ctx.options.rootDir, esm.fullPath); } if (((_b = ctx.argv) == null ? void 0 : _b.runEnv) === "Browser") { const code2 = [shebang, `/** @type {import(${JSON.stringify(resolvedEntryWithoutExt)})} */`, `export * from ${JSON.stringify(resolvedEntry)};`, "", `/** @type {import(${JSON.stringify(resolvedEntryWithoutExt)})} */`, `import * as _module from ${JSON.stringify(resolvedEntry)};`, hasDefaultExport ? "\nexport default _module;" : "", ...namedExports.filter(name2 => name2 !== "default").map(name2 => `export const ${name2} = _module.${name2};`), ""].join("\n"); await import_fs_extra.default.writeFile(esmOutput, code2); } else { const _dirname2 = import_path.default.relative(import_path.default.dirname(esmOutput), rootDir); const esmPath = import_path.default.join(_dirname2, import_path.default.relative(rootDir, input)); const code2 = [shebang, `import jiti from 'jiti';`, `import path from 'node:path';`, "", `const pathname = new URL(".", import.meta.url).pathname;`, `const mjsPath = path.resolve(pathname, '${esmPath}');`, `/** @type {import(${JSON.stringify(esmPath)})} */`, `const _module = jiti(null, ${serializedJitiOptions(_dirname2)})(mjsPath);`, "", hasDefaultExport ? "export default _module;" : "", "", ...namedExports.filter(name2 => name2 !== "default").map(name2 => `export const ${name2} = _module.${name2};`), ""].join("\n"); await import_fs_extra.default.writeFile(esmOutput, code2); } let dtsOutput = `${output}.d.ts`; if (ctx.pkg.typings || ctx.pkg.types) { const dir = import_path.default.dirname(import_path.default.resolve(ctx.options.rootDir, dts.fullPath)); if (dir !== dirname) { dirname = dir; await import_fs_extra.default.mkdir(dirname, { recursive: true }); } dtsOutput = import_path.default.resolve(ctx.options.rootDir, dts.fullPath); } const _dirname = import_path.default.relative(import_path.default.dirname(dtsOutput), rootDir); const typesPath = import_path.default.join(_dirname, import_path.default.relative(rootDir, input)); const dtsCode = [`export * from '${typesPath}';`, hasDefaultExport ? `export { default } from '${typesPath}';` : "", ""].join("\n"); await import_fs_extra.default.writeFile(dtsOutput, dtsCode); if (shebang) { await (0, import_shebang.makeExecutable)(cjsOutput); await (0, import_shebang.makeExecutable)(esmOutput); } } await ctx.hooks.callHook("rollup:done", ctx); return; }; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { rollupStub, runBrowserRollupStub, stubBuild, tryResolve });