env-manage-plugin
Version:
A dev env plugin that integrates an Express server with request proxying capabilities.
119 lines (118 loc) • 3.79 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const fs = tslib_1.__importStar(require("fs"));
const path = tslib_1.__importStar(require("path"));
const portfinder_1 = tslib_1.__importDefault(require("portfinder"));
class Utils {
/**
* 转化列表为 Map
* @param {*} list
* @param {*} keys
* @returns
*/
static generateMap(
// 传入的数组,元素类型为 T
list) {
// 使用 reduce 方法将数组元素存入对象
return list.reduce((map, item) => {
const key = Utils.getRowKey(item);
map.set(key, item);
return map;
}, new Map());
}
static isESModuleByPackageJson() {
const packageJsonPath = path.resolve(process.cwd(), "package.json");
if (fs.existsSync(packageJsonPath)) {
return Promise.resolve(`${packageJsonPath}`).then(s => tslib_1.__importStar(require(s))).then((packageJson) => {
if (Object.hasOwnProperty.call(packageJson.default, "type")) {
return packageJson.default.type === "module";
}
return false;
})
.catch(() => {
return false;
});
}
return Promise.resolve(false);
}
static isESModule(filepath) {
const ext = path.extname(filepath);
// 检查文件扩展名
if (ext === ".mjs") {
return true;
}
else if (ext === ".cjs") {
return false;
}
else if (ext === ".js") {
// 查找最近的 package.json 文件
let currentDir = path.dirname(filepath);
while (currentDir) {
const packageJsonPath = path.join(currentDir, "package.json");
if (fs.existsSync(packageJsonPath)) {
try {
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
if (packageJson.type === "module") {
return true;
}
else {
return false;
}
}
catch (error) {
break;
}
}
const parentDir = path.dirname(currentDir);
if (parentDir === currentDir) {
break;
}
currentDir = parentDir;
}
// 如果没有找到 package.json,默认使用 CommonJS
return false;
}
// 对于其他扩展名,默认使用 CommonJS
return false;
}
static getRowKey(rowData) {
return `${rowData?.name ?? ""}+${rowData?.port ?? ""}`;
}
/**
* 查询指定端口是否被占用
* @param port
* @returns
*/
static isPortOccupied(port) {
return portfinder_1.default
.getPortPromise({
port: port,
stopPort: port,
})
.then(() => {
return false;
})
.catch(() => {
return true;
});
}
}
/**
* 去除具有相同 name 和 port 组合的环境配置重复项
* @param {Array} envList - 环境配置列表
* @returns {Array} - 去重后的环境配置列表
*/
Utils.removeEnvDuplicates = (envList) => {
const uniqueMap = new Map();
const result = [];
envList.forEach((item) => {
const rowKey = Utils.getRowKey(item);
if (!uniqueMap.has(rowKey)) {
uniqueMap.set(rowKey, true);
result.push(item);
}
});
return result;
};
exports.default = Utils;