@serpent/common-cli
Version:
通用的 cli 相关的函数
223 lines (218 loc) • 12.6 kB
JavaScript
;
var tslib_es6 = require('./tslib.es6-8ea38f41.cjs');
var path = require('path');
var Module = require('module');
var url = require('url');
var cmd = require('./cmd-1c5c4619.cjs');
require('./isCommandExists-fcea61ed.cjs');
var run = require('./run.cjs');
var context = require('./context-e98d804e.cjs');
require('./Dir-a1286a2f.cjs');
var project = require('./project-7917b261.cjs');
var readJsonFile = require('./readJsonFile-f1989956.cjs');
require('fs');
var createPackage = require('./createPackage-b7459d3e.cjs');
require('./satisfies-2e2ee518.cjs');
require('./format-4c37063e.cjs');
require('./info-08047f0f.cjs');
require('./logger.cjs');
require('./warn-8730a30c.cjs');
require('http');
require('https');
var debug = require('./debug.cjs');
require('./supportColor-07ee281e.cjs');
require('os');
require('./_commonjsHelpers-ed042b00.cjs');
require('./table-780cf84a.cjs');
require('./index-efd292d5.cjs');
require('./helper-a8839c0a.cjs');
require('./exists-4a19b288.cjs');
require('crypto');
require('child_process');
require('node:buffer');
require('node:path');
require('node:child_process');
require('node:process');
require('node:url');
require('node:os');
require('./index-94e9b39b.cjs');
require('assert');
require('events');
require('buffer');
require('stream');
require('util');
require('tty');
function proxy(COMMAND_KEY, COMMAND_VERSION, options) {
var _this = this;
var pkgName = options.pkgName, _a = options.configOpts, configOpts = _a === void 0 ? [] : _a, configPath = options.configPath, _b = options.nodeArgs, nodeArgs = _b === void 0 ? [] : _b, silent = options.silent, bootstrap = options.bootstrap;
var binName = options.binName || pkgName;
var debug$1 = debug.createDebug("".concat(COMMAND_KEY.replace(/-/g, ':'), ":").concat(binName));
return cmd.cmd({
usage: "".concat(COMMAND_KEY, " ").concat(binName, " [options]"),
version: false,
help: false,
options: {
forceVendor: cmd.opt('boolean', '是否强制重新创建 durka/vendors 下的项目'),
},
}, function (ctx) { return tslib_es6.__awaiter(_this, void 0, void 0, function () {
var forceVendor, cliRootDir, resolve, pkg, binFile, exec, workRootDir, workVendorsDir_1, configArgs, cacheFile, cache, _a, entry, _b, args, newCache;
var _this = this;
return tslib_es6.__generator(this, function (_c) {
switch (_c.label) {
case 0:
forceVendor = ctx.options.forceVendor;
debug$1('command options %o', ctx.options);
cliRootDir = ctx.findupPackageRoot(url.fileURLToPath(options.metaUrl));
resolve = Module.createRequire(options.metaUrl).resolve;
debug$1('cli root dir: %s', cliRootDir);
pkg = resolvePkg(pkgName, resolve);
binFile = ctx.tryGetProjectBinFile(pkg.rootDir, binName);
if (!binFile)
throw new Error("\u65E0\u6CD5\u627E\u5230 ".concat(pkgName, " \u9879\u76EE\u7684 bin \u6587\u4EF6"));
debug$1('target command bin file %s', binFile);
exec = function (file, args) {
if (args === void 0) { args = []; }
return tslib_es6.__awaiter(_this, void 0, void 0, function () {
var child, e_1, exited;
var _a, _b;
return tslib_es6.__generator(this, function (_c) {
switch (_c.label) {
case 0:
_c.trys.push([0, 2, , 3]);
child = run.run(tslib_es6.__spreadArray(tslib_es6.__spreadArray(tslib_es6.__spreadArray(tslib_es6.__spreadArray(['node'], nodeArgs, true), [file], false), args, true), ctx.args, true), { silent: silent });
(_a = options.onChildForked) === null || _a === void 0 ? void 0 : _a.call(options, child);
return [4 /*yield*/, child];
case 1:
_c.sent();
return [3 /*break*/, 3];
case 2:
e_1 = _c.sent();
exited = (_b = options.onChildError) === null || _b === void 0 ? void 0 : _b.call(options, e_1);
if (!exited) {
console.log(e_1.message);
process.exit(e_1.exitCode || 1);
}
return [3 /*break*/, 3];
case 3: return [2 /*return*/];
}
});
});
};
if (!(ctx.args.includes('-h') || ctx.args.includes('--help'))) return [3 /*break*/, 2];
ctx.help(); // 输出当前代理的帮助信息
return [4 /*yield*/, exec(binFile)]; // 输出代理的命令的帮助信息
case 1:
_c.sent(); // 输出代理的命令的帮助信息
return [3 /*break*/, 6];
case 2:
workRootDir = ctx.findupPackageRoot();
workVendorsDir_1 = path.join(workRootDir, 'durka', 'vendors');
debug$1('work root dir: %s', workRootDir);
configArgs = [];
if (configPath && configOpts.length && configOpts.every(function (c) { return !ctx.args.includes(c); })) {
configArgs.push(configOpts[0], configPath);
}
debug$1('config args: %o, opts: %o, path: %s', configArgs, configOpts, configPath);
cacheFile = path.join(workVendorsDir_1, pkgName, '.cache');
if (!(!forceVendor && ctx.existsFile(cacheFile))) return [3 /*break*/, 4];
cache = ctx.tryReadJsonFile(cacheFile);
debug$1('proxy command cache %o', cache);
if (!(cache && cache.version === COMMAND_VERSION && cache.path === cacheFile && cache.entry)) return [3 /*break*/, 4];
debug$1('run proxy command on cache');
return [4 /*yield*/, exec(cache.entry, tslib_es6.__spreadArray(tslib_es6.__spreadArray([], configArgs, true), cache.args, true))];
case 3: return [2 /*return*/, _c.sent()];
case 4:
_a = bootstrap({
pkg: pkg,
binFile: binFile,
workRootDir: workRootDir,
workVendorsDir: workVendorsDir_1,
cliRootDir: cliRootDir,
resolve: resolve,
resolvePkg: function (pkgName) { return resolvePkg(pkgName, resolve); },
proxyPackage: function (pkgName, cb, opts) { return proxyPackage(resolve, workVendorsDir_1, pkgName, cb, opts); },
createPackage: function (pkgName, cb, pkgDetail) {
if (pkgDetail === void 0) { pkgDetail = {}; }
return createPackage.createPackage(workVendorsDir_1, pkgName, pkgDetail, cb);
},
}), entry = _a.entry, _b = _a.args, args = _b === void 0 ? [] : _b;
debug$1('created proxy command', { entry: entry, args: args });
newCache = { version: COMMAND_VERSION, path: cacheFile, entry: entry, args: args };
ctx.writeJsonFile(cacheFile, newCache);
debug$1('write proxy command cache %o', newCache);
debug$1('run proxy command on fresh');
return [4 /*yield*/, exec(entry, tslib_es6.__spreadArray(tslib_es6.__spreadArray([], configArgs, true), args, true))];
case 5:
_c.sent();
_c.label = 6;
case 6: return [2 /*return*/];
}
});
}); });
}
function getTypesFileFromPkg(pkg) {
var _a;
if (pkg.types)
return pkg.types;
var exp = (_a = pkg.exports) === null || _a === void 0 ? void 0 : _a['.'];
return exp && exp.types ? exp.types : '';
}
function resolvePkg(pkgName, resolve) {
// 不要直接 resolve('xxx/package.json'),esm 中没声明 export package.json 就 resolve 不了
var mainFile = resolve(pkgName);
var jsonPath = context.findupPackage(mainFile);
var rootDir = path.dirname(jsonPath);
return {
name: pkgName,
rootDir: rootDir,
jsonPath: jsonPath,
mainFile: mainFile,
get typesFile() {
return path.resolve(rootDir, getTypesFileFromPkg(readJsonFile.readJsonFile(jsonPath)));
},
get jsonDetail() {
return readJsonFile.readJsonFile(jsonPath);
},
};
}
function proxyPackage(resolve, vendorsDir, pkgName, _cb, _opts) {
var pkg = resolvePkg(pkgName, resolve);
var jsonDetail = pkg.jsonDetail, rootDir = pkg.rootDir;
var cb = _cb;
var options = _opts;
if (typeof _cb === 'object') {
options = _cb;
cb = null;
}
if (!options)
options = {};
var exportDefault = options.exportDefault;
return createPackage.createPackage(vendorsDir, pkgName, {}, function (dist) {
var _a, _b;
if (jsonDetail.type)
dist.jsonDetail.type = jsonDetail.type;
if (jsonDetail.version)
dist.jsonDetail.version = jsonDetail.version;
if (jsonDetail.bin && !options.noBin) {
var binFile = options.binFile || project.tryGetProjectBinFile(rootDir, options.binName);
if (!binFile)
throw new Error("\u5728\u76EE\u5F55 ".concat(rootDir, " \u4E2D\u65E0\u6CD5\u627E\u5230\u9879\u76EE ").concat(pkg.name, " \u7684 bin \u6587\u4EF6"));
if (jsonDetail.type === 'module' || binFile.endsWith('.mjs'))
dist.setBinMJS({ source: binFile });
else
dist.setBinCJS({ source: binFile });
}
if (jsonDetail.main && !options.noMain && !options.noMainCJS)
dist.setMainCJS({ source: rootDir, exportDefault: exportDefault });
if ((jsonDetail.module || ((_b = (_a = jsonDetail.exports) === null || _a === void 0 ? void 0 : _a['.']) === null || _b === void 0 ? void 0 : _b['import'])) && !options.noMain && !options.noMainMJS)
dist.setMainMJS({ source: rootDir, exportDefault: exportDefault });
if (jsonDetail.types && !options.noTypes)
dist.setTypes({ source: rootDir, exportDefault: exportDefault });
if (typeof cb === 'function')
cb(dist);
});
}
/** 重写查找指定CJS 与 ESM模块的方法 */
var redirectResolve = function (modules, path) { return "const Module = require('module')\nconst path = require('path')\nconst { fileURLToPath } = require('url')\n\nconst proxies = [".concat(modules.map(function (m) { return "'".concat(m, "'"); }).join(', '), "]\nconst resolvePath = '").concat(path, "'\nconst match = (id) => typeof id === 'string' && (proxies.includes(id) || proxies.some(p => id.startsWith(p + '/')))\n\nconst originalRequire = Module.prototype.require\nModule.prototype.require = function(id) {\n if (match(id)) {\n const local = require.resolve(id, { paths: Array.from(new Set([resolvePath, process.cwd()])) }) // \u4F18\u5148\u4F7F\u7528\u6307\u5B9A\u7684\u8DEF\u5F84\u4E0A\u6A21\u5757\n return originalRequire.apply(this, [local])\n }\n return originalRequire.apply(this, arguments)\n}\n\nconst originalCreateRequire = Module.createRequire || Module.createRequireFromPath\nModule.createRequire = function(importerFileUrl) {\n const newRequire = originalCreateRequire.apply(this, arguments)\n const originalResolve = newRequire.resolve\n\n const importerFile = fileURLToPath(importerFileUrl)\n newRequire.resolve = function(id) {\n if (match(id)) {\n const result = require.resolve(id, { paths: Array.from(new Set([resolvePath, path.dirname(importerFile)])) })\n return result\n }\n return originalResolve.apply(this, arguments)\n }\n return newRequire\n}\n"); };
exports.proxy = proxy;
exports.redirectResolve = redirectResolve;