UNPKG

yapi-ts-builder

Version:

基于 yapi-to-typescript 实现的 YApi 接口定义生成工具

204 lines (202 loc) 8.77 kB
#!/usr/bin/env node "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.run = void 0; const TSNode = __importStar(require("ts-node")); const consola_1 = __importDefault(require("consola")); const fs_extra_1 = __importDefault(require("fs-extra")); const ora_1 = __importDefault(require("ora")); const path_1 = __importDefault(require("path")); const prompts_1 = __importDefault(require("prompts")); const yargs_1 = __importDefault(require("yargs")); const vtils_1 = require("vtils"); const Generator_1 = require("./Generator"); TSNode.register({ // 不加载本地的 tsconfig.json skipProject: true, // 仅转译,不做类型检查 transpileOnly: true, // 自定义编译选项 compilerOptions: { strict: false, target: 'es2017', module: 'commonjs', moduleResolution: 'node', declaration: false, removeComments: false, esModuleInterop: true, allowSyntheticDefaultImports: true, importHelpers: false, // 转换 js,支持在 ytt.config.js 里使用最新语法 allowJs: true, lib: ['es2017'], }, }); async function run(cmd, options) { var _a, _b, _c, _d, _e, _f; let useCustomConfigFile = false; let cwd; let configTSFile; let configJSFile; let configFile; let configFileExist; if (!(options === null || options === void 0 ? void 0 : options.configFile)) { cwd = process.cwd(); configTSFile = path_1.default.join(cwd, 'ytt.config.ts'); configJSFile = path_1.default.join(cwd, 'ytt.config.js'); // 检查是否存在配置文件 const configTSFileExist = await fs_extra_1.default.pathExists(configTSFile); const configJSFileExist = !configTSFileExist && (await fs_extra_1.default.pathExists(configJSFile)); configFileExist = configTSFileExist || configJSFileExist; configFile = configTSFileExist ? configTSFile : configJSFile; } else { useCustomConfigFile = true; configFile = options.configFile; cwd = path_1.default.dirname(configFile); configFileExist = await fs_extra_1.default.pathExists(configFile); } if (cmd === 'help') { console.log(`\n${(0, vtils_1.dedent) ` # 用法 初始化配置文件: ytt init 生成代码: ytt 查看帮助: ytt help `}\n`); } else if (cmd === 'init') { if (configFileExist) { consola_1.default.info(`检测到配置文件: ${configFile}`); const answers = await (0, prompts_1.default)({ message: '是否覆盖已有配置文件?', name: 'override', type: 'confirm', }); if (!answers.override) return; } let outputConfigFile; let outputConfigFileType; if (useCustomConfigFile) { outputConfigFile = configFile; outputConfigFileType = configFile.endsWith('.js') ? 'js' : 'ts'; } else { const answers = await (0, prompts_1.default)({ message: '选择配置文件类型?', name: 'configFileType', type: 'select', choices: [ { title: 'TypeScript(ytt.config.ts)', value: 'ts' }, { title: 'JavaScript(ytt.config.js)', value: 'js' }, ], }); outputConfigFile = answers.configFileType === 'js' ? configJSFile : configTSFile; outputConfigFileType = answers.configFileType; } await fs_extra_1.default.outputFile(outputConfigFile, (0, vtils_1.dedent) ` import { defineConfig } from 'yapi-ts-builder' export default defineConfig([ { serverUrl: 'http://foo.bar', // 不可修改,仅支持生成类型 typesOnly: true, // 不可修改,仅支持ts target: "typescript", prodEnvName: 'production', outputFilePath: 'src/api/index.${outputConfigFileType}', dataKey: 'data', projects: [ { token: 'hello', categories: [ { id: 0 }, ], }, ], }, ]) `); consola_1.default.success('写入配置文件完毕'); } else { if (!configFileExist) { return consola_1.default.error(`找不到配置文件: ${useCustomConfigFile ? configFile : `${configTSFile}${configJSFile}`}`); } consola_1.default.success(`找到配置文件: ${configFile}`); let config; let generator; let spinner; try { config = require(configFile).default; generator = new Generator_1.Generator(config, { cwd }); spinner = (0, ora_1.default)('正在获取数据并生成代码...').start(); const delayNotice = (0, vtils_1.wait)(5000); delayNotice.then(() => { spinner.text = `正在获取数据并生成代码... (若长时间处于此状态,请检查是否有接口定义的数据过大导致拉取或解析缓慢)`; }); await generator.prepare(); delayNotice.cancel(); const output = await generator.generate(); spinner.stop(); consola_1.default.success('获取数据并生成代码完毕'); await generator.write(output); consola_1.default.success('写入文件完毕'); await generator.destroy(); await ((_b = (_a = config.hooks) === null || _a === void 0 ? void 0 : _a.success) === null || _b === void 0 ? void 0 : _b.call(_a)); } catch (err) { spinner === null || spinner === void 0 ? void 0 : spinner.stop(); await (generator === null || generator === void 0 ? void 0 : generator.destroy()); await ((_d = (_c = config === null || config === void 0 ? void 0 : config.hooks) === null || _c === void 0 ? void 0 : _c.fail) === null || _d === void 0 ? void 0 : _d.call(_c)); /* istanbul ignore next */ consola_1.default.error(err); } await ((_f = (_e = config === null || config === void 0 ? void 0 : config.hooks) === null || _e === void 0 ? void 0 : _e.complete) === null || _f === void 0 ? void 0 : _f.call(_e)); } } exports.run = run; /* istanbul ignore next */ // 这是测试覆盖率工具的注解,表示忽略这段代码的测试覆盖 if (require.main === module) { // 通过判断 require.main === module 来确保这段代码只在直接运行时执行,而在被其他模块引入时不会执行 // 使用 yargs 解析命令行参数,获取命令行参数,设置 -c 作为 --config 的别名 const argv = (0, yargs_1.default)(process.argv).alias('c', 'config').argv; // 调用主程序的 run 函数 run(argv._[2], { // 获取第三个参数作为命令名(如 init/help) configFile: argv.config // 如果指定了 config 参数,则将解析为绝对路径其作为配置文件路径, 否则为使用默认配置文件路径 ? path_1.default.resolve(process.cwd(), argv.config) : undefined, }); }